diff --git a/Cargo.lock b/Cargo.lock index 0c34a6a952..dc08d4542e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6341,7 +6341,6 @@ dependencies = [ "raw-window-handle", "rfd", "serde_json", - "smithay-clipboard", "socket2", "tempfile", "vectorcraft-engine", @@ -6666,6 +6665,7 @@ dependencies = [ "serde", "serde_json", "sha2", + "siphasher", "skrifa 0.47.0", "smallvec", "thiserror 2.0.21", diff --git a/ROADMAP.md b/ROADMAP.md index b5a2f43c7a..fe325ff849 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -141,6 +141,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-10-31: Export for Screens works as the reference app's dialog: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File (the chosen artboards as one PDF's pages, `pdfs: "single"`) or Multiple Files, iOS and Android rows, format presets in a ☰ menu, and a count of the files the export writes (#4895). About 55 community PRs and fixes landed the same day: Find Font, Replace Font, Outline Stroke and Expand leave hidden and locked art alone (with a warning); DXF export writes LINE and ELLIPSE entities and outlines only the strokes a CAD line can't draw; Blob Brush Angle and Roundness; Shift-constrained Perspective Selection; Grid Repeat Options Preview; a gradient mesh from a file budgeted at about a million quads; width-profile strokes keep their shape zoomed out; `.ai`/EPS import fidelity (area type, envelopes, transparency in dictionaries, character styles); PDF import finds hyphenated and CMap-suffixed font names; Windows renders follow the process's core affinity; Enter or Escape in a floating panel's field no longer reaches the canvas (#4803); Properties shows Blend Options for any selected blend (#4817); Artwork Cleanup finds doubled type (#4835) and joins stacked lines into one object (Join Point Text, #4826). Headline numbers unchanged. - 2026-10-31: Arrange Tools, a built-in add-on (Object › Plug-ins › Arrange Tools): Arrange in Grid lays the selected objects out in rows and columns, a row or a column with gaps, from the selection's top-left or centred on the artboard; Swap Objects swaps two objects' places (and, with Swap Objects and Sizes, their sizes); Replace with Top Object puts a copy of the topmost selected object in place of each of the others, kept, stretched or fitted in proportion; Set Size of Each gives every selected object an exact width and/or height about a reference point; Zoom to Selection fits the view to the selection. Each is one undo step with a previewed dialog where it has options. A VectorCraft addition: headline numbers unchanged. - 2026-11-11: Window › Swatch Libraries › Gradients › Organic Fades: fifteen soft fades (ten linear, five radial) through three to five unevenly spaced stops with off-center midpoints, mixed with the Perceptual method, that thin out to transparent at the end of a linear one and at the edge of a radial one; they also list in the Swatches panel's library menu, `swatch.library.list` and the Gradient panel's Presets. +- 2026-11-13: Gradient panel › Method: Hue Clockwise and Hue Counterclockwise mix a linear, radial, conic or diamond gradient's colors around the hue wheel in one direction, so red to blue passes through magenta one way and through yellow and green the other (`paint.editGradient` `method`: `hue-clockwise`, `hue-counterclockwise`); SVG and PDF exports write such a gradient as an image. - 2026-11-11: Window › Swatch Libraries › Gradients › Holographic: seven foils (opaque linear gradients of six narrow pastel and pearl bands with off-center midpoints) and seven glows (radial gradients from a bright center out to a clear edge), mixed with the Perceptual method; they also list in the Swatches panel's library menu, `swatch.library.list` and the Gradient panel's Presets. - 2026-10-30: Gradient panel presets: a Presets menu applies one of the built-in gradient libraries' presets (grouped by theme) or a saved one to the gradient behind the active proxy, keeping its placement, as one undo step; the panel menu saves the current gradient as a preset, kept with the preferences, and deletes saved ones (`gradient.presets.list/apply/save/delete`). - 2026-10-23: Pathfinder › Trap: the Pathfinder panel's Trap… and Effect › Pathfinder › Trap… add a thin overprinting strip of the lighter colour inside the darker one where two solid colours meet, so misregistered plates leave no gap ([trapping](https://helpx.adobe.com/illustrator/using/trapping.html)), with Thickness, Height/Width, Tint Reduction, Traps with Process Color and Reverse Traps. Illustrator effects 49/50 (SVG Filters remains); Live vector effects hours 6–10 → 4–8; headline numbers unchanged. diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index 0d4deca36f..b66c15070f 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.rs @@ -418,10 +418,18 @@ fn convert(args: &[String]) -> Result<(), String> { // Save as Template writes every artboard, with the .ai options. ("file.saveAsTemplate", json!({"path": output, "format": "ait", "outlineText": outline_text, "acknowledgeLoss": replace_lossy})) } else { - // A conversion keeps hidden layers and objects, written hidden, where the format can (SVG, - // PSD). - let params = json!({"path": output, "artboard": artboard, "range": range, "outlineText": outline_text, "hiddenLayers": true, "acknowledgeLoss": replace_lossy}); + let params = json!({"path": output, "artboard": artboard, "range": range, "acknowledgeLoss": replace_lossy}); let mut params = with_pixel_scale(params, &output, scale, ppi); + // An option the format doesn't read comes back in the warnings, so each goes out only + // when it was asked for: `outlineText` with --outline-text, and `hiddenLayers` to the + // formats that have it (SVG, PSD), where a conversion keeps hidden layers and objects, + // written hidden. + if outline_text { + params["outlineText"] = json!(true); + } + if vectorcraft_engine::cmd::fileio::writable_format(None, Some(&output)).is_ok_and(|f| f.options.iter().any(|o| o.name == "hiddenLayers")) { + params["hiddenLayers"] = json!(true); + } if let Some(decimals) = decimals { params["decimals"] = json!(decimals); } diff --git a/apps/vectorcraft-cli/tests/it/fileio.rs b/apps/vectorcraft-cli/tests/it/fileio.rs index 71044be4a5..cdb16d28d3 100644 --- a/apps/vectorcraft-cli/tests/it/fileio.rs +++ b/apps/vectorcraft-cli/tests/it/fileio.rs @@ -177,6 +177,27 @@ fn convert_reports_import_warnings() { assert!(w.iter().any(|w| w.as_str().unwrap().contains("nowhere-to-be-found.png")), "{out}"); } +/// A conversion sends each format only the options it reads, so its warnings name an unused +/// option only when the command line gave one: `--outline-text` for a format without it. +#[test] +fn convert_warns_about_an_unused_option_only_when_one_was_given() { + let svg = tmp("unused-option.svg"); + std::fs::write(&svg, r#""#).unwrap(); + let unused = |out: &Value| -> Vec { + let w = out["warnings"].as_array().unwrap_or_else(|| panic!("{out}")); + w.iter().filter_map(Value::as_str).filter(|w| w.contains("was not used")).map(str::to_string).collect() + }; + for ext in ["png", "jpg", "pdf", "ai", "eps", "psd", "dxf", "svg", "txt", "vectorcraft", "vctemplate"] { + let path = tmp(&format!("unused-option.{ext}")); + let out: Value = serde_json::from_str(ok(&["convert", &svg, &path]).trim()).unwrap(); + assert!(unused(&out).is_empty(), "{ext}: {out}"); + } + let out: Value = serde_json::from_str(ok(&["convert", &svg, &tmp("unused-option-outlined.svg"), "--outline-text"]).trim()).unwrap(); + assert!(unused(&out).is_empty(), "{out}"); + let out: Value = serde_json::from_str(ok(&["convert", &svg, &tmp("unused-option-outlined.png"), "--outline-text"]).trim()).unwrap(); + assert_eq!(unused(&out), ["`outlineText` was not used: PNG files don't read it"], "{out}"); +} + #[test] fn convert_writes_legacy_ai_with_its_options() { // Two artboards, a shown rectangle and a hidden one. diff --git a/apps/vectorcraft/Cargo.toml b/apps/vectorcraft/Cargo.toml index 55b9e344e7..ffa1d2a5e8 100644 --- a/apps/vectorcraft/Cargo.toml +++ b/apps/vectorcraft/Cargo.toml @@ -96,26 +96,26 @@ winit = { version = "0.30", default-features = false, features = ["wayland-csd-a x11rb = { version = "0.13", default-features = false, features = ["xinput", "xkb"] } # Asks the Wayland compositor which GPU it draws with (linux-dmabuf feedback, src/compositor_gpu.rs), -# so Automatic draws on that one. Both are already in the build through winit. +# so Automatic draws on that one, and copies and pastes text, SVG and PNG through the compositor's +# core data-device protocol on the window's connection (src/clipboard.rs), where arboard has neither +# data-control (GNOME) nor X11 (a Flatpak on a Wayland session). Both are already in the build +# through winit. wayland-client = "0.31" -# Copy and Paste of text through the compositor's core data-device protocol on the window's -# connection (src/clipboard.rs), where arboard has neither data-control (GNOME) nor X11 (a Flatpak -# on a Wayland session). MIT, already in the build through egui-winit. -smithay-clipboard = "0.7" wayland-protocols = { version = "0.32", features = ["client", "unstable"] } # The save dialog's parent window on Wayland (src/portal_save.rs): an xdg-foreign handle (in # wayland-protocols' `unstable` set) made on the window's own connection. MIT, already in the build # through winit and rfd. wayland-backend = { version = "0.3", features = ["client_system"] } -# Waits for the screen color sampler's portal answer and for the portal leaving the bus at the same -# time (src/linux_screen_color/request.rs). Apache-2.0 OR MIT, already in the build through zbus. -futures-lite = "2" # The save dialog's file type (src/portal_save.rs, #2679): the desktop portal over D-Bus, on the # systems where rfd shows the portal's dialog. MIT, already in the build through accesskit. Pinned # exactly: review the diff before bumping. [target.'cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))'.dependencies] zbus = "=5.19.0" +# Waits for a portal answer (the save dialog's and the screen color sampler's) and for the portal +# leaving the bus at the same time (src/portal_request.rs). Apache-2.0 OR MIT, already in the build +# through zbus. +futures-lite = "2" # Tells whether arboard reads through the compositor's data-control protocol or through X11, the # same check arboard makes (src/clipboard.rs). MIT OR Apache-2.0, already in the build through # arboard. diff --git a/apps/vectorcraft/src/clipboard.rs b/apps/vectorcraft/src/clipboard.rs index 1daccc22f1..77a96442c4 100644 --- a/apps/vectorcraft/src/clipboard.rs +++ b/apps/vectorcraft/src/clipboard.rs @@ -10,8 +10,9 @@ //! 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, and where there is no -//! X11 either (a Flatpak on GNOME) to the compositor's core protocol on the window's connection, -//! text only. A clipboard that can't be opened is tried again after a wait that grows to a +//! X11 either (a Flatpak on GNOME) to the compositor's core protocol on the window's connection: +//! Copy offers SVG (`image/svg+xml`), PNG (`image/png`) and text together, and Paste reads SVG, +//! text and PNG. A clipboard that can't be opened is tried again after a wait that grows to a //! minute, not each time Paste asks. On Linux and the BSDs a read waits 2 s at most for the app //! that copied to send its data (a bitmap 10 s), and until that app answers, later reads fail at //! once; a paste then waits for that read's answer off the UI thread. @@ -24,8 +25,8 @@ use std::path::PathBuf; use vectorcraft_engine::cmd::clipboard::{BITMAP, EPS, FILE_HEAD, Flavour, PDF, PNG, SVG, TEXT, file_flavour}; use vectorcraft_ui_egui::{ClipboardRead, SystemClipboard}; -/// This platform's system clipboard. On Linux, `window`'s Wayland connection carries text where -/// arboard can't open (GNOME has no data-control protocol, a Flatpak there no X11). +/// This platform's system clipboard. On Linux, `window`'s Wayland connection carries text, SVG and +/// PNG where arboard can't open (GNOME has no data-control protocol, a Flatpak there no X11). pub fn system_clipboard(window: Option>) -> Box { #[cfg(windows)] let cb = { @@ -629,6 +630,10 @@ mod portable { enum Ours { Text(String), Image(usize, usize), + /// A Copy through the Wayland core protocol, whose data source tells whether the + /// clipboard still holds it. + #[cfg(target_os = "linux")] + Source, } /// A read of arboard's clipboard. @@ -858,18 +863,14 @@ mod portable { #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] impl Late { /// What a paste of one of `mimes` takes once the answer comes ([`Unanswered::paste`]). The - /// core protocol's text is waited for as long, until [`IMAGE_WAIT`] after its read was - /// sent, then read again, and pasted unless it is empty, what `ours` put on the clipboard, - /// or doesn't come. + /// core protocol's answer is waited for as long, until [`IMAGE_WAIT`] after its read was + /// sent; then the clipboard is read again and pasted as at once, unless it holds the Copy + /// made here ([`super::wayland::Unanswered::paste`]). fn paste(self, ours: Option<&Ours>, mimes: &[&'static str]) -> Option { match self { Self::Arboard(unanswered) => unanswered.paste(ours, mimes), #[cfg(target_os = "linux")] - Self::Wayland(unanswered) => { - let text = unanswered.text(IMAGE_WAIT).ok().filter(|t| !t.is_empty())?; - let held = matches!(ours, Some(Ours::Text(t)) if *t == text); - (!held).then(|| Flavour { mime: TEXT, data: text.into_bytes() }) - } + Self::Wayland(unanswered) => unanswered.paste(mimes, IMAGE_WAIT), } } } @@ -962,14 +963,15 @@ mod portable { /// An open clipboard connection. enum Backend { Arboard(Arboard), - /// The compositor's core data-device protocol on the window's connection (text only). + /// The compositor's core data-device protocol on the window's connection. #[cfg(target_os = "linux")] - Wayland(super::wayland::TextClipboard), + Wayland(super::wayland::DataClipboard), } - /// What a write of a picture says where the clipboard carries text only. + /// What a bitmap read or write says on the core protocol, which carries pictures as PNG data + /// only ([`Clipboard::write`], [`Clipboard::read_now_or_later`]). #[cfg(target_os = "linux")] - const TEXT_ONLY: &str = "this clipboard carries text only"; + const PNG_ONLY: &str = "this clipboard carries pictures as PNG data"; impl Backend { /// arboard (Wayland data-control, else X11), else the core protocol on `window`'s @@ -979,7 +981,10 @@ mod portable { || Arboard::open().map(Self::Arboard), || { #[cfg(target_os = "linux")] - return window.and_then(|w| super::wayland::TextClipboard::new(w.clone())).map(Self::Wayland).ok_or("not a Wayland window"); + return window + .and_then(|w| super::wayland::DataClipboard::new(w.clone())) + .map(Self::Wayland) + .ok_or("not a Wayland window with a seat and a data-device manager"); #[cfg(not(target_os = "linux"))] { let _ = window; @@ -993,7 +998,7 @@ mod portable { match self { Self::Arboard(_) => "arboard", #[cfg(target_os = "linux")] - Self::Wayland(_) => "the Wayland core protocol (text only)", + Self::Wayland(_) => "the Wayland core protocol", } } @@ -1001,7 +1006,7 @@ mod portable { match self { Self::Arboard(cb) => cb.read(Request::Text).text(), #[cfg(target_os = "linux")] - Self::Wayland(cb) => cb.get_text(), + Self::Wayland(cb) => cb.text(), } } @@ -1009,10 +1014,17 @@ mod portable { match self { Self::Arboard(cb) => cb.cb.set_text(text).map_err(|e| e.to_string()), #[cfg(target_os = "linux")] - Self::Wayland(cb) => { - cb.set_text(text); - Ok(()) - } + Self::Wayland(cb) => cb.copy(&[Flavour { mime: TEXT, data: text.as_bytes().to_vec() }]), + } + } + + /// Whether the clipboard holds the core protocol's last Copy made here (never for arboard, + /// whose writes are checked by what they wrote). + #[cfg(target_os = "linux")] + fn holds_source(&mut self) -> bool { + match self { + Self::Arboard(_) => false, + Self::Wayland(cb) => cb.holds_ours(), } } @@ -1025,7 +1037,7 @@ mod portable { #[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd")))] Self::Arboard(cb) => cb.read(Request::Image).image(), #[cfg(target_os = "linux")] - Self::Wayland(_) => Err(TEXT_ONLY.into()), + Self::Wayland(_) => Err(PNG_ONLY.into()), } } @@ -1041,7 +1053,7 @@ mod portable { Ok(Box::new(move || Ok(image))) } #[cfg(target_os = "linux")] - Self::Wayland(_) => Err(TEXT_ONLY.into()), + Self::Wayland(_) => Err(PNG_ONLY.into()), } } @@ -1049,7 +1061,7 @@ mod portable { match self { Self::Arboard(cb) => cb.cb.set_image(img).map_err(|e| e.to_string()), #[cfg(target_os = "linux")] - Self::Wayland(_) => Err(TEXT_ONLY.into()), + Self::Wayland(_) => Err(PNG_ONLY.into()), } } @@ -1057,15 +1069,12 @@ mod portable { match self { Self::Arboard(cb) => cb.cb.clear().map_err(|e| e.to_string()), #[cfg(target_os = "linux")] - Self::Wayland(cb) => { - cb.set_text(""); - Ok(()) - } + Self::Wayland(cb) => cb.copy(&[]), } } /// The read that got no answer in its wait, when a paste of one of `mimes` can take its - /// answer ([`Arboard::unanswered`], [`TextReads::unanswered`](super::wayland::TextReads::unanswered)). + /// answer ([`Arboard::unanswered`], [`Reads::unanswered`](super::wayland::Reads::unanswered)). #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] fn unanswered(&mut self, mimes: &[&'static str]) -> Option { match self { @@ -1223,9 +1232,15 @@ mod portable { Some(ClipboardRead::Later(Box::new(move || unanswered.paste(ours.as_ref(), &mimes)))) } - /// Text and copied files are read here, and work that reads arboard's image comes back. + /// Text and copied files are read here, and work that reads arboard's image comes back. On + /// the Wayland core protocol the first of `mimes` the clipboard offers is read: text here, + /// SVG and PNG by the work that comes back, which waits [`IMAGE_WAIT`] at most. fn read_now_or_later(&mut self, mimes: &[&'static str]) -> Option { let cb = self.cb(Asker::User).ok()?; + #[cfg(target_os = "linux")] + if let Backend::Wayland(cb) = cb { + return cb.read(mimes, IMAGE_WAIT); + } if let Some(f) = copied_file(cb.file_list(), mimes) { return Some(ClipboardRead::Now(f)); } @@ -1247,13 +1262,23 @@ mod portable { } impl SystemClipboard for Clipboard { + /// arboard takes the text, else the PNG as a bitmap; the Wayland core protocol offers the + /// SVG, PNG and text together ([`DataClipboard::copy`](super::wayland::DataClipboard::copy)). fn write(&mut self, flavours: &[Flavour]) -> Result<(), String> { + let cb = self.cb(Asker::User)?; + #[cfg(target_os = "linux")] + if let Backend::Wayland(wl) = cb { + wl.copy(flavours)?; + // What a read got late was on the clipboard before this write. + wl.forget_unanswered(); + self.ours = wl.holds_ours().then_some(Ours::Source); + return Ok(()); + } let text = text_of(flavours); let image = match &text { Some(_) => None, None => flavours.iter().find(|f| f.mime == PNG).and_then(|f| decode_png(&f.data)), }; - let cb = self.cb(Asker::User)?; let ours = match (text, image) { (Some(t), _) => { cb.set_text(t.as_str())?; @@ -1281,6 +1306,8 @@ mod portable { match &self.ours { Some(Ours::Text(t)) => cb.get_text().is_ok_and(|now| now == *t), Some(Ours::Image(w, h)) => cb.image_now().is_ok_and(|now| (now.width, now.height) == (*w, *h)), + #[cfg(target_os = "linux")] + Some(Ours::Source) => cb.holds_source(), None => false, } } @@ -1307,7 +1334,8 @@ mod portable { read } - /// Text, and on macOS vector art or a bitmap (by the pasteboard's types). Linux has no + /// Text, on macOS vector art or a bitmap (by the pasteboard's types), and on the Wayland + /// core protocol SVG, text or PNG (by the types offered, nothing read). arboard has no /// cheap way to ask for a bitmap (reading one costs as much as pasting it): the paste keys /// take it, the menu item waits for text. fn has(&mut self, mimes: &[&'static str]) -> bool { @@ -1315,7 +1343,12 @@ mod portable { if super::mac::has(mimes) { return true; } - mimes.contains(&TEXT) && self.cb(Asker::Probe).is_ok_and(|cb| cb.get_text().is_ok_and(|t| !t.is_empty())) + let Ok(cb) = self.cb(Asker::Probe) else { return false }; + #[cfg(target_os = "linux")] + if let Backend::Wayland(wl) = cb { + return wl.has(mimes); + } + mimes.contains(&TEXT) && cb.get_text().is_ok_and(|t| !t.is_empty()) } } @@ -1656,45 +1689,58 @@ mod portable { #[cfg(target_os = "linux")] #[test] fn a_paste_after_an_unanswered_core_protocol_text_read_waits_for_its_answer() { - use super::super::wayland::TextReads; + use std::sync::{Arc, Mutex}; + + use super::super::wayland::{Reads, Seen}; use vectorcraft_engine::cmd::clipboard::PASTE_ORDER; - /// Core protocol text reads whose owner answers with `text` only once the sender + /// Core protocol reads of a clipboard offering `types`, whose owner answers each read + /// of a text type with `text` and of `image/png` with `png`, only once the sender /// returned is used or dropped. - fn slow_text(text: &'static str) -> (TextReads, std::sync::mpsc::Sender<()>) { + fn slow_owner(types: &[&str], text: &'static str, png: &'static [u8]) -> (Reads, Arc>, std::sync::mpsc::Sender<()>) { let (release, gate) = std::sync::mpsc::channel::<()>(); - let loads = Loads::spawn("test", Duration::ZERO, move |()| { + let loads = Loads::spawn("test", Duration::ZERO, move |wire: String| { let _ = gate.recv(); - Ok(text.to_string()) + Ok(if wire == PNG { png.to_vec() } else { text.as_bytes().to_vec() }) }) .unwrap(); - (TextReads::new(loads), release) + let seen = Arc::new(Mutex::new(Seen::offering(types))); + (Reads::new(loads, seen.clone()), seen, release) } - // Text was copied here; the clipboard's owner answers the check with `text` late. - let paste_after_check = |text: &'static str| { - let (mut reads, release) = slow_text(text); + // The clipboard's owner answers the check with `text` late; `copied_here` when the + // clipboard holds the Copy made here meanwhile. + let paste_after_check = |text: &'static str, copied_here: bool| { + let (mut reads, seen, release) = slow_owner(&["text/plain;charset=utf-8", PNG], text, b"\x89PNG"); // The check whether the clipboard still holds what was copied here gets no answer // in its wait (2 s on the UI thread, none here). - assert!(reads.get(Duration::ZERO).is_err()); + assert!(reads.text(Duration::ZERO).is_err()); // The paste's own read fails at once while the owner hasn't answered. - assert!(reads.get(Duration::from_secs(600)).is_err()); + assert!(reads.text(Duration::from_secs(600)).is_err()); // A paste of a bitmap alone can't take text: the read stays kept. assert!(reads.unanswered(&[BITMAP]).is_none()); let late = Late::Wayland(reads.unanswered(&PASTE_ORDER).expect("the check's read is kept for the paste")); - let ours = Ours::Text("copied here".into()); - let paste = std::thread::spawn(move || late.paste(Some(&ours), &PASTE_ORDER)); + if copied_here { + let mut seen = seen.lock().unwrap(); + seen.copy(vec!["text/plain;charset=utf-8", PNG]); + seen.selection(vec!["text/plain;charset=utf-8".into(), PNG.into()]); + } + let paste = std::thread::spawn(move || late.paste(None, &PASTE_ORDER)); drop(release); paste.join().ok().flatten() }; - let pasted = paste_after_check("copied elsewhere").expect("the other app's text is pasted"); + let pasted = paste_after_check("copied elsewhere", false).expect("the other app's text is pasted"); assert_eq!((pasted.mime, pasted.data), (TEXT, b"copied elsewhere".to_vec())); - // The text copied here, or nothing: the paste takes the internal clipboard. - assert!(paste_after_check("copied here").is_none()); - assert!(paste_after_check("").is_none()); + // Text that only names a picture goes with it: the picture is pasted, as at once. + let pasted = paste_after_check("https://example.com/art.png", false).expect("the picture is pasted"); + assert_eq!((pasted.mime, pasted.data), (PNG, b"\x89PNG".to_vec())); + // The Copy made here, by its data source: the paste takes the internal clipboard. + assert!(paste_after_check("copied elsewhere", true).is_none()); + // Empty text is not pasted: the picture beside it is. + assert_eq!(paste_after_check("", false).map(|f| f.mime), Some(PNG)); // An answer that came before the paste may be old: it is dropped, not pasted. - let (mut reads, release) = slow_text("old"); - assert!(reads.get(Duration::ZERO).is_err()); + let (mut reads, _, release) = slow_owner(&["text/plain"], "old", b""); + assert!(reads.text(Duration::ZERO).is_err()); drop(release); while reads.waiting() { std::thread::yield_now(); @@ -1705,14 +1751,14 @@ mod portable { // again and takes the new owner's text. let (release, gate) = std::sync::mpsc::channel::<()>(); let mut texts_read = 0; - let loads = Loads::spawn("test", Duration::ZERO, move |()| { + let loads = Loads::spawn("test", Duration::ZERO, move |_: String| { let _ = gate.recv(); texts_read += 1; - Ok(if texts_read == 1 { "old owner" } else { "new owner" }.to_string()) + Ok(if texts_read == 1 { "old owner" } else { "new owner" }.as_bytes().to_vec()) }) .unwrap(); - let mut reads = TextReads::new(loads); - assert!(reads.get(Duration::ZERO).is_err()); + let mut reads = Reads::new(loads, Arc::new(Mutex::new(Seen::offering(&["UTF8_STRING"])))); + assert!(reads.text(Duration::ZERO).is_err()); let late = Late::Wayland(reads.unanswered(&[TEXT]).expect("the read is kept for the paste")); let paste = std::thread::spawn(move || late.paste(None, &[TEXT])); drop(release); @@ -1737,81 +1783,311 @@ mod portable { /// The compositor's clipboard through the core data-device protocol (`wl_data_device`), on the /// window's own Wayland connection: what Copy and Paste use where the compositor lacks the /// data-control protocol arboard needs (GNOME) and there is no X11 to fall back on (the Flatpak on -/// a Wayland session). Text only (smithay-clipboard), and only while the window has focus, as the -/// protocol has it. A read waits [`LOAD_WAIT`] at most: smithay-clipboard waits for the owner's -/// data with no limit, so reads run on a worker of their own. A read that gets no answer in that -/// time is kept for a paste to wait for off the UI thread, as arboard's are. +/// a Wayland session). A Copy offers its SVG as `image/svg+xml`, its PNG as `image/png` and its +/// text under each of [`TEXT_TYPES`]; Paste reads the clipboard's SVG, text and PNG, and the paste +/// check looks at the types offered without reading any data. The protocol gives the clipboard to +/// the window with the keyboard focus only. A worker thread handles the protocol's events and +/// starts a thread for each paste of a Copy's data by another app ([`MAX_SENDS`] at once). Reads +/// run on another worker and take [`MAX_BYTES`] at most; text waits [`LOAD_WAIT`] at most, SVG and +/// PNG as long as a paste's bitmap from arboard. A read that gets no answer in its wait is kept for +/// a paste to wait for off the UI thread, as arboard's are. #[cfg(target_os = "linux")] mod wayland { - use std::sync::{Arc, mpsc}; + use std::io::{Read, Write}; + use std::os::fd::AsFd as _; + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + use std::sync::{Arc, Mutex, MutexGuard, PoisonError, mpsc}; use std::time::{Duration, Instant}; - use super::TEXT; + use vectorcraft_engine::cmd::clipboard::names_a_picture; + use vectorcraft_ui_egui::ClipboardRead; + use wayland_client::backend::ObjectData; + use wayland_client::globals::{GlobalListContents, registry_queue_init}; + use wayland_client::protocol::wl_callback::{self, WlCallback}; + use wayland_client::protocol::wl_data_device::{self, WlDataDevice}; + use wayland_client::protocol::wl_data_device_manager::{self, WlDataDeviceManager}; + use wayland_client::protocol::wl_data_offer::{self, WlDataOffer}; + use wayland_client::protocol::wl_data_source::{self, WlDataSource}; + use wayland_client::protocol::wl_keyboard::{self, WlKeyboard}; + use wayland_client::protocol::wl_pointer::{self, WlPointer}; + use wayland_client::protocol::wl_registry::{self, WlRegistry}; + use wayland_client::protocol::wl_seat::{self, WlSeat}; + use wayland_client::{Connection, Dispatch, Proxy, QueueHandle, WEnum}; + use super::loads::{Asker, GONE, LOAD_WAIT, Loads, wait_for_answer}; + use super::{BITMAP, Flavour, PNG, SVG, TEXT}; - /// What a text read gives. - type Text = Result; + /// The types text is offered under and read from, best first: `text/plain;charset=utf-8` (GTK + /// and Qt apps), `UTF8_STRING` (X11 apps through XWayland) and `text/plain`. + const TEXT_TYPES: [&str; 3] = ["text/plain;charset=utf-8", "UTF8_STRING", "text/plain"]; + /// The most bytes a read takes from the app that copied (untrusted data), VectorCraft's own + /// limit: a read of more fails. + const MAX_BYTES: usize = 64 << 20; + /// The most pastes of a Copy's data that are sent at once; a paste beyond them gets nothing. + const MAX_SENDS: usize = 8; + /// The most types of an offer that are kept (untrusted data). + const MAX_TYPES: usize = 256; - pub struct TextClipboard { - /// Writes: a store only hands the text to smithay-clipboard's thread. - cb: smithay_clipboard::Clipboard, - /// Reads, on a worker with a second clipboard on the same connection. - reads: TextReads, - /// Held as long as the clipboards: their connection is the window's. - _window: Arc, + /// What a read gives: the bytes, or why there are none. + type Got = Result, String>; + + fn lock(m: &Mutex) -> MutexGuard<'_, T> { + m.lock().unwrap_or_else(PoisonError::into_inner) } - /// Text reads on a worker, and the last one that got no answer in its wait. - pub(super) struct TextReads { - loads: Loads<(), Text>, - /// The last read that got no answer in its wait, until a paste takes it or the next read - /// is sent. + /// The types a Copy of `flavours` offers, each with its data: SVG as `image/svg+xml`, PNG as + /// `image/png` and text under each of [`TEXT_TYPES`]. Flavours with no data and other flavours + /// (PDF) are not offered. + fn copy_types(flavours: &[Flavour]) -> Vec<(&'static str, Arc<[u8]>)> { + let mut out: Vec<(&'static str, Arc<[u8]>)> = vec![]; + for f in flavours.iter().filter(|f| !f.data.is_empty()) { + let types: &[&'static str] = match f.mime { + SVG => &[SVG], + PNG => &[PNG], + TEXT => &TEXT_TYPES, + _ => &[], + }; + let data: Arc<[u8]> = f.data.as_slice().into(); + for &t in types { + if !out.iter().any(|(o, _)| *o == t) { + out.push((t, data.clone())); + } + } + } + out + } + + /// The type among `offered` that a read of `mime` asks for, in any letter case: SVG as + /// `image/svg+xml`, text as the first of [`TEXT_TYPES`] offered, a bitmap as `image/png`. + fn wire_type<'a>(mime: &str, offered: &'a [String]) -> Option<&'a str> { + let wanted: &[&str] = match mime { + SVG => &[SVG], + TEXT => &TEXT_TYPES, + BITMAP | PNG => &[PNG], + _ => &[], + }; + wanted.iter().find_map(|w| offered.iter().find(|o| o.eq_ignore_ascii_case(w))).map(String::as_str) + } + + /// The flavour a read of `mime` makes of `data`: SVG as it is, a bitmap as PNG, text with its + /// line ends as `\n`. None when `data` is empty. + fn flavour(mime: &'static str, data: Vec) -> Option { + if data.is_empty() { + return None; + } + Some(match mime { + TEXT => Flavour { mime: TEXT, data: String::from_utf8_lossy(&data).replace("\r\n", "\n").replace('\r', "\n").into_bytes() }, + BITMAP | PNG => Flavour { mime: PNG, data }, + _ => Flavour { mime, data }, + }) + } + + /// What a paste of one of `mimes` takes from a clipboard offering `offered`, `read` reading the + /// offer's type for each one tried: the first of `mimes` offered with data, except that text + /// that is blank or only names a picture gives way to the PNG when `mimes` has a bitmap + /// (`adopt_system_clipboard_or_defer` in `vectorcraft-ui-egui`). + fn pick(offered: &[String], mimes: &[&'static str], mut read: impl FnMut(&str) -> Option>) -> Option { + let mut take = |mime: &'static str| flavour(mime, read(wire_type(mime, offered)?)?); + let first = mimes.iter().find_map(|&m| take(m))?; + if first.mime == TEXT && mimes.contains(&BITMAP) { + let text = String::from_utf8_lossy(&first.data); + if text.trim().is_empty() || names_a_picture(&text) { + return take(BITMAP).or(Some(first)); + } + } + Some(first) + } + + /// `from` read to its end, `cap` bytes at most: more is an error, as is a failed read. + fn read_capped(from: impl Read, cap: usize) -> Got { + let mut data = vec![]; + from.take(cap as u64 + 1).read_to_end(&mut data).map_err(|e| format!("couldn't read the clipboard's data: {e}"))?; + if data.len() > cap { + return Err(format!("the clipboard's data is larger than {} MiB", cap >> 20)); + } + Ok(data) + } + + /// The threads that send a Copy's data to the apps that paste it, counted. + #[derive(Clone, Default)] + struct Sends(Arc); + + impl Sends { + /// `data` written to `to` on a thread of its own, which then closes `to`; an app that + /// closes its end early ends the write (the process ignores `SIGPIPE`). While + /// [`MAX_SENDS`] are being written `to` is closed at once with nothing written → false. + fn start(&self, mut to: impl Write + Send + 'static, data: Arc<[u8]>) -> bool { + if self.0.fetch_add(1, Ordering::SeqCst) >= MAX_SENDS { + self.0.fetch_sub(1, Ordering::SeqCst); + return false; + } + let count = self.0.clone(); + let send = move || { + let _ = to.write_all(&data); + drop(to); + count.fetch_sub(1, Ordering::SeqCst); + }; + if std::thread::Builder::new().name("wayland-clipboard-send".into()).spawn(send).is_err() { + self.0.fetch_sub(1, Ordering::SeqCst); + return false; + } + true + } + + /// How many are being written. + #[cfg(test)] + fn running(&self) -> usize { + self.0.load(Ordering::SeqCst) + } + } + + /// What the protocol worker has seen of the clipboard. + #[derive(Default)] + pub(super) struct Seen { + /// The types of the clipboard's offer, none when it is empty. + offered: Vec, + /// The types of this connection's last Copy, until its data source is canceled. + copied: Option>, + /// Whether the clipboard holds that Copy. + ours: bool, + } + + impl Seen { + /// A clipboard offering `types`, copied elsewhere. + #[cfg(test)] + pub(super) fn offering(types: &[&str]) -> Self { + Self { offered: types.iter().map(|t| t.to_string()).collect(), ..Self::default() } + } + + /// A Copy of `types` (none: the clipboard emptied) was given the clipboard. + pub(super) fn copy(&mut self, types: Vec<&'static str>) { + self.ours = !types.is_empty(); + self.copied = Some(types).filter(|t| !t.is_empty()); + } + + /// The clipboard's offer has `offered` now. It holds the last Copy while that Copy's data + /// source is not canceled and the offer has the Copy's types, no more and no fewer, as the + /// compositor offers a source's types. An offer made before the Copy and handled after it + /// makes the Copy not ours until the Copy's own offer comes. + pub(super) fn selection(&mut self, offered: Vec) { + self.ours = self.copied.as_ref().is_some_and(|c| c.len() == offered.len() && c.iter().all(|t| offered.iter().any(|o| o == t))); + self.offered = offered; + } + + /// The last Copy's data source was canceled: another app holds the clipboard. + pub(super) fn cancelled(&mut self) { + self.copied = None; + self.ours = false; + } + } + + /// Reads of the clipboard's offer on a worker, and the last one that got no answer in its wait. + pub(super) struct Reads { + /// Each request is the offer's type to read. + loads: Loads, + seen: Arc>, + /// The last text read that got no answer in its wait, until a paste takes it or the next + /// read is sent. unanswered: Option, } /// A text read that got no answer in its wait. pub(super) struct Unanswered { - answer: mpsc::Receiver, + answer: mpsc::Receiver, sent: Instant, - /// The worker, for the read made again once the answer comes. - reads: Asker<(), Text>, + /// The worker, for the reads made once the answer comes. + reads: Asker, + seen: Arc>, } impl Unanswered { - /// The text, read again once this read's answer comes, waiting for that answer until - /// `limit` after the read was sent, and for the new one as long, [`LOAD_WAIT`] at least. - /// The late answer may come from an app that lost the clipboard while it was awaited. - pub(super) fn text(self, limit: Duration) -> Text { + /// What a paste of one of `mimes` takes once this read's answer comes, waiting for it until + /// `limit` after the read was sent: the clipboard read again as [`pick`] reads it, each read + /// waiting as long, [`LOAD_WAIT`] at least, since the app that answers late may have lost the + /// clipboard meanwhile. None when the answer doesn't come or the clipboard holds this + /// connection's Copy. + pub(super) fn paste(self, mimes: &[&'static str], limit: Duration) -> Option { let left = |now: Instant| (self.sent + limit).saturating_duration_since(now); - let _late = wait_for_answer(&self.answer, left(Instant::now()))?; - wait_for_answer(&self.reads.ask(())?, LOAD_WAIT.max(left(Instant::now())))? + let _late = wait_for_answer(&self.answer, left(Instant::now())).ok()?; + let offered = { + let seen = lock(&self.seen); + if seen.ours { + return None; + } + seen.offered.clone() + }; + pick(&offered, mimes, |wire| wait_for_answer(&self.reads.ask(wire.to_string()).ok()?, LOAD_WAIT.max(left(Instant::now()))).ok()?.ok()) } } - impl TextReads { - pub(super) fn new(loads: Loads<(), Text>) -> Self { - Self { loads, unanswered: None } + impl Reads { + pub(super) fn new(loads: Loads, seen: Arc>) -> Self { + Self { loads, seen, unanswered: None } } - /// The text, waiting `wait` at most. A read that gets no answer in that time is kept - /// ([`Self::unanswered`]) for a paste to wait for off the UI thread; a read sent means the - /// one kept has been answered, and its answer is dropped. - pub(super) fn get(&mut self, wait: Duration) -> Text { + /// The offer's type for `mime`, when it has one. + fn wire(&self, mime: &str) -> Option { + wire_type(mime, &lock(&self.seen).offered).map(str::to_string) + } + + /// The text, waiting `wait` at most; empty when the clipboard has none. A read that gets no + /// answer in that time is kept ([`Self::unanswered`]) for a paste to wait for off the UI + /// thread; a read sent means the one kept has been answered, and its answer is dropped. + pub(super) fn text(&mut self, wait: Duration) -> Result { + let Some(wire) = self.wire(TEXT) else { return Ok(String::new()) }; let sent = Instant::now(); - let answer = self.loads.ask(())?; + let answer = self.loads.ask(wire)?; self.unanswered = None; match wait_for_answer(&answer, wait) { - Ok(text) => text, + Ok(got) => Ok(flavour(TEXT, got?).map(|f| String::from_utf8_lossy(&f.data).into_owned()).unwrap_or_default()), Err(why) => { if why != GONE { - self.unanswered = Some(Unanswered { answer, sent, reads: self.loads.asker() }); + self.unanswered = Some(Unanswered { answer, sent, reads: self.loads.asker(), seen: self.seen.clone() }); } Err(why) } } } - /// The read that got no answer in its wait, while its answer has still not come and a + /// What a paste of one of `mimes` reads: the first the clipboard offers. Text is read here, + /// [`LOAD_WAIT`] at most, and pasted unless it is empty; SVG and PNG are asked for here and + /// waited for, `wait` at most, by the work that comes back. When that read fails or is + /// empty, the work reads the rest of `mimes` as [`pick`] does, each read waiting until + /// `wait` after the first was sent, [`LOAD_WAIT`] at least. + pub(super) fn read(&mut self, mimes: &[&'static str], wait: Duration) -> Option { + mimes.iter().enumerate().find_map(|(i, &mime)| { + let wire = self.wire(mime)?; + if mime == TEXT { + let text = self.text(LOAD_WAIT).ok().filter(|t| !t.is_empty())?; + return Some(ClipboardRead::Now(Flavour { mime: TEXT, data: text.into_bytes() })); + } + let sent = Instant::now(); + let answer = self.loads.ask(wire).ok()?; + self.unanswered = None; + let (reads, seen, rest) = (self.loads.asker(), self.seen.clone(), mimes.get(i + 1..).unwrap_or_default().to_vec()); + Some(ClipboardRead::Later(Box::new(move || { + if let Some(f) = wait_for_answer(&answer, wait).ok().and_then(Result::ok).and_then(|data| flavour(mime, data)) { + return Some(f); + } + let offered = lock(&seen).offered.clone(); + let left = || LOAD_WAIT.max((sent + wait).saturating_duration_since(Instant::now())); + pick(&offered, &rest, |wire| wait_for_answer(&reads.ask(wire.to_string()).ok()?, left()).ok()?.ok()) + }))) + }) + } + + /// Whether the clipboard offers one of `mimes`; nothing is read. + pub(super) fn has(&self, mimes: &[&'static str]) -> bool { + let seen = lock(&self.seen); + mimes.iter().any(|m| wire_type(m, &seen.offered).is_some()) + } + + /// Whether the clipboard holds this connection's last Copy. + pub(super) fn holds_ours(&self) -> bool { + lock(&self.seen).ours + } + + /// The text read that got no answer in its wait, while its answer has still not come and a /// paste of one of `mimes` can take text. Once it has come the answer may be old, and it is /// dropped: a new read is made. pub(super) fn unanswered(&mut self, mimes: &[&'static str]) -> Option { @@ -1819,6 +2095,11 @@ mod wayland { self.loads.waiting().then_some(unanswered) } + /// Drops the read that got no answer in its wait: a paste no longer takes its answer. + pub(super) fn forget_unanswered(&mut self) { + self.unanswered = None; + } + /// Whether a read sent is still unanswered. #[cfg(test)] pub(super) fn waiting(&self) -> bool { @@ -1826,55 +2107,591 @@ mod wayland { } } - /// The read worker's clipboard and the window whose connection it uses, dropped in that order. - struct Loader { - cb: smithay_clipboard::Clipboard, + /// The protocol objects of a [`DataClipboard`], kept up to date by its worker. + #[derive(Default)] + struct Objects { + device: Option, + keyboard: Option, + pointer: Option, + /// The serial of the last key press, click or keyboard focus, which a Copy takes the + /// clipboard with. + serial: Option, + /// The clipboard's offer. + selection: Option, + /// The offer of a drag over the window. + drag: Option, + /// The last Copy's data source. + source: Option, + } + + /// An offer's types, as its events give them. + #[derive(Default)] + struct OfferData(Mutex>); + + /// A Copy's types with their data. + struct SourceData(Vec<(&'static str, Arc<[u8]>)>); + + /// What the protocol worker's event handlers change. + struct State { + objects: Arc>, + seen: Arc>, + sends: Sends, + } + + impl State { + /// Lets go of every object, once the clipboard is dropped. + fn close(&mut self, seat: &WlSeat) { + let mut o = lock(&self.objects); + for offer in [o.selection.take(), o.drag.take()].into_iter().flatten() { + offer.destroy(); + } + if let Some(source) = o.source.take() { + source.destroy(); + } + if let Some(device) = o.device.take().filter(|d| d.version() >= 2) { + device.release(); + } + if let Some(keyboard) = o.keyboard.take().filter(|k| k.version() >= 3) { + keyboard.release(); + } + if let Some(pointer) = o.pointer.take().filter(|p| p.version() >= 3) { + pointer.release(); + } + if seat.version() >= 5 { + seat.release(); + } + } + } + + impl Dispatch for State { + fn event(_: &mut Self, _: &WlRegistry, _: wl_registry::Event, _: &GlobalListContents, _: &Connection, _: &QueueHandle) {} + } + + impl Dispatch for State { + fn event(_: &mut Self, _: &WlCallback, _: wl_callback::Event, _: &(), _: &Connection, _: &QueueHandle) {} + } + + impl Dispatch for State { + fn event(_: &mut Self, _: &WlDataDeviceManager, _: wl_data_device_manager::Event, _: &(), _: &Connection, _: &QueueHandle) {} + } + + impl Dispatch for State { + fn event(state: &mut Self, seat: &WlSeat, event: wl_seat::Event, _: &(), _: &Connection, qh: &QueueHandle) { + let wl_seat::Event::Capabilities { capabilities: WEnum::Value(caps) } = event else { return }; + let mut o = lock(&state.objects); + if !caps.contains(wl_seat::Capability::Keyboard) { + if let Some(keyboard) = o.keyboard.take().filter(|k| k.version() >= 3) { + keyboard.release(); + } + } else if o.keyboard.is_none() { + o.keyboard = Some(seat.get_keyboard(qh, ())); + } + if !caps.contains(wl_seat::Capability::Pointer) { + if let Some(pointer) = o.pointer.take().filter(|p| p.version() >= 3) { + pointer.release(); + } + } else if o.pointer.is_none() { + o.pointer = Some(seat.get_pointer(qh, ())); + } + } + } + + /// The serial a Copy takes the clipboard with after the keyboard event `event`, `serial` before + /// it: a key or the keyboard focus coming in sets it, the focus leaving clears it, and other + /// events leave it. A modifier change's serial is not an input event's, and the release of Ctrl + /// after Ctrl+C comes before the Copy's data is ready. + fn keyboard_serial(event: &wl_keyboard::Event, serial: Option) -> Option { + match event { + wl_keyboard::Event::Enter { serial, .. } | wl_keyboard::Event::Key { serial, .. } => Some(*serial), + wl_keyboard::Event::Leave { .. } => None, + _ => serial, + } + } + + impl Dispatch for State { + fn event(state: &mut Self, _: &WlKeyboard, event: wl_keyboard::Event, _: &(), _: &Connection, _: &QueueHandle) { + let mut o = lock(&state.objects); + o.serial = keyboard_serial(&event, o.serial); + } + } + + impl Dispatch for State { + fn event(state: &mut Self, _: &WlPointer, event: wl_pointer::Event, _: &(), _: &Connection, _: &QueueHandle) { + if let wl_pointer::Event::Button { serial, .. } = event { + lock(&state.objects).serial = Some(serial); + } + } + } + + impl Dispatch for State { + fn event(state: &mut Self, _: &WlDataDevice, event: wl_data_device::Event, _: &(), _: &Connection, _: &QueueHandle) { + let mut o = lock(&state.objects); + match event { + wl_data_device::Event::Selection { id } => { + let mut offered = id.as_ref().and_then(|offer| offer.data::()).map(|d| lock(&d.0).clone()).unwrap_or_default(); + offered.dedup(); + if let Some(old) = std::mem::replace(&mut o.selection, id) { + old.destroy(); + } + lock(&state.seen).selection(offered); + } + wl_data_device::Event::Enter { id, .. } => { + if let Some(old) = std::mem::replace(&mut o.drag, id) { + old.destroy(); + } + } + wl_data_device::Event::Leave | wl_data_device::Event::Drop => { + if let Some(old) = o.drag.take() { + old.destroy(); + } + } + _ => {} + } + } + + /// The one event of a data device that makes an object is `data_offer`. + fn event_created_child(_: u16, qh: &QueueHandle) -> Arc { + qh.make_data::(OfferData::default()) + } + } + + impl Dispatch for State { + fn event(_: &mut Self, _: &WlDataOffer, event: wl_data_offer::Event, data: &OfferData, _: &Connection, _: &QueueHandle) { + if let wl_data_offer::Event::Offer { mime_type } = event { + let mut types = lock(&data.0); + if types.len() < MAX_TYPES { + types.push(mime_type); + } + } + } + } + + impl Dispatch for State { + fn event(state: &mut Self, source: &WlDataSource, event: wl_data_source::Event, data: &SourceData, _: &Connection, _: &QueueHandle) { + match event { + // A type the Copy doesn't offer gets nothing: dropping `fd` closes it. + wl_data_source::Event::Send { mime_type, fd } => { + if let Some((_, bytes)) = data.0.iter().find(|(t, _)| t.eq_ignore_ascii_case(&mime_type)) { + state.sends.start(std::fs::File::from(fd), bytes.clone()); + } + } + wl_data_source::Event::Cancelled => { + source.destroy(); + let mut o = lock(&state.objects); + if o.source.as_ref() == Some(source) { + o.source = None; + lock(&state.seen).cancelled(); + } + } + _ => {} + } + } + } + + /// Reads the clipboard's offer for the read worker. + struct Receiver { + conn: Connection, + objects: Arc>, + /// Held as long as the connection, which is the window's. _window: Arc, } - impl Loader { - fn load(&self) -> Result { - self.cb.load().map_err(|e| e.to_string()) + impl Receiver { + /// The clipboard's data of type `wire`, read until the app that copied closes the pipe, + /// [`MAX_BYTES`] at most. + fn receive(&self, wire: String) -> Got { + let offer = lock(&self.objects).selection.clone().ok_or("the clipboard is empty")?; + let (from, to) = std::io::pipe().map_err(|e| format!("couldn't open a pipe for the clipboard's data: {e}"))?; + offer.receive(wire, to.as_fd()); + // The request carries a copy of the write end: once it is sent, the app that copied + // holds the only one, and the read ends when that app closes it. + drop(to); + self.conn.flush().map_err(|e| format!("couldn't reach the compositor: {e}"))?; + read_capped(from, MAX_BYTES) } } - impl TextClipboard { - /// None when `window` isn't a Wayland window or the read worker can't start. - #[allow(unsafe_code)] + pub struct DataClipboard { + reads: Reads, + objects: Arc>, + manager: WlDataDeviceManager, + conn: Connection, + qh: QueueHandle, + /// Tells the protocol worker to stop. + stop: Arc, + /// Held as long as the connection, which is the window's. + _window: Arc, + } + + impl DataClipboard { + /// None when `window` isn't a Wayland window, the compositor has no data-device manager or + /// seat, or a worker can't start. pub fn new(window: Arc) -> Option { - use winit::raw_window_handle::{HasDisplayHandle as _, RawDisplayHandle}; - let RawDisplayHandle::Wayland(d) = window.display_handle().ok()?.as_raw() else { return None }; - let display = d.display.as_ptr(); - // SAFETY: the display is winit's open `wl_display`, which outlives `window`; each - // clipboard is held beside a clone of `window` and dropped before it. smithay-clipboard - // makes its own event queue on the display and doesn't close it. - let (cb, reader) = unsafe { (smithay_clipboard::Clipboard::new(display), smithay_clipboard::Clipboard::new(display)) }; - let loader = Loader { cb: reader, _window: window.clone() }; - // `loader.load()`, not `loader.cb.load()`: a closure moves only the fields it names, - // and the worker must hold the window as long as its clipboard. + let conn = connection(&window)?; + let (globals, mut queue) = registry_queue_init::(&conn).ok()?; + let qh = queue.handle(); + let manager: WlDataDeviceManager = globals.bind(&qh, 1..=3, ()).ok()?; + let seat: WlSeat = globals.bind(&qh, 1..=5, ()).ok()?; + let (objects, seen) = (Arc::>::default(), Arc::>::default()); + lock(&objects).device = Some(manager.get_data_device(&seat, &qh, ())); + let mut state = State { objects: objects.clone(), seen: seen.clone(), sends: Sends::default() }; + // The seat's keyboard and pointer, and the clipboard's offer when the window has focus. + queue.roundtrip(&mut state).ok()?; + let receiver = Receiver { conn: conn.clone(), objects: objects.clone(), _window: window.clone() }; // Dropping doesn't wait for an unanswered read: only arboard's X11 handles hand what the // app copied on when the last one goes. - let loads = Loads::spawn("wayland-clipboard-read", Duration::ZERO, move |()| loader.load())?; - Some(Self { cb, reads: TextReads::new(loads), _window: window }) + let loads = Loads::spawn("wayland-clipboard-read", Duration::ZERO, move |wire| receiver.receive(wire))?; + let stop = Arc::new(AtomicBool::new(false)); + let (stopped, held) = (stop.clone(), window.clone()); + let work = move || { + while !stopped.load(Ordering::SeqCst) && queue.blocking_dispatch(&mut state).is_ok() {} + state.close(&seat); + let _ = queue.flush(); + drop(held); + }; + std::thread::Builder::new().name("wayland-clipboard".into()).spawn(work).ok()?; + Some(Self { reads: Reads::new(loads, seen), objects, manager, conn, qh, stop, _window: window }) } - pub fn get_text(&mut self) -> Result { - self.reads.get(LOAD_WAIT) + /// Gives the clipboard to a Copy of `flavours` ([`copy_types`]); none empties it. Err when + /// the seat has no data device or the window has had no input to take the clipboard with. + pub fn copy(&mut self, flavours: &[Flavour]) -> Result<(), String> { + let offered = copy_types(flavours); + let mut o = lock(&self.objects); + let device = o.device.clone().ok_or("the seat has no clipboard")?; + let serial = o.serial.ok_or("the window has had no key press or click to copy with")?; + let types: Vec<&'static str> = offered.iter().map(|(t, _)| *t).collect(); + let source = (!offered.is_empty()).then(|| { + let source = self.manager.create_data_source(&self.qh, SourceData(offered)); + for t in &types { + source.offer(t.to_string()); + } + source + }); + device.set_selection(source.as_ref(), serial); + if let Some(old) = std::mem::replace(&mut o.source, source) { + old.destroy(); + } + lock(&self.reads.seen).copy(types); + drop(o); + self.conn.flush().map_err(|e| format!("couldn't reach the compositor: {e}")) } - pub fn set_text(&self, text: &str) { - self.cb.store(text); + pub fn text(&mut self) -> Result { + self.reads.text(LOAD_WAIT) + } + + /// What a paste of one of `mimes` reads ([`Reads::read`]), SVG and PNG waited for `wait` at + /// most. + pub fn read(&mut self, mimes: &[&'static str], wait: Duration) -> Option { + self.reads.read(mimes, wait) + } + + pub fn has(&self, mimes: &[&'static str]) -> bool { + self.reads.has(mimes) + } + + pub fn holds_ours(&self) -> bool { + self.reads.holds_ours() } /// The read that got no answer in its wait, when a paste of one of `mimes` can take its - /// answer ([`TextReads::unanswered`]). + /// answer ([`Reads::unanswered`]). pub(super) fn unanswered(&mut self, mimes: &[&'static str]) -> Option { self.reads.unanswered(mimes) } /// Drops the read that got no answer in its wait: a paste no longer takes its answer. pub fn forget_unanswered(&mut self) { - self.reads.unanswered = None; + self.reads.forget_unanswered(); + } + } + + impl Drop for DataClipboard { + /// Stops the protocol worker, which a sync request's answer wakes. + fn drop(&mut self) { + self.stop.store(true, Ordering::SeqCst); + let _ = self.conn.display().sync(&self.qh, ()); + let _ = self.conn.flush(); + } + } + + /// A connection on `window`'s Wayland display. + #[allow(unsafe_code)] + fn connection(window: &winit::window::Window) -> Option { + use wayland_backend::sys::client::Backend; + use winit::raw_window_handle::{HasDisplayHandle as _, RawDisplayHandle}; + let RawDisplayHandle::Wayland(d) = window.display_handle().ok()?.as_raw() else { return None }; + // SAFETY: the display is winit's open `wl_display`, which outlives `window`; every user of + // the connection holds a clone of `window`. A backend made from a foreign display does not + // close it when dropped. + let backend = unsafe { Backend::from_foreign_display(d.display.as_ptr().cast()) }; + Some(Connection::from_backend(backend)) + } + + #[cfg(test)] + mod tests { + use super::*; + + fn flavour_of(mime: &'static str, data: &[u8]) -> Flavour { + Flavour { mime, data: data.to_vec() } + } + + fn offered(types: &[&str]) -> Vec { + types.iter().map(|t| t.to_string()).collect() + } + + #[test] + fn a_copy_offers_its_svg_png_and_text_each_with_its_own_data() { + let flavours = [flavour_of(TEXT, b""), flavour_of(SVG, b""), flavour_of(super::super::PDF, b"%PDF"), flavour_of(PNG, b"png")]; + let types: Vec<(&str, Vec)> = copy_types(&flavours).into_iter().map(|(t, d)| (t, d.to_vec())).collect(); + assert_eq!( + types, + [ + ("text/plain;charset=utf-8", b"".to_vec()), + ("UTF8_STRING", b"".to_vec()), + ("text/plain", b"".to_vec()), + (SVG, b"".to_vec()), + (PNG, b"png".to_vec()), + ] + ); + // With Include SVG Code off the engine makes no SVG flavour, and none is offered; a + // flavour with no data is not offered either. + let types: Vec<&str> = copy_types(&[flavour_of(PNG, b"png"), flavour_of(TEXT, b"")]).into_iter().map(|(t, _)| t).collect(); + assert_eq!(types, [PNG]); + assert!(copy_types(&[]).is_empty()); + } + + #[test] + fn a_read_asks_for_the_offers_own_type() { + let all = offered(&["text/plain", "TEXT", "UTF8_STRING", "Image/PNG", "image/svg+xml", "application/pdf"]); + assert_eq!(wire_type(TEXT, &all), Some("UTF8_STRING")); + assert_eq!(wire_type(TEXT, &offered(&["text/plain", "text/plain;charset=UTF-8"])), Some("text/plain;charset=UTF-8")); + assert_eq!(wire_type(BITMAP, &all), Some("Image/PNG")); + assert_eq!(wire_type(SVG, &all), Some("image/svg+xml")); + // PDF, EPS and metafiles are not read here, nor types no reader knows. + assert_eq!(wire_type(super::super::PDF, &all), None); + assert_eq!(wire_type(TEXT, &offered(&["text/html", "image/jpeg"])), None); + assert_eq!(wire_type(SVG, &[]), None); + } + + /// What a paste of `mimes` takes from a clipboard holding `data` by type, and the types read. + fn pasted(data: &[(&str, &[u8])], mimes: &[&'static str]) -> (Option, Vec) { + let types: Vec = data.iter().map(|(t, _)| t.to_string()).collect(); + let mut read = vec![]; + let f = pick(&types, mimes, |wire| { + read.push(wire.to_string()); + data.iter().find(|(t, _)| *t == wire).map(|(_, d)| d.to_vec()) + }); + (f, read) + } + + #[test] + fn a_paste_takes_svg_then_text_then_png() { + use vectorcraft_engine::cmd::clipboard::PASTE_ORDER; + let svg: (&str, &[u8]) = (SVG, b""); + let text: (&str, &[u8]) = ("text/plain;charset=utf-8", b"a\r\nb"); + let png: (&str, &[u8]) = (PNG, b"\x89PNG"); + let (f, read) = pasted(&[text, png, svg], &PASTE_ORDER); + assert_eq!(f.map(|f| (f.mime, f.data)), Some((SVG, svg.1.to_vec()))); + assert_eq!(read, [SVG]); + // Text before a bitmap, its line ends made `\n`. + let (f, _) = pasted(&[png, text], &PASTE_ORDER); + assert_eq!(f.map(|f| (f.mime, f.data)), Some((TEXT, b"a\nb".to_vec()))); + // An offer of a PNG or SVG alone pastes it. + assert_eq!(pasted(&[png], &PASTE_ORDER).0.map(|f| (f.mime, f.data)), Some((PNG, png.1.to_vec()))); + assert_eq!(pasted(&[svg], &PASTE_ORDER).0.map(|f| f.mime), Some(SVG)); + // Blank text, or text that only names a picture, gives way to the picture. + for beside in [&b" \n"[..], b"https://example.com/art.png", b""] { + let (f, read) = pasted(&[("UTF8_STRING", beside), png], &PASTE_ORDER); + assert_eq!(f.map(|f| f.mime), Some(PNG)); + assert_eq!(read, ["UTF8_STRING", PNG]); + } + // With no picture, or a paste of text alone, the text is what there is. + assert_eq!(pasted(&[("text/plain", &b"https://example.com/art.png"[..])], &PASTE_ORDER).0.map(|f| f.mime), Some(TEXT)); + assert_eq!(pasted(&[("text/plain", &b" "[..]), png], &[TEXT]).0.map(|f| f.mime), Some(TEXT)); + // An empty clipboard, a type no reader knows, data that doesn't come or is empty. + assert_eq!(pasted(&[], &PASTE_ORDER).0, None); + assert_eq!(pasted(&[("application/x-other", &b"x"[..])], &PASTE_ORDER).0, None); + assert_eq!(pasted(&[(PNG, &b""[..])], &PASTE_ORDER).0, None); + let types = offered(&[PNG]); + assert_eq!(pick(&types, &PASTE_ORDER, |_| None), None); + } + + #[test] + fn the_clipboard_holds_a_copy_until_another_app_takes_it() { + let mut seen = Seen::default(); + let types = vec!["text/plain;charset=utf-8", SVG, PNG]; + seen.copy(types.clone()); + assert!(seen.ours, "a Copy holds the clipboard before its offer comes"); + // An offer made before the Copy and handled after it. + seen.selection(offered(&[PNG])); + assert!(!seen.ours); + // The Copy's own offer, its types in another order. + seen.selection(offered(&[PNG, SVG, "text/plain;charset=utf-8"])); + assert!(seen.ours); + // Another app's copy: an offer with other types, then the source canceled. + seen.selection(offered(&[PNG, SVG, "text/plain;charset=utf-8", "text/html"])); + assert!(!seen.ours); + seen.selection(offered(&[PNG, SVG, "text/plain;charset=utf-8"])); + seen.cancelled(); + assert!(!seen.ours, "a canceled source no longer holds the clipboard"); + // Another app's offer with the same types after that is not ours. + seen.selection(offered(&[PNG, SVG, "text/plain;charset=utf-8"])); + assert!(!seen.ours); + // An empty Copy empties the clipboard. + seen.copy(vec![]); + assert!(!seen.ours); + seen.selection(vec![]); + assert!(!seen.ours && seen.offered.is_empty()); + } + + #[test] + fn a_copy_takes_the_clipboard_with_a_key_press_not_a_modifier_change() { + let key = |serial| wl_keyboard::Event::Key { serial, time: 0, key: 46, state: WEnum::Value(wl_keyboard::KeyState::Pressed) }; + let modifiers = |serial| wl_keyboard::Event::Modifiers { serial, mods_depressed: 0, mods_latched: 0, mods_locked: 0, group: 0 }; + // Ctrl+C, then Ctrl released before the Copy's data is ready. + let serial = keyboard_serial(&key(7), None); + assert_eq!(keyboard_serial(&modifiers(8), serial), Some(7)); + assert_eq!(keyboard_serial(&wl_keyboard::Event::RepeatInfo { rate: 25, delay: 600 }, Some(7)), Some(7)); + assert_eq!(keyboard_serial(&modifiers(9), None), None); + } + + #[test] + fn a_read_stops_at_its_limit() { + assert_eq!(MAX_BYTES, 64 * 1024 * 1024); + assert_eq!(read_capped(&b"12345678"[..], 8), Ok(b"12345678".to_vec())); + assert_eq!(read_capped(&b""[..], 8), Ok(vec![])); + assert_eq!(read_capped(&[0u8; 9][..], 8), Err("the clipboard's data is larger than 0 MiB".to_string())); + assert_eq!(read_capped(&vec![0u8; (2 << 20) + 1][..], 2 << 20), Err("the clipboard's data is larger than 2 MiB".to_string())); + /// A pipe that breaks. + struct Broken; + impl Read for Broken { + fn read(&mut self, _: &mut [u8]) -> std::io::Result { + Err(std::io::ErrorKind::BrokenPipe.into()) + } + } + assert!(read_capped(Broken, 8).is_err_and(|e| e.starts_with("couldn't read the clipboard's data"))); + } + + #[test] + fn a_copys_data_is_sent_through_the_pipe_and_closed() { + let sends = Sends::default(); + let (from, to) = std::io::pipe().unwrap(); + let data: Arc<[u8]> = vec![7u8; 300_000].into(); + assert!(sends.start(to, data.clone())); + // More than a pipe holds: the write ends once all of it is read, then the pipe closes. + assert_eq!(read_capped(from, MAX_BYTES).as_deref(), Ok(&data[..])); + // An app that closes its end before reading ends the send. + let (from, to) = std::io::pipe().unwrap(); + drop(from); + assert!(sends.start(to, data.clone())); + while sends.running() > 0 { + std::thread::yield_now(); + } + } + + #[test] + fn pastes_that_read_nothing_hold_a_few_sends_at_most() { + let sends = Sends::default(); + let data: Arc<[u8]> = vec![1u8; 300_000].into(); + // Apps that ask for the data and never read it. + let stalled: Vec<_> = (0..MAX_SENDS) + .map(|_| { + let (from, to) = std::io::pipe().unwrap(); + assert!(sends.start(to, data.clone())); + from + }) + .collect(); + // The next paste gets its pipe closed at once, with nothing written. + let (from, to) = std::io::pipe().unwrap(); + assert!(!sends.start(to, data.clone())); + assert_eq!(read_capped(from, MAX_BYTES), Ok(vec![])); + // Once those apps close their pipes, the sends end and others are sent again. + drop(stalled); + while sends.running() > 0 { + std::thread::yield_now(); + } + let (from, to) = std::io::pipe().unwrap(); + assert!(sends.start(to, data.clone())); + assert_eq!(read_capped(from, MAX_BYTES).map(|d| d.len()), Ok(data.len())); + } + + /// What a clipboard holds, by type. + type Held = &'static [(&'static str, &'static [u8])]; + const PNG_ONLY: Held = &[(PNG, b"\x89PNG")]; + const SVG_ONLY: Held = &[(SVG, b"")]; + const TEXT_ONLY: Held = &[("text/plain;charset=utf-8", b"words")]; + const EMPTY_TEXT: Held = &[("text/plain", b"")]; + const NOTHING: Held = &[]; + const UNKNOWN: Held = &[("application/x-other", b"x")]; + + /// Reads of a clipboard holding `data`, answered at once. + fn reads_of(data: Held) -> Reads { + let loads = Loads::spawn("test", Duration::ZERO, move |wire: String| { + data.iter().find(|(t, _)| *t == wire).map(|(_, d)| d.to_vec()).ok_or_else(|| "not offered".to_string()) + }) + .unwrap(); + let types: Vec<&str> = data.iter().map(|(t, _)| *t).collect(); + Reads::new(loads, Arc::new(Mutex::new(Seen::offering(&types)))) + } + + #[test] + fn a_picture_or_svg_alone_can_be_pasted_and_is() { + use vectorcraft_engine::cmd::clipboard::PASTE_ORDER; + let wait = Duration::from_secs(600); + for (data, mime) in [(PNG_ONLY, PNG), (SVG_ONLY, SVG)] { + let mut reads = reads_of(data); + // The paste check enables Paste from the types alone. + assert!(reads.has(&PASTE_ORDER)); + let Some(ClipboardRead::Later(work)) = reads.read(&PASTE_ORDER, wait) else { panic!("{mime} is read off the UI thread") }; + assert_eq!(work().map(|f| (f.mime, f.data)), Some((mime, data[0].1.to_vec()))); + } + let mut reads = reads_of(TEXT_ONLY); + assert!(reads.has(&[TEXT]) && !reads.has(&[BITMAP, SVG])); + let Some(ClipboardRead::Now(f)) = reads.read(&PASTE_ORDER, wait) else { panic!("text is read at once") }; + assert_eq!((f.mime, f.data), (TEXT, b"words".to_vec())); + // An empty clipboard, or one with no type a paste reads, enables nothing and pastes nothing. + for data in [NOTHING, UNKNOWN] { + let mut reads = reads_of(data); + assert!(!reads.has(&PASTE_ORDER)); + assert!(reads.read(&PASTE_ORDER, wait).is_none()); + assert_eq!(reads.text(wait), Ok(String::new())); + } + // Empty text is not pasted. + assert!(reads_of(EMPTY_TEXT).read(&[TEXT], wait).is_none()); + } + + #[test] + fn an_svg_that_sends_nothing_gives_way_to_the_text_or_png_beside_it() { + use vectorcraft_engine::cmd::clipboard::PASTE_ORDER; + const EMPTY_SVG_TEXT: Held = &[(SVG, b""), ("text/plain", b"words"), (PNG, b"\x89PNG")]; + const EMPTY_SVG_PNG: Held = &[(SVG, b""), (PNG, b"\x89PNG")]; + const EMPTY_SVG_URL: Held = &[(SVG, b""), ("text/plain", b"https://example.com/art.png"), (PNG, b"\x89PNG")]; + let wait = Duration::from_secs(600); + const EMPTY_PNG: Held = &[(PNG, b"")]; + for (data, mime, bytes) in + [(EMPTY_SVG_TEXT, TEXT, &b"words"[..]), (EMPTY_SVG_PNG, PNG, &b"\x89PNG"[..]), (EMPTY_SVG_URL, PNG, &b"\x89PNG"[..])] + { + // Held while the work runs, as the clipboard is. + let mut reads = reads_of(data); + let Some(ClipboardRead::Later(work)) = reads.read(&PASTE_ORDER, wait) else { panic!("the SVG is asked for") }; + assert_eq!(work().map(|f| (f.mime, f.data)), Some((mime, bytes.to_vec()))); + } + // A failed PNG read, last of all, pastes nothing. + let mut reads = reads_of(EMPTY_PNG); + let Some(ClipboardRead::Later(work)) = reads.read(&PASTE_ORDER, wait) else { panic!("the PNG is asked for") }; + assert!(work().is_none()); + } + + #[test] + fn a_read_that_fails_pastes_nothing() { + let loads = Loads::spawn("test", Duration::ZERO, |_: String| Err::, _>("the clipboard's data is larger than 64 MiB".to_string())) + .unwrap(); + let mut reads = Reads::new(loads, Arc::new(Mutex::new(Seen::offering(&[PNG, "text/plain"])))); + assert_eq!(reads.text(Duration::from_secs(600)), Err("the clipboard's data is larger than 64 MiB".to_string())); + let Some(ClipboardRead::Later(work)) = reads.read(&[BITMAP], Duration::from_secs(600)) else { panic!("the PNG is asked for") }; + assert!(work().is_none()); } } } diff --git a/apps/vectorcraft/src/linux_screen_color.rs b/apps/vectorcraft/src/linux_screen_color.rs index 0f46af19d8..cfb8d7d69f 100644 --- a/apps/vectorcraft/src/linux_screen_color.rs +++ b/apps/vectorcraft/src/linux_screen_color.rs @@ -4,7 +4,6 @@ //! parent is the window, named on that thread as for the portal's save dialog (`portal_save`). mod portal; -mod request; /// The portal's color sampler over the window `parent` holds; `ui` is woken when it answers. pub fn sampler(ui: egui::Context, parent: super::host_services::Parent) -> vectorcraft_ui_egui::screen_color::StartSampler { diff --git a/apps/vectorcraft/src/linux_screen_color/portal.rs b/apps/vectorcraft/src/linux_screen_color/portal.rs index b7518e1ce3..21bcb34da5 100644 --- a/apps/vectorcraft/src/linux_screen_color/portal.rs +++ b/apps/vectorcraft/src/linux_screen_color/portal.rs @@ -61,9 +61,9 @@ pub(super) fn connect(builder: zbus::Result Result, Failure> { const DESKTOP: &str = "org.freedesktop.portal.Desktop"; - let token = super::request::token("vectorcraft_color").map_err(Failure::Failed)?; + let token = crate::portal_request::token("vectorcraft_color").map_err(Failure::Failed)?; // Made before the call: a portal can send its answer before the call returns. - let replies = super::request::Responses::new(conn).map_err(Failure::Failed)?; + let replies = crate::portal_request::Responses::new(conn).map_err(Failure::Failed)?; let proxy = Proxy::new(conn, DESKTOP, "/org/freedesktop/portal/desktop", "org.freedesktop.portal.Screenshot") .map_err(|e| Failure::Failed(e.to_string()))?; let options = HashMap::from([("handle_token", Value::from(token.as_str()))]); @@ -106,6 +106,7 @@ fn answer(code: u32, results: &HashMap) -> Result HashMap { HashMap::from([("color".into(), OwnedValue::try_from(Value::from(rgb)).unwrap())]) @@ -186,35 +187,6 @@ mod tests { } } - /// A session bus of its own (`dbus-daemon`), `None` when there is none to run. - fn private_bus() -> Option<(Daemon, String)> { - use std::io::BufRead as _; - let spawning = crate::spawning(); - let daemon = std::process::Command::new("dbus-daemon") - .args(["--session", "--nofork", "--print-address=1"]) - .stdout(std::process::Stdio::piped()) - .spawn(); - drop(spawning); - let Ok(daemon) = daemon else { - eprintln!("no dbus-daemon: skipped"); - return None; - }; - let mut daemon = Daemon(daemon); - let mut address = String::new(); - std::io::BufReader::new(daemon.0.stdout.take().unwrap()).read_line(&mut address).unwrap(); - Some((daemon, address.trim().to_string())) - } - - /// Stops the private bus when the test ends, unwinding included. - struct Daemon(std::process::Child); - - impl Drop for Daemon { - fn drop(&mut self) { - let _ = self.0.kill(); - let _ = self.0.wait(); - } - } - /// The client's connection to the private bus at `address`, made as the sampler makes its own. fn client(address: &str) -> Connection { connect(zbus::blocking::connection::Builder::address(address)).unwrap() diff --git a/apps/vectorcraft/src/linux_screen_color/request.rs b/apps/vectorcraft/src/linux_screen_color/request.rs deleted file mode 100644 index f442b840a3..0000000000 --- a/apps/vectorcraft/src/linux_screen_color/request.rs +++ /dev/null @@ -1,127 +0,0 @@ -//! The answer to the color sampler's XDG desktop portal request -//! (). -//! The wait ends with the request's `Response`, or with an error when the portal leaves the bus -//! first. - -use std::io::Read as _; - -use futures_lite::{StreamExt as _, future}; -use zbus::blocking::{Connection, MessageIterator}; -use zbus::zvariant::OwnedObjectPath; - -const DESKTOP: &str = "org.freedesktop.portal.Desktop"; - -/// A request token: `prefix`, then 128 bits from the operating system's random device, so the -/// token is unique and can't be guessed, as the Request documentation asks. -pub(super) fn token(prefix: &str) -> Result { - let mut bytes = [0; 16]; - std::fs::File::open("/dev/urandom") - .and_then(|mut file| file.read_exact(&mut bytes)) - .map_err(|e| format!("could not create a portal request token: {e}"))?; - let random: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect(); - Ok(format!("{prefix}_{random}")) -} - -/// Subscriptions made before a portal method call, on every request path: a portal older than -/// version 0.9 ignores `handle_token` and answers on the request path it returns, and its answer -/// can come before the call's reply. Each stream keeps every signal from the time it is made. -pub(super) struct Responses { - replies: MessageIterator, - owners: MessageIterator, -} - -impl Responses { - pub(super) fn new(conn: &Connection) -> Result { - let reply_rule = zbus::MatchRule::builder() - .msg_type(zbus::message::Type::Signal) - .sender(DESKTOP) - .and_then(|b| b.interface("org.freedesktop.portal.Request")) - .and_then(|b| b.member("Response")) - .map_err(|e| e.to_string())? - .build(); - let owner_rule = zbus::MatchRule::builder() - .msg_type(zbus::message::Type::Signal) - .sender("org.freedesktop.DBus") - .and_then(|b| b.path("/org/freedesktop/DBus")) - .and_then(|b| b.interface("org.freedesktop.DBus")) - .and_then(|b| b.member("NameOwnerChanged")) - .and_then(|b| b.arg(0, DESKTOP)) - .map_err(|e| e.to_string())? - .build(); - Ok(Self { - replies: MessageIterator::for_match_rule(reply_rule, conn, None).map_err(|e| e.to_string())?, - owners: MessageIterator::for_match_rule(owner_rule, conn, None).map_err(|e| e.to_string())?, - }) - } - - /// The `Response` on the request path `call` returned, from the connection that returned it. - /// An error when that connection leaves the bus first, or the bus connection closes. - pub(super) fn wait(self, call: &zbus::Message) -> Result { - enum Event { - Reply(Option>), - Owner(Option>), - } - let handle: OwnedObjectPath = call.body().deserialize().map_err(|e| e.to_string())?; - let portal = call.header().sender().map(|s| s.as_str().to_string()).ok_or("the portal answered without a sender")?; - let mut replies = self.replies.into_inner(); - let mut owners = self.owners.into_inner(); - future::block_on(async { - loop { - let event = future::or(async { Event::Reply(replies.next().await) }, async { Event::Owner(owners.next().await) }).await; - match event { - Event::Reply(reply) => { - let reply = reply.ok_or("the portal closed without an answer")?.map_err(|e| e.to_string())?; - let header = reply.header(); - if header.path().map(|p| p.as_str()) == Some(handle.as_str()) && header.sender().map(|s| s.as_str()) == Some(portal.as_str()) - { - return Ok(reply); - } - } - Event::Owner(message) => { - let message = message.ok_or("the portal connection closed")?.map_err(|e| e.to_string())?; - if owner_disappeared(&message, &portal)? { - return Err("the desktop portal disappeared while waiting for its answer".into()); - } - } - } - } - }) - } -} - -/// Whether `message` is the bus's `NameOwnerChanged` saying that the connection `portal` no longer -/// owns the portal's name. The bus itself must send it: another connection can't end the wait. -fn owner_disappeared(message: &zbus::Message, portal: &str) -> Result { - if message.header().sender().map(|s| s.as_str()) != Some("org.freedesktop.DBus") { - return Ok(false); - } - let (name, old, new): (String, String, String) = message.body().deserialize().map_err(|e| e.to_string())?; - Ok(name == DESKTOP && old == portal && new != portal) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn only_the_bus_can_report_portal_owner_loss() { - let changed = |sender, name, old, new| { - zbus::Message::signal("/org/freedesktop/DBus", "org.freedesktop.DBus", "NameOwnerChanged") - .unwrap() - .sender(sender) - .unwrap() - .build(&(name, old, new)) - .unwrap() - }; - let forged = changed(":1.42", DESKTOP, ":1.7", ""); - assert!(!owner_disappeared(&forged, ":1.7").unwrap()); - let real = changed("org.freedesktop.DBus", DESKTOP, ":1.7", ""); - assert!(owner_disappeared(&real, ":1.7").unwrap()); - let other = changed("org.freedesktop.DBus", "org.example.Other", ":1.7", ""); - assert!(!owner_disappeared(&other, ":1.7").unwrap()); - let old = changed("org.freedesktop.DBus", DESKTOP, ":1.8", ""); - assert!(!owner_disappeared(&old, ":1.7").unwrap()); - let acquired = changed("org.freedesktop.DBus", DESKTOP, "", ":1.7"); - assert!(!owner_disappeared(&acquired, ":1.7").unwrap()); - } -} diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index 33e962c0aa..cd3ea7cd36 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -53,6 +53,8 @@ mod mac_tablet; mod mac_window; #[cfg(target_os = "macos")] mod open_documents; +#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] +mod portal_request; #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd", test))] mod portal_save; mod prefs_dir; diff --git a/apps/vectorcraft/src/portal_request.rs b/apps/vectorcraft/src/portal_request.rs new file mode 100644 index 0000000000..da4cb9ad23 --- /dev/null +++ b/apps/vectorcraft/src/portal_request.rs @@ -0,0 +1,231 @@ +//! Linux and the BSDs: the answer to an XDG desktop portal request +//! (), +//! for the save dialog (`portal_save`) and, on Linux, the screen color sampler +//! (`linux_screen_color`). The wait ends with the request's `Response`, or with an error when the +//! portal leaves the bus first. + +use futures_lite::{StreamExt as _, future}; +use zbus::blocking::{Connection, MessageIterator}; +use zbus::zvariant::OwnedObjectPath; + +const DESKTOP: &str = "org.freedesktop.portal.Desktop"; + +/// A request token: `prefix`, then 128 bits from the operating system's random device, so the +/// token is unique and can't be guessed, as the Request documentation asks. +#[cfg(target_os = "linux")] +pub(crate) fn token(prefix: &str) -> Result { + use std::io::Read as _; + + let mut bytes = [0; 16]; + std::fs::File::open("/dev/urandom") + .and_then(|mut file| file.read_exact(&mut bytes)) + .map_err(|e| format!("could not create a portal request token: {e}"))?; + let random: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect(); + Ok(format!("{prefix}_{random}")) +} + +/// Subscriptions made before a portal method call, on every request path: a portal older than +/// version 0.9 ignores `handle_token` and answers on the request path it returns, and its answer +/// can come before the call's reply. Each stream keeps every signal from the time it is made. +pub(crate) struct Responses { + replies: MessageIterator, + owners: MessageIterator, +} + +impl Responses { + pub(crate) fn new(conn: &Connection) -> Result { + let reply_rule = zbus::MatchRule::builder() + .msg_type(zbus::message::Type::Signal) + .sender(DESKTOP) + .and_then(|b| b.interface("org.freedesktop.portal.Request")) + .and_then(|b| b.member("Response")) + .map_err(|e| e.to_string())? + .build(); + let owner_rule = zbus::MatchRule::builder() + .msg_type(zbus::message::Type::Signal) + .sender("org.freedesktop.DBus") + .and_then(|b| b.path("/org/freedesktop/DBus")) + .and_then(|b| b.interface("org.freedesktop.DBus")) + .and_then(|b| b.member("NameOwnerChanged")) + .and_then(|b| b.arg(0, DESKTOP)) + .map_err(|e| e.to_string())? + .build(); + Ok(Self { + replies: MessageIterator::for_match_rule(reply_rule, conn, None).map_err(|e| e.to_string())?, + owners: MessageIterator::for_match_rule(owner_rule, conn, None).map_err(|e| e.to_string())?, + }) + } + + /// The `Response` on the request path `call` returned, from the connection that returned it. + /// An error when that connection leaves the bus first, or the bus connection closes. A + /// `Response` the portal sent before it left is still the answer. + pub(crate) fn wait(self, call: &zbus::Message) -> Result { + enum Event { + Reply(Option>), + Owner(Option>), + } + let handle: OwnedObjectPath = call.body().deserialize().map_err(|e| e.to_string())?; + let portal = call.header().sender().map(|s| s.as_str().to_string()).ok_or("the portal answered without a sender")?; + let answers = |reply: &zbus::Message| { + let header = reply.header(); + header.path().map(|p| p.as_str()) == Some(handle.as_str()) && header.sender().map(|s| s.as_str()) == Some(portal.as_str()) + }; + let mut replies = self.replies.into_inner(); + let mut owners = self.owners.into_inner(); + future::block_on(async { + loop { + let event = future::or(async { Event::Owner(owners.next().await) }, async { Event::Reply(replies.next().await) }).await; + match event { + Event::Reply(reply) => { + let reply = reply.ok_or("the portal closed without an answer")?.map_err(|e| e.to_string())?; + if answers(&reply) { + return Ok(reply); + } + } + Event::Owner(message) => { + let message = message.ok_or("the portal connection closed")?.map_err(|e| e.to_string())?; + if owner_disappeared(&message, &portal)? { + // zbus puts each message in every matching stream before it reads the + // next one, so a `Response` that came before the bus's report is + // already queued: it is still the answer. + while let Some(Some(reply)) = future::poll_once(replies.next()).await { + if let Ok(reply) = reply + && answers(&reply) + { + return Ok(reply); + } + } + return Err("the desktop portal disappeared while waiting for its answer".into()); + } + } + } + } + }) + } +} + +/// Whether `message` is the bus's `NameOwnerChanged` saying that the connection `portal` no longer +/// owns the portal's name. The bus itself must send it: another connection can't end the wait. +fn owner_disappeared(message: &zbus::Message, portal: &str) -> Result { + if message.header().sender().map(|s| s.as_str()) != Some("org.freedesktop.DBus") { + return Ok(false); + } + let (name, old, new): (String, String, String) = message.body().deserialize().map_err(|e| e.to_string())?; + Ok(name == DESKTOP && old == portal && new != portal) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_the_bus_can_report_portal_owner_loss() { + let changed = |sender, name, old, new| { + zbus::Message::signal("/org/freedesktop/DBus", "org.freedesktop.DBus", "NameOwnerChanged") + .unwrap() + .sender(sender) + .unwrap() + .build(&(name, old, new)) + .unwrap() + }; + let forged = changed(":1.42", DESKTOP, ":1.7", ""); + assert!(!owner_disappeared(&forged, ":1.7").unwrap()); + let real = changed("org.freedesktop.DBus", DESKTOP, ":1.7", ""); + assert!(owner_disappeared(&real, ":1.7").unwrap()); + let other = changed("org.freedesktop.DBus", "org.example.Other", ":1.7", ""); + assert!(!owner_disappeared(&other, ":1.7").unwrap()); + let old = changed("org.freedesktop.DBus", DESKTOP, ":1.8", ""); + assert!(!owner_disappeared(&old, ":1.7").unwrap()); + let acquired = changed("org.freedesktop.DBus", DESKTOP, "", ":1.7"); + assert!(!owner_disappeared(&acquired, ":1.7").unwrap()); + } + + /// Through a real D-Bus: when the bus has reported the portal gone, a `Response` the portal sent + /// before it left is still the answer; without one the wait ends with an error. + #[test] + fn a_queued_answer_wins_over_the_portal_leaving() { + use std::collections::HashMap; + + use zbus::blocking::connection::Builder; + use zbus::zvariant::OwnedValue; + + for answered in [true, false] { + let Some((_daemon, address)) = test_bus::private_bus() else { return }; + let address = address.as_str(); + let portal = Builder::address(address).unwrap().name(DESKTOP).unwrap().build().unwrap(); + let unique = portal.unique_name().unwrap().to_string(); + let client = Builder::address(address).unwrap().build().unwrap(); + let responses = Responses::new(&client).unwrap(); + // zbus puts each message in every matching stream before it reads the next one + // (`src/connection/socket_reader.rs`), so once this stream has the bus's report, + // `responses` holds the `Response` sent before it. + let gone_rule = zbus::MatchRule::builder() + .msg_type(zbus::message::Type::Signal) + .sender("org.freedesktop.DBus") + .unwrap() + .member("NameOwnerChanged") + .unwrap() + .arg(0, DESKTOP) + .unwrap() + .build(); + let gone = MessageIterator::for_match_rule(gone_rule, &client, None).unwrap(); + let path = "/org/freedesktop/portal/desktop/request/test/t1"; + if answered { + let results = HashMap::::new(); + portal.emit_signal(None::<&str>, path, "org.freedesktop.portal.Request", "Response", &(0_u32, results)).unwrap(); + } + portal.close().unwrap(); + // On a thread of its own, so a report that never comes fails the test instead of + // hanging it. + let (seen, report) = std::sync::mpsc::channel(); + let left = unique.clone(); + std::thread::spawn(move || { + let mut gone = gone; + let _ = seen.send(gone.any(|m| m.is_ok_and(|m| owner_disappeared(&m, &left).unwrap_or(false)))); + }); + assert_eq!(report.recv_timeout(std::time::Duration::from_secs(30)), Ok(true), "the bus did not report the portal gone"); + // The call's reply as `wait` reads it: the request path, from the portal's connection. + let call = zbus::Message::signal("/", "org.example.Test", "Reply") + .unwrap() + .sender(unique.as_str()) + .unwrap() + .build(&OwnedObjectPath::try_from(path).unwrap()) + .unwrap(); + let waited = responses.wait(&call); + assert_eq!(waited.is_ok(), answered, "{waited:?}"); + } + } +} + +/// The private session bus that the D-Bus tests of the portal requests run on. +#[cfg(test)] +pub(crate) mod test_bus { + /// A session bus of its own (`dbus-daemon`), `None` when there is none to run. + pub(crate) fn private_bus() -> Option<(Daemon, String)> { + use std::io::BufRead as _; + let spawning = crate::spawning(); + let daemon = std::process::Command::new("dbus-daemon") + .args(["--session", "--nofork", "--print-address=1"]) + .stdout(std::process::Stdio::piped()) + .spawn(); + drop(spawning); + let Ok(daemon) = daemon else { + eprintln!("no dbus-daemon: skipped"); + return None; + }; + let mut daemon = Daemon(daemon); + let mut address = String::new(); + std::io::BufReader::new(daemon.0.stdout.take().unwrap()).read_line(&mut address).unwrap(); + Some((daemon, address.trim().to_string())) + } + + /// Stops the private bus when the test ends, unwinding included. + pub(crate) struct Daemon(std::process::Child); + + impl Drop for Daemon { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } + } +} diff --git a/apps/vectorcraft/src/portal_save.rs b/apps/vectorcraft/src/portal_save.rs index a9bf5d1009..6d1a8734b2 100644 --- a/apps/vectorcraft/src/portal_save.rs +++ b/apps/vectorcraft/src/portal_save.rs @@ -8,6 +8,7 @@ //! ([`vectorcraft_ui_egui::picks::PickAnswer`]); the app gives the name that type's extension. //! rfd shows the dialog when the portal can't (no session bus, no file chooser), with zenity as its //! own fallback. PhotoCraft's `portal_save.rs` (storytold/photocraft#6151) makes the same call. +//! rfd also shows the dialog when the portal leaves the bus before it answers. //! //! The dialog's parent is the window: `x11:` on X11, and on Wayland (Linux) a handle //! from the compositor's xdg-foreign protocol, as rfd names it (its `window_identifier`). @@ -183,37 +184,18 @@ pub fn pick(pick: &FilePick, window: Option<&winit::window::Window>) -> Option Result, String> { use std::sync::atomic::{AtomicU32, Ordering}; - use zbus::blocking::{MessageIterator, Proxy}; - use zbus::zvariant::OwnedObjectPath; + use zbus::blocking::Proxy; const DESKTOP: &str = "org.freedesktop.portal.Desktop"; - const REQUEST: &str = "org.freedesktop.portal.Request"; static NEXT: AtomicU32 = AtomicU32::new(0); let token = format!("vectorcraft_save_{}_{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)); - // Listen before asking, on every request path: a portal older than version 0.9 ignores - // `handle_token` and answers on the request path it returns, and its answer can come before - // the call's reply. The stream keeps every `Response` from the time it is made. - let rule = zbus::MatchRule::builder() - .msg_type(zbus::message::Type::Signal) - .sender(DESKTOP) - .and_then(|b| b.interface(REQUEST)) - .and_then(|b| b.member("Response")) - .map_err(|e| e.to_string())? - .build(); - let responses = MessageIterator::for_match_rule(rule, conn, None).map_err(|e| e.to_string())?; + // Made before the call: a portal can send its answer before the call returns, and a portal + // that leaves the bus while its dialog is open ends the wait. + let responses = crate::portal_request::Responses::new(conn)?; let chooser = Proxy::new(conn, DESKTOP, "/org/freedesktop/portal/desktop", "org.freedesktop.portal.FileChooser").map_err(|e| e.to_string())?; // The title is empty, as rfd sends it for a save. let call = chooser.call_method("SaveFile", &(request.parent.as_str(), "", options(request, &token))).map_err(|e| e.to_string())?; - let handle: OwnedObjectPath = call.body().deserialize().map_err(|e| e.to_string())?; - // The answer is the `Response` on the path returned, from the connection that returned it. - let portal = call.header().sender().map(|s| s.as_str().to_string()); - let reply = responses - .filter_map(Result::ok) - .find(|m| { - let header = m.header(); - header.path().map(|p| p.as_str()) == Some(handle.as_str()) && header.sender().map(|s| s.as_str()) == portal.as_deref() - }) - .ok_or("the save dialog closed without an answer")?; + let reply = responses.wait(&call)?; let (code, results): (u32, HashMap) = reply.body().deserialize().map_err(|e| e.to_string())?; answer(code, &results) } @@ -495,26 +477,22 @@ mod tests { Old, /// As `Old`, with the `Response` sent before the reply that names its path. OldEarly, + /// As `Current`, but it leaves the bus 300 ms after its reply without a `Response`, as a + /// portal that exits while its dialog is open. + Exits, + /// Leaves the bus right after its reply, without a `Response`. + ExitsAtOnce, + /// Sends its `Response` right after its reply, then leaves the bus. + AnswersAndExits, } /// A session bus of its own (`dbus-daemon`) with a mock `org.freedesktop.portal.FileChooser` /// that answers `SaveFile` from `script` as `portal` says, as PhotoCraft's portal tests run it. /// `None` when there is no `dbus-daemon` to run. #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] - fn mock_portal(script: Script, portal: Portal) -> Option<(zbus::blocking::Connection, Seen, std::process::Child)> { - use std::io::BufRead as _; - + fn mock_portal(script: Script, portal: Portal) -> Option<(zbus::blocking::Connection, Seen, crate::portal_request::test_bus::Daemon)> { use zbus::zvariant::OwnedObjectPath; - let spawning = crate::spawning(); - let daemon = std::process::Command::new("dbus-daemon") - .args(["--session", "--nofork", "--print-address=1"]) - .stdout(std::process::Stdio::piped()) - .spawn(); - drop(spawning); - let mut daemon = daemon.ok()?; - let mut address = String::new(); - std::io::BufReader::new(daemon.stdout.take()?).read_line(&mut address).ok()?; - let address = address.trim().to_string(); + let (daemon, address) = crate::portal_request::test_bus::private_bus()?; let server = zbus::blocking::connection::Builder::address(address.as_str()).ok()?.name("org.freedesktop.portal.Desktop").ok()?.build().ok()?; let seen = Seen::default(); @@ -539,8 +517,8 @@ mod tests { }); let Some(sender) = header.sender().map(|s| s.as_str().trim_start_matches(':').replace('.', "_")) else { break }; let token = match portal { - Portal::Current => text("handle_token").unwrap_or_default(), Portal::Old | Portal::OldEarly => format!("old{}", calls.unwrap_or_default()), + Portal::Current | Portal::Exits | Portal::ExitsAtOnce | Portal::AnswersAndExits => text("handle_token").unwrap_or_default(), }; let path = format!("/org/freedesktop/portal/desktop/request/{sender}/{token}"); let Ok(handle) = OwnedObjectPath::try_from(path.as_str()) else { break }; @@ -558,14 +536,22 @@ mod tests { if server.reply(&header, &handle).is_err() { break; } - if portal == Portal::Old { + if matches!(portal, Portal::Old | Portal::Exits) { // As a person answers the dialog: after the caller has the path returned. std::thread::sleep(std::time::Duration::from_millis(300)); } + if matches!(portal, Portal::Exits | Portal::ExitsAtOnce) { + break; + } if portal != Portal::OldEarly && respond().is_err() { break; } + if portal == Portal::AnswersAndExits { + break; + } } + // The portal leaves the bus: the bus sends `NameOwnerChanged` for its name. + let _ = server.close(); }); let client = zbus::blocking::connection::Builder::address(address.as_str()).ok()?.build().ok()?; Some((client, seen, daemon)) @@ -589,7 +575,7 @@ mod tests { #[test] fn the_portal_is_asked_on_the_first_file_type_and_answers_the_one_picked() { let script = vec![(0, Some(("file:///home/me/Art/poster", "PDF-compatible .ai"))), (1, None)]; - let Some((conn, seen, mut daemon)) = mock_portal(script, Portal::Current) else { + let Some((conn, seen, _daemon)) = mock_portal(script, Portal::Current) else { eprintln!("no dbus-daemon: skipped"); return; }; @@ -599,7 +585,6 @@ mod tests { assert_eq!(save_within(&conn, &request), Ok(None)); let seen = seen.lock().map(|s| s.clone()).unwrap_or_default(); assert_eq!(seen.first(), Some(&(Some("Untitled-1.vectorcraft".to_string()), Some(request.filters[0].0.clone())))); - let _ = daemon.kill(); } /// A portal older than 0.9 answers on the request path it returns, and the answer is awaited @@ -607,13 +592,12 @@ mod tests { #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] #[test] fn the_answer_is_awaited_on_the_path_the_portal_returns() { - let Some((conn, _seen, mut daemon)) = mock_portal(vec![(0, Some(("file:///tmp/card", "SVG")))], Portal::Old) else { + let Some((conn, _seen, _daemon)) = mock_portal(vec![(0, Some(("file:///tmp/card", "SVG")))], Portal::Old) else { eprintln!("no dbus-daemon: skipped"); return; }; let request = request(); assert_eq!(pick_answer(save_within(&conn, &request).unwrap(), &request), ["/tmp/card", "svg"]); - let _ = daemon.kill(); } /// A portal older than 0.9 can answer before its reply names the request path: the answer is @@ -622,14 +606,41 @@ mod tests { #[test] fn an_answer_that_comes_before_the_path_is_kept() { let script = vec![(0, Some(("file:///tmp/card", "SVG"))), (1, None)]; - let Some((conn, _seen, mut daemon)) = mock_portal(script, Portal::OldEarly) else { + let Some((conn, _seen, _daemon)) = mock_portal(script, Portal::OldEarly) else { eprintln!("no dbus-daemon: skipped"); return; }; let request = request(); assert_eq!(pick_answer(save_within(&conn, &request).unwrap(), &request), ["/tmp/card", "svg"]); assert_eq!(save_within(&conn, &request), Ok(None)); - let _ = daemon.kill(); + } + + /// A portal that leaves the bus after its reply without answering, while its dialog is open or + /// at once, ends the wait with an error, and rfd shows the dialog. + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + #[test] + fn a_portal_that_exits_during_the_dialog_ends_the_wait() { + for portal in [Portal::Exits, Portal::ExitsAtOnce] { + let Some((conn, _seen, _daemon)) = mock_portal(vec![(0, Some(("file:///tmp/card", "SVG")))], portal) else { + eprintln!("no dbus-daemon: skipped"); + return; + }; + assert_eq!(save_within(&conn, &request()), Err("the desktop portal disappeared while waiting for its answer".to_string())); + } + } + + /// A portal that answers and then leaves the bus: the save reads the answer. Whether the answer + /// or the bus's report comes first depends on timing here; `portal_request`'s + /// `a_queued_answer_wins_over_the_portal_leaving` queues both before the wait. + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + #[test] + fn an_answer_sent_just_before_the_portal_exits_is_kept() { + let Some((conn, _seen, _daemon)) = mock_portal(vec![(0, Some(("file:///tmp/card", "SVG")))], Portal::AnswersAndExits) else { + eprintln!("no dbus-daemon: skipped"); + return; + }; + let request = request(); + assert_eq!(pick_answer(save_within(&conn, &request).unwrap(), &request), ["/tmp/card", "svg"]); } /// The labels go to the dialog in the interface's language, which is how the answer is matched. diff --git a/crates/color/src/cms.rs b/crates/color/src/cms.rs index 46dcdb52ba..c5e5bc5bea 100644 --- a/crates/color/src/cms.rs +++ b/crates/color/src/cms.rs @@ -531,7 +531,7 @@ impl Cms { } } - /// Gamut warning: can this colour be printed in the working CMYK space? + /// Gamut warning: can this color be printed in this context's CMYK space? pub fn out_of_gamut(&self, c: &Color) -> bool { self.gamut_error(c) > GAMUT_THRESHOLD } diff --git a/crates/color/src/gradient.rs b/crates/color/src/gradient.rs index e49478eab7..54cb50c197 100644 --- a/crates/color/src/gradient.rs +++ b/crates/color/src/gradient.rs @@ -65,24 +65,62 @@ pub enum GradientMethod { /// Mixed in a perceptual colour space (OKLab), so the steps look even to the eye: blue to /// yellow passes through a light blue-grey rather than a dull mid grey. Perceptual, + /// Mixed around the hue wheel, clockwise as the color wheels draw it: the hue angle falls + /// from each stop to the next (red, magenta, blue, cyan, green, yellow, red), and saturation + /// and brightness change evenly ([`hue_mix`]). + HueClockwise, + /// Mixed around the hue wheel the other way: the hue angle rises from each stop to the next + /// (red, yellow, green, cyan, blue, magenta, red). + HueCounterclockwise, } impl GradientMethod { - /// Parse a method name (`classic`, `perceptual`; any case). + /// Every method, in the order the Gradient panel lists them. + pub const ALL: [GradientMethod; 4] = [Self::Classic, Self::Perceptual, Self::HueClockwise, Self::HueCounterclockwise]; + /// Parse a method name (`classic`, `perceptual`, `hue-clockwise`, `hue-counterclockwise`; + /// any case, and the hyphen may be a space or an underscore, or left out). Any other text, + /// one with a separator elsewhere included, is `None`. pub fn parse(s: &str) -> Option { - [Self::Classic, Self::Perceptual].into_iter().find(|m| m.label().eq_ignore_ascii_case(s)) + let name = s.to_ascii_lowercase(); + Self::ALL.into_iter().find(|m| ["-", " ", "_", ""].iter().any(|sep| m.id().replace('-', sep) == name)) } pub fn label(self) -> &'static str { match self { Self::Classic => "Classic", Self::Perceptual => "Perceptual", + Self::HueClockwise => "Hue Clockwise", + Self::HueCounterclockwise => "Hue Counterclockwise", + } + } + /// The method's name in command params (`classic`, `perceptual`, `hue-clockwise`, + /// `hue-counterclockwise`). + pub fn id(self) -> &'static str { + match self { + Self::Classic => "classic", + Self::Perceptual => "perceptual", + Self::HueClockwise => "hue-clockwise", + Self::HueCounterclockwise => "hue-counterclockwise", } } pub fn is_classic(&self) -> bool { *self == Self::Classic } - /// `a` and `b` mixed at `t` (0..1): in display RGB (Classic), or in OKLab (Perceptual: an - /// RGB colour between the two). + /// Does it mix around the hue wheel (Hue Clockwise or Hue Counterclockwise)? The colors + /// between two stops then are not mixes of the stops' inks. + pub fn is_hue(&self) -> bool { + matches!(self, Self::HueClockwise | Self::HueCounterclockwise) + } + /// The method that mixes `b` to `a` through the colors this one mixes `a` to `b` through: a + /// hue method turned the other way, Classic and Perceptual as they are. + pub fn mirrored(self) -> Self { + match self { + Self::HueClockwise => Self::HueCounterclockwise, + Self::HueCounterclockwise => Self::HueClockwise, + m => m, + } + } + /// `a` and `b` mixed at `t` (0..1): in display RGB (Classic), in OKLab (Perceptual: an + /// RGB colour between the two), or around the hue wheel ([`hue_mix`]: an RGB colour). pub fn mix(self, a: &Color, b: &Color, t: f32) -> Color { match self { Self::Classic => Color::lerp(a, b, t), @@ -93,10 +131,68 @@ impl GradientMethod { let c = |v: f64| if v.is_finite() { v.clamp(0.0, 1.0) as f32 } else { 0.0 }; Color::rgb(c(r), c(g), c(bl)) } + Self::HueClockwise => hue_mix(a, b, t, false), + Self::HueCounterclockwise => hue_mix(a, b, t, true), } } } +/// The brightness (0..1) at or below which a color is black for [`hue_mix`], and the spread +/// between its largest and smallest RGB numbers (saturation × brightness) at or below which it +/// has no hue of its own: under half a color level. +const NO_HUE: f32 = 0.4 / 255.0; + +/// The hue difference (degrees) that moves an RGB number by half a color level in a color whose +/// largest and smallest RGB numbers are 1 apart; a color with a smaller spread takes +/// proportionally more degrees. [`hue_mix`] counts two hues closer than this as one hue. +const SAME_HUE: f32 = 60.0 * 0.5 / 255.0; + +/// `a` and `b` mixed at `t` (0..1) around the hue wheel, as display RGB: hue (degrees), +/// saturation and brightness each change evenly from `a`'s to `b`'s. The hue angle only rises +/// (`rising`) or only falls, by the fixed-direction rules of +/// , and two equal hues stay where they are. +/// Two hues that differ by less than half a color level ([`SAME_HUE`]) count as equal and take the +/// short way, so a color and a tint or shade of it, whose computed hues differ by rounding, do +/// not turn the whole wheel. A color whose RGB numbers are less than half a color level apart +/// ([`NO_HUE`]) has no hue and takes the other color's; black has no saturation either and takes +/// the other color's too. Two colors without a hue mix as grays. A `t` that is not a number +/// gives `a`. +pub fn hue_mix(a: &Color, b: &Color, t: f32, rising: bool) -> Color { + let t = if t.is_nan() { 0.0 } else { t.clamp(0.0, 1.0) }; + let ([mut h0, mut s0, v0], [mut h1, mut s1, v1]) = (a.to_hsb(), b.to_hsb()); + let (black0, black1) = (v0 <= NO_HUE, v1 <= NO_HUE); + // The spread between each color's own largest and smallest RGB numbers. + let (spread0, spread1) = (s0 * v0, s1 * v1); + // Black takes the other color's saturation, so it darkens that color rather than graying it. + if black0 && !black1 { + s0 = s1; + } else if black1 && !black0 { + s1 = s0; + } + let (gray0, gray1) = (black0 || spread0 <= NO_HUE, black1 || spread1 <= NO_HUE); + match (gray0, gray1) { + (true, _) => h0 = h1, + (false, true) => h1 = h0, + (false, false) => { + // The short way from the first hue to the second, -180..180. + let short = (h1 - h0 + 180.0).rem_euclid(360.0) - 180.0; + h1 = if short.abs() * spread0.min(spread1) <= SAME_HUE { + h0 + short + } else if rising { + h0 + short.rem_euclid(360.0) + } else { + h0 + short.rem_euclid(360.0) - 360.0 + }; + } + } + let at = |p: f32, q: f32| p + (q - p) * t; + let (h, s, v) = (at(h0, h1), at(s0, s1), at(v0, v1)); + if !(h.is_finite() && s.is_finite() && v.is_finite()) { + return Color::rgb(0.0, 0.0, 0.0); + } + Color::from_hsb(h.rem_euclid(360.0), s.clamp(0.0, 1.0), v.clamp(0.0, 1.0)) +} + /// What a linear, radial, conic or diamond gradient paints past the ends of its stops (the /// Gradient panel's Spread). With Repeat and Reflect, the stops run [`Gradient::repeats`] times /// along the vector (around the circle, for a conic), and keep going past both of its ends. @@ -192,10 +288,11 @@ const MAX_INK_TINTS: usize = 4096; const INK_MIX_STEPS: u32 = 64; /// The mix positions (0..1, after `v0`, before `v1`) between which display RGB mixed linearly -/// stays within [`PERCEPTUAL_TOLERANCE`] of the perceptual mix of `a` and `b`: the span halved -/// where a straight line strays, at most [`PERCEPTUAL_DEPTH`] times, in order. -fn perceptual_steps(a: &Color, b: &Color, (v0, v1): (f32, f32), depth: u32, out: &mut Vec) { - let at = |v: f32| GradientMethod::Perceptual.mix(a, b, v).to_rgb(); +/// stays within [`PERCEPTUAL_TOLERANCE`] of `method`'s mix of `a` and `b` (Perceptual, or around +/// the hue wheel): the span halved where a straight line strays, at most [`PERCEPTUAL_DEPTH`] +/// times, in order. +fn perceptual_steps(method: GradientMethod, a: &Color, b: &Color, (v0, v1): (f32, f32), depth: u32, out: &mut Vec) { + let at = |v: f32| method.mix(a, b, v).to_rgb(); let (c0, c1) = (at(v0), at(v1)); let stray = [0.25, 0.5, 0.75] .into_iter() @@ -206,19 +303,20 @@ fn perceptual_steps(a: &Color, b: &Color, (v0, v1): (f32, f32), depth: u32, out: .fold(0.0, f32::max); if depth < PERCEPTUAL_DEPTH && stray > PERCEPTUAL_TOLERANCE { let m = (v0 + v1) / 2.0; - perceptual_steps(a, b, (v0, m), depth + 1, out); + perceptual_steps(method, a, b, (v0, m), depth + 1, out); out.push(m); - perceptual_steps(a, b, (m, v1), depth + 1, out); + perceptual_steps(method, a, b, (m, v1), depth + 1, out); } } -/// The mix positions (`v`, 0..1) of the stops a Perceptual gradient's curve has between stops `a` -/// and `b`, in order: [`perceptual_steps`] on either side of the midpoint, and the midpoint (½). -fn perceptual_mixes(a: &GradientStop, b: &GradientStop) -> Vec { +/// The mix positions (`v`, 0..1) of the stops the curve of a gradient mixed by `method` +/// (Perceptual, or around the hue wheel) has between stops `a` and `b`, in order: +/// [`perceptual_steps`] on either side of the midpoint, and the midpoint (½). +fn perceptual_mixes(method: GradientMethod, a: &GradientStop, b: &GradientStop) -> Vec { let mut vs = Vec::new(); - perceptual_steps(&a.color, &b.color, (0.0, 0.5), 1, &mut vs); + perceptual_steps(method, &a.color, &b.color, (0.0, 0.5), 1, &mut vs); vs.push(0.5); - perceptual_steps(&a.color, &b.color, (0.5, 1.0), 1, &mut vs); + perceptual_steps(method, &a.color, &b.color, (0.5, 1.0), 1, &mut vs); vs } @@ -512,10 +610,11 @@ impl Gradient { }; (t, c, o, Some(s.midpoint), None) }); - // Perceptual: stops along the mix (`v`) where a straight line would stray from it, the - // midpoint (v = ½) among them, placed through the midpoint as [`Self::sample`] maps them. + // Perceptual and the hue methods: stops along the mix (`v`) where a straight line would + // stray from it, the midpoint (v = ½) among them, placed through the midpoint as + // [`Self::sample`] maps them. let perceptual = next.filter(|_| !self.method.is_classic()).map(|n| { - perceptual_mixes(s, n).into_iter().map(move |v| { + perceptual_mixes(self.method, s, n).into_iter().map(move |v| { let mid = v == 0.5; let t = curve_offset(s, n, v); let o = s.opacity + (n.opacity - s.opacity) * v; @@ -571,11 +670,12 @@ impl Gradient { /// position itself when the two colors' lightness differs by less than /// [`MIN_INK_LIGHTNESS_SPAN`], or when the display RGB mix's lightness turns back somewhere /// on the way from one color's lightness to the other's (checked at [`INK_MIX_STEPS`] even - /// steps), as from red to blue. `None` for a Classic gradient, and when the curve has more - /// than [`MAX_INK_TINTS`] stops ([`Self::fits_ink_tints`]). + /// steps), as from red to blue. `None` for a Classic gradient, for one mixed around the hue + /// wheel (its colors between two stops are not mixes of the stops' inks), and when the curve + /// has more than [`MAX_INK_TINTS`] stops ([`Self::fits_ink_tints`]). pub fn ink_mixes(&self) -> Option> { use crate::libraries::srgb_to_oklab; - if self.method.is_classic() || !self.fits_ink_tints() { + if self.method != GradientMethod::Perceptual || !self.fits_ink_tints() { return None; } let lightness = |c: &Color| srgb_to_oklab(c.to_rgb())[0]; @@ -592,7 +692,7 @@ impl Gradient { .collect::>() .windows(2) .all(|w| (w[1] - w[0]) * (l1 - l0) >= 0.0); - for v in perceptual_mixes(s, n) { + for v in perceptual_mixes(self.method, s, n) { let weight = if by_position { v } else { @@ -650,8 +750,10 @@ impl Gradient { Some(Ramp { stops }) } /// The same ramp the other way round: the stops in reverse order at mirrored offsets, each - /// segment's midpoint mirrored with it. + /// segment's midpoint mirrored with it, and a hue method turned the other way (red to blue + /// through magenta, reversed, is blue to red through magenta). pub fn reverse(&mut self) { + self.method = self.method.mirrored(); self.stops.reverse(); for i in 0..self.stops.len() { // A midpoint belongs to the segment after its stop: reversed, stop i's segment is the @@ -666,6 +768,13 @@ impl Gradient { pub fn sort(&mut self) { self.stops.sort_by(|a, b| a.offset.total_cmp(&b.offset)); } + /// The gradient's colors as a Classic gradient: its curve's stops ([`Self::expanded_stops`]) as + /// stops of their own, mixed in display RGB, within [`PERCEPTUAL_TOLERANCE`] of it. The stops + /// keep no swatch links, tints or process plates. + pub fn as_classic_curve(&self) -> Gradient { + let stops = self.expanded().map(|(t, color, opacity, _)| GradientStop { opacity, ..GradientStop::new(t, color) }).collect(); + Gradient { kind: self.kind, stops, dither: self.dither, method: GradientMethod::Classic, spread: self.spread, repeats: self.repeats } + } /// The part of the gradient from `from` to `to` (0..1, either way round) as a linear gradient /// of its own running 0 → 1: the same colours (midpoints become stops, as in /// [`Self::expanded_stops`]). One colour throughout when `from == to`. @@ -1261,8 +1370,9 @@ impl GradientPaint { } /// Is this gradient drawn as pixels rather than as a vector gradient when it paints a fill /// (`fill`) or a stroke (SVG and PDF draw such gradients as images): a freeform gradient, a - /// dithered fill (dither applies to fills only), or a Perceptual one (its colours don't mix - /// linearly between the stops, as SVG's and PDF's gradients do)? + /// dithered fill (dither applies to fills only), or a Perceptual one or one mixed around the + /// hue wheel (its colours don't mix linearly between the stops, as SVG's and PDF's gradients + /// do)? pub fn draws_as_pixels(&self, fill: bool) -> bool { self.gradient.kind == GradientKind::Freeform || (fill && self.gradient.dither) || !self.gradient.method.is_classic() } diff --git a/crates/color/src/gradient/spread.rs b/crates/color/src/gradient/spread.rs index 8f9933c40c..fa111586ba 100644 --- a/crates/color/src/gradient/spread.rs +++ b/crates/color/src/gradient/spread.rs @@ -59,6 +59,9 @@ impl Gradient { if !self.is_spread() || matches!(kind, GradientKind::Conic | GradientKind::Freeform) || self.stops.is_empty() { return None; } + if self.mirrors_a_hue_turn() { + return self.as_classic_curve().padded_within(geom, area, max_stops); + } let period = geom.period(kind, self.repeat_count()); let corners = [Point::new(area.x0, area.y0), Point::new(area.x1, area.y0), Point::new(area.x1, area.y1), Point::new(area.x0, area.y1)]; let ts = corners.map(|p| period.param_at(kind, p)); @@ -128,6 +131,9 @@ impl Gradient { if self.stops.is_empty() { return Cow::Owned(Gradient { spread: GradientSpread::Pad, repeats: 1, ..self.clone() }); } + if self.mirrors_a_hue_turn() { + return Cow::Owned(self.as_classic_curve().unrolled_within(max_stops).into_owned()); + } let n = self.repeat_count() as usize; let budget = max_stops.min(MAX_SPREAD_STOPS); let kept = n.min(budget / 2).max(1); @@ -159,12 +165,22 @@ impl Gradient { if !self.is_spread() || self.stops.is_empty() { return None; } + if self.mirrors_a_hue_turn() { + return self.as_classic_curve().cycle(); + } let one = whole_run(&self.stops); let runs = if self.spread == GradientSpread::Reflect { 2 } else { 1 }; let stops = self.runs(&one, false, 0.0, runs, runs as f64); Some((Gradient { stops, spread: GradientSpread::Pad, repeats: 1, ..self.clone() }, runs as u32)) } + /// Does the gradient reflect while mixing around the hue wheel? A mirrored run of its stops + /// would turn the wheel the other way, and one gradient has one method, so its runs are + /// written from its curve's stops ([`Self::as_classic_curve`]), which mirror as they are. + fn mirrors_a_hue_turn(&self) -> bool { + self.method.is_hue() && self.spread == GradientSpread::Reflect + } + /// `n` runs of `one` (one run of the stops, [`whole_run`]) on a line of `of` runs from 0 to 1, /// the first of them `start` runs along it and an odd-numbered run when `first_odd` (with /// Reflect, the odd-numbered runs are mirrored). diff --git a/crates/color/src/gradient/spread/tests.rs b/crates/color/src/gradient/spread/tests.rs index a88319ccaa..ab088293da 100644 --- a/crates/color/src/gradient/spread/tests.rs +++ b/crates/color/src/gradient/spread/tests.rs @@ -118,6 +118,46 @@ fn reflect_mirrors_every_other_run_and_its_midpoints() { assert!((p.gradient.stops[2].midpoint - 0.7).abs() < 1e-6, "{:?}", p.gradient.stops); } +/// A gradient mixed around the hue wheel that reflects: a mirrored run turns the wheel back the +/// way it came, so every point keeps its color when the runs are written out as a gradient that +/// pads, unrolled along the vector, or as one cycle, with a repeating one's too. +#[test] +fn reflected_and_repeated_hue_turns_keep_every_color() { + let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(10.0, 0.0), aspect: 1.0, focal: None }; + let stops = || { + let mut red = GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)); + red.midpoint = 0.3; + vec![red, GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))] + }; + let near = |a: Color, b: Color, what: &str| { + assert!(a.to_rgb().iter().zip(b.to_rgb()).all(|(x, y)| (x - y).abs() < 1.0 / 255.0), "{what}: {a:?} vs {b:?}"); + }; + for method in [GradientMethod::HueClockwise, GradientMethod::HueCounterclockwise] { + for spread in [GradientSpread::Reflect, GradientSpread::Repeat] { + let g = Gradient { method, spread, repeats: 2, ..Gradient::new(GradientKind::Linear, stops()) }; + let p = g.padded_over(&geom, Rect::new(-10.0, 0.0, 20.0, 10.0)).unwrap(); + assert_eq!((p.gradient.spread, p.gradient.repeats), (GradientSpread::Pad, 1)); + for k in 0..300 { + let q = Point::new(-10.0 + f64::from(k) * 0.1 + 0.013, 5.0); + let want = g.sample(g.spread_param(geom.param_at(GradientKind::Linear, q)) as f32).0; + let got = p.gradient.sample(p.geom.param_at(GradientKind::Linear, q) as f32).0; + near(want, got, &format!("{method:?} {spread:?} padded at {}", q.x)); + } + let unrolled = g.unrolled(); + let (cycle, runs) = g.cycle().unwrap(); + for k in 0..=200 { + let t = (k as f32 + 0.37) / 201.0; + let want = g.sample(g.spread_param(f64::from(t)) as f32).0; + near(want, unrolled.sample(t).0, &format!("{method:?} {spread:?} unrolled at {t}")); + // One cycle covers `runs` of the two runs between 0 and 1. + let along = t * runs as f32 / 2.0; + let want = g.sample(g.spread_param(f64::from(along)) as f32).0; + near(want, cycle.sample(t).0, &format!("{method:?} {spread:?} cycle at {t}")); + } + } + } +} + #[test] fn stops_inside_a_run_hold_their_colors_to_its_ends() { let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(10.0, 0.0), aspect: 1.0, focal: None }; diff --git a/crates/color/src/gradient/tests.rs b/crates/color/src/gradient/tests.rs index 0709d3068b..cd25753a05 100644 --- a/crates/color/src/gradient/tests.rs +++ b/crates/color/src/gradient/tests.rs @@ -514,6 +514,283 @@ fn perceptual_gradients_draw_as_pixels() { } } +fn two_stops(a: Color, b: Color, method: GradientMethod) -> Gradient { + let mut g = Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, a), GradientStop::new(1.0, b)]); + g.method = method; + g +} + +/// The hue methods mix around the hue wheel in one direction: Hue Counterclockwise raises the +/// hue angle from each stop to the next and Hue Clockwise lowers it, by the fixed-direction rules +/// of (the angles below are that +/// section's own examples), with saturation and brightness changing evenly. +#[test] +fn hue_methods_turn_one_way_around_the_wheel() { + let (red, blue) = (Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0)); + let rising = two_stops(red, blue, GradientMethod::HueCounterclockwise); + assert_eq!(rising.sample(0.0).0.to_hex(), "#ff0000"); + assert_eq!(rising.sample(0.25).0.to_hex(), "#ffff00", "60°"); + assert_eq!(rising.sample(0.5).0.to_hex(), "#00ff00", "120°"); + assert_eq!(rising.sample(1.0).0.to_hex(), "#0000ff"); + let falling = two_stops(red, blue, GradientMethod::HueClockwise); + assert_eq!(falling.sample(0.0).0.to_hex(), "#ff0000"); + assert_eq!(falling.sample(0.5).0.to_hex(), "#ff00ff", "300°"); + assert_eq!(falling.sample(1.0).0.to_hex(), "#0000ff"); + assert_eq!(two_stops(red, blue, GradientMethod::Classic).sample(0.5).0.to_rgb(), [0.5, 0.0, 0.5], "classic: the RGB mix"); + // 30° to 190° and to 230°: halfway is 110° and 130° rising, 290° and 310° falling. + for (to, up, down) in [(190.0, 110.0, 290.0), (230.0, 130.0, 310.0)] { + let (a, b) = (Color::from_hsb(30.0, 0.5, 0.8), Color::from_hsb(to, 0.9, 0.4)); + for (method, want) in [(GradientMethod::HueCounterclockwise, up), (GradientMethod::HueClockwise, down)] { + let [h, s, v] = method.mix(&a, &b, 0.5).to_hsb(); + assert!((h - want).abs() < 0.05, "{method:?} to {to}: hue {h}, not {want}"); + assert!((s - 0.7).abs() < 1e-3 && (v - 0.6).abs() < 1e-3, "{method:?}: saturation {s}, brightness {v}"); + } + } + // The other way round, each method takes the arc the other took. + let back = two_stops(blue, red, GradientMethod::HueClockwise); + assert_eq!(back.sample(0.5).0.to_hex(), "#00ff00"); + // A position that is not a number gives the first color. + assert_eq!(hue_mix(&red, &blue, f32::NAN, true).to_hex(), "#ff0000"); +} + +/// A color without a hue does not turn the wheel: a gray takes the hue of the stop it mixes +/// with, black its saturation too, two grays mix as grays, and two stops of one hue keep that +/// hue, whichever way the method turns. +#[test] +fn hue_methods_keep_the_hue_where_a_stop_has_none() { + let red = Color::rgb(1.0, 0.0, 0.0); + let close = |c: Color, want: [f32; 3], what: &str| { + let got = c.to_rgb(); + assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() < 1e-3), "{what}: {got:?}, not {want:?}"); + }; + let green = Color::rgb(0.0, 1.0, 0.0); + for method in [GradientMethod::HueClockwise, GradientMethod::HueCounterclockwise] { + close(method.mix(&Color::WHITE, &green, 0.5), [0.5, 1.0, 0.5], "white to green: a light green"); + close(method.mix(&green, &Color::WHITE, 0.5), [0.5, 1.0, 0.5], "green to white: a light green"); + close(method.mix(&Color::rgb(0.5, 0.5, 0.5), &green, 0.5), [0.375, 0.75, 0.375], "gray to green"); + close(method.mix(&Color::BLACK, &green, 0.5), [0.0, 0.5, 0.0], "black to green: a dark green, not a gray green"); + close(method.mix(&green, &Color::BLACK, 0.25), [0.0, 0.75, 0.0], "green to black"); + close(method.mix(&Color::BLACK, &Color::WHITE, 0.5), [0.5, 0.5, 0.5], "black to white: gray"); + close(method.mix(&Color::BLACK, &Color::BLACK, 0.5), [0.0, 0.0, 0.0], "black to black"); + let dark = Color::rgb(0.5, 0.0, 0.0); + close(method.mix(&red, &dark, 0.5), [0.75, 0.0, 0.0], "one hue: a red between the two"); + close(method.mix(&red, &red, 0.5), [1.0, 0.0, 0.0], "one color stays"); + // One hue with saturation and brightness both changing: the hue stays, and the color is + // the even mix of saturation and brightness, which is not Classic's RGB mix. + let pink = Color::rgb(1.0, 0.8, 0.8); + close(method.mix(&dark, &pink, 0.5), [0.75, 0.3, 0.3], "dark red to pink"); + assert!((Color::lerp(&dark, &pink, 0.5).to_rgb()[1] - 0.4).abs() < 1e-3, "classic differs"); + // A color whose RGB numbers are under half a color level apart has no hue of its own: a + // near gray leaning blue takes green's hue rather than turning from blue. + let near_gray = Color::rgb(0.5, 0.5, 0.5 + 0.3 / 255.0); + let [h, _, _] = method.mix(&near_gray, &green, 0.5).to_hsb(); + assert!((h - 120.0).abs() < 0.5, "{method:?}: near gray to green passes hue {h}"); + // One a whole color level apart has its hue (240°) and turns from it. + let bluish = Color::rgb(128.0 / 255.0, 128.0 / 255.0, 129.0 / 255.0); + let [h, _, _] = method.mix(&bluish, &green, 0.5).to_hsb(); + let want = if method == GradientMethod::HueClockwise { 180.0 } else { 0.0 }; + assert!(((h - want + 180.0).rem_euclid(360.0) - 180.0).abs() < 0.5, "{method:?}: bluish gray to green passes hue {h}, not {want}"); + } +} + +/// Hues that differ only by rounding are one hue: a color and a tint or shade of it, whose +/// computed hue angles differ in their last digits, mix without turning the wheel, with either +/// method, and a stop added to a ramp leaves the ramp's colors as they were. Hues a whole color +/// level apart still turn. +#[test] +fn hue_methods_take_hues_within_half_a_color_level_as_one() { + let level = |n: u8| f32::from(n) / 255.0; + let rgb8 = |r: u8, g: u8, b: u8| Color::rgb(level(r), level(g), level(b)); + let methods = [GradientMethod::HueClockwise, GradientMethod::HueCounterclockwise]; + // Colors against their 50% tint toward white and a shade at 40% brightness. At least one + // pair's computed hues differ, or the test checks nothing. + let colors = [rgb8(60, 253, 230), rgb8(241, 194, 107), rgb8(68, 32, 130), rgb8(13, 200, 77), rgb8(250, 3, 201), rgb8(90, 91, 200)]; + let mut uneven = 0; + for c in colors { + let [h, s, v] = c.to_hsb(); + let tint = Color::lerp(&c, &Color::WHITE, 0.5); + let shade = Color::from_hsb(h, s, v * 0.4); + for other in [tint, shade] { + let [h1, _, _] = other.to_hsb(); + assert!((h1 - h).abs() < 0.01, "{c:?} and {other:?} are one hue: {h} and {h1}"); + uneven += usize::from(h1 != h); + for method in methods { + for (a, b) in [(c, other), (other, c)] { + for k in 0..=20 { + let [hm, _, _] = method.mix(&a, &b, k as f32 / 20.0).to_hsb(); + let off = (hm - h + 180.0).rem_euclid(360.0) - 180.0; + assert!(off.abs() < 0.5, "{method:?} {a:?} → {b:?} at {k}/20: hue {hm}, not {h}"); + } + } + } + } + } + assert!(uneven > 0, "no pair's hues differ by rounding"); + // Across 0°: 359.99° and 0.01° are one hue too. + for method in methods { + let [h, _, _] = method.mix(&Color::from_hsb(359.99, 1.0, 1.0), &Color::from_hsb(0.01, 1.0, 1.0), 0.5).to_hsb(); + assert!(!(1.0..=359.0).contains(&h), "{method:?} across 0°: {h}"); + } + // A stop added to a ramp samples the ramp's color there, and the ramp keeps its colors: + // white to red, a color to its tint, and a turn from red to blue. + let ramps = [ + (Color::WHITE, rgb8(255, 0, 0)), + (rgb8(60, 253, 230), Color::lerp(&rgb8(60, 253, 230), &Color::WHITE, 0.5)), + (rgb8(255, 0, 0), rgb8(0, 0, 255)), + ]; + for method in methods { + for (a, b) in ramps { + let g = two_stops(a, b, method); + for at in [0.21, 0.5, 0.83] { + let (stops, i) = insert_stop(&g, at); + assert_eq!((stops.len(), i), (3, 1)); + let with = Gradient { stops, ..g.clone() }; + for k in 0..=200 { + let t = k as f32 / 200.0; + let (was, now) = (g.sample(t).0.to_rgb(), with.sample(t).0.to_rgb()); + let off = was.iter().zip(now).map(|(x, y)| (x - y).abs()).fold(0.0, f32::max); + assert!(off < 1.0 / 255.0, "{method:?} {a:?} → {b:?}, a stop at {at}: {was:?} became {now:?} at {t}"); + } + } + } + } + // One color level of hue is a hue of its own: red to a red one level toward yellow turns + // nearly the whole wheel one way and stays put the other. + let (red, next) = (rgb8(255, 0, 0), rgb8(255, 1, 0)); + let [h, _, _] = GradientMethod::HueClockwise.mix(&red, &next, 0.5).to_hsb(); + assert!((h - 180.0).abs() < 1.0, "the long way: {h}"); + let [h, _, _] = GradientMethod::HueCounterclockwise.mix(&red, &next, 0.5).to_hsb(); + assert!(h < 1.0, "the short way: {h}"); +} + +/// Renderers mix linearly between stops: a hue segment becomes stops on its way around the +/// wheel, close enough that the linear ramp between them stays within half a color level of it, +/// through the midpoint and with the opacity changing evenly. +#[test] +fn hue_segments_expand_into_stops_on_the_curve() { + let pairs = [ + (Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0)), + (Color::rgb(1.0, 0.0, 0.0), Color::rgb(1.0, 0.02, 0.0)), + (Color::from_hsb(30.0, 0.5, 0.8), Color::from_hsb(190.0, 0.9, 0.4)), + (Color::cmyk(0.0, 0.9, 0.9, 0.0), Color::WHITE), + (Color::BLACK, Color::rgb(0.0, 1.0, 0.0)), + ]; + for method in [GradientMethod::HueClockwise, GradientMethod::HueCounterclockwise] { + for (a, b) in pairs { + let mut g = two_stops(a, b, method); + g.stops[0].midpoint = 0.3; + g.stops[1].opacity = 0.5; + let ex: Vec<_> = g.expanded().collect(); + assert!((3..=600).contains(&ex.len()), "{method:?} {a:?} → {b:?}: {} stops", ex.len()); + assert!(ex.windows(2).all(|w| w[0].0 < w[1].0), "in order"); + assert!(ex.iter().any(|s| s.3 == Some(0.3) && (s.0 - 0.3).abs() < 1e-6), "a stop stands for the midpoint"); + let ramp = Ramp::new(&g, &Color::to_rgb); + for k in 0..=4000 { + let t = k as f32 / 4000.0; + let (c, o) = g.sample(t); + let [r, gr, bl] = c.to_rgb(); + let off = [r, gr, bl, o].iter().zip(ramp.at(t)).map(|(x, y)| (x - y).abs()).fold(0.0, f32::max); + assert!(off < 0.5 / 255.0, "{method:?} {a:?} → {b:?} at {t}: {off}"); + } + assert_eq!(g.sample_keep_model(0.4), g.sample(0.4), "one mix"); + } + } +} + +/// Reversing a gradient gives the same ramp the other way round: a hue method turns the other +/// way with the stops, so every color keeps its place mirrored, and reversing twice gives the +/// gradient back. Classic and Perceptual keep their method. A backward span and the curve as a +/// Classic gradient hold the same colors. +#[test] +fn reversing_a_hue_gradient_keeps_its_colors_mirrored() { + let near = |a: Color, b: Color, what: &str| { + assert!(a.to_rgb().iter().zip(b.to_rgb()).all(|(x, y)| (x - y).abs() < 1.0 / 255.0), "{what}: {a:?} vs {b:?}"); + }; + for (method, other) in + [(GradientMethod::HueClockwise, GradientMethod::HueCounterclockwise), (GradientMethod::HueCounterclockwise, GradientMethod::HueClockwise)] + { + let mut g = Gradient::new( + GradientKind::Linear, + vec![ + GradientStop { midpoint: 0.3, ..GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)) }, + GradientStop { opacity: 0.5, ..GradientStop::new(0.6, Color::rgb(0.0, 0.0, 1.0)) }, + GradientStop::new(1.0, Color::rgb(0.9, 0.8, 0.1)), + ], + ); + g.method = method; + let mut back = g.clone(); + back.reverse(); + assert_eq!(back.method, other); + let (span, curve) = (g.span(1.0, 0.0), g.as_classic_curve()); + assert!(span.method.is_classic() && curve.method.is_classic()); + assert!(curve.stops.len() > g.stops.len() && curve.stops.iter().all(|s| s.swatch.is_none() && s.midpoint == 0.5)); + for k in 0..=400 { + let t = k as f32 / 400.0; + let (want, opacity) = g.sample(1.0 - t); + near(want, back.sample(t).0, &format!("{method:?} reversed at {t}")); + assert!((opacity - back.sample(t).1).abs() < 1e-4, "{method:?} opacity at {t}"); + near(want, span.sample(t).0, &format!("{method:?} backward span at {t}")); + near(g.sample(t).0, curve.sample(t).0, &format!("{method:?} curve at {t}")); + } + back.reverse(); + assert_eq!(back.method, method); + assert_eq!(back.stops.len(), g.stops.len()); + } + for method in [GradientMethod::Classic, GradientMethod::Perceptual] { + assert_eq!(method.mirrored(), method); + let mut g = blue_yellow(method); + g.reverse(); + assert_eq!(g.method, method); + } +} + +/// The hue methods are written by name, read back, and parsed from their param names; their +/// gradients draw as pixels in SVG and PDF, and are not mixes of the stops' inks. +#[test] +fn hue_methods_save_parse_and_draw_as_pixels() { + for (method, name, id) in [ + (GradientMethod::HueClockwise, "HueClockwise", "hue-clockwise"), + (GradientMethod::HueCounterclockwise, "HueCounterclockwise", "hue-counterclockwise"), + ] { + let g = two_stops(Color::cmyk(0.0, 1.0, 1.0, 0.0), Color::cmyk(1.0, 1.0, 0.0, 0.0), method); + let v = serde_json::to_value(&g).unwrap(); + assert_eq!(v["method"], name); + assert_eq!(serde_json::from_value::(v).unwrap(), g); + assert_eq!(method.id(), id); + for written in [id.to_string(), id.to_uppercase(), id.replace('-', " "), id.replace('-', "_"), name.to_string(), method.label().to_string()] { + assert_eq!(GradientMethod::parse(&written), Some(method), "{written}"); + } + assert!(method.is_hue() && !method.is_classic()); + let paint = GradientPaint::new(g.clone()); + assert!(paint.draws_as_pixels(true) && paint.draws_as_pixels(false)); + assert!(g.ink_mixes().is_none(), "not mixes of the stops' inks"); + assert!( + paint.ink_pixels(Rect::new(0.0, 0.0, 10.0, 10.0), Rect::new(0.0, 0.0, 10.0, 10.0), 4, 4, true).is_none(), + "an RGB image, not an ink image" + ); + } + assert!(!GradientMethod::Perceptual.is_hue() && !GradientMethod::Classic.is_hue()); + for (id, method) in [("classic", GradientMethod::Classic), ("perceptual", GradientMethod::Perceptual)] { + assert_eq!(method.id(), id); + assert_eq!(GradientMethod::parse(id), Some(method)); + } + for bad in [ + "hue", + "clockwise", + "hue-", + "", + "hue clockwise wise", + "c-l-a-s-s-i-c", + "per ceptual", + "hue--clockwise", + "hue-clock_wise", + " classic", + "hue- clockwise", + ] { + assert_eq!(GradientMethod::parse(bad), None, "{bad}"); + } +} + /// A Perceptual gradient of an ink's tints as tints: its stops keep their tints, and each tint on /// the curve has the lightness of the color mixed there, so the tints between the stops are not /// a straight line. diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rs index 0d84e9e6b3..3afca8063c 100644 --- a/crates/color/src/lib.rs +++ b/crates/color/src/lib.rs @@ -102,12 +102,13 @@ impl Color { pub fn to_lab(&self) -> cms::Lab { cms::active().lab(self) } - /// Colour-managed CMYK in the working CMYK space with `intent` (see [`Color::to_cmyk`] for the - /// profile-free formula). + /// Color-managed CMYK in the active CMYK space (the front document's assigned CMYK profile, else + /// the working CMYK space) with `intent` (see [`Color::to_cmyk`] for the profile-free formula). pub fn to_cmyk_managed(&self, intent: cms::Intent) -> [f32; 4] { cms::active().to_cmyk(self, intent) } - /// Gamut warning: true when this colour can't be reproduced in the working CMYK space. + /// Gamut warning: true when this color can't be reproduced in the active CMYK space (the front + /// document's assigned CMYK profile, else the working CMYK space). pub fn out_of_gamut(&self) -> bool { cms::active().out_of_gamut(self) } diff --git a/crates/doc/src/live.rs b/crates/doc/src/live.rs index 52453fd5a6..3cf8312289 100644 --- a/crates/doc/src/live.rs +++ b/crates/doc/src/live.rs @@ -54,8 +54,8 @@ pub use blend_spec::{BlendDefaults, BlendEase, BlendEaseType, BlendOrientation, use blend_spec::{blend_color_shift, blend_ramp}; pub use envelope::{ EnvelopeKind, EnvelopeMap, EnvelopeOptions, H_DOWN, H_LEFT, H_RIGHT, H_UP, PreserveShape, TypeInk, envelope_bounds, envelope_content_bounds, - envelope_content_boxes, envelope_expand, envelope_frame, envelope_grid, envelope_mapper, envelope_of, envelope_overlay, envelope_stroke_margin, - set_type_ink, smooth_handles, warp_grid, + envelope_content_boxes, envelope_content_boxes_with, envelope_expand, envelope_frame, envelope_grid, envelope_mapper, envelope_of, + envelope_overlay, envelope_stroke_margin, set_type_ink, smooth_handles, warp_grid, }; pub(crate) use expand::max_outset; pub use expand::{ diff --git a/crates/doc/src/live/envelope.rs b/crates/doc/src/live/envelope.rs index 44dc406c1d..5aa43b0a67 100644 --- a/crates/doc/src/live/envelope.rs +++ b/crates/doc/src/live/envelope.rs @@ -149,20 +149,31 @@ impl EnvelopeOptions { /// its glyph outlines (see [`envelope_content_bounds`]). Strokes scale with the frame as /// [`Node::transform`] scales them. pub fn envelope_content_boxes(content: &[Arc], frame: Affine) -> Option<(Rect, Rect)> { + envelope_content_boxes_with(content, frame, false).or_else(|| envelope_content_boxes_with(content, frame, true)) +} + +/// [`envelope_content_boxes`] with type that draws nothing given its laid-out box when +/// `blank_type_box` is set and no box when it is not. A caller that measures the members of an +/// envelope's contents one at a time passes `true` only when the whole contents have no box with +/// `false`, so each member is measured as the whole contents measure it. +pub fn envelope_content_boxes_with(content: &[Arc], frame: Affine, blank_type_box: bool) -> Option<(Rect, Rect)> { let frame = if frame.is_finite() && frame.determinant().abs() > 1e-12 { frame } else { Affine::IDENTITY }; let to_frame = frame.inverse(); - let (stroked, plain) = content.iter().fold((None, None), |(stroked, plain), c| { - (vectorcraft_geom::union_opt(stroked, content_box(c, true, to_frame)), vectorcraft_geom::union_opt(plain, content_box(c, false, to_frame))) - }); - Some((stroked?, plain?)) + Some((content_set_box(content, true, to_frame, blank_type_box)?, content_set_box(content, false, to_frame, blank_type_box)?)) } /// The geometric bounds an envelope around `content` on the page axes maps from: type, alone or /// in groups and layers, is measured by its glyph outlines, underlines and strikethroughs instead /// of its laid-out box. Type keeps its laid-out box while nothing is registered with -/// [`set_type_ink`], and when it draws nothing. +/// [`set_type_ink`]. Type that draws nothing adds no box while other content has one; when +/// nothing else has a box, it keeps its laid-out box. pub fn envelope_content_bounds(content: &[Arc]) -> Option { - content.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, content_box(c, false, Affine::IDENTITY))) + content_set_box(content, false, Affine::IDENTITY, false).or_else(|| content_set_box(content, false, Affine::IDENTITY, true)) +} + +/// The union of the boxes [`content_box`] gives each of `content`. +fn content_set_box(content: &[Arc], stroked: bool, to: Affine, blank_type_box: bool) -> Option { + content.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, content_box(c, stroked, to, blank_type_box))) } /// The box of type's glyph outlines, underlines and strikethroughs with its text space mapped by @@ -367,15 +378,16 @@ fn find_type(n: &Node, typed: &mut std::collections::HashSet) -> bool { /// or with `stroked` its visual bounds (strokes scaled by `to` as [`Node::transform`] scales them), /// with type measured by its glyph outlines ([`type_ink`]) instead of its laid-out box, in groups /// and layers too. Type is laid out as it is on the page, and its outlines are then taken into -/// those axes. A character's strokes reach as far past its glyphs as past the laid-out box. -fn content_box(n: &Arc, stroked: bool, to: Affine) -> Option { +/// those axes. A character's strokes reach as far past its glyphs as past the laid-out box. Type +/// that draws nothing has its laid-out box with `blank_type_box`, and no box without it. +fn content_box(n: &Arc, stroked: bool, to: Affine, blank_type_box: bool) -> Option { let mut typed = std::collections::HashSet::new(); find_type(n, &mut typed); - content_box_in(n, stroked, to, &typed) + content_box_in(n, stroked, to, &typed, blank_type_box) } /// [`content_box`], with the addresses of the objects in `n` that hold type ([`find_type`]). -fn content_box_in(n: &Arc, stroked: bool, to: Affine, typed: &std::collections::HashSet) -> Option { +fn content_box_in(n: &Arc, stroked: bool, to: Affine, typed: &std::collections::HashSet, blank_type_box: bool) -> Option { // `n` in the axes of `to`. let moved = || { if to == Affine::IDENTITY { @@ -395,10 +407,13 @@ fn content_box_in(n: &Arc, stroked: bool, to: Affine, typed: &std::collect let ink = match n.projection() { None => type_ink(n, t, to * t.xf, None), Some(h) => type_ink(n, t, t.xf, Some((h, to))), - } - .flatten(); + }; let m = moved(); - let Some(ink) = ink else { return own(&m) }; + let ink = match ink { + Some(Some(ink)) => ink, + Some(None) if !blank_type_box => return None, + _ => return own(&m), + }; if !stroked { return Some(ink); } @@ -413,7 +428,13 @@ fn content_box_in(n: &Arc, stroked: bool, to: Affine, typed: &std::collect NodeKind::Group { children, clip: true } | NodeKind::Layer { children, clip: true, .. } => { // A clipping path that paints strokes over the clip edge, as in `Node::visual_bounds`. let clip = children.first()?; - content_box_in(clip, stroked && matches!(clip.kind, NodeKind::Path { .. } | NodeKind::Compound { .. } | NodeKind::Text(_)), to, typed) + content_box_in( + clip, + stroked && matches!(clip.kind, NodeKind::Path { .. } | NodeKind::Compound { .. } | NodeKind::Text(_)), + to, + typed, + blank_type_box, + ) } NodeKind::Layer { .. } | NodeKind::Group { .. } => { let layer = matches!(n.kind, NodeKind::Layer { .. }); @@ -424,9 +445,11 @@ fn content_box_in(n: &Arc, stroked: bool, to: Affine, typed: &std::collect let mut own_strokes = Node::new(n.id, NodeKind::Group { children: Vec::new(), clip: false }); own_strokes.appearance = n.appearance.clone(); own_strokes.transform(to, true); - own_strokes.visual_of_members(members.map(|c| content_box_in(c, true, to, typed))) + own_strokes.visual_of_members(members.map(|c| content_box_in(c, true, to, typed, blank_type_box))) } else { - members.filter(|c| c.visible || !layer).fold(None, |acc, c| vectorcraft_geom::union_opt(acc, content_box_in(c, false, to, typed))) + members + .filter(|c| c.visible || !layer) + .fold(None, |acc, c| vectorcraft_geom::union_opt(acc, content_box_in(c, false, to, typed, blank_type_box))) } } _ => own(&moved()), @@ -649,7 +672,7 @@ impl<'a> EnvelopeMap<'a> { pub fn new(content: &[Arc], kind: &'a EnvelopeKind, frame: Affine, options: EnvelopeOptions) -> Option { let frame = if frame.is_finite() && frame.determinant().abs() > 1e-12 { frame } else { Affine::IDENTITY }; let to_frame = frame.inverse(); - let src = content.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, content_box(c, false, to_frame)))?; + let src = content_set_box(content, false, to_frame, false).or_else(|| content_set_box(content, false, to_frame, true))?; let src = options.source_box(src); Some(Self { src, frame, to_frame, surface: surface_of(kind, src, frame) }) } @@ -835,14 +858,14 @@ mod tests { let to = Affine::scale(2.0); let mut moved = (*group).clone(); moved.transform(to, true); - let want = moved.visual_of_members(std::iter::once(content_box(&text, true, to))); + let want = moved.visual_of_members(std::iter::once(content_box(&text, true, to, true))); assert!(want.is_some()); - assert_eq!(content_box(&group, true, to), want); + assert_eq!(content_box(&group, true, to, true), want); let mut nested = group; for i in 0..300 { nested = Arc::new(Node::group(NodeId(10 + i), vec![nested])); } - assert!(content_box(&nested, false, Affine::IDENTITY).is_some()); + assert!(content_box(&nested, false, Affine::IDENTITY, true).is_some()); } /// A warp envelope of `style` at `bend` with map `version` around a 200×100 rectangle at diff --git a/crates/effects/src/bake.rs b/crates/effects/src/bake.rs index b77f804de7..7e42147443 100644 --- a/crates/effects/src/bake.rs +++ b/crates/effects/src/bake.rs @@ -83,15 +83,17 @@ fn apply(effects: &[vectorcraft_doc::Effect], path: &PathData, ctx: &GeomContext /// The geometry `g` with the own effects of `item` (one of the fills and strokes `ctx` is the /// context of) applied, and `carried` (`item` as the object's effects left it) with its gradient -/// moved along with them. +/// moved along with them and the Transform effects the geometry pass left out hidden +/// ([`crate::Carry::hide_skipped`]). fn apply_item(item: &AppearanceItem, carried: &AppearanceItem, g: &PathData, ctx: &GeomContext) -> (PathData, AppearanceItem) { let (ig, carry) = apply(item_effects(item), g, &ctx.item(item)); let mut ap = Appearance { items: vec![carried.clone()], ..Default::default() }; - if !carry.moves(&ap) { - return (ig, carried.clone()); + if carry.moves(&ap) { + carry.apply(&mut ap); } - carry.apply(&mut ap); - (ig, ap.items.pop().unwrap_or_else(|| carried.clone())) + let mut out = ap.items.pop().unwrap_or_else(|| carried.clone()); + carry.hide_skipped(out.effects_mut()); + (ig, out) } /// A path node of `kind`'s flavour (compound when the result has several subpaths). @@ -470,6 +472,7 @@ fn leaf_base(n: &Node) -> Option<(PathData, FillRule, GeomContext<'_>, Node)> { if carry.moves(&m.appearance) { carry.apply(&mut m.appearance); } + carry.hide_skipped(&mut m.appearance.effects); // The raster effects of its fills and strokes follow its Transform effects, as on the canvas. crate::raster::follow_items(&mut m); m.appearance.effects = crate::raster::without_geometry(&m.appearance.effects); diff --git a/crates/effects/src/geometry.rs b/crates/effects/src/geometry.rs index a2e5478b28..39924835fd 100644 --- a/crates/effects/src/geometry.rs +++ b/crates/effects/src/geometry.rs @@ -200,8 +200,12 @@ pub fn apply_geometry_bez_carrying(effects: &[Effect], path: &BezPath, bounds: R /// it unevenly (a map after which a refit would not match the mapped gradient): it is fixed to its /// fit on the geometry that effect takes, and then follows that effect and the ones after it as a /// placed gradient does. +/// +/// It also lists the visible Transform effects that move the art once and that the pass left out, +/// their results past the budget, by their index in the effect list it was given: the raster +/// effects before such an effect stay as they are, as the art does ([`Self::hide_skipped`]). #[derive(Clone, Debug, Default, PartialEq)] -pub struct Carry(Vec); +pub struct Carry(Vec, Vec); /// Does `m` fix a gradient fitted to the object to its fit before mapping it? It does when a refit /// would not reproduce the map (a turn, a reflection or an uneven scale) and `m` keeps area: a map @@ -265,7 +269,7 @@ impl Carry { _ => None, }, }; - Carry(step.into_iter().collect()) + Carry(step.into_iter().collect(), vec![]) } /// Does it leave gradients where they are? @@ -310,6 +314,30 @@ impl Carry { pub(crate) fn push(&mut self, more: Carry) { self.0.extend(more.0); + self.1.extend(more.1); + } + + /// Did the pass leave out a Transform effect that moves the art once ([`Self::hide_skipped`])? + pub fn skipped(&self) -> bool { + !self.1.is_empty() + } + + /// Hide each Transform effect of `effects`, the list the pass was given, that it left out (its + /// result past the budget): the art stays where it was, so the raster effects listed before it + /// do not follow it ([`crate::raster::followed`]). Other effects stay as they are. + pub fn hide_skipped(&self, effects: &mut [Effect]) { + for &i in &self.1 { + if let Some(e) = effects.get_mut(i).filter(|e| e.id == "distort.transform") { + e.visible = false; + } + } + } + + /// Note that the Transform effect at index `i` of the pass's list was left out. + pub(crate) fn skip(&mut self, i: usize) { + if !self.1.contains(&i) { + self.1.push(i); + } } } @@ -354,6 +382,13 @@ pub(crate) fn apply_geometry_carrying_within( c.push(Carry::of(&e.id, &p, b, cur.bounds(), next.bounds(), ctx.seed)); } cur = next; + } else if let Some(c) = carry.as_deref_mut() + && e.id == "distort.transform" + && !crate::raster::holds_back(e) + && let Some(i) = effects.iter().position(|x| std::ptr::eq(x, e)) + { + // The raster effects before it stay as the art does. + c.skip(i); } } cur diff --git a/crates/effects/src/group.rs b/crates/effects/src/group.rs index a6581fa449..bb2f605a91 100644 --- a/crates/effects/src/group.rs +++ b/crates/effects/src/group.rs @@ -261,8 +261,17 @@ fn reshaped(src: &Node, n: &Node, doc: Option<&Document>) -> Node { carry.apply(&mut m.appearance); } // So do the raster effects of its fills and strokes, by `n`'s Transform effects - // ([`crate::follow_items`]). - crate::raster::follow_items_of(&mut m, &n.appearance.effects); + // ([`crate::follow_items`]) that moved the outline. + let mut owner = std::borrow::Cow::Borrowed(n.appearance.effects.as_slice()); + if carry.skipped() { + carry.hide_skipped(owner.to_mut()); + if m.appearance.effects == n.appearance.effects { + let mut ap = (*m.appearance).clone(); + ap.effects = owner.to_vec(); + m.appearance = ap.into(); + } + } + crate::raster::follow_items_of(&mut m, &owner); } without_geometry_effects(&mut m); m diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index 89a258bb07..8c829d9e0b 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -895,9 +895,16 @@ pub(crate) fn own_effects_art(doc: Option<&Document>, n: &Node) -> Option return None; } let mut art = one_piece(n); - reshape_leaves(&mut art, &fx, &n.appearance.effects, doc); + let carry = reshape_leaves_carrying(&mut art, &fx, &n.appearance.effects, doc); transform_items(&mut art, doc); - Some(dressed(art, n)) + let mut art = dressed(art, n); + // The raster effects before a Transform effect the path did not take stay as the path does. + if carry.skipped() { + let mut ran = n.appearance.effects.clone(); + carry.hide_skipped(&mut ran); + art.appearance.effects = crate::raster::without_geometry(&ran); + } + Some(art) } /// Map every path under `art` (and its gradients), and every path in the art of the linked opacity @@ -997,7 +1004,8 @@ fn hoist_copies(art: &mut Node) { /// of their own ([`copy_leaf`]) whatever paints them, as Expand Appearance makes them. A live-effect /// plug-in that paints what it returns makes each path a group of its pieces ([`paint_leaf`]), /// whose swatches and patterns must be in `doc` (without one, pieces that name one are refused). -/// Returns how gradients that paint the art as a whole follow the effects. A deferred live-effect +/// Returns how gradients that paint the art as a whole follow the effects, and the Transform +/// effects that nothing in the art took past the budget ([`crate::Carry::skipped`]). A deferred live-effect /// plug-in is listed by its index in `owner`, the effect list `fx` was taken from, or in `fx` when /// `owner` does not hold it. The art of the linked opacity masks of the objects in `art` (not of /// `art` itself) takes each effect as the paths it masks do ([`Step::reshape_masks`]), with the @@ -1053,6 +1061,16 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], owner: &[Effect], budget used = cost; continue; } + // A Transform effect that moves the art once and that nothing in it took (past the budget) + // is left out ([`crate::Carry::hide_skipped`]), listed by its index in `owner`. + if ran.kept + && !ran.took + && e.id == "distort.transform" + && !crate::raster::holds_back(e) + && let Some(i) = owner.iter().position(|x| std::ptr::eq(x, *e)) + { + whole.skip(i); + } if let Some(carry) = ran.whole { whole.push(carry); } @@ -1084,6 +1102,8 @@ struct Step<'a> { struct Ran { /// A path in the art kept its shape (past the budget). kept: bool, + /// A path, image or symbol instance in the art took the effect. + took: bool, /// The linked opacity mask of an object in the art stayed as it was while the paths it masks /// took the effect, or could have ([`Step::reshape_masks`]). masks: bool, @@ -1123,7 +1143,7 @@ impl Step<'_> { depth: usize, ) -> Ran { let (e, params, bounds, seed) = (self.e, self.params, self.bounds, self.seed); - let stayed = Ran { kept: false, masks: true, short: false, whole: None }; + let stayed = Ran { kept: false, took: false, masks: true, short: false, whole: None }; if let Some(plugin) = painted_plugin(e) { if own || has_linked_mask(art, false) { return stayed; @@ -1137,7 +1157,7 @@ impl Step<'_> { *used = used.minus(before).plus(made); } }); - return Ran { kept: false, masks: false, short: false, whole: None }; + return Ran { kept: false, took: true, masks: false, short: false, whole: None }; } // A Warp effect that bends images ([`mark_warped_images`]) bends an image's pixels, not the // art of its linked mask. @@ -1190,7 +1210,7 @@ impl Step<'_> { // ([`transform_placed`]): a mask's art that holds one can't take another effect as the art // it masks does. if own && transform.is_none() && (is_placed(art) || placed_count(art) > 0) { - return Ran { kept: false, masks: true, short: false, whole: None }; + return Ran { kept: false, took: false, masks: true, short: false, whole: None }; } // Art of several objects is copied whole, so the copies don't interleave member by member. // The copies of its members carry their linked masks, moved with them. @@ -1200,7 +1220,7 @@ impl Step<'_> { { if !own { *used = copy_art(art, m, copies, copy_scaling(options), max); - return Ran { kept: false, masks: false, short: false, whole: None }; + return Ran { kept: false, took: true, masks: false, short: false, whole: None }; } // A mask's art: its copies keep to what the rest of the art leaves of `max`, and the // linked mask of the art itself takes them too. That mask's art stays in `used`, as @@ -1212,7 +1232,7 @@ impl Step<'_> { let short = art.children().is_some_and(|c| c.iter().filter(|c| !c.is_guide()).count() <= copies); let none = HashSet::new(); let masks = self.reshape_own_mask(art, &Skip { moved: &none, kept: &none }, max, used, depth); - return Ran { kept: false, masks, short, whole: None }; + return Ran { kept: false, took: true, masks, short, whole: None }; } // A shortfall in the copies matters for the objects a linked mask above them covers, which // the mask would take a different number of copies than, and anywhere in a mask's art. @@ -1223,6 +1243,7 @@ impl Step<'_> { } let counts = |id: NodeId| watch && (own || covered.contains(&id)); let mut short = false; + let mut took = false; for_each_leaf(art, &mut |leaf| { let at = leaf_at; leaf_at += 1; @@ -1247,6 +1268,7 @@ impl Step<'_> { if options.reach_appearance() { let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room, raster_map.is_some(), None); *used = used.minus(before).plus(made); + took |= moved; if moved { // With Transform Objects off the path stays, and its mask takes the // effect's stroke and pattern changes as its own art. @@ -1263,6 +1285,7 @@ impl Step<'_> { let scaling = vectorcraft_doc::Scaling { keep_fit_when_flat: true, ..Default::default() }; let made = copy_leaf(leaf, &path, m, copies, scaling, room, None); *used = used.minus(before).plus(made); + took = true; moved_ids.insert(leaf.id); short |= counts(leaf.id) && copied(leaf) <= copies; return; @@ -1274,6 +1297,7 @@ impl Step<'_> { kept_leaves.insert(at); return; }; + took = true; // A Transform effect's copies of a path are subpaths of it, each with the path's anchors. if counts(leaf.id) && let Some((_, copies, _, _)) = transform @@ -1315,6 +1339,8 @@ impl Step<'_> { *art = Node::group(id, vec![Arc::new(one)]); } let placed = if watch { masked_placed(art, own) } else { 0 }; + // Images and symbol instances take the effect whatever the budget. + took = took || placed_count(art) > 0; // Scale Strokes & Effects leaves the raster effects that follow the effect to // [`follow_art`]. let mut scaling = copy_scaling(options); @@ -1348,7 +1374,7 @@ impl Step<'_> { } let drawn = warped.as_deref().map_or_else(|| art.geometric_bounds(), |w| w.bounds(art)); let whole = (follows && !held).then(|| crate::Carry::of(&e.id, params, bounds, Some(bounds), drawn, seed)); - Ran { kept: !kept_ids.is_empty(), masks, short, whole } + Ran { kept: !kept_ids.is_empty(), took, masks, short, whole } } /// Run the effect over the art of the linked opacity mask of `n` (with `own`) and of each path, @@ -2074,9 +2100,14 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt // effects before this one back from every Transform effect ([`crate::raster::followed`]). let held_later = fx.get(at + 1..).unwrap_or_default().iter().any(crate::raster::holds_back); // The effects before the Transform effect that it keeps, each raster effect following the - // geometry effects before it ([`crate::raster::without_geometry`]) unless held back. + // geometry effects before it that moved the geometry ([`crate::raster::without_geometry`], + // [`crate::Carry::hide_skipped`]) unless held back. + let mut ran = std::borrow::Cow::Borrowed(before); + if carry.skipped() { + carry.hide_skipped(ran.to_mut()); + } let kept_before: Vec = - if held_later { before.iter().filter(|e| !is_geometry(&e.id)).cloned().collect() } else { crate::without_geometry(before) }; + if held_later { before.iter().filter(|e| !is_geometry(&e.id)).cloned().collect() } else { crate::without_geometry(&ran) }; if let Some(plugin) = painted_plugin(&fx[at]) { let mut it = item.clone(); let rest: Vec = kept_before.iter().chain(&fx[at + 1..]).cloned().collect(); @@ -2490,7 +2521,10 @@ fn piece_stage(leaf: &mut Node, e: &Effect, at: &PieceStage, (appearance, index) carry.apply(&mut leaf.appearance); } set_geometry(leaf, out, rule); - follow_piece(leaf, was, at.from, e); + // A Transform effect left out (past the budget) leaves the path and its raster effects as they were. + if !carry.skipped() { + follow_piece(leaf, was, at.from, e); + } Some(made) } diff --git a/crates/effects/src/tests/rasterfollow.rs b/crates/effects/src/tests/rasterfollow.rs index aead8b72ce..a610ae7c71 100644 --- a/crates/effects/src/tests/rasterfollow.rs +++ b/crates/effects/src/tests/rasterfollow.rs @@ -4,9 +4,10 @@ use serde_json::{Value, json}; use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{Appearance, Document, Effect, Node, NodeId}; -use vectorcraft_geom::{Rect, shapes}; +use vectorcraft_geom::{Affine, Anchor, PathData, Point, Rect, SubPath, shapes}; -use crate::{RasterFx, bake_document, expand_outlined, raster_effects}; +use crate::geometry::{Budget, MAX_EFFECT_LINES, apply_geometry_carrying_within}; +use crate::{Carry, GeomContext, RasterFx, apply_geometry_carrying, bake_document, expand_outlined, raster_effects}; fn fx(id: &str, params: Value) -> Effect { Effect { id: id.into(), params, visible: true } @@ -652,3 +653,191 @@ fn a_groups_transform_moves_its_members_fills_shadows_beside_their_own_transform } } } + +/// A closed path of `n` curves along the x axis, 2 pt apart, each drawn with 14 lines at 1 px/pt +/// and with 425 once scaled 1000 times ([`crate::util::line_estimate`]). +fn wavy(n: usize) -> PathData { + let anchors = (0..=n) + .map(|i| { + let x = 2.0 * i as f64; + Anchor::with_handles(Point::new(x, 0.0), Point::new(x - 0.5, -20.0), Point::new(x + 0.5, 20.0)) + }) + .collect(); + PathData::single(SubPath::new(anchors, true)) +} + +/// A red path `id` along `path` with object effects `effects`. +fn path_node(id: u64, path: PathData, effects: Vec) -> Node { + let mut n = Node::path(NodeId(id), path, Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0)); + n.appearance.effects = effects; + n +} + +/// A Transform effect scaling 1000 times. +fn thousandfold() -> Effect { + transform(json!({"scaleH": 100000, "scaleV": 100000})) +} + +/// `n` baked on its own ([`bake_document`]). +fn baked(n: Node) -> Node { + let id = n.id; + let mut d = Document::new(800.0, 800.0); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, n).unwrap(); + bake_document(&d).unwrap().node(id).unwrap().clone() +} + +/// A Transform effect whose result passes the 8 million lines of the effect budget is left out, so +/// the art stays where it is, and the shadow before it keeps its offset and blur with it: drawn, +/// baked for export, and once shown after baking when it is hidden. One within the budget moves +/// and scales both. +#[test] +fn a_transform_past_the_line_budget_moves_the_art_with_its_shadow() { + let path = wavy(30_000); + assert!(Budget::EFFECTS.fits(Budget::of(&path)), "{:?}", Budget::of(&path)); + let candidate = Budget::of(&path.transformed(Affine::scale(1000.0))); + assert!(candidate.lines > MAX_EFFECT_LINES, "{candidate:?}"); + let b = path.bounds().unwrap(); + let n = path_node(30, path.clone(), vec![shadow(10.0, 5.0, 4.0), thousandfold()]); + let (g, carry) = apply_geometry_carrying(&n.appearance.effects, &path, b, &GeomContext::of(&n)); + assert_eq!(g, path, "the art stays where it is"); + assert!(carry.skipped()); + let mut drawn = n.appearance.effects.clone(); + carry.hide_skipped(&mut drawn); + assert!(close(drawn_shadow(&drawn), (10.0, 5.0, 4.0)), "drawn {:?}", drawn_shadow(&drawn)); + let out = baked(n.clone()); + assert_eq!(out.geometric_bounds(), Some(b)); + assert!(close(drawn_shadow(&out.appearance.effects), (10.0, 5.0, 4.0)), "baked {:?}", drawn_shadow(&out.appearance.effects)); + // A hidden shadow keeps its values too, once shown. + let mut hidden = shadow(10.0, 5.0, 4.0); + hidden.visible = false; + let out = baked(path_node(31, path.clone(), vec![hidden, thousandfold()])); + let mut shown = out.appearance.effects.clone(); + shown.iter_mut().for_each(|e| e.visible = true); + assert!(close(drawn_shadow(&shown), (10.0, 5.0, 4.0)), "shown {:?}", drawn_shadow(&shown)); + // A fill's own shadow before its own Transform effect stays too. + let mut fill = path_node(35, path.clone(), vec![]); + if let Some(item) = fill.appearance.items.first_mut() { + *item.effects_mut() = vec![shadow(10.0, 5.0, 4.0), thousandfold()]; + } + let out = baked(fill); + assert!(near(&shadows_in(&out), &[(10.0, 5.0)]), "baked fill {:?}", shadows_in(&out)); + // Within the budget, both move. + let doubled = path_node(32, path.clone(), vec![shadow(10.0, 5.0, 4.0), transform(json!({"scaleH": 200, "scaleV": 200}))]); + let (g, carry) = apply_geometry_carrying(&doubled.appearance.effects, &path, b, &GeomContext::of(&doubled)); + assert!(g != path && !carry.skipped()); + let out = baked(doubled); + assert!(close(drawn_shadow(&out.appearance.effects), (20.0, 10.0, 8.0)), "baked {:?}", drawn_shadow(&out.appearance.effects)); +} + +/// The art of a path whose Transform effect is left out past the budget ([`crate::shape_art`], +/// as a group's or a mask's member is drawn) keeps the object's shadow and its fill's shadow with +/// their own offsets. +#[test] +fn the_shape_art_of_a_skipped_transform_keeps_its_shadows() { + let mut n = path_node(34, wavy(30_000), vec![shadow(10.0, 5.0, 4.0), thousandfold()]); + if let Some(item) = n.appearance.items.first_mut() { + *item.effects_mut() = vec![shadow(1.0, 0.5, 0.0)]; + } + let art = crate::shape_art(None, &n, None).unwrap(); + assert!(near(&shadows_in(&art), &[(10.0, 5.0), (1.0, 0.5)]), "{:?}", shadows_in(&art)); +} + +/// A path whose own Transform effect is left out past the budget, in a group whose geometry effect +/// (a move, which leaves offsets as they are) runs after its members' own, is drawn with its shadow +/// at its own offset; one within the budget scales the shadow with the path. +#[test] +fn a_members_skipped_transform_keeps_its_shadow_under_its_groups_effects() { + for (last, want) in [(thousandfold(), (10.0, 5.0)), (transform(json!({"scaleH": 200, "scaleV": 200})), (20.0, 10.0))] { + let member = path_node(38, wavy(30_000), vec![shadow(10.0, 5.0, 4.0), last.clone()]); + let g = group(37, vec![member], vec![transform(json!({"moveH": 5, "moveV": 5}))]); + let art = crate::evaluate_container(None, &g).unwrap(); + assert!(near(&shadows_in(&node_in(&art, 38)), &[want]), "{last:?}: {:?}", shadows_in(&node_in(&art, 38))); + } +} + +/// Of two Transform effects after a shadow, the shadow follows only the ones that ran: the first +/// left out past the budget, or hidden, and the second within it; and both when the first's +/// result is exactly at the limit. +#[test] +fn only_transforms_that_ran_move_a_preceding_shadow() { + let circle = shapes::ellipse(Rect::new(0.0, 0.0, 100.0, 100.0)); + let b = circle.bounds().unwrap(); + let doubled = Budget::of(&circle.transformed(Affine::scale(2.0))).lines; + assert!(doubled > Budget::of(&circle).lines); + let run = |effects: &[Effect], lines: usize| { + let mut carry = Carry::default(); + apply_geometry_carrying_within(effects, &circle, b, &GeomContext::default(), Budget { anchors: 1000, lines }, Some(&mut carry)); + let mut drawn = effects.to_vec(); + carry.hide_skipped(&mut drawn); + drawn_shadow(&drawn) + }; + let effects = vec![shadow(10.0, 0.0, 4.0), transform(json!({"scaleH": 200, "scaleV": 200})), transform(json!({"rotate": 90}))]; + // Turned 90° counterclockwise on screen, (10, 0) goes to (0, -10). + let only_turned = run(&effects, doubled - 1); + assert!(only_turned.0.abs() < 1e-9 && (only_turned.1 + 10.0).abs() < 1e-9 && (only_turned.2 - 4.0).abs() < 1e-9, "{only_turned:?}"); + let both = run(&effects, doubled); + assert!(both.0.abs() < 1e-9 && (both.1 + 20.0).abs() < 1e-9 && (both.2 - 8.0).abs() < 1e-9, "{both:?}"); + let mut hidden = effects.clone(); + hidden[1].visible = false; + let turned = run(&hidden, doubled); + assert!(turned.0.abs() < 1e-9 && (turned.1 + 10.0).abs() < 1e-9 && (turned.2 - 4.0).abs() < 1e-9, "{turned:?}"); +} + +/// A fill's own Transform effect left out past the budget, after a Transform effect of that fill +/// that makes it a piece of its own (Transform Patterns), leaves the piece and the shadow before it +/// as they were. One within the budget scales both. +#[test] +fn a_skipped_item_transform_keeps_its_shadow() { + let path = wavy(30_000); + let b = path.bounds().unwrap(); + for (last, want) in [(thousandfold(), (10.0, 5.0)), (transform(json!({"scaleH": 200, "scaleV": 200})), (20.0, 10.0))] { + let mut n = path_node(33, path.clone(), vec![]); + if let Some(item) = n.appearance.items.first_mut() { + *item.effects_mut() = vec![transform(json!({"patterns": true})), shadow(10.0, 5.0, 4.0), last.clone()]; + } + let art = crate::reshape(None, &n, None).unwrap(); + assert!(near(&shadows_in(&art), &[want]), "{last:?}: {:?}", shadows_in(&art)); + if want == (10.0, 5.0) { + assert_eq!(art.geometric_bounds(), Some(b), "the piece stays where it is"); + } + // The same with the Transform effect before the one that makes the piece. + let mut n = path_node(36, path.clone(), vec![]); + if let Some(item) = n.appearance.items.first_mut() { + *item.effects_mut() = vec![shadow(10.0, 5.0, 4.0), last.clone(), transform(json!({"patterns": true}))]; + } + let art = crate::reshape(None, &n, None).unwrap(); + assert!(near(&shadows_in(&art), &[want]), "{last:?} first: {:?}", shadows_in(&art)); + } +} + +/// A group's Transform effect moves each member's shadow as it moves that member: the member whose +/// result would pass what the budget leaves keeps its shape and its shadow, and the other takes +/// both. +#[test] +fn a_group_transform_follows_only_the_members_it_moved() { + let small = path_node(41, shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), vec![shadow(1.0, 0.5, 0.0)]); + let large = path_node(42, wavy(30_000), vec![shadow(1.0, 0.5, 0.0)]); + let g = group(40, vec![small, large], vec![thousandfold()]); + let art = crate::evaluate_container(None, &g).unwrap(); + assert!(near(&shadows_in(&node_in(&art, 41)), &[(1000.0, 500.0)]), "{:?}", shadows_in(&node_in(&art, 41))); + assert!(near(&shadows_in(&node_in(&art, 42)), &[(1.0, 0.5)]), "{:?}", shadows_in(&node_in(&art, 42))); +} + +/// A Transform effect that makes copies, or has Transform Objects off, keeps its own rule for the +/// shadow before it, past the budget or not: the shadow stays as it is, and the pass does not +/// report it as left out. +#[test] +fn copying_and_object_disabled_transforms_keep_their_existing_shadow_rules() { + let path = wavy(30_000); + let b = path.bounds().unwrap(); + for t in [ + transform(json!({"scaleH": 100000, "scaleV": 100000, "copies": 1})), + transform(json!({"scaleH": 100000, "scaleV": 100000, "objects": false})), + ] { + let effects = vec![shadow(10.0, 5.0, 4.0), t.clone()]; + let (_, carry) = apply_geometry_carrying(&effects, &path, b, &GeomContext::default()); + assert!(!carry.skipped(), "{t:?}"); + assert!(close(drawn_shadow(&effects), (10.0, 5.0, 4.0)), "{t:?}: {:?}", drawn_shadow(&effects)); + } +} diff --git a/crates/engine/src/cmd/arrowheads.rs b/crates/engine/src/cmd/arrowheads.rs index 0aeda59731..340cf98459 100644 --- a/crates/engine/src/cmd/arrowheads.rs +++ b/crates/engine/src/cmd/arrowheads.rs @@ -18,7 +18,7 @@ use vectorcraft_doc::{Appearance, AppearanceItem, CustomArrowhead, Document, Nod use vectorcraft_geom::{Affine, FillRule, PathData, Point, SubPath}; use vectorcraft_pathops::BoolOp; -use super::{CommandSpec, Result, Session, always, bad, cmd}; +use super::{CommandSpec, EngineError, Result, Session, always, bad, cmd}; /// The arrowheads file's name, in the folder of the preferences. pub const FILE_NAME: &str = "Arrowheads.vectorcraft"; @@ -37,7 +37,7 @@ pub fn specs() -> Vec { "Arrowheads", [], None, - "{} → {arrowheads: [{name (stroke.set `startArrow`/`endArrow` as {custom: name}), reach, halfWidth (in head weights)}], file: the arrowheads file's path or null (no file here, as on the web), skipped: [{name, reason}] symbols of the file that are not heads, error: why the file could not be read, or null} the custom arrowheads, listed after the built-in ones in the Stroke panel's arrowhead menus", + "{} → {arrowheads: [{name (stroke.set `startArrow`/`endArrow` as {custom: name}), reach, halfWidth (in head weights)}], file: the arrowheads file's path or null (no file here, as on the web, or the file is outside the automation read roots), skipped: [{name, reason}] symbols of the file that are not heads, error: why the file could not be read (naming the file by its file name outside the read roots), or null} the custom arrowheads, listed after the built-in ones in the Stroke panel's arrowhead menus", always, list ), @@ -46,7 +46,7 @@ pub fn specs() -> Vec { "Edit Arrowheads", [], None, - "{} open the arrowheads file (a native document next to the preferences; created first with one example head when it is missing). Each symbol in it is one custom arrowhead named after the symbol: it points right, its registration point is the tip, and its height is drawn as wide as the built-in heads; its visible fills and outlined strokes make the head. Saving the file reloads the heads → {path, created: whether the file was made now}", + "{} open the arrowheads file (a native document next to the preferences; created first with one example head when it is missing). Each symbol in it is one custom arrowhead named after the symbol: it points right, its registration point is the tip, and its height is drawn as wide as the built-in heads; its visible fills and outlined strokes make the head. Saving the file reloads the heads. Under automation read roots, a file outside them is an error, and nothing is made or opened → {path, created: whether the file was made now}", has_file, edit ), @@ -55,7 +55,7 @@ pub fn specs() -> Vec { "Reload Arrowheads", [], None, - "{} read the arrowheads file again (a save of it from VectorCraft does this already) → {count, skipped: [{name, reason}]}", + "{} read the arrowheads file again (a save of it from VectorCraft does this already; under automation read roots, a file outside them is an error and is not read) → {count, skipped: [{name, reason}]}", has_file, reload ), @@ -409,13 +409,36 @@ fn skipped(s: &Session) -> Vec { s.arrowheads.skipped.iter().map(|(name, reason)| json!({"name": name, "reason": reason})).collect() } +/// The arrowheads file at `path` checked for reading against the automation roots in force: an agent +/// confined to read roots reaches the file only inside them. The error names the file by its file +/// name outside them. +fn may_reach(path: &str) -> Result<()> { + crate::file_access::check_read(path).map_err(|e| super::fileio::naming_in_error(EngineError::Other(e), path)) +} + +/// `msg`, an error about the arrowheads file at `path`, as the request being served may see it: the +/// file named whole inside the read roots, else by its file name. +fn shown_error(msg: &str, path: Option<&str>) -> String { + let Some(path) = path else { return msg.to_string() }; + match super::fileio::naming_in_error(EngineError::Other(msg.to_string()), path) { + EngineError::Other(m) => m, + e => e.to_string(), + } +} + fn list(s: &mut Session, _: &Value) -> Result { let heads: Vec = s.arrowheads.heads.iter().map(|h| json!({"name": h.name, "reach": h.reach(), "halfWidth": h.half_width()})).collect(); - Ok(json!({"arrowheads": heads, "file": s.arrowheads.path, "skipped": skipped(s), "error": s.arrowheads.error})) + let path = s.arrowheads.path.as_deref(); + let file = path.filter(|p| crate::file_access::check_read(p).is_ok()); + let error = s.arrowheads.error.as_deref().map(|e| shown_error(e, path)); + Ok(json!({"arrowheads": heads, "file": file, "skipped": skipped(s), "error": error})) } fn reload(s: &mut Session, _: &Value) -> Result { const C: &str = "stroke.arrowheads.reload"; + if let Some(path) = &s.arrowheads.path { + may_reach(path)?; + } s.reload_arrowheads(); if let Some(e) = &s.arrowheads.error { return Err(bad(C, e.clone())); @@ -426,8 +449,11 @@ fn reload(s: &mut Session, _: &Value) -> Result { fn edit(s: &mut Session, _: &Value) -> Result { const C: &str = "stroke.arrowheads.edit"; let path = s.arrowheads.path.clone().ok_or_else(|| bad(C, "no arrowheads file here"))?; + // Checked before anything is made, brought to the front or opened. + may_reach(&path)?; if let Some(dir) = std::path::Path::new(&path).parent() { - std::fs::create_dir_all(dir).map_err(|e| bad(C, format!("{}: {e}", dir.display())))?; + let dir = dir.to_string_lossy(); + std::fs::create_dir_all(&*dir).map_err(|e| super::fileio::naming_in_error(bad(C, format!("{dir}: {e}")), &dir))?; } // Made only when no file is there, also when another run makes one at the same moment. let bytes = vectorcraft_format::save_file(&starter()); @@ -446,7 +472,8 @@ fn edit(s: &mut Session, _: &Value) -> Result { s.set_active(i); } None => { - crate::file_access::unconfined(|| s.execute("document.open", &json!({ "path": path })))?; + // Opened in the request's own scope, so the document keeps the roots it was opened under. + s.execute("document.open", &json!({ "path": path }))?; } } Ok(json!({"path": path, "created": created})) diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index 6c75eae128..c94de5d3b2 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -90,7 +90,7 @@ pub fn specs() -> Vec { "Gamut Warning", [], None, - "{ids?|id?, colors?: [color] (#rrggbbaa and #rgba are refused)} colours that can't be printed in the working CMYK (selection, or the whole document when nothing is selected) → {checked, outOfGamut: [{hex, deltaE, count}]}", + "{ids?|id?, colors?: [color] (#rrggbbaa and #rgba are refused)} colors that can't be printed in the document's assigned CMYK profile, else the working CMYK (selection, or the whole document when nothing is selected) → {checked, outOfGamut: [{hex, deltaE, count}]}", has_doc, gamut_check ), diff --git a/crates/engine/src/cmd/docinfo.rs b/crates/engine/src/cmd/docinfo.rs index a43325becd..a9fb07bdf8 100644 --- a/crates/engine/src/cmd/docinfo.rs +++ b/crates/engine/src/cmd/docinfo.rs @@ -18,7 +18,7 @@ pub fn specs() -> Vec { "Document Info", ["Window", "Document Info"], None, - "{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), images, swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient with a stop above opacity 0, at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else Linear gradient, Radial gradient or Freeform gradient; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone", + "{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), images, swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient with a stop above opacity 0, at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else Linear gradient, Radial gradient or Freeform gradient; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone. brushNames, brushes, spotObjects, patternObjects and gradientObjects leave out hidden objects, objects at an opacity of 0 and the objects inside a hidden group or layer or one at an opacity of 0 (with selectionOnly too), their characters' paints and colorized images included; objects still counts them as paths, groups and the other kinds", has_doc, info ), @@ -425,6 +425,64 @@ fn applied_brushes(d: &Document, n: &Node, members: &HashSet<*const Node>) -> Ve if follows { used } else { vec![] } } +/// Whether `n` draws, as far as its own state goes: a hidden object, and an object at an opacity +/// of 0, paint no color, and neither do their members. +fn draws(n: &Node) -> bool { + n.visible && n.opacity > 0.0 +} + +/// The object of `d` at index path `path`, with whether the groups and layers around it draw +/// ([`draws`]). +fn node_and_drawn<'a>(d: &'a Document, path: &[usize]) -> Option<(&'a Node, bool)> { + let (first, rest) = path.split_first()?; + let mut at: &Node = d.layers.get(*first)?; + let mut drawn = true; + for &i in rest { + drawn &= draws(at); + at = &**at.children()?.get(i)?; + } + Some((at, drawn)) +} + +/// The spot colors, the patterns and the gradients (`spots`: [`spot_swatches`]) that object `n` +/// paints, each once: those of its own fills and strokes ([`own_paints`], `members` included), of +/// its drawn characters and, for a grayscale or 1-bit image, of the color it is colorized with. +fn object_paints(d: &Document, spots: &HashSet<&str>, members: &HashSet<*const Node>, n: &Node) -> [Vec; 3] { + let (spot, pattern, gradient) = (|p: &Paint| spot_labels(spots, p), one_label(pattern_label), one_label(gradient_label)); + let labels: [&PaintNames<'_>; 3] = [&spot, &pattern, &gradient]; + let painted_runs = painted_runs(d, spots, n); + let mut used = labels.map(|label| own_paints(d, n, members, painted_runs.as_ref(), label)); + // The characters' own paints: an inline graphic draws no outline and does not take its run's + // paint (a list marker set in its run does), and a stroke with no width paints nothing. + if let Some((t, painted)) = &painted_runs { + for run in painted.iter().filter_map(|i| t.runs.get(*i)) { + let stroke = (run.style.stroke_width > 0.0).then_some(&run.style.stroke); + for paint in std::iter::once(&run.style.fill).chain(stroke) { + for (used, label) in used.iter_mut().zip(labels) { + for name in label(paint) { + if !used.contains(&name) { + used.push(name); + } + } + } + } + } + } + // A grayscale or 1-bit image colorized with a spot color prints it, while its pixels take the + // color, as the renderer draws it. + if let NodeKind::Image(im) = &n.kind + && let Some(colorize) = n.extras().colorize.as_deref() + && d.image_blob(im).is_some_and(|b| b.takes_colorize()) + { + for name in spot(colorize) { + if !used[0].contains(&name) { + used[0].insert(0, name); + } + } + } + used +} + fn info(s: &mut Session, p: &Value) -> Result { const C: &str = "document.info"; let category = str_param(p, "category"); @@ -440,8 +498,13 @@ fn info(s: &mut Session, p: &Value) -> Result { let st = s.doc()?; let d = &st.doc; let selection_only = bool_or(p, "selectionOnly", false); - let roots: Vec<&Node> = - if selection_only { st.selection.objects.iter().filter_map(|id| d.node(*id)).collect() } else { d.layers.iter().map(|l| &**l).collect() }; + // Each root with whether the groups and layers around it draw: a selected object inside a hidden group or layer, or one + // at an opacity of 0, paints nothing. + let roots: Vec<(&Node, bool)> = if selection_only { + st.selection.objects.iter().filter_map(|id| node_and_drawn(d, &d.index_path(*id)?)).collect() + } else { + d.layers.iter().map(|l| (&**l, true)).collect() + }; let mut counts: BTreeMap<&str, usize> = BTreeMap::new(); // The paths' total length, as Document Info › Objects shows it (the length of a cut line, a // strip of LEDs along the letters, #1958). @@ -467,7 +530,6 @@ fn info(s: &mut Session, p: &Value) -> Result { let mut spot_objects: Vec = vec![]; let mut spot_rows: Vec<(String, String)> = vec![]; let mut spot = BTreeSet::new(); - let (spot_label, pattern, gradient) = (|p: &Paint| spot_labels(&spot_swatches, p), one_label(pattern_label), one_label(gradient_label)); let mut styles: Vec<&str> = if selection_only { vec![] } else { d.graphic_styles.iter().map(|g| g.name.as_str()).collect() }; // `library` holds the Brushes panel's brushes, and `brushes` the brushes the visited objects' strokes draw with, each once, // in walk order. @@ -494,10 +556,18 @@ fn info(s: &mut Session, p: &Value) -> Result { members.extend(children.iter().map(|c| std::ptr::from_ref(&**c))); } }); - for r in roots { - r.walk(&mut |n| { + // Depth first, in paint order, as `Node::walk` visits: each object with whether it and the groups and layers around it + // draw. An object that does not draw is still counted, and its members are visited. + let mut stack: Vec<(&Node, bool)> = vec![]; + for (r, drawn) in roots { + stack.push((r, drawn)); + while let Some((n, around)) = stack.pop() { if !seen.insert(std::ptr::from_ref(n)) { - return; + continue; + } + let drawn = around && draws(n); + if let Some(ch) = n.children() { + stack.extend(ch.iter().rev().map(|c| (&**c, drawn))); } let k = match &n.kind { // The Guides row counts paths made into guides; ruler guides are not objects. @@ -545,42 +615,8 @@ fn info(s: &mut Session, p: &Value) -> Result { if let Some(k) = k { *counts.entry(k).or_default() += 1; } - // The spot colors, the patterns and the gradients this object's fills and strokes paint, each once. - let painted_runs = painted_runs(d, &spot_swatches, n); - let mut used_spots = own_paints(d, n, &members, painted_runs.as_ref(), &spot_label); - let mut used_patterns = own_paints(d, n, &members, painted_runs.as_ref(), &pattern); - let mut used_gradients = own_paints(d, n, &members, painted_runs.as_ref(), &gradient); - // The characters' own paints: an inline graphic draws no outline and does not take its - // run's paint (a list marker set in its run does), and a stroke with no width paints - // nothing. - if let Some((t, painted)) = &painted_runs { - for run in painted.iter().filter_map(|i| t.runs.get(*i)) { - let stroke = (run.style.stroke_width > 0.0).then_some(&run.style.stroke); - for paint in std::iter::once(&run.style.fill).chain(stroke) { - let labels: [(&mut Vec, &PaintNames<'_>); 3] = - [(&mut used_spots, &spot_label), (&mut used_patterns, &pattern), (&mut used_gradients, &gradient)]; - for (used, label) in labels { - for name in label(paint) { - if !used.contains(&name) { - used.push(name); - } - } - } - } - } - } - // A grayscale or 1-bit image colorized with a spot color prints it, while its pixels take - // the color, as the renderer draws it. - if let NodeKind::Image(im) = &n.kind - && let Some(colorize) = n.extras().colorize.as_deref() - && d.image_blob(im).is_some_and(|b| b.takes_colorize()) - { - for name in spot_label(colorize) { - if !used_spots.contains(&name) { - used_spots.insert(0, name); - } - } - } + // The spot colors, the patterns and the gradients this object paints, each once; none when it does not draw. + let [used_spots, used_patterns, used_gradients] = if drawn { object_paints(d, &spot_swatches, &members, n) } else { Default::default() }; // Objects counts the objects that Spot Color Objects, Pattern Objects and Gradient Objects list. if !used_spots.is_empty() { let name = n.display_name(); @@ -615,9 +651,11 @@ fn info(s: &mut Session, p: &Value) -> Result { { styles.push(&g.name); } - for b in applied_brushes(d, n, &members) { - if !brushes.contains(&b) { - brushes.push(b); + if drawn { + for b in applied_brushes(d, n, &members) { + if !brushes.contains(&b) { + brushes.push(b); + } } } if let NodeKind::Repeat(spec) = &n.kind { @@ -625,7 +663,7 @@ fn info(s: &mut Session, p: &Value) -> Result { repeats.push(entry); repeat_rows.push(row); } - }); + } } // The document's fonts include those of the type in opacity masks and in the art of its // symbols and patterns, as Find Font lists them. @@ -1455,6 +1493,115 @@ mod tests { assert_eq!(spots(&mut s), (vec![], None, None)); } + /// Brushes, Spot Color Objects, Pattern Objects and Gradient Objects leave out a hidden object, + /// an object at an opacity of 0 and the objects inside a hidden layer or a group at an opacity of + /// 0, with Selection Only too: their fills, strokes, characters and colorized pixels paint no + /// color. Objects still counts them. + #[test] + fn info_skips_paints_on_hidden_and_clear_objects_and_their_members() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + s.execute("swatch.new", &json!({"name": "Ink", "color": {"model": "cmyk", "c": 0, "m": 1, "y": 1, "k": 0}, "spot": true})).unwrap(); + let square = |s: &mut Session, x: f64| { + s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap() + }; + let tile = square(&mut s, 0.0); + s.execute("object.pattern.make", &json!({"ids": [tile], "name": "Dots", "edit": false})).unwrap(); + // A patterned square that stays drawn, an object at an opacity of 0 and a hidden one. + let (shown, clear, hidden) = (square(&mut s, 20.0), square(&mut s, 40.0), square(&mut s, 60.0)); + s.execute("paint.setFill", &json!({"ids": [shown, clear], "swatch": "Dots"})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [hidden], "swatch": "Ink"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [shown, clear, hidden], "none": true})).unwrap(); + // A brushed square in a group. + let (brushed, other) = (square(&mut s, 80.0), square(&mut s, 100.0)); + s.execute("brush.apply", &json!({"ids": [brushed], "name": "Charcoal"})).unwrap(); + s.execute("select.set", &json!({"ids": [brushed, other]})).unwrap(); + let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + // Type whose characters are filled with the spot color. + let word = s.execute("text.create", &json!({"x": 0, "y": 200, "text": "Hi"})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({"ids": [word], "swatch": "Ink"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [word], "none": true})).unwrap(); + // A grayscale image colorized with the spot color. + let mut bytes = Vec::new(); + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(2, 1, vec![0, 255]).unwrap()) + .write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png) + .unwrap(); + let image = s + .edit("Place", |d, sel| { + d.images.insert("gray".into(), vectorcraft_doc::ImageBlob::png(bytes)); + let id = d.alloc_id(); + let im = vectorcraft_doc::ImageObject { + key: "gray".into(), + width: 2, + height: 1, + xf: Default::default(), + link: None, + placement: Default::default(), + pixels: None, + }; + d.insert(d.default_layer(), 0, Node::new(id, NodeKind::Image(Box::new(im))))?; + sel.set([id]); + Ok(id) + }) + .unwrap(); + s.execute("paint.setFill", &json!({"swatch": "Ink"})).unwrap(); + // A square with a gradient on a layer of its own. + let layer = s.execute("layer.new", &json!({"name": "Back"})).unwrap()["id"].as_u64().unwrap(); + let ramp = square(&mut s, 120.0); + s.execute( + "paint.setFill", + &json!({"ids": [ramp], "gradient": {"kind": "linear", "stops": [{"offset": 0, "color": "#000"}, {"offset": 1, "color": "#fff"}]}}), + ) + .unwrap(); + s.execute("paint.setStroke", &json!({"ids": [ramp], "none": true})).unwrap(); + let listed = |s: &mut Session, p: Value| { + let i = s.execute("document.info", &p).unwrap(); + let ids = |k: &str| -> Vec { + let mut ids: Vec = i[k].as_array().unwrap().iter().map(|o| o["id"].as_u64().unwrap()).collect(); + ids.sort_unstable(); + ids + }; + (i["brushNames"].clone(), ids("spotObjects"), ids("patternObjects"), ids("gradientObjects"), i["objects"].clone()) + }; + // Everything drawn: each object is listed. + let (brushes, spots, patterns, gradients, before) = listed(&mut s, json!({})); + assert_eq!(brushes, json!(["Charcoal"])); + // New squares take the new spot color as their fill, the group's members included. + assert_eq!((spots, patterns, gradients), (vec![hidden, brushed, other, word, image.0], vec![shown, clear], vec![ramp])); + s.edit("hide", |d, _| { + d.node_mut(NodeId(clear)).unwrap().opacity = 0.0; + d.node_mut(NodeId(hidden)).unwrap().visible = false; + d.node_mut(NodeId(group)).unwrap().opacity = 0.0; + d.node_mut(NodeId(word)).unwrap().opacity = 0.0; + d.node_mut(image).unwrap().opacity = 0.0; + d.node_mut(NodeId(layer)).unwrap().visible = false; + Ok(()) + }) + .unwrap(); + let (brushes, spots, patterns, gradients, after) = listed(&mut s, json!({})); + assert_eq!((brushes, spots, patterns, gradients), (json!([]), vec![], vec![shown], vec![])); + // Objects counts the listed objects, and every object as before. + assert_eq!((after["spots"].clone(), after["patterns"].clone(), after["gradients"].clone()), (Value::Null, json!(1), Value::Null)); + for k in ["paths", "groups", "textObjects", "images"] { + assert_eq!(after[k], before[k], "{k}: {after}"); + } + let rows = s.execute("document.info", &json!({"category": "brushes"})).unwrap()["sections"][0]["rows"].clone(); + assert_eq!(rows, json!([])); + // Selection Only: an object selected inside a group at an opacity of 0 or a hidden layer paints nothing either. + s.execute("select.set", &json!({"ids": [brushed, ramp]})).unwrap(); + let (brushes, _, _, gradients, after) = listed(&mut s, json!({"selectionOnly": true})); + assert_eq!((brushes, gradients, after["paths"].clone()), (json!([]), vec![], json!(2))); + // Drawn again, the group's brush and the layer's gradient are listed. + s.edit("show", |d, _| { + d.node_mut(NodeId(group)).unwrap().opacity = 1.0; + d.node_mut(NodeId(layer)).unwrap().visible = true; + Ok(()) + }) + .unwrap(); + let (brushes, _, _, gradients, _) = listed(&mut s, json!({"selectionOnly": true})); + assert_eq!((brushes, gradients), (json!(["Charcoal"]), vec![ramp])); + } + /// Document Info › Objects counts an object with a gradient or a pattern on both its fill and /// its stroke once, and with Selection Only a selection that holds a group and an object inside /// it counts that object once. diff --git a/crates/engine/src/cmd/expand.rs b/crates/engine/src/cmd/expand.rs index 352e520433..d4a6c60802 100644 --- a/crates/engine/src/cmd/expand.rs +++ b/crates/engine/src/cmd/expand.rs @@ -634,7 +634,9 @@ pub(crate) fn reshaped(doc: &Document, l: &Node) -> Option { if carry.moves(&m.appearance) { carry.apply(&mut m.appearance); } - // So do the raster effects of its fills and strokes. + // So do the raster effects of it and of its fills and strokes, by the Transform effects that + // moved it. + carry.hide_skipped(&mut m.appearance.effects); vectorcraft_render::effects::follow_items(&mut m); m.appearance.effects = without_geometry(&m.appearance.effects); Some(m) @@ -662,7 +664,8 @@ pub(crate) fn fill_shape( if carry.moves(&one) { carry.apply(&mut one); } - let moved = one.items.pop().unwrap_or_else(|| item.clone()); + let mut moved = one.items.pop().unwrap_or_else(|| item.clone()); + carry.hide_skipped(moved.effects_mut()); Some((with_path(l, outline.clone()), outline, b, moved)) } @@ -1388,8 +1391,9 @@ fn band_edges(lo: f64, hi: f64, n: usize, runs: Option<(f64, usize)>) -> Vec Vec<(f64, (Color, f32))> { let at = |t: f64| (t, g.sample_keep_model(t as f32)); let mut v = vec![at(t0)]; - // A Perceptual gradient curves between its stops: the mesh takes a column at each of the stops - // its expansion adds, so the linear mix between columns follows that curve. + // A Perceptual gradient, or one mixed around the hue wheel, curves between its stops: the mesh + // takes a column at each of the stops its expansion adds, so the linear mix between columns + // follows that curve. if !g.method.is_classic() { v.extend(g.expanded().map(|(o, ..)| f64::from(o)).filter(|o| *o > t0 && *o < t1).map(at)); } diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 333db1c68f..9154ce7ee5 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -69,8 +69,8 @@ pub use dxf::{UNSUPPORTED, Unsupported, unsupported}; pub use encode::{ARTBOARD_PARAMS, ArtboardPick, Encoded, Note, NoteKind, encode, encode_all, encode_with_notes, encode_with_warnings, note_texts}; pub(crate) use encode::{anti_alias, background, with_single_artboard}; pub(crate) use export::with_artboard_fills; -pub(crate) use export::{export_crop, isolated}; -pub use export::{export_doc, export_source}; +pub(crate) use export::{EXPORT_PARAMS, export_crop, isolated}; +pub use export::{export_doc, export_source, unused_option_notes}; use load::err; pub(crate) use load::import_svg; pub(crate) use load::is_placeholder; diff --git a/crates/engine/src/cmd/fileio/batch.rs b/crates/engine/src/cmd/fileio/batch.rs index 0974934ded..5863dd4ff7 100644 --- a/crates/engine/src/cmd/fileio/batch.rs +++ b/crates/engine/src/cmd/fileio/batch.rs @@ -80,10 +80,12 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { /// document's last artboard, the last one; a Paste in Place, in Front or in Back step that names /// `artboards` keeps them, and one that names neither, while the Artboard tool is chosen with /// several artboards selected, pastes on those. A Fit to Artwork Bounds step that names neither -/// `index` nor `indices`, while the Artboard tool is chosen with several artboards selected when the -/// step runs, gets those as its `indices`, which its journal entry records. Otherwise a step that -/// resizes the active artboard ([`crate::FIT_ACTIVE_ARTBOARD`]) and names no `index` (nor -/// `indices`, for Fit to Artwork Bounds) gets that artboard as its `index`. +/// `index` nor `indices`, while the Artboard tool is chosen with two or more artboards selected when +/// the step runs, gets those as its `indices`. Otherwise a step that resizes the active artboard +/// ([`crate::FIT_ACTIVE_ARTBOARD`]) and names no `index` (nor `indices`, for Fit to Artwork Bounds) +/// gets that artboard as its `index`. A Fit to Artwork Bounds step that still names neither gets +/// `index` 0, the command's default. A Fit to Artwork Bounds step's journal entry records the +/// `indices` or `index` it got. /// `grouped` gets each step's undo groups, as [`Session::batch_steps`] keeps them. fn run_steps( s: &mut Session, @@ -104,7 +106,8 @@ fn run_steps( if s.active().is_some() { s.begin_interaction(label)?; } - let mut params = c.get("params").cloned().unwrap_or(json!({})); + // `"params": null` reads as no params, so the artboards below can still be added. + let mut params = c.get("params").filter(|v| !v.is_null()).cloned().unwrap_or(json!({})); let key = if crate::ON_ACTIVE_ARTBOARD.contains(&id.as_str()) { Some("artboard") } else { @@ -115,12 +118,9 @@ fn run_steps( let names_artboards = id.starts_with("edit.pasteIn") && (params.get("artboards").is_some() || (params.get("artboard").is_none() && !crate::cmd::edit::artboard_tool_picks(s).is_empty())); // A Fit to Artwork Bounds step that names neither `index` nor `indices`, while the Artboard - // tool is chosen with several artboards selected, fits those, as the command does on its own. - let fit_picks = if id == "artboard.fitToArt" && params.get("index").is_none() && params.get("indices").is_none() { - crate::cmd::edit::artboard_tool_picks(s) - } else { - Vec::new() - }; + // tool is chosen with two or more artboards selected, fits those. + let fit_unnamed = id == "artboard.fitToArt" && params.get("index").is_none() && params.get("indices").is_none(); + let fit_picks = if fit_unnamed { crate::cmd::edit::artboard_tool_picks(s) } else { Vec::new() }; if !fit_picks.is_empty() && let Some(o) = params.as_object_mut() { @@ -136,6 +136,15 @@ fn run_steps( { o.insert(key.into(), json!(usize::try_from(a).map_or(last, |a| a.min(last)))); } + // With neither, the step fits the command's default, the first artboard, named here so the + // journal records it. + if fit_unnamed + && params.get("index").is_none() + && params.get("indices").is_none() + && let Some(o) = params.as_object_mut() + { + o.insert("index".into(), json!(0)); + } // The documents with an undo group open, held so that the step's first edit in one copies it. let start = s.active().map(|d| d.uid); let held: Vec<(u64, Arc)> = s.docs.iter().filter(|st| st.undo_group.is_some()).map(|st| (st.uid, st.doc.clone())).collect(); @@ -147,8 +156,9 @@ fn run_steps( grouped.push(step_groups(s, start, &held)); // The step's journal entry records what it took from the preferences or the clock (a // save's date, a new document's), as a command of its own would, and the artboards a Fit to - // Artwork Bounds step took from the Artboard tool. - if (noted != params || !fit_picks.is_empty()) + // Artwork Bounds step took from the Artboard tool, the batch or the command's default, so a + // replay does not fit the artboards the Artboard tool has selected then. + if (noted != params || fit_unnamed) && let Some(c) = c.as_object_mut() { c.insert("params".into(), noted); diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index 9e95948def..5abe3e879c 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -27,7 +27,7 @@ pub fn specs() -> Vec { "Serialize Document", [], None, - "{format?: vectorcraft (default)|template|svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd (ait, a .ait template, is written by file.saveAsTemplate), …the format's options (see document.formats; SVG ones also as svg: {…}), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own)} → {text, warnings} for svg (plus dataBase64, the file, when its encoding isn't UTF-8), else {dataBase64, warnings}; an SVG of several artboards also gives files: [{name, text}], linked images linked: [{name, dataBase64}]. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is ignored", + "{format?: vectorcraft (default)|template|svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd (ait, a .ait template, is written by file.saveAsTemplate), …the format's options (see document.formats; SVG ones also as svg: {…}), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own)} → {text, warnings} for svg (plus dataBase64, the file, when its encoding isn't UTF-8), else {dataBase64, warnings}; an SVG of several artboards also gives files: [{name, text}], linked images linked: [{name, dataBase64}]. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it", has_doc, export::serialize ), @@ -36,7 +36,7 @@ pub fn specs() -> Vec { "Export Document", [], None, - "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin., which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as .html / .map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the visible art), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is ignored. Never changes the document's path", + "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin., which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as .html / .map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the visible art), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Never changes the document's path", has_doc, export::export ), @@ -45,7 +45,7 @@ pub fn specs() -> Vec { "Export Selection…", ["File"], None, - "{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|hpgl|vectorcraft|template (default: from the extension, else png), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), …the format's options} the selected objects (template layers left out), each in the layers and groups that hold it, whose clipping paths, opacity masks, effects, opacity and blend modes apply as on the canvas (an object of a blend, envelope, repeat or intertwine on its own; txt: the selected type alone), cropped to the bounds the renderer measures for that art (a clip group by its clip) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is ignored", + "{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|hpgl|vectorcraft|template (default: from the extension, else png), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), …the format's options} the selected objects (template layers left out), each in the layers and groups that hold it, whose clipping paths, opacity masks, effects, opacity and blend modes apply as on the canvas (an object of a blend, envelope, repeat or intertwine on its own; txt: the selected type alone), cropped to the bounds the renderer measures for that art (a clip group by its clip) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it", has_selection, export::export_selection ), @@ -108,7 +108,7 @@ pub fn specs() -> Vec { "Batch", [], None, - "{label?, commands: [{command, params}], artboard?: index (the active artboard; the app passes it: each edit.pasteInPlace, edit.pasteInFront, edit.pasteInBack, object.align, object.distribute, object.distributeSpacing, select.allOnArtboard or symbol.edit step that names none gets it, and each artboard.fitToArt or artboard.fitToSelection step that names no index gets it as index, or the last artboard of a document with fewer; an artboard.fitToArt step that names neither index nor indices, while the Artboard tool is chosen with several artboards selected when the step runs, gets those as indices instead, and the journal records them)} run several commands as ONE undo step (one in each document they edit: steps may open, switch, close or revert documents); stops at the first error and rolls everything back, documents included", + "{label?, commands: [{command, params}], artboard?: index (the active artboard; the app passes it: each edit.pasteInPlace, edit.pasteInFront, edit.pasteInBack, object.align, object.distribute, object.distributeSpacing, select.allOnArtboard or symbol.edit step that names none gets it, and each artboard.fitToArt or artboard.fitToSelection step that names no index gets it as index, or the last artboard of a document with fewer; an artboard.fitToArt step that names neither index nor indices, while the Artboard tool is chosen with two or more artboards selected when the step runs, gets those as indices instead; the journal records the indices or index an artboard.fitToArt step got)} run several commands as ONE undo step (one in each document they edit: steps may open, switch, close or revert documents); stops at the first error and rolls everything back, documents included", has_doc, batch::batch ), diff --git a/crates/engine/src/cmd/fileio/export.rs b/crates/engine/src/cmd/fileio/export.rs index 19e496306f..1ae96c6f81 100644 --- a/crates/engine/src/cmd/fileio/export.rs +++ b/crates/engine/src/cmd/fileio/export.rs @@ -15,8 +15,45 @@ use super::{ ARTBOARD_PARAMS, Format, default_name, encode_all, encode_with_warnings, merge, with_black_output, writable, write_encoded, write_or_return, }; +/// The keys the export commands take for every format, beside the path, the format and the +/// options `document.formats` lists for each: `richBlack` is Appearance of Black's setting for a +/// raster export, and `params` an exporter plug-in's own. +pub(crate) const EXPORT_PARAMS: [&str; 4] = ["includeArtboardFill", "selectedOnly", "richBlack", "params"]; + +/// A note for each option in `p` that some format takes but the file an export of `cmd` writes in +/// `f` doesn't read (`{format: pdf, quality: 80}`), in the wording of a save's note. An exporter +/// plug-in's format gets none. The notes cover the formats' options only: a key of the command's +/// own ([`EXPORT_PARAMS`]) and an artboard choice that a selection export leaves out get none. +pub fn unused_option_notes(cmd: &str, f: &Format, p: &Value) -> Vec { + let Some(given) = p.as_object() else { return Vec::new() }; + if vectorcraft_plugins::export::by_format(f.id).is_some() { + return Vec::new(); + } + let listed = |k: &str| super::FORMATS.iter().filter(|f| f.write).flat_map(|f| f.options).any(|o| o.name == k); + let written = super::save::written_as(cmd, f, p); + let legacy = f.id == "ai" && super::legacy_ai::wanted(cmd, f, p).unwrap_or(false); + let reads = |k: &str| match (f.id, k) { + // A legacy `.ai` file is not a PDF: it reads its own options only. + ("ai", _) if legacy => super::legacy_ai::reads(k), + // The other `.ai` files don't read the legacy file's options, and `preserveEditing` is + // on for them whatever is given. + ("ai", "preserveEditing") => false, + ("ai", _) if super::legacy_ai::LEGACY_ONLY.contains(&k) => false, + // An export writes one file: only a save writes each artboard to a file of its own, and + // a native file's `range` names those files. + ("vectorcraft" | "template" | "ai", "separateArtboards") | ("vectorcraft" | "template", "range") => false, + _ => super::save::reads_option(f, k), + }; + given + .iter() + .filter(|(k, v)| !v.is_null() && !EXPORT_PARAMS.contains(&k.as_str()) && listed(k) && !reads(k)) + .map(|(k, _)| super::save::unused_option_note(k, &written)) + .collect() +} + pub(super) fn serialize(s: &mut Session, p: &Value) -> Result { let f = writable("document.serialize", Some(text_param(p, "format", "document.serialize")?.unwrap_or("vectorcraft")), None)?; + let unused = unused_option_notes("document.serialize", f, p); let expanded = expand_presets(s, "document.serialize", p)?; let p = with_black_output(s, &expanded); let (doc, display_doc_title) = source(s, f, &p, "document.serialize")?; @@ -27,7 +64,8 @@ pub(super) fn serialize(s: &mut Session, p: &Value) -> Result { { o.insert("_displayDocTitle".into(), json!(display_doc_title)); } - let enc = encode_all(doc, f.id, &q)?; + let mut enc = encode_all(doc, f.id, &q)?; + enc.add_setting_notes(unused); let files = enc.named(doc, &default_name(doc, f.extensions[0])); let (main, linked) = files.split_at(enc.files.len()); // Text formats come back as text; an SVG in UTF-16 or ISO 8859-1 also as its bytes. @@ -58,6 +96,7 @@ pub(super) fn export(s: &mut Session, p: &Value) -> Result { super::check_not_lossy_overwrite(s.doc()?, path, p, "document.export")?; } let f = writable("document.export", text_param(p, "format", "document.export")?, path)?; + let unused = unused_option_notes("document.export", f, p); let expanded = expand_presets(s, "document.export", p)?; let p = with_black_output(s, &expanded); let (doc, display_doc_title) = source(s, f, &p, "document.export")?; @@ -68,7 +107,8 @@ pub(super) fn export(s: &mut Session, p: &Value) -> Result { { o.insert("_displayDocTitle".into(), json!(display_doc_title)); } - let enc = encode_all(doc, f.id, &q)?; + let mut enc = encode_all(doc, f.id, &q)?; + enc.add_setting_notes(unused); write_encoded(path, &default_name(doc, f.extensions[0]), doc, &enc, json!({ "format": f.id, "warnings": enc.notes() })) } @@ -315,12 +355,18 @@ pub(super) fn export_selection(s: &mut Session, p: &Value) -> Result { super::check_not_lossy_overwrite(s.doc()?, path, p, C)?; } let f = writable(C, text_param(p, "format", C)?, path)?; + let unused = unused_option_notes(C, f, p); let expanded = expand_presets(s, C, p)?; let p = with_black_output(s, &expanded); let (d, bounds) = selection(s, C, f.id == "txt")?; // The encoder's warnings (options accepted but not applied, features approximated or left // out), as document.export reports them. - let (bytes, warnings) = encode_with_warnings(&d, f.id, &without_artboards(&p))?; + let (bytes, mut warnings) = encode_with_warnings(&d, f.id, &without_artboards(&p))?; + for note in unused { + if !warnings.contains(¬e) { + warnings.push(note); + } + } write_or_return(path, &bytes, json!({ "format": f.id, "warnings": warnings, "bounds": [bounds.x0, bounds.y0, bounds.width(), bounds.height()] })) } diff --git a/crates/engine/src/cmd/fileio/legacy_ai.rs b/crates/engine/src/cmd/fileio/legacy_ai.rs index 05b6e03551..23168f1e25 100644 --- a/crates/engine/src/cmd/fileio/legacy_ai.rs +++ b/crates/engine/src/cmd/fileio/legacy_ai.rs @@ -65,6 +65,18 @@ pub(super) fn named(f: &Format) -> Format { Format { label: "legacy .ai (version 7)", ..*f } } +/// The `.ai` options that only a legacy file reads: a PDF-compatible `.ai` file and a `.ai` file +/// without PDF content don't. +pub(super) const LEGACY_ONLY: [&str; 3] = ["transparentImages", "hiddenObjects", "outlineText"]; + +/// Does an export of a legacy file read option `key`? It reads the version, the file's own +/// options ([`LEGACY_ONLY`]), the artboards to write, and `useArtboards`, which the export reads +/// before [`encode`] runs. It reads none of the other `.ai` options and none of the PDF options +/// that a PDF-compatible `.ai` file takes. +pub(super) fn reads(key: &str) -> bool { + matches!(key, "aiVersion" | "useArtboards") || LEGACY_ONLY.contains(&key) || super::ARTBOARD_PARAMS.contains(&key) +} + /// What a legacy `.ai` does with the images it can't hold (`transparentImages`). #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum SeeThrough { diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index 6a2a0986a3..0a306ee1a9 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -317,7 +317,7 @@ pub fn save_plan(s: &Session, mode: SaveMode, p: &Value) -> Result { let notes = top .filter(|k| !reads_option(format, k)) .chain(nested.filter(|k| !reads_option(format, k)).map(|k| format!("options.{k}"))) - .map(|k| format!("`{k}` was not used: {} files don't read it", written.label)) + .map(|k| unused_option_note(&k, &written)) .collect(); let lossy_source = super::lossy_source(st, p); Ok(SavePlan { mode, path, format, options, name, folder, modified, notes, lossy_source }) @@ -467,6 +467,12 @@ pub fn reads_option(f: &Format, key: &str) -> bool { f.options.iter().any(|o| o.name == key) || (is_pdf(f) && (super::pdf::OPTIONS.iter().any(|o| o.name == key) || super::pdf::is_setting(key))) } +/// The note a save or an export gives for option `key`, as the request names it, which the file it +/// writes (`written`, see [`written_as`]) doesn't read. +pub(super) fn unused_option_note(key: &str, written: &Format) -> String { + format!("`{key}` was not used: {} files don't read it", written.label) +} + /// Formats that carry the whole native document: they lose nothing, and record links relative to /// where they are written. A `.ai` or `.ait` file is a PDF carrying it; EPS carries it in comments. fn is_native(f: &Format) -> bool { @@ -636,7 +642,7 @@ fn without_pdf(f: &Format) -> Format { /// `f` named, in its errors and notes, as the file a save with options `p` writes: a version 7 /// `.ai` as the legacy `.ai`, and a `.ai` or `.ait` with `pdfCompatible: false` as one saved /// without PDF content. -fn written_as(cmd: &str, f: &Format, p: &Value) -> Format { +pub(super) fn written_as(cmd: &str, f: &Format, p: &Value) -> Format { if f.id == "ai" && super::legacy_ai::wanted(cmd, f, p).unwrap_or(false) { super::legacy_ai::named(f) } else if matches!(f.id, "ai" | "ait") && !bool_or(p, "pdfCompatible", true) { diff --git a/crates/engine/src/cmd/fileio/tests_exportas.rs b/crates/engine/src/cmd/fileio/tests_exportas.rs index f3566e82ba..cc1345060d 100644 --- a/crates/engine/src/cmd/fileio/tests_exportas.rs +++ b/crates/engine/src/cmd/fileio/tests_exportas.rs @@ -141,6 +141,137 @@ fn what_the_file_loses_comes_before_a_note_on_the_options() { assert_eq!(r["warnings"], json!(w)); } +/// A session with one artboard and a selected rectangle on it. +fn with_art() -> Session { + let mut s = session(60.0, 40.0, 1); + s.execute("shape.rectangle", &json!({"x": 5, "y": 5, "width": 20, "height": 10})).unwrap(); + s +} + +/// The warnings of reply `r` that name an option the file doesn't read. +fn unused(r: &Value) -> Vec { + r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).filter(|w| w.contains("was not used")).map(str::to_string).collect() +} + +/// An option that only another format reads is accepted, and the reply's warnings name it in the +/// words of a save's note; `document.export`, `document.serialize` and `document.exportSelection` +/// give the same note. +#[test] +fn an_option_only_another_format_reads_gets_a_note() { + let (mut s, notes) = (with_art(), unused); + for cmd in ["document.export", "document.serialize", "document.exportSelection"] { + let r = s.execute(cmd, &json!({"format": "pdf", "quality": 80, "outlineText": true})).unwrap(); + assert_eq!( + notes(&r), + ["`outlineText` was not used: PDF files don't read it", "`quality` was not used: PDF files don't read it"], + "{cmd}: {r}" + ); + } + // The format's own options, the keys every export takes and null values get none. + for p in [ + json!({"format": "jpg", "quality": 80, "scale": 2}), + json!({"format": "ai", "compress": true, "compatibility": "1.7"}), + json!({"format": "pdf", "quality": null, "selectedOnly": false, "includeArtboardFill": false, "useArtboards": true}), + json!({"format": "svg", "outlineText": true, "svg": {"decimals": 2}}), + ] { + let r = s.execute("document.export", &p).unwrap(); + assert!(notes(&r).is_empty(), "{p}: {r}"); + } + let r = s.execute("document.serialize", &json!({"format": "png", "compress": true, "marks": {"trim": true}, "svg": {"minify": true}})).unwrap(); + assert_eq!( + notes(&r), + [ + "`compress` was not used: PNG files don't read it", + "`marks` was not used: PNG files don't read it", + "`svg` was not used: PNG files don't read it" + ], + "{r}" + ); + // The note names the kind of file written, as a save's does. + let r = s.execute("document.export", &json!({"format": "ai", "pdfCompatible": false, "quality": 80})).unwrap(); + assert_eq!(notes(&r), ["`quality` was not used: non-PDF-compatible .ai files don't read it"], "{r}"); + let r = s.execute("document.export", &json!({"format": "pdf", "preserveEditing": false, "range": "1"})).unwrap(); + assert!(notes(&r).is_empty(), "{r}"); + let r = s.execute("document.export", &json!({"format": "vectorcraft", "artboard": 0})).unwrap(); + assert_eq!(notes(&r), ["`artboard` was not used: VectorCraft files don't read it"], "{r}"); +} + +/// A legacy `.ai` file reads its own options and the artboards to write, not the other `.ai` +/// options or the PDF options. +#[test] +fn a_legacy_ai_export_notes_the_options_of_the_other_ai_files() { + let (mut s, notes) = (with_art(), unused); + let r = s.execute("document.export", &json!({"format": "ai", "aiVersion": "7", "compress": true, "marks": {"trim": true}})).unwrap(); + assert_eq!( + notes(&r), + ["`compress` was not used: legacy .ai (version 7) files don't read it", "`marks` was not used: legacy .ai (version 7) files don't read it"], + "{r}" + ); + let r = + s.execute("document.export", &json!({"format": "ai", "aiVersion": "7", "outlineText": true, "hiddenObjects": "omit", "range": "1"})).unwrap(); + assert!(notes(&r).is_empty(), "{r}"); + let r = s.execute("document.export", &json!({"format": "ai", "aiVersion": "7", "useArtboards": false})).unwrap(); + assert!(notes(&r).is_empty(), "{r}"); +} + +/// The `.ai` files other than the legacy one don't read the legacy file's own options. +#[test] +fn a_pdf_compatible_ai_export_notes_the_legacy_options() { + let (mut s, notes) = (with_art(), unused); + let unread = json!({"format": "ai", "aiVersion": "pdf", "outlineText": true, "hiddenObjects": "omit", "transparentImages": "omit"}); + let r = s.execute("document.export", &unread).unwrap(); + assert_eq!( + notes(&r), + [ + "`hiddenObjects` was not used: PDF-compatible .ai files don't read it", + "`outlineText` was not used: PDF-compatible .ai files don't read it", + "`transparentImages` was not used: PDF-compatible .ai files don't read it" + ], + "{r}" + ); +} + +/// `preserveEditing` is always on for a `.ai` file, so an export that gives it gets a note. +#[test] +fn an_ai_export_notes_preserve_editing() { + let (mut s, notes) = (with_art(), unused); + let r = s.execute("document.export", &json!({"format": "ai", "preserveEditing": false, "range": "1"})).unwrap(); + assert_eq!(notes(&r), ["`preserveEditing` was not used: PDF-compatible .ai files don't read it"], "{r}"); +} + +/// An export writes one file: only a save writes each artboard to a file of its own, so an export +/// notes `separateArtboards`, and the `range` that names those files for a native file. +#[test] +fn an_export_notes_the_options_that_only_a_save_reads() { + let (mut s, notes) = (with_art(), unused); + let r = s.execute("document.export", &json!({"format": "ai", "separateArtboards": true, "range": "1"})).unwrap(); + assert_eq!(notes(&r), ["`separateArtboards` was not used: PDF-compatible .ai files don't read it"], "{r}"); + for (format, label) in [("vectorcraft", "VectorCraft"), ("template", "VectorCraft Template")] { + let r = s.execute("document.export", &json!({"format": format, "separateArtboards": true, "range": "1", "compress": true})).unwrap(); + assert_eq!( + notes(&r), + [format!("`range` was not used: {label} files don't read it"), format!("`separateArtboards` was not used: {label} files don't read it")], + "{r}" + ); + } +} + +/// The legacy `.ai` options that the notes go by are the ones the `.ai` option table describes as +/// the legacy file's ("with aiVersion 7"), so an option added to the table is not noted as unread +/// on a legacy export by mistake. +#[test] +fn the_legacy_ai_options_are_the_ones_the_option_table_names() { + let described: Vec<&str> = native::AI_OPTIONS.iter().filter(|o| o.description.starts_with("with aiVersion 7")).map(|o| o.name).collect(); + assert_eq!(described, legacy_ai::LEGACY_ONLY); + for key in described.iter().chain(&ARTBOARD_PARAMS).chain(&["aiVersion", "useArtboards"]) { + assert!(legacy_ai::reads(key), "{key}"); + assert!(native::AI_OPTIONS.iter().any(|o| o.name == *key), "{key} is not a .ai option"); + } + for key in ["compress", "pdfCompatible", "separateArtboards", "editingData", "marks"] { + assert!(!legacy_ai::reads(key), "{key}"); + } +} + #[test] fn note_texts_give_the_losses_first_each_kind_in_order() { use super::encode::{Note, note_texts}; diff --git a/crates/engine/src/cmd/fileio/tests_pdfedit.rs b/crates/engine/src/cmd/fileio/tests_pdfedit.rs index 0b560e5e04..b7b0ddde59 100644 --- a/crates/engine/src/cmd/fileio/tests_pdfedit.rs +++ b/crates/engine/src/cmd/fileio/tests_pdfedit.rs @@ -15,9 +15,8 @@ fn open(s: &mut Session, name: &str, bytes: &[u8]) -> Value { s.execute("document.open", &json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(bytes)})).unwrap() } -fn tmp(name: &str) -> String { - let dir = std::env::temp_dir().join(format!("vc-pdfedit-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); +/// The path of `name` in the test's folder `dir`. +fn tmp(dir: &std::path::Path, name: &str) -> String { dir.join(name).to_string_lossy().to_string() } @@ -114,8 +113,9 @@ fn the_legacy_payload_name_is_accepted() { #[test] fn ai_files_are_pdfs_that_save_and_reopen_editable() { + let scratch = vectorcraft_testkit::TempDir::new("pdfedit"); let mut s = rich(); - let path = tmp("art.ai"); + let path = tmp(&scratch, "art.ai"); let r = s.execute("document.save", &json!({"path": path, "preserveEditing": false, "range": "1"})).unwrap(); assert_eq!(r["path"], path.as_str()); // As saved (Save stamps the File Info dates). @@ -134,11 +134,11 @@ fn ai_files_are_pdfs_that_save_and_reopen_editable() { let again = vectorcraft_pdf::editing(&std::fs::read(&path).unwrap()).unwrap(); assert_eq!(vectorcraft_format::load(&again.data).unwrap().layers, s.doc().unwrap().doc.layers); // Save As also writes a plain PDF (the document then saves back as PDF); PNG stays an export. - assert_eq!(s.execute("document.save", &json!({"path": tmp("x.pdf")})).unwrap()["format"], "pdf"); - assert!(s.execute("document.save", &json!({"path": tmp("x.png")})).is_err(), "PNG is written with document.export"); + assert_eq!(s.execute("document.save", &json!({"path": tmp(&scratch, "x.pdf")})).unwrap()["format"], "pdf"); + assert!(s.execute("document.save", &json!({"path": tmp(&scratch, "x.png")})).is_err(), "PNG is written with document.export"); // A plain PDF named .ai opens as artwork, without a path to save over. let plain = b64(&s.execute("document.exportPdf", &json!({"preserveEditing": false})).unwrap()); - let plain_path = tmp("plain.ai"); + let plain_path = tmp(&scratch, "plain.ai"); std::fs::write(&plain_path, plain).unwrap(); let r = s.execute("document.open", &json!({"path": plain_path})).unwrap(); assert_eq!(r["restored"], false); @@ -149,9 +149,10 @@ fn ai_files_are_pdfs_that_save_and_reopen_editable() { /// As does, leaving the document's own path alone. #[test] fn exports_write_ai_as_save_as_does() { + let scratch = vectorcraft_testkit::TempDir::new("pdfedit"); let mut s = rich(); let before = comparable(&s.doc().unwrap().doc); - let path = tmp("exported.ai"); + let path = tmp(&scratch, "exported.ai"); let r = s.execute("document.export", &json!({"path": path})).unwrap(); assert_eq!(r["format"], "ai", "{r}"); let bytes = std::fs::read(&path).unwrap(); @@ -225,12 +226,13 @@ fn ait_templates_open_their_document_untitled() { /// from Template opens it as an untitled copy of the document, layers and art included. #[test] fn save_as_template_writes_an_ait_that_new_from_template_opens_untitled() { + let scratch = vectorcraft_testkit::TempDir::new("pdfedit"); let mut s = rich(); s.execute("layer.new", &json!({"name": "Notes"})).unwrap(); s.execute("shape.ellipse", &json!({"x": 20, "y": 120, "width": 40, "height": 30})).unwrap(); let before = comparable(&s.doc().unwrap().doc); assert_eq!(before.layers.len(), 2); - let path = tmp("brochure template.ait"); + let path = tmp(&scratch, "brochure template.ait"); let r = s.execute("file.saveAsTemplate", &json!({"path": path})).unwrap(); assert_eq!(r["format"], "ait", "{r}"); let bytes = std::fs::read(&path).unwrap(); @@ -253,6 +255,7 @@ fn save_as_template_writes_an_ait_that_new_from_template_opens_untitled() { /// writes a `.ait`. #[test] fn save_as_template_names_its_file_after_the_template_format() { + let scratch = vectorcraft_testkit::TempDir::new("pdfedit"); let mut s = rich(); for (name, format, saved) in [ ("card.png", None, "card.vctemplate"), @@ -261,7 +264,7 @@ fn save_as_template_names_its_file_after_the_template_format() { ("card.pdf", Some("ait"), "card.ait"), ("card v1.2", None, "card v1.2.vctemplate"), ] { - let (typed, want) = (tmp(&format!("named/{name}")), tmp(&format!("named/{saved}"))); + let (typed, want) = (tmp(&scratch, &format!("named/{name}")), tmp(&scratch, &format!("named/{saved}"))); let _ = std::fs::create_dir_all(std::path::Path::new(&typed).parent().unwrap()); let _ = std::fs::remove_file(&typed); let _ = std::fs::remove_file(&want); @@ -273,7 +276,7 @@ fn save_as_template_names_its_file_after_the_template_format() { assert!(ait || vectorcraft_format::load(&bytes).is_ok_and(|d| d.template), "{name}: a native template"); assert!(!std::path::Path::new(&typed).exists(), "{name}: nothing written under the typed name"); } - for (cmd, p) in [("file.saveAs", json!({"format": "ait"})), ("document.save", json!({"path": tmp("card.ait")}))] { + for (cmd, p) in [("file.saveAs", json!({"format": "ait"})), ("document.save", json!({"path": tmp(&scratch, "card.ait")}))] { let e = s.execute(cmd, &p).unwrap_err().to_string(); assert!(e.contains("file.saveAsTemplate") && !e.contains("document.export"), "{cmd}: {e}"); } @@ -284,8 +287,9 @@ fn save_as_template_names_its_file_after_the_template_format() { /// nothing writes keeps its own error. #[test] fn exports_of_an_ait_name_save_as_template() { + let scratch = vectorcraft_testkit::TempDir::new("pdfedit"); let mut s = rich(); - let path = tmp("exported.ait"); + let path = tmp(&scratch, "exported.ait"); let _ = std::fs::remove_file(&path); for (cmd, p) in [ ("document.export", json!({"path": path})), @@ -305,8 +309,9 @@ fn exports_of_an_ait_name_save_as_template() { /// file; `aiVersion` "pdf" writes the PDF-compatible template. #[test] fn save_as_template_refuses_a_legacy_ait() { + let scratch = vectorcraft_testkit::TempDir::new("pdfedit"); let mut s = rich(); - let path = tmp("legacy-ait/card.ait"); + let path = tmp(&scratch, "legacy-ait/card.ait"); let dir = std::path::Path::new(&path).parent().unwrap().to_path_buf(); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); @@ -424,7 +429,8 @@ fn an_ai_of_the_arts_bounds_carries_no_editing_data() { let mut s = art_outside_the_artboards(); let before = comparable(&s.doc().unwrap().doc); let left_out = |v: &Value| v["warnings"].as_array().unwrap().iter().any(|w| w == super::save::AI_EDITING_NEEDS_THE_ARTBOARDS); - let path = tmp("art-bounds.ai"); + let scratch = vectorcraft_testkit::TempDir::new("pdfedit"); + let path = tmp(&scratch, "art-bounds.ai"); for extra in [json!({}), json!({"range": "2"}), json!({"editingData": false}), json!({"path": path})] { let mut params = json!({"format": "ai", "useArtboards": false}); params.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); @@ -670,6 +676,7 @@ fn editing_copy(bytes: &[u8]) -> vectorcraft_doc::Document { /// writes the copy; the version 7 `.ai` keeps the compound path and the clipping group. #[test] fn transparency_clipping_and_opacity_masks_come_back_from_the_editing_copy() { + let scratch = vectorcraft_testkit::TempDir::new("pdfedit"); let mut s = see_through_session(); let before = (*s.doc().unwrap().doc).clone(); // The mask's art is one path, and it reads back as that path. @@ -682,7 +689,7 @@ fn transparency_clipping_and_opacity_masks_come_back_from_the_editing_copy() { assert_eq!(see_through_outline(&editing_copy(&bytes)), want, "{opts}"); } // Each artboard in a file of its own: the first holds all the art. - let path = tmp("see-through.ai"); + let path = tmp(&scratch, "see-through.ai"); let r = s.execute("document.save", &json!({"path": path, "separateArtboards": true})).unwrap(); let files: Vec = r["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap().to_string()).collect(); assert_eq!(files.len(), 3, "{r}"); @@ -812,7 +819,8 @@ fn image_outline(doc: &vectorcraft_doc::Document) -> Vec { /// the linked image keeps its path and its path relative to the document's folder. #[test] fn images_come_back_from_the_editing_copy() { - let dir = tmp("ai-images"); + let scratch = vectorcraft_testkit::TempDir::new("pdfedit"); + let dir = tmp(&scratch, "ai-images"); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(format!("{dir}/art")).unwrap(); let png = |w: u32, h: u32, f: &dyn Fn(u32, u32) -> [u8; 4]| { @@ -882,6 +890,7 @@ fn type_outline(doc: &vectorcraft_doc::Document) -> Vec { /// for other apps alone as type, with every save option that writes the copy. #[test] fn type_comes_back_from_the_editing_copy() { + let scratch = vectorcraft_testkit::TempDir::new("pdfedit"); let mut s = Session::new(); s.execute("file.new", &json!({"width": 300, "height": 200})).unwrap(); s.execute("text.create", &json!({"x": 20, "y": 40, "text": "Hello\nWorld", "size": 24})).unwrap(); @@ -889,7 +898,7 @@ fn type_comes_back_from_the_editing_copy() { // The new type is selected. s.execute("object.rotate", &json!({"angle": 30})).unwrap(); s.execute("text.create", &json!({"x": 20, "y": 120, "text": "Area type in a frame", "area": {"width": 120, "height": 60}})).unwrap(); - let path = tmp("type.ai"); + let path = tmp(&scratch, "type.ai"); s.execute("document.save", &json!({"path": path})).unwrap(); let before = type_outline(&s.doc().unwrap().doc); assert_eq!(before.len(), 3, "{before:#?}"); @@ -971,6 +980,7 @@ fn gradient_session() -> Session { /// gradient. #[test] fn gradients_and_patterns_come_back_from_the_editing_copy() { + let scratch = vectorcraft_testkit::TempDir::new("pdfedit"); let mut s = gradient_session(); let before = (*s.doc().unwrap().doc).clone(); let want = paint_outline(&before); @@ -990,7 +1000,7 @@ fn gradients_and_patterns_come_back_from_the_editing_copy() { let copy = editing_copy(&b64(&r)); assert_eq!(paint_outline(©), want, "{opts}"); } - let path = tmp("gradients.ai"); + let path = tmp(&scratch, "gradients.ai"); let r = s.execute("document.save", &json!({"path": path, "separateArtboards": true})).unwrap(); let files: Vec = r["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap().to_string()).collect(); assert_eq!(files.len(), 3, "{r}"); diff --git a/crates/engine/src/cmd/fileio/tests_pdffidelity.rs b/crates/engine/src/cmd/fileio/tests_pdffidelity.rs index 86cb84cfcb..d3d8a988f8 100644 --- a/crates/engine/src/cmd/fileio/tests_pdffidelity.rs +++ b/crates/engine/src/cmd/fileio/tests_pdffidelity.rs @@ -59,7 +59,7 @@ fn live_texts(s: &Session) -> Vec { #[test] fn pdf_place_keeps_live_text_from_bytes_and_unlinked_paths() { let bytes = live_text_pdf(); - let dir = vectorcraft_testkit::temp_dir("pdf-place-live-text"); + let dir = vectorcraft_testkit::TempDir::new("pdf-place-live-text"); let path = dir.join("text.pdf"); std::fs::write(&path, &bytes).unwrap(); for source in [json!({"name": "text.pdf", "dataBase64": vectorcraft_format::base64_encode(&bytes)}), json!({"path": path, "link": false})] { @@ -71,7 +71,6 @@ fn pdf_place_keeps_live_text_from_bytes_and_unlinked_paths() { assert_eq!(live_texts(&s), ["Second page"], "{r}"); assert!(!r["warnings"].to_string().contains("outlines"), "{r}"); } - std::fs::remove_dir_all(dir).unwrap(); } #[test] diff --git a/crates/engine/src/cmd/fileio/tests_readonly.rs b/crates/engine/src/cmd/fileio/tests_readonly.rs index badf82a8cf..ae9762efc3 100644 --- a/crates/engine/src/cmd/fileio/tests_readonly.rs +++ b/crates/engine/src/cmd/fileio/tests_readonly.rs @@ -9,7 +9,7 @@ use crate::{EngineError, READ_ONLY_LOCATION, Session}; #[test] fn readonly_error_is_typed_and_other_writers_keep_their_error() { - let dir = vectorcraft_testkit::temp_dir("save-refusal"); + let dir = vectorcraft_testkit::TempDir::new("save-refusal"); let path = dir.join("Poster.vectorcraft").to_string_lossy().into_owned(); for kind in [ErrorKind::PermissionDenied, ErrorKind::ReadOnlyFilesystem, ErrorKind::StorageFull, ErrorKind::NotFound, ErrorKind::Other] { let typed = write_save_file_with(&path, &mut |_| Err(io::Error::new(kind, "injected"))).unwrap_err(); @@ -26,7 +26,6 @@ fn readonly_error_is_typed_and_other_writers_keep_their_error() { } assert!(!std::path::Path::new(&path).exists()); } - std::fs::remove_dir_all(dir).unwrap(); } #[test] diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs index 090a7cb46c..18bb3469b9 100644 --- a/crates/engine/src/cmd/gradient.rs +++ b/crates/engine/src/cmd/gradient.rs @@ -24,7 +24,7 @@ pub fn specs() -> Vec { "Gradient", ["Window", "Gradient"], None, - "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual (how the colours between the stops mix: in display RGB, or perceptually (OKLab) so the steps look even; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds), reverse?: bool, dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient", + "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient", has_doc, edit_gradient ), @@ -126,7 +126,11 @@ fn parse_kind(k: &str) -> Parsed { fn method_param(p: &Value) -> Parsed> { match p.get("method") { None | Some(Value::Null) => Ok(None), - Some(v) => v.as_str().and_then(GradientMethod::parse).map(Some).ok_or_else(|| "`method` must be classic or perceptual".into()), + Some(v) => v + .as_str() + .and_then(GradientMethod::parse) + .map(Some) + .ok_or_else(|| "`method` must be classic, perceptual, hue-clockwise or hue-counterclockwise".into()), } } diff --git a/crates/engine/src/cmd/gradpresets.rs b/crates/engine/src/cmd/gradpresets.rs index 29de2210ae..037033ea8a 100644 --- a/crates/engine/src/cmd/gradpresets.rs +++ b/crates/engine/src/cmd/gradpresets.rs @@ -215,7 +215,7 @@ fn apply(s: &mut Session, p: &Value) -> Result { o.insert("stroke".into(), json!(stroke)); o.insert("kind".into(), json!(g.kind.label().to_lowercase())); o.insert("stops".into(), stops_json(&g.stops)); - o.insert("method".into(), json!(g.method.label().to_lowercase())); + o.insert("method".into(), json!(g.method.id())); // A freeform preset takes no spread (paint.editGradient refuses one). if g.kind != vectorcraft_color::GradientKind::Freeform { o.insert("spread".into(), json!(g.spread.label().to_lowercase())); diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index 6a111fb700..e847326e88 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -2276,7 +2276,7 @@ fn series_colours_survive_native_save_open_and_export() { let second = group(s.doc().unwrap().doc.node(id).unwrap(), "2025").id; s.execute("paint.setFill", &json!({"ids": [first.0], "color": "#f00"})).unwrap(); s.execute("paint.setFill", &json!({"ids": [second.0], "color": "#008080"})).unwrap(); - let dir = vectorcraft_testkit::temp_dir("graph-palette"); + let dir = vectorcraft_testkit::TempDir::new("graph-palette"); let path = dir.join("palette.vectorcraft"); s.execute("document.save", &json!({"path": path})).unwrap(); s.execute("document.open", &json!({"path": path})).unwrap(); @@ -2690,7 +2690,8 @@ fn series_types_survive_save_and_open_and_older_files_have_none() { s.execute("file.new", &json!({})).unwrap(); let id = graph(&mut s, "column"); s.execute("graph.setType", &json!({"seriesIndexes": [1], "type": "line"})).unwrap(); - let path = vectorcraft_testkit::temp_dir("graph-kinds").join("kinds.vectorcraft"); + let dir = vectorcraft_testkit::TempDir::new("graph-kinds"); + let path = dir.join("kinds.vectorcraft"); s.execute("document.save", &json!({"path": path})).unwrap(); s.execute("document.open", &json!({"path": path})).unwrap(); assert_eq!(spec(&s, id).series_kinds, [None, Some(GraphKind::Line)]); @@ -2818,7 +2819,8 @@ fn value_axis_options_survive_save_and_open_and_are_left_out_when_unset() { let id = two_scale_graph(&mut s); s.execute("graph.setType", &json!({"valueAxis": "both", "separateScales": true, "rightAxisMin": 0, "rightAxisMax": 2000})).unwrap(); s.execute("graph.setType", &json!({"seriesIndexes": [1], "valueAxis": "right"})).unwrap(); - let path = vectorcraft_testkit::temp_dir("graph-axes").join("axes.vectorcraft"); + let dir = vectorcraft_testkit::TempDir::new("graph-axes"); + let path = dir.join("axes.vectorcraft"); s.execute("document.save", &json!({"path": path})).unwrap(); s.execute("document.open", &json!({"path": path})).unwrap(); let g = spec(&s, id); @@ -3020,7 +3022,8 @@ fn tick_and_label_options_survive_save_and_open_and_are_left_out_when_unset() { &json!({"tickLength": "full", "tickMarks": 3, "categoryTickLength": "short", "ticksBetweenLabels": true, "suffix": "%"}), ) .unwrap(); - let path = vectorcraft_testkit::temp_dir("graph-ticks").join("ticks.vectorcraft"); + let dir = vectorcraft_testkit::TempDir::new("graph-ticks"); + let path = dir.join("ticks.vectorcraft"); s.execute("document.save", &json!({"path": path})).unwrap(); s.execute("document.open", &json!({"path": path})).unwrap(); let g = spec(&s, id); @@ -3259,7 +3262,8 @@ fn designs_and_markers_survive_save_and_open() { save_design(&mut s, "Pill"); let id = graph(&mut s, "line"); s.execute("graph.marker", &json!({"seriesIndexes": [0], "design": "Pill"})).unwrap(); - let path = vectorcraft_testkit::temp_dir("graph-designs").join("designs.vectorcraft"); + let dir = vectorcraft_testkit::TempDir::new("graph-designs"); + let path = dir.join("designs.vectorcraft"); s.execute("document.save", &json!({"path": path})).unwrap(); s.execute("document.open", &json!({"path": path})).unwrap(); assert_eq!(s.execute("graph.design", &json!({})).unwrap()["designs"], json!(["Pill"])); @@ -3657,7 +3661,8 @@ fn column_designs_survive_save_and_open_and_follow_their_design() { assert!(series_parts(&s, id, 1).iter().all(|n| matches!(n.kind, NodeKind::Path { .. })), "the line series"); let v = s.execute("graph.column", &json!({"id": id.0, "seriesIndexes": [0]})).unwrap(); assert_eq!(v, json!({"designs": ["Coin"], "design": "Coin", "columnType": "repeating", "each": 2.5, "fractions": "scale"})); - let path = vectorcraft_testkit::temp_dir("graph-column-designs").join("columns.vectorcraft"); + let dir = vectorcraft_testkit::TempDir::new("graph-column-designs"); + let path = dir.join("columns.vectorcraft"); s.execute("document.save", &json!({"path": path})).unwrap(); s.execute("document.open", &json!({"path": path})).unwrap(); let options = ColumnDesign { design: "Coin".into(), column_type: ColumnType::Repeating, each: 2.5, fractions: Fractions::Scale }; @@ -4179,7 +4184,8 @@ fn legends_in_wedges_put_the_series_labels_inside_the_pie() { s.execute("graph.setType", &json!({"legend": true})).unwrap(); assert!(!spec(&s, id).pie_legend_in_wedges); assert!(s.execute("graph.setType", &json!({"pieLegend": "inside"})).is_err()); - let path = vectorcraft_testkit::temp_dir("graph-pie").join("pie.vectorcraft"); + let dir = vectorcraft_testkit::TempDir::new("graph-pie"); + let path = dir.join("pie.vectorcraft"); s.execute("graph.setType", &json!({"pieLegend": "wedges", "piePosition": "stacked", "pieSort": "all"})).unwrap(); s.execute("document.save", &json!({"path": path})).unwrap(); s.execute("document.open", &json!({"path": path})).unwrap(); @@ -4320,7 +4326,8 @@ fn the_legend_across_top_runs_in_rows_above_the_plot() { assert!(ys.iter().all(|y| *y + 8.0 <= 100.0 - 8.0 + 1e-6), "{ys:?}"); let xs: Vec = (0..6).map(|i| swatch(&s, i).x1).collect(); assert!(xs.iter().all(|x| *x <= 400.0), "{xs:?}"); - let path = vectorcraft_testkit::temp_dir("graph-top").join("top.vectorcraft"); + let dir = vectorcraft_testkit::TempDir::new("graph-top"); + let path = dir.join("top.vectorcraft"); s.execute("graph.setType", &json!({"dropShadow": true})).unwrap(); s.execute("document.save", &json!({"path": path})).unwrap(); s.execute("document.open", &json!({"path": path})).unwrap(); @@ -4439,7 +4446,8 @@ fn filled_lines_are_bands_in_the_series_colour() { s.execute("paint.setFill", &json!({"ids": [grp.0], "color": "#ff0000"})).unwrap(); s.execute("graph.setData", &json!({"id": id.0, "rows": [[2], [3], [2]]})).unwrap(); assert_eq!(series_parts(&s, id, 0)[0].appearance.fill_paint().color().unwrap().to_hex(), "#ff0000"); - let path = vectorcraft_testkit::temp_dir("graph-filled").join("filled.vectorcraft"); + let dir = vectorcraft_testkit::TempDir::new("graph-filled"); + let path = dir.join("filled.vectorcraft"); s.execute("graph.setType", &json!({"firstRowInFront": true, "firstColumnInFront": true})).unwrap(); s.execute("document.save", &json!({"path": path})).unwrap(); s.execute("document.open", &json!({"path": path})).unwrap(); @@ -4566,7 +4574,8 @@ fn a_graph_labels_anti_aliasing_method_survives_it_being_drawn_again() { s.execute("edit.undo", &json!({})).unwrap(); assert_eq!(spec(&s, id).label_styles.categories_anti_alias, None); s.execute("edit.redo", &json!({})).unwrap(); - let path = vectorcraft_testkit::temp_dir("graph-label-anti-alias").join("labels.vectorcraft"); + let dir = vectorcraft_testkit::TempDir::new("graph-label-anti-alias"); + let path = dir.join("labels.vectorcraft"); s.execute("document.save", &json!({"path": path})).unwrap(); s.execute("document.open", &json!({"path": path})).unwrap(); assert_eq!(spec(&s, id).label_styles.categories_anti_alias, Some(TypeAntiAlias::Strong)); @@ -4609,7 +4618,8 @@ fn formatting_one_label_keeps_that_kind_of_label() { assert_eq!(look("0").2, "#0000ff", "every value axis number"); assert_eq!(look("0").1, 9.0); // Kept through save and open; nothing written when unset. - let path = vectorcraft_testkit::temp_dir("graph-labels").join("labels.vectorcraft"); + let dir = vectorcraft_testkit::TempDir::new("graph-labels"); + let path = dir.join("labels.vectorcraft"); s.execute("document.save", &json!({"path": path})).unwrap(); s.execute("document.open", &json!({"path": path})).unwrap(); assert_eq!(spec(&s, id).label_styles.categories.as_ref().unwrap().size, 14.0); @@ -4778,7 +4788,8 @@ fn paragraph_formats_are_kept_when_the_graph_is_drawn_again() { let v = text_id(&s, col, "Axes", "4"); s.execute("select.set", &json!({"ids": [v.0]})).unwrap(); s.execute("text.setFormat", &json!({"composer": "singleLine"})).unwrap(); - let path = vectorcraft_testkit::temp_dir("graph-label-paras").join("labels.vectorcraft"); + let dir = vectorcraft_testkit::TempDir::new("graph-label-paras"); + let path = dir.join("labels.vectorcraft"); s.execute("document.save", &json!({"path": path})).unwrap(); s.execute("document.open", &json!({"path": path})).unwrap(); s.execute("select.set", &json!({"ids": [col.0]})).unwrap(); diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index c7c82c7625..2a8d074617 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -63,7 +63,7 @@ pub fn specs() -> Vec { "Edit Profile", [], None, - "{name: a category of file.newPresets} open the category's New Document profile as a document to edit (File › Save keeps the changes for the next file.new); a category without a profile file gets the shipped profile written first → document.open's result", + "{name: a category of file.newPresets} open the category's New Document profile as a document to edit (File › Save keeps the changes for the next file.new); a category without a profile file gets the shipped profile written first; under automation roots it needs write and read access to the file, and an error names the file by its file name outside the read roots → document.open's result", always, edit_profile ), @@ -72,7 +72,7 @@ pub fn specs() -> Vec { "Reset Profile", [], None, - "{name: a category of file.newPresets} delete the category's profile file, so the shipped profile (today's defaults) applies again; an open copy of it stays open → {name, reset: whether a file was deleted}", + "{name: a category of file.newPresets} delete the category's profile file, so the shipped profile (today's defaults) applies again; an open copy of it stays open; under automation roots it needs write access to the file, and an error names the file by its file name outside the read roots → {name, reset: whether a file was deleted}", always, reset_profile ), @@ -999,10 +999,17 @@ fn list_profiles(s: &mut Session, _: &Value) -> Result { Ok(json!({ "profiles": profiles, "folder": s.new_doc_profile_dir().and_then(shown) })) } +/// `msg`, an error about the profile file at `path`, as the request being served may see it: the +/// file named whole inside the read roots, else by its file name. +fn profile_error(msg: String, path: &str) -> super::EngineError { + super::fileio::naming_in_error(super::EngineError::Other(msg), path) +} + /// The file of profile `name` for `cmd` to change, checked against the request's write access. fn writable_profile(s: &Session, name: &str, cmd: &str) -> Result { let path = s.profile_path(name).ok_or_else(|| bad(cmd, "New Document profiles need the preferences folder, which this run doesn't have"))?; - crate::file_access::check_write(&path.to_string_lossy()).map_err(super::EngineError::Other)?; + let file = path.to_string_lossy(); + crate::file_access::check_write(&file).map_err(|e| profile_error(e, &file))?; Ok(path) } @@ -1012,13 +1019,13 @@ fn edit_profile(s: &mut Session, p: &Value) -> Result { let file = writable_profile(s, name, C)?; let path = file.to_string_lossy().to_string(); // document.open reads it next: a profile it can't open is not written either. - crate::file_access::check_read(&path).map_err(super::EngineError::Other)?; + crate::file_access::check_read(&path).map_err(|e| profile_error(e, &path))?; if !file.exists() { let bytes = vectorcraft_format::save(&shipped_profile(s, name), false); file.parent() .map_or(Ok(()), std::fs::create_dir_all) .and_then(|()| std::fs::write(&file, bytes)) - .map_err(|e| super::EngineError::Other(format!("{path}: {e}")))?; + .map_err(|e| profile_error(format!("{path}: {e}"), &path))?; } s.execute("document.open", &json!({ "path": path })) } @@ -1031,7 +1038,7 @@ fn reset_profile(s: &mut Session, p: &Value) -> Result { let reset = match std::fs::remove_file(&file) { Ok(()) => true, Err(e) if e.kind() == std::io::ErrorKind::NotFound => false, - Err(e) => return Err(super::EngineError::Other(format!("{path}: {e}"))), + Err(e) => return Err(profile_error(format!("{path}: {e}"), &path)), }; Ok(json!({ "name": name, "reset": reset })) } diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 3464df3833..85d11ea7ec 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -21,7 +21,7 @@ pub fn specs() -> Vec { "Fill", [], None, - "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid colour recolours only the gradient mesh point last clicked with the Mesh tool or Direct Selection; while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern) → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}", + "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid colour recolours only the gradient mesh point last clicked with the Mesh tool or Direct Selection; while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern) → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}", has_doc, |s, p| set_paint(s, p, true) ), diff --git a/crates/engine/src/cmd/params.rs b/crates/engine/src/cmd/params.rs index c38854ae76..ddbaec22a2 100644 --- a/crates/engine/src/cmd/params.rs +++ b/crates/engine/src/cmd/params.rs @@ -773,9 +773,7 @@ fn check_export_options(id: &str, params: &Value) -> Result<()> { NO_SAVE_FORMAT } "document.export" | "document.exportSelection" | "document.serialize" => { - // `richBlack` is Appearance of Black's setting for a raster export, and `params` an - // exporter plug-in's own. - keys.extend(["includeArtboardFill", "selectedOnly", "richBlack", "params"]); + keys.extend(super::fileio::EXPORT_PARAMS); keys.extend(FORMATS.iter().filter(|f| f.write).flat_map(|f| f.options).map(|o| o.name)); NO_FORMAT } diff --git a/crates/engine/src/cmd/pathops.rs b/crates/engine/src/cmd/pathops.rs index ac57d1852f..b4ce273dad 100644 --- a/crates/engine/src/cmd/pathops.rs +++ b/crates/engine/src/cmd/pathops.rs @@ -946,7 +946,7 @@ pub(crate) fn outlined_stroke( /// geometry effects leave nothing to paint, an empty group takes the path's place. /// `None` when `l` has no stroke to outline. pub(crate) fn outline_strokes(d: &mut Document, brushes: &[vectorcraft_brush::Brush], l: &Node) -> Option { - use vectorcraft_render::effects::{GeomContext, apply_geometry_with, has_geometry, has_transform_art, reshape, without_geometry}; + use vectorcraft_render::effects::{GeomContext, apply_geometry_carrying, has_geometry, has_transform_art, reshape, without_geometry}; if !l.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(st) if outlinable(st))) { return None; } @@ -983,11 +983,16 @@ pub(crate) fn outline_strokes(d: &mut Document, brushes: &[vectorcraft_brush::Br parts.push(styled_copy(d, l, std::mem::take(&mut fills))); } let mut plain = st.clone(); - plain.effects = without_geometry(&st.effects); let stroked = match path.bounds() { - Some(b) if has_geometry(&st.effects) => apply_geometry_with(&st.effects, &path, b, &ctx.item(item)), + Some(b) if has_geometry(&st.effects) => { + let (stroked, carry) = apply_geometry_carrying(&st.effects, &path, b, &ctx.item(item)); + // Its raster effects follow only the Transform effects that moved it. + carry.hide_skipped(&mut plain.effects); + stroked + } _ => path.clone(), }; + plain.effects = without_geometry(&plain.effects); parts.extend(outlined_stroke(d, brushes, &stroked, rule, &plain)); } _ => {} diff --git a/crates/engine/src/cmd/swatch.rs b/crates/engine/src/cmd/swatch.rs index 22c1c0c929..d0713a243a 100644 --- a/crates/engine/src/cmd/swatch.rs +++ b/crates/engine/src/cmd/swatch.rs @@ -410,6 +410,8 @@ fn gradient_key(g: &Gradient) -> Option> { let method = match g.method { GradientMethod::Classic => 0, GradientMethod::Perceptual => 1, + GradientMethod::HueClockwise => 2, + GradientMethod::HueCounterclockwise => 3, }; Some((kind, method, g.dither, g.painted_spread(), g.stops.iter().map(stop_key).collect::>()?)) } diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index 0ef7555e02..10d21266ba 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -55,6 +55,11 @@ pub struct DocState { pub recalled_selection: RecalledSelection, /// Process-unique id of this open document (tab indices shift when tabs close). pub uid: u64, + /// How many times File → Revert replaced the document's content in its tab + /// ([`Session::replace_document`]). Work started for the document (a file read for Place, a + /// pasted bitmap) is dropped when this has changed by the time it finishes; edits do not + /// change it, and a batch that fails puts it back with the document. + pub reverts: u64, /// Preferences › User Interface › Open Documents As Tabs when the document opened: cleared, /// the UI opens it in a floating window of its own. pub opened_as_tab: bool, @@ -313,6 +318,7 @@ impl DocState { last_selection_cmd: None, recalled_selection: RecalledSelection::default(), uid: NEXT_DOC_UID.fetch_add(1, std::sync::atomic::Ordering::Relaxed), + reverts: 0, opened_as_tab: true, mask_view: None, spelling_ignored: Default::default(), diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 0d472ef81d..da26dbfc71 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -370,6 +370,8 @@ impl Session { st.history.limit = old.history.limit; // Same open document (caches keyed by uid stay valid); a new revision redraws it. st.uid = old.uid; + // Work started for the content being thrown away is dropped when it finishes. + st.reverts = old.reverts + 1; st.opened_as_tab = old.opened_as_tab; st.revision = old.revision + 1; st.format = old.format; @@ -404,11 +406,18 @@ impl Session { true } + /// Close the document in tab `index` (`file.close`). Closing a tab other than the current one + /// keeps the current document current, and its tool keeps its state: no document is switched + /// to. Closing the current document makes the tab now at `index` current, or the last tab when + /// it was the last one. False, changing nothing, when `index` is past the last document. pub fn close_document(&mut self, index: usize) -> bool { if index >= self.docs.len() { return false; } - self.reset_tool_for_doc_switch(); + let front = self.active().map(|d| d.uid).filter(|_| self.active != Some(index)); + if front.is_none() { + self.reset_tool_for_doc_switch(); + } // Closed (saved or discarded): nothing left to recover. let uid = self.docs[index].uid; cmd::recovery::forget(self, uid); @@ -416,6 +425,10 @@ impl Session { if let Some(stash) = &mut self.batch_stash { stash.push(old); } + if let Some(uid) = front { + self.active = self.docs.iter().position(|d| d.uid == uid); + return true; + } self.active = if self.docs.is_empty() { None } else { Some(index.min(self.docs.len() - 1)) }; self.sync_front_composite_fonts(); self.sync_front_profiles(); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 6c231dc7e5..c260b42d90 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -47,6 +47,7 @@ mod dashalign; mod dcs; mod distort; mod docsetup; +mod document_close; mod document_move; mod draw2; mod dynamic_symbols; diff --git a/crates/engine/src/tests/arrowheads.rs b/crates/engine/src/tests/arrowheads.rs index b350341767..0cdc3312ff 100644 --- a/crates/engine/src/tests/arrowheads.rs +++ b/crates/engine/src/tests/arrowheads.rs @@ -284,6 +284,87 @@ fn an_unreadable_arrowheads_file_lists_no_heads_and_says_why() { assert_eq!(bare.execute("stroke.arrowheads.list", &json!({})).unwrap()["file"], serde_json::Value::Null); } +/// Automation roots that grant reading `read` alone. +fn read_roots(read: &[&std::path::Path]) -> Arc { + crate::file_access::AutomationRoots::new(read, &[]).unwrap().unwrap() +} + +#[test] +fn an_agent_outside_the_arrowheads_files_folder_sees_its_file_name_alone_and_cannot_reload_it() { + let dir = folder("roots-list"); + let (prefs, other) = (dir.join("prefs"), dir.join("other")); + std::fs::create_dir_all(&prefs).unwrap(); + std::fs::create_dir_all(&other).unwrap(); + let file = prefs.join(arrowheads::FILE_NAME); + std::fs::write(&file, b"not a drawing").unwrap(); + let (file, prefs_text) = (file.to_string_lossy().to_string(), prefs.to_string_lossy().to_string()); + let mut s = Session::new(); + s.attach_arrowheads_file(file.clone()); + let (outside, inside) = (read_roots(&[&other]), read_roots(&[&prefs])); + let list = crate::file_access::confine(Some(&outside), || s.execute("stroke.arrowheads.list", &json!({}))).unwrap(); + assert_eq!(list["file"], serde_json::Value::Null, "{list}"); + let error = list["error"].as_str().unwrap(); + assert!(error.starts_with(arrowheads::FILE_NAME) && !error.contains(&prefs_text), "{error}"); + let list = crate::file_access::confine(Some(&inside), || s.execute("stroke.arrowheads.list", &json!({}))).unwrap(); + assert_eq!(list["file"].as_str(), Some(file.as_str())); + assert!(list["error"].as_str().unwrap().starts_with(&file), "{list}"); + // A good file now: an agent outside the folder cannot have it read. + std::fs::write(&file, vectorcraft_format::save_file(&arrowheads::starter())).unwrap(); + let e = crate::file_access::confine(Some(&outside), || s.execute("stroke.arrowheads.reload", &json!({}))).unwrap_err().to_string(); + assert!(e.contains("outside the read root") && e.ends_with(arrowheads::FILE_NAME) && !e.contains(&prefs_text), "{e}"); + let list = s.execute("stroke.arrowheads.list", &json!({})).unwrap(); + assert!(list["arrowheads"].as_array().unwrap().is_empty() && list["error"].is_string(), "not read again: {list}"); + let r = crate::file_access::confine(Some(&inside), || s.execute("stroke.arrowheads.reload", &json!({}))).unwrap(); + assert_eq!(r["count"], 1); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn an_agent_edits_the_arrowheads_file_only_inside_its_read_roots() { + let dir = folder("roots-edit"); + let (prefs, other) = (dir.join("prefs"), dir.join("other")); + std::fs::create_dir_all(&other).unwrap(); + let file = prefs.join(arrowheads::FILE_NAME).to_string_lossy().to_string(); + let prefs_text = prefs.to_string_lossy().to_string(); + let (mut s, _) = session_with_line(); + s.attach_arrowheads_file(file.clone()); + let line_doc = s.doc().unwrap().uid; + let outside = read_roots(&[&other]); + let edit = |s: &mut Session, roots: &Arc| { + crate::file_access::confine(Some(roots), || s.execute("stroke.arrowheads.edit", &json!({}))) + }; + // Refused before the folder or the file is made, or anything is opened. + let e = edit(&mut s, &outside).unwrap_err().to_string(); + assert!(e.ends_with(arrowheads::FILE_NAME) && !e.contains(&prefs_text), "{e}"); + assert!(!prefs.exists(), "no folder made"); + assert_eq!((s.documents().len(), s.doc().unwrap().uid), (1, line_doc)); + // From the Stroke panel menu (no roots), the file is made and opened. + assert_eq!(s.execute("stroke.arrowheads.edit", &json!({})).unwrap()["created"], true); + assert_eq!(s.documents().len(), 2); + // Open already: still not brought to the front for an agent outside the folder. + s.execute("document.activate", &json!({"index": 0})).unwrap(); + assert!(edit(&mut s, &outside).is_err()); + assert_eq!((s.documents().len(), s.doc().unwrap().uid), (2, line_doc)); + // Inside the read roots: opened under them, with its path. + let inside = read_roots(&[&prefs]); + let mut agent = Session::new(); + agent.attach_arrowheads_file(file.clone()); + let r = edit(&mut agent, &inside).unwrap(); + assert_eq!((r["path"].as_str(), &r["created"]), (Some(file.as_str()), &json!(false))); + let st = agent.doc().unwrap(); + assert_eq!(st.path.as_deref(), Some(file.as_str())); + assert!(st.opened_by.as_ref().is_some_and(|r| Arc::ptr_eq(r, &inside)), "opened under the agent's roots"); + // A missing file inside the roots is still made first. + let fresh = dir.join("fresh").join(arrowheads::FILE_NAME).to_string_lossy().to_string(); + let mut agent = Session::new(); + agent.attach_arrowheads_file(fresh.clone()); + let r = edit(&mut agent, &read_roots(&[&dir])).unwrap(); + assert_eq!(r["created"], true); + assert!(std::path::Path::new(&fresh).is_file()); + assert_eq!(agent.doc().unwrap().path.as_deref(), Some(fresh.as_str())); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn the_heads_listed_after_a_save_are_read_from_the_file_and_editing_keeps_it() { let dir = folder("saved"); diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index 21cbf678eb..6eeace1073 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -840,7 +840,7 @@ fn shape_builder_applies_a_merge_before_what_comes_next() { }), ]; let _proof = crate::tests_colormgmt::GLOBAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - let dir = vectorcraft_testkit::temp_dir("shape-builder-merge-first"); + let dir = vectorcraft_testkit::TempDir::new("shape-builder-merge-first"); for (what, then) in next { let mut s = session(); if what == "Select All Instances" { diff --git a/crates/engine/src/tests/cancel.rs b/crates/engine/src/tests/cancel.rs index 8237707a10..9a044ead89 100644 --- a/crates/engine/src/tests/cancel.rs +++ b/crates/engine/src/tests/cancel.rs @@ -22,7 +22,8 @@ fn revision(s: &Session) -> u64 { #[test] fn a_pdf_export_cancelled_between_pages_stops_writes_nothing_and_changes_nothing() { - let path = vectorcraft_testkit::temp_dir("cancel-pdf").join("out.pdf"); + let dir = vectorcraft_testkit::TempDir::new("cancel-pdf"); + let path = dir.join("out.pdf"); std::fs::remove_file(&path).ok(); let mut s = session(5); let before = (revision(&s), s.doc().unwrap().history.undo.len()); @@ -66,7 +67,7 @@ fn a_cancelled_flattening_export_stops_before_the_pages() { #[test] fn raster_exports_and_svg_stop_when_cancelled_too() { - let dir = vectorcraft_testkit::temp_dir("cancel-formats"); + let dir = vectorcraft_testkit::TempDir::new("cancel-formats"); let mut s = session(3); let token = CancelToken::new(); token.cancel(); diff --git a/crates/engine/src/tests/compare.rs b/crates/engine/src/tests/compare.rs index 3bd4446d61..3a6c66e2f5 100644 --- a/crates/engine/src/tests/compare.rs +++ b/crates/engine/src/tests/compare.rs @@ -36,7 +36,7 @@ fn error(s: &mut Session, p: Value) -> String { #[test] fn an_export_compares_equal_and_a_moved_square_counts_the_pixels_it_changed() { - let dir = vectorcraft_testkit::temp_dir("compare-moved"); + let dir = vectorcraft_testkit::TempDir::new("compare-moved"); let png = path_in(&dir, "art.png"); let (mut s, id) = session(); export(&mut s, &png); @@ -54,12 +54,11 @@ fn an_export_compares_equal_and_a_moved_square_counts_the_pixels_it_changed() { assert_eq!(r["rmse"].as_f64(), Some(rmse), "{r}"); // Above every difference, nothing is over. assert_eq!(compare(&mut s, json!({"path": png, "threshold": 1}))["over"], json!(0)); - let _ = std::fs::remove_dir_all(dir); } #[test] fn the_image_and_the_render_are_flattened_on_the_background() { - let dir = vectorcraft_testkit::temp_dir("compare-background"); + let dir = vectorcraft_testkit::TempDir::new("compare-background"); let png = path_in(&dir, "clear.png"); // Transparent everywhere, with red in the color channels that the alpha hides. image::RgbaImage::from_pixel(80, 40, image::Rgba([255, 0, 0, 0])).save(&png).unwrap(); @@ -81,12 +80,11 @@ fn the_image_and_the_render_are_flattened_on_the_background() { assert_eq!((r["rmse"].as_f64(), r["over"].as_u64()), (Some(rmse(255.0)), Some(1600)), "{r}"); // A threshold just above 128/255 leaves the gray differences out. assert_eq!(compare(&mut s, json!({"path": png, "background": "#808080", "threshold": 0.51}))["over"], json!(0)); - let _ = std::fs::remove_dir_all(dir); } #[test] fn an_image_of_other_proportions_is_refused_and_one_pixel_is_allowed() { - let dir = vectorcraft_testkit::temp_dir("compare-size"); + let dir = vectorcraft_testkit::TempDir::new("compare-size"); let (mut s, _) = session(); let square = path_in(&dir, "square.png"); image::RgbaImage::from_pixel(30, 30, image::Rgba([255; 4])).save(&square).unwrap(); @@ -96,12 +94,11 @@ fn an_image_of_other_proportions_is_refused_and_one_pixel_is_allowed() { image::RgbaImage::from_pixel(80, 41, image::Rgba([255; 4])).save(&taller).unwrap(); let r = compare(&mut s, json!({"path": taller})); assert_eq!((r["width"].as_u64(), r["height"].as_u64(), r["total"].as_u64()), (Some(80), Some(41), Some(3280)), "{r}"); - let _ = std::fs::remove_dir_all(dir); } #[test] fn an_export_whose_height_was_rounded_compares_equal() { - let dir = vectorcraft_testkit::temp_dir("compare-rounded"); + let dir = vectorcraft_testkit::TempDir::new("compare-rounded"); let png = path_in(&dir, "art.png"); // 20.25 pt at 2 pixels a point is 40.5 rows, which the export rounds to 41. let mut s = Session::new(); @@ -112,7 +109,6 @@ fn an_export_whose_height_was_rounded_compares_equal() { export(&mut s, &png); let r = compare(&mut s, json!({"path": png})); assert_eq!(r, json!({"width": 80, "height": 41, "rmse": 0.0, "over": 0, "total": 3280, "threshold": 0.08})); - let _ = std::fs::remove_dir_all(dir); } #[test] @@ -151,7 +147,7 @@ fn a_linked_image_is_drawn_from_its_file_as_a_png_export_draws_it() { #[test] fn an_image_that_cannot_be_decoded_and_a_missing_font_warn_as_a_png_export_does() { - let dir = vectorcraft_testkit::temp_dir("compare-warnings"); + let dir = vectorcraft_testkit::TempDir::new("compare-warnings"); let png = path_in(&dir, "art.png"); let (mut s, _) = session(); export(&mut s, &png); @@ -167,12 +163,11 @@ fn an_image_that_cannot_be_decoded_and_a_missing_font_warn_as_a_png_export_does( assert!(warnings.iter().any(|w| w == "an image couldn't be decoded and is missing from the picture"), "{r}"); assert!(warnings.iter().any(|w| w.as_str().unwrap().contains("Nonexistent Sans Probe")), "{r}"); assert!(warnings.iter().any(|w| w.as_str().unwrap().contains("doesn't fit its frame")), "{r}"); - let _ = std::fs::remove_dir_all(dir); } #[test] fn diff_path_writes_each_pixels_differences() { - let dir = vectorcraft_testkit::temp_dir("compare-diff"); + let dir = vectorcraft_testkit::TempDir::new("compare-diff"); let png = path_in(&dir, "art.png"); let diff = path_in(&dir, "diff.png"); let (mut s, id) = session(); @@ -188,12 +183,11 @@ fn diff_path_writes_each_pixels_differences() { } let changed = img.pixels().filter(|p| p.0[0] != 0).count(); assert_eq!(changed as u64, r["over"].as_u64().unwrap()); - let _ = std::fs::remove_dir_all(dir); } #[test] fn missing_unreadable_and_malformed_inputs_are_errors() { - let dir = vectorcraft_testkit::temp_dir("compare-errors"); + let dir = vectorcraft_testkit::TempDir::new("compare-errors"); let (mut s, _) = session(); let png = path_in(&dir, "art.png"); export(&mut s, &png); @@ -216,14 +210,13 @@ fn missing_unreadable_and_malformed_inputs_are_errors() { let e = error(&mut s, p.clone()); assert!(e.contains(want), "{p}: {e}"); } - let _ = std::fs::remove_dir_all(dir); } /// A planar TIFF whose header claims more strips than the decoder can count (2^31 + 1 rows a strip /// each, times 5 planes) is refused as too large to draw, without a panic. #[test] fn a_tiff_with_more_strips_than_can_be_counted_is_too_large() { - let dir = vectorcraft_testkit::temp_dir("compare-strips"); + let dir = vectorcraft_testkit::TempDir::new("compare-strips"); let (mut s, _) = session(); let plane = |v: u16| vec![v; 6]; let channels = [plane(200), plane(40), plane(10), plane(0), plane(90)]; @@ -247,12 +240,11 @@ fn a_tiff_with_more_strips_than_can_be_counted_is_too_large() { std::fs::write(&tif, &file).unwrap(); let e = error(&mut s, json!({"path": tif})); assert_eq!(e, "invalid parameters for `document.compare`: an image of 3 × 2147483649 pixels is too large to draw"); - let _ = std::fs::remove_dir_all(dir); } #[test] fn the_image_and_the_difference_image_stay_inside_the_automation_roots() { - let dir = vectorcraft_testkit::temp_dir("compare-roots"); + let dir = vectorcraft_testkit::TempDir::new("compare-roots"); for d in ["in", "out", "elsewhere"] { std::fs::create_dir_all(dir.join(d)).unwrap(); } @@ -272,5 +264,4 @@ fn the_image_and_the_difference_image_stay_inside_the_automation_roots() { assert!(!std::path::Path::new(&stray).exists()); let kept = path_in(&dir.join("out"), "diff.png"); assert_eq!(run(json!({"path": inside, "diffPath": kept})).unwrap()["diffPath"], json!(kept)); - let _ = std::fs::remove_dir_all(dir); } diff --git a/crates/engine/src/tests/containers.rs b/crates/engine/src/tests/containers.rs index 437f932724..42cebea2ad 100644 --- a/crates/engine/src/tests/containers.rs +++ b/crates/engine/src/tests/containers.rs @@ -312,7 +312,7 @@ fn an_images_stroke_with_outline_object_follows_its_opaque_area() { run(&mut s, "effect.apply", json!({"effect": "path.offsetPath", "params": {"offset": 3}, "item": 0})); assert_eq!([shade(&s, 61, 100), shade(&s, 64, 100)], ["white", "black"]); // Relinked to an opaque image, the stroke follows the frame 3 pt out: it shows from 43 to 50. - let dir = vectorcraft_testkit::temp_dir("outline-object-relink"); + let dir = vectorcraft_testkit::TempDir::new("outline-object-relink"); std::fs::create_dir_all(&dir).unwrap(); let path = dir.join("opaque.png"); let mut png = vec![]; diff --git a/crates/engine/src/tests/css.rs b/crates/engine/src/tests/css.rs index 1ce5b09e41..39fb6a5bc2 100644 --- a/crates/engine/src/tests/css.rs +++ b/crates/engine/src/tests/css.rs @@ -57,6 +57,28 @@ fn type_gives_font_properties_and_gradients_css_gradients() { assert!(text.contains("background-image: linear-gradient(90deg, "), "{text}"); } +/// CSS gradients mix linearly: a gradient mixed around the hue wheel is written through the stops +/// on its way around the wheel, so red to blue lists green one way and magenta the other. +#[test] +fn gradients_mixed_around_the_hue_wheel_give_css_the_stops_on_their_way() { + let mut s = session(); + run(&mut s, "shape.rectangle", json!({"x": 0, "y": 100, "width": 100, "height": 50})); + let stops = json!([{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]); + let gradient = |s: &mut Session, method: &str| { + run(s, "paint.setFill", json!({"gradient": {"kind": "linear", "method": method, "stops": stops}})); + let text = css(&run(s, "css.selection", json!({}))).to_string(); + text.lines().find(|l| l.contains("linear-gradient(")).unwrap_or_else(|| panic!("a gradient in {text}")).to_string() + }; + let classic = gradient(&mut s, "classic"); + assert_eq!(classic.matches('%').count(), 2, "{classic}"); + for (method, middle, other) in [("hue-counterclockwise", "#00ff00 50%", "#ff00ff"), ("hue-clockwise", "#ff00ff 50%", "#00ff00")] { + let line = gradient(&mut s, method); + assert!(line.matches('%').count() > 2, "{method}: {line}"); + assert!(line.contains("#ff0000 0%") && line.contains("#0000ff 100%"), "{method}: {line}"); + assert!(line.contains(middle) && !line.contains(other), "{method}: {line}"); + } +} + #[test] fn generate_covers_the_document_and_an_empty_selection_has_none() { let mut s = session(); diff --git a/crates/engine/src/tests/dcs.rs b/crates/engine/src/tests/dcs.rs index 5c806884d8..b780f14c09 100644 --- a/crates/engine/src/tests/dcs.rs +++ b/crates/engine/src/tests/dcs.rs @@ -3,8 +3,6 @@ //! the Links panel's Show DCS Transparency Interactions (`links.list` with `dcsTransparency`). //! The files are made from scratch as http://www.telegraphics.net/doc/DCS.txt describes them. -use std::path::PathBuf; - use serde_json::{Value, json}; use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{Node, NodeKind}; @@ -17,12 +15,9 @@ fn session() -> Session { s } -/// A fresh scratch folder for one test. -fn temp_dir(name: &str) -> PathBuf { - let d = std::env::temp_dir().join(format!("vc-dcs-{name}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&d); - std::fs::create_dir_all(&d).unwrap(); - d +/// A fresh scratch folder for one test, removed when dropped. +fn temp_dir(name: &str) -> vectorcraft_testkit::TempDir { + vectorcraft_testkit::TempDir::new(&format!("dcs-{name}")) } /// A plate program: one 2 × 2 grayscale image (`gray`, row by row) on a 20 × 10 pt page. diff --git a/crates/engine/src/tests/document_close.rs b/crates/engine/src/tests/document_close.rs new file mode 100644 index 0000000000..a1b106d365 --- /dev/null +++ b/crates/engine/src/tests/document_close.rs @@ -0,0 +1,91 @@ +//! `file.close {index}`: closing a document tab other than the current one keeps the current +//! document current, and closing the current one makes its neighbor current. + +use serde_json::json; + +use crate::*; + +/// A session with documents A, B, C and D, in that order, D current. +fn four() -> Session { + let mut s = Session::new(); + for name in ["A", "B", "C", "D"] { + s.execute("file.new", &json!({"name": name, "created": null})).unwrap(); + } + s +} + +fn order(s: &Session) -> String { + s.documents().iter().map(DocState::title).collect::>().join("") +} + +fn current(s: &Session) -> String { + s.active().map(DocState::title).unwrap_or_default() +} + +fn close(s: &mut Session, index: usize) { + s.execute("file.close", &json!({"index": index})).unwrap_or_else(|e| panic!("file.close {index}: {e}")); +} + +#[test] +fn closing_a_tab_before_the_current_one_keeps_the_current_document() { + let mut s = four(); + close(&mut s, 0); + assert_eq!((order(&s), current(&s)), ("BCD".into(), "D".into())); + assert_eq!(s.active_index(), Some(2)); + assert!(s.set_active(1)); + close(&mut s, 0); + assert_eq!((order(&s), current(&s)), ("CD".into(), "C".into())); + assert_eq!(s.active_index(), Some(0)); +} + +#[test] +fn closing_a_tab_after_the_current_one_keeps_the_current_document() { + let mut s = four(); + assert!(s.set_active(1)); + close(&mut s, 3); + assert_eq!((order(&s), current(&s)), ("ABC".into(), "B".into())); + close(&mut s, 2); + assert_eq!((order(&s), current(&s)), ("AB".into(), "B".into())); + assert_eq!(s.active_index(), Some(1)); +} + +#[test] +fn closing_the_current_tab_makes_its_neighbor_current() { + let mut s = four(); + assert!(s.set_active(1)); + close(&mut s, 1); + assert_eq!((order(&s), current(&s)), ("ACD".into(), "C".into()), "the tab that took its place"); + assert!(s.set_active(2)); + close(&mut s, 2); + assert_eq!((order(&s), current(&s)), ("AC".into(), "C".into()), "the last tab: the one before it"); + s.execute("file.close", &json!({})).unwrap(); + assert_eq!((order(&s), current(&s)), ("A".into(), "A".into()), "without an index, the current one closes"); + close(&mut s, 0); + assert!(s.active().is_none()); + assert!(s.execute("file.close", &json!({"index": 0})).is_err(), "no document left"); +} + +#[test] +fn closing_another_tab_keeps_the_tool_and_the_documents_edits() { + let mut s = four(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + let resets = s.tool_resets; + let nodes = s.doc().unwrap().doc.node_count(); + let history = super::history(&s); + close(&mut s, 1); + assert_eq!(s.tool_resets, resets, "no document was switched to, so the tool is not reset"); + assert_eq!(super::history(&s), history); + assert_eq!(s.doc().unwrap().doc.node_count(), nodes); + assert!(s.doc().unwrap().is_dirty(), "the document keeps its unsaved edit"); + close(&mut s, 2); + assert_ne!(s.tool_resets, resets, "closing the current document resets the tool"); +} + +#[test] +fn a_bad_index_closes_nothing() { + let mut s = four(); + assert!(s.set_active(2)); + assert!(s.execute("file.close", &json!({"index": 4})).is_err()); + assert!(!s.close_document(4)); + assert_eq!((order(&s), current(&s)), ("ABCD".into(), "C".into())); +} diff --git a/crates/engine/src/tests/envelope.rs b/crates/engine/src/tests/envelope.rs index 9d8999e388..055cc62740 100644 --- a/crates/engine/src/tests/envelope.rs +++ b/crates/engine/src/tests/envelope.rs @@ -792,6 +792,56 @@ fn an_envelope_of_type_that_draws_nothing_maps_from_its_laid_out_box() { assert_box(src_of(&s, e), laid, "warp"); } +/// Type that draws nothing adds no box next to other content: Make with Warp and Make with Mesh +/// around it and a rectangle, alone or in a group, map from the rectangle. +#[test] +fn type_that_draws_nothing_adds_no_box_next_to_other_content() { + for (cmd, params) in + [("object.envelope.makeWithWarp", json!({"style": "arc", "bend": 0})), ("object.envelope.makeWithMesh", json!({"rows": 1, "cols": 1}))] + { + for grouped in [false, true] { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 200.0, 100.0); + let want = node(&s, a).geometric_bounds().unwrap(); + let t = id_of(&s.execute("text.create", &json!({"x": 400, "y": 450, "text": " ", "size": 96})).unwrap()); + let laid = node(&s, t).geometric_bounds().unwrap(); + assert!(laid.x1 > want.x1 && laid.y1 > want.y1, "the laid-out box {laid:?} reaches past {want:?}"); + sel(&mut s, &[a, t]); + if grouped { + s.execute("object.group", &json!({})).unwrap(); + } + let layer = s.doc().unwrap().doc.layers[0].clone(); + assert_box(live::envelope_content_bounds(&[layer]).unwrap(), want, "content bounds"); + let e = id_of(&s.execute(cmd, ¶ms).unwrap()); + assert_box(src_of(&s, e), want, &format!("{cmd}, grouped: {grouped}")); + } + } +} + +/// Deleting every character of enveloped type in Edit Contents leaves the envelope mapping from +/// the rectangle beside it; with nothing beside it, from the type's laid-out box. +#[test] +fn edit_contents_that_empties_type_maps_from_the_other_content() { + for with_rect in [true, false] { + let mut s = session(); + let a = with_rect.then(|| rect(&mut s, 100.0, 100.0, 200.0, 100.0)); + let rect_box = a.map(|a| node(&s, a).geometric_bounds().unwrap()); + let t = id_of(&s.execute("text.create", &json!({"x": 400, "y": 450, "text": "Type", "size": 96})).unwrap()); + sel(&mut s, &a.into_iter().chain([t]).collect::>()); + let e = id_of(&s.execute("object.envelope.makeWithWarp", &json!({"style": "arc", "bend": 0})).unwrap()); + sel(&mut s, &[e]); + s.execute("object.envelope.editContents", &json!({"editing": true})).unwrap(); + s.execute("text.setText", &json!({"ids": [t.0], "text": " "})).unwrap(); + sel(&mut s, &[e]); + s.execute("object.envelope.editContents", &json!({"editing": false})).unwrap(); + let NodeKind::Envelope { content, .. } = node(&s, e).kind else { panic!("envelope") }; + let blank = content.iter().find(|c| c.id == t).expect("the type stays"); + assert!(matches!(&blank.kind, NodeKind::Text(tx) if tx.plain_text().trim().is_empty()), "the type was emptied"); + let want = rect_box.unwrap_or_else(|| blank.geometric_bounds().unwrap()); + assert_box(src_of(&s, e), want, &format!("with a rectangle: {with_rect}")); + } +} + /// The strikethrough bar runs to the last glyph's advance, past its outline: the envelope maps /// from it too. #[test] diff --git a/crates/engine/src/tests/fontfiles.rs b/crates/engine/src/tests/fontfiles.rs index 8bef8733b5..52a8ff08a3 100644 --- a/crates/engine/src/tests/fontfiles.rs +++ b/crates/engine/src/tests/fontfiles.rs @@ -14,12 +14,12 @@ use crate::cmd::findfiles::{self, Limits, Rules, Visitor}; use crate::cmd::fontfiles::{self, FontSearch, MAX_FONT_FILE, Sought, copy_into}; use crate::{EngineError, Session}; -/// A fresh temporary folder (canonical, as a search reports it). -fn folder(tag: &str) -> PathBuf { - let dir = vectorcraft_testkit::temp_dir(&format!("fontfiles-{tag}")); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - findfiles::plain(std::fs::canonicalize(&dir).unwrap()) +/// A fresh temporary folder, removed when the first part is dropped, and its path (canonical, as a +/// search reports it). +fn folder(tag: &str) -> (vectorcraft_testkit::TempDir, PathBuf) { + let dir = vectorcraft_testkit::TempDir::new(&format!("fontfiles-{tag}")); + let path = findfiles::plain(std::fs::canonicalize(&*dir).unwrap()); + (dir, path) } /// A session whose folder searches may go anywhere in `root`, on two threads. @@ -103,7 +103,7 @@ fn missing_fonts_are_listed_symbols_included() { /// listed finds the other fonts' files. #[test] fn an_overlong_font_name_leaves_the_other_fonts_searchable() { - let root = folder("long-name"); + let (_dir, root) = folder("long-name"); std::fs::write(root.join("Findme.otf"), vectorcraft_testkit::fonts::renamed("Findme Sans 3")).unwrap(); let mut s = session_for(&root); s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap(); @@ -120,7 +120,7 @@ fn an_overlong_font_name_leaves_the_other_fonts_searchable() { /// apps' folders, such as the attachments a mail app keeps in the home folder's Library. #[test] fn the_fonts_folder_next_to_a_document_in_another_apps_folder_isnt_offered() { - let root = folder("next-to"); + let (_dir, root) = folder("next-to"); let home = root.join("Users/me"); let mut s = Session::new(); s.search_rules = Some(Rules { home: Some(home.clone()), ..Rules::default() }); @@ -140,7 +140,7 @@ fn the_fonts_folder_next_to_a_document_in_another_apps_folder_isnt_offered() { #[cfg(unix)] #[test] fn the_fonts_folder_next_to_a_document_is_an_absolute_path() { - let root = folder("relative"); + let (_dir, root) = folder("relative"); std::fs::create_dir_all(root.join("pkg/Fonts")).unwrap(); let cwd = std::env::current_dir().unwrap(); let up = "../".repeat(cwd.components().count().saturating_sub(1)); @@ -160,7 +160,7 @@ fn the_fonts_folder_next_to_a_document_is_an_absolute_path() { #[test] fn a_search_finds_a_missing_fonts_file_by_its_names() { - let root = folder("find"); + let (_dir, root) = folder("find"); std::fs::create_dir_all(root.join("x/y")).unwrap(); std::fs::write(root.join("x/y/Findme.otf"), vectorcraft_testkit::fonts::renamed("Findme Sans 3")).unwrap(); std::fs::write(root.join("other.ttf"), bundled("SourceSerif4-Regular.ttf")).unwrap(); @@ -199,7 +199,7 @@ fn a_search_finds_a_missing_fonts_file_by_its_names() { /// when they are inside them. #[test] fn a_search_shows_a_confined_caller_only_paths_inside_its_read_roots() { - let root = folder("read-roots"); + let (_dir, root) = folder("read-roots"); let font = vectorcraft_testkit::fonts::renamed("Findme Sans 3"); let (home, wide) = (root.join("home"), root.join("lrf-wide")); for dir in [&home, &wide] { @@ -228,12 +228,11 @@ fn a_search_shows_a_confined_caller_only_paths_inside_its_read_roots() { assert!(finished(&mut s)["error"].as_str().is_some_and(|e| e.contains("lrf-wide"))); let r = ask(&mut s, &narrow, json!({})); assert_eq!((r["state"].as_str(), r["error"].as_str(), r.get("folder")), (Some("failed"), Some("the folder can't be read"), None), "{r}"); - let _ = std::fs::remove_dir_all(&root); } #[test] fn junk_search_params_never_fail_internally() { - let root = folder("junk"); + let (_dir, root) = folder("junk"); let mut s = session_for(&root); s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap(); text(&mut s, 20.0, "No Such Font Family", "Regular"); @@ -297,7 +296,7 @@ impl Visitor for Blocked { #[test] fn stop_ends_only_the_search_it_names() { - let root = folder("stop"); + let (_dir, root) = folder("stop"); std::fs::write(root.join("a.ttf"), b"font").unwrap(); let mut s = session_for(&root); let (tx, rx) = mpsc::channel(); @@ -330,7 +329,7 @@ fn adding_fonts_needs_vectorcraft_s_fonts_folder() { #[test] fn copying_never_replaces_a_file() { - let root = folder("copy"); + let (_dir, root) = folder("copy"); let (src, dest) = (root.join("src"), root.join("dest")); std::fs::create_dir_all(&src).unwrap(); std::fs::create_dir_all(&dest).unwrap(); @@ -376,12 +375,11 @@ fn copying_never_replaces_a_file() { assert_eq!(reasons[..2], ["larger than 256 MB", "not a file"]); assert!(r.copied.is_empty() && reasons.len() == 3, "{r:?}"); assert!(!dest.join("huge.otf").exists() && !dest.join("folder.otf").exists()); - let _ = std::fs::remove_dir_all(&root); } #[test] fn only_font_files_are_copied() { - let root = folder("allowed"); + let (_dir, root) = folder("allowed"); let (src, dest) = (root.join("src"), root.join("dest")); std::fs::create_dir_all(&src).unwrap(); std::fs::create_dir_all(&dest).unwrap(); @@ -395,13 +393,12 @@ fn only_font_files_are_copied() { let not_a_font = |n: &str| (src.join(n), "not a font file".to_string()); assert_eq!(r.skipped, [not_a_font("notes.txt"), not_a_font("Script")]); assert!(!dest.join("notes.txt").exists() && !dest.join("Script").exists()); - let _ = std::fs::remove_dir_all(&root); } /// A search reads no font file larger than Add Fonts copies, and finds a smaller copy of the font. #[test] fn a_search_skips_font_files_too_large_to_add() { - let root = folder("too-large"); + let (_dir, root) = folder("too-large"); let (big, small) = (root.join("big").join("Sizeme.otf"), root.join("small").join("Sizeme.otf")); let font = vectorcraft_testkit::fonts::renamed("Sizeme Sans 3"); for path in [&big, &small] { @@ -415,7 +412,6 @@ fn a_search_skips_font_files_too_large_to_add() { s.execute("text.findFontFiles", &json!({"folder": root, "fonts": [{"family": "Sizeme Sans 3"}, {"family": "No Such Sans"}]})).unwrap(); let r = finished(&mut s); assert_eq!(r["fonts"][0]["files"], json!([small]), "{r}"); - let _ = std::fs::remove_dir_all(&root); } /// A suitcase font: a file without an extension or with `.suit`, empty but for the fonts in its @@ -424,7 +420,7 @@ fn a_search_skips_font_files_too_large_to_add() { #[test] fn suitcase_fonts_are_found_and_copied_with_their_fork() { use vectorcraft_testkit::fonts::{renamed, suitcase_fork}; - let root = folder("suitcase"); + let (_dir, root) = folder("suitcase"); let (src, dest) = (root.join("src"), root.join("dest")); std::fs::create_dir_all(src.join("sub")).unwrap(); std::fs::create_dir_all(&dest).unwrap(); @@ -467,5 +463,4 @@ fn suitcase_fonts_are_found_and_copied_with_their_fork() { // The font scan reads the copies. let db = vectorcraft_text::FontDb::with_font_dirs(vec![dest.clone()]); assert_eq!((db.styles("Suitme Sans 3"), db.styles("Other Sans 33")), (vec!["Regular".to_string()], vec!["Regular".to_string()])); - let _ = std::fs::remove_dir_all(&root); } diff --git a/crates/engine/src/tests/gradient.rs b/crates/engine/src/tests/gradient.rs index a2aea6341d..b8c8bcd325 100644 --- a/crates/engine/src/tests/gradient.rs +++ b/crates/engine/src/tests/gradient.rs @@ -511,7 +511,7 @@ fn an_outlined_stroke_leaves_dither_behind() { /// The Gradient panel's Method (Illustrator 30): `method` set and cleared through the gradient /// commands, on fills and strokes, kept by the params, swatches and a native save and load; -/// anything but classic or perceptual is refused without editing. +/// anything but the four method names is refused without editing. #[test] fn method_is_a_gradient_option_that_saves_and_loads() { use vectorcraft_color::GradientMethod; @@ -548,7 +548,7 @@ fn method_is_a_gradient_option_that_saves_and_loads() { let before = node(&s, id).appearance.clone(); for bad in [json!("smooth"), json!(1), json!(true)] { let e = s.execute("paint.editGradient", &json!({"method": bad})).unwrap_err().to_string(); - assert!(e.contains("`method` must be classic or perceptual"), "{e}"); + assert!(e.contains("`method` must be classic, perceptual, hue-clockwise or hue-counterclockwise"), "{e}"); assert!(s.execute("paint.setFill", &json!({"gradient": {"method": bad}})).is_err()); } assert_eq!(node(&s, id).appearance, before); @@ -566,6 +566,76 @@ fn method_is_a_gradient_option_that_saves_and_loads() { assert!(back.gradient.dither && back.gradient.method == GradientMethod::Perceptual); } +/// The hue methods: `method` hue-clockwise and hue-counterclockwise set through the gradient +/// commands on fills and strokes, as one undo step, kept by the params, a swatch, a saved preset +/// and a native save and load, and written with or without the hyphen. +#[test] +fn the_hue_methods_are_set_saved_and_loaded() { + use vectorcraft_color::GradientMethod; + let mut s = session(); + let id = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let stops = json!([{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]); + s.execute("paint.setFill", &json!({"gradient": {"stops": stops}})).unwrap(); + for (name, method, middle) in + [("hue-clockwise", GradientMethod::HueClockwise, "#ff00ff"), ("hue-counterclockwise", GradientMethod::HueCounterclockwise, "#00ff00")] + { + let undo = s.doc().unwrap().history.undo.len(); + s.execute("paint.editGradient", &json!({"method": name})).unwrap(); + let g = fill_gradient(&s, id); + assert_eq!(g.gradient.method, method); + assert_eq!(g.gradient.stops.len(), 2, "{name}: the stops stay as they were"); + assert_eq!(g.gradient.sample(0.5).0.to_hex(), middle, "{name}: halfway around the wheel"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "{name}: one undo step"); + // The params carry it, so a swatch, a preset and a copied paint keep it. + let p = vectorcraft_tools::params::gradient_params(&g); + assert_eq!(p["method"], json!(name)); + let mut q = gradient_param(&g); + q["name"] = json!(format!("Wheel {name}")); + s.execute("swatch.new", &q).unwrap(); + let Some(Paint::Gradient(sw)) = s.doc().unwrap().doc.swatch(&format!("Wheel {name}")).map(|w| w.paint.clone()) else { + panic!("a gradient swatch") + }; + assert_eq!(sw.gradient.method, method, "{name}: the swatch"); + s.execute("gradient.presets.save", &json!({"name": format!("Preset {name}")})).unwrap(); + s.execute("paint.editGradient", &json!({"method": "classic"})).unwrap(); + s.execute("gradient.presets.apply", &json!({"name": format!("Preset {name}")})).unwrap(); + assert_eq!(fill_gradient(&s, id).gradient.method, method, "{name}: the preset"); + // Saved and opened again. + let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + let Paint::Gradient(saved) = back.node(id).unwrap().appearance.fill_paint() else { panic!("a gradient fill") }; + assert_eq!(saved.gradient.method, method, "{name}: the native file keeps the method"); + } + // Strokes take it too, and the name reads without the hyphen and in any case. + for (name, method) in [("hue-clockwise", GradientMethod::HueClockwise), ("hue-counterclockwise", GradientMethod::HueCounterclockwise)] { + for written in [name.replace('-', " "), name.replace('-', "").to_uppercase()] { + s.execute("paint.setStroke", &json!({"gradient": {"method": "classic"}})).unwrap(); + s.execute("paint.editGradient", &json!({"method": written, "stroke": true})).unwrap(); + let Paint::Gradient(st) = node(&s, id).appearance.stroke_paint() else { panic!("a gradient stroke") }; + assert_eq!(st.gradient.method, method, "{written}"); + } + } + // Reverse gives the same ramp the other way round: the hue method turns with the stops, so + // the middle keeps its color, unless the edit names a method too. + s.execute("paint.editGradient", &json!({"method": "hue-clockwise", "stroke": false})).unwrap(); + let before = fill_gradient(&s, id).gradient; + s.execute("paint.editGradient", &json!({"reverse": true, "stroke": false})).unwrap(); + let after = fill_gradient(&s, id).gradient; + assert_eq!(after.method, GradientMethod::HueCounterclockwise); + assert_eq!((after.stops[0].color.to_hex(), after.stops[1].color.to_hex()), ("#0000ff".to_string(), "#ff0000".to_string())); + for t in [0.25, 0.5, 0.75] { + assert_eq!(after.sample(t).0.to_hex(), before.sample(1.0 - t).0.to_hex(), "reversed at {t}"); + } + s.execute("paint.editGradient", &json!({"reverse": true, "method": "hue-counterclockwise", "stroke": false})).unwrap(); + assert_eq!(fill_gradient(&s, id).gradient.method, GradientMethod::HueCounterclockwise, "a method in the edit wins"); + // Half a name is refused, nothing changed. + let before = node(&s, id).appearance.clone(); + for bad in ["hue", "clockwise", "hue-clock"] { + let e = s.execute("paint.editGradient", &json!({"method": bad})).unwrap_err().to_string(); + assert!(e.contains("`method` must be classic, perceptual, hue-clockwise or hue-counterclockwise"), "{bad}: {e}"); + } + assert_eq!(node(&s, id).appearance, before); +} + /// A conic gradient through `paint.setFill`, the Gradient panel's edits, transforms, the params /// agents and swatches read, and the native format. #[test] diff --git a/crates/engine/src/tests/journal.rs b/crates/engine/src/tests/journal.rs index 5eb66ec6c8..1c4287e9c1 100644 --- a/crates/engine/src/tests/journal.rs +++ b/crates/engine/src/tests/journal.rs @@ -273,9 +273,62 @@ fn a_batch_fit_selection_replays_but_an_action_uses_the_current_selection() { assert_eq!(boards(&a), [was[0], fitted[1], fitted[2]], "the action fits the artboards selected when it plays"); } +/// The journal records the `index` a batch's Fit to Artwork Bounds step took from the batch's +/// `artboard`, or the command's default (the first artboard) when the batch names none, so a replay +/// fits that artboard even when the Artboard tool then has several selected. +#[test] +fn a_batch_fit_step_records_the_batchs_artboard() { + let fitted = three_fitted_artboards(); + let boards = |s: &Session| s.doc().unwrap().doc.artboards.iter().map(|a| a.rect).collect::>(); + let steps = json!([{"command": "artboard.fitToArt", "params": {}}]); + for (batch, index, picks) in [(json!({"artboard": 1, "commands": steps}), 1, json!([0, 2])), (json!({"commands": steps}), 0, json!([1, 2]))] { + let mut s = Session::new(); + let was = three_artboards_with_art(&mut s); + let start = s.journal.len(); + s.execute("command.batch", &batch).unwrap(); + let mut want = was.clone(); + want[index] = fitted[index]; + assert_eq!(boards(&s), want, "{batch}"); + let (id, p) = s.journal.last().unwrap().clone(); + assert_eq!((id.as_str(), &p["commands"][0]["params"]), ("command.batch", &json!({ "index": index }))); + let mut r = Session::new(); + for (n, (id, p)) in s.journal.iter().enumerate() { + if n == start { + r.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap(); + r.set_tool_option("selected", &picks); + } + r.execute(id, p).unwrap(); + } + assert_eq!(boards(&r), want, "{batch}: the replay fits artboard {index}, not the selected ones"); + assert_eq!(s.journal_for_action(start), [("command.batch".to_string(), json!({"commands": steps}))]); + } +} + +/// A batch step with `"params": null` gets the Artboard tool's selected artboards, or else the +/// batch's `artboard`, as a step without params does. +#[test] +fn a_batch_fit_step_with_null_params_gets_the_artboards() { + let fitted = three_fitted_artboards(); + let boards = |s: &Session| s.doc().unwrap().doc.artboards.iter().map(|a| a.rect).collect::>(); + let steps = json!([{"command": "artboard.fitToArt", "params": null}]); + let mut s = Session::new(); + let was = three_artboards_with_art(&mut s); + s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap(); + s.set_tool_option("selected", &json!([2, 0])); + s.execute("command.batch", &json!({"artboard": 1, "commands": steps})).unwrap(); + assert_eq!(boards(&s), [fitted[0], was[1], fitted[2]], "the selected artboards"); + let (_, p) = s.journal.last().unwrap().clone(); + assert_eq!(p["commands"][0]["params"], json!({"indices": [0, 2]})); + let mut s = Session::new(); + three_artboards_with_art(&mut s); + s.execute("command.batch", &json!({"artboard": 1, "commands": steps})).unwrap(); + assert_eq!(boards(&s), [was[0], fitted[1], was[2]], "the batch's artboard"); +} + #[test] fn a_save_records_its_date_and_replays_it() { - let path = vectorcraft_testkit::temp_dir("journal-save").join("a.vectorcraft").to_string_lossy().into_owned(); + let dir = vectorcraft_testkit::TempDir::new("journal-save"); + let path = dir.join("a.vectorcraft").to_string_lossy().into_owned(); let mut s = Session::new(); s.execute("file.new", &json!({"created": null})).unwrap(); s.execute("document.save", &json!({"path": path})).unwrap(); @@ -290,7 +343,6 @@ fn a_save_records_its_date_and_replays_it() { assert_eq!(s.doc().unwrap().doc.metadata.modified, Some(2_000_000_000)); assert!(s.execute("document.save", &json!({"path": path, "modified": "today"})).is_err()); // Save As stamps the same way; Save a Copy leaves the document's dates (and records none). - let dir = vectorcraft_testkit::temp_dir("journal-save"); s.execute("file.saveAs", &json!({"path": dir.join("b.vectorcraft").to_string_lossy(), "modified": 2_000_000_100})).unwrap(); assert_eq!(s.journal.last().unwrap().1["modified"], json!(2_000_000_100)); s.execute("file.saveCopy", &json!({"path": dir.join("c.vectorcraft").to_string_lossy()})).unwrap(); @@ -316,7 +368,8 @@ fn replayed(s: &Session) -> Session { #[test] fn a_save_in_a_batch_records_its_date_and_replays_it() { - let path = vectorcraft_testkit::temp_dir("journal-batch").join("a.vectorcraft").to_string_lossy().into_owned(); + let dir = vectorcraft_testkit::TempDir::new("journal-batch"); + let path = dir.join("a.vectorcraft").to_string_lossy().into_owned(); let mut s = Session::new(); s.execute("file.new", &json!({"created": 1_000_000_000})).unwrap(); let rect = json!({"x": 10, "y": 10, "width": 50, "height": 40}); @@ -698,7 +751,8 @@ fn a_failed_batch_closes_the_documents_it_opened_and_restores_the_ones_it_closed #[test] fn a_failed_batch_brings_back_a_document_it_reverted() { - let path = vectorcraft_testkit::temp_dir("journal-batch").join("revert.vectorcraft").to_string_lossy().into_owned(); + let dir = vectorcraft_testkit::TempDir::new("journal-batch"); + let path = dir.join("revert.vectorcraft").to_string_lossy().into_owned(); let mut s = Session::new(); s.execute("file.new", &json!({"created": null})).unwrap(); s.execute("document.save", &json!({"path": path, "modified": null})).unwrap(); diff --git a/crates/engine/src/tests/library.rs b/crates/engine/src/tests/library.rs index d7927ec6bf..c2dccc7bb5 100644 --- a/crates/engine/src/tests/library.rs +++ b/crates/engine/src/tests/library.rs @@ -816,7 +816,7 @@ fn style_order_of(s: &mut Session) -> Vec { #[cfg(not(target_arch = "wasm32"))] #[test] fn a_library_item_rename_is_saved_or_taken_back() { - let dir = vectorcraft_testkit::temp_dir("library-rename-item"); + let dir = vectorcraft_testkit::TempDir::new("library-rename-item"); let folder = dir.to_string_lossy().to_string(); let mut s = session(); s.libraries.set_dir(Some(folder.clone())); @@ -836,7 +836,6 @@ fn a_library_item_rename_is_saved_or_taken_back() { run(&mut s, "library.renameItem", json!({"kind": "charStyle", "item": "Text", "name": " Text "})); assert!(s.execute("library.renameItem", &json!({"kind": "charStyle", "item": "Text", "name": "Copy"})).is_err()); assert_eq!(style_order_of(&mut s), ["Text"], "taken back"); - let _ = std::fs::remove_dir_all(&dir); } #[cfg(not(target_arch = "wasm32"))] @@ -1056,7 +1055,8 @@ fn a_new_item_is_added_where_it_is_dropped() { #[cfg(not(target_arch = "wasm32"))] #[test] fn an_add_that_cannot_be_placed_makes_no_library() { - let folder = vectorcraft_testkit::temp_dir("library-add-unplaced").to_string_lossy().to_string(); + let dir = vectorcraft_testkit::TempDir::new("library-add-unplaced"); + let folder = dir.to_string_lossy().to_string(); let mut s = session(); s.libraries.set_dir(Some(folder.clone())); for bad in [json!({"kind": "fillColor", "color": "#808080", "group": "Nope"}), json!({"kind": "fillColor", "color": "#808080", "after": "Nope"})] @@ -1163,7 +1163,7 @@ fn a_library_of_one_repeated_name_imports_numbered() { #[cfg(not(target_arch = "wasm32"))] #[test] fn a_library_is_exported_to_a_file_and_imported_from_it() { - let dir = vectorcraft_testkit::temp_dir("library-export"); + let dir = vectorcraft_testkit::TempDir::new("library-export"); let path = dir.join("Brand.vclibrary").to_string_lossy().to_string(); let (mut s, g, ..) = brand(); run(&mut s, "library.createGroup", json!({"name": "Logos", "items": [{"kind": "graphic", "item": g}]})); diff --git a/crates/engine/src/tests/linked_stops.rs b/crates/engine/src/tests/linked_stops.rs index 7f70d24ff0..9ed3db2724 100644 --- a/crates/engine/src/tests/linked_stops.rs +++ b/crates/engine/src/tests/linked_stops.rs @@ -416,6 +416,34 @@ fn spot_gradients_drawn_as_images_warn() { assert!(!spot_warning(&warnings), "{warnings:?}"); } +/// A spot gradient mixed around the hue wheel is an image in process colors with the warning, +/// where the same stops mixed by Perceptual are a Separation or DeviceN shading: the colors +/// between its stops are not tints or mixes of the stops' inks. +#[test] +fn hue_wheel_spot_gradients_export_as_images_and_warn() { + let (mut s, _) = setup(); + run(&mut s, "swatch.new", json!({"name": "Leaf", "color": {"c": 1, "m": 0, "y": 1, "k": 0}, "spot": true})); + let spot_warning = |w: &[String]| w.iter().any(|w| w.contains("spot colors in gradients exported as images")); + let ink_to_leaf = json!({"stops": [{"offset": 0, "swatch": "Ink"}, {"offset": 1, "swatch": "Leaf"}]}); + for method in ["hue-clockwise", "hue-counterclockwise"] { + for (what, stops) in [("Ink → paper", ink_to_white(80.0)), ("Ink → Leaf", ink_to_leaf.clone())] { + for kind in ["linear", "radial", "conic", "diamond"] { + run(&mut s, "paint.editGradient", with(stops.clone(), json!({"method": method, "kind": kind}))); + let (pdf, warnings) = pdf_of(&s); + assert!(pdf.contains("/Subtype/Image"), "{method} {kind} {what}: an image"); + assert!(!pdf.contains("/Separation") && !pdf.contains("/DeviceN"), "{method} {kind} {what}: no spot ink shading"); + assert!(spot_warning(&warnings), "{method} {kind} {what}: {warnings:?}"); + } + } + // Without spot inks: an image, without the warning. + let red_blue = json!({"stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}], "kind": "linear"}); + run(&mut s, "paint.editGradient", with(red_blue, json!({"method": method}))); + let (pdf, warnings) = pdf_of(&s); + assert!(pdf.contains("/Subtype/Image"), "{method}: a process gradient is an image"); + assert!(!spot_warning(&warnings), "{method}: {warnings:?}"); + } +} + #[test] fn freeform_gradients_without_points_warn_about_spot_stops() { let (mut s, id) = setup(); diff --git a/crates/engine/src/tests/linkfiles.rs b/crates/engine/src/tests/linkfiles.rs index ef9127042a..6f64a2fe33 100644 --- a/crates/engine/src/tests/linkfiles.rs +++ b/crates/engine/src/tests/linkfiles.rs @@ -14,12 +14,12 @@ use crate::cmd::linkfiles::{self, LinkSearch, Sought}; use crate::tests_links::{BLUE, RED, place, png}; use crate::{EngineError, Session}; -/// A fresh temporary folder (canonical, as a search reports it). -fn folder(tag: &str) -> PathBuf { - let dir = vectorcraft_testkit::temp_dir(&format!("linkfiles-{tag}")); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - findfiles::plain(std::fs::canonicalize(&dir).unwrap()) +/// A fresh temporary folder, removed when the first part is dropped, and its path (canonical, as a +/// search reports it). +fn folder(tag: &str) -> (vectorcraft_testkit::TempDir, PathBuf) { + let dir = vectorcraft_testkit::TempDir::new(&format!("linkfiles-{tag}")); + let path = findfiles::plain(std::fs::canonicalize(&*dir).unwrap()); + (dir, path) } /// Write `bytes` to the file at `path`, making its folders. @@ -80,7 +80,7 @@ fn found(r: &Value, name: &str, root: &Path) -> Vec<(String, String, bool)> { /// innermost out up to the first that differs. #[test] fn files_found_are_ranked_by_what_the_link_saved() { - let root = folder("rank"); + let (_dir, root) = folder("rank"); let mut s = session_for(&root); let (logo, photo) = (png(60, 40, RED), png(50, 30, BLUE)); write(&root.join("orig/logo.png"), &logo); @@ -127,7 +127,7 @@ fn files_found_are_ranked_by_what_the_link_saved() { /// the files found are ranked by the folder names they share with that path. #[test] fn a_classic_mac_path_is_found_by_its_name_and_folders() { - let root = folder("classic"); + let (_dir, root) = folder("classic"); let mut s = session_for(&root); let photo = png(50, 30, BLUE); write(&root.join("orig/photo.png"), &photo); @@ -158,7 +158,7 @@ fn a_classic_mac_path_is_found_by_its_name_and_folders() { #[test] fn parent_components_in_a_saved_path_are_resolved_before_ranking() { for (tag, saved) in [("classic-up", "Old Disk:Projects:Art::photo.png"), ("slash-up", "/old/Projects/Art/../photo.png")] { - let root = folder(tag); + let (_dir, root) = folder(tag); let mut s = session_for(&root); let photo = png(50, 30, BLUE); write(&root.join("orig/photo.png"), &photo); @@ -188,7 +188,7 @@ fn parent_components_in_a_saved_path_are_resolved_before_ranking() { /// files, whatever their status. #[test] fn a_search_looks_for_the_missing_files_or_the_objects_given() { - let root = folder("which"); + let (_dir, root) = folder("which"); let mut s = session_for(&root); write(&root.join("orig/gone.png"), &png(40, 30, RED)); write(&root.join("orig/here.png"), &png(40, 30, BLUE)); @@ -225,7 +225,7 @@ fn a_search_looks_for_the_missing_files_or_the_objects_given() { /// other contents leaves it to search every folder. #[test] fn a_search_ends_once_every_linked_file_has_its_same_file() { - let root = folder("early"); + let (_dir, root) = folder("early"); let mut s = session_for(&root); s.search_threads = Some(1); let bytes = png(40, 30, RED); @@ -265,7 +265,7 @@ impl Visitor for Blocked { #[test] fn stop_ends_only_the_search_it_names() { - let root = folder("stop"); + let (_dir, root) = folder("stop"); std::fs::write(root.join("a.png"), b"png").unwrap(); let mut s = session_for(&root); let (tx, rx) = mpsc::channel(); @@ -290,7 +290,7 @@ fn stop_ends_only_the_search_it_names() { /// roots, the replies are as before. #[test] fn a_search_shows_a_confined_caller_only_paths_inside_its_read_roots() { - let root = folder("read-roots"); + let (_dir, root) = folder("read-roots"); let mut s = session_for(&root); let photo = png(40, 30, RED); write(&root.join("lrf-away/photo.png"), &photo); @@ -343,14 +343,13 @@ fn a_search_shows_a_confined_caller_only_paths_inside_its_read_roots() { let r = ask(&mut s, &narrow, json!({})); assert_eq!((r["state"].as_str(), r["error"].as_str()), (Some("failed"), Some("the folder can't be read")), "{r}"); hidden(&r); - let _ = std::fs::remove_dir_all(&root); } /// A link's saved path relative to the document is shown to a confined caller when it leads to a /// file inside its read roots, and left out when `..` leads out of them. #[test] fn a_relative_link_path_is_judged_from_the_documents_folder() { - let root = folder("read-roots-relative"); + let (_dir, root) = folder("read-roots-relative"); let mut s = session_for(&root); let home = root.join("home"); write(&root.join("lrf-away/photo.png"), &png(40, 30, RED)); @@ -370,14 +369,13 @@ fn a_relative_link_path_is_judged_from_the_documents_folder() { assert_eq!(r["links"][0].get("path"), shown.then(|| json!(saved)).as_ref(), "{saved}: {r}"); finished(&mut s); } - let _ = std::fs::remove_dir_all(&root); } /// `image.info` leaves a linked file outside the confined caller's read roots unnamed (`link` /// null), as `links.info` leaves it out, and keeps the other fields. #[test] fn image_info_leaves_out_a_link_outside_the_read_roots() { - let root = folder("read-roots-info"); + let (_dir, root) = folder("read-roots-info"); let mut s = session_for(&root); let pic = root.join("lrf-away/photo.png"); write(&pic, &png(40, 30, RED)); @@ -391,12 +389,11 @@ fn image_info_leaves_out_a_link_outside_the_read_roots() { let info = ask(&mut s, "links.info"); assert!(info.get("link").is_none() && !info.to_string().contains("lrf-away"), "{info}"); assert_eq!(s.execute("image.info", &json!({"id": id})).unwrap()["link"], json!(pic)); - let _ = std::fs::remove_dir_all(&root); } #[test] fn relinking_with_copy_puts_the_file_in_the_documents_folder() { - let root = folder("copy"); + let (_dir, root) = folder("copy"); let mut s = session_for(&root); write(&root.join("orig/photo.png"), &png(40, 30, RED)); let id = placed(&mut s, &root.join("orig/photo.png")); @@ -443,14 +440,13 @@ fn relinking_with_copy_puts_the_file_in_the_documents_folder() { let image = placed(&mut unsaved, &found); let r = unsaved.execute("links.relink", &json!({"ids": [image], "path": found, "copy": true})); assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg.contains("save the document first")), "{r:?}"); - let _ = std::fs::remove_dir_all(&root); } /// Copy takes images only: with copy, a call that includes a placed document fails and copies /// nothing; without it, the document is relinked where its file is. #[test] fn copy_refuses_placed_documents() { - let root = folder("copy-placed"); + let (_dir, root) = folder("copy-placed"); let mut s = session_for(&root); s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); let badge = root.join("badge.vectorcraft"); @@ -471,7 +467,7 @@ fn copy_refuses_placed_documents() { #[cfg(unix)] #[test] fn a_copy_stays_inside_the_write_root() { - let root = folder("roots"); + let (_dir, root) = folder("roots"); let mut s = session_for(&root); write(&root.join("orig/photo.png"), &png(40, 30, RED)); let id = placed(&mut s, &root.join("orig/photo.png")); @@ -487,14 +483,13 @@ fn a_copy_stays_inside_the_write_root() { assert!(matches!(&r, Err(EngineError::Other(m)) if m.contains("outside the write root")), "{r:?}"); assert!(!root.join("doc/photo 2.png").exists()); assert_eq!(std::fs::read(allowed.join("photo.png")).unwrap(), b"kept as it is"); - let _ = std::fs::remove_dir_all(&root); } /// An SVG's linked files are read on the importer's own thread (it needs a deep stack): the roots /// in force on the thread that opens the SVG hold there too. #[test] fn an_svg_reads_its_links_within_the_read_root() { - let root = folder("svg-roots"); + let (_dir, root) = folder("svg-roots"); for dir in ["in", "out"] { write(&root.join(dir).join("dot.png"), &png(4, 4, RED)); } @@ -513,12 +508,11 @@ fn an_svg_reads_its_links_within_the_read_root() { assert_eq!(import("in"), inside, "inside the read root: read as before"); assert_ne!(import("out"), outside, "outside the read root: not read"); }); - let _ = std::fs::remove_dir_all(&root); } #[test] fn junk_search_params_never_fail_internally() { - let root = folder("junk"); + let (_dir, root) = folder("junk"); let mut s = session_for(&root); write(&root.join("orig/a.png"), &png(4, 4, RED)); let id = placed(&mut s, &root.join("orig/a.png")); diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index deaf60b64f..209d22a42a 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -631,6 +631,39 @@ fn the_profile_follows_the_preset_access_and_reset() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn profile_errors_name_the_file_by_its_name_outside_the_read_roots() { + let (mut s, dir) = with_profiles("errors"); + let elsewhere = dir.with_extension("elsewhere"); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::create_dir_all(&elsewhere).unwrap(); + let whole = dir.join("Print.vectorcraft").to_string_lossy().to_string(); + let run = |s: &mut Session, roots: &std::sync::Arc, cmd: &str| { + crate::file_access::confine(Some(roots), || s.execute(cmd, &json!({"name": "Print"}))).unwrap_err().to_string() + }; + // No write access: edit and reset are refused before anything is written or deleted. + let read_only = crate::file_access::AutomationRoots::new(&[elsewhere.as_path()], &[]).unwrap().unwrap(); + for cmd in ["file.newProfiles.edit", "file.newProfiles.reset"] { + let e = run(&mut s, &read_only, cmd); + assert!(e.ends_with(": Print.vectorcraft") && !e.contains(&whole), "{cmd}: {e}"); + } + // Write access without read access: edit is refused, and nothing is written. + let write_only = crate::file_access::AutomationRoots::new(&[elsewhere.as_path()], &[dir.as_path()]).unwrap().unwrap(); + let e = run(&mut s, &write_only, "file.newProfiles.edit"); + assert!(e.contains("outside the read root") && e.ends_with(": Print.vectorcraft") && !e.contains(&whole), "{e}"); + assert!(!dir.join("Print.vectorcraft").exists()); + // A file reset cannot delete (a folder in its place) is named by its file name too. + std::fs::create_dir_all(dir.join("Print.vectorcraft")).unwrap(); + let e = run(&mut s, &write_only, "file.newProfiles.reset"); + assert!(e.starts_with("Print.vectorcraft: ") && !e.contains(&whole), "{e}"); + // Inside the read roots the error names the whole path. + let inside = crate::file_access::AutomationRoots::new(&[dir.as_path()], &[dir.as_path()]).unwrap().unwrap(); + let e = run(&mut s, &inside, "file.newProfiles.reset"); + assert!(e.starts_with(&format!("{whole}: ")), "{e}"); + let _ = std::fs::remove_dir_all(&elsewhere); + let _ = std::fs::remove_dir_all(&dir); +} + /// The new document's links find their files from the profile's file, as a document opened from /// that file does; a document without a profile has no such file. #[test] diff --git a/crates/engine/src/tests/objexpand.rs b/crates/engine/src/tests/objexpand.rs index b8c4724853..32c0cb143f 100644 --- a/crates/engine/src/tests/objexpand.rs +++ b/crates/engine/src/tests/objexpand.rs @@ -1600,3 +1600,54 @@ fn expand_info_counts_two_fills_but_not_a_plain_rectangle() { run(&mut s, "appearance.addFill", json!({})); assert_eq!(run(&mut s, "object.expand.info", json!({}))["appearance"], json!(true), "two fills"); } + +/// A Transform effect left out past the effect budget (its result over 8 million lines drawn) +/// leaves the art where it is, and Expand, Expand Appearance and Outline Stroke keep the drop +/// shadow before it with its own offset and blur, as the canvas draws it: the object's, the fill's +/// and the stroke's. +#[test] +fn a_shadow_before_a_skipped_transform_expands_with_its_own_offset() { + use vectorcraft_doc::{Appearance, Effect}; + use vectorcraft_geom::{Anchor, PathData, Point, SubPath}; + let anchors = (0..=30_000) + .map(|i| { + let x = 2.0 * f64::from(i); + Anchor::with_handles(Point::new(x, 0.0), Point::new(x - 0.5, -20.0), Point::new(x + 0.5, 20.0)) + }) + .collect(); + let path = PathData::single(SubPath::new(anchors, true)); + let bounds = path.bounds().unwrap(); + let effects = || { + vec![ + Effect { id: "stylize.dropShadow".into(), params: json!({"x": 10, "y": 5, "blur": 4}), visible: true }, + Effect { id: "distort.transform".into(), params: json!({"scaleH": 100000, "scaleV": 100000}), visible: true }, + ] + }; + let shadow = |effects: &[Effect]| match vectorcraft_render::effects::raster_effects(effects).first() { + Some(vectorcraft_render::effects::RasterFx::DropShadow { dx, dy, blur, .. }) => (*dx, *dy, *blur), + other => panic!("expected a drop shadow, got {other:?}"), + }; + let mut d = vectorcraft_doc::Document::new(200.0, 200.0); + let basic = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 2.0); + let mut object = Node::path(NodeId(1), path.clone(), basic.clone()); + object.appearance.effects = effects(); + let m = crate::cmd::expand::reshaped(&d, &object).unwrap(); + assert_eq!(m.geometric_bounds(), Some(bounds), "the art stays where it is"); + assert_eq!(shadow(&m.appearance.effects), (10.0, 5.0, 4.0), "the object's shadow"); + let mut fill = Node::path(NodeId(2), path.clone(), basic.clone()); + *fill.appearance.items[0].effects_mut() = effects(); + let (_, _, _, moved) = crate::cmd::expand::fill_shape(&d, &fill, &fill.appearance.items[0], &path, bounds).unwrap(); + assert_eq!(shadow(moved.effects()), (10.0, 5.0, 4.0), "the fill's shadow"); + let mut stroke = Node::path(NodeId(3), path.clone(), basic); + *stroke.appearance.items[1].effects_mut() = effects(); + let outlined = crate::cmd::pathops::outline_strokes(&mut d, &[], &stroke).unwrap(); + let mut drawn = vec![]; + outlined.walk(&mut |n| { + for item in &n.appearance.items { + if !vectorcraft_render::effects::raster_effects(item.effects()).is_empty() { + drawn.push(shadow(item.effects())); + } + } + }); + assert_eq!(drawn, [(10.0, 5.0, 4.0)], "the stroke's shadow"); +} diff --git a/crates/engine/src/tests/prefs.rs b/crates/engine/src/tests/prefs.rs index 3808d06797..37127f686a 100644 --- a/crates/engine/src/tests/prefs.rs +++ b/crates/engine/src/tests/prefs.rs @@ -756,6 +756,9 @@ fn precise_cursors_replace_every_pen_state() { Cursor::LivePaintBucket, Cursor::LivePaintBucketFace, Cursor::LivePaintBucketEdge, + Cursor::LivePaintSelectFace, + Cursor::LivePaintSelectEdge, + Cursor::LivePaintSelectOutside, ] { assert_eq!(c.precise(), Cursor::Crosshair, "{c:?}"); } diff --git a/crates/engine/src/tests/shortcutset.rs b/crates/engine/src/tests/shortcutset.rs index 8f216b8c00..fb5292e243 100644 --- a/crates/engine/src/tests/shortcutset.rs +++ b/crates/engine/src/tests/shortcutset.rs @@ -51,7 +51,7 @@ fn entries_keep_their_sections_and_the_command_counts_codes() { assert_eq!(r["codes"]["modifiers"], json!([{"value": 64, "count": 2}, {"value": 80, "count": 1}])); assert_eq!((r["unread"].as_array().unwrap().len(), r["truncated"].as_bool()), (0, Some(false)), "{r}"); // The same from a file, and from its bytes. - let dir = vectorcraft_testkit::temp_dir("shortcutset-read"); + let dir = vectorcraft_testkit::TempDir::new("shortcutset-read"); let path = dir.join("Studio Keys.kys"); std::fs::write(&path, text).unwrap(); let mut s = Session::new(); @@ -59,7 +59,6 @@ fn entries_keep_their_sections_and_the_command_counts_codes() { assert_eq!((r["set"].as_str(), r["entries"].as_array().unwrap().len()), (Some("Studio Keys"), 3)); let b64 = vectorcraft_format::base64_encode(text.as_bytes()); assert_eq!(s.execute("shortcutSet.read", &json!({ "dataBase64": b64 })).unwrap()["entries"].as_array().unwrap().len(), 3); - let _ = std::fs::remove_dir_all(dir); } #[test] @@ -124,7 +123,7 @@ fn caps_nesting_entries_and_names() { #[test] fn big_files_are_read_up_to_the_cap() { let text = format!("/Menus {{ /E {{ /Key 1 }} {} }}", " ".repeat(5 << 20)); - let dir = vectorcraft_testkit::temp_dir("shortcutset-big"); + let dir = vectorcraft_testkit::TempDir::new("shortcutset-big"); let path = dir.join("Big.kys"); std::fs::write(&path, &text).unwrap(); let b64 = vectorcraft_format::base64_encode(text.as_bytes()); @@ -145,7 +144,6 @@ fn big_files_are_read_up_to_the_cap() { assert_eq!(fits.len(), (4 << 20) + 3); std::fs::write(&path, &fits).unwrap(); assert_eq!(s.execute("shortcutSet.read", &json!({ "path": path.to_string_lossy() })).unwrap()["truncated"], false); - let _ = std::fs::remove_dir_all(dir); } fn matched(s: &mut Session, p: Value) -> Vec { diff --git a/crates/engine/src/tests/spelling.rs b/crates/engine/src/tests/spelling.rs index 16d7f01993..dd10df1597 100644 --- a/crates/engine/src/tests/spelling.rs +++ b/crates/engine/src/tests/spelling.rs @@ -161,7 +161,7 @@ fn a_changed_word_replaces_the_old_one() { #[test] fn the_custom_dictionary_file_is_read_and_kept_up_to_date() { let _one_at_a_time = dictionary_lock(); - let dir = vectorcraft_testkit::temp_dir("spelling-dictionary"); + let dir = vectorcraft_testkit::TempDir::new("spelling-dictionary"); let file = dir.join("Custom Dictionary.txt"); std::fs::write(&file, "kqzvwx\nnot one word\n\n").unwrap(); let mut s = session(); @@ -224,7 +224,7 @@ fn in_dictionary(s: &mut Session, word: &str) -> bool { #[test] fn a_dictionary_file_that_cant_be_read_whole_is_never_written_over() { let _one_at_a_time = dictionary_lock(); - let dir = vectorcraft_testkit::temp_dir("spelling-unreadable"); + let dir = vectorcraft_testkit::TempDir::new("spelling-unreadable"); // A folder where the file should be can't be read as one; a file past what craft-proof reads // would lose its other words if written back. let folder = dir.join("Custom Dictionary.txt"); @@ -248,7 +248,7 @@ fn a_change_that_cant_be_saved_is_taken_back() { let _one_at_a_time = dictionary_lock(); let mut s = session(); run(&mut s, "text.spelling.addWord", json!({"word": "wkqzvx"})); - let dir = vectorcraft_testkit::temp_dir("spelling-rollback"); + let dir = vectorcraft_testkit::TempDir::new("spelling-rollback"); let folder = dir.join("Custom Dictionary.txt"); std::fs::create_dir_all(&folder).unwrap(); let mut failing = session(); @@ -266,7 +266,7 @@ fn a_change_that_cant_be_saved_is_taken_back() { fn a_dictionary_edit_is_saved_whole_or_not_at_all() { let _one_at_a_time = dictionary_lock(); const EDIT: &str = "text.spelling.editDictionary"; - let dir = vectorcraft_testkit::temp_dir("spelling-edit"); + let dir = vectorcraft_testkit::TempDir::new("spelling-edit"); let file = dir.join("Custom Dictionary.txt"); std::fs::write(&file, "pqzvka\npqzvkb\n").unwrap(); let mut s = session(); @@ -302,7 +302,7 @@ fn a_dictionary_edit_is_saved_whole_or_not_at_all() { fn a_word_another_window_saved_stays_when_this_save_fails() { let _one_at_a_time = dictionary_lock(); use std::os::unix::fs::PermissionsExt; - let dir = vectorcraft_testkit::temp_dir("spelling-readonly"); + let dir = vectorcraft_testkit::TempDir::new("spelling-readonly"); let file = dir.join("Custom Dictionary.txt"); std::fs::write(&file, "").unwrap(); let mut s = session(); diff --git a/crates/engine/src/tests/store.rs b/crates/engine/src/tests/store.rs index b6ac7b0201..21967473bb 100644 --- a/crates/engine/src/tests/store.rs +++ b/crates/engine/src/tests/store.rs @@ -7,10 +7,8 @@ use vectorcraft_color::cms; use crate::Session; use crate::store::{MAX_PRESET_FILE, file_stem, holds}; -fn fresh_dir(tag: &str) -> std::path::PathBuf { - let dir = vectorcraft_testkit::temp_dir(&format!("store-{tag}")); - let _ = std::fs::remove_dir_all(&dir); - dir +fn fresh_dir(tag: &str) -> vectorcraft_testkit::TempDir { + vectorcraft_testkit::TempDir::new(&format!("store-{tag}")) } fn saved_names(s: &mut Session) -> Vec { @@ -20,7 +18,8 @@ fn saved_names(s: &mut Session) -> Vec { #[test] fn saved_presets_come_back_in_the_next_session_and_renames_and_deletes_follow() { - let dir = fresh_dir("presets").join("PDF Presets"); + let root = fresh_dir("presets"); + let dir = root.join("PDF Presets"); let mut a = Session::new(); a.attach_pdf_preset_store(dir.clone()); a.execute("pdf.preset.save", &json!({"name": "Press", "description": "for the printer", "preset": "Press Quality"})).unwrap(); @@ -42,7 +41,8 @@ fn saved_presets_come_back_in_the_next_session_and_renames_and_deletes_follow() #[test] fn a_rename_that_cannot_be_written_keeps_the_preset_under_its_old_name() { - let dir = fresh_dir("rename-fails").join("PDF Presets"); + let root = fresh_dir("rename-fails"); + let dir = root.join("PDF Presets"); let mut a = Session::new(); a.attach_pdf_preset_store(dir.clone()); a.execute("pdf.preset.save", &json!({"name": "Web", "description": "for screens"})).unwrap(); @@ -59,7 +59,8 @@ fn a_rename_that_cannot_be_written_keeps_the_preset_under_its_old_name() { #[test] fn a_rename_that_only_changes_case_keeps_one_file() { - let dir = fresh_dir("rename-case").join("PDF Presets"); + let root = fresh_dir("rename-case"); + let dir = root.join("PDF Presets"); let mut a = Session::new(); a.attach_pdf_preset_store(dir.clone()); a.execute("pdf.preset.save", &json!({"name": "Web"})).unwrap(); @@ -80,7 +81,8 @@ fn file_names(dir: &std::path::Path) -> Vec { #[cfg(windows)] #[test] fn a_rename_that_only_changes_case_and_cannot_be_written_keeps_the_old_file() { - let dir = fresh_dir("rename-case-fails").join("PDF Presets"); + let root = fresh_dir("rename-case-fails"); + let dir = root.join("PDF Presets"); let mut a = Session::new(); a.attach_pdf_preset_store(dir.clone()); a.execute("pdf.preset.save", &json!({"name": "Web", "description": "for screens"})).unwrap(); @@ -103,7 +105,8 @@ fn a_rename_that_only_changes_case_and_cannot_be_written_keeps_the_old_file() { #[cfg(not(any(windows, target_vendor = "apple")))] #[test] fn a_rename_that_only_changes_case_and_cannot_be_moved_keeps_the_old_preset() { - let dir = fresh_dir("rename-case-blocked").join("PDF Presets"); + let root = fresh_dir("rename-case-blocked"); + let dir = root.join("PDF Presets"); let mut a = Session::new(); a.attach_pdf_preset_store(dir.clone()); a.execute("pdf.preset.save", &json!({"name": "Web", "description": "for screens"})).unwrap(); @@ -118,7 +121,8 @@ fn a_rename_that_only_changes_case_and_cannot_be_moved_keeps_the_old_preset() { #[test] fn a_folder_that_does_not_exist_yet_takes_the_presets_the_preferences_held() { - let dir = fresh_dir("seed").join("PDF Presets"); + let root = fresh_dir("seed"); + let dir = root.join("PDF Presets"); let mut a = Session::new(); a.execute("pdf.preset.save", &json!({"name": "From Preferences"})).unwrap(); a.attach_pdf_preset_store(dir.clone()); @@ -155,7 +159,8 @@ fn a_write_reads_the_file_it_replaces_only_one_byte_past_the_new_length() { #[test] fn a_saved_preset_replaces_an_oversized_file_in_its_place() { - let dir = fresh_dir("oversized-put").join("PDF Presets"); + let root = fresh_dir("oversized-put"); + let dir = root.join("PDF Presets"); let mut a = Session::new(); a.attach_pdf_preset_store(dir.clone()); a.execute("pdf.preset.save", &json!({"name": "Web"})).unwrap(); @@ -171,7 +176,8 @@ fn a_saved_preset_replaces_an_oversized_file_in_its_place() { #[test] fn damaged_unsafe_and_oversized_preset_files_are_skipped() { - let dir = fresh_dir("damaged").join("PDF Presets"); + let root = fresh_dir("damaged"); + let dir = root.join("PDF Presets"); let mut a = Session::new(); a.attach_pdf_preset_store(dir.clone()); a.execute("pdf.preset.save", &json!({"name": "Good"})).unwrap(); @@ -214,7 +220,8 @@ fn icc_named(name: &str) -> Vec { #[test] fn stored_profiles_register_again_and_removing_one_removes_its_copy() { - let dir = fresh_dir("profiles").join("Color Profiles"); + let root = fresh_dir("profiles"); + let dir = root.join("Color Profiles"); std::fs::create_dir_all(&dir).unwrap(); let name = "StoreRGB-1"; let file = format!("{}.icc", file_stem(name)); @@ -229,7 +236,8 @@ fn stored_profiles_register_again_and_removing_one_removes_its_copy() { // A profile loaded from elsewhere is copied in, whatever the file is called. let other = "StoreRGB-2"; - let loose = vectorcraft_testkit::temp_dir("store-loose").join("whatever.icm"); + let loose_dir = vectorcraft_testkit::TempDir::new("store-loose"); + let loose = loose_dir.join("whatever.icm"); std::fs::write(&loose, icc_named(other)).unwrap(); let r = s.execute("color.loadProfile", &json!({"path": loose.to_str().unwrap()})).unwrap(); assert_eq!((r["name"].as_str(), r["remembered"].as_bool()), (Some(other), Some(true))); diff --git a/crates/engine/src/tests/swatchlib.rs b/crates/engine/src/tests/swatchlib.rs index b380a4e06b..445ce38ea7 100644 --- a/crates/engine/src/tests/swatchlib.rs +++ b/crates/engine/src/tests/swatchlib.rs @@ -130,11 +130,9 @@ fn reset_defaults_restores_missing_swatches_or_replaces_them() { assert_eq!(s.paint.fill, Paint::solid(Color::from_hex("#abcdef").unwrap()), "the default fill is unlinked too"); } -/// A fresh scratch folder for one test. -fn temp_dir(name: &str) -> std::path::PathBuf { - let d = std::env::temp_dir().join(format!("vc-swatchlib-{name}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&d); - d +/// A fresh scratch folder for one test, removed when the returned value is dropped. +fn temp_dir(name: &str) -> vectorcraft_testkit::TempDir { + vectorcraft_testkit::TempDir::new(&format!("swatchlib-{name}")) } #[test] diff --git a/crates/engine/src/tests/webexport.rs b/crates/engine/src/tests/webexport.rs index bdd474612f..cf427f8174 100644 --- a/crates/engine/src/tests/webexport.rs +++ b/crates/engine/src/tests/webexport.rs @@ -294,7 +294,7 @@ fn files_named_after_the_title_follow_windows_naming_rules() { #[test] fn files_are_written_beside_the_path() { - let dir = vectorcraft_testkit::temp_dir("webexport"); + let dir = vectorcraft_testkit::TempDir::new("webexport"); let mut s = two_colours(); let path = dir.join("art.gif").to_string_lossy().to_string(); let r = run(&mut s, "document.exportForWeb", json!({"path": path})); @@ -324,7 +324,7 @@ fn an_export_says_when_an_image_could_not_be_decoded() { let r = run(&mut s, "document.exportForWeb.preview", json!({"format": format})); assert!(undecoded(&r), "{format} preview: {}", r["warnings"]); } - let dir = vectorcraft_testkit::temp_dir("webexport-undecoded"); + let dir = vectorcraft_testkit::TempDir::new("webexport-undecoded"); let page = dir.join("page.html").to_string_lossy().to_string(); let r = run(&mut s, "document.exportForWeb", json!({"path": page, "output": "html"})); assert!(undecoded(&r), "{r}"); diff --git a/crates/engine/src/tests/xform.rs b/crates/engine/src/tests/xform.rs index 8e3830c81c..7de9793525 100644 --- a/crates/engine/src/tests/xform.rs +++ b/crates/engine/src/tests/xform.rs @@ -600,6 +600,35 @@ fn free_transform_distort_mode_via_pointer() { assert_eq!(s.journal.last().map(|j| j.0.as_str()), Some("object.distort")); } +/// With Constrain on, a Free Distort corner keeps to the diagonal through the opposite corner, in +/// one undo step that undoes and redoes whole. +#[test] +fn free_transform_constrained_distort_keeps_the_corner_on_its_diagonal() { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 200.0, 100.0); + let v = ViewInfo::default(); + s.select_tool("freeTransform", v).unwrap(); + s.set_tool_option("mode", &json!("distort")); + s.set_tool_option("constrain", &json!(true)); + let before = undo_len(&s); + s.pointer(&PointerEvent::new(PointerKind::Down, 300.0, 200.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 320.0, 230.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 340.0, 260.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 340.0, 260.0), v).unwrap(); + let pts = |s: &Session| -> Vec { s.doc().unwrap().doc.node(a).unwrap().path_data().unwrap().anchors().map(|(_, _, an)| an.p).collect() }; + let has_all = |pts: &[Point], want: [(f64, f64); 4]| want.iter().all(|&(x, y)| pts.iter().any(|q| q.distance(Point::new(x, y)) < 1e-6)); + // (40, 60) along the diagonal (200, 100) is 0.28 of it, (56, 28). + let distorted = [(100.0, 100.0), (300.0, 100.0), (356.0, 228.0), (100.0, 200.0)]; + let original = [(100.0, 100.0), (300.0, 100.0), (300.0, 200.0), (100.0, 200.0)]; + assert!(has_all(&pts(&s), distorted), "{:?}", pts(&s)); + assert_eq!(undo_len(&s), before + 1); + assert_eq!(s.journal.last().map(|j| j.0.as_str()), Some("object.distort")); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(has_all(&pts(&s), original), "{:?}", pts(&s)); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(has_all(&pts(&s), distorted), "{:?}", pts(&s)); +} + #[test] fn free_transform_cmd_held_once_a_corner_drag_started_distorts_in_one_step() { let mut s = session(); diff --git a/crates/engine/tests/color_settings.rs b/crates/engine/tests/color_settings.rs index fe56377d4e..e8b3ab0906 100644 --- a/crates/engine/tests/color_settings.rs +++ b/crates/engine/tests/color_settings.rs @@ -653,7 +653,7 @@ fn loading_the_working_rgb_profile_again_takes_effect_at_once() { bytes }; let name = "Reload RGB"; - let dir = vectorcraft_testkit::temp_dir("reload-working-rgb"); + let dir = vectorcraft_testkit::TempDir::new("reload-working-rgb"); let load = |s: &mut Session, builtin: &str| { let path = dir.join(format!("{}.icc", builtin.len())); std::fs::write(&path, renamed(builtin, name)).unwrap(); @@ -734,11 +734,9 @@ impl Drop for ProofReset { } } -/// A folder of its own for the test `tag`, empty. -fn fresh_dir(tag: &str) -> std::path::PathBuf { - let dir = vectorcraft_testkit::temp_dir(&format!("color-settings-{tag}")); - let _ = std::fs::remove_dir_all(&dir); - dir +/// A folder of its own for the test `tag`, empty, removed when dropped. +fn fresh_dir(tag: &str) -> vectorcraft_testkit::TempDir { + vectorcraft_testkit::TempDir::new(&format!("color-settings-{tag}")) } /// An ICC file of an RGB profile named `name` (a built-in one with its description replaced by a @@ -785,7 +783,8 @@ fn color_settings_come_back_in_the_next_session() { let root = fresh_dir("color-settings"); let (profiles, file) = (root.join("Color Profiles"), root.join("Color Settings.json")); let loaded = "StoreRGB-6"; - let icc = vectorcraft_testkit::temp_dir("store-color-settings").join("loaded.icc"); + let icc_dir = vectorcraft_testkit::TempDir::new("store-color-settings"); + let icc = icc_dir.join("loaded.icc"); let _reset = ColorSettingsReset { profile: Some(loaded), paths: vec![root.clone(), icc.clone()] }; std::fs::write(&icc, icc_named(loaded)).unwrap(); diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index 6577754de0..d88d99665f 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -12,10 +12,10 @@ use vectorcraft_testkit::invariants::{check_all, check_session, doc_json}; use vectorcraft_testkit::strategies::{command_param_keys, junk_params_for_command, junk_values, param_keys, safe_value_for_command}; /// Commands that replace/close the active document or touch the filesystem are fine to call, but -/// their file and folder params are redirected into a temp dir (`safe_value_for_command`, which -/// `junk_params_for_command` applies, by the keys the command catalog names as files and folders). -fn safe_path() -> String { - vectorcraft_testkit::temp_dir("sweep").join("out.bin").to_string_lossy().to_string() +/// their file and folder params are redirected into the test's temp dir `dir` (`safe_value_for_command`, +/// which `junk_params_for_command` applies, by the keys the command catalog names as files and folders). +fn safe_path(dir: &std::path::Path) -> String { + dir.join("out.bin").to_string_lossy().to_string() } /// `r`, after failing the case if the command panicked. The engine's guard reports a panic as @@ -219,7 +219,8 @@ fn junk_cases(c: &vectorcraft_engine::CommandSpec, path: &str) -> Vec { #[test] fn every_command_with_junk_params() { - let path = safe_path(); + let dir = vectorcraft_testkit::TempDir::new("sweep"); + let path = safe_path(&dir); let mut failures = vec![]; let mut calls = 0usize; for fx in Fixture::ALL { @@ -311,8 +312,8 @@ fn names_location(spec: Option<&vectorcraft_engine::CommandSpec>, key: &str) -> /// command alone in at least one case ([`junk_cases`]). #[test] fn sweep_cases_name_files_only_inside_the_temp_folder() { - let path = safe_path(); - let dir = vectorcraft_testkit::temp_dir("sweep"); + let dir = vectorcraft_testkit::TempDir::new("sweep"); + let path = safe_path(&dir); let mut unsent = vec![]; let mut outside = std::collections::BTreeSet::new(); for c in command_specs() { @@ -344,8 +345,8 @@ fn sweep_cases_name_files_only_inside_the_temp_folder() { /// `paths: [{ids, path}]`, each with a string in the temp folder, and a folder key a folder there. #[test] fn sweep_cases_send_the_file_keys_of_the_command_catalog() { - let path = safe_path(); - let dir = vectorcraft_testkit::temp_dir("sweep"); + let dir = vectorcraft_testkit::TempDir::new("sweep"); + let path = safe_path(&dir); let spec = |id: &str| command_specs().iter().find(|c| c.id == id).unwrap(); let inside = |v: &Value| v.as_str().is_some_and(|s| std::path::Path::new(s).starts_with(&dir)); for (id, key) in [ @@ -381,7 +382,8 @@ fn sweep_cases_send_the_file_keys_of_the_command_catalog() { /// document as it was, still applies after it. #[test] fn commands_that_do_not_wait_for_a_tool_edit_change_no_document() { - let path = safe_path(); + let dir = vectorcraft_testkit::TempDir::new("sweep"); + let path = safe_path(&dir); let mut failures = vec![]; for fx in [Fixture::Single, Fixture::Multi] { for c in command_specs().iter().filter(|c| !vectorcraft_engine::waits_for_tool_edit(c.id)) { @@ -1127,7 +1129,8 @@ fn serializable_cases(c: &vectorcraft_engine::CommandSpec, path: &str) -> Vec Value { #[test] fn a_found_font_is_copied_without_replacing_a_file_and_its_type_redraws() { - let root = vectorcraft_testkit::temp_dir("font-folder"); - let _ = std::fs::remove_dir_all(&root); - std::fs::create_dir_all(root.join("Downloads/Deep")).unwrap(); - let root = plain(std::fs::canonicalize(&root).unwrap()); + let dir = vectorcraft_testkit::TempDir::new("font-folder"); + std::fs::create_dir_all(dir.join("Downloads/Deep")).unwrap(); + let root = plain(std::fs::canonicalize(&*dir).unwrap()); let fonts = root.join("App Fonts"); vectorcraft_text::set_app_font_dir(fonts.clone()); assert!(vectorcraft_text::system_font_dirs().contains(&fonts)); @@ -85,5 +84,4 @@ fn a_found_font_is_copied_without_replacing_a_file_and_its_type_redraws() { // Only files the last search found are copied. let r = s.execute("text.addFontFiles", &json!({"files": [root.join("other.ttf")]})); assert!(r.as_ref().is_err_and(|e| e.to_string().contains("the last text.findFontFiles search")), "{r:?}"); - let _ = std::fs::remove_dir_all(&root); } diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 37f8c63acf..04e7094f9e 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -6142,7 +6142,8 @@ fn findme_wanted() -> vectorcraft_text::WantedFonts { /// Whether reading `bytes` as a font file a search reads panics. fn search_reads(what: &str, bytes: &[u8]) -> Result, TestCaseError> { - let path = vectorcraft_testkit::temp_dir("font-search-fuzz").join(format!("{:?}.ttc", std::thread::current().id())); + let dir = vectorcraft_testkit::TempDir::new("font-search-fuzz"); + let path = dir.join("font.ttc"); std::fs::write(&path, bytes).unwrap(); catch_quiet(|| findme_wanted().provided_by(&path)).map_err(|e| TestCaseError::fail(format!("{what}: a search reading the file panicked: {e}"))) } diff --git a/crates/engine/tests/it/model_based.rs b/crates/engine/tests/it/model_based.rs index b11e3b0591..583dfda441 100644 --- a/crates/engine/tests/it/model_based.rs +++ b/crates/engine/tests/it/model_based.rs @@ -134,7 +134,8 @@ fn a_failed_batch_restores_the_file_the_history_and_a_drag_in_progress() { (doc_json(&st.doc), st.history.undo.len(), st.history.redo.len()) }; // Save As, then a failing step: the document keeps no file and stays modified. - let path = vectorcraft_testkit::temp_dir("batch-rollback").join("named.vectorcraft").to_string_lossy().to_string(); + let dir = vectorcraft_testkit::TempDir::new("batch-rollback"); + let path = dir.join("named.vectorcraft").to_string_lossy().to_string(); let save = json!({"command": "file.saveAs", "params": {"path": path}}); assert!(s.execute("command.batch", &json!({"commands": [rect(0), save, fail]})).is_err()); assert_eq!(state(&s), before); @@ -170,7 +171,7 @@ fn empty_batch_is_harmless() { #[test] fn save_open_via_commands_roundtrips() { let mut s = fixtures::rich_session(); - let dir = vectorcraft_testkit::temp_dir("engine-save"); + let dir = vectorcraft_testkit::TempDir::new("engine-save"); let path = dir.join("rich.vectorcraft"); exec(&mut s, "document.save", json!({"path": path.to_str().unwrap()})); let want = doc_json(&s.doc().unwrap().doc); diff --git a/crates/engine/tests/removed_font.rs b/crates/engine/tests/removed_font.rs index ca5dc1f13a..da885b40b8 100644 --- a/crates/engine/tests/removed_font.rs +++ b/crates/engine/tests/removed_font.rs @@ -37,9 +37,7 @@ fn laid_out_in(s: &Session, id: u64) -> Vec { #[test] fn type_in_a_removed_font_falls_back_after_a_rescan() { - let root = vectorcraft_testkit::temp_dir("removed-font"); - let _ = std::fs::remove_dir_all(&root); - std::fs::create_dir_all(&root).unwrap(); + let root = vectorcraft_testkit::TempDir::new("removed-font"); vectorcraft_text::set_user_font_dirs(vec![root.clone()]); let file = root.join("Gonefont.otf"); std::fs::write(&file, vectorcraft_testkit::fonts::renamed(FAMILY)).unwrap(); @@ -72,5 +70,4 @@ fn type_in_a_removed_font_falls_back_after_a_rescan() { assert_eq!(status(&mut s), ("exact".into(), FAMILY.into())); assert!(listed(&mut s)); assert_eq!(laid_out_in(&s, id), [FAMILY]); - let _ = std::fs::remove_dir_all(&root); } diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index ab39f467d2..1321188f12 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -2634,6 +2634,34 @@ fn gradient_options_and_links_the_data_cant_hold_are_reported() { let back = read_back(&doc); let Paint::Gradient(g) = back.layers[0].children().unwrap()[0].appearance.items[0].paint() else { panic!("a gradient") }; assert_eq!((color(&g.gradient.stops[0].color), g.gradient.stops[0].swatch.as_deref()), (color(&BRAND), None)); + // A gradient mixed around the hue wheel, either way, is written as a classic one of the stops + // on its curve, no more than the reader reads, and opens with the colors it had. + for method in [vectorcraft_color::gradient::GradientMethod::HueClockwise, vectorcraft_color::gradient::GradientMethod::HueCounterclockwise] { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut g = sunset(); + g.method = method; + let want = g.clone(); + let n = painted( + &mut doc, + shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0)), + vec![AppearanceItem::Fill(FillLayer::new(gradient_paint(g, None, None)))], + ); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::GRADIENT_HUE], "{method:?}"); + let back = read_back(&doc); + let Paint::Gradient(g) = back.layers[0].children().unwrap()[0].appearance.items[0].paint() else { panic!("a gradient") }; + assert!(g.gradient.method.is_classic(), "{method:?}"); + let written = g.gradient.stops.len(); + assert!((want.stops.len() + 1..=crate::import::MAX_GRADIENT_STOPS).contains(&written), "{method:?}: {written} stops"); + for k in 0..=100 { + let t = k as f32 / 100.0; + let ((a, ao), (b, bo)) = (want.sample(t), g.gradient.sample(t)); + let (a, b) = (a.to_rgb(), b.to_rgb()); + assert!(a.iter().zip(b).all(|(x, y)| (x - y).abs() < 0.03) && (ao - bo).abs() < 0.03, "{method:?} at {t}: {a:?} {ao} vs {b:?} {bo}"); + } + } } /// A pattern whose art reaches past its tile is written as its tiles cut to the shape: a definition diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index cd0455f10f..7db5d11896 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -36,7 +36,7 @@ pub(super) use images::PAYLOAD; #[cfg(test)] pub(super) use images::{IMAGE_DEPTH, IMAGES, LINKS_EMBEDDED}; #[cfg(test)] -pub(super) use paints::{GRADIENT_MIX, GRADIENT_SHAPES, GRADIENTS, STOP_LINKS, SWATCH_PLACEMENT, free_gradient_name}; +pub(super) use paints::{GRADIENT_HUE, GRADIENT_MIX, GRADIENT_SHAPES, GRADIENTS, STOP_LINKS, SWATCH_PLACEMENT, free_gradient_name}; #[cfg(test)] pub(super) use symbols::{MISSING_SYMBOL, SYMBOL_ART, SYMBOL_COUNT, SYMBOL_OPTIONS}; #[cfg(test)] diff --git a/crates/eps/src/ai_editing/writer/paints.rs b/crates/eps/src/ai_editing/writer/paints.rs index 0a7220faa5..f1b52dd91b 100644 --- a/crates/eps/src/ai_editing/writer/paints.rs +++ b/crates/eps/src/ai_editing/writer/paints.rs @@ -21,6 +21,7 @@ pub(in crate::ai_editing) const SWATCH_PLACEMENT: &str = "the placement of pattern swatches that move, turn or scale their pattern is left out of the editing data for other apps"; pub(in crate::ai_editing) const GRADIENT_MIX: &str = "gradients that mix their colors perceptually or dither are written as classic gradients in the editing data for other apps"; +pub(in crate::ai_editing) const GRADIENT_HUE: &str = "gradients mixed around the hue wheel are written in process colors, with the colors between their stops as stops of their own (at most 256), in the editing data for other apps"; pub(in crate::ai_editing) const CONIC: &str = "conic gradients are written as linear gradients along their vector, with the same stops, in the editing data for other apps"; pub(in crate::ai_editing) const STOP_LINKS: &str = @@ -56,6 +57,19 @@ fn writable_gradient(g: &Gradient) -> bool { g.kind != GradientKind::Freeform && !g.stops.is_empty() && g.stops.len() <= crate::import::MAX_GRADIENT_STOPS } +/// `g` as the data holds its colors: one mixed around the hue wheel (the data's gradients mix +/// their stops' colors directly) as a classic gradient of the stops on its curve +/// ([`Gradient::as_classic_curve`]), no more than the `.ai` reader reads when it pads +/// ([`GRADIENT_HUE`]); others as they are. +fn hue_as_stops(g: &Gradient) -> std::borrow::Cow<'_, Gradient> { + use std::borrow::Cow; + if !g.method.is_hue() { + return Cow::Borrowed(g); + } + let curve = g.as_classic_curve(); + Cow::Owned(if curve.is_spread() { curve } else { curve.fitted(crate::import::MAX_GRADIENT_STOPS).into_owned() }) +} + /// Is a gradient of `kind` written as a radial one: a radial gradient, or a diamond (the ellipse /// through its square's corners, [`DIAMOND`])? fn written_radial(kind: GradientKind) -> bool { @@ -86,9 +100,11 @@ impl Writer<'_> { pub(in crate::ai_editing) fn reserve_swatch_gradients(&mut self) { let doc = self.doc; for sw in doc.swatches_iter() { - // As `swatch_paint` writes it: the stops of one that repeats or reflects repeated. + // As `swatch_paint` writes it: one mixed around the hue wheel as the stops on its curve, + // and the stops of one that repeats or reflects repeated. if let Paint::Gradient(g) = &sw.paint - && let gradient = g.gradient.unrolled_within(crate::import::MAX_GRADIENT_STOPS) + && let stops = hue_as_stops(&g.gradient) + && let gradient = stops.unrolled_within(crate::import::MAX_GRADIENT_STOPS) && writable_gradient(&gradient) && !self.gradients.iter().any(|d| d.name == sw.name) { @@ -149,6 +165,10 @@ impl Writer<'_> { // The data has no spread: a gradient that repeats or reflects is written with its stops // repeated over `area` (a conic one, written linear, around its turn). let mut g: GradientPaint = (**g).clone(); + if g.gradient.method.is_hue() { + self.warn(GRADIENT_HUE); + g.gradient = hue_as_stops(&g.gradient).into_owned(); + } if g.gradient.is_spread() { self.warn(SPREAD); match g.gradient.padded_within(&geom, area, crate::import::MAX_GRADIENT_STOPS) { @@ -557,13 +577,17 @@ impl Writer<'_> { /// be written. pub(super) fn swatch_paint(&mut self, s: &mut String, sw: &vectorcraft_color::swatch::Swatch) -> bool { // A swatch has no placement: one that repeats or reflects holds its stops repeated along - // its vector. - let unrolled = match &sw.paint { - Paint::Gradient(g) => Some(g.gradient.unrolled_within(crate::import::MAX_GRADIENT_STOPS)), + // its vector, and one mixed around the hue wheel the stops on its curve. + let stops = match &sw.paint { + Paint::Gradient(g) => Some(hue_as_stops(&g.gradient)), _ => None, }; + let unrolled = stops.as_deref().map(|g| g.unrolled_within(crate::import::MAX_GRADIENT_STOPS)); match &sw.paint { Paint::Gradient(g) if unrolled.as_deref().is_some_and(writable_gradient) => { + if g.gradient.method.is_hue() { + self.warn(GRADIENT_HUE); + } if g.gradient.is_spread() { self.warn(SPREAD); } diff --git a/crates/eps/src/import/ai.rs b/crates/eps/src/import/ai.rs index a3de7560e3..4595061151 100644 --- a/crates/eps/src/import/ai.rs +++ b/crates/eps/src/import/ai.rs @@ -39,6 +39,7 @@ pub(crate) use envelope::DRAWN as ENVELOPE_DRAWN; pub(crate) use envelope::MAX_CHECKED; pub(crate) use envelope::TYPE_DRAWN as ENVELOPE_TYPE_DRAWN; pub(crate) use envelope::{GridPoint as EnvelopeGridPoint, PLUGIN as DEFORM_PLUGIN, outline as envelope_outline, upright as envelope_upright}; +pub(crate) use envelope::{MAX_ANY as ENVELOPE_MAX_ANY, MAX_SOLID as ENVELOPE_MAX_SOLID}; pub(crate) use envelope::{WARPED_TYPE_DRAWN, WarpedType}; pub(crate) use frames::text_frames; pub use obj::{NameEncoding, Names}; diff --git a/crates/eps/src/import/ai/envelope.rs b/crates/eps/src/import/ai/envelope.rs index 741ebfabdf..3ae753b7d5 100644 --- a/crates/eps/src/import/ai/envelope.rs +++ b/crates/eps/src/import/ai/envelope.rs @@ -32,7 +32,7 @@ use std::sync::Arc; use kurbo::{Affine, BezPath, Point, Rect, Vec2}; use vectorcraft_doc::live::{ EnvelopeKind, EnvelopeOptions, GradientMesh, H_DOWN, H_LEFT, H_RIGHT, H_UP, PreserveShape, default_fidelity, envelope_content_boxes, - envelope_stroke_margin, + envelope_content_boxes_with, envelope_stroke_margin, }; use vectorcraft_doc::{Appearance, Document, Effect, ImageBlob, LayerColor, Node, NodeId, NodeKind, PatternDef}; use vectorcraft_geom::PathData; @@ -73,9 +73,9 @@ const MOVED_SLACK: f64 = 0.5; const KNOWN_BITS: i64 = 0b111 | 1 << 16 | 1 << 17; /// More of the inked pixels than this differing, each with all its neighbours, and the envelope /// doesn't come out as drawn. -const MAX_SOLID: f64 = 0.03; +pub(crate) const MAX_SOLID: f64 = 0.03; /// More of the inked pixels than this differing at all, and the envelope doesn't come out as drawn. -const MAX_ANY: f64 = 0.1; +pub(crate) const MAX_ANY: f64 = 0.1; /// The whole number of entry `key`: `None` when it is missing, `Some(None)` when it isn't one. fn whole(o: &Obj, key: &str) -> Option> { @@ -150,23 +150,31 @@ fn half_stroked_box(content: &[Arc]) -> Option { fn grown(r: Rect, by: f64) -> Rect { if by.is_finite() && by > 0.0 { r.inflate(by, by) } else { r } } - fn walk(n: &Arc, acc: Option) -> Option { + /// `n`'s box, with type that draws nothing given its laid-out box only with `blank`. + fn walk(n: &Arc, acc: Option, blank: bool) -> Option { let one = std::slice::from_ref(n); match &n.kind { NodeKind::Text(t) => { - let Some((_, ink)) = envelope_content_boxes(one, Affine::IDENTITY) else { return acc }; + let Some((_, ink)) = envelope_content_boxes_with(one, Affine::IDENTITY, blank) else { return acc }; // The characters' own strokes as the type's bounds with strokes measure them (they // have no miter allowance there), and the strokes of its appearance along a side. vectorcraft_geom::union_opt(acc, Some(grown(ink, t.char_stroke_outset().max(along(&n.appearance))))) } NodeKind::Group { children, clip: false } => { - let members = children.iter().fold(None, |acc, c| walk(c, acc)); + let members = children.iter().fold(None, |acc, c| walk(c, acc, blank)); vectorcraft_geom::union_opt(acc, members.map(|b| grown(b, along(&n.appearance)))) } - _ => vectorcraft_geom::union_opt(acc, envelope_content_boxes(one, Affine::IDENTITY).map(|(stroked, _)| stroked)), + _ => vectorcraft_geom::union_opt(acc, envelope_content_boxes_with(one, Affine::IDENTITY, blank).map(|(stroked, _)| stroked)), } } - content.iter().fold(None, |acc, c| walk(c, acc)) + let blank = blank_type_box(content); + content.iter().fold(None, |acc, c| walk(c, acc, blank)) +} + +/// Do the contents of an envelope give type that draws nothing its laid-out box: has nothing else +/// in `content` a box ([`envelope_content_boxes_with`])? +fn blank_type_box(content: &[Arc]) -> bool { + envelope_content_boxes_with(content, Affine::IDENTITY, false).is_none() } /// Envelope `kind` mapping from its contents' glyphs grown by as far as their strokes paint along a @@ -216,19 +224,24 @@ fn painted_outlines(outlines: &Node) -> Option { /// their members grown by as far as their own strokes paint along a side, other objects by their /// bounds with strokes. `None` when nothing in it has bounds. fn painted_box(content: &[Arc]) -> Option { - fn walk(n: &Arc, acc: Option) -> Option { + /// `n`'s box, with type that draws nothing given its laid-out box only with `blank`. + fn walk(n: &Arc, acc: Option, blank: bool) -> Option { match &n.kind { NodeKind::Text(_) => vectorcraft_geom::union_opt(acc, vectorcraft_effects::outline_text(n).as_ref().and_then(painted_outlines)), NodeKind::Group { children, clip: false } => { let along = n.appearance.painted_strokes().map(|s| s.side_reach(true)).fold(0.0, f64::max); - let members = children.iter().fold(None, |acc, c| walk(c, acc)); + let members = children.iter().fold(None, |acc, c| walk(c, acc, blank)); let grown = |r: Rect| if along.is_finite() && along > 0.0 { r.inflate(along, along) } else { r }; vectorcraft_geom::union_opt(acc, members.map(grown)) } - _ => vectorcraft_geom::union_opt(acc, envelope_content_boxes(std::slice::from_ref(n), Affine::IDENTITY).map(|(stroked, _)| stroked)), + _ => vectorcraft_geom::union_opt( + acc, + envelope_content_boxes_with(std::slice::from_ref(n), Affine::IDENTITY, blank).map(|(stroked, _)| stroked), + ), } } - content.iter().fold(None, |acc, c| walk(c, acc)) + let blank = blank_type_box(content); + content.iter().fold(None, |acc, c| walk(c, acc, blank)) } /// The bounds margin of `painted`, the box of what contents with geometric box `plain` paint, a side @@ -648,6 +661,9 @@ pub(crate) enum TypeKept { Budget, /// Its live envelope doesn't draw as its drawn art. Differs, + /// A page that the layers, which don't draw as it, were compared with holds it against them + /// ([`WarpedType::open_alone`]). + Page, } /// What [`WarpedType::settle_envelopes`] did. @@ -657,9 +673,10 @@ pub(crate) struct TypedSettled { pub(crate) live: usize, /// Why each of the others kept its drawn art. pub(crate) kept: Vec, - /// Each live envelope's id, with what takes its place again when the layers with it don't draw - /// as the page: its hidden type, then its drawn art. - pub(crate) put_back: Vec<(NodeId, Vec)>, + /// Each live envelope's place among the envelopes of type (in the order they were read) and + /// id, with what takes its place again when the layers with it don't draw as the page: its + /// hidden type, then its drawn art. + pub(crate) put_back: Vec<(usize, NodeId, Vec)>, } /// The text objects read with a Warp and the envelopes of type, and what the import has left of the @@ -672,6 +689,9 @@ pub struct WarpedType { pub(super) checks: usize, pub(super) spent: Spent, pub(super) page: Option, + /// The envelopes of type that may open live in layers built without a page, by their place + /// among them ([`Self::open_alone`]): none when `None`. + pub(super) alone: Option>, } impl WarpedType { @@ -682,14 +702,33 @@ impl WarpedType { /// These, for layers `compared` with a page. Layers that aren't leave the envelopes of type /// their drawn art and their hidden type, with the note ([`TYPE_DRAWN`]) added to `notes`: a - /// live envelope opens only where the page chooses it. + /// live envelope opens only where the page chooses it. Unless [`Self::open_alone`] names some: + /// then they all wait, as with a page, and only those named may stay live. pub(crate) fn compared(mut self, compared: bool, notes: &mut Vec) -> Self { - if !compared && !std::mem::take(&mut self.envelopes).is_empty() && !notes.iter().any(|n| n == TYPE_DRAWN) { + if !compared && self.alone.is_none() && !std::mem::take(&mut self.envelopes).is_empty() && !notes.iter().any(|n| n == TYPE_DRAWN) { notes.push(TYPE_DRAWN.into()); } self } + /// Let the envelopes of type at `places` (among them, in the order they were read) open live in + /// layers built without a page, where they draw as their drawn art: a page these same layers, + /// read the same way, were compared with weighed them and didn't hold them against the layers' + /// difference from it. All the envelopes of type are settled as they were then, in the same + /// order and with the same checks, so each that opens live draws as it was weighed; then the + /// others get their drawn art back ([`Self::settle_envelopes`]). `count` is how many envelopes + /// of type that reading had: a reading with another number of them names none. + pub(crate) fn open_alone(&mut self, places: &[usize], count: usize) { + if self.envelopes.len() == count { + self.alone = Some(places.iter().copied().filter(|i| *i < count).collect()); + } + } + + /// How many envelopes of type wait for their type. + pub(crate) fn envelope_count(&self) -> usize { + self.envelopes.len() + } + /// Make each envelope of type live where it draws as its drawn art, its contents' text slots /// holding their type: `type_of` gives, for a slot's id, the hidden text object it became in /// `doc` and the type the contents take in its place (the slot's visibility and lock are the @@ -713,16 +752,28 @@ impl WarpedType { doc.layers.iter().for_each(|l| collect_shown(l, &mut shown)); let envelopes = std::mem::take(&mut self.envelopes); let mut waiting = envelopes.len(); - for envelope in envelopes { + for (place, envelope) in envelopes.into_iter().enumerate() { waiting -= 1; match self.typed_live(doc, envelope, &type_of, &shown, waiting) { - Ok(put_back) => { + Ok((id, put_back)) => { settled.live += 1; - settled.put_back.push(put_back); + settled.put_back.push((place, id, put_back)); } Err(why) => settled.kept.push(why), } } + // Built without a page, the envelopes [`Self::open_alone`] doesn't name get their drawn art + // and hidden type back. One inside another that got its own back went with that art. + if let Some(free) = &self.alone { + let (stay, back): (Vec<_>, Vec<_>) = std::mem::take(&mut settled.put_back).into_iter().partition(|(place, ..)| free.contains(place)); + for (_, id, nodes) in back { + if doc.insert_beside(vec![(id, nodes)], true).is_ok() || doc.node(id).is_none() { + settled.live = settled.live.saturating_sub(1); + settled.kept.push(TypeKept::Page); + } + } + settled.put_back = stay; + } settled } @@ -1019,6 +1070,7 @@ mod tests { /// miter join may at a corner. #[test] fn stroked_type_is_tried_mapped_from_its_glyphs_grown_by_half_its_stroke() { + vectorcraft_text::register_envelope_ink(); let mut text = type_node(1, CharStyle::default()); let mut appearance = (*text.appearance).clone(); appearance.items.push(AppearanceItem::Stroke(mitred())); @@ -1034,6 +1086,7 @@ mod tests { /// turned and stretched as well as upright. #[test] fn type_with_a_character_stroke_is_tried_mapped_from_its_bounds_with_strokes() { + vectorcraft_text::register_envelope_ink(); let style = CharStyle { stroke: Paint::solid(Color::BLACK), stroke_width: 4.0, ..CharStyle::default() }; for xf in [ Affine::IDENTITY, @@ -1053,6 +1106,7 @@ mod tests { /// A stroke on a group's own appearance round type grows the box by half its weight too. #[test] fn a_stroke_on_a_group_of_type_grows_the_box_by_half_its_weight() { + vectorcraft_text::register_envelope_ink(); let mut group = Node::new(NodeId(2), NodeKind::Group { children: vec![Arc::new(type_node(1, CharStyle::default()))], clip: false }); let mut appearance = (*group.appearance).clone(); appearance.items.push(AppearanceItem::Stroke(mitred())); @@ -1235,6 +1289,39 @@ mod tests { assert_eq!(painted_outlines(&outlines), Some(Rect::new(9.0, 9.0, 21.0, 21.0))); } + /// Type that draws nothing adds no box next to other content in the boxes the import tries an + /// envelope with Distort Appearance mapped from, loose and in a group, as it adds none to the + /// contents' geometric box: a rectangle with a round 4 point stroke beside type of only spaces + /// gives the rectangle's bounds with strokes. + #[test] + fn type_that_draws_nothing_adds_no_box_to_the_stroked_boxes() { + use kurbo::Shape; + vectorcraft_text::register_envelope_ink(); + let mut stroke = StrokeLayer::new(Paint::solid(Color::BLACK), 4.0); + (stroke.join, stroke.cap) = (LineJoin::Round, LineCap::Round); + let mut appearance = Appearance::default(); + appearance.items.push(AppearanceItem::Stroke(stroke)); + let square = Arc::new(Node::path(NodeId(1), PathData::from_bezpath(&Rect::new(10.0, 10.0, 110.0, 60.0).to_path(0.1)), appearance)); + let blank = Node::new( + NodeId(2), + NodeKind::Text(Box::new(TextObject::point(Point::new(400.0, 450.0), " ", CharStyle { size: 96.0, ..CharStyle::default() }))), + ); + let laid = blank.geometric_bounds().unwrap(); + assert!(laid.x1 > 110.0 && laid.y1 > 60.0, "the laid-out box {laid:?} reaches past the rectangle"); + let want = Rect::new(8.0, 8.0, 112.0, 62.0); + let blank = Arc::new(blank); + for content in [vec![square.clone(), blank.clone()], vec![Arc::new(Node::group(NodeId(3), vec![square.clone(), blank.clone()]))]] { + let (_, plain) = envelope_content_boxes(&content, Affine::IDENTITY).unwrap(); + assert!(close(plain, Rect::new(10.0, 10.0, 110.0, 60.0), 1e-6), "{plain:?}"); + let half = half_stroked_box(&content).unwrap(); + assert!(close(half, want, 1e-6), "{half:?}"); + let painted = painted_box(&content).unwrap(); + assert!(close(painted, want, 1e-6), "{painted:?}"); + } + // With nothing else in the envelope, the type keeps its laid-out box. + assert_eq!(half_stroked_box(&[blank]), Some(laid)); + } + /// A side of what contents paint within a ten-thousandth of a point of their geometric box's is /// that side, inside it or out: the two boxes measure the same outline two ways. Further inside, /// there is no box; further out, it counts. diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs index ca943e8817..0bcae74b32 100644 --- a/crates/eps/src/import/ai/read/document.rs +++ b/crates/eps/src/import/ai/read/document.rs @@ -1367,6 +1367,7 @@ impl<'a> Reader<'a> { checks: self.envelope_checks, spent: self.envelope_spent, page, + alone: None, }, styles_read, text_patterns, diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 9b86f38350..f2a0a41ca7 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -8280,7 +8280,7 @@ fn warped_type_on_the_page_spends_what_is_left_of_the_budget() { let copy = |w: &super::envelope::WarpedLook| super::envelope::WarpedLook { slot: w.slot, look: w.look.clone(), left_out: None }; let page = Some(Rect::new(0.0, 60.0, 60.0, 100.0)); let settle = |w: &super::envelope::WarpedLook, spent| { - let warped = super::envelope::WarpedType { looks: vec![copy(w)], envelopes: vec![], checks: 1, spent, page }; + let warped = super::envelope::WarpedType { looks: vec![copy(w)], envelopes: vec![], checks: 1, spent, page, alone: None }; warped.settle(&mut doc.clone(), Some, &Default::default(), &mut vec![]) }; let spent = || super::envelope::Spent { any: MAX_DIFFERENCE / 2.0, solid: MAX_SOLID_DIFFERENCE / 2.0 }; diff --git a/crates/eps/src/import/native/build.rs b/crates/eps/src/import/native/build.rs index 8adcfccef0..1b212194a1 100644 --- a/crates/eps/src/import/native/build.rs +++ b/crates/eps/src/import/native/build.rs @@ -1,5 +1,6 @@ use super::compare::{ - MAX_DIFFERENCE, MAX_PAGES_COMPARED, MAX_PIXELS_COMPARED, MAX_SOLID_DIFFERENCE, PageView, compare, comparison_samples, difference, pixels_compared, + MAX_DIFFERENCE, MAX_PAGES_COMPARED, MAX_PIXELS_COMPARED, MAX_SOLID_DIFFERENCE, PAST_THE_PAGE, PageView, compare, comparison_samples, difference, + pixels_compared, }; use super::plan::{made_only, make_slots, plan, readable_all}; use super::slots::{ @@ -230,6 +231,24 @@ pub(super) fn build_from( outlined: bool, trust: bool, unit: f64, +) -> Result<(Document, Vec), String> { + build_weighing(structure, data, visible, page, outlined, trust, unit, &mut None) +} + +/// [`build_from`]. When the layers with their live envelopes don't draw as the page, and don't with +/// the drawn art of every live envelope put back either, `free` is set to the envelopes of type +/// (by their place among them, as read) that opened live and that the page doesn't hold against +/// them ([`held_back`]), whether or not the layers are then used, and however. +#[allow(clippy::too_many_arguments)] +pub(super) fn build_weighing( + structure: Structure, + data: &[u8], + visible: Option<&Document>, + page: Page, + outlined: bool, + trust: bool, + unit: f64, + free: &mut Option>, ) -> Result<(Document, Vec), String> { let Structure { mut doc, @@ -468,12 +487,14 @@ pub(super) fn build_from( let warped_type = warped_type.compared(frame.is_some(), &mut notes); let bound = [&bound_text, &bound_visible]; let typed = settle_warped_type(warped_type, &mut doc, &filled, &threaded_frames, bound, &mut restyled, &mut notes)?; + // Each live envelope of type's place among the envelopes of type, by its id. + let places: Vec<(NodeId, usize)> = typed.iter().map(|(place, id, _)| (*id, *place)).collect(); // The live envelopes and what takes the place of each again, when the layers with them don't // draw as the page, with the note that says so. let envelopes_drawn: Vec<(NodeId, Vec, &str)> = envelopes_drawn .into_iter() .map(|(id, art)| (id, vec![art], ai::ENVELOPE_DRAWN)) - .chain(typed.into_iter().map(|(id, nodes)| (id, nodes, ai::ENVELOPE_TYPE_DRAWN))) + .chain(typed.into_iter().map(|(_, id, nodes)| (id, nodes, ai::ENVELOPE_TYPE_DRAWN))) .collect(); if empty > 0 { notes.push(format!("{empty} {}", if frame.is_some() { TEXT_LEFT_OUT } else { TYPE_LEFT_OUT })); @@ -525,20 +546,21 @@ pub(super) fn build_from( notes.extend(unseen_note(unseen).into_iter().chain(note)); } other => match drawn_or_trusted(&frame, &mut view, &mut doc, &envelopes_drawn, ¬es, unseen, trust, why, reflow) { - Ok(more) => notes.extend(more), + Ok((more, held)) => { + *free = held.map(|held| free_places(&places, &held)); + notes.extend(more); + } // The objects that draw differently from the page come in as its art, from // the placement that draws closer to it. The layers don't draw as the page: - // envelopes of type keep their drawn art and their type, hidden. + // the envelopes of type it holds against them keep their drawn art and their + // type, hidden. Where no placement's differing objects can then come in as the + // page's art (an object that holds type isn't replaced), every envelope of type + // keeps its drawn art, and that is tried again. Err(why) => { - let typed = type_drawn(&mut doc, &envelopes_drawn); - let other = other.map(|(_, mut other, unseen)| { - type_drawn(&mut other, &envelopes_drawn); - (other, unseen) - }); - let placements = closer_first(&frame, &mut view, (doc, unseen), other, reflow); - let Some((kept, unseen, kept_notes)) = placements.into_iter().find_map(|(base, unseen)| { - keep_differing(&base, &frame, &mut view, &threaded_frames, &shown, reflow).map(|(kept, n)| (kept, unseen, n)) - }) else { + let other = other.map(|(_, other, unseen)| (other, unseen)); + let layers = Placements { doc: &doc, unseen, other: other.as_ref(), drawn: &envelopes_drawn, places: &places }; + let found = keep_differing_typed(&frame, &mut view, &layers, &threaded_frames, &shown, reflow, free); + let Some((kept, unseen, kept_notes, typed)) = found else { return Err(why); }; doc = kept; @@ -693,8 +715,9 @@ fn bound_slots( /// anchors. Before that, the envelopes of type open live where they draw as their drawn art, with /// the type of their text slots (made type, one text object for the slot, not threaded, bound to /// no text variable and no visibility variable, `bound`'s second set, and no wrap object); the -/// others keep their drawn art, with a note. Returns each live envelope of type's id with what -/// takes its place again (its hidden type, then its drawn art). +/// others keep their drawn art, with a note. Returns each live envelope of type's place among the +/// envelopes of type (in the order they were read) and id, with what takes its place again (its +/// hidden type, then its drawn art). fn settle_warped_type( mut warped: ai::WarpedType, doc: &mut Document, @@ -703,7 +726,7 @@ fn settle_warped_type( bound: [&BTreeSet; 2], restyled: &mut Vec, notes: &mut Vec, -) -> Result)>, String> { +) -> Result)>, String> { let [bound_text, bound_visible] = bound; let made = |slot| match filled.get(&slot).map(|f| f.text.as_slice()).filter(|_| !bound_text.contains(&slot)) { Some(&[one]) => Some(one), @@ -1152,15 +1175,15 @@ const MAX_DIFFERING: usize = 64; const MAX_PATCH_PAIRS: usize = 4_000_000; /// The layers as read and at the placed files' other placement (each with its count of text -/// objects the page doesn't draw), the one that draws closer to the page first. `reflow` as in -/// [`PageView::difference`]. -fn closer_first( +/// objects the page doesn't draw, and what goes with it), the one that draws closer to the page +/// first. `reflow` as in [`PageView::difference`]. +fn closer_first( frame: &Frame<'_>, view: &mut PageView, - doc: (Document, usize), - other: Option<(Document, usize)>, + doc: (Document, usize, T), + other: Option<(Document, usize, T)>, reflow: bool, -) -> Vec<(Document, usize)> { +) -> Vec<(Document, usize, T)> { match other { Some(other) if view.difference_on_every_page(&other.0, frame.rect, reflow).any < view.difference_on_every_page(&doc.0, frame.rect, reflow).any => @@ -1278,6 +1301,73 @@ fn keep_differing( Some((kept, note.into_iter().chain([format!("{DREW_DIFFERENTLY}: {}", layers.join(", "))]).collect())) } +/// The places (among the envelopes of type, as read) of the live envelopes of type in `places` +/// (each with its id) that `held` doesn't list. +fn free_places(places: &[(NodeId, usize)], held: &BTreeSet) -> Vec { + places.iter().filter(|(id, _)| !held.contains(id)).map(|(_, place)| *place).collect() +} + +/// The layers of [`keep_differing_typed`]: `doc`, `unseen` text objects of it taken out; the placed +/// files' other placement of it, when it has one, with how many of its text objects were; its live +/// envelopes, as [`drawn_or_trusted`] takes them; and the place of each live envelope of type +/// among the envelopes of type, by its id. +struct Placements<'a> { + doc: &'a Document, + unseen: usize, + other: Option<&'a (Document, usize)>, + drawn: &'a [(NodeId, Vec, &'a str)], + places: &'a [(NodeId, usize)], +} + +/// [`keep_differing`] of the placement of `layers` that draws closer to the page, the envelopes of +/// type the page holds against that placement ([`held_back`], each placement weighed on its own: the +/// other one draws placed files elsewhere, under or over the envelopes) having their drawn art and +/// hidden type back; and where none of the placements' differing objects can then come in as the +/// page's art, every envelope of type: the document, how many of its text objects were taken out, +/// its notes, and whether an envelope of type got its drawn art back. A placement that draws as the +/// page with only the envelopes the page holds put back is used as it is, as one with all the live +/// envelopes' drawn art put back would have been ([`drawn_or_trusted`]): nothing in it differs to +/// come in as the page's art. `free` is set to the places of those the page doesn't hold against +/// the layers as read. +#[allow(clippy::too_many_arguments)] +fn keep_differing_typed( + frame: &Frame<'_>, + view: &mut PageView, + layers: &Placements<'_>, + threaded_frames: &BTreeSet, + shown: &[Vec>], + reflow: bool, + free: &mut Option>, +) -> Option<(Document, usize, Vec, bool)> { + let held = held_back(frame, view, layers.doc, layers.drawn, reflow); + *free = Some(free_places(layers.places, &held)); + let held_other = layers.other.map(|(other, _)| held_back(frame, view, other, layers.drawn, reflow)); + let all: BTreeSet = layers.places.iter().map(|(id, _)| *id).collect(); + let fewer = held.len() < all.len() || held_other.as_ref().is_some_and(|h| h.len() < all.len()); + let mut tries = vec![]; + if fewer { + tries.push((held, held_other)); + } + tries.push((all.clone(), Some(all.clone()))); + tries.into_iter().find_map(|(held, held_other)| { + // Each placement with what it put back: whether an envelope of type, and whether only some. + let mut base = layers.doc.clone(); + let typed = (type_drawn(&mut base, layers.drawn, &held), held.len() < all.len()); + let other = layers.other.map(|(other, unseen)| { + let (mut other, held) = (other.clone(), held_other.as_ref().unwrap_or(&held)); + let typed = (type_drawn(&mut other, layers.drawn, held), held.len() < all.len()); + (other, *unseen, typed) + }); + let placements = closer_first(frame, view, (base, layers.unseen, typed), other, reflow); + placements.into_iter().find_map(|(base, unseen, (typed, some))| { + if some && let Ok(notes) = compare(frame, view, &base, reflow) { + return Some((base, unseen, notes, typed)); + } + keep_differing(&base, frame, view, threaded_frames, shown, reflow).map(|(kept, notes)| (kept, unseen, notes, typed)) + }) + }) +} + /// Copy page drawing IDs, including mask art outside the ordinary child tree. pub(super) fn reid_page_art(doc: &mut Document, source: &Node) -> Node { let mut copy = doc.reid(source); @@ -1338,9 +1428,9 @@ fn slot_content( /// The layers `doc` don't draw as the page (`why`), `unseen` text objects of them taken out: the /// notes to add when `doc` with each live envelope `drawn` lists replaced by the drawn art it took /// the place of (see [`ai::Structure::envelopes_drawn`]) draws as the page, `doc` then being that; -/// else, with `trust`, the notes for `doc` as it is but for its envelopes of type, which keep their -/// drawn art ([`type_drawn`]). An error, `why`, otherwise. The envelope note is added unless -/// `notes` has it. +/// else, with `trust`, the notes for `doc` as it is but for the envelopes of type the page holds +/// against it ([`held_back`]), which keep their drawn art ([`type_drawn`]), with those envelopes. +/// An error, `why`, otherwise. The envelope note is added unless `notes` has it. #[allow(clippy::too_many_arguments)] fn drawn_or_trusted( frame: &Frame<'_>, @@ -1352,7 +1442,7 @@ fn drawn_or_trusted( trust: bool, why: String, reflow: bool, -) -> Result, String> { +) -> Result<(Vec, Option>), String> { let unseen_note = |n: usize| (n > 0).then(|| format!("{n} {UNSEEN_TEXT}")); let mut put_back = doc.clone(); // Each envelope still there, in place of the art it took the place of. @@ -1379,26 +1469,143 @@ fn drawn_or_trusted( envelope.push(say.to_string()); } } - return Ok(envelope.into_iter().chain(unseen_note(unseen + more)).chain(note).collect()); + return Ok((envelope.into_iter().chain(unseen_note(unseen + more)).chain(note).collect(), None)); } } if trust { - let typed = type_drawn(doc, drawn).then(|| ai::ENVELOPE_TYPE_DRAWN.to_string()).filter(|n| !notes.contains(n)); + let held = held_back(frame, view, doc, drawn, reflow); + let typed = type_drawn(doc, drawn, &held).then(|| ai::ENVELOPE_TYPE_DRAWN.to_string()).filter(|n| !notes.contains(n)); let trusted = format!("{why}: they come from its editing data all the same"); - return Ok(typed.into_iter().chain(unseen_note(unseen)).chain([trusted]).collect()); + return Ok((typed.into_iter().chain(unseen_note(unseen)).chain([trusted]).collect(), Some(held))); } Err(why) } +/// The live envelopes of type in `drawn` (as [`drawn_or_trusted`] takes them) that the page holds +/// against the layers `doc`, which don't draw as it even with every live envelope's drawn art put +/// back: by their ids, those where the layers don't draw as the page. The envelope and its drawn art +/// are drawn together on a layer of their own, without the rest of the layers, on the page check's +/// drawing of each page they lie on: in the pixels they ink there, the layers with the envelope may +/// differ from the page in no more than the envelope's own check allows against its drawn art (at +/// all, and with all their neighbors, away from type: [`compare`]); and in the order they were +/// read, the envelopes that stay live may differ there in no more of each page together than half +/// of what the page check allows (a budget of the same size as the one their own checks share, kept +/// apart from it). Art that differs elsewhere on the page doesn't hold them. One the layers don't +/// draw where it is and as itself ([`drawn_in_place`]) is held, wherever it lies: drawn on its own, +/// it would be weighed elsewhere than it draws, or on pixels a clip or mask hides, and what holds it +/// can draw it onto a page from off it. Another envelope on no page stays live, as the page check +/// doesn't see it, unless the page holds all the art that prints ([`Frame::whole`]), where art past +/// it is compared too: there one reaching past the page is held. Past [`MAX_WEIGHED`] of them on +/// the pages, or where the page check can't weigh one, they are all held. +fn held_back(frame: &Frame<'_>, view: &mut PageView, doc: &Document, drawn: &[(NodeId, Vec, &str)], reflow: bool) -> BTreeSet { + let typed: Vec<(NodeId, &Node, &Node)> = drawn + .iter() + .filter(|(_, _, say)| *say == ai::ENVELOPE_TYPE_DRAWN) + .filter_map(|(id, art, _)| Some((*id, doc.node(*id)?, art.last()?))) + .collect(); + let all: BTreeSet = typed.iter().map(|(id, ..)| *id).collect(); + if all.is_empty() { + return all; + } + let pages = view.regions(frame.rect); + let past = |b: Rect| frame.whole && !frame.rect.inflate(PAST_THE_PAGE, PAST_THE_PAGE).contains_rect(b); + let mut held = BTreeSet::new(); + let mut in_place = std::collections::HashMap::new(); + drawn_in_place(&doc.layers, &all, true, &mut in_place); + // Those the page check sees, by the boxes of the envelope and its drawn art. + let mut seen = vec![]; + for (id, live, art) in typed { + if !in_place.get(&id).copied().unwrap_or(false) { + held.insert(id); + continue; + } + match vectorcraft_geom::union_opt(live.visual_bounds(), art.visual_bounds()) { + Some(b) if past(b) => { + held.insert(id); + } + Some(b) if pages_touched(b, &pages, 1.0).is_empty() => {} + _ => seen.push((id, live, art)), + } + } + if seen.len() > MAX_WEIGHED { + return all; + } + // The pixels of each page where the envelopes that stay live differ from it: at all, and with + // all their neighbors. + let mut spent = vec![(0usize, 0usize); pages.len()]; + for (id, live, art) in seen { + // The envelope and its drawn art, shown, on a layer of their own in `doc`. + let mut nodes: Vec> = [live, art].into_iter().cloned().map(Arc::new).collect(); + for n in &mut nodes { + let n = Arc::make_mut(n); + (n.visible, n.opacity) = (true, 1.0); + } + let mut one = doc.clone(); + let mut layer = Node::layer(NodeId(0), "", vectorcraft_doc::LayerColor::Preset(0)); + if let Some(children) = layer.children_mut() { + *children = nodes; + } + one.layers = vec![Arc::new(layer)]; + let bounds = vectorcraft_render::encode::art_bounds(&one); + if bounds.is_some_and(past) { + held.insert(id); + continue; + } + let on = bounds.map_or(vec![], |b| pages_touched(b, &pages, 1.0)); + let mut added = spent.clone(); + let mut fits = true; + for (i, ink) in view.inked(&one, &on) { + let Some((any, solid)) = view.differing_in(doc, i, &ink, reflow) else { return all }; + let inked = ink.iter().filter(|p| **p).count() as f64; + let pixels = ink.len().max(1) as f64; + let Some((a, s)) = added.get_mut(i) else { return all }; + *a += any; + *s += solid; + fits &= any as f64 <= inked * ai::ENVELOPE_MAX_ANY + && solid as f64 <= inked * ai::ENVELOPE_MAX_SOLID + && *a as f64 <= pixels * MAX_DIFFERENCE / 2.0 + && *s as f64 <= pixels * MAX_SOLID_DIFFERENCE / 2.0; + } + if fits { + spent = added; + } else { + held.insert(id); + } + } + held +} + +/// Which of the objects `ids` among `nodes` (or what they hold) are drawn where they are and as +/// themselves (`plain`: so far, above `nodes`), into `out` by id: under layers and groups that +/// neither clip them, mask them nor have an appearance of their own (whose effects can move or copy +/// them), and in no envelope, repeat, blend or other object that draws what it holds elsewhere or +/// more than once. +fn drawn_in_place(nodes: &[Arc], ids: &BTreeSet, plain: bool, out: &mut std::collections::HashMap) { + for n in nodes { + if ids.contains(&n.id) { + out.insert(n.id, plain); + } + let Some(children) = n.children() else { continue }; + let keeps = match n.kind { + NodeKind::Layer { clip, .. } | NodeKind::Group { clip, .. } => { + !clip && n.appearance == vectorcraft_doc::Appearance::default() && n.extras().mask.is_none() + } + _ => false, + }; + drawn_in_place(children, ids, plain && keeps, out); + } +} + /// Put each live envelope of type in `drawn` (as [`drawn_or_trusted`] takes them) that `doc` still -/// has back as its hidden type and its drawn art: whether one was. An envelope of type opens live -/// only where the layers with it draw as the page, so where they don't, though they are used all -/// the same (the editing data trusted, or the objects that differ come in as the page's art), it -/// keeps its drawn art. -fn type_drawn(doc: &mut Document, drawn: &[(NodeId, Vec, &str)]) -> bool { +/// has and `held` lists back as its hidden type and its drawn art: whether one was. An envelope of +/// type opens live only where the page doesn't hold it against the layers ([`held_back`]), so where +/// they don't draw as the page though they are used all the same (the editing data trusted, or the +/// objects that differ come in as the page's art), one the page holds against them keeps its drawn +/// art. +fn type_drawn(doc: &mut Document, drawn: &[(NodeId, Vec, &str)], held: &BTreeSet) -> bool { let typed: Vec<(NodeId, Vec)> = drawn .iter() - .filter(|(id, _, say)| *say == ai::ENVELOPE_TYPE_DRAWN && doc.node(*id).is_some()) + .filter(|(id, _, say)| *say == ai::ENVELOPE_TYPE_DRAWN && held.contains(id) && doc.node(*id).is_some()) .map(|(id, art, _)| (*id, art.clone())) .collect(); if typed.is_empty() || doc.insert_beside(typed, true).is_err() { @@ -2562,4 +2769,359 @@ mod candidate_tests { replace_unread(&mut doc, &frame, &unread, &[], &BTreeSet::new(), &mut copied).unwrap(); assert!(copied.contains(&nodes[0].id) && !copied.contains(&nodes[1].id)); } + + /// A rectangle on `rect` filled with `color`, with an id of `doc`'s. + fn filled_rect(doc: &mut Document, rect: Rect, color: vectorcraft_color::Color) -> Node { + let paint = vectorcraft_color::Paint::solid(color); + Node::path( + doc.alloc_id(), + vectorcraft_geom::shapes::rectangle(rect), + vectorcraft_doc::Appearance::basic(paint, vectorcraft_color::Paint::None, 0.0), + ) + } + + /// A live envelope as [`drawn_or_trusted`] takes it: its id, what takes its place again, its note. + type Envelope = (NodeId, Vec, &'static str); + + /// The layers `doc` with a black rectangle on each of `lives` standing in for a live envelope of + /// type, its drawn art a black rectangle on the matching one of `arts`: the layers, and the + /// envelopes as [`drawn_or_trusted`] takes them. + fn stand_ins(lives: &[Rect], arts: &[Rect]) -> (Document, Vec) { + let mut doc = Document::new(100.0, 100.0); + let layer = doc.layers[0].id; + let mut drawn = vec![]; + for (live, art) in lives.iter().zip(arts) { + let n = filled_rect(&mut doc, *live, vectorcraft_color::Color::BLACK); + let id = n.id; + doc.insert(Some(layer), 0, n).unwrap(); + let art = filled_rect(&mut doc, *art, vectorcraft_color::Color::BLACK); + drawn.push((id, vec![art], ai::ENVELOPE_TYPE_DRAWN)); + } + (doc, drawn) + } + + /// The page holds an envelope of type against layers that don't draw as it only where the + /// layers with the envelope differ from the page where it or its drawn art inks: not where the + /// page draws other art that the layers don't have. + #[test] + fn the_page_holds_back_only_envelopes_of_type_where_it_differs_from_them() { + let rect = Rect::new(0.0, 0.0, 100.0, 100.0); + let mut page = Document::new(100.0, 100.0); + let layer = page.layers[0].id; + // The first two envelopes' drawn art, and a square the layers don't have. + for r in [Rect::new(10.0, 10.0, 30.0, 30.0), Rect::new(60.0, 10.0, 80.0, 30.0), Rect::new(10.0, 60.0, 30.0, 80.0)] { + let n = filled_rect(&mut page, r, vectorcraft_color::Color::BLACK); + page.insert(Some(layer), 0, n).unwrap(); + } + // Live where its drawn art is; moved off its drawn art; and where the page draws nothing. + let (doc, drawn) = stand_ins( + &[Rect::new(10.0, 10.0, 30.0, 30.0), Rect::new(66.0, 10.0, 86.0, 30.0), Rect::new(60.0, 60.0, 80.0, 80.0)], + &[Rect::new(10.0, 10.0, 30.0, 30.0), Rect::new(60.0, 10.0, 80.0, 30.0), Rect::new(60.0, 60.0, 80.0, 80.0)], + ); + let frame = Frame { page: &page, page_rect: rect, rect, whole: false, pages: vec![(rect, Affine::IDENTITY)], more: vec![] }; + let mut view = PageView::new(&frame); + assert!(compare(&frame, &mut view, &doc, false).is_err()); + assert_eq!(held_back(&frame, &mut view, &doc, &drawn, false), BTreeSet::from([drawn[1].0, drawn[2].0])); + // Only envelopes of type are weighed. + let other: Vec<_> = drawn.iter().map(|(id, art, _)| (*id, art.clone(), ai::ENVELOPE_DRAWN)).collect(); + assert!(held_back(&frame, &mut view, &doc, &other, false).is_empty()); + } + + /// The envelopes of type that stay live may together differ from the page where they ink in no + /// more than half of what the page check allows: the next one past that is held back, though + /// on its own it would stay. + #[test] + fn envelopes_of_type_stay_live_within_half_of_what_the_page_check_allows() { + let rect = Rect::new(0.0, 0.0, 100.0, 100.0); + let halves = [Rect::new(0.0, 0.0, 100.0, 25.0), Rect::new(0.0, 25.0, 100.0, 50.0)]; + let mut page = Document::new(100.0, 100.0); + let layer = page.layers[0].id; + for r in halves { + let n = filled_rect(&mut page, r, vectorcraft_color::Color::BLACK); + page.insert(Some(layer), 0, n).unwrap(); + } + // White lines two pixels high over each, 6 points apart: 8% of what each inks differs, 2% of + // the page, and none of it with all its neighbors. + for (i, y) in [3.0, 9.0, 15.0, 21.0, 28.0, 34.0, 40.0, 46.0].into_iter().enumerate() { + let n = filled_rect(&mut page, Rect::new(0.0, y, 100.0, y + 0.5), vectorcraft_color::Color::WHITE); + page.insert(Some(layer), halves.len() + i, n).unwrap(); + } + let (doc, drawn) = stand_ins(&halves, &halves); + let frame = Frame { page: &page, page_rect: rect, rect, whole: false, pages: vec![(rect, Affine::IDENTITY)], more: vec![] }; + let mut view = PageView::new(&frame); + assert_eq!(held_back(&frame, &mut view, &doc, &drawn, false), BTreeSet::from([drawn[1].0])); + assert!(held_back(&frame, &mut view, &doc, &drawn[1..], false).is_empty()); + } + + /// A page of 100 points with a black rectangle on each of `rects`, and its frame (`whole`: the + /// page holds all the art that prints). + fn black_page(rects: &[Rect]) -> Document { + let mut page = Document::new(100.0, 100.0); + let layer = page.layers[0].id; + for r in rects { + let n = filled_rect(&mut page, *r, vectorcraft_color::Color::BLACK); + page.insert(Some(layer), 0, n).unwrap(); + } + page + } + + /// The frame of `page`, its 100-point square (`whole`: the page holds all the art that prints). + fn frame_of(page: &Document, whole: bool) -> Frame<'_> { + let rect = Rect::new(0.0, 0.0, 100.0, 100.0); + Frame { page, page_rect: rect, rect, whole, pages: vec![(rect, Affine::IDENTITY)], more: vec![] } + } + + /// An envelope of type is held back where the layers with it differ from the page in more of + /// the pixels it and its drawn art ink than its own check allows against its drawn art, though + /// that is far less of the page than the page check allows. + #[test] + fn an_envelope_of_type_differing_in_more_of_its_pixels_than_its_check_allows_is_held_back() { + // Half a point off its drawn art, which the page draws: 22% of the pixels they ink differ, + // a tenth of a percent of the page, and none with all their neighbors. + let page = black_page(&[Rect::new(30.5, 10.0, 34.5, 20.0)]); + let (doc, drawn) = stand_ins(&[Rect::new(30.0, 10.0, 34.0, 20.0)], &[Rect::new(30.5, 10.0, 34.5, 20.0)]); + let frame = frame_of(&page, false); + let mut view = PageView::new(&frame); + assert_eq!(held_back(&frame, &mut view, &doc, &drawn, false), BTreeSet::from([drawn[0].0])); + } + + /// An envelope of type that the layers don't draw where it is and as itself is held back though + /// it draws as the page, wherever it lies: one that a clip group or a clipping sublayer clips, an + /// opacity mask masks, or that a group with an appearance of its own, another envelope, a repeat + /// or a blend holds. Drawn on its own, it would be weighed on pixels a clip hides, or elsewhere + /// than it draws, and what holds it can draw it onto the page from off it. One in a plain group + /// is weighed, and one off the page in a plain group stays live. + #[test] + fn envelopes_of_type_the_layers_dont_draw_in_place_are_held_back() { + let at = |i: usize| { + let (x, y) = if i < 4 { (5.0 + 20.0 * i as f64, 5.0) } else { (5.0 + 20.0 * (i - 4) as f64, 30.0) }; + Rect::new(x, y, x + 15.0, y + 15.0) + }; + let off = [Rect::new(120.0, 5.0, 135.0, 20.0), Rect::new(140.0, 5.0, 155.0, 20.0)]; + let page = black_page(&(0..8).map(at).collect::>()); + let mut doc = Document::new(100.0, 100.0); + let layer = doc.layers[0].id; + let mut drawn = vec![]; + let mut stand_in = |doc: &mut Document, r: Rect| { + let n = filled_rect(doc, r, vectorcraft_color::Color::BLACK); + drawn.push((n.id, vec![filled_rect(doc, r, vectorcraft_color::Color::BLACK)], ai::ENVELOPE_TYPE_DRAWN)); + Arc::new(n) + }; + let group = |doc: &mut Document, children: Vec>, clip: bool| Node::new(doc.alloc_id(), NodeKind::Group { children, clip }); + let fill = vectorcraft_doc::Appearance { + items: vec![vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(vectorcraft_color::Paint::solid( + vectorcraft_color::Color::BLACK, + )))], + ..Default::default() + }; + let mut objects = vec![]; + // 0: in a plain group. + let n = stand_in(&mut doc, at(0)); + objects.push(group(&mut doc, vec![n], false)); + // 1: in a clip group. + let n = stand_in(&mut doc, at(1)); + let mut clip = filled_rect(&mut doc, at(1).inflate(2.0, 2.0), vectorcraft_color::Color::BLACK); + if let NodeKind::Path { clipping, .. } = &mut clip.kind { + *clipping = true; + } + objects.push(group(&mut doc, vec![Arc::new(clip), n], true)); + // 2: in another envelope. + let n = stand_in(&mut doc, at(2)); + let r = at(2); + let points = vec![kurbo::Point::new(r.x0, r.y0), kurbo::Point::new(r.x1, r.y0), kurbo::Point::new(r.x0, r.y1), kurbo::Point::new(r.x1, r.y1)]; + let kind = Box::new(vectorcraft_doc::live::EnvelopeKind::Mesh { rows: 1, cols: 1, points, handles: vec![] }); + let options = vectorcraft_doc::live::EnvelopeOptions::NEW; + objects.push(Node::new( + doc.alloc_id(), + NodeKind::Envelope { content: vec![n], kind, fidelity: 50.0, editing: false, options, frame: Box::default() }, + )); + // 3: in a group with an appearance of its own. + let n = stand_in(&mut doc, at(3)); + let mut styled = group(&mut doc, vec![n], false); + styled.appearance = fill.clone().into(); + objects.push(styled); + // 4: in a group with an opacity mask. + let n = stand_in(&mut doc, at(4)); + let mut masked = group(&mut doc, vec![n], false); + let mask = filled_rect(&mut doc, at(4).inflate(2.0, 2.0), vectorcraft_color::Color::WHITE); + masked.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(mask, true))); + objects.push(masked); + // 5: in a clipping sublayer. + let n = stand_in(&mut doc, at(5)); + let mut clip = filled_rect(&mut doc, at(5).inflate(2.0, 2.0), vectorcraft_color::Color::BLACK); + if let NodeKind::Path { clipping, .. } = &mut clip.kind { + *clipping = true; + } + let mut sublayer = Node::layer(doc.alloc_id(), "Clipped", vectorcraft_doc::LayerColor::Preset(1)); + if let NodeKind::Layer { clip: c, children, .. } = &mut sublayer.kind { + (*c, *children) = (true, vec![Arc::new(clip), n]); + } + objects.push(sublayer); + // 6: in a repeat; 7: in a blend. + let n = stand_in(&mut doc, at(6)); + objects.push(Node::new(doc.alloc_id(), NodeKind::Repeat(vectorcraft_doc::RepeatSpec::grid(vec![n], 0.0, 0.0)))); + let n = stand_in(&mut doc, at(7)); + objects.push(Node::new(doc.alloc_id(), NodeKind::Blend { children: vec![n], spec: Box::default() })); + // 8: off the page in a group with an appearance of its own (an effect could draw it onto the + // page); 9: off the page in a plain group. + let n = stand_in(&mut doc, off[0]); + let mut styled = group(&mut doc, vec![n], false); + styled.appearance = fill.into(); + objects.push(styled); + let n = stand_in(&mut doc, off[1]); + objects.push(group(&mut doc, vec![n], false)); + for n in objects { + doc.insert(Some(layer), 0, n).unwrap(); + } + let frame = frame_of(&page, false); + let mut view = PageView::new(&frame); + let held = held_back(&frame, &mut view, &doc, &drawn, false); + assert_eq!(held, drawn[1..9].iter().map(|(id, ..)| *id).collect::>()); + } + + /// On a page that holds all the art that prints, which the page check also compares past the + /// page, an envelope of type reaching past the page, or lying off it, is held back; on another + /// page, the part on the page is weighed, and one off it stays live. + #[test] + fn on_a_page_that_holds_all_the_art_an_envelope_of_type_past_it_is_held_back() { + let on = Rect::new(10.0, 10.0, 30.0, 30.0); + let across = Rect::new(90.0, 40.0, 110.0, 60.0); + let off = Rect::new(120.0, 10.0, 140.0, 30.0); + let page = black_page(&[on, Rect::new(90.0, 40.0, 100.0, 60.0)]); + let (doc, drawn) = stand_ins(&[on, across, off], &[on, across, off]); + for (whole, held) in [(true, BTreeSet::from([drawn[1].0, drawn[2].0])), (false, BTreeSet::new())] { + let frame = frame_of(&page, whole); + let mut view = PageView::new(&frame); + assert_eq!(held_back(&frame, &mut view, &doc, &drawn, false), held, "whole: {whole}"); + } + // On the page by its box, past it by what it draws: a Transform effect of its own draws a + // copy of it 100 points to the right, off the page. + let page = black_page(&[on]); + let (mut doc, drawn) = stand_ins(&[on], &[on]); + let effect = + vectorcraft_doc::Effect { id: "distort.transform".into(), params: serde_json::json!({"moveH": 100, "copies": 1}), visible: true }; + doc.node_mut(drawn[0].0).unwrap().appearance.effects.push(effect); + for (whole, held) in [(true, BTreeSet::from([drawn[0].0])), (false, BTreeSet::new())] { + let frame = frame_of(&page, whole); + let mut view = PageView::new(&frame); + assert_eq!(held_back(&frame, &mut view, &doc, &drawn, false), held, "drawn past the page, whole: {whole}"); + } + } + + /// Where the objects that draw differently from the page are to come in as its art and the + /// envelopes of type the page doesn't hold stay live, but one of those holds the difference in + /// its box (an object that holds type isn't replaced), every envelope of type gets its drawn art + /// back and that is tried again: the layers are still used. + #[test] + fn objects_come_in_as_the_page_art_with_every_envelope_of_type_put_back_where_a_live_one_holds_a_difference() { + let (a, b, dot, other) = ( + Rect::new(10.0, 10.0, 20.0, 20.0), + Rect::new(40.0, 10.0, 50.0, 20.0), + Rect::new(27.0, 12.0, 33.0, 18.0), + Rect::new(70.0, 70.0, 90.0, 90.0), + ); + // The page draws a dot in the gap between the two rectangles of the envelope's stand-in. + let page = black_page(&[a, b, dot, other]); + let mut doc = Document::new(100.0, 100.0); + let layer = doc.layers[0].id; + let square = filled_rect(&mut doc, other, vectorcraft_color::Color::BLACK); + doc.insert(Some(layer), 0, square).unwrap(); + // The stand-in holds type, hidden; its drawn art is the two rectangles. + let style = vectorcraft_doc::CharStyle::default(); + let mut text = + Node::new(doc.alloc_id(), NodeKind::Text(Box::new(vectorcraft_doc::TextObject::point(kurbo::Point::new(12.0, 18.0), "A", style)))); + text.visible = false; + let parts = vec![ + Arc::new(filled_rect(&mut doc, a, vectorcraft_color::Color::BLACK)), + Arc::new(filled_rect(&mut doc, b, vectorcraft_color::Color::BLACK)), + ]; + let mut children = parts.clone(); + children.push(Arc::new(text)); + let live = Node::new(doc.alloc_id(), NodeKind::Group { children, clip: false }); + let id = live.id; + doc.insert(Some(layer), 0, live).unwrap(); + let art = Node::new(doc.alloc_id(), NodeKind::Group { children: parts, clip: false }); + let drawn: Vec = vec![(id, vec![art], ai::ENVELOPE_TYPE_DRAWN)]; + let frame = frame_of(&page, false); + let mut view = PageView::new(&frame); + assert!(compare(&frame, &mut view, &doc, false).is_err()); + let layers = Placements { doc: &doc, unseen: 0, other: None, drawn: &drawn, places: &[(id, 0)] }; + let mut free = None; + let found = keep_differing_typed(&frame, &mut view, &layers, &BTreeSet::new(), &[], false, &mut free); + assert_eq!(free, Some(vec![0]), "the page doesn't hold the envelope"); + let Some((kept, _, notes, typed)) = found else { panic!("the layers aren't used") }; + assert!(typed, "the envelope got its drawn art back"); + assert!(kept.node(id).is_none()); + assert!(notes.iter().any(|n| n.starts_with(DREW_DIFFERENTLY)), "{notes:?}"); + } + + /// The placed files' other placement is weighed on its own: an envelope of type that the layers + /// as read draw as the page, but that a placed file moved over it at the other placement makes + /// differ, gets its drawn art back there, where that placement's differing objects then come in + /// as the page's art. + #[test] + fn the_other_placement_of_placed_files_is_weighed_on_its_own() { + let black = vectorcraft_color::Color::BLACK; + let gray = vectorcraft_color::Color::rgb(0.5, 0.5, 0.5); + let (envelope, fillers) = (Rect::new(10.0, 10.0, 30.0, 30.0), [Rect::new(40.0, 80.0, 50.0, 90.0), Rect::new(70.0, 80.0, 80.0, 90.0)]); + let placed = Rect::new(60.0, 60.0, 76.0, 76.0); + // The page draws the envelope's drawn art in two halves. + let page = black_page(&[Rect::new(10.0, 10.0, 20.0, 30.0), Rect::new(20.0, 10.0, 30.0, 30.0), placed, fillers[0], fillers[1]]); + let (mut doc, drawn) = stand_ins(&[envelope], &[envelope]); + let layer = doc.layers[0].id; + for r in fillers { + let n = filled_rect(&mut doc, r, black); + doc.insert(Some(layer), 0, n).unwrap(); + } + // Two placed files, standing in as rectangles: one 20 points above where the page has it, one + // a gray rectangle off the art. At their other placement the first is where the page has it + // and the gray one lies over half of the envelope. + let image = filled_rect(&mut doc, Rect::new(60.0, 40.0, 76.0, 56.0), black); + let strip = filled_rect(&mut doc, Rect::new(85.0, 40.0, 95.0, 60.0), gray); + // On top of the layer: the strip covers the envelope where it lies over it. + let top = doc.layers[0].children().map_or(0, Vec::len); + let (image, strip) = (doc.insert(Some(layer), top, image).unwrap(), doc.insert(Some(layer), top + 1, strip).unwrap()); + let mut other = doc.clone(); + other.node_mut(image).unwrap().transform(Affine::translate(Vec2::new(0.0, 20.0)), PAGE_MOVE); + other.node_mut(strip).unwrap().transform(Affine::translate(Vec2::new(-65.0, -30.0)), PAGE_MOVE); + let frame = frame_of(&page, false); + let mut view = PageView::new(&frame); + assert!(held_back(&frame, &mut view, &doc, &drawn, false).is_empty()); + assert_eq!(held_back(&frame, &mut view, &other, &drawn, false), BTreeSet::from([drawn[0].0])); + let other = (other, 0); + let layers = Placements { doc: &doc, unseen: 0, other: Some(&other), drawn: &drawn, places: &[(drawn[0].0, 0)] }; + let mut free = None; + let found = keep_differing_typed(&frame, &mut view, &layers, &BTreeSet::new(), &[], false, &mut free); + assert_eq!(free, Some(vec![0]), "the layers as read don't hold the envelope"); + let Some((kept, _, notes, typed)) = found else { panic!("the layers aren't used") }; + assert!(notes.iter().any(|n| n.starts_with(DREW_DIFFERENTLY)), "{notes:?}"); + assert!(typed && kept.node(drawn[0].0).is_none(), "the envelope keeps its drawn art at the other placement"); + } + + /// Where putting back only the envelopes of type the page holds makes the layers draw as the page, + /// though putting back every live envelope's drawn art doesn't (an envelope of type the page + /// doesn't hold has stale drawn art), the layers are used as they then are: nothing differs to + /// come in as the page's art. + #[test] + fn layers_that_draw_as_the_page_with_the_held_envelopes_of_type_put_back_are_used_so() { + let (held, kept_live) = (Rect::new(10.0, 10.0, 30.0, 30.0), Rect::new(60.0, 10.0, 80.0, 30.0)); + let page = black_page(&[held, kept_live]); + // The first is drawn 6 points off its drawn art, which the page draws; the second draws as the + // page, its drawn art 6 points off. + let (doc, drawn) = stand_ins(&[Rect::new(16.0, 10.0, 36.0, 30.0), kept_live], &[held, Rect::new(66.0, 10.0, 86.0, 30.0)]); + let frame = frame_of(&page, false); + let mut view = PageView::new(&frame); + assert!(compare(&frame, &mut view, &doc, false).is_err()); + let mut all = doc.clone(); + all.insert_beside(drawn.iter().map(|(id, art, _)| (*id, art.clone())).collect(), true).unwrap(); + assert!(compare(&frame, &mut view, &all, false).is_err(), "with every drawn art put back they don't draw as the page"); + let places = [(drawn[0].0, 0), (drawn[1].0, 1)]; + let layers = Placements { doc: &doc, unseen: 0, other: None, drawn: &drawn, places: &places }; + let mut free = None; + let found = keep_differing_typed(&frame, &mut view, &layers, &BTreeSet::new(), &[], false, &mut free); + assert_eq!(free, Some(vec![1])); + let Some((kept, _, notes, typed)) = found else { panic!("the layers aren't used") }; + assert!(typed && kept.node(drawn[0].0).is_none() && kept.node(drawn[1].0).is_some()); + assert!(!notes.iter().any(|n| n.starts_with(DREW_DIFFERENTLY)), "{notes:?}"); + } } diff --git a/crates/eps/src/import/native/compare.rs b/crates/eps/src/import/native/compare.rs index 34f458f328..424ac4079a 100644 --- a/crates/eps/src/import/native/compare.rs +++ b/crates/eps/src/import/native/compare.rs @@ -570,6 +570,34 @@ impl PageView { } } } + + /// Which pixels of each of the pages `on` `art` inks (draws over with an alpha above 8 of 255), + /// drawn as the layers are drawn on them, row by row. + pub(super) fn inked(&mut self, art: &Document, on: &[usize]) -> Vec<(usize, Vec)> { + self.draw(art, on) + .into_iter() + .map(|(i, drawn)| (i, drawn.pixels.as_chunks::<4>().0.iter().map(|p| u32::from(p[3]) > WHITE).collect())) + .collect() + } + + /// Of the pixels of page `i` that `marks` marks (row by row), how many `b` draws differently from + /// the page, as [`compared`] counts them: those that differ (with `reflow`, those away from type), + /// and those that differ with all their neighbors, away from type. `None` when `marks` isn't the + /// page's size. + pub(super) fn differing_in(&mut self, b: &Document, i: usize, marks: &[bool], reflow: bool) -> Option<(usize, usize)> { + self.layered(b, &[i]); + let printed = as_printed(b); + let b = printed.as_ref().unwrap_or(b); + let page = self.pages.get(i)?; + let layered = self.drawn.last()?.pages.get(i)?.as_ref()?; + let (differs, typed, solid) = differing_pixels(&page.drawn, &layered.pixels, &page.counted_type(b, page.region, reflow), &page.skipped())?; + if marks.len() != differs.len() { + return None; + } + let any = marks.iter().zip(&differs).zip(&typed).filter(|((m, d), t)| **m && **d && !(reflow && **t)).count(); + let solid = marks.iter().zip(&solid).filter(|(m, s)| **m && **s).count(); + Some((any, solid)) + } } /// The `w` × `h` pixels of `from` from pixel (`x`, `y`): `None` unless they lie in it, from a pixel. @@ -682,8 +710,27 @@ pub(super) fn compared(x: &vectorcraft_render::Rendered, y: &vectorcraft_render: /// [`compared`], and which of the pixels (row by row) are counted in its `solid` share: none when /// the drawings can't be compared. fn compared_with_solid(x: &vectorcraft_render::Rendered, y: &vectorcraft_render::Rendered, areas: &[Rect], skip: &[Rect]) -> (Difference, Vec) { - if x.width == 0 || x.height == 0 || x.width != y.width || x.height != y.height { + let Some((differs, typed, solid)) = differing_pixels(x, y, areas, skip) else { return (Difference { any: 1.0, art: 1.0, solid: 1.0, typed: 0.0 }, vec![]); + }; + let area = (f64::from(x.width) * f64::from(x.height)).max(1.0); + let any = differs.iter().filter(|d| **d).count() as f64 / area; + let art = differs.iter().zip(&typed).filter(|(d, t)| **d && !**t).count() as f64 / area; + let shares = Difference { any, art, solid: solid.iter().filter(|s| **s).count() as f64 / area, typed: any - art }; + (shares, solid) +} + +/// Which pixels (row by row) of two drawings of the same size differ ([`differ`], those in `skip` +/// counting as alike), which of those lie in the type's `areas`, and which differ with all their +/// neighbors away from type: [`compared`]'s pixels. `None` when the drawings can't be compared. +fn differing_pixels( + x: &vectorcraft_render::Rendered, + y: &vectorcraft_render::Rendered, + areas: &[Rect], + skip: &[Rect], +) -> Option<(Vec, Vec, Vec)> { + if x.width == 0 || x.height == 0 || x.width != y.width || x.height != y.height { + return None; } let (w, h) = (x.width as usize, x.height as usize); // Pixels in `skip` count as alike. @@ -691,10 +738,9 @@ fn compared_with_solid(x: &vectorcraft_render::Rendered, y: &vectorcraft_render: let differs: Vec = x.pixels.as_chunks::<4>().0.iter().zip(y.pixels.as_chunks::<4>().0).zip(&skipped).map(|((p, q), s)| !*s && differ(p, q)).collect(); if !differs.contains(&true) { - return (Difference { any: 0.0, art: 0.0, solid: 0.0, typed: 0.0 }, vec![false; w * h]); + return Some((differs, vec![false; w * h], vec![false; w * h])); } - let typed = in_areas(areas, w, h); - let art = differs.iter().zip(&typed).filter(|(d, t)| **d && !**t).count(); + let typed: Vec = in_areas(areas, w, h).into_iter().zip(&differs).map(|(t, d)| t && *d).collect(); // Which pixels differ with their left and right neighbors. let mut across = vec![false; w * h]; for (k, a) in across.iter_mut().enumerate() { @@ -706,11 +752,7 @@ fn compared_with_solid(x: &vectorcraft_render::Rendered, y: &vectorcraft_render: for (k, s) in solid.iter_mut().enumerate().skip(w).take(w * h.saturating_sub(2)) { *s = !typed.get(k).copied().unwrap_or(true) && [k - w, k, k + w].iter().all(|n| across.get(*n).copied().unwrap_or(false)); } - let area = (w as f64 * h as f64).max(1.0); - let any = differs.iter().filter(|d| **d).count() as f64 / area; - let art = art as f64 / area; - let shares = Difference { any, art, solid: solid.iter().filter(|s| **s).count() as f64 / area, typed: any - art }; - (shares, solid) + Some((differs, typed, solid)) } /// Where the type that shows in `nodes` is, in pixels of `region` drawn at `scale` (with a margin @@ -879,7 +921,7 @@ const NOTABLE_DIFFERENCE: f64 = 0.002; pub(in crate::import) const MAX_SOLID_DIFFERENCE: f64 = 0.001; /// How far (points) the art the layers print may reach past a page that holds it all. -const PAST_THE_PAGE: f64 = 1.0; +pub(super) const PAST_THE_PAGE: f64 = 1.0; /// Do the layers' art and the page's own look alike (where the page holds all the art that prints, /// also round it), on every page the frame has ([`Frame::more`])? An error says they don't; `Ok` has diff --git a/crates/eps/src/import/native/layers.rs b/crates/eps/src/import/native/layers.rs index ee39aec1f1..d1af3301df 100644 --- a/crates/eps/src/import/native/layers.rs +++ b/crates/eps/src/import/native/layers.rs @@ -1,4 +1,4 @@ -use super::build::{PAGE_MOVE, Page, alone_scale, build, build_from, build_on_page, build_without_page, reid_page_art}; +use super::build::{PAGE_MOVE, Page, alone_scale, build, build_from, build_on_page, build_weighing, build_without_page, reid_page_art}; use super::slots::LAYERS_UNREAD; use super::{Affine, Arc, Cow, Document, Imported, Node, NodeKind, PathData, Rect, Vec2, ai}; @@ -177,15 +177,27 @@ pub fn layered_ai_from( add_notes(&mut all, read.notes()); (visible, all, false) }; - let built = structure - .unwrap_or_else(|| ai::read_over_page(&data, false, names).map(Box::new)) - .and_then(|structure| build_from(*structure, &data, Some(&visible), Page::Artboard, outlined, trust, unit)); + // The envelopes of type the page doesn't hold against layers that don't draw as it, and how many + // envelopes of type the layers had. + let (mut free, mut count) = (None, 0); + let built = structure.unwrap_or_else(|| ai::read_over_page(&data, false, names).map(Box::new)).and_then(|structure| { + count = structure.warped_type.envelope_count(); + build_weighing(*structure, &data, Some(&visible), Page::Artboard, outlined, trust, unit, &mut free) + }); // Layers that waited on the page only for their envelopes of type open alone, as they would - // have without them, each envelope keeping its drawn art, unless one opened live with the page. - let live = matches!(&built, Ok((done, _)) if holds_type_envelope(&done.layers)); + // have without them, unless one opened live with the layers drawing as the page. Alone, each + // envelope keeps its drawn art but those the page didn't hold against the layers, which open + // live as they were weighed. They were weighed on the layers as compared with the page, before + // any object of them came in as the page's art: those layers aren't used here, whatever came of + // them. + let live = free.is_none() && matches!(&built, Ok((done, _)) if holds_type_envelope(&done.layers)); if !live && let Some((mut done, notes)) = alone.and_then(|(pages, unit)| { - let structure = ai::read_over_page(&data, false, names).ok()?; + let mut structure = ai::read_over_page(&data, false, names).ok()?; + // With none free, nothing needs settling again: every envelope keeps its drawn art. + if let Some(free) = free.as_deref().filter(|free| !free.is_empty()) { + structure.warped_type.open_alone(free, count); + } build_without_page(structure, &data, &pages, unit).ok()?.ok() }) { diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index c7cdf20e11..1f634b3744 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -5528,6 +5528,11 @@ fn type_envelope(keys: &str, drawn: &str) -> String { /// [`type_envelope`], with `after` (on plain lines, written on `%_` ones) after the text object in /// its contents, such as the text object's XML id. fn type_envelope_with(keys: &str, drawn: &str, after: &str) -> String { + type_envelope_of(0, keys, drawn, after) +} + +/// [`type_envelope_with`] around the type of story `story`. +fn type_envelope_of(story: u32, keys: &str, drawn: &str, after: &str) -> String { let corner = |x: f64, y: f64, nx: f64, ny: f64, px: f64, py: f64| format!("[0.8 1 {x} {y} {nx} {ny} 1 {px} {py} 1] /N X#\n"); let mesh = format!( "/Mesh X!\n2 /Version X#\n/Cartesian /Type X#\n[1 1] /Size X#\n/Data X#\n/DeviceGray /CS X#\n[0 0] /P X#\n{}{}{}{}/E X#\n/End X!\n", @@ -5536,18 +5541,23 @@ fn type_envelope_with(keys: &str, drawn: &str, after: &str) -> String { corner(80.0, 70.0, 80.0, 60.0, 70.0, 70.0), corner(80.0, 40.0, 70.0, 40.0, 80.0, 50.0), ); - type_envelope_on(keys, &mesh, drawn, after) + type_envelope_on_story(story, keys, &mesh, drawn, after) } /// [`type_envelope_with`], with `shape` (on plain lines, written on `%_` ones) in the group before /// its dictionary, where the editing data saves the envelope's mesh. fn type_envelope_on(keys: &str, shape: &str, drawn: &str, after: &str) -> String { + type_envelope_on_story(0, keys, shape, drawn, after) +} + +/// [`type_envelope_on`] around the type of story `story`. +fn type_envelope_on_story(story: u32, keys: &str, shape: &str, drawn: &str, after: &str) -> String { let hidden = |s: &str| -> String { s.lines().map(|l| format!("%_{l}\n")).collect() }; format!( "{}{}%_X=\n{}%_X+\n%_ (AIDeformArtKey) ,\n%_1 /Int (AIDeformStyle) ,\n%_;\n%_\n%_9 () XW\nu\n{drawn}U\n9 () XW\n(Adobe Deform Plugin) 1 0 0 XP\n", hidden(&format!("u\n{shape}U\n")), hidden(&format!("/ArtDictionary :\n{keys}")), - hidden(&format!("u\n{}{after}U\n9 () XW\n", text_object(0))), + hidden(&format!("u\n{}{after}U\n9 () XW\n", text_object(story))), ) } @@ -5594,7 +5604,12 @@ fn arc_envelope(text: &Node, bend: f64) -> Node { /// The type of the file with an envelope of type whose drawn art is `drawn`, read with its text /// document `doc`: the hidden text object it keeps, as the reader makes it. fn made_envelope_type(doc: &str) -> Node { - let art = native_with_text(&layer("Art", true, &type_envelope(&arc_keys(0.3), &format!("{}\n", square(10, 10)))), doc); + made_envelope_type_of(doc, 0) +} + +/// [`made_envelope_type`] of story `story`. +fn made_envelope_type_of(doc: &str, story: u32) -> Node { + let art = native_with_text(&layer("Art", true, &type_envelope_of(story, &arc_keys(0.3), &format!("{}\n", square(10, 10)), "")), doc); let r = import(&eps(&page_square(10, 10), &art)).unwrap(); let mut text = None; r.document.walk(|n| { @@ -5685,9 +5700,9 @@ fn an_envelope_of_white_type_that_draws_apart_from_its_drawn_art_keeps_it() { /// A `.ai` whose layers would open alone, without its PDF part, waits on the PDF part when an /// envelope of type is in them, as for the other live envelopes: one opens live only where the -/// layers with it draw as the page. Where they don't, they open alone as before, the envelope -/// keeping its drawn art and its type, hidden, with the note, even though it would draw as that -/// drawn art; where they do, it opens live (#3179). +/// layers with it draw as the page. Where they don't, the page drawing nothing where the envelope +/// is, they open alone as before, the envelope keeping its drawn art and its type, hidden, with the +/// note, even though it would draw as that drawn art; where they do, it opens live (#3179). #[test] fn an_envelope_of_type_waits_on_the_page_of_layers_that_would_open_alone() { let Some(family) = installed_family() else { return }; @@ -5751,9 +5766,10 @@ fn an_envelope_of_type_that_draws_apart_from_the_page_does_not_open_live() { } /// Layers used though they draw differently from the page (the editing data trusted) leave an -/// envelope of type its drawn art and its type, hidden, with the note, even where it draws as that -/// drawn art: one opens live only where the layers with it draw as the page. A `.ai` whose layers -/// would open alone then opens alone, as it would without the envelope (#3179). +/// envelope of type its drawn art and its type, hidden, with the note, where the page draws +/// nothing where the envelope is, even where it draws as that drawn art: one opens live only where +/// the layers with it draw as the page there. A `.ai` whose layers would open alone then opens +/// alone, as it would without the envelope (#3179). #[test] fn trusted_layers_that_draw_apart_from_the_page_leave_an_envelope_of_type_its_drawn_art() { let Some(family) = installed_family() else { return }; @@ -5789,19 +5805,27 @@ fn trusted_layers_that_draw_apart_from_the_page_leave_an_envelope_of_type_its_dr assert!(!notes.iter().any(|n| n.ends_with("they come from its editing data all the same")), "{notes:?}"); } -/// Layers whose objects that draw differently from the page come in as its art leave an envelope -/// of type its drawn art and its type, hidden, with the note, even where the envelope draws as the -/// page: the layers with it don't (#3179). -#[test] -fn layers_with_objects_that_come_in_as_the_page_art_leave_an_envelope_of_type_its_drawn_art() { - let Some(family) = installed_family() else { return }; - let doc = type_envelope_text(&family, None); - let (drawn, page) = drawn_envelope(&arc_envelope(&made_envelope_type(&doc), 30.0)); - // A square black in the layers and cyan on the page, away from the envelope. +/// The layers and the page of a file with an envelope of type that draws as its drawn art, and a +/// square black in the layers and cyan on the page, away from the envelope; the page draws the +/// envelope bent by `page_bend` (percent). +fn envelope_beside_a_differing_square(family: &str, page_bend: f64) -> (String, String) { + let doc = type_envelope_text(family, None); + let text = made_envelope_type(&doc); + let (drawn, _) = drawn_envelope(&arc_envelope(&text, 30.0)); + let (_, page) = drawn_envelope(&arc_envelope(&text, page_bend)); let body = format!("{}\n{}\n{}", square(10, 10), square_16(76, BLACK), type_envelope(&arc_keys(0.3), &drawn)); - let art = native_with_text(&layer("Art", true, &body), &doc); let cyan = "1 0 0 0 setcmykcolor 76 10 moveto 92 10 lineto 92 26 lineto 76 26 lineto closepath fill"; - let r = import(&eps(&format!("{}\n{cyan}\n{page}", page_square(10, 10)), &art)).unwrap(); + (native_with_text(&layer("Art", true, &body), &doc), format!("{}\n{cyan}\n{page}", page_square(10, 10))) +} + +/// Layers whose objects that draw differently from the page come in as its art keep an envelope of +/// type live where the envelope draws as the page: the art that differs isn't the envelope's, and +/// the layers with it then draw as the page (#3179). +#[test] +fn layers_with_objects_that_come_in_as_the_page_art_keep_an_envelope_of_type_that_draws_as_the_page_live() { + let Some(family) = installed_family() else { return }; + let (art, page) = envelope_beside_a_differing_square(&family, 30.0); + let r = import(&eps(&page, &art)).unwrap(); assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); assert!( r.warnings.iter().any(|n| n.starts_with("objects that drew differently from the file's own page came in as its art")), @@ -5809,12 +5833,169 @@ fn layers_with_objects_that_come_in_as_the_page_art_leave_an_envelope_of_type_it r.warnings ); let (envelopes, loose) = envelopes_and_type(&r.document); + assert_eq!(envelopes, [vec!["FLUX".to_string()]], "{:?}", r.warnings); + assert!(loose.is_empty(), "{loose:?}"); + assert!(!r.warnings.iter().any(|n| n == crate::import::ai::ENVELOPE_TYPE_DRAWN), "{:?}", r.warnings); +} + +/// Layers used though they draw differently from the page (the editing data trusted) leave an +/// envelope of type its drawn art and its type, hidden, with the note, where the page draws it +/// otherwise than they do (bent the other way), though other art differs too: the page holds the +/// envelope against them where it is (#3179). +#[test] +fn trusted_layers_leave_an_envelope_of_type_the_page_draws_otherwise_its_drawn_art() { + let Some(family) = installed_family() else { return }; + let (art, page) = envelope_beside_a_differing_square(&family, -30.0); + let r = crate::import_trusting(&eps(&page, &art), true, true).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + assert!(r.warnings.iter().any(|n| n.ends_with("they come from its editing data all the same")), "{:?}", r.warnings); + let (envelopes, loose) = envelopes_and_type(&r.document); assert!(envelopes.is_empty(), "{envelopes:?}"); assert_eq!(loose, [("FLUX".to_string(), false)], "{:?}", r.warnings); - assert_eq!(loose_type_names(&r.document), [None]); assert!(r.warnings.iter().any(|n| n == crate::import::ai::ENVELOPE_TYPE_DRAWN), "{:?}", r.warnings); } +/// Layers used though they draw differently from the page (the editing data trusted) keep an +/// envelope of type live where the page draws it as they do and the art that differs is elsewhere +/// (#3179). +#[test] +fn trusted_layers_keep_an_envelope_of_type_live_where_other_art_differs_from_the_page() { + let Some(family) = installed_family() else { return }; + let (art, page) = envelope_beside_a_differing_square(&family, 30.0); + let r = crate::import_trusting(&eps(&page, &art), true, true).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + assert!(r.warnings.iter().any(|n| n.ends_with("they come from its editing data all the same")), "{:?}", r.warnings); + let (envelopes, loose) = envelopes_and_type(&r.document); + assert_eq!(envelopes, [vec!["FLUX".to_string()]], "{:?}", r.warnings); + assert!(loose.is_empty(), "{loose:?}"); + assert!(!r.warnings.iter().any(|n| n == crate::import::ai::ENVELOPE_TYPE_DRAWN), "{:?}", r.warnings); +} + +/// A `.ai` whose layers would open alone, and that waits on its PDF part for an envelope of type, +/// opens alone with the envelope live where the page draws it as the layers do, though the page +/// also draws art the layers don't have: the envelope's drawn art put back wouldn't make the layers +/// draw as the page (#3179). +#[test] +fn layers_that_would_open_alone_keep_an_envelope_of_type_live_where_other_art_differs_from_the_page() { + let Some(family) = installed_family() else { return }; + let stories = [("FLUX\r", 0, (8170.0, 8180.0), (0.0, 0.0), 0.0), ("Note\r", 0, (8170.0, 8220.0), (0.0, 0.0), 0.0)]; + let mut doc = text_document(&stories).replace("(Helvetica)", &format!("({family})")); + // [`native_with_text`] writes 60 characters a line: the end of the data, `~>`, isn't split. + while ascii85(doc.as_bytes()).len() % 60 == 1 { + doc.push('\n'); + } + let (drawn, _) = drawn_envelope(&arc_envelope(&made_envelope_type(&doc), 30.0)); + let art = format!("u\n{}U\n{}", text_object(1), type_envelope(&arc_keys(0.3), &drawn)); + let file = private(&native_with_text(&layer("Art", true, &art), &doc)); + let names = crate::NameEncoding::default(); + let open = |page: Document| { + let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") }; + crate::layered_ai_from(layers, page, vec![], false, false, 1.0, names) + }; + // The layers alone, with the envelope's drawn art: what the page draws. + let (mut page, notes, _) = open(pdf_part(80.0, 80.0)); + assert!(envelopes_and_type(&page).0.is_empty(), "{notes:?}"); + // And a black square the layers don't have, away from the type. + add_black_square(&mut page, 80.0, 4.0); + let (d, notes, read) = open(page); + assert!(read, "{notes:?}"); + let (envelopes, loose) = envelopes_and_type(&d); + assert_eq!(envelopes, [vec!["FLUX".to_string()]], "{notes:?}"); + assert_eq!(loose, [("Note".to_string(), true)], "{notes:?}"); + assert!(!notes.iter().any(|n| n == crate::import::ai::ENVELOPE_TYPE_DRAWN), "{notes:?}"); +} + +/// A black square of 16 points at (`x`, `y`) put on top of `page`'s first layer. +fn add_black_square(page: &mut Document, x: f64, y: f64) { + let paint = vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK); + let item = vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(paint)); + let path = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(x, y, x + 16.0, y + 16.0)); + let square = Node::path(page.alloc_id(), path, vectorcraft_doc::Appearance { items: vec![item], ..Default::default() }); + let layer = page.layers[0].id; + page.insert(Some(layer), 0, square).unwrap(); +} + +/// A `.ai` whose layers would open alone, with the editing data trusted, opens alone with an +/// envelope of type live where the page draws it as the layers do, though the page also draws art +/// they don't have: not from the layers compared with the page, which would say they come from the +/// editing data all the same (#3179). +#[test] +fn trusted_layers_that_would_open_alone_open_alone_with_an_envelope_of_type_the_page_doesnt_hold_live() { + let Some(family) = installed_family() else { return }; + let stories = [("FLUX\r", 0, (8170.0, 8180.0), (0.0, 0.0), 0.0), ("Note\r", 0, (8170.0, 8220.0), (0.0, 0.0), 0.0)]; + let mut doc = text_document(&stories).replace("(Helvetica)", &format!("({family})")); + while ascii85(doc.as_bytes()).len() % 60 == 1 { + doc.push('\n'); + } + let (drawn, _) = drawn_envelope(&arc_envelope(&made_envelope_type(&doc), 30.0)); + let art = format!("u\n{}U\n{}", text_object(1), type_envelope(&arc_keys(0.3), &drawn)); + let file = private(&native_with_text(&layer("Art", true, &art), &doc)); + let names = crate::NameEncoding::default(); + let open = |page: Document, trust: bool| { + let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") }; + crate::layered_ai_from(layers, page, vec![], false, trust, 1.0, names) + }; + let (mut page, _, _) = open(pdf_part(80.0, 80.0), false); + add_black_square(&mut page, 80.0, 4.0); + let (d, notes, read) = open(page, true); + assert!(read, "{notes:?}"); + let (envelopes, loose) = envelopes_and_type(&d); + assert_eq!(envelopes, [vec!["FLUX".to_string()]], "{notes:?}"); + assert_eq!(loose, [("Note".to_string(), true)], "{notes:?}"); + assert!(notes.is_empty(), "{notes:?}"); +} + +/// Of two envelopes of type in a `.ai` whose layers would open alone, the one the page holds +/// against the layers (it draws nothing where the envelope is) keeps its drawn art and its type, +/// hidden, with the note, and the other opens live: each by its place among the envelopes of type +/// as the layers are read, both times they are (#3179). +#[test] +fn layers_that_would_open_alone_keep_live_only_the_envelopes_of_type_the_page_doesnt_hold() { + let Some(family) = installed_family() else { return }; + let stories = [ + ("FLUX\r", 0, (8170.0, 8180.0), (0.0, 0.0), 0.0), + ("HILL\r", 0, (8170.0, 8200.0), (0.0, 0.0), 0.0), + ("Note\r", 0, (8170.0, 8220.0), (0.0, 0.0), 0.0), + ]; + let mut doc = text_document(&stories).replace("(Helvetica)", &format!("({family})")); + while ascii85(doc.as_bytes()).len() % 60 == 1 { + doc.push('\n'); + } + let drawn = |story| drawn_envelope(&arc_envelope(&made_envelope_type_of(&doc, story), 30.0)).0; + let art = format!( + "u\n{}U\n{}{}", + text_object(2), + type_envelope_of(0, &arc_keys(0.3), &drawn(0), ""), + type_envelope_of(1, &arc_keys(0.3), &drawn(1), "") + ); + let file = private(&native_with_text(&layer("Art", true, &art), &doc)); + let names = crate::NameEncoding::default(); + let open = |page: Document| { + let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") }; + crate::layered_ai_from(layers, page, vec![], false, false, 1.0, names) + }; + // The layers alone, with the drawn art of both envelopes, but the first's: the page draws + // nothing where the first is. + let (mut page, notes, _) = open(pdf_part(80.0, 80.0)); + let top = page.layers[0].clone(); + let first = top + .children() + .into_iter() + .flatten() + .filter(|n| matches!(n.kind, NodeKind::Group { .. })) + .min_by(|a, b| a.visual_bounds().map_or(f64::MAX, |r| r.y0).total_cmp(&b.visual_bounds().map_or(f64::MAX, |r| r.y0))) + .map(|n| n.id) + .unwrap_or_else(|| panic!("no drawn art: {notes:?}")); + page.remove(first).unwrap(); + let (d, notes, read) = open(page); + assert!(read, "{notes:?}"); + let (envelopes, mut loose) = envelopes_and_type(&d); + assert_eq!(envelopes, [vec!["HILL".to_string()]], "{notes:?}"); + loose.sort(); + assert_eq!(loose, [("FLUX".to_string(), false), ("Note".to_string(), true)], "{notes:?}"); + assert!(notes.iter().any(|n| n == crate::import::ai::ENVELOPE_TYPE_DRAWN), "{notes:?}"); +} + /// An envelope of type whose type a visibility variable binds keeps its drawn art, as one whose type /// a text variable binds does: the binding stays the hidden type's, which the live envelope would /// take the place of (#3179). diff --git a/crates/eps/src/legacy_ai.rs b/crates/eps/src/legacy_ai.rs index 042a7ed2d2..00bb29d12f 100644 --- a/crates/eps/src/legacy_ai.rs +++ b/crates/eps/src/legacy_ai.rs @@ -115,6 +115,7 @@ const CONIC: &str = "conic gradients are written as solid wedges clipped to the const DIAMOND: &str = "diamond gradients are written as four linear gradients clipped to the shape (legacy .ai files have no diamond gradient)"; const SPREAD: &str = "gradients that repeat or reflect are written with their stops repeated across the shape (legacy .ai gradients only pad)"; const SPREAD_CAPPED: &str = "gradients that repeat or reflect are written with at most 256 stops; they pad past those"; +const HUE_STOPS: &str = "gradients mixed around the hue wheel are written in process colors, with the colors between their stops as stops of their own (at most 256; legacy .ai gradients mix their stops' colors directly)"; /// Wedges a conic gradient is written as: one a degree. const CONIC_WEDGES: usize = 360; const STROKES: &str = diff --git a/crates/eps/src/legacy_ai/tests.rs b/crates/eps/src/legacy_ai/tests.rs index 76e96f5aa9..6b2f8335b8 100644 --- a/crates/eps/src/legacy_ai/tests.rs +++ b/crates/eps/src/legacy_ai/tests.rs @@ -198,6 +198,46 @@ fn many_repeats_are_written_within_the_stops_the_reader_reads() { assert_eq!(stops, Some(written), "every stop written is read"); } +/// The format's gradients mix their stops' colors directly: a gradient mixed around the hue wheel +/// is written with the colors on its way around the wheel as stops, no more than the reader +/// reads, with a warning, and opens with the colors it had. +#[test] +fn hue_wheel_gradients_are_written_with_the_stops_on_their_curve() { + use vectorcraft_color::GradientMethod; + for (method, middle) in [(GradientMethod::HueCounterclockwise, [0.0, 1.0, 0.0]), (GradientMethod::HueClockwise, [1.0, 0.0, 1.0])] { + let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))]; + let g = GradientPaint::new(Gradient { method, ..Gradient::new(GradientKind::Linear, stops) }); + let want = g.gradient.clone(); + let mut doc = Document::new(200.0, 100.0); + let n = shape(&mut doc, shapes::rectangle(Rect::new(20.0, 10.0, 180.0, 90.0)), Paint::Gradient(Box::new(g)), Paint::None); + let l = doc.layers[0].id; + doc.insert(Some(l), 0, n).unwrap(); + let out = write(&doc); + assert!(out.warnings.iter().any(|w| w == HUE_STOPS), "{method:?}: {:?}", out.warnings); + let text = String::from_utf8_lossy(&out.bytes).into_owned(); + let def = text.split("%AI5_BeginGradient: (Gradient)\n").nth(1).and_then(|d| d.split("%AI5_EndGradient").next()).unwrap(); + let written = def.matches(" %_Bs\n").count(); + // The two ends and each sixth of the wheel between them, where the way turns in RGB. + assert!((3..=crate::import::MAX_GRADIENT_STOPS).contains(&written), "{method:?}: {written} stops"); + let read = crate::import(&out.bytes).unwrap().document; + let mut back = None; + read.walk(|n| { + if let (None, Paint::Gradient(g)) = (&back, n.appearance.fill_paint()) { + back = Some(g.gradient.clone()); + } + }); + let back = back.unwrap(); + assert!(back.method.is_classic(), "{method:?}"); + let mid = back.sample(0.5).0.to_rgb(); + assert!(mid.iter().zip(middle).all(|(a, b)| (a - b).abs() < 0.03), "{method:?}: the middle is {mid:?}"); + for k in 0..=100 { + let t = k as f32 / 100.0; + let (a, b) = (want.sample(t).0.to_rgb(), back.sample(t).0.to_rgb()); + assert!(a.iter().zip(b).all(|(x, y)| (x - y).abs() < 0.03), "{method:?} at {t}: {a:?} vs {b:?}"); + } + } +} + /// A radial gradient repeated out from a center far from the shape is written with its ramp points /// (percent) to five decimals, so its runs keep their places hundreds of runs out. #[test] diff --git a/crates/eps/src/legacy_ai/writer.rs b/crates/eps/src/legacy_ai/writer.rs index 06d9e0ddcc..20f8b32b96 100644 --- a/crates/eps/src/legacy_ai/writer.rs +++ b/crates/eps/src/legacy_ai/writer.rs @@ -9,7 +9,7 @@ use super::{ ROTATED_TYPE, Rect, STROKES, SUBLAYERS, Shape, StrokeLayer, SubPath, TITLE_AND_COLOR_NAMES, TRANSPARENCY, TYPE, TYPE_ATTRIBUTES, TextKind, TextObject, UNDECODED, Vec2, Write, ai_ops, latin, ps, stroke, }; -use super::{CONIC, CONIC_WEDGES, DIAMOND, SPREAD, SPREAD_CAPPED}; +use super::{CONIC, CONIC_WEDGES, DIAMOND, HUE_STOPS, SPREAD, SPREAD_CAPPED}; pub(super) struct Writer<'a> { doc: &'a Document, @@ -693,6 +693,16 @@ impl<'a> Writer<'a> { /// (its distance a fraction of the radius, at most 1, §3.5.5; `0 0 0 0 Bh` at the center, /// §3.5.6), `1 (name) x y angle length 1 0 0 1 0 0 Bg`. fn gradient(&mut self, g: &GradientPaint, bounds: Rect) -> String { + // A gradient mixed around the hue wheel (the format's gradients mix their stops' colors + // directly): the stops on its curve, no more than the reader reads, in a definition of + // its own. + if g.gradient.method.is_hue() { + self.warn(HUE_STOPS); + let curve = g.gradient.as_classic_curve(); + let gradient = if curve.is_spread() { curve } else { curve.fitted(crate::import::MAX_GRADIENT_STOPS).into_owned() }; + let p = GradientPaint { gradient, swatch: None, ..g.clone() }; + return self.gradient(&p, bounds); + } // A gradient that repeats or reflects (the format's gradients pad past their ends): its // stops repeated as many times as `bounds` needs, in a definition of its own, no more // stops than the reader reads. diff --git a/crates/eps/src/scene.rs b/crates/eps/src/scene.rs index 0ec561dd31..c20c5847a2 100644 --- a/crates/eps/src/scene.rs +++ b/crates/eps/src/scene.rs @@ -42,6 +42,7 @@ const SPOT_GRADIENTS_L2: &str = "gradients mixing a spot color with other inks are written in process colors at PostScript Level 2 (Level 3 keeps the spot inks)"; const SPOT_GRADIENTS_SHARED: &str = "gradients whose spot inks can't share a DeviceN color space are written without the spot inks"; const SPOT_GRADIENTS_PERCEPTUAL: &str = "Perceptual gradients of spot colors are written in process colors"; +const SPOT_GRADIENTS_HUE: &str = "gradients of spot colors mixed around the hue wheel are written in process colors"; const CONIC_WEDGES: &str = "conic gradients are written as solid wedges (EPS has no conic shading)"; const DIAMOND_QUADRANTS: &str = "diamond gradients are written as four linear gradients (EPS has no diamond shading)"; const SPREAD_CAPPED: &str = @@ -913,8 +914,8 @@ impl<'a> Scene<'a> { /// them. Paper white adds no ink, a gray stop is black ink, and a spot stop's process plates /// print with its ink. An off-center midpoint is a stop /// with the inks halfway between its two stops. `None` for a gradient without a spot ink, and, - /// with a warning, for one whose inks can't be kept or that is mixed by the Perceptual method; - /// it is then written in process colors. + /// with a warning, for one whose inks can't be kept or that is mixed by the Perceptual method + /// or around the hue wheel; it is then written in process colors. fn ink_stops(&mut self, g: &vectorcraft_color::Gradient) -> Option<(GradientSpace, RawStops)> { let doc = self.doc; let spot_of = |s: &vectorcraft_color::GradientStop| -> Option { @@ -936,7 +937,7 @@ impl<'a> Scene<'a> { return None; } if !g.method.is_classic() { - self.warn(SPOT_GRADIENTS_PERCEPTUAL); + self.warn(if g.method.is_hue() { SPOT_GRADIENTS_HUE } else { SPOT_GRADIENTS_PERCEPTUAL }); return None; } if names.len() > MAX_DEVICE_N { @@ -1093,6 +1094,14 @@ impl<'a> Scene<'a> { /// both levels; a diamond: four linear gradients, [`Self::diamond_quadrants`]). fn gradient(&mut self, g: &GradientPaint, bounds: Rect, area: Rect) { let geom = g.resolve(bounds); + // One mixed around the hue wheel that reflects is repeated from its curve's stops, which + // keep no swatch links: the warning [`Self::ink_stops`] gives the others. + if g.gradient.method.is_hue() && g.gradient.is_spread() && g.gradient.spread == vectorcraft_color::GradientSpread::Reflect { + let doc = self.doc; + if g.gradient.stops.iter().any(|s| s.swatch.as_deref().is_some_and(|n| doc.swatch(n).is_some_and(|w| w.spot))) { + self.warn(SPOT_GRADIENTS_HUE); + } + } // A linear, radial or diamond gradient that repeats or reflects: PostScript's shadings // pad past their ends, so its stops are repeated as many times as the area needs. if let Some(padded) = g.gradient.padded_over(&geom, area) { diff --git a/crates/eps/src/tests.rs b/crates/eps/src/tests.rs index 0d5649ead5..c98cb9689a 100644 --- a/crates/eps/src/tests.rs +++ b/crates/eps/src/tests.rs @@ -673,6 +673,53 @@ fn perceptual_gradients_of_spot_inks_are_written_in_process_colors() { assert!(text(&export(&d, &opts(&d), None, None).unwrap()).contains("/ColorSpace VCdn0")); } +/// The colors between two stops mixed around the hue wheel are not mixes of the stops' inks: a +/// gradient of spot inks mixed that way is written in process colors, with its own warning, as +/// the same gradient without spot inks is. +#[test] +fn hue_wheel_gradients_of_spot_inks_are_written_in_process_colors() { + for method in [GradientMethod::HueClockwise, GradientMethod::HueCounterclockwise] { + let stops = vec![spot_stop(0.0, "Gold Ink", GOLD, 1.0), spot_stop(1.0, "Leaf Ink", LEAF, 1.0)]; + let mut hue = Gradient::new(GradientKind::Linear, stops.clone()); + hue.method = method; + // Reflecting, it is written from the stops on its curve, and warns all the same. + let reflected = Gradient { spread: vectorcraft_color::GradientSpread::Reflect, repeats: 2, ..hue.clone() }; + let r = spot_gradient_doc_of(reflected); + let reflected_out = export(&r, &opts(&r), None, None).unwrap(); + let reflected_page = checked_page(&text(&reflected_out)); + assert!(!reflected_page.contains("VCdn") && !reflected_page.contains("VCsp"), "{method:?} reflected: {reflected_page}"); + assert!( + reflected_out.warnings.iter().any(|w| w.contains("mixed around the hue wheel are written in process colors")), + "{method:?} reflected: {:?}", + reflected_out.warnings + ); + let d = spot_gradient_doc_of(hue); + let out = export(&d, &opts(&d), None, None).unwrap(); + let page = checked_page(&text(&out)); + assert!(!page.contains("VCdn") && !page.contains("VCsp"), "{method:?}: {page}"); + assert!(page.contains("/ColorSpace /DeviceCMYK"), "{method:?}: {page}"); + assert!( + out.warnings.iter().any(|w| w.contains("gradients of spot colors mixed around the hue wheel are written in process colors")), + "{method:?}: {:?}", + out.warnings + ); + assert!(!out.warnings.iter().any(|w| w.contains("Perceptual")), "{method:?}: {:?}", out.warnings); + let process = |c: Color| GradientStop::new(0.0, c); + let mut plain = Gradient::new(GradientKind::Linear, vec![process(GOLD), GradientStop { offset: 1.0, ..process(LEAF) }]); + plain.method = method; + let p = spot_gradient_doc_of(plain); + let plain_out = export(&p, &opts(&p), None, None).unwrap(); + assert!(!plain_out.warnings.iter().any(|w| w.contains("hue wheel")), "{method:?}: {:?}", plain_out.warnings); + let plain_page = checked_page(&text(&plain_out)); + let shading = |s: &str| -> Option { + let i = s.find("/ShadingType")?; + Some(s[i..i + s[i..].find("shfill")?].to_string()) + }; + assert!(shading(&page).is_some_and(|s| s.contains("/Bounds")), "{method:?}: {page}"); + assert_eq!(shading(&page), shading(&plain_page), "{method:?}"); + } +} + #[test] fn rgb_is_written_as_cmyk_when_asked_and_in_cmyk_documents() { let d = doc_with(|d| vec![red_rect(d)]); diff --git a/crates/mcp/src/tests/exportas.rs b/crates/mcp/src/tests/exportas.rs index f46956bab8..4e41002bf0 100644 --- a/crates/mcp/src/tests/exportas.rs +++ b/crates/mcp/src/tests/exportas.rs @@ -40,9 +40,21 @@ fn an_option_no_format_takes_is_an_error() { assert!(e.contains(named), "{method}: {e}"); } } - // One object can still carry several formats' options. + // One object can still carry several formats' options; the warnings name those the file + // doesn't read. let r = call_tool(&mut h, "export", &json!({"format": "pdf", "options": {"quality": 80, "styling": "style"}})); assert!(!r.is_error, "{r:?}"); + let warnings = text(&r)["warnings"].clone(); + for key in ["quality", "styling"] { + assert!(warnings.as_array().unwrap().contains(&json!(format!("`{key}` was not used: PDF files don't read it"))), "{warnings}"); + } + // `app.export` and `file.export` give the same warning. + let params = json!({"format": "pdf", "quality": 80}); + let note = json!("`quality` was not used: PDF files don't read it"); + let r = h.call("app.export", params.clone()).unwrap(); + assert!(r["warnings"].as_array().unwrap().contains(¬e), "app.export: {r}"); + let r = h.call("engine.execute", json!({"command": "file.export", "params": params})).unwrap(); + assert!(r["warnings"].as_array().unwrap().contains(¬e), "file.export: {r}"); } /// `app.save`, `file.save` and `file.exportForScreens` refuse a key no format takes before they diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index df2627dfc2..8836b72ac2 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1477,13 +1477,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.action.record", "Begin Recording", "", - "{set?: index} begin recording an automatically named Action N in the Actions panel's set at set (0 is the top set), by default the current set or the first set; with no sets, make Set 1. The set becomes current, and ui.action.stop adds the recorded action after that set's existing actions. An explicit invalid set, an existing recording, or a set where the new action would give it more than 1,000 actions or an action set file larger than 8 MiB is an error and changes nothing. While an action records, a recorded command whose step would give the action more than 10,000 steps or its set's action set file more than 8 MiB is an error and does not run, and the recording goes on. A recorded command whose step passes a limit only as it runs, from values it adds to its step, keeps its edit and result; the status bar names the limit, later recorded commands are an error and do not run, and ui.action.stop leaves its step out → {set, name}", + "{set?: index, action?: index, after?: index} begin recording an automatically named Action N in the Actions panel's set at set (0 is the top set), by default the current set or the first set; with no sets, make Set 1. The set becomes current, and ui.action.stop adds the recorded action after that set's existing actions. With action, record into the action at action in set instead: ui.action.stop puts the recorded steps after step after of that action, else after its last step, and the steps after them keep whether they are excluded. The panel's Begin Recording button passes the selected action and its selected step. action without set, after without action, an index past the last set, action or step, an explicit invalid set, an existing recording, or a set where the new action would give it more than 1,000 actions or an action set file larger than 8 MiB is an error and changes nothing. While an action records, a recorded command whose step would give the action more than 10,000 steps or its set's action set file more than 8 MiB is an error and does not run, and the recording goes on. A recorded command whose step passes a limit only as it runs, from values it adds to its step, keeps its edit and result; the status bar names the limit, later recorded commands are an error and do not run, and ui.action.stop leaves its step out → {set, name}, or with action {set, action, name}", ), ( "ui.action.stop", "Stop Playing/Recording", "", - "{} end the Actions panel's recording and keep its steps, in the action ui.action.new made for it, else in a new action after the last action of its set, as the panel's Stop Playing/Recording button does. It also ends an action playing step by step or with pauses, or one waiting at a stop, whose message box closes: the steps played stay and the rest do not run. Recorded steps still past 10,000 in the action, or past 8 MiB in its set's action set file, are left out, and the status bar names the limit. With nothing recording or playing it changes nothing → {stopped}", + "{} end the Actions panel's recording and keep its steps, in the action ui.action.new made for it or the action ui.action.record named, at the place it named, else in a new action after the last action of its set, as the panel's Stop Playing/Recording button does. It also ends an action playing step by step or with pauses, or one waiting at a stop, whose message box closes: the steps played stay and the rest do not run. Recorded steps still past 10,000 in the action, or past 8 MiB in its set's action set file, are left out, and the status bar names the limit. With nothing recording or playing it changes nothing → {stopped}", ), ( "ui.action.insertStop", @@ -1521,6 +1521,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{set: index, action: index, step: index} delete one step, a stop or a command, of the Actions panel's action at action in set (0 is the top set, action or step). The steps after it keep whether they are excluded, and no step of that action stays selected. A Record Stop dialog open on that step closes, and one open on a later step of the action follows it up. A missing or invalid index is an error and changes nothing. Undo does not bring the step back. The panel's Delete Selection runs this for the selected step → {set, action, step}", ), + ( + "ui.action.moveStep", + "Move Action Step", + "", + "{set: index, action: index, step: index, toSet?: index, toAction?: index, before: index} move one step, a stop or a command, of the Actions panel's action at action in set (0 is the top set, action or step) into the action at toAction in toSet (default: the same set and action), before the step at index before there, or after its last step when before is its number of steps; before counts the steps as they are before the move. The step keeps its params and whether it is excluded, and the other steps keep theirs. A selected step stays selected, and a moved selected step makes its new action the selected one and its set the current one. A Record Stop dialog open on a step follows the step, and the steps that the recording in progress adds to either action stay after the steps that were before them. A step put back just before or just after itself does not move. A missing or invalid index, or a move that would give the action more than 10,000 steps or its set's file more than 8 MiB, counting the steps that the recording in progress adds to the set, is an error and changes nothing. Undo does not move the step back. Dragging a step row in the panel runs this → {set, action, step, moved}", + ), ( "ui.batchDialog", "Batch…", diff --git a/crates/pdf/Cargo.toml b/crates/pdf/Cargo.toml index a5a3b83863..d4394dfefa 100644 --- a/crates/pdf/Cargo.toml +++ b/crates/pdf/Cargo.toml @@ -30,6 +30,7 @@ craft-pdf = { workspace = true } log = { workspace = true } chrono = { workspace = true } smallvec = "1" +siphasher = "1" weezl = "0.2" serde = { workspace = true } # The XMP packet that File Info is read from (file_info.rs); the version usvg already uses. diff --git a/crates/pdf/src/export/paint.rs b/crates/pdf/src/export/paint.rs index acb96f1713..77815f93b3 100644 --- a/crates/pdf/src/export/paint.rs +++ b/crates/pdf/src/export/paint.rs @@ -463,7 +463,9 @@ impl Exporter<'_> { /// than an image? pub(super) fn perceptual_spot(&self, g: &vectorcraft_color::GradientPaint, fill: bool) -> bool { let gr = &g.gradient; - !gr.method.is_classic() + // Not one mixed around the hue wheel: its colors between two stops are not tints or + // mixes of the stops' inks, so it stays an image. + gr.method == vectorcraft_color::GradientMethod::Perceptual && gr.kind != GradientKind::Freeform && !(fill && gr.dither) && (self.one_spot_ink(gr).is_some() || self.device_n_inks_only(gr)) @@ -476,7 +478,7 @@ impl Exporter<'_> { /// other gradients, and for an ink too light for lightness to tell its tints apart, which /// [`Self::spot_stops`] then writes with the stops' own tints. fn perceptual_spot_stops(&mut self, g: &vectorcraft_color::Gradient) -> Option> { - if g.method.is_classic() { + if g.method != vectorcraft_color::GradientMethod::Perceptual { return None; } let ink = self.one_spot_ink(g)?; @@ -494,7 +496,7 @@ impl Exporter<'_> { let from_stops = g.gradient.kind != GradientKind::Freeform || !g.has_freeform_points(); if from_stops && self.has_spot_stop(&g.gradient) { self.warn( - "spot colors in gradients exported as images (freeform or dithered gradients, and Perceptual ones with RGB or Lab stops or too many stops) are written in process colors", + "spot colors in gradients exported as images (freeform or dithered gradients, ones mixed around the hue wheel, and Perceptual ones with RGB or Lab stops or too many stops) are written in process colors", ); } } @@ -623,9 +625,9 @@ impl Exporter<'_> { let field = freeform.then(|| g.freeform_on(b).model_field(spread_scale(b))); let cmyk_doc = self.doc.color_mode == vectorcraft_doc::ColorMode::Cmyk; if g.gradient.kind == GradientKind::Conic { - self.warn("conic gradients drawn as pixels (dithered fills, and Perceptual ones other than spot ink shadings), in a PDF/A file or with more than 97 stops are exported as images"); + self.warn("conic gradients drawn as pixels (dithered fills, ones mixed around the hue wheel, and Perceptual ones other than spot ink shadings), in a PDF/A file or with more than 97 stops are exported as images"); } else if g.gradient.kind == GradientKind::Diamond { - self.warn("diamond gradients drawn as pixels (dithered fills, and Perceptual ones other than spot ink shadings), with translucent stops or without an extent are exported as images"); + self.warn("diamond gradients drawn as pixels (dithered fills, ones mixed around the hue wheel, and Perceptual ones other than spot ink shadings), with translucent stops or without an extent are exported as images"); } else if !freeform { self.warn("linear and radial gradients drawn as pixels are exported as images"); } diff --git a/crates/pdf/src/import/actual_text.rs b/crates/pdf/src/import/actual_text.rs index 6d7ddbaf9d..aec147f99e 100644 --- a/crates/pdf/src/import/actual_text.rs +++ b/crates/pdf/src/import/actual_text.rs @@ -104,4 +104,35 @@ impl Builder<'_> { } true } + + /// A Type 3 glyph under an active ActualText span. + pub(super) fn actual_type3_glyph(&mut self, key: u128, at: Placement, look: Look, opacity: f32, advance: f64) -> bool { + self.flush_glyphs(); + self.flush_type3(); + if let (Some(stroke), Some(line)) = (&look.stroke, &mut self.text) + && look.fill.is_none() + && line.stroke_actual(key, at, stroke.clone(), look.overprint_stroke) + { + return true; + } + let pending = self.actual.pending.take(); + let content = match pending.as_deref() { + Some(text) if !text.is_empty() => TextContent::Actual(text), + _ => TextContent::Pen, + }; + let place = |line: &mut TextLine| line.push_content(&look, at, opacity, advance, content); + if !self.text.as_mut().is_some_and(place) { + self.flush_text(); + let mut line = TextLine::new(at, opacity); + if !place(&mut line) { + self.actual.pending = pending; + return false; + } + self.text = Some(line); + } + if let Some(line) = &mut self.text { + line.has_type3 = true; + } + true + } } diff --git a/crates/pdf/src/import/builder.rs b/crates/pdf/src/import/builder.rs index 21d862d2fd..c1be8fba84 100644 --- a/crates/pdf/src/import/builder.rs +++ b/crates/pdf/src/import/builder.rs @@ -12,6 +12,18 @@ use super::{ Upright, Walked, clipped, contains, fold_stop_opacity, function_paint, gradient_shape, is_rectangle, luminance, mask_spec, shading_gradient, }; +fn is_colour_face(face: &vectorcraft_text::FontFace) -> bool { + use skrifa::Tag; + use skrifa::raw::TableProvider; + let Ok(font) = skrifa::FontRef::new(face.file_data()) else { + return false; + }; + font.colr().is_ok() + || font.table_data(Tag::new(b"SVG ")).is_some() + || font.table_data(Tag::new(b"CBDT")).is_some() + || font.table_data(Tag::new(b"sbix")).is_some() +} + impl<'p> Builder<'p> { pub(super) fn new(next: u64, colors: Colors<'p>, text_as: TextAs, route: bool) -> Self { Self { @@ -22,6 +34,7 @@ impl<'p> Builder<'p> { blend: BlendMode::Normal, page: Rect::ZERO, glyphs: None, + type3_run: None, text: None, text_glyphs: vec![], text_as, @@ -102,6 +115,7 @@ impl<'p> Builder<'p> { self.root_groups.clear(); self.blend = BlendMode::Normal; self.glyphs = None; + self.type3_run = None; self.text = None; self.text_glyphs.clear(); self.mask = None; @@ -221,13 +235,48 @@ impl<'p> Builder<'p> { } } - /// Finish the open glyph runs and the art drawn through the current soft mask. + /// Finish the open glyph runs, type 3 runs and the art drawn through the current soft mask. pub(super) fn flush(&mut self) { self.flush_glyphs(); + self.flush_type3(); self.flush_text(); self.flush_masked(); } + /// Finish the open Type 3 font text run as a named group ``. + pub(super) fn flush_type3(&mut self) { + if let Some(run) = self.type3_run.take() + && !run.nodes.is_empty() + { + let Some(left) = self.objects_left.checked_sub(1) else { + self.warn(super::entry::TOO_MANY_OBJECTS); + return; + }; + self.objects_left = left; + let mut g = Node::group(self.id(), run.nodes); + g.name = Some("".to_string()); + self.emit(Arc::new(g), run.group); + } + } + + /// Add nodes from an interpreted Type 3 glyph to the current Type 3 run. + pub(super) fn push_type3_nodes(&mut self, nodes: Vec>) { + if nodes.is_empty() { + return; + } + let group = self.current_group(); + if let Some(run) = &mut self.type3_run { + if run.group != group { + self.flush_type3(); + self.type3_run = Some(super::state::Type3Run { nodes, group }); + } else { + run.nodes.extend(nodes); + } + } else { + self.type3_run = Some(super::state::Type3Run { nodes, group }); + } + } + /// The art drawn through the graphics state's soft mask so far, as one masked object. fn flush_masked(&mut self) { if self.masked.is_empty() { @@ -391,7 +440,7 @@ impl<'p> Builder<'p> { let Some(mut line) = self.text.take() else { return false }; let held = std::mem::take(&mut line.held); // Type the file names itself (ActualText) is in reading order as it stands. - let checked = !glyphs.is_empty() && line.mapped(); + let checked = !glyphs.is_empty() && line.mapped() && !line.has_type3; let mut outlined = false; if let Some((t, opacity, facts)) = line.finish() { if checked && reshaped::reshapes(&t.plain_text()) && !reshaped::draws_as(&t, &facts.ink) { @@ -509,23 +558,26 @@ impl<'p> Builder<'p> { /// Read a soft mask, pattern cell or type 3 glyph (`read`) on its own: its art, in the /// coordinates `page` has. `None` when nested too deeply. - fn nested(&mut self, page: Rect, read: impl FnOnce(&mut Self)) -> Option>> { + pub(super) fn nested(&mut self, page: Rect, blend: BlendMode, read: impl FnOnce(&mut Self)) -> Option>> { if self.nested >= MAX_NESTED { return None; } + let outer_type3 = self.type3_run.take(); self.flush(); let saved = Saved { stack: std::mem::replace(&mut self.stack, vec![Frame::new(FrameKind::Root)]), root_groups: std::mem::take(&mut self.root_groups), - blend: std::mem::replace(&mut self.blend, BlendMode::Normal), + blend: std::mem::replace(&mut self.blend, blend), mask: self.mask.take(), page: std::mem::replace(&mut self.page, page), + type3_run: outer_type3, }; self.nested += 1; read(self); let art = self.close_frames(); self.nested -= 1; - (self.stack, self.root_groups, self.blend, self.mask, self.page) = (saved.stack, saved.root_groups, saved.blend, saved.mask, saved.page); + (self.stack, self.root_groups, self.blend, self.mask, self.page, self.type3_run) = + (saved.stack, saved.root_groups, saved.blend, saved.mask, saved.page, saved.type3_run); Some(art) } @@ -537,7 +589,7 @@ impl<'p> Builder<'p> { } let page = self.page; let saved = std::mem::replace(&mut self.white_images, m.mask_type() == MaskType::Alpha); - let art = self.nested(page, |b| m.interpret(b)); + let art = self.nested(page, BlendMode::Normal, |b| m.interpret(b)); self.white_images = saved; let spec = match art { Some(art) => { @@ -601,7 +653,7 @@ impl<'p> Builder<'p> { // A swatch is shared with uses outside an alpha mask, and pattern paints keep their // colours there: its images are read as they are. let white = std::mem::take(&mut self.white_images); - let art = self.nested(Rect::ZERO, |b| { + let art = self.nested(Rect::ZERO, BlendMode::Normal, |b| { // A cell whose content can't be decoded is empty. let _ = t.interpret(b, Affine::IDENTITY, stroke); }); @@ -799,6 +851,125 @@ impl<'p> Builder<'p> { self.text_glyphs.push(GlyphRun { path, paint, opacity, stroke, scale, overprint }); } + fn type3_font_name(&mut self, key: u128) -> FontInfo { + if let Some(n) = self.font_names.get(&key) { + return n.clone(); + } + let name = self.fonts.get(&key).map(|f| f.name.clone()); + let ps = name.as_deref().map(|n| match n.split_once('+') { + Some((tag, rest)) if tag.len() == 6 && tag.chars().all(|c| c.is_ascii_uppercase()) => rest.to_string(), + _ => n.to_string(), + }); + let installed = ps.as_deref().and_then(|ps| vectorcraft_text::FontDb::global().find_postscript(ps)); + let n = match (installed, name) { + (Some(face), _) => FontInfo { family: face.family.clone(), style: face.style.clone(), face: Some(face) }, + (None, Some(name)) => { + let families = self.families.get_or_insert_with(Families::available); + let (family, style, found) = families.resolve(&name, None, false); + if !found && !family.is_empty() && !self.missing_fonts.contains(&family) { + self.missing_fonts.push(family.clone()); + } + let face = vectorcraft_text::FontDb::global().face(&family, &style); + FontInfo { family, style, face } + } + (None, None) => { + let d = vectorcraft_doc::CharStyle::default(); + FontInfo { family: d.font_family, style: d.font_style, face: None } + } + }; + self.font_names.insert(key, n.clone()); + n + } + + /// Type 3 glyph as live type: added to the line being gathered if it has a ToUnicode mapping. + pub(super) fn type_type3_glyph( + &mut self, + t3: &craft_pdf::interpret::font::Type3Glyph<'_>, + m: Affine, + scale: f64, + paint: Option<&craft_pdf::interpret::Paint<'_>>, + stroke: Option<&StrokeProps>, + overprint: bool, + ) -> bool { + if self.text_as != TextAs::Text || self.nested > 0 { + return false; + } + let t3_key = craft_pdf::interpret::CacheKey::cache_key(t3); + let Some(&(font_key, has_to_unicode)) = self.scan.type3_cache_map.get(&t3_key) else { + return false; + }; + let (is_type3, to_unicode, is_colour) = match self.fonts.get(&font_key) { + Some(f) => (f.is_type3, has_to_unicode || f.to_unicode, f.is_colour), + None => (true, has_to_unicode, false), + }; + let authored = self.actual.active(); + if !is_type3 || (!to_unicode && !authored) || is_colour { + return false; + } + let unicode = t3.as_unicode().filter(|u| !super::cid::replacement(u)); + if !authored && unicode.is_none() { + return false; + } + let text: String = match unicode { + Some(BfString::Char(c)) => c.to_string(), + Some(BfString::String(s)) => s, + None => String::new(), + }; + let Some(at) = Placement::of(m) else { return false }; + if !authored && (text.is_empty() || text.chars().any(|c| c.is_control())) { + return false; + } + let width = t3.advance_width().filter(|w| w.is_finite()); + let advance = width.map_or(at.size * 0.5, |w| w as f64 / 1000.0 * at.size * at.h_scale / 100.0); + let info = self.type3_font_name(font_key); + if info.face.as_ref().is_some_and(|f| is_colour_face(f)) { + return false; + } + let (paint, opacity) = match paint { + Some(p) => { + let (paint, opacity) = self.paint(p, stroke.is_some(), self.walked(true)); + (Some(paint), opacity) + } + None => (None, 1.0), + }; + let stroke = stroke.zip(paint.clone()).map(|(p, paint)| (paint, line_width(p, scale))); + let look = Look { + font: font_key, + family: info.family, + style: info.style, + version: None, + size: at.size, + h_scale: at.h_scale, + overprint_fill: stroke.is_none() && overprint, + overprint_stroke: stroke.is_some() && overprint, + fill: if stroke.is_none() { paint } else { None }, + stroke, + }; + if authored { + return self.actual_type3_glyph(font_key, at, look, opacity, advance); + } + let text = visual_glyph_text(text); + let place = |line: &mut TextLine| line.push(&look, at, opacity, advance, &text); + self.flush_glyphs(); + self.flush_type3(); + if let (Some(s), Some(line)) = (&look.stroke, &mut self.text) + && look.fill.is_none() + && line.stroke_last(font_key, at, s.clone(), overprint) + { + return true; + } + if !self.text.as_mut().is_some_and(place) { + self.flush_text(); + let mut line = TextLine::new(at, opacity); + place(&mut line); + self.text = Some(line); + } + if let Some(line) = &mut self.text { + line.has_type3 = true; + } + true + } + /// Glyph `o` as type: added to the line being gathered (or starting one). `false`: it keeps /// its outline (no Unicode text, mirrored, not type mode, or in a span whose ActualText is /// empty). No `paint`: invisible text, diff --git a/crates/pdf/src/import/device.rs b/crates/pdf/src/import/device.rs index b39905d6e0..3fcefd7b8e 100644 --- a/crates/pdf/src/import/device.rs +++ b/crates/pdf/src/import/device.rs @@ -33,6 +33,7 @@ impl<'a> Device<'a> for Builder<'_> { fn draw_path(&mut self, path: &BezPath, transform: Affine, paint: &craft_pdf::interpret::Paint<'a>, draw_mode: &PathDrawMode) { self.flush_glyphs(); + self.flush_type3(); let walked = self.walked(false); if self.hold_glyph_stroke(path, transform, paint, draw_mode, walked) { return; @@ -174,7 +175,7 @@ impl<'a> Device<'a> for Builder<'_> { GlyphDrawMode::Invisible => { let typed = match glyph { Glyph::Outline(o) => self.type_glyph(o, transform * glyph_transform, mean_scale(transform), None, None, false), - Glyph::Type3(_) => false, + Glyph::Type3(t3) => self.type_type3_glyph(t3, transform * glyph_transform, mean_scale(transform), None, None, false), }; if !typed { self.warn(INVISIBLE_TEXT_NOTE); @@ -186,6 +187,7 @@ impl<'a> Device<'a> for Builder<'_> { }; match glyph { Glyph::Outline(o) => { + self.flush_type3(); let scale = mean_scale(transform); let overprint = self.glyph_overprint(stroke.is_some()); if self.type_glyph(o, transform * glyph_transform, scale, Some(paint), stroke.as_ref(), overprint) { @@ -216,16 +218,26 @@ impl<'a> Device<'a> for Builder<'_> { if self.nested >= MAX_NESTED { return; } - self.flush(); - self.nested += 1; - t3.interpret(self, transform, glyph_transform, paint); - self.nested -= 1; + let scale = mean_scale(transform); + let overprint = self.glyph_overprint(stroke.is_some()); + if self.type_type3_glyph(t3, transform * glyph_transform, scale, Some(paint), stroke.as_ref(), overprint) { + return; + } + self.flush_glyphs(); + self.flush_text(); + let art = self.nested(self.page, self.blend, |b| { + t3.interpret(b, transform, glyph_transform, paint); + }); + if let Some(nodes) = art { + self.push_type3_nodes(nodes); + } } } } fn draw_image(&mut self, image: Image<'a, '_>, transform: Affine) { self.flush_glyphs(); + self.flush_type3(); self.flush_text(); match image { Image::Raster(r) => { diff --git a/crates/pdf/src/import/state.rs b/crates/pdf/src/import/state.rs index b74cbf5dab..0470d641e2 100644 --- a/crates/pdf/src/import/state.rs +++ b/crates/pdf/src/import/state.rs @@ -62,6 +62,13 @@ pub(super) struct GlyphRun { /// swatch made for it. pub(super) type PatternReadings = (u32, Vec<(Vec, String)>); +/// A run of Type 3 glyph graphics preserved inside a named group. +#[derive(Clone, Debug)] +pub(super) struct Type3Run { + pub(super) nodes: Vec>, + pub(super) group: Option, +} + /// Builder state a nested interpretation (soft mask, pattern cell) starts afresh and gives back. pub(super) struct Saved { pub(super) stack: Vec, @@ -69,6 +76,7 @@ pub(super) struct Saved { pub(super) blend: BlendMode, pub(super) mask: Option>, pub(super) page: Rect, + pub(super) type3_run: Option, } pub(super) struct Builder<'p> { @@ -80,6 +88,7 @@ pub(super) struct Builder<'p> { pub(super) blend: BlendMode, pub(super) page: Rect, pub(super) glyphs: Option, + pub(super) type3_run: Option, pub(super) text: Option, /// The glyphs of the open line of type (`text`) that show, each as the outline it would be /// kept as: what the line becomes when its type wouldn't draw as the file does diff --git a/crates/pdf/src/import_scan.rs b/crates/pdf/src/import_scan.rs index 4f4e35dd3e..b65254eafa 100644 --- a/crates/pdf/src/import_scan.rs +++ b/crates/pdf/src/import_scan.rs @@ -13,6 +13,8 @@ use std::collections::{HashMap, HashSet}; +use siphasher::sip128::{Hasher128, SipHasher13}; + use crate::import_color::items; use craft_pdf::interpret::CacheKey; use craft_pdf::syntax::Pdf; @@ -250,6 +252,13 @@ fn pdf_doc_char(c: u8) -> char { mapped.copied().unwrap_or(char::from(c)) } +/// Calculate a 128-bit siphash of a value, matching hayro-interpret's `hash128`. +pub(crate) fn hash128(value: &T) -> u128 { + let mut state = SipHasher13::new(); + value.hash(&mut state); + state.finish128().as_u128() +} + /// One page as the interpreter walks it. #[derive(Default)] pub(crate) struct Scan { @@ -282,6 +291,8 @@ pub(crate) struct Scan { /// fills and of its strokes (indices into [`Self::inks`]), where all of its text shown in an /// ink is shown in the same one. text_inks: Changes<[Option; 2]>, + /// Type 3 glyph cache key -> (font cache key, whether font has /ToUnicode). + pub type3_cache_map: HashMap, } impl Scan { @@ -642,9 +653,58 @@ impl Walker<'_, '_> { if let Some(f) = res.fonts.get::>(key.as_ref()) && let Some(name) = font_name(&f) { - self.fonts.entry(f.cache_key()).or_insert_with(|| { + let is_type3 = f.get::>(b"Subtype").is_some_and(|s| s.as_ref() == b"Type3"); + let to_unicode = f.get::>(b"ToUnicode").is_some(); + let f_key = f.cache_key(); + const MAX_TYPE3_CACHE_MAP: usize = 1 << 20; + if is_type3 && self.out.type3_cache_map.len().saturating_add(257) <= MAX_TYPE3_CACHE_MAP { + for gid in 0..=256u32 { + let hash = hash128(&(f_key, skrifa::GlyphId::new(gid))); + self.out.type3_cache_map.insert(hash, (f_key, to_unicode)); + } + } + let is_colour = if is_type3 { + let mut colour = false; + let mut seen_streams = HashSet::new(); + let mut decoded_bytes = 0usize; + const MAX_CHARPROC_BYTES: usize = 16 << 20; + if let Some(char_procs) = f.get::>(b"CharProcs") { + for key in char_procs.keys() { + if let Some(stream) = char_procs.get::>(key.as_ref()) { + if !seen_streams.insert(stream.cache_key()) { + continue; + } + if decoded_bytes >= MAX_CHARPROC_BYTES { + colour = true; + break; + } + if let Ok(data) = stream.decoded_within(MAX_CHARPROC_BYTES.saturating_sub(decoded_bytes)) { + decoded_bytes = decoded_bytes.saturating_add(data.len()); + let mut iter = TypedIter::new(data.as_ref()); + while let Some(op) = iter.next() { + match op { + TypedInstruction::ColorGlyph(_) => { + colour = true; + break; + } + TypedInstruction::ShapeGlyph(_) => break, + _ => {} + } + } + if colour { + break; + } + } + } + } + } + colour + } else { + false + }; + self.fonts.entry(f_key).or_insert_with(|| { let embedded = embeds_glyphs(&f); - FontNote { name, embedded, vertical: vertical_metrics(&f, embedded) } + FontNote { name, embedded, vertical: vertical_metrics(&f, embedded), is_type3, to_unicode, is_colour } }); } } @@ -879,6 +939,12 @@ pub(crate) struct FontNote { pub embedded: bool, /// A composite font written vertically: its descendant's metrics. pub vertical: Option, + /// Whether this is a Type 3 font. + pub is_type3: bool, + /// Whether this font specifies a /ToUnicode map. + pub to_unicode: bool, + /// Whether this Type 3 font contains coloured glyph descriptions (d0/ColorGlyph). + pub is_colour: bool, } /// The most CIDs a vertical font's widths are read for (the most a CID-keyed font has). @@ -1020,6 +1086,15 @@ fn cid_ranges(a: &Array<'_>, per: usize, mut each: impl FnMut(u32, &[f64])) { /// descendant CIDFont's `BaseFont` is taken, the font program's own name (§9.7.4.1); without one, /// the `BaseFont` without the CMap's name on its end. fn font_name(f: &Dict<'_>) -> Option { + if f.get::>(b"Subtype").is_some_and(|s| s.as_ref() == b"Type3") { + if let Some(base) = f.get::>(b"BaseFont") { + return Some(String::from_utf8_lossy(base.as_ref()).into_owned()); + } + if let Some(name) = f.get::>(b"Name") { + return Some(String::from_utf8_lossy(name.as_ref()).into_owned()); + } + return Some("Type3".to_string()); + } let base = String::from_utf8_lossy(f.get::>(b"BaseFont")?.as_ref()).into_owned(); if f.get::>(b"Subtype").is_none_or(|s| s.as_ref() != b"Type0") { return Some(base); diff --git a/crates/pdf/src/import_text.rs b/crates/pdf/src/import_text.rs index 200ec93673..9b0122326f 100644 --- a/crates/pdf/src/import_text.rs +++ b/crates/pdf/src/import_text.rs @@ -218,6 +218,8 @@ pub(crate) struct TextLine { /// The strokes of its glyphs' outlines drawn between them, one per glyph with ink so far /// (written right after the line). pub held: Vec, + /// Whether this line holds Type 3 font glyphs. + pub has_type3: bool, } /// Where the file put a glyph: the glyph's index in the line, and its advance in the file's font @@ -266,6 +268,7 @@ impl TextLine { drawn_spaces: vec![], drawn_space: None, held: vec![], + has_type3: false, } } diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index 8caac7b0de..8f9959c77f 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -5,7 +5,7 @@ //! width profiles, fitted or dotted dashes as the canvas's filled outlines and brushed strokes //! as their brush art), opacity and blend modes (transparency groups), //! clip groups, linear/radial gradients (shadings), pattern fills and strokes as their tiles and -//! freeform and Perceptual gradients and dithered gradient fills as images at the raster +//! freeform and Perceptual gradients, gradients mixed around the hue wheel and dithered gradient fills as images at the raster //! effects resolution (clipped to what they paint), embedded images (resampled and //! compressed as the Compression settings say) and text as outlined glyph paths, or as real //! text in embedded subset fonts (Advanced). Colours are converted, tagged with ICC profiles and diff --git a/crates/pdf/src/tests/cmykimages.rs b/crates/pdf/src/tests/cmykimages.rs index 5b86f2b895..45222bb04d 100644 --- a/crates/pdf/src/tests/cmykimages.rs +++ b/crates/pdf/src/tests/cmykimages.rs @@ -687,6 +687,26 @@ fn dithered_and_perceptual_gradients_of_cmyk_stops_are_written_as_cmyk_images() assert_ne!(w[0].space, "DeviceCMYK", "converted to RGB"); } +/// The colors between two stops mixed around the hue wheel are not mixes of the stops' inks: a +/// gradient of CMYK stops mixed that way is an RGB image, in a linear, radial, conic or diamond +/// gradient. +#[test] +fn hue_wheel_gradients_of_cmyk_stops_are_written_as_rgb_images() { + for method in [GradientMethod::HueClockwise, GradientMethod::HueCounterclockwise] { + for mode in [ColorMode::Cmyk, ColorMode::Rgb] { + for kind in [GradientKind::Linear, GradientKind::Radial, GradientKind::Conic, GradientKind::Diamond] { + let stops = vec![GradientStop::new(0.0, Color::cmyk(0.0, 1.0, 1.0, 0.0)), GradientStop::new(1.0, Color::cmyk(1.0, 1.0, 0.0, 0.0))]; + let d = gradient_doc(mode, Gradient { method, ..Gradient::new(kind, stops) }); + let out = export_with_report(&d, &opts(json!({}))).unwrap(); + let w = written(&out.bytes); + assert_eq!(w.len(), 1, "{method:?} {mode:?} {kind:?}: one opaque image: {w:?}"); + assert_eq!(w[0].space, "DeviceRGB", "{method:?} {mode:?} {kind:?}"); + assert!(out.warnings.iter().any(|m| m.contains("exported as images")), "{method:?} {mode:?} {kind:?}: {:?}", out.warnings); + } + } + } +} + /// A stop in another model, or linked to a spot swatch, keeps the RGB image. #[test] fn gradients_with_a_stop_that_is_not_process_cmyk_stay_rgb_images() { diff --git a/crates/pdf/src/tests/text_placement.rs b/crates/pdf/src/tests/text_placement.rs index f275def4dd..417a88e5b9 100644 --- a/crates/pdf/src/tests/text_placement.rs +++ b/crates/pdf/src/tests/text_placement.rs @@ -112,6 +112,25 @@ fn type3(first: usize, upm: f64) -> Vec { vec![font, a, b] } +/// A Type 3 font with a ToUnicode CMap. +fn type3_with_to_unicode(first: usize, upm: f64) -> Vec { + let s = 1.0 / upm; + let (h, w) = (upm * 0.5, upm); + let a = stream("", &format!("{h} 0 0 0 {h} {upm} d1 0 0 {} {} re f", h * 0.8, upm * 0.7)); + let b = stream("", &format!("{w} 0 0 0 {w} {upm} d1 0 0 {} {} re f", w * 0.9, upm * 0.7)); + let to_u = stream( + "", + "/CIDInit /ProcSet findresource begin 12 dict begin begincmap /CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def /CMapName /T3-UCS def /CMapType 2 def 1 begincodespacerange <00> endcodespacerange 2 beginbfchar\n<61> <0061>\n<62> <0062>\nendbfchar endcmap CMapName currentdict /CMap defineresource pop end end", + ); + let font = format!( + "<< /Type /Font /Subtype /Type3 /FontBBox [0 0 {w} {w}] /FontMatrix [{s} 0 0 {s} 0 0] /CharProcs << /a {} 0 R /b {} 0 R >> /Encoding << /Type /Encoding /Differences [97 /a /b] >> /FirstChar 97 /LastChar 98 /Widths [{h} {w}] /ToUnicode {} 0 R /Resources << >> >>", + first + 1, + first + 2, + first + 3 + ); + vec![font, a, b, to_u] +} + /// A 300 × 200 pt page drawing `content`, plus `entries` in the page dictionary, with fonts: /// - `/F1`: Source Sans 3, embedded, a simple TrueType font; /// - `/F4`: Source Sans 3 as a Type 0 font, Identity-H (two-byte glyph ids, see [`gids`]); @@ -146,9 +165,13 @@ fn sized_page(w: f64, h: f64, content: &str, entries: &str) -> Vec { let t3 = n + objs.len(); objs.extend(type3(t3, 1000.0)); objs.extend(type3(t3 + 3, 100.0)); + let t3u = t3 + 6; + objs.extend(type3_with_to_unicode(t3u, 1000.0)); + let t30u = t3u + 4; + objs.extend(type3_with_to_unicode(t30u, 100.0)); let refs: Vec<&str> = objs.iter().map(String::as_str).collect(); let resources = format!( - "/Font << /F1 {} 0 R /F4 {} 0 R /F5 {} 0 R /F6 {} 0 R /T3 {t3} 0 R /T30 {} 0 R /HV << /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >> >>", + "/Font << /F1 {} 0 R /F4 {} 0 R /F5 {} 0 R /F6 {} 0 R /T3 {t3} 0 R /T30 {} 0 R /T3U {t3u} 0 R /T30U {t30u} 0 R /HV << /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >> >>", n + 2, n + 5, n + 6, @@ -416,7 +439,16 @@ fn vertical_glyphs_narrower_than_an_em_stay_on_their_column() { fn type3_glyphs_follow_the_font_matrix() { for font in ["T3", "T30"] { let d = open_as(&page(&format!("BT /{font} 20 Tf 20 50 Td (ab) Tj ET"), ""), TextAs::Text); - assert!(texts(&d).is_empty(), "Type 3 text keeps its outlines"); + assert!(texts(&d).is_empty(), "Type 3 text without ToUnicode keeps its outlines"); + let mut groups = 0; + d.walk(|n| { + if let NodeKind::Group { .. } = &n.kind + && n.name.as_deref() == Some("") + { + groups += 1; + } + }); + assert_eq!(groups, 1, "{font}: Type 3 text run must be preserved inside named group "); let mut boxes = contours(&d); boxes.sort_by(|a, b| a.x0.total_cmp(&b.x0)); // `a` at x 20 (0.4 em = 8 pt wide), `b` after its half-em advance; 0.7 em = 14 pt tall, @@ -429,6 +461,60 @@ fn type3_glyphs_follow_the_font_matrix() { } } +/// Type 3 fonts with ToUnicode import as live text in Text mode, and as named groups in Paths mode. +/// Tests both 1000 UPM (/T3U) and 100 UPM (/T30U) to verify FontMatrix scaling. +#[test] +fn type3_font_with_to_unicode_imports_as_live_text() { + for font in ["T3U", "T30U"] { + let d_text = open_as(&page(&format!("BT /{font} 20 Tf 20 50 Td (ab) Tj ET"), ""), TextAs::Text); + let t = texts(&d_text); + assert_eq!(t.len(), 1, "{font}: Type 3 with ToUnicode should import as live text"); + assert_eq!(t[0].plain_text(), "ab"); + let run = &t[0].runs[0]; + assert!((run.style.size - 20.0).abs() < 1e-3, "{font}: font size should be 20 pt, got {}", run.style.size); + + let d_paths = open_as(&page(&format!("BT /{font} 20 Tf 20 50 Td (ab) Tj ET"), ""), TextAs::Outlines); + assert!(texts(&d_paths).is_empty(), "In Outlines mode, Type 3 text should be outlines"); + let mut groups = 0; + d_paths.walk(|n| { + if let NodeKind::Group { .. } = &n.kind + && n.name.as_deref() == Some("") + { + groups += 1; + } + }); + assert_eq!(groups, 1, "In Paths mode, Type 3 text should be grouped in "); + } +} + +/// Invisible Type 3 text (mode 3) with ToUnicode imports as searchable text. +#[test] +fn type3_invisible_with_to_unicode_imports_as_searchable_text() { + let d = open_as(&page("BT /T3U 20 Tf 3 Tr 20 50 Td (ab) Tj ET", ""), TextAs::Text); + let t = texts(&d); + assert_eq!(t.len(), 1, "Invisible Type 3 text with ToUnicode imports as searchable text"); + assert_eq!(t[0].plain_text(), "ab"); + for r in &t[0].runs { + assert!(r.style.fill.is_none(), "Invisible text has no fill: {:?}", r.style.fill); + assert!(!r.style.has_stroke(), "Invisible text has no stroke"); + } +} + +/// Type 3 text with ActualText replacement honors authored text or suppression. +#[test] +fn type3_with_actual_text() { + // Authored replacement "XYZ" over Type 3 glyphs (ab) + let d = open_as(&page("/Span << /ActualText (XYZ) >> BDC BT /T3U 20 Tf 20 50 Td (ab) Tj ET EMC", ""), TextAs::Text); + let t = texts(&d); + assert_eq!(t.len(), 1, "Type 3 with ActualText should import as live text"); + assert_eq!(t[0].plain_text(), "XYZ"); + + // Empty ActualText suppresses mapped text + let d_empty = open_as(&page("/Span << /ActualText () >> BDC BT /T3U 20 Tf 20 50 Td (ab) Tj ET EMC", ""), TextAs::Text); + let t_empty = texts(&d_empty); + assert!(t_empty.is_empty(), "Empty ActualText should suppress text"); +} + /// A font that isn't embedded or installed is set in a stand-in: the line still starts where /// the file starts it, on its baseline, and is as long as the file's. #[test] diff --git a/crates/render/src/fx/bounds.rs b/crates/render/src/fx/bounds.rs index 2887180a42..13a6dad415 100644 --- a/crates/render/src/fx/bounds.rs +++ b/crates/render/src/fx/bounds.rs @@ -69,12 +69,23 @@ pub(crate) fn visual_bounds(symbols: &SymbolBoxes, n: &Node) -> Option { } let bp = node_bezpath(n)?; let ctx = GeomContext { doc: Some(symbols.document()), ..GeomContext::of(n) }; - let g = effected_path(symbols.document(), n, &bp); + let (g, carry) = effected_path_carrying(symbols.document(), n, &bp); + // The raster effects reach as far as they are drawn: following only the Transform effects + // that moved the art ([`effects::Carry::hide_skipped`]). + let mut ran = std::borrow::Cow::Borrowed(n); + if carry.skipped() { + carry.hide_skipped(&mut ran.to_mut().appearance.effects); + } let mut r: Option = (!g.elements().is_empty()).then(|| g.bounding_box()); - for item in &n.appearance.items { + for (j, item) in n.appearance.items.iter().enumerate() { let fx = item_effects(item); if effects::has_geometry(fx) { - let ig = apply(fx, &g, &ctx.item(item)); + let (ig, c) = apply_carrying(fx, &g, &ctx.item(item)); + if c.skipped() + && let Some(it) = ran.to_mut().appearance.items.get_mut(j) + { + c.hide_skipped(it.effects_mut()); + } if !ig.elements().is_empty() { let b = ig.bounding_box(); r = Some(r.map_or(b, |r| r.union(b))); @@ -82,7 +93,44 @@ pub(crate) fn visual_bounds(symbols: &SymbolBoxes, n: &Node) -> Option { } } let s = n.appearance.outset(); - r.map(|r| with_raster_reach(symbols, n, r.inflate(s, s))) + r.map(|r| with_raster_reach(symbols, &ran, r.inflate(s, s))) +} + +/// `n` with the Transform effects its geometry passes leave out (past the budget) hidden, in its +/// own list and in its fills' and strokes' ([`effects::Carry::hide_skipped`]): the effects its +/// raster effects are drawn from. Borrowed when it has no Transform effect or no raster effect, is +/// not a path or compound path, or its art is made by [`effects::reshape`] or a 3D effect. +fn ran<'a>(doc: &Document, n: &'a Node) -> std::borrow::Cow<'a, Node> { + let transforms = |fx: &[Effect]| fx.iter().any(|e| e.visible && e.id == "distort.transform"); + let mut out = std::borrow::Cow::Borrowed(n); + if (!transforms(&n.appearance.effects) && !n.appearance.items.iter().any(|i| transforms(item_effects(i)))) + || (effects::raster_effects(&n.appearance.effects).is_empty() + && n.appearance.items.iter().all(|i| effects::raster_effects(item_effects(i)).is_empty())) + || effects::has_painted_effects(n) + || effects::has_revolve(n) + || effects::has_solid(n) + { + return out; + } + let Some(bp) = node_bezpath(n) else { return out }; + let ctx = GeomContext { doc: Some(doc), ..GeomContext::of(n) }; + let (g, carry) = apply_carrying(&n.appearance.effects, &bp, &ctx); + if carry.skipped() { + carry.hide_skipped(&mut out.to_mut().appearance.effects); + } + for (j, item) in n.appearance.items.iter().enumerate() { + let fx = item_effects(item); + if !transforms(fx) || g.elements().is_empty() { + continue; + } + let (_, c) = apply_carrying(fx, &g, &ctx.item(item)); + if c.skipped() + && let Some(it) = out.to_mut().appearance.items.get_mut(j) + { + c.hide_skipped(it.effects_mut()); + } + } + out } /// `r`, the art of `n` with its strokes, grown by how far the raster effects of `n`'s fills and @@ -176,13 +224,37 @@ fn paints(item: &AppearanceItem) -> bool { /// [`Node::visual_bounds_with`] measures them, without the reach of `n`'s own raster effects /// (symbol instances measured by their art from `symbols`): what Rasterize makes its image over. pub(crate) fn drawn_bounds(symbols: &SymbolBoxes, n: &Node) -> Option { + drawn_bounds_ran(symbols, n, None) +} + +/// [`drawn_bounds`], with `ran`, [`ran`] of `n`, when the caller has it. +fn drawn_bounds_ran(symbols: &SymbolBoxes, n: &Node, ran: Option<&Node>) -> Option { // A 3D effect's art holds its fills' and strokes' raster effects, measured with it. if let Some(b) = three_d_bounds(symbols, n) { return b; } let b = art_bounds(symbols, n)?; - let items = n.appearance.items.iter().filter(|i| paints(i) && !effects::raster_effects(item_effects(i)).is_empty()); - Some(items.map(|i| spread(symbols, &item_raster(n, i), item_bounds(symbols.document(), n, i).unwrap_or(b))).fold(b, |acc, r| acc.union(r))) + let mut items = + n.appearance.items.iter().enumerate().filter(|(_, i)| paints(i) && !effects::raster_effects(item_effects(i)).is_empty()).peekable(); + if items.peek().is_none() { + return Some(b); + } + let own; + let ran = match ran { + Some(r) => r, + None => { + own = self::ran(symbols.document(), n); + &*own + } + }; + Some( + items + .map(|(j, i)| { + let r = ran.appearance.items.get(j).unwrap_or(i); + spread(symbols, &item_raster(ran, r), item_bounds(symbols.document(), n, i).unwrap_or(b)) + }) + .fold(b, |acc, r| acc.union(r)), + ) } /// The bounds of what `item`, a fill or stroke of the path or compound path `n`, paints: the path @@ -363,7 +435,9 @@ pub(crate) fn painted_reach(symbols: &SymbolBoxes, n: &Node) -> Option { if let Some(art) = effects::crop_marks_art(n) { return drawn_bounds(symbols, &art); } - drawn_bounds(symbols, n).map(|b| spread(symbols, &n.appearance.effects, b)) + let ran = ran(symbols.document(), n); + let b = drawn_bounds_ran(symbols, n, Some(&ran))?; + Some(spread(symbols, &ran.appearance.effects, b)) } /// The outline the renderer clips `n`'s Feather, Inner Glow and Rasterize with Create Clipping diff --git a/crates/render/src/fx/pixels.rs b/crates/render/src/fx/pixels.rs index 052a8401a4..72731f7330 100644 --- a/crates/render/src/fx/pixels.rs +++ b/crates/render/src/fx/pixels.rs @@ -676,6 +676,13 @@ impl Renderer { ap.items.pop() }); let item = carried.as_ref().and_then(Option::as_ref).unwrap_or(item); + // Its raster effects follow only the Transform effects that moved it. + let ran = carry.skipped().then(|| { + let mut it = item.clone(); + carry.hide_skipped(it.effects_mut()); + it + }); + let item = ran.as_ref().unwrap_or(item); let ib = if effects::has_geometry(item_effects(item)) && !ig.elements().is_empty() { ig.bounding_box() } else { bounds }; let rfx = effects::raster_effects(&item_raster(n, item)); if rfx.is_empty() { diff --git a/crates/render/src/fx/renderer.rs b/crates/render/src/fx/renderer.rs index 1e4c39f4eb..190d433973 100644 --- a/crates/render/src/fx/renderer.rs +++ b/crates/render/src/fx/renderer.rs @@ -381,7 +381,8 @@ impl Renderer { return; } let gctx = GeomContext { doc: Some(f.symbols.document()), ..GeomContext::of(paints) }; - let rfx = effects::raster_effects(&n.appearance.effects); + // `paints` hides the Transform effects that did not move `g`. + let rfx = effects::raster_effects(&paints.appearance.effects); // Document-space reach of the painted geometry (strokes, arrowheads…). let outset = n.appearance.outset(); let reach = g.bounding_box().inflate(outset, outset); @@ -926,12 +927,18 @@ impl Renderer { } } -/// `n` with the gradients of its fills and strokes moved along with its effects by `carry`, or -/// `None` when they stay where they are. +/// `n` with the gradients of its fills and strokes moved along with its effects by `carry`, and +/// the Transform effects the geometry pass left out hidden ([`effects::Carry::hide_skipped`]), so +/// its raster effects and those of its fills and strokes stay with its art; `None` when it stays +/// as it is. fn carried(n: &Node, carry: &effects::Carry) -> Option> { - carry.moves(&n.appearance).then(|| { + let moves = carry.moves(&n.appearance); + (moves || carry.skipped()).then(|| { let mut m = n.clone(); - carry.apply(&mut m.appearance); + if moves { + carry.apply(&mut m.appearance); + } + carry.hide_skipped(&mut m.appearance.effects); Arc::new(m) }) } @@ -943,6 +950,42 @@ mod tests { use vectorcraft_color::Color; use vectorcraft_doc::{Document, color::BlendMode}; + /// The node a path is painted from hides a Transform effect left out past the effect budget, + /// so the drop shadow before it is drawn with its own offset and blur, as the art stays. + #[test] + fn a_path_paints_from_the_transforms_that_moved_it() { + use vectorcraft_geom::{Anchor, PathData, Point, SubPath}; + let anchors = (0..=30_000) + .map(|i| { + let x = 2.0 * f64::from(i); + Anchor::with_handles(Point::new(x, 0.0), Point::new(x - 0.5, -20.0), Point::new(x + 0.5, 20.0)) + }) + .collect(); + let path = PathData::single(SubPath::new(anchors, true)); + let mut n = Node::path( + vectorcraft_doc::NodeId(1), + path.clone(), + vectorcraft_doc::Appearance::basic(vectorcraft_color::Paint::solid(Color::rgb(1.0, 0.0, 0.0)), vectorcraft_color::Paint::None, 0.0), + ); + n.appearance.effects = vec![ + vectorcraft_doc::Effect { id: "stylize.dropShadow".into(), params: serde_json::json!({"x": 10, "y": 5, "blur": 4}), visible: true }, + vectorcraft_doc::Effect { + id: "distort.transform".into(), + params: serde_json::json!({"scaleH": 100000, "scaleV": 100000}), + visible: true, + }, + ]; + let doc = Document::new(100.0, 100.0); + let bp = path.to_bezpath(); + let (g, carry) = effected_path_carrying(&doc, &n, &bp); + assert_eq!(g.bounding_box(), bp.bounding_box(), "the art stays where it is"); + let paints = carried(&n, &carry).expect("the Transform effect is hidden"); + match effects::raster_effects(&paints.appearance.effects).first() { + Some(RasterFx::DropShadow { dx, dy, blur, .. }) => assert!((*dx, *dy, *blur) == (10.0, 5.0, 4.0), "{dx} {dy} {blur}"), + other => panic!("expected a drop shadow, got {other:?}"), + } + } + #[test] fn uncached_darkness_shadow_subtracts_before_separate_opacity() { let doc = Document::new(100.0, 100.0); diff --git a/crates/render/src/tests/objectfx.rs b/crates/render/src/tests/objectfx.rs index e8cf7a1745..c359f65219 100644 --- a/crates/render/src/tests/objectfx.rs +++ b/crates/render/src/tests/objectfx.rs @@ -1178,3 +1178,44 @@ fn symbol_instances_with_effects_are_charged_to_the_symbol_budget() { assert!(!r.charge_fx_instance(&d, &inst), "the next does not"); assert_eq!(r.symbol_nodes, vectorcraft_doc::MAX_SYMBOL_NODES); } + +/// A closed path of 30,000 curves along the x axis, 2 pt apart: drawn with about 420,000 lines, +/// and with more than the effect budget's 8 million once scaled 1000 times. +fn wavy() -> vectorcraft_geom::PathData { + use vectorcraft_geom::{Anchor, PathData, SubPath}; + let anchors = (0..=30_000) + .map(|i| { + let x = 2.0 * f64::from(i); + Anchor::with_handles(Point::new(x, 0.0), Point::new(x - 0.5, -20.0), Point::new(x + 0.5, 20.0)) + }) + .collect(); + PathData::single(SubPath::new(anchors, true)) +} + +/// A Transform effect left out past the effect budget leaves the art where it is, and the drop +/// shadow before it (the object's, or the fill's before the fill's own Transform effect) reaches +/// as far as it is drawn: by its own offset, not by a thousand times it. +#[test] +fn a_shadow_before_a_skipped_transform_reaches_as_far_as_it_is_drawn() { + let shadow = fx("stylize.dropShadow", json!({"x": 10, "y": 5, "blur": 0})); + let big = fx("distort.transform", json!({"scaleH": 100000, "scaleV": 100000})); + let path = wavy(); + let art = path.bounds().unwrap(); + let mut object = Node::path(NodeId(1), path.clone(), Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0)); + let mut fill = object.clone(); + object.appearance.effects = vec![shadow.clone(), big.clone()]; + if let Some(item) = fill.appearance.items.first_mut() { + *item.effects_mut() = vec![shadow, big]; + } + let d = Document::new(100.0, 100.0); + let symbols = d.symbol_boxes(); + // Within the shadow's 10 pt on every side (the visual bounds grow each side by the most any + // side reaches). + let within = |b: Rect| b.x0 >= art.x0 - 11.0 && b.y0 >= art.y0 - 11.0 && b.x1 <= art.x1 + 11.0 && b.y1 <= art.y1 + 11.0; + for (what, n) in [("object", &object), ("fill", &fill)] { + let b = crate::fx::visual_bounds(&symbols, n).unwrap(); + assert!(within(b), "{what}: visual {b:?} for art {art:?}"); + let b = crate::fx::painted_reach(&symbols, n).unwrap(); + assert!(within(b), "{what}: painted {b:?} for art {art:?}"); + } +} diff --git a/crates/svg/src/export/paint.rs b/crates/svg/src/export/paint.rs index 29c502cbdd..bedf456f11 100644 --- a/crates/svg/src/export/paint.rs +++ b/crates/svg/src/export/paint.rs @@ -529,9 +529,9 @@ impl Writer<'_> { self.warn(if freeform { "freeform gradients are written as images clipped to their shapes" } else if conic { - "conic gradients with translucent stops, dither or the Perceptual method are written as images clipped to their shapes" + "conic gradients with translucent stops, dither or a method other than Classic are written as images clipped to their shapes" } else if g.gradient.kind == GradientKind::Diamond { - "diamond gradients with translucent stops, dither, the Perceptual method or no extent are written as images clipped to their shapes" + "diamond gradients with translucent stops, dither, a method other than Classic or no extent are written as images clipped to their shapes" } else { "linear and radial gradients drawn as pixels are written as images clipped to their shapes" }); diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index b7013073d9..7e5d220fbb 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -47,6 +47,10 @@ //! rasterised in SVG //! (). //! On characters they are written as linear gradients through stops on the perceptual curve. +//! * **Gradients mixed around the hue wheel** (Hue Clockwise and Hue Counterclockwise, +//! VectorCraft's own methods) fill or stroke objects as an `` of the gradient too, at the +//! document's raster effects resolution. On characters they are written as gradients through +//! stops on their way around the wheel. //! * **Symbol instances** the shared `` would paint differently from the canvas (stained, //! scaled with strokes, turned or scaled with effects, brushes or live objects, or holding //! pattern paints or unlinked masks, which stay on the page) are written as their own art. diff --git a/crates/svg/tests/it/raster_paints.rs b/crates/svg/tests/it/raster_paints.rs index 2ee1dd3bb5..a6bd69fc5a 100644 --- a/crates/svg/tests/it/raster_paints.rs +++ b/crates/svg/tests/it/raster_paints.rs @@ -214,6 +214,39 @@ fn perceptual_gradients_are_images_and_classic_ones_stay_vector() { assert!(!svg.contains(" std::path::PathBuf { dir } +/// A test's own temporary directory, removed with everything in it when dropped, also when the +/// test panics. [`temp_dir`] makes it, with the same checks, under a tag no other `TempDir` in this +/// process uses, so tests running alongside never share one. A removal that fails (a file still +/// held open) is ignored; the next process with the same id empties the directory before use. +pub struct TempDir(std::path::PathBuf); + +impl TempDir { + /// A new empty directory `vectorcraft-testkit---` in the system temporary + /// folder, where `n` counts the `TempDir`s made in this process. + pub fn new(tag: &str) -> Self { + static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + Self(temp_dir(&format!("{tag}-{n}"))) + } +} + +impl std::ops::Deref for TempDir { + type Target = std::path::PathBuf; + fn deref(&self) -> &std::path::PathBuf { + &self.0 + } +} + +impl AsRef for TempDir { + fn as_ref(&self) -> &std::path::Path { + &self.0 + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + /// How many shapes an SVG draws: its `` elements and the basic shapes SVG export writes /// simple shapes as (``, ``, ``, ``, ``, ``). pub fn svg_shapes(svg: &str) -> usize { @@ -134,4 +169,40 @@ mod tests { assert!(super::temp_dir(tag).join("mine.txt").is_file(), "a later call keeps this process's files"); std::fs::remove_dir_all(&dir).unwrap(); } + + #[test] + fn a_test_dir_is_removed_with_its_contents_when_dropped() { + let dir = super::TempDir::new("dropped"); + let path = dir.to_path_buf(); + std::fs::create_dir_all(path.join("nested")).unwrap(); + std::fs::write(path.join("nested").join("a.txt"), b"a").unwrap(); + drop(dir); + assert!(!path.exists(), "{} is left", path.display()); + } + + #[test] + fn a_test_dir_is_removed_when_its_test_panics() { + let mut path = None; + let r = super::catch_quiet::<()>(|| { + let dir = super::TempDir::new("panicked"); + std::fs::write(dir.join("a.txt"), b"a").unwrap(); + path = Some(dir.to_path_buf()); + panic!("the test fails"); + }); + assert_eq!(r.err().as_deref(), Some("the test fails")); + let path = path.unwrap(); + assert!(!path.exists(), "{} is left", path.display()); + } + + #[test] + fn test_dirs_with_one_tag_are_separate_and_private() { + let (a, b) = (super::TempDir::new("shared-tag"), super::TempDir::new("shared-tag")); + assert_ne!(*a, *b); + std::fs::write(a.join("a.txt"), b"a").unwrap(); + assert_eq!(std::fs::read_dir(&*b).unwrap().count(), 0, "one test's files are not in another's directory"); + #[cfg(unix)] + assert_eq!(std::os::unix::fs::PermissionsExt::mode(&std::fs::metadata(&*a).unwrap().permissions()) & 0o777, 0o700); + drop(a); + assert!(b.is_dir(), "dropping one leaves the other"); + } } diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs index 4f3566b97d..fedd795d78 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -34,7 +34,7 @@ mod ruby; mod shaped; mod vertical; -pub(crate) use bidi::{is_rtl, para_bidi}; +pub(crate) use bidi::{is_rtl, para_bidi, starts_bidi}; use breaking::tab_advance; #[cfg(test)] use breaking::{break_line, candidates}; diff --git a/crates/text/src/layout/bidi.rs b/crates/text/src/layout/bidi.rs index e4b6263244..3f9872983d 100644 --- a/crates/text/src/layout/bidi.rs +++ b/crates/text/src/layout/bidi.rs @@ -4,15 +4,21 @@ use super::{BidiInfo, Level, ParaDirection, Range, SGlyph}; /// without one, from its first strong character. `None` for the usual paragraph with nothing right /// to left in it (no right-to-left character or direction), which skips the algorithm. pub(crate) fn para_bidi(text: &str, direction: Option) -> Option> { - use unicode_bidi::BidiClass::{AL, AN, FSI, R, RLE, RLI, RLO}; let rtl_set = direction == Some(ParaDirection::RightToLeft); - if !rtl_set && !text.chars().any(|c| matches!(unicode_bidi::bidi_class(c), R | AL | AN | RLE | RLO | RLI | FSI)) { + if !rtl_set && !text.chars().any(starts_bidi) { return None; } let level = direction.map(|d| if d == ParaDirection::RightToLeft { Level::rtl() } else { Level::ltr() }); Some(BidiInfo::new(text, level)) } +/// Whether character `c` makes [`para_bidi`] resolve a paragraph that holds it: a right-to-left +/// letter, an Arabic number, or a right-to-left embedding, override or isolate. +pub(crate) fn starts_bidi(c: char) -> bool { + use unicode_bidi::BidiClass::{AL, AN, FSI, R, RLE, RLI, RLO}; + matches!(unicode_bidi::bidi_class(c), R | AL | AN | RLE | RLO | RLI | FSI) +} + /// [`para_bidi`] for a paragraph whose characters in `set` (byte ranges of `text`, in order and not /// overlapping, from [`Ctx::char_directions`]) have a Character Direction: each range is resolved /// as a Unicode bidi embedding, as if an LRE or RLE stood before it and a PDF after it (UAX #9 X2, diff --git a/crates/text/src/layout/region.rs b/crates/text/src/layout/region.rs index 6272e54d71..d7293c1109 100644 --- a/crates/text/src/layout/region.rs +++ b/crates/text/src/layout/region.rs @@ -105,17 +105,32 @@ fn near_segment(a: Point, b: Point, y: f64, r: f64) -> Option<(f64, f64)> { (hi > lo).then_some((lo, hi)) } -/// Inside intervals (even-odd) of the horizontal line at `y` through `polys`, less the points -/// closer than `inset` to any edge of them (holes included), measured from the edge itself. -fn inset_intervals(polys: &[Vec], y: f64, inset: f64) -> Vec<(f64, f64)> { - let iv = poly_intervals(polys, y); +/// The x at which some point of the band `top..bottom` (`top <= bottom`) is closer than `r` to the +/// segment `a`–`b`. The points closer than `r` to the segment make a convex shape, so within the +/// band its leftmost and rightmost points lie on the band's top or bottom or beside an end of the +/// segment inside the band, and the result is one interval. +fn near_segment_in_band(a: Point, b: Point, top: f64, bottom: f64, r: f64) -> Option<(f64, f64)> { + let ends = [a, b].into_iter().filter(|p| p.y >= top && p.y <= bottom).map(|p| (p.x - r, p.x + r)); + let (lo, hi) = [near_segment(a, b, top, r), near_segment(a, b, bottom, r)] + .into_iter() + .flatten() + .chain(ends) + .fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), (c, d)| (lo.min(c), hi.max(d))); + (hi > lo).then_some((lo, hi)) +} + +/// [`band_intervals`] less every x at which some point of the band `top..bottom` is closer than +/// `inset` to an edge of `polys` (holes included), measured from the edge itself. +fn band_inset_intervals(polys: &[Vec], top: f64, bottom: f64, inset: f64) -> Vec<(f64, f64)> { + let iv = band_intervals(polys, top, bottom); if inset <= 0.0 || iv.is_empty() { return iv; } if !inset.is_finite() { return vec![]; } - let near = polys.iter().flat_map(|p| (0..p.len()).filter_map(move |i| near_segment(p[i], p[(i + 1) % p.len()], y, inset))); + let (top, bottom) = (top.min(bottom), top.max(bottom)); + let near = polys.iter().flat_map(|p| (0..p.len()).filter_map(move |i| near_segment_in_band(p[i], p[(i + 1) % p.len()], top, bottom, inset))); subtract_intervals(&iv, &union_intervals(near.collect())) } @@ -132,14 +147,13 @@ fn union_intervals(mut v: Vec<(f64, f64)>) -> Vec<(f64, f64)> { out } -/// `a` minus `b` (both unions of disjoint intervals). +/// `a` minus `b` (both unions of disjoint intervals, `b` sorted as [`union_intervals`] gives it). fn subtract_intervals(a: &[(f64, f64)], b: &[(f64, f64)]) -> Vec<(f64, f64)> { let mut out = vec![]; for &(mut s, e) in a { - for &(c, d) in b { - if d <= s || c >= e { - continue; - } + // Only the intervals of `b` from the first that ends after `s` to the last that starts + // before `e` cut into this one. + for &(c, d) in b[b.partition_point(|&(_, d)| d <= s)..].iter().take_while(|&&(c, _)| c < e) { if c > s { out.push((s, c)); } @@ -166,6 +180,194 @@ fn intersect_intervals(a: &[(f64, f64)], b: &[(f64, f64)]) -> Vec<(f64, f64)> { out } +/// The most pairs of edges [`slant_boundaries`] compares for one band. +const MAX_EDGE_PAIRS: usize = 1 << 14; + +/// An edge of a frame that isn't horizontal, within a band: its lower and upper ends, its y range +/// within the band and its x range there. +type Slant = (Point, Point, (f64, f64), (f64, f64)); + +/// The x of the line through `p` and `q` (not horizontal) at `y`. +fn line_x(p: Point, q: Point, y: f64) -> f64 { + p.x + (y - p.y) / (q.y - p.y) * (q.x - p.x) +} + +/// The x ranges within a band at which the edges `slants` bound the frame. Edges that lie along one +/// line and overlap there (contours that meet along an edge, however each one divides it) count by +/// parity: a stretch of the line that an even number of them cover has the frame on both sides. +/// At most [`MAX_EDGE_PAIRS`] pairs are compared; edges left unpaired still count as boundaries, +/// which can make a line shorter at a seam but never puts it outside the frame. The flag is false +/// when the limit left edges unpaired. +fn slant_boundaries(slants: &mut [Slant]) -> (Vec<(f64, f64)>, bool) { + fn root(parent: &mut [usize], mut i: usize) -> usize { + while parent[i] != i { + parent[i] = parent[parent[i]]; + i = parent[i]; + } + i + } + // Edges along one line overlap in x, so only edges whose x ranges overlap are compared. + slants.sort_by(|u, v| u.3.0.total_cmp(&v.3.0)); + let mut parent: Vec = (0..slants.len()).collect(); + let mut pairs = 0; + 'edges: for (i, &(p, q, _, (_, x1))) in slants.iter().enumerate() { + // Ends on the line up to rounding (a few units in the last place of the coordinates) + // count as on it. + let scale = p.x.abs().max(p.y.abs()).max(q.x.abs()).max(q.y.abs()).max(1.0); + let (d, tol) = (q - p, 4.0 * f64::EPSILON * scale); + let on_line = |r: Point| d.cross(r - p).abs() <= tol * d.hypot(); + for (j, &(r, s, ..)) in slants.iter().enumerate().skip(i + 1).take_while(|(_, o)| o.3.0 <= x1 + tol) { + pairs += 1; + if pairs > MAX_EDGE_PAIRS { + break 'edges; + } + if on_line(r) && on_line(s) { + let (a, b) = (root(&mut parent, i), root(&mut parent, j)); + parent[a] = b; + } + } + } + let mut groups: Vec<(usize, usize)> = (0..slants.len()).map(|i| (root(&mut parent, i), i)).collect(); + groups.sort_unstable(); + let mut out = Vec::new(); + for run in groups.chunk_by(|a, b| a.0 == b.0) { + if let [(_, i)] = run { + out.push(slants[*i].3); + continue; + } + // The stretches an odd number of the edges cover: pairs of their sorted y ends. + let (p, q, ..) = slants[run[0].1]; + let mut ys: Vec = run.iter().flat_map(|&(_, i)| [slants[i].2.0, slants[i].2.1]).collect(); + ys.sort_by(f64::total_cmp); + for c in ys.as_chunks::<2>().0.iter().filter(|c| c[1] > c[0]) { + let (s, t) = (line_x(p, q, c[0]), line_x(p, q, c[1])); + out.push((s.min(t), s.max(t))); + } + } + (out, pairs <= MAX_EDGE_PAIRS) +} + +/// The most pieces a line's band is cut into to keep it inside an Invert Wrap shape grown by its +/// offset. +const INVERT_WRAP_PIECES: f64 = 64.0; + +/// The edges of `polys` that reach into the band `top..bottom` (`top <= bottom`), leaving out those +/// that only touch its top or bottom: the horizontal ones as (y, x0, x1) and the others as +/// [`Slant`]s. +fn band_edges(polys: &[Vec], top: f64, bottom: f64) -> (Vec<(f64, f64, f64)>, Vec) { + let mut flats: Vec<(f64, f64, f64)> = Vec::new(); + let mut slants: Vec = Vec::new(); + for poly in polys { + for (i, &a) in poly.iter().enumerate() { + let b = poly[(i + 1) % poly.len()]; + let (lo, hi) = (a.y.min(b.y), a.y.max(b.y)); + if hi <= top || lo >= bottom { + continue; + } + if a.y == b.y { + flats.push((a.y, a.x.min(b.x), a.x.max(b.x))); + } else { + let (p, q) = if a.y < b.y { (a, b) } else { (b, a) }; + let ys = (lo.max(top), hi.min(bottom)); + let (s, t) = (line_x(p, q, ys.0), line_x(p, q, ys.1)); + slants.push((p, q, ys, (s.min(t), s.max(t)))); + } + } + } + (flats, slants) +} + +/// Inside intervals (even-odd) of `polys` over the whole band `top..bottom`: the intervals at the +/// middle of the band minus every x at which an edge lies within the band. A vertical line at any +/// other x meets no edge inside the band, so it is inside over the whole band exactly when it is +/// inside at the middle. An edge that only touches the top or bottom of the band leaves the band's +/// width alone, and so does a stretch of an edge that contours meet along (one that an even number +/// of edges cover). +fn band_intervals(polys: &[Vec], top: f64, bottom: f64) -> Vec<(f64, f64)> { + let (top, bottom) = (top.min(bottom), top.max(bottom)); + // Contours that meet along an edge cross the middle of the band at the same x, up to a few + // units of rounding: the intervals on either side of it join (an edge that bounds the + // shape there is still subtracted below). A vertical edge crosses the middle at its own x with + // no rounding, so a gap at one is never taken for a seam. + let y = (top + bottom) * 0.5; + let mut upright: Vec = polys + .iter() + .flat_map(|poly| poly.iter().zip(poly.iter().cycle().skip(1))) + .filter(|(a, b)| a.x == b.x && (a.y <= y) != (b.y <= y)) + .map(|(a, _)| a.x) + .collect(); + upright.sort_by(f64::total_cmp); + let upright = |x: f64| upright.binary_search_by(|v| v.total_cmp(&x)).is_ok(); + let mut mid = poly_intervals(polys, y); + mid.dedup_by(|next, prev| { + let gap = next.0 - prev.1; + let seam = gap <= 8.0 * f64::EPSILON * prev.1.abs().max(next.0.abs()).max(1.0) && (gap <= 0.0 || !(upright(prev.1) || upright(next.0))); + if seam { + prev.1 = prev.1.max(next.1); + } + seam + }); + subtract_intervals(&mid, &band_boundaries(polys, top, bottom).0) +} + +/// The x at which `polys` (even-odd) is inside somewhere in the band `top..bottom`, sorted and +/// disjoint: the intervals at the middle of the band and every x at which an edge lies within the +/// band. A vertical line at any other x meets no edge inside the band, so it is inside somewhere in +/// the band exactly when it is inside at the middle. Edges that contours meet along, which bound no +/// part of the shape, are left out as in [`band_intervals`]. When [`MAX_EDGE_PAIRS`] leaves edges +/// unpaired, `admit` keeps only the intervals at the middle, which the shape holds; otherwise every +/// edge counts, which can only widen the result. +fn band_cover(polys: &[Vec], top: f64, bottom: f64, admit: bool) -> Vec<(f64, f64)> { + let (top, bottom) = (top.min(bottom), top.max(bottom)); + let mut iv = poly_intervals(polys, (top + bottom) * 0.5); + let (edges, paired) = band_boundaries(polys, top, bottom); + if paired || !admit { + iv.extend(edges); + } + iv.retain(|e| e.1 > e.0); + union_intervals(iv) +} + +/// [`band_cover`] with `admit`, plus the x of every horizontal edge that lies along the top or +/// bottom of the band (`top < bottom`), counted by parity as in [`band_boundaries`]: the x at which +/// the shape or its outline meets the closed band. +fn band_cover_closed(polys: &[Vec], top: f64, bottom: f64) -> Vec<(f64, f64)> { + let mut iv = band_cover(polys, top, bottom, true); + for y in [top, bottom] { + let mut xs: Vec = polys + .iter() + .flat_map(|poly| poly.iter().zip(poly.iter().cycle().skip(1))) + .filter(|(a, b)| a.y == y && b.y == y) + .flat_map(|(a, b)| [a.x, b.x]) + .collect(); + xs.sort_by(f64::total_cmp); + iv.extend(xs.as_chunks::<2>().0.iter().map(|c| (c[0], c[1]))); + } + iv.retain(|e| e.1 > e.0); + union_intervals(iv) +} + +/// Every x at which an edge of `polys` bounds the shape within the band `top..bottom` +/// (`top <= bottom`), sorted and disjoint, leaving out edges that only touch the top or bottom of +/// the band, stretches of edges that an even number of edges cover, and vertical edges. The flag is +/// false when [`MAX_EDGE_PAIRS`] left edges unpaired, which can only add to the result. +fn band_boundaries(polys: &[Vec], top: f64, bottom: f64) -> (Vec<(f64, f64)>, bool) { + let (mut flats, mut slants) = band_edges(polys, top, bottom); + let (mut edges, paired) = slant_boundaries(&mut slants); + // The x covered by an odd number of the horizontal edges at one height: pairs of their + // sorted ends. + flats.sort_by(|p, q| p.0.total_cmp(&q.0)); + for run in flats.chunk_by(|p, q| p.0 == q.0) { + let mut xs: Vec = run.iter().flat_map(|&(_, a, b)| [a, b]).collect(); + xs.sort_by(f64::total_cmp); + edges.extend(xs.as_chunks::<2>().0.iter().map(|c| (c[0], c[1]))); + } + // A vertical edge covers a single x: where it bounds the shape, the band's middle already + // ends at it or an edge of some width meets it, so it is left out (vertical seams join). + edges.retain(|e| e.1 > e.0); + (union_intervals(edges), paired) +} + impl Region { pub(super) fn cells(path: &BezPath, opts: &LayoutOptions, wrap: &[vectorcraft_doc::WrapShape]) -> Vec { // A frame out of range has no cells, and a wrap shape out of range is left out. @@ -212,23 +414,63 @@ impl Region { self.cell.y1 - self.inset } - /// Inside intervals (even-odd) of the horizontal line at `y`, minus the wrap objects (or - /// inside them, for Invert Wrap). Offsets grow each wrap shape vertically and horizontally. - /// On a shaped frame the intervals keep the inset from the frame's edges, measured from the - /// edge itself. Along the line, the text also keeps the inset beside each wrap object (outside - /// it, or inside it for Invert Wrap); above and below a wrap object only its offset applies. - fn intervals(&self, y: f64) -> Vec<(f64, f64)> { - let mut iv = - if self.polys.is_empty() || self.rect { vec![(self.cell.x0, self.cell.x1)] } else { inset_intervals(&self.polys, y, self.inset) }; + /// `iv` minus every x at which a wrap object lies somewhere in the band `top..bottom` (or the x + /// inside it over the whole band, for Invert Wrap). Offsets grow each wrap shape vertically + /// and horizontally. Along the line, the text also keeps the inset beside each wrap object + /// (outside it, or inside it for Invert Wrap); above and below a wrap object only its offset + /// applies. + fn wrapped(&self, mut iv: Vec<(f64, f64)>, top: f64, bottom: f64) -> Vec<(f64, f64)> { + let (top, bottom) = (top.min(bottom), top.max(bottom)); + let inset = self.inset; for (polys, off, invert) in self.wraps.iter() { - let ys = if *off > 0.0 { vec![y - off, y - off * 0.5, y, y + off * 0.5, y + off] } else { vec![y] }; - let w = union_intervals(ys.into_iter().flat_map(|y| poly_intervals(polys, y)).map(|(a, b)| (a - off, b + off)).collect()); + if iv.is_empty() { + break; + } + let grow = |v: Vec<(f64, f64)>| union_intervals(v.into_iter().map(|(a, b)| (a - off, b + off)).collect()); + let shrink = |v: Vec<(f64, f64)>| v.into_iter().map(|(a, b)| (a + inset, b - inset)).filter(|(a, b)| b > a).collect::>(); iv = if *invert { - let w: Vec<_> = w.into_iter().map(|(a, b)| (a + self.inset, b - self.inset)).filter(|(a, b)| b > a).collect(); - intersect_intervals(&iv, &w) + // The band is cut into pieces. Each height of a piece `y0..y1` is within the offset + // of some height from `y0` plus the offset to `y1` less the offset, so an x the + // shape holds at all of those heights is inside the grown shape over the piece. In + // a piece less than twice the offset tall, each height of the piece is within the + // offset of every height from `y1` less the offset to `y0` plus the offset, so an x + // the shape holds at any of them is. Text within the offset of such an x, for every + // piece, stays inside the grown shape; finer pieces give it more of that room. + // + // The band is also cut at every height an offset above or below an anchor of the + // shape (when there are at most [`INVERT_WRAP_PIECES`] of them). Within a piece + // between such cuts, no anchor enters or leaves the offset window of any of its + // heights, so where two parts of the shape bridge a gap together (one within the + // offset above and one below), the heights from `y1` less the offset to `y0` plus + // the offset reach from one to the other, and the horizontal edges they end at + // count. + let pieces = if *off > 0.0 { ((bottom - top) * 4.0 / off).ceil().clamp(1.0, INVERT_WRAP_PIECES) } else { 1.0 }; + let mut cuts: Vec = (0..=pieces as usize).map(|k| top + (bottom - top) * k as f64 / pieces).collect(); + // A band of no height stays one piece: no anchor lies strictly inside it, and + // removing the repeated cut would leave no piece. + if *off > 0.0 && bottom > top { + let mut anchors: Vec = + polys.iter().flatten().flat_map(|p| [p.y - off, p.y + off]).filter(|&y| y > top && y < bottom).collect(); + anchors.sort_by(f64::total_cmp); + anchors.dedup(); + if anchors.len() <= INVERT_WRAP_PIECES as usize { + cuts.extend(anchors); + cuts.sort_by(f64::total_cmp); + cuts.dedup(); + } + } + for w in cuts.windows(2) { + let (a, b) = (w[0] + off, w[1] - off); + let held = if a <= b { band_intervals(polys, a, b) } else { band_cover_closed(polys, b, a) }; + iv = intersect_intervals(&iv, &shrink(grow(held))); + if iv.is_empty() { + break; + } + } + iv } else { - let w = union_intervals(w.into_iter().map(|(a, b)| (a - self.inset, b + self.inset)).collect()); - subtract_intervals(&iv, &w) + let w = grow(band_cover(polys, top - off, bottom + off, false)); + subtract_intervals(&iv, &union_intervals(w.into_iter().map(|(a, b)| (a - inset, b + inset)).collect())) }; } iv @@ -242,8 +484,8 @@ impl Region { /// Every horizontal span inside the frame (and the cell) over the band `top..bottom`, left to /// right (text wraps on both sides of an object). pub(super) fn spans(&self, top: f64, bottom: f64) -> Vec<(f64, f64)> { - // The inset from the cell's edges; `intervals` already keeps it from the frame's edges and - // beside the wrap objects. + // The inset from the cell's edges; `band_inset_intervals` already keeps it from the frame's + // edges and `wrapped` beside the wrap objects. let clip = |(a, b): (f64, f64)| { let (a, b) = (a.max(self.cell.x0 + self.inset), b.min(self.cell.x1 - self.inset)); (b > a).then_some((a, b)) @@ -252,33 +494,19 @@ impl Region { if plain && self.wraps.is_empty() { return (self.cell.width() > 0.0).then_some((self.cell.x0, self.cell.x1)).and_then(clip).into_iter().collect(); } - let fb = if plain { + let fb = if top.is_nan() || bottom.is_nan() { + return vec![]; + } else if plain { self.cell } else { self.polys.iter().flatten().fold(Rect::new(f64::MAX, f64::MAX, f64::MIN, f64::MIN), |r, p| r.union_pt(*p)) }; - let clamp = |y: f64| if plain { y } else { y.clamp(fb.y0 + 1e-4, fb.y1 - 1e-4) }; - // Sample the band densely enough for curved frames (circles, blobs). - let samples = 5; - let mut rows: Vec> = - (0..samples).map(|k| self.intervals(clamp(top + (bottom - top) * k as f64 / (samples - 1) as f64))).collect(); - let mid = rows.swap_remove(samples / 2); - if !self.wraps.is_empty() { - // Wrap objects split lines: keep exactly what is free on every sampled row. - let free = rows.iter().fold(mid, |acc, r| intersect_intervals(&acc, r)); - return free.into_iter().filter_map(clip).collect(); - } - mid.into_iter() - .filter_map(|(mut a, mut b)| { - for o in &rows { - let best = - o.iter().map(|&(c, d)| (a.max(c), b.min(d))).filter(|(c, d)| d > c).max_by(|x, y| (x.1 - x.0).total_cmp(&(y.1 - y.0)))?; - a = best.0; - b = best.1; - } - clip((a, b)) - }) - .collect() + // `max` then `min` rather than `clamp`, which panics on a frame less than 2e-4 tall. + let clamp = |y: f64| if plain { y } else { y.max(fb.y0 + 1e-4).min(fb.y1 - 1e-4) }; + let free = if plain { vec![(self.cell.x0, self.cell.x1)] } else { band_inset_intervals(&self.polys, clamp(top), clamp(bottom), self.inset) }; + // Wrap objects split lines: keep what is free of them over the whole band. + let free = if self.wraps.is_empty() { free } else { self.wrapped(free, clamp(top), clamp(bottom)) }; + free.into_iter().filter_map(clip).collect() } } @@ -321,10 +549,194 @@ fn cell_spans(path: &BezPath, opts: &LayoutOptions, wrap: &[vectorcraft_doc::Wra fn assert_spans(got: &[(f64, f64)], want: &[(f64, f64)]) { assert_eq!(got.len(), want.len(), "{got:?} != {want:?}"); for (g, w) in got.iter().zip(want) { - assert!((g.0 - w.0).abs() < 1e-6 && (g.1 - w.1).abs() < 1e-6, "{got:?} != {want:?}"); + assert!((g.0 - w.0).abs() < 1e-9 && (g.1 - w.1).abs() < 1e-9, "{got:?} != {want:?}"); } } +/// A line stays inside a frame whose right edge pinches in to a point between any fixed heights of +/// the line's band, with or without text wrap shapes elsewhere. +#[cfg(test)] +#[test] +fn a_line_stays_inside_a_frame_that_pinches_in_within_its_band() { + let notch = + |tip: (f64, f64), (y0, y1): (f64, f64)| closed(&[&[(0.0, 0.0), (100.0, 0.0), (100.0, y0), tip, (100.0, y1), (100.0, 100.0), (0.0, 100.0)]]); + let far = PathData::from_bezpath(&Rect::new(300.0, 0.0, 310.0, 100.0).to_path(0.1)); + let far = vectorcraft_doc::WrapShape { path: far, wrap: Default::default() }; + for (frame, x) in + [(notch((60.0, 47.5), (45.0, 50.0)), 60.0), (notch((70.0, 42.0), (41.0, 43.0)), 70.0), (notch((80.0, 59.0), (58.0, 60.0)), 80.0)] + { + for wrap in [&[][..], std::slice::from_ref(&far)] { + let cells = Region::cells(&frame, &LayoutOptions::default(), wrap); + assert_spans(&cells[0].spans(40.0, 60.0), &[(0.0, x)]); + assert_eq!(cells[0].span(40.0, 60.0), Some((0.0, x))); + } + } +} + +/// A line stays clear of a wrap object whose tip reaches into its band between any fixed heights of +/// the band, with or without an offset, and inside an Invert Wrap object whose edge pinches in +/// there. Invert Wrap with an offset keeps the lines it kept beside a straight edge. +#[cfg(test)] +#[test] +fn a_line_stays_clear_of_a_wrap_object_that_reaches_into_its_band() { + let frame = Rect::new(0.0, 0.0, 100.0, 100.0).to_path(0.1); + let spans = |shape: &[(f64, f64)], offset: f64, invert: bool| { + let path = PathData::from_bezpath(&closed(&[shape])); + let wrap = vectorcraft_doc::WrapShape { path, wrap: vectorcraft_doc::TextWrap { offset, invert } }; + let cells = Region::cells(&frame, &LayoutOptions::default(), &[wrap]); + assert!(cells[0].rect); + cells[0].spans(40.0, 60.0) + }; + assert_spans(&spans(&[(100.0, 45.0), (40.0, 47.5), (100.0, 50.0)], 0.0, false), &[(0.0, 40.0)]); + assert_spans(&spans(&[(100.0, 47.0), (40.0, 47.5), (100.0, 48.0)], 1.0, false), &[(0.0, 39.0)]); + // Two contours that cancel each other (even-odd) hold no area and leave the line whole. + let band: &[(f64, f64)] = &[(0.0, 45.0), (100.0, 45.0), (100.0, 55.0), (0.0, 55.0)]; + let path = PathData::from_bezpath(&closed(&[band, band])); + let wrap = vectorcraft_doc::WrapShape { path, wrap: vectorcraft_doc::TextWrap { offset: 0.0, invert: false } }; + assert_spans(&Region::cells(&frame, &LayoutOptions::default(), &[wrap])[0].spans(40.0, 60.0), &[(0.0, 100.0)]); + let notch = [(0.0, 0.0), (100.0, 0.0), (100.0, 45.0), (60.0, 47.5), (100.0, 50.0), (100.0, 100.0), (0.0, 100.0)]; + assert_spans(&spans(¬ch, 0.0, true), &[(0.0, 60.0)]); + let triangle = [(0.0, 0.0), (100.0, 100.0), (0.0, 100.0)]; + assert_spans(&spans(&triangle, 5.0, true), &[(0.0, 50.0)]); + assert_spans(&spans(&triangle, 15.0, true), &[(0.0, 70.0)]); + // An Invert Wrap shape that steps sideways within the band keeps the room its offset bridges. + let upper: &[(f64, f64)] = &[(0.0, 0.0), (40.0, 0.0), (40.0, 50.0), (0.0, 50.0)]; + let lower: &[(f64, f64)] = &[(45.0, 50.0), (85.0, 50.0), (85.0, 100.0), (45.0, 100.0)]; + let path = PathData::from_bezpath(&closed(&[upper, lower])); + let wrap = vectorcraft_doc::WrapShape { path, wrap: vectorcraft_doc::TextWrap { offset: 5.0, invert: true } }; + assert_spans(&Region::cells(&frame, &LayoutOptions::default(), &[wrap])[0].spans(40.0, 60.0), &[(40.0, 45.0)]); + // An Invert Wrap shape of two parts whose offsets meet across the gap between them (45.25 + 5 + // reaches past 55.125 - 5) keeps the whole line. + let upper: &[(f64, f64)] = &[(0.0, 0.0), (100.0, 0.0), (100.0, 45.25), (0.0, 45.25)]; + let lower: &[(f64, f64)] = &[(0.0, 55.125), (100.0, 55.125), (100.0, 100.0), (0.0, 100.0)]; + let path = PathData::from_bezpath(&closed(&[upper, lower])); + let wrap = vectorcraft_doc::WrapShape { path, wrap: vectorcraft_doc::TextWrap { offset: 5.0, invert: true } }; + assert_spans(&Region::cells(&frame, &LayoutOptions::default(), &[wrap])[0].spans(40.0, 60.0), &[(0.0, 100.0)]); + // A gap the offsets do not bridge (45 + 5 stops short of 55.125 - 5) holds no line. + let upper: &[(f64, f64)] = &[(0.0, 0.0), (100.0, 0.0), (100.0, 45.0), (0.0, 45.0)]; + let path = PathData::from_bezpath(&closed(&[upper, lower])); + let wrap = vectorcraft_doc::WrapShape { path, wrap: vectorcraft_doc::TextWrap { offset: 5.0, invert: true } }; + assert!(Region::cells(&frame, &LayoutOptions::default(), &[wrap])[0].spans(40.0, 60.0).is_empty()); + // A band of no height keeps Invert Wrap and its offset. + let strip: &[(f64, f64)] = &[(20.0, 0.0), (40.0, 0.0), (40.0, 100.0), (20.0, 100.0)]; + let path = PathData::from_bezpath(&closed(&[strip])); + let wrap = vectorcraft_doc::WrapShape { path, wrap: vectorcraft_doc::TextWrap { offset: 5.0, invert: true } }; + assert_spans(&Region::cells(&frame, &LayoutOptions::default(), &[wrap])[0].spans(50.0, 50.0), &[(15.0, 45.0)]); +} + +/// A hole that starts and ends inside a line's band splits the line, and a band below the hole, or +/// one that only touches it, keeps the whole width. +#[cfg(test)] +#[test] +fn a_hole_inside_a_band_splits_the_line() { + let frame = closed(&[&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], &[(40.0, 52.0), (60.0, 52.0), (60.0, 58.0), (40.0, 58.0)]]); + let cells = Region::cells(&frame, &LayoutOptions::default(), &[]); + assert!(!cells[0].rect); + assert_spans(&cells[0].spans(40.0, 60.0), &[(0.0, 40.0), (60.0, 100.0)]); + assert_spans(&cells[0].spans(60.0, 80.0), &[(0.0, 100.0)]); + // A band that only touches the hole at its top or bottom keeps the whole width. + assert_spans(&cells[0].spans(58.0, 78.0), &[(0.0, 100.0)]); + assert_spans(&cells[0].spans(32.0, 52.0), &[(0.0, 100.0)]); + // A band given bottom first covers the same heights. + assert_spans(&cells[0].spans(60.0, 40.0), &[(0.0, 40.0), (60.0, 100.0)]); + assert!(cells[0].spans(f64::NAN, 60.0).is_empty()); +} + +/// Lines run across an edge two contours share (a horizontal one over the part both cover) and +/// stop at the part only one covers (a step). +#[cfg(test)] +#[test] +fn lines_cross_an_edge_two_contours_share() { + let seam = closed(&[&[(0.0, 0.0), (100.0, 0.0), (100.0, 50.0), (0.0, 50.0)], &[(0.0, 50.0), (100.0, 50.0), (100.0, 100.0), (0.0, 100.0)]]); + let cells = Region::cells(&seam, &LayoutOptions::default(), &[]); + assert!(!cells[0].rect); + assert_spans(&cells[0].spans(40.0, 60.0), &[(0.0, 100.0)]); + let step = closed(&[&[(0.0, 0.0), (100.0, 0.0), (100.0, 50.0), (0.0, 50.0)], &[(0.0, 50.0), (50.0, 50.0), (50.0, 100.0), (0.0, 100.0)]]); + let cells = Region::cells(&step, &LayoutOptions::default(), &[]); + assert_spans(&cells[0].spans(40.0, 60.0), &[(0.0, 50.0)]); + // Contours that meet along a seam that bends within the band, one drawn each way along it. + let bent = closed(&[ + &[(0.0, 0.0), (50.0, 0.0), (70.0, 47.5), (50.0, 100.0), (0.0, 100.0)], + &[(50.0, 0.0), (100.0, 0.0), (100.0, 100.0), (50.0, 100.0), (70.0, 47.5)], + ]); + let cells = Region::cells(&bent, &LayoutOptions::default(), &[]); + assert_spans(&cells[0].spans(40.0, 60.0), &[(0.0, 100.0)]); + // Contours side by side, meeting along a vertical edge. + let side = closed(&[&[(0.0, 0.0), (50.0, 0.0), (50.0, 100.0), (0.0, 100.0)], &[(50.0, 0.0), (100.0, 0.0), (100.0, 100.0), (50.0, 100.0)]]); + let cells = Region::cells(&side, &LayoutOptions::default(), &[]); + assert_spans(&cells[0].spans(40.0, 60.0), &[(0.0, 100.0)]); + // The same, with an extra anchor on one side of the shared edge. + let split = + closed(&[&[(0.0, 0.0), (50.0, 0.0), (50.0, 50.0), (50.0, 100.0), (0.0, 100.0)], &[(50.0, 0.0), (100.0, 0.0), (100.0, 100.0), (50.0, 100.0)]]); + let cells = Region::cells(&split, &LayoutOptions::default(), &[]); + assert_spans(&cells[0].spans(40.0, 60.0), &[(0.0, 100.0)]); + // A slanted shared edge with an extra anchor on one side. + let slanted = + closed(&[&[(0.0, 0.0), (40.0, 0.0), (50.0, 50.0), (60.0, 100.0), (0.0, 100.0)], &[(40.0, 0.0), (100.0, 0.0), (100.0, 100.0), (60.0, 100.0)]]); + let cells = Region::cells(&slanted, &LayoutOptions::default(), &[]); + assert_spans(&cells[0].spans(40.0, 60.0), &[(0.0, 100.0)]); + // Slanted edges of two contours 1e-7 pt apart are not one edge: the line stops at each. + let near = + closed(&[&[(0.0, 0.0), (40.0, 0.0), (60.0, 100.0), (0.0, 100.0)], &[(40.0 + 1e-7, 0.0), (100.0, 0.0), (100.0, 100.0), (60.0 + 1e-7, 100.0)]]); + let cells = Region::cells(&near, &LayoutOptions::default(), &[]); + assert_spans(&cells[0].spans(40.0, 60.0), &[(0.0, 48.0), (52.0 + 1e-7, 100.0)]); + // The same 1e-6 pt apart, 1e8 pt from the origin. + let (x, y) = (1e8, 1e8); + let far = closed(&[ + &[(x, y), (x + 40.0, y), (x + 60.0, y + 100.0), (x, y + 100.0)], + &[(x + 40.0 + 1e-6, y), (x + 100.0, y), (x + 100.0, y + 100.0), (x + 60.0 + 1e-6, y + 100.0)], + ]); + let cells = Region::cells(&far, &LayoutOptions::default(), &[]); + let spans = cells[0].spans(y + 40.0, y + 60.0); + assert!(spans.len() == 2 && spans[0].1 < x + 48.001 && spans[1].0 > x + 51.999, "{spans:?}"); + // A real gap of 0.01 pt between contours far from the origin stays a gap. + let x = 1e8; + let apart = closed(&[ + &[(x, 0.0), (x + 50.0, 0.0), (x + 50.0, 100.0), (x, 100.0)], + &[(x + 50.01, 0.0), (x + 100.0, 0.0), (x + 100.0, 100.0), (x + 50.01, 100.0)], + ]); + let cells = Region::cells(&apart, &LayoutOptions::default(), &[]); + assert_spans(&cells[0].spans(40.0, 60.0), &[(x, x + 50.0), (x + 50.01, x + 100.0)]); + // So does a gap of 1e-7 pt between vertical edges there, a few units of rounding wide. + let apart = closed(&[ + &[(x, 0.0), (x + 50.0, 0.0), (x + 50.0, 100.0), (x, 100.0)], + &[(x + 50.0 + 1e-7, 0.0), (x + 100.0, 0.0), (x + 100.0, 100.0), (x + 50.0 + 1e-7, 100.0)], + ]); + let cells = Region::cells(&apart, &LayoutOptions::default(), &[]); + assert_spans(&cells[0].spans(40.0, 60.0), &[(x, x + 50.0), (x + 50.0 + 1e-7, x + 100.0)]); +} + +/// A frame of 200 thin slanted strips, whose edges in the band overlap in x far more than +/// [`MAX_EDGE_PAIRS`] times, holds no line in the band (no strip holds a vertical line across it). +#[cfg(test)] +#[test] +fn many_overlapping_edges_in_a_band_hold_no_line_outside_the_frame() { + let strips: Vec> = + (0..200).map(|i| f64::from(i) * 2.0).map(|x| vec![(x, 0.0), (x + 1.0, 0.0), (x + 501.0, 100.0), (x + 500.0, 100.0)]).collect(); + let strips: Vec<&[(f64, f64)]> = strips.iter().map(Vec::as_slice).collect(); + let cells = Region::cells(&closed(&strips), &LayoutOptions::default(), &[]); + assert!(cells[0].spans(40.0, 60.0).is_empty()); + assert!(!cells[0].spans(50.0, 50.0).is_empty()); +} + +/// A frame shorter than the band's margin at the frame's top and bottom holds no line and does +/// not panic; a rectangle keeps its inset spans, top and bottom. +#[cfg(test)] +#[test] +fn flat_frames_and_rectangles_keep_their_spans() { + for height in [0.0, 1e-5] { + let flat = closed(&[&[(0.0, 0.0), (10.0, 0.0), (0.0, height)], &[(20.0, 0.0), (30.0, 0.0), (20.0, height)]]); + let cells = Region::cells(&flat, &LayoutOptions::default(), &[]); + assert!(!cells[0].rect); + assert!(cells[0].spans(-5.0, 5.0).iter().all(|&(a, b)| b - a < 1e-3)); + } + let square = Rect::new(0.0, 0.0, 100.0, 100.0).to_path(0.1); + let cells = Region::cells(&square, &LayoutOptions { inset: 10.0, ..LayoutOptions::default() }, &[]); + assert!(cells[0].rect); + assert_eq!((cells[0].top(), cells[0].bottom()), (10.0, 90.0)); + assert_spans(&cells[0].spans(40.0, 60.0), &[(10.0, 90.0)]); +} + /// On a triangle, the inset keeps the line 10 pt from the sloped edge, measured from the edge /// itself (x + y <= 100 - 10√2 at the band's bottom), not 10 pt along the line. #[cfg(test)] diff --git a/crates/text/src/thread.rs b/crates/text/src/thread.rs index b78527378d..ff22f3a5e8 100644 --- a/crates/text/src/thread.rs +++ b/crates/text/src/thread.rs @@ -262,22 +262,41 @@ impl<'a> Rest<'a> { } /// How many bytes of `rest` fit in `frame`, measured as `probe` makes the frame for some runs (with -/// their paragraph styles, the list counts and the continuation mark). +/// their paragraph styles, the list counts and the continuation mark). `no_rtl`: no paragraph of +/// the rest resolves right to left on its own (no character [`crate::layout::starts_bidi`] holds +/// and no right-to-left Character Direction). /// -/// Area type without Shrink Text to Fit whose lines align to the top is first measured with the -/// whole paragraphs of the rest that end at or after byte `want`, and then with twice as many bytes -/// each time, while the rest goes on past them. The layout places lines in order and stops at the -/// first line that does not fit, and each paragraph is shaped and broken on its own text. So when -/// that line starts before the last paragraph break measured, the frame holds the same bytes with -/// the whole rest. Other type, and a rest that ends first, is measured with the whole rest. -fn fit_rest(db: &FontDb, probe: impl Fn(Vec) -> TextObject, frame: &TextObject, rest: Rest<'_>, mut want: usize) -> usize { - let by_paragraph = matches!(frame.kind, TextKind::Area { .. }) - && frame.area.fit.min_scale().is_none() - && frame.area.vertical_align == vectorcraft_doc::VerticalAlign::Top; +/// Area type without Shrink Text to Fit is first measured with the whole paragraphs of the rest +/// that end at or after byte `want`, and then with twice as many bytes each time, while the rest +/// goes on past them. The layout places lines in order and stops at the first line that does not +/// fit, and each paragraph is shaped and broken on its own text. So when that line starts before +/// the last paragraph break measured, the frame holds the same bytes with the whole rest. Lines +/// aligned to the center, the bottom or justified vertically move by the space the placed lines +/// leave, and a frame that is not a plain rectangle flows them again from there. A pass that places +/// less text than the one before is undone, so no pass places more text than the final layout; when +/// that layout stops before the last paragraph break measured, every pass stopped at the same line +/// as with the whole rest. +/// +/// Type on a path is measured the same way when its line starts at the start bracket whatever text +/// follows: no Dynamic Text, Optical Margin Alignment or Roman Hanging Punctuation, the first +/// paragraph aligned Left, Justify Left or Auto, and no right-to-left text (`no_rtl`, and the first +/// paragraph's direction not right to left) unless the type is vertical. Each glyph's step along the +/// path then depends only on the glyphs before it, so when the first glyph that does not fit comes +/// before the last paragraph break measured, the path holds the same bytes with the whole rest. +/// +/// Other type, and a rest that ends first, is measured with the whole rest. +fn fit_rest(db: &FontDb, probe: impl Fn(Vec) -> TextObject, frame: &TextObject, rest: Rest<'_>, mut want: usize, no_rtl: bool) -> usize { + let on_path = matches!(frame.kind, TextKind::OnPath { .. }); + let by_paragraph = match frame.kind { + TextKind::Area { .. } => frame.area.fit.min_scale().is_none(), + TextKind::OnPath { .. } => path_starts_at_bracket(&probe(Vec::new()), no_rtl), + _ => false, + }; if by_paragraph { while let Some(end) = rest.break_after(want.saturating_sub(1)).filter(|&end| end < rest.len) { let (n, unplaced) = fit(db, &probe(rest.before(end))); - if unplaced.is_some_and(|u| u + 1 < end) { + let first_out = if on_path { Some(n) } else { unplaced }; + if first_out.is_some_and(|u| u + 1 < end) { return n; } want = end.saturating_mul(2); @@ -286,6 +305,35 @@ fn fit_rest(db: &FontDb, probe: impl Fn(Vec) -> TextObject, frame: &Tex fit(db, &probe(rest.all())).0 } +/// Whether type on a path made as `head` (the frame with its first paragraph's style) places its +/// line from the start bracket, glyph by glyph, whatever text follows: see [`fit_rest`]. +fn path_starts_at_bracket(head: &TextObject, no_rtl: bool) -> bool { + use vectorcraft_doc::{Justify, ParaDirection}; + let para = head.para_at(0); + !head.dynamic_text + && !head.optical_margin + && !para.roman_hanging + && matches!(para.justify, Justify::Auto | Justify::Left | Justify::JustifyLeft) + && (head.vertical || (no_rtl && para.direction != Some(ParaDirection::RightToLeft))) +} + +/// The end of the last character of `runs` that makes its paragraph resolve right to left +/// ([`crate::layout::starts_bidi`], or a run with the right-to-left Character Direction); 0 when +/// there is none. +fn rtl_end(runs: &[TextRun]) -> usize { + let mut off = 0; + let mut end = 0; + for r in runs { + if r.style.char_direction == Some(vectorcraft_doc::ParaDirection::RightToLeft) && !r.text.is_empty() { + end = off + r.text.len(); + } else if let Some((i, c)) = r.text.char_indices().rev().find(|&(_, c)| crate::layout::starts_bidi(c)) { + end = off + i + c.len_utf8(); + } + off += r.text.len(); + } + end +} + /// A frame's share of a story: its runs, its paragraphs' styles (one per paragraph) and the /// numbered list paragraphs counted before its first one, at level 1 and at the levels past it /// ([`TextObject::list_count`], [`TextObject::list_level_counts`]). @@ -379,7 +427,10 @@ pub fn distribute_continuing_levels( continued: bool, mut counts: ListCounts, ) -> Vec { - let mut story_rest = Rest { runs, run: 0, skip: 0, raw: true, len: runs_len(runs) }; + let story_len = runs_len(runs); + let mut story_rest = Rest { runs, run: 0, skip: 0, raw: true, len: story_len }; + // Where the story's right-to-left text ends ([`rtl_end`]), read once, for type on a path. + let story_rtl_end = std::cell::OnceCell::new(); // Once the story is used up, what is left is one empty run with the style there. let mut used_up: Option = None; let mut out = Vec::with_capacity(frames.len()); @@ -415,7 +466,12 @@ pub fn distribute_continuing_levels( probe.first_para_continues = continues; probe }; - fit_rest(db, probe, f, rest, want) + // The rest is the story after its first `story_len - len` bytes. + let no_rtl = len == 0 + || (matches!(f.kind, TextKind::OnPath { .. }) + && !f.vertical + && *story_rtl_end.get_or_init(|| rtl_end(runs)) <= story_len.saturating_sub(len)); + fit_rest(db, probe, f, rest, want, no_rtl) }; want = n.saturating_mul(2).max(MIN_MEASURE); let mut head = rest.slice(0, n); diff --git a/crates/text/src/thread/tests.rs b/crates/text/src/thread/tests.rs index 943aeb2973..7554a808f9 100644 --- a/crates/text/src/thread/tests.rs +++ b/crates/text/src/thread/tests.rs @@ -19,6 +19,14 @@ fn path_frame(length: f64) -> TextObject { t } +/// Type on a curved path about 300 long. +fn curved_path_frame() -> TextObject { + let mut t = path_frame(300.0); + let curve = kurbo::CubicBez::new((0.0, 0.0), (100.0, -120.0), (200.0, 120.0), (300.0, 0.0)); + t.kind = TextKind::OnPath { path: PathData::from_bezpath(&kurbo::Shape::to_path(&curve, 0.1)), start: 0.0, end: None }; + t +} + /// Type on a path that overflows ends its line where its text stops fitting, as area type's /// last line does, so a story flows on from there through area type and type on a path alike. #[test] @@ -543,6 +551,7 @@ fn paragraphs(n: usize) -> String { /// text and paragraph style that changes how much a frame holds. #[test] fn frames_take_the_shares_the_whole_rest_gives_them() { + use vectorcraft_doc::VerticalAlign; use vectorcraft_doc::text::{NumberStyle, ParaList}; let db = FontDb::global(); let plain = CharStyle::default(); @@ -649,6 +658,123 @@ fn frames_take_the_shares_the_whole_rest_gives_them() { let two = [&frames[0], &frames[1]]; took += same_as_whole_rest(db, &two, &story(¶graphs(200)), &[], "overflowing last frame"); + // Lines aligned to the center, the bottom or justified vertically, in rectangles, ellipses and + // frames that wrap around an object, with Shrink Text to Fit in one frame, and a story whose + // last paragraph runs through several frames. + let last_long = format!("{}\n{}", paragraphs(6), "The quick brown fox jumps over the lazy dog. ".repeat(40)); + for align in [VerticalAlign::Center, VerticalAlign::Bottom, VerticalAlign::Justify] { + let mut rects = frames.clone(); + for f in &mut rects { + f.area.vertical_align = align; + } + took += same_as_whole_rest(db, &refs(&rects), &story(¶graphs(120)), &spaced, &format!("{align:?}")); + took += same_as_whole_rest(db, &refs(&rects), &story(&breaks), &[], &format!("{align:?}, empty paragraphs")); + took += same_as_whole_rest(db, &refs(&rects), &styled, &[], &format!("{align:?}, style runs")); + took += same_as_whole_rest(db, &refs(&rects), &story(¶graphs(120)), &listed, &format!("{align:?}, lists")); + took += same_as_whole_rest(db, &refs(&rects), &story(&last_long), &[], &format!("{align:?}, long last paragraph")); + let mut ellipses = rects.clone(); + for (k, f) in ellipses.iter_mut().enumerate() { + let x = 200.0 * k as f64; + f.kind = TextKind::Area { frame: shapes::ellipse(Rect::new(x, 0.0, x + 160.0, 90.0)) }; + } + took += same_as_whole_rest(db, &refs(&ellipses), &story(¶graphs(120)), &[], &format!("{align:?}, ellipses")); + took += same_as_whole_rest(db, &refs(&ellipses), &story(&long_paras), &justified, &format!("{align:?}, ellipses, justified")); + let mut wrapped = rects.clone(); + for (k, f) in wrapped.iter_mut().enumerate() { + let x = 200.0 * k as f64; + f.wrap = vec![vectorcraft_doc::WrapShape { path: shapes::ellipse(Rect::new(x + 40.0, 10.0, x + 90.0, 40.0)), wrap: Default::default() }]; + } + took += same_as_whole_rest(db, &refs(&wrapped), &story(¶graphs(120)), &[], &format!("{align:?}, wrapped")); + let mut shrink = rects.clone(); + shrink[2].area.fit = vectorcraft_doc::AreaFit::ShrinkText { min_percent: 60.0 }; + took += same_as_whole_rest(db, &refs(&shrink), &story(¶graphs(120)), &[], &format!("{align:?}, Shrink Text to Fit")); + } + + // Type on a path: lines that start at the start bracket, and lines whose place or length + // depends on the text after them (centered or right-aligned, hanging punctuation, Dynamic + // Text, right-to-left text), horizontal and vertical. + let paths = |edit: Edit| -> Vec { + (0..6) + .map(|k| { + let mut t = if k % 2 == 0 { path_frame(300.0) } else { curved_path_frame() }; + if k % 3 == 2 { + // Brackets inside the path, with room for the line's ends to hang past them. + if let TextKind::OnPath { start, end, .. } = &mut t.kind { + (*start, *end) = (0.1, Some(0.8)); + } + } + edit(&mut t); + t + }) + .collect() + }; + let hebrew = "\u{5e9}\u{5dc}\u{5d5}\u{5dd} \u{5e2}\u{5d5}\u{5dc}\u{5dd} ".repeat(4); + let rtl_early = format!("{}\n{}\n{}", paragraphs(2), hebrew.trim_end(), paragraphs(100)); + let ends_unhung = format!("{}\nlast words", paragraphs(120)); + let rtl_late = format!("{}\n{}\n{}", paragraphs(80), hebrew.trim_end(), paragraphs(20)); + let whole = story(¶graphs(120)); + let at = paragraphs(60).len(); + let directed = [ + slice_runs(&whole, 0, at), + vec![TextRun::new( + " set right to left ", + CharStyle { char_direction: Some(vectorcraft_doc::ParaDirection::RightToLeft), ..Default::default() }, + )], + slice_runs(&whole, at, runs_len(&whole)), + ] + .concat(); + type Edit = fn(&mut TextObject); + let edits: [(&str, Edit); 15] = [ + ("path", |_| {}), + ("path, Left", |t| t.para.justify = Justify::Left), + ("path, Auto", |t| t.para.justify = Justify::Auto), + ("path, Justify Left", |t| t.para.justify = Justify::JustifyLeft), + ("path, Center", |t| t.para.justify = Justify::Center), + ("path, Right", |t| t.para.justify = Justify::Right), + ("path, Justify All", |t| t.para.justify = Justify::JustifyAll), + ("path, spacing", |t| t.path_spacing = 8.0), + ("path, Optical Margin Alignment", |t| t.optical_margin = true), + ("path, Roman Hanging Punctuation", |t| t.para.roman_hanging = true), + ("path, Dynamic Text", |t| t.dynamic_text = true), + ("path, right to left", |t| t.para.direction = Some(vectorcraft_doc::ParaDirection::RightToLeft)), + ("path, Auto right to left", |t| { + t.para.justify = Justify::Auto; + t.para.direction = Some(vectorcraft_doc::ParaDirection::RightToLeft); + }), + ("vertical path", |t| t.vertical = true), + ("vertical path, Center", |t| { + t.vertical = true; + t.para.justify = Justify::Center; + }), + ]; + for (case, edit) in edits { + let on = paths(edit); + took += same_as_whole_rest(db, &refs(&on), &story(¶graphs(120)), &[], case); + took += same_as_whole_rest(db, &refs(&on), &story(&rtl_early), &[], &format!("{case}, right-to-left paragraph early")); + took += same_as_whole_rest(db, &refs(&on), &story(&rtl_late), &[], &format!("{case}, right-to-left paragraph late")); + took += same_as_whole_rest(db, &refs(&on), &directed, &[], &format!("{case}, right-to-left Character Direction")); + took += same_as_whole_rest(db, &refs(&on), &story(&last_long), &[], &format!("{case}, long last paragraph")); + // The story's last character does not hang, the last one measured does. + took += same_as_whole_rest(db, &refs(&on), &story(&ends_unhung), &[], &format!("{case}, story ending in a letter")); + } + let on = paths(|_| {}); + took += same_as_whole_rest(db, &refs(&on), &styled, &[], "path, style runs"); + took += same_as_whole_rest(db, &refs(&on), &story(¶graphs(120)), &listed, "path, lists"); + took += same_as_whole_rest(db, &refs(&on), &story(&breaks), &[], "path, spaces and empty paragraphs"); + let story_paras: Vec = (0..120) + .map(|i| ParaStyle { justify: [Justify::Left, Justify::Center, Justify::Auto][i % 3], roman_hanging: i % 5 == 0, ..Default::default() }) + .collect(); + took += same_as_whole_rest(db, &refs(&on), &story(¶graphs(120)), &story_paras, "path, paragraph styles"); + let mut between = frames.clone(); + for (k, f) in between.iter_mut().enumerate() { + if k % 2 == 1 { + *f = path_frame(260.0); + } else { + f.area.vertical_align = VerticalAlign::Bottom; + } + } + took += same_as_whole_rest(db, &refs(&between), &story(¶graphs(120)), &[], "paths between area type"); + // Short stories, an empty one and one of empty runs. took += same_as_whole_rest(db, &refs(&frames), &story("Hi"), &[], "short story"); took += same_as_whole_rest(db, &refs(&frames), &story(""), &[], "empty story"); @@ -674,6 +800,9 @@ fn seeded_stories_take_the_shares_the_whole_rest_gives_them() { let mut paras = 1; for _ in 0..(150 + next(250)) { let mut text = words[next(words.len() as u64) as usize].to_string(); + if next(60) == 0 { + text = "\u{5e9}\u{5dc}\u{5d5}\u{5dd}".to_string(); + } text.push(if next(6) == 0 { paras += 1; '\n' @@ -692,30 +821,80 @@ fn seeded_stories_take_the_shares_the_whole_rest_gives_them() { ..Default::default() }) .collect(); - let frames: Vec = (0..2 + next(6)).map(|k| sized(200.0 * k as f64, 40.0 + next(120) as f64, 10.0 + next(120) as f64)).collect(); + let mut frames: Vec = + (0..2 + next(6)).map(|k| sized(200.0 * k as f64, 40.0 + next(120) as f64, 10.0 + next(120) as f64)).collect(); + // Lines aligned every way, and type on a path, horizontal or vertical. + for f in &mut frames { + use vectorcraft_doc::VerticalAlign; + f.area.vertical_align = [VerticalAlign::Top, VerticalAlign::Center, VerticalAlign::Bottom, VerticalAlign::Justify][next(4) as usize]; + if next(4) == 0 { + *f = if next(2) == 0 { path_frame(80.0 + next(400) as f64) } else { curved_path_frame() }; + f.vertical = next(3) == 0; + } + } same_as_whole_rest(db, &frames.iter().collect::>(), &runs, &styles, &format!("case {case}")); } } -/// A long story of short paragraphs through many frames: each frame is measured with about the -/// text it takes and a little more, not with the whole rest of the story. -#[test] -fn many_frames_measure_about_the_text_they_take() { - let db = FontDb::global(); +/// Each of `frames` takes its share of a long story of short paragraphs measured with about the text +/// it takes and a little more, not with the whole rest of the story. +fn measures_about_the_text_taken(db: &FontDb, frames: &[TextObject], case: &str) { let text = paragraphs(1500); let story = vec![TextRun::new(text.clone(), CharStyle::default())]; - let frames: Vec = (0..40).map(|k| frame(200.0 * k as f64)).collect(); let refs: Vec<&TextObject> = frames.iter().collect(); let before = fit_bytes(); let parts = distribute(db, &refs, &story, &[]); let measured = fit_bytes() - before; let joined: String = parts.iter().flat_map(|p| &p.runs).map(|r| r.text.as_str()).collect(); - assert_eq!(joined, text, "no character lost or duplicated"); + assert_eq!(joined, text, "{case}: no character lost or duplicated"); let placed: usize = parts[..parts.len() - 1].iter().map(|p| runs_len(&p.runs)).sum(); let longest = text.split('\n').map(str::len).max().unwrap_or(0); - assert!(placed > 0 && placed < text.len() / 4, "the frames hold part of the story: {placed} of {}", text.len()); + assert!(placed > 0 && placed < text.len() / 4, "{case}: the frames hold part of the story: {placed} of {}", text.len()); let bound = 4 * placed + frames.len() * 2 * (MIN_MEASURE + longest); - assert!(measured <= bound, "measured {measured} bytes for {placed} placed in {} frames (at most {bound})", frames.len()); + assert!(measured <= bound, "{case}: measured {measured} bytes for {placed} placed in {} frames (at most {bound})", frames.len()); +} + +/// A long story of short paragraphs through many frames: each frame is measured with about the +/// text it takes and a little more, not with the whole rest of the story. That holds for area type +/// aligned to the top, the center or the bottom or justified vertically, in rectangles and other +/// shapes, and for type on a path whose line starts at the start bracket, horizontal or vertical. +#[test] +fn many_frames_measure_about_the_text_they_take() { + use vectorcraft_doc::VerticalAlign; + let db = FontDb::global(); + let frames: Vec = (0..40).map(|k| frame(200.0 * k as f64)).collect(); + measures_about_the_text_taken(db, &frames, "top"); + for align in [VerticalAlign::Center, VerticalAlign::Bottom, VerticalAlign::Justify] { + let mut aligned = frames.clone(); + for f in &mut aligned { + f.area.vertical_align = align; + } + measures_about_the_text_taken(db, &aligned, &format!("{align:?}")); + let mut shaped = aligned.clone(); + for (k, f) in shaped.iter_mut().enumerate() { + let x = 200.0 * k as f64; + f.kind = TextKind::Area { frame: shapes::ellipse(Rect::new(x, 0.0, x + 160.0, 90.0)) }; + } + measures_about_the_text_taken(db, &shaped, &format!("{align:?}, ellipses")); + } + for justify in [Justify::Left, Justify::JustifyLeft, Justify::Auto] { + let paths: Vec = (0..40) + .map(|_| { + let mut t = path_frame(300.0); + t.para.justify = justify; + t + }) + .collect(); + measures_about_the_text_taken(db, &paths, &format!("path, {justify:?}")); + } + let vertical: Vec = (0..40) + .map(|_| { + let mut t = path_frame(300.0); + t.vertical = true; + t + }) + .collect(); + measures_about_the_text_taken(db, &vertical, "vertical path"); } /// Frames that already hold text and take a story over several measurements each: each frame's own diff --git a/crates/tools/src/builder/live_paint.rs b/crates/tools/src/builder/live_paint.rs index 2b6cef4532..e2d6c9f77e 100644 --- a/crates/tools/src/builder/live_paint.rs +++ b/crates/tools/src/builder/live_paint.rs @@ -480,6 +480,8 @@ pub const LP_SELECT_WIDTH_RANGE: (f64, f64) = (1.0, 20.0); /// Select Strokes off, Alt-click selects the face under the pointer as a click does and a marquee /// takes no edges; with Select Fills off, a click selects the edge nearest the pointer as Alt-click /// does and a marquee takes no faces; with both off, a click or a marquee selects no face or edge. +/// The pointer shows what a click at that point selects ([`LivePaintSelectionTool::pick_at`]): a +/// face, an edge, or nothing. From the press to the release it keeps the look it had at the press. pub struct LivePaintSelectionTool { pub(super) cache: RegionCache, pub(super) hover: LpHover, @@ -502,6 +504,8 @@ struct LpDrag { shift: bool, /// The face or edge under the press, which a click selects (or with Shift toggles). hit: Option, + /// The cursor at the press, which the drag keeps. + cursor: Cursor, } impl LpDrag { @@ -538,6 +542,22 @@ impl LivePaintSelectionTool { (false, false) => None, } } + + /// The face or edge a click at `p` selects, Alt held or not, with its cursor: the visible part of + /// the kind [`LivePaintSelectionTool::picks_edge`] asks for, of a Live Paint group the tool takes + /// ([`lp_part_at`], [`lp_selectable`]), and [`Cursor::LivePaintSelectFace`] or + /// [`Cursor::LivePaintSelectEdge`]; None and [`Cursor::LivePaintSelectOutside`] where a click + /// selects no face or edge. + fn pick_at(&self, cx: &ToolContext, p: Point, alt: bool) -> (Option, Cursor) { + let Some(edge) = self.picks_edge(alt) else { return (None, Cursor::LivePaintSelectOutside) }; + let hit = lp_part_at(cx.doc, p, cx.tol(4.0), edge, &|id| lp_selectable(cx, id)).and_then(|(_, part)| part).map(|n| n.id); + let cursor = match (hit, edge) { + (None, _) => Cursor::LivePaintSelectOutside, + (Some(_), true) => Cursor::LivePaintSelectEdge, + (Some(_), false) => Cursor::LivePaintSelectFace, + }; + (hit, cursor) + } } /// The faces (with `faces`) and edges (with `edges`) that marquee `r` touches, among the faces and @@ -592,9 +612,8 @@ impl Tool for LivePaintSelectionTool { vec![] } PointerKind::Down => { - let part = edge.and_then(|e| lp_part_at(cx.doc, p, cx.tol(4.0), e, &|id| lp_selectable(cx, id))); - let hit = part.and_then(|(_, part)| part).map(|n| n.id); - self.drag = Some(LpDrag { start: p, cur: p, shift: ev.mods.shift, hit }); + let (hit, cursor) = self.pick_at(cx, p, ev.mods.alt); + self.drag = Some(LpDrag { start: p, cur: p, shift: ev.mods.shift, hit, cursor }); vec![] } PointerKind::Drag => { @@ -652,8 +671,11 @@ impl Tool for LivePaintSelectionTool { lp_overlays(&self.hover, &self.cache, self.color, self.width as f32, self.width as f32) } - fn cursor(&self, _cx: &ToolContext, _p: Point, _m: Mods) -> Cursor { - Cursor::Arrow + fn cursor(&self, cx: &ToolContext, p: Point, m: Mods) -> Cursor { + match &self.drag { + Some(d) => d.cursor, + None => self.pick_at(cx, p, m.alt).1, + } } fn options(&self) -> Value { diff --git a/crates/tools/src/builder/tests.rs b/crates/tools/src/builder/tests.rs index 89ce04eb3d..298e6a1907 100644 --- a/crates/tools/src/builder/tests.rs +++ b/crates/tools/src/builder/tests.rs @@ -1636,6 +1636,84 @@ fn live_paint_selection_click_outside_the_faces_selects_the_edge_it_highlights() assert_eq!(lp_click(&mut t, &cx, ev(PointerKind::Down, 106.0, 50.0)), vec![Action::Exec("select.none".into(), json!({}))]); } +/// The Live Paint Selection pointer shows what a click at the point selects, from the point and +/// the modifier keys alone (no move first): a face, an edge, or nothing. Groups the tool does not +/// take (locked, hidden, outside isolation) show nothing to select. A press keeps its look until +/// the release. +#[test] +fn live_paint_selection_cursor_shows_what_a_click_selects() { + let mut d = Document::new(500.0, 500.0); + let (g, _) = live_square(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0)); + let (other, _) = live_square(&mut d, Rect::new(200.0, 0.0, 300.0, 100.0)); + let s = Selection::default(); + let p = paint(); + let plain = Mods::default(); + let alt = Mods { alt: true, ..Default::default() }; + let (face, edge, out) = (Cursor::LivePaintSelectFace, Cursor::LivePaintSelectEdge, Cursor::LivePaintSelectOutside); + let at = |t: &LivePaintSelectionTool, cx: &ToolContext, x: f64, m: Mods| t.cursor(cx, Point::new(x, 50.0), m); + let mut t = LivePaintSelectionTool::default(); + { + let cx = cx(&d, &s, &p); + // Both options on: a face inside the square; with Alt the side within reach, inside or + // outside the face; nothing away from the groups or from every side. + assert_eq!( + [at(&t, &cx, 50.0, plain), at(&t, &cx, 98.5, plain), at(&t, &cx, 102.0, plain), at(&t, &cx, 150.0, plain)], + [face, face, out, out] + ); + assert_eq!([at(&t, &cx, 98.5, alt), at(&t, &cx, 102.0, alt), at(&t, &cx, 50.0, alt), at(&t, &cx, 150.0, alt)], [edge, edge, out, out]); + // The cursor agrees with what a click there selects. + let face_id = faces(d.node(g).unwrap())[0].id; + assert_eq!(lp_click(&mut t, &cx, ev(PointerKind::Down, 50.0, 50.0)), vec![Action::Exec("select.set".into(), json!({ "ids": [face_id.0] }))]); + assert_eq!(lp_click(&mut t, &cx, ev(PointerKind::Down, 50.0, 50.0).with_mods(alt)), vec![Action::Exec("select.none".into(), json!({}))]); + // Select Fills off: a side without Alt too, never a face. + t.set_option("selectFills", &json!(false)); + assert_eq!([at(&t, &cx, 98.5, plain), at(&t, &cx, 50.0, plain), at(&t, &cx, 98.5, alt)], [edge, out, edge]); + // Select Strokes off: the face with Alt too, never a side. + t.set_option("selectFills", &json!(true)); + t.set_option("selectStrokes", &json!(false)); + assert_eq!([at(&t, &cx, 98.5, alt), at(&t, &cx, 102.0, alt)], [face, out]); + // Both off: nothing. + t.set_option("selectFills", &json!(false)); + assert_eq!([at(&t, &cx, 50.0, plain), at(&t, &cx, 98.5, alt)], [out, out]); + } + let mut t = LivePaintSelectionTool::default(); + // A locked group shows nothing to select; the other group still does. + d.node_mut(g).unwrap().locked = true; + { + let cx = cx(&d, &s, &p); + assert_eq!([at(&t, &cx, 50.0, plain), at(&t, &cx, 98.5, alt), at(&t, &cx, 250.0, plain)], [out, out, face]); + } + d.node_mut(g).unwrap().locked = false; + // In isolation mode, a group outside the isolated art shows nothing to select. + { + let cx = ToolContext { isolation: Some(other), ..cx(&d, &s, &p) }; + assert_eq!([at(&t, &cx, 50.0, plain), at(&t, &cx, 250.0, plain)], [out, face]); + } + // A hidden group shows nothing to select. + d.node_mut(g).unwrap().visible = false; + { + let cx = cx(&d, &s, &p); + assert_eq!([at(&t, &cx, 50.0, plain), at(&t, &cx, 98.5, alt)], [out, out]); + } + d.node_mut(g).unwrap().visible = true; + // A press keeps its look while the drag goes elsewhere, and the release lets it follow again. + let cx = cx(&d, &s, &p); + t.pointer(&cx, &ev(PointerKind::Down, 50.0, 50.0)); + t.pointer(&cx, &ev(PointerKind::Drag, 150.0, 50.0)); + assert_eq!(at(&t, &cx, 150.0, plain), face); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 50.0)); + assert_eq!(at(&t, &cx, 150.0, plain), out); + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 50.0)); + t.pointer(&cx, &ev(PointerKind::Drag, 50.0, 50.0)); + assert_eq!(at(&t, &cx, 50.0, plain), out); + t.key(&cx, ToolKey::Escape, plain); + assert_eq!(at(&t, &cx, 50.0, plain), face, "Escape ends the press"); + for c in [face, edge, out] { + assert_eq!(c.precise(), Cursor::Crosshair, "{c:?}"); + assert_eq!(c.stand_in(), None, "{c:?} is drawn"); + } +} + /// Presses at `from` with `m`, drags to `to` and releases there; returns what the release does /// (the press and the drag do nothing). fn lp_drag(t: &mut LivePaintSelectionTool, cx: &ToolContext, from: (f64, f64), to: (f64, f64), m: Mods) -> Vec { diff --git a/crates/tools/src/cursor.rs b/crates/tools/src/cursor.rs index d5cdd05bc5..584149da8f 100644 --- a/crates/tools/src/cursor.rs +++ b/crates/tools/src/cursor.rs @@ -148,6 +148,14 @@ pub enum Cursor { LivePaintBucketFace, /// The Live Paint Bucket where a click paints an edge of a Live Paint group: a brush. LivePaintBucketEdge, + /// Live Paint Selection over a face of a Live Paint group that a click selects: the arrow with a + /// filled square. + LivePaintSelectFace, + /// Live Paint Selection over an edge of a Live Paint group that a click selects: the arrow with + /// a short line. + LivePaintSelectEdge, + /// Live Paint Selection where a click selects no face or edge: the arrow with an x. + LivePaintSelectOutside, /// The Measure tool. Measure, /// The Print Tiling tool. @@ -248,7 +256,8 @@ impl Cursor { } /// General › Use Precise Cursors: the drawing tools' pointers (the Pen's in every state, the - /// Anchor Point and Curvature tools', the Eyedropper's, the Slice and Blend tools') become a plain crosshair at the hotspot. + /// Anchor Point and Curvature tools', the Eyedropper's, the Slice and Blend tools', the Live + /// Paint tools') become a plain crosshair at the hotspot. pub fn precise(self) -> Self { match self { Cursor::Pen @@ -287,6 +296,9 @@ impl Cursor { | Cursor::LivePaintBucket | Cursor::LivePaintBucketFace | Cursor::LivePaintBucketEdge + | Cursor::LivePaintSelectFace + | Cursor::LivePaintSelectEdge + | Cursor::LivePaintSelectOutside | Cursor::Measure | Cursor::PrintTiling | Cursor::SymbolSprayer diff --git a/crates/tools/src/cursors.toml b/crates/tools/src/cursors.toml index 107eb34aeb..6f5b32e56a 100644 --- a/crates/tools/src/cursors.toml +++ b/crates/tools/src/cursors.toml @@ -28,7 +28,7 @@ shown_when = [ "The Selection tool over empty canvas or over an unselected object (no Alt).", "Dragging with the Selection tool (a move), with Direct Selection (an anchor, a segment or a handle), or with a shape tool (from the selection's centre point).", "Any tool with no cursor of its own (Touch Type, Rotate View).", - "The resting state of Live Paint Selection, Reshape (away from a path), Free Transform, Puppet Warp and Crop Image (nothing selected or outside the box), the Perspective Grid (locked or away from handles) and Perspective Selection.", + "The resting state of Reshape (away from a path), Free Transform, Puppet Warp and Crop Image (nothing selected or outside the box), the Perspective Grid (locked or away from handles) and Perspective Selection.", ] hotspot = "The arrow's tip." look = "The default pointer: a solid arrow. ArrowHollow is its hollow twin." @@ -89,6 +89,39 @@ shown_when = [ hotspot = "The front arrowhead's tip." look = "Says \"a copy\": a double arrowhead, one in front of the other." +[[cursor]] +id = "LivePaintSelectFace" +group = "Selection" +shown_when = [ + "Live Paint Selection over a face of a Live Paint group that a click selects: inside the face, with Select Fills on, and without Alt unless Select Strokes is off.", + "From a press there until the release, wherever the drag goes.", + "With Use Precise Cursors on, the crosshair shows instead.", +] +hotspot = "The arrow's tip." +look = "Arrow with a small filled square badge (a face). LivePaintSelectEdge and LivePaintSelectOutside share the arrow." + +[[cursor]] +id = "LivePaintSelectEdge" +group = "Selection" +shown_when = [ + "Live Paint Selection within reach of an edge of a Live Paint group that a click selects: Select Strokes is on, and Alt is held or Select Fills is off.", + "From a press there until the release, wherever the drag goes.", + "With Use Precise Cursors on, the crosshair shows instead.", +] +hotspot = "The arrow's tip." +look = "Arrow with a short line badge (an edge)." + +[[cursor]] +id = "LivePaintSelectOutside" +group = "Selection" +shown_when = [ + "Live Paint Selection where a click selects no face or edge: away from Live Paint groups, over a group that is locked, hidden or outside the isolated art, inside a face with Alt held and no edge within reach, or with Select Fills and Select Strokes both off.", + "From a press there until the release, wherever the drag goes.", + "With Use Precise Cursors on, the crosshair shows instead.", +] +hotspot = "The arrow's tip." +look = "Arrow with a small x badge (nothing to select)." + [[cursor]] id = "Move" group = "Selection" diff --git a/crates/tools/src/params.rs b/crates/tools/src/params.rs index 095e0d21cf..c7a205a19e 100644 --- a/crates/tools/src/params.rs +++ b/crates/tools/src/params.rs @@ -76,7 +76,7 @@ pub fn gradient_params(g: &GradientPaint) -> Value { v["dither"] = json!(true); } if !g.gradient.method.is_classic() { - v["method"] = json!(g.gradient.method.label().to_lowercase()); + v["method"] = json!(g.gradient.method.id()); } // A freeform gradient has no ends to spread past (`paint.setFill` refuses a spread for one). if g.gradient.is_spread() { diff --git a/crates/tools/src/xform/free.rs b/crates/tools/src/xform/free.rs index 2d137153fc..1583584940 100644 --- a/crates/tools/src/xform/free.rs +++ b/crates/tools/src/xform/free.rs @@ -4,8 +4,9 @@ //! Alt from centre), outside the corners rotates, inside moves, and Cmd-dragging a side handle //! shears along that side. A scale snaps as the Selection tool's does. The Perspective Distort and Free Distort modes (tool option `mode`, or //! Cmd / Cmd+Alt+Shift while dragging a corner like classic Illustrator) move the corners of the -//! box and preview `object.distort`. After a rotation the box stays turned with the selection, as -//! the Selection tool's does: its handles scale, shear and distort along the selection's own sides. +//! box and preview `object.distort`; in Free Distort, Shift or the Constrain option keeps a dragged +//! corner on the diagonal through the opposite corner. After a rotation the box stays turned with +//! the selection, as the Selection tool's does: its handles scale, shear and distort along the selection's own sides. use serde_json::{Value, json}; use vectorcraft_doc::OrientedBox; @@ -123,6 +124,18 @@ fn corner_index(h: Handle) -> Option { } } +/// The part of drag `d` that lies along the diagonal from corner `h` of `r` to the opposite +/// corner. A Free Distort corner dragged with Shift or Constrain moves only along that line, so its +/// offset from the opposite corner keeps the box's width-to-height ratio. A box with no width and no height gives no movement. +pub fn along_diagonal(r: Rect, h: Handle, d: Vec2) -> Vec2 { + let u = h.pos(r) - h.opposite().pos(r); + let len2 = u.hypot2(); + if len2 <= 1e-18 || !len2.is_finite() { + return Vec2::ZERO; + } + u * (d.dot(u) / len2) +} + /// The distorted quad for dragging handle `h` of `r` by `d`. pub fn distort_quad(r: Rect, h: Handle, d: Vec2, mode: DistortMode) -> [Point; 4] { let mut q = rect_corners(r); @@ -194,9 +207,13 @@ impl FreeTransformTool { self.guides.clear(); let xf = match d.op { Op::Corners(h, mode) => { + // Shift or Constrain keeps a Free Distort corner on its diagonal. + let constrained = shift && mode == DistortMode::Distort && h.is_corner(); + let local = if constrained { along_diagonal(bx.rect, h, local) } else { local }; let q = distort_quad(bx.rect, h, local, mode).map(|c| bx.to_doc() * c); self.quad = Some(q); - self.measure = cx.measurement_labels.then(|| (p, cx.offset_label(delta.x, delta.y))); + let moved = if constrained { bx.to_doc() * (h.pos(bx.rect) + local) - bx.to_doc() * h.pos(bx.rect) } else { delta }; + self.measure = cx.measurement_labels.then(|| (p, cx.offset_label(moved.x, moved.y))); let corners: Vec = q.iter().map(|c| json!([c.x, c.y])).collect(); let r = bx.rect; let mut params = json!({ "corners": corners, "from": [r.x0, r.y0, r.x1, r.y1] }); @@ -571,6 +588,123 @@ mod tests { assert_eq!(q[2], Point::new(10.0, 10.0)); } + /// The corners an `object.distort` preview sends. + fn sent_corners(a: &[Action]) -> Vec { + let Some(Action::Preview(c, v)) = a.last() else { panic!("{a:?}") }; + assert_eq!(c, "object.distort"); + v["corners"].as_array().unwrap().iter().map(|p| Point::new(p[0].as_f64().unwrap(), p[1].as_f64().unwrap())).collect() + } + + fn assert_corners(got: &[Point], want: [(f64, f64); 4]) { + for (g, w) in got.iter().zip(want) { + assert!(g.distance(Point::new(w.0, w.1)) < 1e-9, "{got:?} != {want:?}"); + } + } + + /// A 200 × 100 rectangle at (100, 100)–(300, 200), selected. + fn wide_rect() -> (vectorcraft_doc::Document, Selection, vectorcraft_doc::NodeId) { + let (mut d, id) = doc_with_rect(); + let wide = Affine::translate((100.0, 100.0)) * Affine::scale_non_uniform(2.0, 1.0) * Affine::translate((-100.0, -100.0)); + d.node_mut(id).unwrap().transform(wide, false); + let mut s = Selection::default(); + s.add(id); + (d, s, id) + } + + /// In Free Distort, Shift or the Constrain option keeps the dragged corner on the diagonal + /// through the opposite corner; the other three corners stay put. + #[test] + fn free_distort_corner_keeps_to_its_diagonal_with_shift_or_constrain() { + let (d, s, _) = wide_rect(); + let p = paint(); + let cx = cx(&d, &s, &p); + let shift = Mods { shift: true, ..Default::default() }; + // The bottom-right corner dragged by (40, 60): along the diagonal (200, 100) that is + // (40·200 + 60·100) / (200² + 100²) = 0.28 of it, (56, 28). + let fixed = [(100.0, 100.0), (300.0, 100.0), (356.0, 228.0), (100.0, 200.0)]; + let drag = |t: &mut FreeTransformTool, m: Mods| { + t.pointer(&cx, &ev(PointerKind::Down, 300.0, 200.0).with_mods(m)); + let a = t.pointer(&cx, &ev(PointerKind::Drag, 340.0, 260.0).with_mods(m)); + t.pointer(&cx, &ev(PointerKind::Up, 340.0, 260.0).with_mods(m)); + sent_corners(&a) + }; + let mut t = FreeTransformTool::default(); + t.set_option("mode", &json!("distort")); + assert_corners(&drag(&mut t, Mods::default()), [(100.0, 100.0), (300.0, 100.0), (340.0, 260.0), (100.0, 200.0)]); + assert_corners(&drag(&mut t, shift), fixed); + t.set_option("constrain", &json!(true)); + assert_corners(&drag(&mut t, Mods::default()), fixed); + // Cmd+Shift on a corner in the Free Transform mode is Free Distort, constrained too. + let mut t = FreeTransformTool::default(); + assert_corners(&drag(&mut t, Mods { cmd: true, shift: true, ..Default::default() }), fixed); + // Cmd+Alt+Shift stays Perspective Distort, with Constrain on as well. + t.set_option("constrain", &json!(true)); + let perspective = Mods { cmd: true, alt: true, shift: true, ..Default::default() }; + assert_corners(&drag(&mut t, perspective), [(100.0, 100.0), (300.0, 40.0), (300.0, 260.0), (100.0, 200.0)]); + // The measurement label shows how far the corner moved. + let cx = ToolContext { measurement_labels: true, ..cx }; + let mut t = FreeTransformTool::default(); + t.set_option("mode", &json!("distort")); + t.pointer(&cx, &ev(PointerKind::Down, 300.0, 200.0).with_mods(shift)); + t.pointer(&cx, &ev(PointerKind::Drag, 340.0, 260.0).with_mods(shift)); + let want = cx.offset_label(56.0, 28.0); + assert!(t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text == &want)), "{want}"); + } + + /// Shift pressed in the middle of a Free Distort corner drag constrains it from then on, in the + /// same undo step; letting go frees the corner again. + #[test] + fn shift_pressed_during_a_free_distort_drag_constrains_it() { + let (d, s, _) = wide_rect(); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = FreeTransformTool::default(); + t.set_option("mode", &json!("distort")); + t.pointer(&cx, &ev(PointerKind::Down, 300.0, 200.0)); + let a = t.pointer(&cx, &ev(PointerKind::Drag, 310.0, 210.0)); + assert_eq!(a[0], Action::Begin("Distort".into())); + let a = t.pointer(&cx, &ev(PointerKind::Drag, 340.0, 260.0).with_mods(Mods { shift: true, ..Default::default() })); + assert_eq!(a.len(), 1, "no new undo step: {a:?}"); + assert_corners(&sent_corners(&a), [(100.0, 100.0), (300.0, 100.0), (356.0, 228.0), (100.0, 200.0)]); + let a = t.pointer(&cx, &ev(PointerKind::Drag, 340.0, 260.0)); + assert_corners(&sent_corners(&a), [(100.0, 100.0), (300.0, 100.0), (340.0, 260.0), (100.0, 200.0)]); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 340.0, 260.0)), vec![Action::Commit]); + } + + /// A turned box is constrained along its own diagonal. + #[test] + fn a_turned_box_is_constrained_along_its_own_diagonal() { + let (mut d, s, id) = wide_rect(); + let c = Vec2::new(200.0, 150.0); + let turn = Affine::translate(c) * Affine::rotate(-30f64.to_radians()) * Affine::translate(-c); + d.node_mut(id).unwrap().transform(turn, false); + let p = paint(); + let cx = cx(&d, &s, &p); + let bx = selection_box(&cx).unwrap(); + assert!((bx.rect.width() - 200.0).abs() < 1e-9 && (bx.rect.height() - 100.0).abs() < 1e-9, "{bx:?}"); + let corner = Handle::BottomRight.pos(bx.rect); + let (from, to) = (bx.to_doc() * corner, bx.to_doc() * (corner + Vec2::new(40.0, 60.0))); + let mut t = FreeTransformTool::default(); + t.set_option("mode", &json!("distort")); + t.set_option("constrain", &json!(true)); + t.pointer(&cx, &ev(PointerKind::Down, from.x, from.y)); + let got = sent_corners(&t.pointer(&cx, &ev(PointerKind::Drag, to.x, to.y))); + let want = bx.to_doc() * (corner + Vec2::new(56.0, 28.0)); + assert!(got[2].distance(want) < 1e-9, "{got:?} {want:?}"); + for (i, k) in [(0, Handle::TopLeft), (1, Handle::TopRight), (3, Handle::BottomLeft)] { + assert!(got[i].distance(bx.to_doc() * k.pos(bx.rect)) < 1e-9, "{got:?}"); + } + } + + /// A box with no size has no diagonal to move along; a line keeps to its own length. + #[test] + fn along_diagonal_of_a_degenerate_box() { + assert_eq!(along_diagonal(Rect::new(5.0, 5.0, 5.0, 5.0), Handle::BottomRight, Vec2::new(3.0, 4.0)), Vec2::ZERO); + assert_eq!(along_diagonal(Rect::new(5.0, 0.0, 5.0, 10.0), Handle::BottomRight, Vec2::new(3.0, 4.0)), Vec2::new(0.0, 4.0)); + let d = along_diagonal(Rect::new(0.0, 0.0, 10.0, 10.0), Handle::TopLeft, Vec2::new(1.0, 0.0)); + assert!(d.x.is_finite() && (d - Vec2::new(0.5, 0.5)).hypot() < 1e-12, "{d:?}"); + } + #[test] fn distort_drag_shows_move_measurement_labels() { let (d, id) = doc_with_rect(); diff --git a/crates/trace/src/group.rs b/crates/trace/src/group.rs index b51ae57907..a0e3b85020 100644 --- a/crates/trace/src/group.rs +++ b/crates/trace/src/group.rs @@ -420,13 +420,13 @@ mod tests { #[test] fn a_dense_trace_is_grouped_with_a_few_box_tests_per_path() { - let img = noise(120, 120); + let img = noise(150, 150); for (method, stacked) in [(crate::Method::Abutting, false), (crate::Method::Overlapping, true)] { let paths = traced(&img, method); let n = paths.len(); let counted = |by_pairs: bool| { BOX_TESTS.with(|n| n.set(0)); - let found = if by_pairs { parents_by_pairs(&paths, 120, 120, stacked) } else { parents(&paths, 120, 120, stacked) }; + let found = if by_pairs { parents_by_pairs(&paths, 150, 150, stacked) } else { parents(&paths, 150, 150, stacked) }; (found, BOX_TESTS.with(std::cell::Cell::get)) }; let (found, tests) = counted(false); diff --git a/crates/trace/src/quantize.rs b/crates/trace/src/quantize.rs index 9452671def..f5a2d9fa47 100644 --- a/crates/trace/src/quantize.rs +++ b/crates/trace/src/quantize.rs @@ -8,7 +8,7 @@ mod denoise; mod palette; mod rare; -use cut_edge::{choosing_pixels, compact, settled}; +use cut_edge::{choosing_pixels, compact, settled, settled_wide, settles_wide}; pub(crate) use cut_edge::{continuous_tone, settle_cut_edges}; pub use denoise::denoise; pub(crate) use denoise::denoise_keeping; @@ -91,7 +91,8 @@ pub(crate) fn quantize_keeping(img: &Raster, params: &TraceParams) -> (Quantized let g = l.round().clamp(0.0, 255.0) as u8; [g, g, g] }); - (settled(merge_mixed(compact(labels, palette.collect()), img.width as usize, img.height as usize, &[]), img, &own), vec![]) + let q = merge_mixed(compact(labels, palette.collect()), img.width as usize, img.height as usize, &[]); + (if settles_wide(params) { settled_wide(q, img, &own, true) } else { settled(q, img, &own) }, vec![]) } // Logo mode traces without quantising; asked directly, it quantises like Color. Mode::Color | Mode::Logo => { @@ -170,7 +171,7 @@ pub(crate) fn quantize_keeping(img: &Raster, params: &TraceParams) -> (Quantized if library { q } else { merge_mixed(q, img.width as usize, img.height as usize, &rare) } }; let q = reduce(params.colors); - let q = settled(q, img, &own); + let q = if settles_wide(params) { settled_wide(q, img, &own, false) } else { settled(q, img, &own) }; rare.retain(|c| q.palette.contains(c)); (q, rare) } diff --git a/crates/trace/src/quantize/cut_edge.rs b/crates/trace/src/quantize/cut_edge.rs index 22e5c02af2..99b3c42845 100644 --- a/crates/trace/src/quantize/cut_edge.rs +++ b/crates/trace/src/quantize/cut_edge.rs @@ -1,5 +1,5 @@ use super::palette::{Bin, HistKey, Used, centers, median_cut, nearest_lab}; -use super::{Quantized, Raster, TRANSPARENT, luma, oklab}; +use super::{Mode, Palette, Quantized, Raster, TRANSPARENT, TraceParams, luma, oklab}; /// `q` with its blend pixels settled, and the colours that leaves unused dropped. /// @@ -65,6 +65,214 @@ pub(super) fn settled(mut q: Quantized, img: &Raster, own: &[bool]) -> Quantized if changed { compact(q.labels, q.palette) } else { q } } +/// The most colors (Color) or grays (Grayscale) a palette may ask for to have its blend pixels +/// settled by [`settled_wide`] rather than [`settled`]. The limited-color presets ask for 3 to 16 +/// colors. +const LIMITED_COLORS: u32 = 16; + +/// Whether a trace with `params` settles its blend pixels with [`settled_wide`]: Grayscale, and +/// Color with a Limited palette, of at most [`LIMITED_COLORS`] colors. +pub(super) fn settles_wide(params: &TraceParams) -> bool { + match params.mode { + Mode::Grayscale => params.colors <= LIMITED_COLORS, + Mode::Color | Mode::Logo => params.palette == Palette::Limited && params.colors <= LIMITED_COLORS, + Mode::BlackAndWhite => false, + } +} + +/// How far (px, across, along or diagonally) [`settled_wide`] looks for the picture's own pixels +/// around a blend pixel: blur spreads an edge over several pixels, and its two sides can lie this +/// far apart. +const BLEND_REACH: usize = 8; + +/// How far (px, across, along or diagonally) an own pixel of its color keeps a blend pixel's color +/// in [`settled_wide`]: where three colors meet, the blend is of its color too. +const OWN_NEAR: usize = 4; + +/// How many of the colors within reach of a blend pixel, nearest to its color first, +/// [`settled_wide`] pairs up. +const NEAR_COLORS: usize = 8; + +/// How many columns at a time [`settled_wide`] keeps the colors within reach for, so that its +/// memory does not grow with the width of the picture. +const BLEND_STRIP: usize = 7; + +/// How far apart (squared levels) the distances of a blend pixel off the lines between two pairs +/// of colors may be for [`settled_wide`] to count them as equal: rounding leaves a gray that lies +/// between two grays about 1e-28 off the line between them. +const SAME_FIT: f64 = 1e-6; + +/// How much nearer (squared) to the line between a pair of colors than to its own color a blend +/// pixel must lie for [`settled_wide`] to settle it: half as far, as [`settled`] asks. +const BETTER_FIT: f64 = 0.25; + +/// How far off the line between a pair of colors (as a share of their distance apart) a blend pixel +/// that lies between the two may be for [`settled_wide`] to settle it whatever its own color. +const ON_THE_LINE: f64 = 0.15; + +/// [`settled`] for a limited palette (see [`settles_wide`]), which also settles the in-between +/// tones of an edge blurred over several pixels: without it they trace as a ring of a third color +/// around the edge. +/// +/// A blend pixel (see [`own_colours`]) whose color is none of those of the picture's own pixels +/// within [`OWN_NEAR`] pixels of it takes the side it is nearer to of the pair of the colors of own +/// pixels within [`BLEND_REACH`] pixels that it is best a blend of (of two pairs that explain it +/// equally well, the closer one), when that explains it twice as well as its own color does, or +/// when it lies between the two and off the line between them by less than [`ON_THE_LINE`] of +/// their distance apart. Only the [`NEAR_COLORS`] colors nearest to its color are paired. It keeps +/// its own color when that color is one of the pair, or when one color is all there is around it. +/// With `gray` (Grayscale), a pixel's color is its gray (see [`luma`]). +pub(super) fn settled_wide(mut q: Quantized, img: &Raster, own: &[bool], gray: bool) -> Quantized { + let (w, h) = (img.width as usize, img.height as usize); + if q.labels.len() != w * h || own.len() != w * h { + return q; + } + let before = q.labels.clone(); + let colors: Vec<[f64; 3]> = q.palette.iter().map(|c| c.map(f64::from)).collect(); + let dist2 = |a: [f64; 3], b: [f64; 3]| (0..3).map(|k| (a[k] - b[k]).powi(2)).sum::(); + // The colors of the own pixels within reach of each pixel, as bits (one word per 64 palette + // colors), a strip of columns at a time: along its row for the rows within reach (a window + // sliding along each row, kept for the last 2 × reach + 1 rows), then across those rows. + let words = q.palette.len().div_ceil(64).max(1); + let span = 2 * BLEND_REACH + 1; + let strip = BLEND_STRIP.min(w); + let mut rows = vec![0u64; span * strip * words]; + let mut counts = vec![0u32; q.palette.len()]; + let mut window = vec![0u64; words]; + let mut bits = vec![0u64; words]; + // The bits of row `y` for the columns `x0..x1` (at most `strip` of them). + let mut row_colors = |y: usize, x0: usize, x1: usize, rows: &mut [u64]| { + let Some(out) = rows.get_mut((y % span) * strip * words..(y % span + 1) * strip * words) else { return }; + counts.fill(0); + window.fill(0); + // The own pixel at `x` enters the window (`add`) or leaves it. + let step = |counts: &mut [u32], window: &mut [u64], x: usize, add: bool| { + let i = y * w + x; + let l = before[i] as usize; + if !own[i] || l >= counts.len() { + return; + } + if add { + counts[l] += 1; + window[l / 64] |= 1 << (l % 64); + } else { + counts[l] -= 1; + if counts[l] == 0 { + window[l / 64] &= !(1 << (l % 64)); + } + } + }; + let first = x0.saturating_sub(BLEND_REACH); + for x in first..(x0 + BLEND_REACH).min(w) { + step(&mut counts, &mut window, x, true); + } + for x in x0..x1 { + if x + BLEND_REACH < w { + step(&mut counts, &mut window, x + BLEND_REACH, true); + } + if let Some(gone) = x.checked_sub(BLEND_REACH + 1).filter(|&g| g >= first) { + step(&mut counts, &mut window, gone, false); + } + if let Some(o) = out.get_mut((x - x0) * words..(x - x0 + 1) * words) { + o.copy_from_slice(&window); + } + } + }; + let mut changed = false; + let mut near: Vec = Vec::new(); + let mut by_distance: Vec<(f64, u16)> = Vec::new(); + let pixel = |p: &[u8]| if gray { [f64::from(luma([p[0], p[1], p[2], p[3]])); 3] } else { [f64::from(p[0]), f64::from(p[1]), f64::from(p[2])] }; + for (x0, y) in (0..w).step_by(strip.max(1)).flat_map(|x0| (0..h).map(move |y| (x0, y))) { + let x1 = (x0 + strip).min(w); + if y == 0 { + for yy in 0..BLEND_REACH.min(h) { + row_colors(yy, x0, x1, &mut rows); + } + } + if y + BLEND_REACH < h { + row_colors(y + BLEND_REACH, x0, x1, &mut rows); + } + 'pixels: for x in x0..x1 { + let i = y * w + x; + let mine_l = before[i]; + if own[i] || mine_l == TRANSPARENT { + continue; + } + // Its color is the picture's own here. + for yy in y.saturating_sub(OWN_NEAR)..=(y + OWN_NEAR).min(h - 1) { + for xx in x.saturating_sub(OWN_NEAR)..=(x + OWN_NEAR).min(w - 1) { + if own[yy * w + xx] && before[yy * w + xx] == mine_l { + continue 'pixels; + } + } + } + bits.fill(0); + for yy in y.saturating_sub(BLEND_REACH)..=(y + BLEND_REACH).min(h - 1) { + let at = (yy % span) * strip * words + (x - x0) * words; + for (b, r) in bits.iter_mut().zip(rows.get(at..at + words).unwrap_or_default()) { + *b |= r; + } + } + near.clear(); + for (k, &b) in bits.iter().enumerate() { + let mut b = b; + while b != 0 { + let l = (k * 64 + b.trailing_zeros() as usize) as u16; + b &= b - 1; + near.push(l); + } + } + let (Some(p), Some(&mine)) = (img.rgba.get(i * 4..i * 4 + 4).map(pixel), colors.get(mine_l as usize)) else { + continue; + }; + if near.iter().filter(|&&l| l != mine_l).count() < 2 { + continue; + } + // In busy art many colors lie within reach: only the ones nearest to its color are paired. + // Each distance is worked out once, and only the nearest few are sorted (nearest first, + // then by index). + if near.len() > NEAR_COLORS { + by_distance.clear(); + by_distance.extend(near.iter().map(|&l| (colors.get(l as usize).map_or(f64::INFINITY, |&c| dist2(p, c)), l))); + let order = |a: &(f64, u16), b: &(f64, u16)| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1)); + by_distance.select_nth_unstable_by(NEAR_COLORS, order); + by_distance.truncate(NEAR_COLORS); + by_distance.sort_unstable_by(order); + near.clear(); + near.extend(by_distance.iter().map(|&(_, l)| l)); + } + // The pair it is best a blend of, by the square of how far it lies off the line between them, + // and of two pairs it lies equally far off, the closer pair (in grays it lies on the line + // between every pair of grays darker and lighter than it). + let mut best: Option<(f64, [u16; 2], u16, f64, bool)> = None; + for (n, &a) in near.iter().enumerate() { + let Some(&ca) = colors.get(a as usize) else { continue }; + let pa = [p[0] - ca[0], p[1] - ca[1], p[2] - ca[2]]; + for &b in &near[n + 1..] { + let Some(&cb) = colors.get(b as usize) else { continue }; + let d = [cb[0] - ca[0], cb[1] - ca[1], cb[2] - ca[2]]; + let len2 = d[0] * d[0] + d[1] * d[1] + d[2] * d[2]; + let along = if len2 > 0.0 { (pa[0] * d[0] + pa[1] * d[1] + pa[2] * d[2]) / len2 } else { 0.0 }; + let t = along.clamp(0.0, 1.0); + let off2 = (pa[0] - t * d[0]).powi(2) + (pa[1] - t * d[1]).powi(2) + (pa[2] - t * d[2]).powi(2); + if best.is_none_or(|x| off2 < x.0 - SAME_FIT || (off2 <= x.0 + SAME_FIT && len2 < x.3)) { + best = Some((off2, [a, b], if t < 0.5 { a } else { b }, len2, along > 0.0 && along < 1.0)); + } + } + } + // A pixel already of one of the two colors it is best a blend of stays as it is. + if let Some((off2, pair, to, apart2, between)) = best + && !pair.contains(&mine_l) + && (off2 < BETTER_FIT * dist2(p, mine) || (between && off2 < ON_THE_LINE * ON_THE_LINE * apart2)) + { + q.labels[i] = to; + changed = true; + } + } + } + if changed { compact(q.labels, q.palette) } else { q } +} + /// Whether `img` is continuous tone (a photo, a gradient) rather than flat art, however noisy /// or unevenly lit (a scan): whether eight colours leave much of it unsaid. Flat art is a few /// colours and what noise and lighting make of them, and eight colours come within a few levels @@ -443,3 +651,66 @@ fn edge_blend_of(own: [f64; 3], beside: [u8; 3], alpha: u8) -> bool { let off2: f64 = (0..3).map(|c| (own[c] - from[c] - t * d[c]).powi(2)).sum(); off2 <= EDGE_BLEND * EDGE_BLEND } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_gray_blend_takes_the_closer_of_two_pairs_it_lies_between_despite_rounding() { + // Gray 105 in the middle, with own pixels of gray 50 to its left, 200 to its right and black + // along the top row, and a palette gray of 120 of its own. It lies between 0 and 200 exactly + // and between 50 and 200 to within rounding: it takes 50, the nearer of the closer pair. + let gray = |x: u32, y: u32| match (x, y) { + (8, 8) => 105, + (_, 0) => 0, + (0..=8, _) => 50, + _ => 200, + }; + let img = Raster::from_fn(17, 17, |x, y| { + let v = gray(x, y); + [v, v, v, 255] + }); + let palette = vec![[0, 0, 0], [50, 50, 50], [200, 200, 200], [120, 120, 120]]; + let labels: Vec = (0..17 * 17) + .map(|i| match gray(i % 17, i / 17) { + 0 => 0, + 50 => 1, + 200 => 2, + _ => 3, + }) + .collect(); + let own: Vec = labels.iter().map(|&l| l != 3).collect(); + let q = settled_wide(Quantized { labels, palette }, &img, &own, true); + let middle = q.labels[8 * 17 + 8]; + assert_eq!(q.palette[usize::from(middle)], [50, 50, 50]); + } + + #[test] + fn a_blend_pixel_beyond_the_end_of_a_pair_keeps_its_nearest_color() { + // A column of [92, 92, 92] between own pixels of [100, 100, 100] to its left and + // [200, 200, 200] to its right, with a palette color of [90, 90, 90]: it lies beyond the + // darker end of the pair, not between the two, and its own color is the nearer, so it + // keeps it. + let value = |x: u32| match x { + 0..=7 => 100, + 8 => 92, + _ => 200, + }; + let img = Raster::from_fn(17, 17, |x, _| { + let v = value(x); + [v, v, v, 255] + }); + let palette = vec![[100, 100, 100], [200, 200, 200], [90, 90, 90]]; + let labels: Vec = (0..17 * 17u32) + .map(|i| match value(i % 17) { + 100 => 0, + 200 => 1, + _ => 2, + }) + .collect(); + let own: Vec = labels.iter().map(|&l| l != 2).collect(); + let q = settled_wide(Quantized { labels, palette }, &img, &own, false); + assert_eq!(q.palette[usize::from(q.labels[8 * 17 + 8])], [90, 90, 90]); + } +} diff --git a/crates/trace/src/tests.rs b/crates/trace/src/tests.rs index d0a589b916..b244c3b79b 100644 --- a/crates/trace/src/tests.rs +++ b/crates/trace/src/tests.rs @@ -1330,6 +1330,115 @@ fn a_blend_of_two_colours_is_no_sliver_of_a_third() { assert!(b.y0 > 89.0 && b.y1 < 110.0, "{b:?}"); } +/// A light disc of radius 32 at (55, 60) on a dark ground, its edge blurred into a ramp 10 px +/// wide, and elsewhere a patch of the tone halfway between the two, so that the palette holds +/// that tone. Returns the picture and whether a color is that tone. +fn blurred_disc_and_halfway_patch() -> (Raster, impl Fn([u8; 3]) -> bool) { + const DARK: [f64; 3] = [20.0, 25.0, 35.0]; + const LIGHT: [f64; 3] = [225.0, 195.0, 160.0]; + let mid = [0, 1, 2].map(|k| (DARK[k] + LIGHT[k]) / 2.0); + let img = Raster::from_fn(160, 120, |x, y| { + let (px, py) = (f64::from(x) + 0.5, f64::from(y) + 0.5); + let c = if (112.0..152.0).contains(&px) && (40.0..80.0).contains(&py) { + mid + } else { + let t = ((32.0 - Point::new(px, py).distance(Point::new(55.0, 60.0))) / 10.0 + 0.5).clamp(0.0, 1.0); + [0, 1, 2].map(|k| DARK[k] + t * (LIGHT[k] - DARK[k])) + }; + let c = |k: usize| c[k].round() as u8; + [c(0), c(1), c(2), 255] + }); + (img, move |c: [u8; 3]| (0..3).all(|k| (f64::from(c[k]) - mid[k]).abs() <= 12.0)) +} + +#[test] +fn a_blurred_edge_is_no_ring_of_a_tone_between_its_sides() { + let (img, is_mid) = blurred_disc_and_halfway_patch(); + let res = trace(&img, &sixteen_colors()); + let mids: Vec<&TracedPath> = res.paths.iter().filter(|p| is_mid(p.color)).collect(); + assert_eq!(mids.len(), 1, "the patch, and no ring around the disc: {:?}", res.paths.iter().map(|p| p.color).collect::>()); + let b = mids[0].path.bounds().unwrap(); + assert!(b.x0 > 110.0 && b.y0 > 38.0 && b.y1 < 82.0, "{b:?}"); + // The disc's edge lies halfway along the ramp. + let light = res.paths.iter().find(|p| p.color[0] > 180).unwrap(); + let off = along(&light.path).iter().map(|p| (p.distance(Point::new(55.0, 60.0)) - 32.0).abs()).fold(0.0, f64::max); + assert!(off < 1.0, "{off} px off the middle of the ramp"); +} + +#[test] +fn grayscale_settles_a_tinted_blurred_edge_by_its_lightness() { + // The same blurred disc and halfway patch in grays, and tinted green at the same lightness + // (every pixel moved by the same color, which keeps its luma): Grayscale reads lightness + // alone, so both make the same grays in the same places. + let lightness = |x: u32, y: u32| { + let (px, py) = (f64::from(x) + 0.5, f64::from(y) + 0.5); + if (112.0..152.0).contains(&px) && (40.0..80.0).contains(&py) { + 130 + } else { + let t = ((32.0 - Point::new(px, py).distance(Point::new(55.0, 60.0))) / 10.0 + 0.5).clamp(0.0, 1.0); + (40.0 + 180.0 * t).round() as u8 + } + }; + let gray = Raster::from_fn(160, 120, |x, y| { + let v = lightness(x, y); + [v, v, v, 255] + }); + let tinted = Raster::from_fn(160, 120, |x, y| { + let v = lightness(x, y); + [v - 40, v + 28, v - 40, 255] + }); + let lumas = |img: &Raster| img.rgba.as_chunks::<4>().0.iter().map(|&p| crate::quantize::luma(p)).collect::>(); + assert_eq!(lumas(&tinted), lumas(&gray)); + let params = TraceParams { mode: Mode::Grayscale, colors: 8, ..TraceParams::default() }; + assert_eq!(quantize(&tinted, ¶ms), quantize(&gray, ¶ms)); +} + +#[test] +fn grayscale_settles_a_blurred_edge_between_its_own_two_grays() { + // A dark gray and a light gray meet in a ramp 12 px wide, and a black band runs across the top. + // In grays every blend lies between black and the light gray as well as between the two grays + // (to within rounding): the ramp's pixels just below the band take the nearer of the two grays, + // the grays on either side of them. + for (dark, light) in [(40u8, 200u8), (50, 200), (30, 170), (60, 230), (45, 215)] { + let img = Raster::from_fn(160, 60, |x, y| { + let v = if y < 8 { + 0 + } else { + let t = ((f64::from(x) + 0.5 - 74.0) / 12.0).clamp(0.0, 1.0); + (f64::from(dark) + f64::from(light - dark) * t).round() as u8 + }; + [v, v, v, 255] + }); + let params = TraceParams { mode: Mode::Grayscale, colors: 8, ..TraceParams::default() }; + let q = quantize(&img, ¶ms); + let middle = u16::from(dark) + u16::from(light); + for y in 10..16 { + for x in 74..86 { + let v = img.rgba[(y * 160 + x) * 4]; + let g = q.palette[usize::from(q.labels[y * 160 + x])][0]; + assert_eq!(2 * u16::from(g) < middle, 2 * u16::from(v) < middle, "{dark} to {light}, ({x}, {y}): {v} took gray {g}"); + assert!(g >= dark, "{dark} to {light}, ({x}, {y}): {v} took gray {g}"); + } + } + } +} + +#[test] +fn the_photo_presets_keep_the_tones_of_a_blurred_edge() { + // The photo presets ask for more colors than the limited-color presets and keep the middle of + // the ramp in the halfway tone: only a blend pixel with the colors on both sides within 2 px of + // it takes a side. + let (img, is_mid) = blurred_disc_and_halfway_patch(); + for name in ["High Fidelity Photo", "Low Fidelity Photo"] { + let q = quantize(&img, &preset(name).unwrap()); + let middle = (0..160 * 120) + .filter(|&i| (Point::new((i % 160) as f64 + 0.5, (i / 160) as f64 + 0.5).distance(Point::new(55.0, 60.0)) - 32.0).abs() < 1.0) + .filter(|&i| q.palette.get(usize::from(q.labels[i])).is_some_and(|&c| is_mid(c))) + .count(); + assert!(middle > 100, "{name}: {middle} pixels of the halfway tone in the middle of the ramp"); + } +} + #[test] fn hairlines_keep_their_colour_in_color_mode() { // Black lines one pixel wide on white: every black pixel is on an edge, none is a blend. diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index d75eae537f..d8b415f922 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -67,8 +67,10 @@ pub(crate) use panes::{consolidate, pane, tile, tiled_area}; use raster::{changed_pixels, pixel_region, upload}; pub(crate) use raster::{color_image, color_image_owned, render_job}; pub use selection_marks::SelectionMarks; +#[cfg(test)] +pub(crate) use task_bar::chip_paints; use task_bar::task_bar; -pub(crate) use task_bar::{has_colors, task_bar_rect}; +pub(crate) use task_bar::{has_colors, task_bar_rect, task_bar_shows_fonts, task_bar_shows_type}; #[cfg(test)] use tool_overlays::{DIAL_RADIUS, HiddenMarks}; pub use tool_overlays::{HiddenChars, SpellingMarks}; diff --git a/crates/ui-egui/src/canvas/cursor.rs b/crates/ui-egui/src/canvas/cursor.rs index 8b368fa496..ca017bef3e 100644 --- a/crates/ui-egui/src/canvas/cursor.rs +++ b/crates/ui-egui/src/canvas/cursor.rs @@ -83,7 +83,10 @@ pub(super) fn cursor_icon(c: Cursor) -> egui::CursorIcon { | Cursor::CornerRadius | Cursor::PathBracket | Cursor::TypeWidget - | Cursor::LoadedText => C::Default, + | Cursor::LoadedText + | Cursor::LivePaintSelectFace + | Cursor::LivePaintSelectEdge + | Cursor::LivePaintSelectOutside => C::Default, Cursor::SelectionCopy => C::Copy, Cursor::Move => C::Move, Cursor::Crosshair => C::Crosshair, diff --git a/crates/ui-egui/src/canvas/task_bar.rs b/crates/ui-egui/src/canvas/task_bar.rs index 5372cc083d..e908640c25 100644 --- a/crates/ui-egui/src/canvas/task_bar.rs +++ b/crates/ui-egui/src/canvas/task_bar.rs @@ -13,6 +13,12 @@ pub(crate) fn task_bar_rect(ctx: &egui::Context) -> Option { ctx.memory(|m| m.areas().is_visible(&egui::LayerId::new(egui::Order::Middle, id)).then(|| m.area_rect(id)).flatten()) } +/// Whether the Contextual Task Bar, where it was last drawn, held the font controls: on a canvas +/// too narrow for them it leaves them out. +pub(crate) fn task_bar_shows_fonts(ctx: &egui::Context) -> bool { + task_bar_rect(ctx).is_some() && ctx.data(|d| d.get_temp::(task_bar_id().with("fonts")).unwrap_or(false)) +} + /// Whether the objects `ids` (or anything inside them) are painted with a colour: a solid colour, /// a gradient's stops or a mesh's points, which Recolor Artwork can change. pub(crate) fn has_colors(doc: &vectorcraft_doc::Document, ids: &[vectorcraft_doc::NodeId]) -> bool { @@ -30,21 +36,59 @@ fn picked_artboards_bounds(app: &VectorcraftApp) -> Option { picked.iter().filter_map(|i| st.doc.artboards.get(*i)).map(|a| a.rect).reduce(|a, b| a.union(b)) } +/// The Type tools whose Contextual Task Bar shows the text formatting controls. The Touch Type +/// tool has no bar: its own handles take the place of one. +const TYPE_TOOLS: [&str; 6] = ["type", "areaType", "typeOnPath", "verticalType", "verticalAreaType", "verticalTypeOnPath"]; + +/// Whether every selected object is a type object, with no anchors picked out. +fn only_type_selected(app: &VectorcraftApp) -> bool { + app.session.active().is_some_and(|st| { + !st.selection.is_empty() + && st.selection.anchors.is_empty() + && st.selection.objects.iter().all(|id| st.doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Text(_)))) + }) +} + +/// Whether a selection tool is in use with something selected. +fn selection_tool_with_selection(app: &VectorcraftApp) -> bool { + matches!(app.session.tool_id(), "selection" | "directSelection" | "groupSelection") + && app.session.active().is_some_and(|st| !st.selection.is_empty()) +} + +/// Whether a Type tool edits type, or has type selected: its bar then shows only the text +/// formatting controls. +fn type_tool_on_type(app: &VectorcraftApp) -> bool { + TYPE_TOOLS.contains(&app.session.tool_id()) && (crate::panels::character::text_editing(app).is_some() || only_type_selected(app)) +} + +/// Whether the Contextual Task Bar shows the font family, font style and Font Size controls: a +/// Type tool edits or has selected type, or a selection tool has only type selected. +pub(crate) fn task_bar_shows_type(app: &VectorcraftApp) -> bool { + type_tool_on_type(app) || (selection_tool_with_selection(app) && only_type_selected(app)) +} + /// The Contextual Task Bar: a floating pill under the selection with the most likely next actions. /// With the Artboard tool it sits under the selected artboards and offers Resize (Artboard /// Options), Duplicate, Rearrange All (with two or more artboards) and Export (Export for Screens). /// A basic shape selected with the Selection tool shows a Shape Properties button in place of Lock. +/// Selected type also shows the font family, font style and Font Size controls before its Fill. +/// While a Type tool edits type, or has type selected, the bar shows only those controls and the +/// Fill. The font controls take a second row when one row would be wider than the canvas, and +/// narrow there to fit it. /// Its handle drags it anywhere on the canvas; unpinned it keeps that offset as it follows the /// selection, pinned it stays put ([`crate::state::TaskBarPlace`]). pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { let t = Tokens::get(ui.ctx()); let on_artboards = app.session.tool_id() == "artboard"; - if !on_artboards - && (app.session.active().is_none_or(|st| st.selection.is_empty()) - || !matches!(app.session.tool_id(), "selection" | "directSelection" | "groupSelection")) - { + // Text added with a Type tool shows its formatting controls, as the help page describes + // (). + let typing = type_tool_on_type(app); + if !(on_artboards || typing || selection_tool_with_selection(app)) { return; } + // Selected type has the font controls too, as the help page describes + // (). + let fonts = task_bar_shows_type(app); let Some(b) = (if on_artboards { picked_artboards_bounds(app) } else { app.selection_bounds() }) else { return }; let Some(st) = app.session.active() else { return }; let n = st.selection.len(); @@ -93,7 +137,9 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { items.push((tl!("Rearrange All"), "dc-rearrange", TASK_BAR_REARRANGE_ARTBOARDS, none())); } items.push((tl!("Export"), "share-2", "file.exportForScreens", none())); - } else { + } else if !typing { + // The selection tools' object actions. A Type tool's bar leaves them out, Create Outlines + // and the type conversions included. // Edit Path: the Direct Selection tool, to edit the path's anchors. let edit_path = || (tl!("Edit Path"), "dc-direct", "tool.select", json!({"tool": "directSelection"})); // As in the reference app, an image offers Image Trace, Crop Image and Remove Background, and @@ -185,22 +231,31 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { } items.push((tl!("Duplicate"), "copy", "edit.duplicate", none())); } - // The paints the Fill and Stroke proxies show, "?" when the selected objects' paints differ. - let (fill, stroke) = crate::panels::current_paints(app); - let (fill_mixed, stroke_mixed) = crate::panels::mixed_paints(app, ui.ctx()); + let (fill, stroke, fill_mixed, stroke_mixed) = chip_paints(app, ui.ctx()); let colored = has_colors(&st.doc, &st.selection.objects); let doc = st.uid; // Under the selection's lowest corner on screen, centered on the selection (the view may be // rotated). let lowest = xf.quad(b).iter().map(|c| c.y).fold(f32::NEG_INFINITY, f32::max); let anchor = pos2(xf.to_screen(b.center()).x, lowest); - let est_w = 150.0 + items.iter().map(|(l, _, _, _)| l.len() as f32 * 7.2 + 44.0).sum::(); + let bounds = xf.rect.shrink(8.0); + // On a canvas too narrow for the type controls at their narrowest, the bar leaves them out. + let fonts = fonts && bounds.width() - 18.0 >= crate::panels::character::task_bar_min_room(); + ui.ctx().data_mut(|d| d.insert_temp(task_bar_id().with("fonts"), fonts)); + // The width of the bar's frame (margins and stroke), its handle, Fill and Stroke chips, + // Recolor Artwork, Lock or Shape Properties, and More Options, each after a 6-point gap. + let chips: f32 = + [(!on_artboards, 26.0), (!on_artboards && !typing, 26.0), (!on_artboards && !typing && colored, 30.0), (!on_artboards && !typing, 30.0)] + .iter() + .filter(|(shown, _)| *shown) + .map(|(_, w)| w + 6.0) + .sum(); + let (font_row, est) = size_estimate(&items, fonts, 18.0 + 4.0 + chips + 36.0, bounds.width()); // Its place under the selection, then where the handle moved it, kept on the canvas (with the // bar's size last frame, the estimate before it first shows). - let under = pos2(anchor.x - est_w / 2.0, anchor.y + 28.0); + let under = pos2(anchor.x - est.x / 2.0, anchor.y + 28.0); let id = task_bar_id(); - let size = egui::AreaState::load(ui.ctx(), id).and_then(|s| s.size).unwrap_or(vec2(est_w, 44.0)); - let bounds = xf.rect.shrink(8.0); + let size = egui::AreaState::load(ui.ctx(), id).and_then(|s| s.size).unwrap_or(est); let keep_in = |p: Pos2| p.clamp(bounds.min, (bounds.max - size).max(bounds.min)); let place = &mut app.ui.task_bar_place; // Just unpinned: follow the selection from the pinned spot. @@ -255,23 +310,21 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { run = Some((*cmd, params.clone())); } } + // Type's font family, font style and Font Size, which act as the Character + // panel's do: on the characters a Type tool selects, else on the selected type. + if fonts && !font_row { + crate::panels::character::task_bar(app, ui, f32::INFINITY); + } // The selected objects' Fill, Stroke, Recolor Artwork and Lock (a basic shape's - // properties instead), left out with the Artboard tool. - if !on_artboards { - let (r, resp) = ui.allocate_exact_size(vec2(26.0, 30.0), Sense::click()); - let chip = egui::Rect::from_center_size(r.center(), vec2(16.0, 16.0)); - widgets::proxy_chip(ui, chip, &fill, fill_mixed, None); - ui.painter().rect_stroke(chip, 0.0, Stroke::new(1.0, t.button_border), StrokeKind::Outside); - if resp.on_hover_text(tl!("Fill")).clicked() { - app.session.fill_active = true; - show_swatches = true; - } + // properties instead), left out with the Artboard tool. A Type tool's bar has + // the Fill alone. + if !on_artboards && paint_chip(ui, &t, &fill, fill_mixed, None, tl!("Fill")) { + app.session.fill_active = true; + show_swatches = true; + } + if !on_artboards && !typing { // The Stroke chip, drawn as a ring as the Control bar's is. - let (r, resp) = ui.allocate_exact_size(vec2(26.0, 30.0), Sense::click()); - let chip = egui::Rect::from_center_size(r.center(), vec2(16.0, 16.0)); - widgets::proxy_chip(ui, chip, &stroke, stroke_mixed, Some(4.0)); - ui.painter().rect_stroke(chip, 0.0, Stroke::new(1.0, t.button_border), StrokeKind::Outside); - if resp.on_hover_text(tl!("Stroke")).clicked() { + if paint_chip(ui, &t, &stroke, stroke_mixed, Some(4.0), tl!("Stroke")) { app.session.fill_active = false; show_swatches = true; } @@ -316,6 +369,13 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { } }); }); + if font_row { + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 6.0; + // The canvas's width less the frame's margins and stroke. + crate::panels::character::task_bar(app, ui, bounds.width() - 18.0); + }); + } }); }); if moved != Vec2::ZERO { @@ -353,6 +413,42 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { } } +/// Whether the type controls go on a second row, and the bar's estimated size before it first +/// shows: `items` and, when `fonts`, the font family, font style and Font Size controls, which take +/// a second row when one row, with the bar's other controls `fixed` points wide, would be wider than +/// `room` (and narrow to fit it there). +fn size_estimate(items: &[(&str, &str, &str, serde_json::Value)], fonts: bool, fixed: f32, room: f32) -> (bool, Vec2) { + let font_w: f32 = crate::panels::character::TASK_BAR_WIDTHS.iter().filter(|_| fonts).map(|w| w + 6.0).sum(); + let items_w = if fonts { fixed } else { 150.0 } + items.iter().map(|(l, _, _, _)| l.len() as f32 * 7.2 + 44.0).sum::(); + if fonts && items_w + font_w > room { (true, vec2(items_w.max((font_w + 16.0).min(room)), 80.0)) } else { (false, vec2(items_w + font_w, 44.0)) } +} + +/// The paints the Fill and Stroke chips show, and whether each is mixed ("?"): the proxies', or +/// while a Type tool edits type, the edited characters' fill, which a swatch picked then paints. +pub(crate) fn chip_paints(app: &VectorcraftApp, ctx: &egui::Context) -> (vectorcraft_color::Paint, vectorcraft_color::Paint, bool, bool) { + let (fill, stroke) = crate::panels::current_paints(app); + let (fill_mixed, stroke_mixed) = crate::panels::mixed_paints(app, ctx); + if crate::panels::character::text_editing(app).is_some() + && let Some((chars, _)) = crate::panels::character::text_style(app) + { + let mixed = crate::panels::character::shared(app, |s| s.fill.clone()).is_none(); + return (chars.fill, stroke, mixed, stroke_mixed); + } + (fill, stroke, fill_mixed, stroke_mixed) +} + +/// One of the Contextual Task Bar's Fill and Stroke chips, showing `paint` ("?" when `mixed`, a +/// ring of `ring` points for the stroke), named `tip` for screen readers. Returns whether it was +/// clicked. +fn paint_chip(ui: &mut Ui, t: &Tokens, paint: &vectorcraft_color::Paint, mixed: bool, ring: Option, tip: &str) -> bool { + let (r, resp) = ui.allocate_exact_size(vec2(26.0, 30.0), Sense::click()); + let chip = egui::Rect::from_center_size(r.center(), vec2(16.0, 16.0)); + widgets::proxy_chip(ui, chip, paint, mixed, ring); + ui.painter().rect_stroke(chip, 0.0, Stroke::new(1.0, t.button_border), StrokeKind::Outside); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tip)); + resp.on_hover_text(tip).clicked() +} + /// The Contextual Task Bar's Center on Top and Center on Bottom, as in the Type menu, for type on a /// closed path. fn center_on_path_items(app: &VectorcraftApp, items: &mut Vec<(&'static str, &'static str, &'static str, serde_json::Value)>) { diff --git a/crates/ui-egui/src/cursors.rs b/crates/ui-egui/src/cursors.rs index 34156f2c41..a438a71881 100644 --- a/crates/ui-egui/src/cursors.rs +++ b/crates/ui-egui/src/cursors.rs @@ -468,6 +468,27 @@ fn paint_brush(p: &mut Ink, o: Pos2) { } } +/// Live Paint Selection: the solid arrow with a badge at its lower right saying what a click +/// selects: a filled square over a face ([`Cursor::LivePaintSelectFace`]), a short line between two +/// anchor marks over an edge ([`Cursor::LivePaintSelectEdge`]), an x where it selects nothing. +fn live_paint_select(p: &mut Ink, o: Pos2, part: Cursor) { + arrow(p, o, false); + let b = o + vec2(12.0, 13.0); + match part { + Cursor::LivePaintSelectFace => { + poly(p, [(0.0, 0.0), (6.0, 0.0), (6.0, 6.0), (0.0, 6.0)].map(|(x, y)| b + vec2(x, y)).to_vec(), INK, INK); + } + Cursor::LivePaintSelectEdge => { + let (a, c) = (b + vec2(0.0, 7.0), b + vec2(7.0, 0.0)); + strokes(p, &[vec![a, c]]); + for m in [a, c] { + poly(p, [(-1.5, -1.5), (1.5, -1.5), (1.5, 1.5), (-1.5, 1.5)].map(|(x, y)| m + vec2(x, y)).to_vec(), INK, INK); + } + } + _ => strokes(p, &[vec![b, b + vec2(6.0, 6.0)], vec![b + vec2(6.0, 0.0), b + vec2(0.0, 6.0)]]), + } +} + /// The Hand tool and Space: an open hand (palm and four fingers, thumb to the left), or the same /// hand closed while it drags the view. Windows has no system hand that isn't a pointing finger /// (winit maps egui's Grab and Grabbing to the four-headed move cursor), so it is drawn like the @@ -516,7 +537,7 @@ fn magnifier(p: &mut Ink, o: Pos2, out: bool) { /// Every cursor with a glyph: its own, drawn here, or the one it borrows. #[cfg(test)] -const GLYPHS: [Cursor; 95] = [ +const GLYPHS: [Cursor; 98] = [ Cursor::Hand, Cursor::HandGrab, Cursor::ZoomIn, @@ -586,6 +607,9 @@ const GLYPHS: [Cursor; 95] = [ Cursor::LivePaintBucket, Cursor::LivePaintBucketFace, Cursor::LivePaintBucketEdge, + Cursor::LivePaintSelectFace, + Cursor::LivePaintSelectEdge, + Cursor::LivePaintSelectOutside, Cursor::Measure, Cursor::PrintTiling, Cursor::SymbolSprayer, @@ -710,6 +734,7 @@ fn glyph(c: Cursor, p: Pos2) -> Option> { Cursor::LivePaintBucket => paint_bucket(ink, p, false), Cursor::LivePaintBucketFace => paint_bucket(ink, p, true), Cursor::LivePaintBucketEdge => paint_brush(ink, p), + Cursor::LivePaintSelectFace | Cursor::LivePaintSelectEdge | Cursor::LivePaintSelectOutside => live_paint_select(ink, p, c), Cursor::Hand => hand(ink, p, false), Cursor::HandGrab => hand(ink, p, true), Cursor::ZoomIn => magnifier(ink, p, false), diff --git a/crates/ui-egui/src/cursors/tests.rs b/crates/ui-egui/src/cursors/tests.rs index 4a12ff91b6..ae1947616f 100644 --- a/crates/ui-egui/src/cursors/tests.rs +++ b/crates/ui-egui/src/cursors/tests.rs @@ -331,6 +331,45 @@ fn the_live_paint_bucket_shows_a_bucket_or_a_brush() { } } +/// Live Paint Selection's cursors are the solid arrow, its tip on the hotspot, with a badge at its +/// lower right: a filled square over a face, a line between two anchor marks over an edge, and an x +/// where a click selects nothing. +#[test] +fn live_paint_selection_shows_the_arrow_with_a_face_edge_or_x_badge() { + for ppp in [2.0f32, 3.0] { + let img = |c| rasterize(c, ppp).unwrap_or_else(|| panic!("{c:?} at {ppp}")); + let (arrow, cross) = (img(Cursor::Arrow), img(Cursor::Crosshair)); + let (face, edge, out) = (img(Cursor::LivePaintSelectFace), img(Cursor::LivePaintSelectEdge), img(Cursor::LivePaintSelectOutside)); + // The pixel at (dx, dy) points from the hotspot. + let at = |img: &CustomCursorImage, dx: f32, dy: f32| { + let [hx, hy] = img.hotspot.map(usize::from); + let (x, y) = ((hx as f32 + dx * ppp) as usize, (hy as f32 + dy * ppp) as usize); + if x < img.size[0] as usize && y < img.size[1] as usize { pixel(img, x, y) } else { [0; 4] } + }; + let inked = |p: [u8; 4]| p[3] > 200 && p[0] < 64; + // Inside the square, away from the x's strokes and the edge's line. + let square = (15.0, 14.0); + // The edge's upper anchor mark, beyond the square and the x. + let mark = (19.0, 13.0); + // On the x's stroke from top left to bottom right, away from the edge's line. + let x_stroke = (13.0, 14.0); + for (c, i, want) in [ + (Cursor::LivePaintSelectFace, &face, [true, false, true]), + (Cursor::LivePaintSelectEdge, &edge, [false, true, false]), + (Cursor::LivePaintSelectOutside, &out, [false, false, true]), + ] { + assert_eq!(i.hotspot, arrow.hotspot, "{c:?} has the arrow's hotspot at {ppp}"); + assert!(inked(at(i, 1.5, 6.0)), "{c:?} is the solid arrow at {ppp}"); + let got = [square, mark, x_stroke].map(|(x, y)| inked(at(i, x, y))); + assert_eq!(got, want, "{c:?} at {ppp}"); + assert!(c.stand_in().is_none(), "{c:?} is drawn"); + assert_ne!(i, &arrow, "{c:?} is not the plain arrow at {ppp}"); + assert_eq!(rasterize(c.precise(), ppp).as_ref(), Some(&cross), "{c:?} with Use Precise Cursors at {ppp}"); + } + assert!(face != edge && edge != out && face != out, "three looks at {ppp}"); + } +} + #[test] fn each_bitmap_is_made_once_so_the_os_cursor_is_kept() { let mut images = Images::default(); diff --git a/crates/ui-egui/src/dialogs/color_picker/tests.rs b/crates/ui-egui/src/dialogs/color_picker/tests.rs index 4d678b1069..5587b9c560 100644 --- a/crates/ui-egui/src/dialogs/color_picker/tests.rs +++ b/crates/ui-egui/src/dialogs/color_picker/tests.rs @@ -106,6 +106,94 @@ fn gamut_correction_gives_a_printable_colour() { assert_eq!(gamut_fix(&mut app, &ctx, "picker-gamut", &Color::rgb8(128, 128, 128)), None); } +/// The cached warning follows the CMYK space it is checked in: assigning the document a CMYK +/// profile, removing it, or changing the working CMYK space updates it for the same color. +#[test] +fn gamut_warning_follows_a_profile_change() { + const CHILD: &str = "VECTORCRAFT_TEST_GAMUT_PROFILE_CHANGE"; + if std::env::var_os(CHILD).is_none() { + // Color settings are process-wide: change them in a separate test process. + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "dialogs::color_picker::tests::gamut_warning_follows_a_profile_change", "--nocapture"]) + .env(CHILD, "1") + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"), + "isolated gamut test failed:\n{stdout}\n{}", + String::from_utf8_lossy(&output.stderr), + ); + return; + } + use vectorcraft_color::cms; + let mut app = app(); + let ctx = egui::Context::default(); + let blue = Color::rgb(0.0, 0.0, 1.0); + let fix = gamut_fix(&mut app, &ctx, "picker-gamut", &blue); + assert!(fix.is_some(), "pure blue is out of the default CMYK gamut"); + // Device CMYK has no gamut to fall outside of. + app.run("edit.assignProfile", json!({"cmyk": cms::DEVICE_CMYK})).unwrap(); + assert_eq!(gamut_fix(&mut app, &ctx, "picker-gamut", &blue), None); + app.run("edit.assignProfile", json!({"cmyk": null})).unwrap(); + assert_eq!(gamut_fix(&mut app, &ctx, "picker-gamut", &blue), fix); + app.run("edit.colorSettings", json!({"cmyk": cms::DEVICE_CMYK})).unwrap(); + assert_eq!(gamut_fix(&mut app, &ctx, "picker-gamut", &blue), None); + app.run("edit.colorSettings", json!({"cmyk": cms::GENERIC_CMYK})).unwrap(); + assert_eq!(gamut_fix(&mut app, &ctx, "picker-gamut", &blue), fix); +} + +/// Loading a new file of the document's assigned CMYK profile, under the same name, updates the +/// cached warning for the same color. +#[test] +fn gamut_warning_follows_a_profile_loaded_again() { + const CHILD: &str = "VECTORCRAFT_TEST_GAMUT_PROFILE_RELOAD"; + if std::env::var_os(CHILD).is_none() { + // Color settings and loaded profiles are process-wide: change them in a separate test process. + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "dialogs::color_picker::tests::gamut_warning_follows_a_profile_loaded_again", "--nocapture"]) + .env(CHILD, "1") + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"), + "isolated gamut test failed:\n{stdout}\n{}", + String::from_utf8_lossy(&output.stderr), + ); + return; + } + use vectorcraft_color::cms; + // A built-in CMYK profile's file renamed `name`: padded with spaces, which names drop. + let renamed = |builtin: &str, name: &str| { + let utf16 = |s: &str| s.encode_utf16().flat_map(u16::to_be_bytes).collect::>(); + let mut bytes = cms::icc_bytes(builtin).unwrap().to_vec(); + let (from, to) = (utf16(builtin), utf16(&format!("{name: { - let mut params = json!({ "format": f.id, "path": path, "useArtboards": use_artboards }); - if use_artboards { - params["range"] = json!(range); + let mut params = json!({ "format": f.id, "path": path }); + // A format that holds the whole document (a template) has no Use Artboards: the + // export is not given the option, which its warnings would name as not used. + if plugin.is_some() || f.options.iter().any(|o| o.name == "useArtboards") { + params["useArtboards"] = json!(use_artboards); + if use_artboards { + params["range"] = json!(range); + } } if let Some(plugin) = plugin.filter(|p| !p.manifest().params.is_empty()) { plugin::open_export(app, &plugin, params); diff --git a/crates/ui-egui/src/font_menu.rs b/crates/ui-egui/src/font_menu.rs index 590b93a2fa..c7a74e3178 100644 --- a/crates/ui-egui/src/font_menu.rs +++ b/crates/ui-egui/src/font_menu.rs @@ -55,6 +55,8 @@ pub enum WheelOwner { Control, /// The Character popover attached to this Control bar link. ControlPopover(egui::Id), + /// The Contextual Task Bar's type controls. + TaskBar, } impl WheelOwner { @@ -68,6 +70,12 @@ impl WheelOwner { Self::ControlPopover(anchor) => { return app.ui.control_bar && app.ui.screen_mode < 2 && widgets::popover_is_open(ctx, anchor); } + Self::TaskBar => { + return app.ui.task_bar + && app.ui.screen_mode < 3 + && crate::canvas::task_bar_shows_type(app) + && crate::canvas::task_bar_shows_fonts(ctx); + } Self::Character => "character", Self::Properties => { let selected = app.session.active().and_then(|document| document.selection.objects.first().and_then(|id| document.doc.node(*id))); @@ -106,12 +114,24 @@ pub struct MenuLook<'a> { pub wheel: bool, /// Its owner, so a field hidden before the next layout cannot capture wheel input. pub wheel_owner: Option, + /// The name screen readers give the closed field when no label stands beside it. + pub name: Option<&'a str>, } impl Default for MenuLook<'static> { /// Samples on in the theme's colors, English names, medium rows, no favorites, no wheel. fn default() -> Self { - Self { samples: true, on_white: false, english_names: true, row: ROW, favorites: &[], recent: &[], wheel: false, wheel_owner: None } + Self { + samples: true, + on_white: false, + english_names: true, + row: ROW, + favorites: &[], + recent: &[], + wheel: false, + wheel_owner: None, + name: None, + } } } @@ -131,6 +151,7 @@ impl<'a> MenuLook<'a> { recent: app.recent_fonts(), wheel: false, wheel_owner: None, + name: None, } } } @@ -382,7 +403,7 @@ pub fn font_menu( // The search field and filters stay in place over the rows, which scroll. The rows are all // one height (a family's styles too), so only those in view are laid out: there are thousands // of families. - let (field, shown) = widgets::combo_menu_field(ui, &id, current, width, |menu| { + let (field, shown) = widgets::combo_menu_field_named(ui, &id, look.name, current, width, |menu| { menu.height(height).show_rows_with_header( |ui| { // Wider than a narrow field, so the filters keep their rows and long names show. diff --git a/crates/ui-egui/src/free_transform.rs b/crates/ui-egui/src/free_transform.rs index dbebedffa2..9240c1e529 100644 --- a/crates/ui-egui/src/free_transform.rs +++ b/crates/ui-egui/src/free_transform.rs @@ -1,7 +1,7 @@ //! The Free Transform widget (#598): while the Free Transform tool is active, a small floating box //! at the canvas's top left with Constrain (as holding Shift: proportional scaling, moves and -//! rotations by 45°) over the tool's three modes, Free Transform, Perspective Distort and Free -//! Distort. It sets the tool's options through `tool.setOption` (`constrain`, `mode`), as agents +//! rotations by 45°, and Free Distort corners kept on their diagonal) over the tool's three modes, +//! Free Transform, Perspective Distort and Free Distort. It sets the tool's options through `tool.setOption` (`constrain`, `mode`), as agents //! do; the modifier keys keep working while dragging. use egui::{Color32, CornerRadius, Pos2, Rect, Sense, Stroke, StrokeKind, Ui, pos2, vec2}; @@ -61,8 +61,8 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &Ui, canvas: Rect) { .shadow(egui::epaint::Shadow { offset: [0, 2], blur: 8, spread: 0, color: Color32::from_black_alpha(60) }) .show(ui, |ui| { ui.spacing_mut().item_spacing.y = 2.0; - // Constrain shapes only what the Free Transform mode does. - if button(ui, Glyph::Icon("link"), tl!("Constrain"), constrain, mode == "free") { + // Constrain shapes what the Free Transform and Free Distort modes do. + if button(ui, Glyph::Icon("link"), tl!("Constrain"), constrain, mode != "perspective") { set = Some(("constrain", json!(!constrain))); } let (line, _) = ui.allocate_exact_size(vec2(BUTTON, 3.0), Sense::hover()); @@ -148,7 +148,8 @@ mod tests { } /// The widget shows with the Free Transform tool only; its buttons set the mode and Constrain - /// (inert in the distort modes); a corner dragged in Free Distort moves that corner alone. + /// (inert in Perspective Distort); a corner dragged in Free Distort moves that corner alone, and + /// with Constrain on it keeps to the diagonal through the opposite corner. #[test] fn the_widget_sets_the_mode_and_a_corner_drag_then_distorts() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); @@ -175,26 +176,50 @@ mod tests { assert_eq!(options(&app), ("free".into(), true), "Constrain on"); click(&mut app, &ctx, at(3)); assert_eq!(options(&app), ("distort".into(), true)); - click(&mut app, &ctx, at(0)); - assert_eq!(options(&app), ("distort".into(), true), "Constrain is inert in Free Distort"); click(&mut app, &ctx, at(2)); assert_eq!(options(&app).0, "perspective"); + click(&mut app, &ctx, at(0)); + assert_eq!(options(&app), ("perspective".into(), true), "Constrain is inert in Perspective Distort"); click(&mut app, &ctx, at(3)); - // Free Distort: the top-left corner dragged alone. + // Free Distort with Constrain on: the top-left corner dragged by (-20, -10) keeps to the + // diagonal (-100, -60), so it moves by 2,600 / 13,600 of it, about (-19.1, -11.5). let xf = Xf::new(canvas, app.view().unwrap()); - let (from, to) = (xf.to_screen(Point::new(100.0, 100.0)), xf.to_screen(Point::new(80.0, 90.0))); let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; - frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from), button(from, true)]); - frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from + (to - from) / 2.0)]); - frame(&mut app, &ctx, vec![egui::Event::PointerMoved(to)]); - frame(&mut app, &ctx, vec![button(to, false)]); - frame(&mut app, &ctx, vec![]); - let st = app.session.active().unwrap(); - let node = st.doc.node(vectorcraft_doc::NodeId(id.as_u64().unwrap())).unwrap(); - let pts: Vec = node.path_data().unwrap().anchors().map(|(.., a)| a.p).collect(); - let near = |q: Point| pts.iter().any(|p| p.distance(q) < 0.5); + let drag = |app: &mut VectorcraftApp, from: Point, to: Point| { + let (from, to) = (xf.to_screen(from), xf.to_screen(to)); + frame(app, &ctx, vec![egui::Event::PointerMoved(from), button(from, true)]); + frame(app, &ctx, vec![egui::Event::PointerMoved(from + (to - from) / 2.0)]); + frame(app, &ctx, vec![egui::Event::PointerMoved(to)]); + frame(app, &ctx, vec![button(to, false)]); + frame(app, &ctx, vec![]); + }; + let corners = |app: &VectorcraftApp| -> Vec { + let st = app.session.active().unwrap(); + let node = st.doc.node(vectorcraft_doc::NodeId(id.as_u64().unwrap())).unwrap(); + node.path_data().unwrap().anchors().map(|(.., a)| a.p).collect() + }; + let has = |pts: &[Point], q: Point| pts.iter().any(|p| p.distance(q) < 0.5); + drag(&mut app, Point::new(100.0, 100.0), Point::new(80.0, 90.0)); + let k = (20.0 * 100.0 + 10.0 * 60.0) / (100.0f64 * 100.0 + 60.0 * 60.0); + let pts = corners(&app); assert!( - near(Point::new(80.0, 90.0)) && near(Point::new(200.0, 100.0)) && near(Point::new(200.0, 160.0)) && near(Point::new(100.0, 160.0)), + has(&pts, Point::new(100.0 - 100.0 * k, 100.0 - 60.0 * k)) + && has(&pts, Point::new(200.0, 100.0)) + && has(&pts, Point::new(200.0, 160.0)) + && has(&pts, Point::new(100.0, 160.0)), + "{pts:?}" + ); + app.run("edit.undo", json!({})).unwrap(); + // Constrain off in Free Distort: the corner moves with the pointer. + click(&mut app, &ctx, at(0)); + assert_eq!(options(&app), ("distort".into(), false), "Constrain works in Free Distort"); + drag(&mut app, Point::new(100.0, 100.0), Point::new(80.0, 90.0)); + let pts = corners(&app); + assert!( + has(&pts, Point::new(80.0, 90.0)) + && has(&pts, Point::new(200.0, 100.0)) + && has(&pts, Point::new(200.0, 160.0)) + && has(&pts, Point::new(100.0, 160.0)), "{pts:?}" ); assert_eq!(app.session.tool_id(), TOOL); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index ff72685662..56c525f57f 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -4130,6 +4130,9 @@ axis Both И двете @msg Couldn't open {name}: {e} Неуспешно отваряне на {name}: {e} @msg Couldn't place {name}: the document it was dropped on was closed Неуспешно поставяне на {name}: документът, върху който беше пуснат, е затворен @msg Couldn't place {name}: the document it was placed in was closed Неуспешно поставяне на {name}: документът, в който се поставяше, е затворен +@msg Couldn't place {name}: the document it was dropped on was reverted Неуспешно поставяне на {name}: документът, върху който беше пуснат, е върнат към запазеното +@msg Couldn't place {name}: the document it was placed in was reverted Неуспешно поставяне на {name}: документът, в който се поставяше, е върнат към запазеното +@msg Couldn't paste: the document it was pasted in was reverted Неуспешно поставяне: документът, в който се поставяше, е върнат към запазеното @msg Couldn't read {name}: {e} Неуспешно четене на {name}: {e} @msg Couldn't save recovery data: {e} Неуспешно запазване на данните за възстановяване: {e} @msg Create Outlines: select text objects Създаване на контури: изберете текстови обекти @@ -5406,6 +5409,8 @@ lighting Light Светлина Pen Перо Pentagram Петограм Perceptual Перцептивен + Hue Clockwise Оттенък по часовниковата стрелка + Hue Counterclockwise Оттенък обратно на часовниковата стрелка Phone 360×800 Телефон 360×800 Phone 375×667 Телефон 375×667 Phone 375×812 Телефон 375×812 @@ -5975,7 +5980,7 @@ axis Y Axis Y ос @msg `dither` applies to gradient fills (stroke: false) `dither` се прилага към градиентни запълки (stroke: false) @msg `dither` applies to gradient fills (paint.setFill) `dither` се прилага към градиентни запълки (paint.setFill) @msg `dither` must be true or false `dither` трябва да бъде true или false -@msg `method` must be classic or perceptual `method` трябва да е classic или perceptual +@msg `method` must be classic, perceptual, hue-clockwise or hue-counterclockwise `method` трябва да е classic, perceptual, hue-clockwise или hue-counterclockwise # Heavy plug-in filters (plugin.inspect, plug-in runs) Install “{name}”, which asks for a heavy budget? Да се инсталира ли „{name}“, който иска голям изчислителен бюджет? Each run may take up to {minutes} minutes and do {times} times the work other plug-ins may. It runs in the background, and you can cancel it. Всяко изпълнение може да продължи до {minutes} минути и да свърши {times} пъти повече работа, отколкото е позволено на другите приставки. То се изпълнява във фонов режим и можете да го откажете. @@ -6016,6 +6021,7 @@ axis Y Axis Y ос Continue Продължаване Continue Action Продължаване на действието Delete Action Step Изтриване на стъпка от действието + Move Action Step Преместване на стъпка от действието Press Play Current Selection in the Actions panel to go on. За да продължите, натиснете „Изпълнение на текущия избор“ в панела „Действия“. Stop: {message} Спиране: {message} @msg no action is waiting at a stop няма действие, което чака при спиране @@ -6176,6 +6182,22 @@ axis Y Axis Y ос Graphite Pencil Графитен молив Wax Crayon Восъчен пастел Charcoal Dust Въглен прах + Notched Ribbon Назъбена лента + Double Line Двойна линия + Wave Вълна + Teardrop Сълза + Striped Ribbon Раирана лента + Fine Nib Тънък писец + Broad Nib Широк писец + Chisel Длето + Round Pen Кръгло перо + Pressure Pen Перо с натиск + Beads Мъниста + Dash Dot Тире-точка + Scallops Фестони + Stars Звезди + Triangles Триъгълници + Sparkles Искри Save Brush Library… Запази библиотека с четки… @msg no empty artboards to delete няма празни работни области за изтриване Scale Presets Пресети за мащаб diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 0c77f90ad8..c7d82d2c6d 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -4494,6 +4494,9 @@ imageTrace Outline Obris @msg Couldn't open {name}: {e} Nije moguće otvoriti {name}: {e} @msg Couldn't place {name}: the document it was dropped on was closed Nije moguće postaviti {name}: dokument na koji je ispušten je zatvoren @msg Couldn't place {name}: the document it was placed in was closed Nije moguće postaviti {name}: dokument u koji je postavljen je zatvoren +@msg Couldn't place {name}: the document it was dropped on was reverted Nije moguće postaviti {name}: dokument na koji je ispušten je vraćen na sačuvano +@msg Couldn't place {name}: the document it was placed in was reverted Nije moguće postaviti {name}: dokument u koji je postavljen je vraćen na sačuvano +@msg Couldn't paste: the document it was pasted in was reverted Nije moguće zalijepiti: dokument u koji se lijepilo je vraćen na sačuvano @msg Couldn't read {name}: {e} Nije moguće pročitati {name}: {e} @msg Couldn't save recovery data: {e} Nije moguće sačuvati podatke za oporavak: {e} @msg Create Outlines: select text objects Kreiraj obrise: odaberite tekstualne objekte @@ -5503,6 +5506,8 @@ imageTrace Outline Obris Vivid Živo Spectrum Spektar Perceptual Perceptivno + Hue Clockwise Nijansa u smjeru kazaljke na satu + Hue Counterclockwise Nijansa suprotno od kazaljke na satu Relative Colorimetric Relativna kolorimetrija Absolute Colorimetric Apsolutna kolorimetrija Exact Tačno @@ -5994,7 +5999,7 @@ axis Y Axis Y osa @msg `dither` applies to gradient fills (stroke: false) `dither` se primjenjuje na gradijentne ispune (stroke: false) @msg `dither` applies to gradient fills (paint.setFill) `dither` se primjenjuje na gradijentne ispune (paint.setFill) @msg `dither` must be true or false `dither` mora biti true ili false -@msg `method` must be classic or perceptual `method` mora biti classic ili perceptual +@msg `method` must be classic, perceptual, hue-clockwise or hue-counterclockwise `method` mora biti classic, perceptual, hue-clockwise ili hue-counterclockwise Install “{name}”, which asks for a heavy budget? Instalirati „{name}”, koji traži veliki budžet? Each run may take up to {minutes} minutes and do {times} times the work other plug-ins may. It runs in the background, and you can cancel it. Svako pokretanje može trajati do {minutes} minuta i obaviti {times} puta više posla nego drugi dodaci. Radi u pozadini i možete ga otkazati. It may take minutes, so it runs in the background, where you can cancel it. Može trajati minutama, pa radi u pozadini, gdje ga možete otkazati. @@ -6058,6 +6063,7 @@ axis Y Axis Y osa Continue Nastavi Continue Action Nastavi akciju Delete Action Step Izbriši korak akcije + Move Action Step Premjesti korak akcije Press Play Current Selection in the Actions panel to go on. Za nastavak pritisnite „Reprodukuj trenutni odabir“ na panelu Akcije. Stop: {message} Zaustavljanje: {message} @msg no action is waiting at a stop nijedna akcija ne čeka na zaustavljanju @@ -6229,6 +6235,22 @@ axis Y Axis Y osa Graphite Pencil Grafitna olovka Wax Crayon Voštana bojica Charcoal Dust Ugljena prašina + Notched Ribbon Zarezana traka + Double Line Dvostruka linija + Wave Talas + Teardrop Suza + Striped Ribbon Prugasta traka + Fine Nib Tanki vrh + Broad Nib Široki vrh + Chisel Dlijeto + Round Pen Okruglo pero + Pressure Pen Pero na pritisak + Beads Perle + Dash Dot Crta-tačka + Scallops Festoni + Stars Zvijezde + Triangles Trouglovi + Sparkles Iskrice Save Brush Library… Sačuvaj biblioteku četkica… @msg `{_1}` has no brushes to apply `{_1}` nema četkica za primjenu @msg missing `library` (see brush.libraries) nedostaje `library` (pogledajte brush.libraries) diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 6601948ba6..cacf2566be 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -3144,6 +3144,8 @@ digits Malayalam Malaiàlam per slice per tall Percent: Percentatge: Perceptual Perceptual + Hue Clockwise To en sentit horari + Hue Counterclockwise To en sentit antihorari Perceptual Scales Escales perceptuals Performance Rendiment Permissions Permisos @@ -3928,6 +3930,22 @@ digits Malayalam Malaiàlam Graphite Pencil Llapis de grafit Wax Crayon Cera de colors Charcoal Dust Pols de carbó + Notched Ribbon Cinta dentada + Double Line Línia doble + Wave Ona + Teardrop Llàgrima + Striped Ribbon Cinta ratllada + Fine Nib Plomí fi + Broad Nib Plomí ample + Chisel Escarpra + Round Pen Ploma rodona + Pressure Pen Ploma de pressió + Beads Perles + Dash Dot Ratlla i punt + Scallops Festons + Stars Estrelles + Triangles Triangles + Sparkles Espurnes Scatter: Dispersió: Scissors Tisores Scissors Tool Eina de tisores @@ -4054,6 +4072,7 @@ digits Malayalam Malaiàlam Continue Continua Continue Action Continua l’acció Delete Action Step Suprimeix el pas de l’acció + Move Action Step Mou el pas de l’acció Press Play Current Selection in the Actions panel to go on. Per continuar, premeu «Reprodueix la selecció actual» al tauler Accions. Stop: {message} Aturada: {message} @msg no action is waiting at a stop cap acció no espera en una aturada @@ -5196,7 +5215,7 @@ digits Malayalam Malaiàlam @msg `ids` must be an array of object ids, not {v} `ids` ha de ser una matriu d’identificadors d’objecte, no {v} @msg `colors` must be an array of colors, not {v} `colors` ha de ser una matriu de colors, no {v} @msg `library` is a library id or name (see {list}) `library` és un identificador o un nom de biblioteca (vegeu {list}) -@msg `method` must be classic or perceptual `method` ha de ser classic o perceptual +@msg `method` must be classic, perceptual, hue-clockwise or hue-counterclockwise `method` ha de ser classic, perceptual, hue-clockwise o hue-counterclockwise @msg `spread` must be pad, repeat or reflect `spread` ha de ser pad, repeat o reflect @msg `repeats` must be a whole number from 1 to {MAX_REPEATS} `repeats` ha de ser un nombre enter d’1 a {MAX_REPEATS} @msg `spread` applies to linear, radial, conic and diamond gradients `spread` s’aplica als degradats lineals, radials, cònics i de rombe @@ -5523,6 +5542,9 @@ digits Malayalam Malaiàlam @msg Couldn't paste: the document it was pasted in was closed No s’ha pogut enganxar: el document on s’enganxava s’ha tancat @msg Couldn't place {name}: the document it was dropped on was closed No s’ha pogut col·locar {name}: el document on es va deixar anar estava tancat @msg Couldn't place {name}: the document it was placed in was closed No s’ha pogut col·locar {name}: el document on es va col·locar estava tancat +@msg Couldn't place {name}: the document it was dropped on was reverted No s’ha pogut col·locar {name}: el document on es va deixar anar s’ha revertit +@msg Couldn't place {name}: the document it was placed in was reverted No s’ha pogut col·locar {name}: el document on es va col·locar s’ha revertit +@msg Couldn't paste: the document it was pasted in was reverted No s’ha pogut enganxar: el document on s’enganxava s’ha revertit @msg Couldn't place {name}: {e} No s’ha pogut col·locar {name}: {e} @msg Couldn't read {name}: {e} No s’ha pogut llegir {name}: {e} @msg Couldn't save recovery data: {e} No s’han pogut desar les dades de recuperació: {e} diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index baef0a88e6..b243c070fe 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4651,6 +4651,9 @@ imageTrace Outline Obrys @msg Couldn't open {name}: {e} {name} nelze otevřít: {e} @msg Couldn't place {name}: the document it was dropped on was closed {name} nelze umístit: dokument, na který byl přetažen, byl zavřen @msg Couldn't place {name}: the document it was placed in was closed {name} nelze umístit: dokument, do kterého se umísťoval, byl zavřen +@msg Couldn't place {name}: the document it was dropped on was reverted {name} nelze umístit: dokument, na který byl přetažen, byl vrácen k uložené verzi +@msg Couldn't place {name}: the document it was placed in was reverted {name} nelze umístit: dokument, do kterého se umísťoval, byl vrácen k uložené verzi +@msg Couldn't paste: the document it was pasted in was reverted Nelze vložit: dokument, do kterého se vkládalo, byl vrácen k uložené verzi @msg Couldn't read {name}: {e} {name} nelze přečíst: {e} @msg Couldn't save recovery data: {e} Data pro obnovení nelze uložit: {e} @msg Create Outlines: select text objects Převést na křivky: vyberte textové objekty @@ -5714,6 +5717,8 @@ imageTrace Outline Obrys Spectrum Spektrum # Rendering intents, recolor methods, gradient kinds Perceptual Percepční + Hue Clockwise Odstín ve směru hodinových ručiček + Hue Counterclockwise Odstín proti směru hodinových ručiček Relative Colorimetric Relativní kolorimetrický Absolute Colorimetric Absolutní kolorimetrický Exact Přesná @@ -6311,7 +6316,7 @@ axis Y Axis osa Y @msg `dither` applies to gradient fills (stroke: false) `dither` platí pro výplně přechodem (stroke: false) @msg `dither` applies to gradient fills (paint.setFill) `dither` platí pro výplně přechodem (paint.setFill) @msg `dither` must be true or false `dither` musí být true nebo false -@msg `method` must be classic or perceptual `method` musí být classic nebo perceptual +@msg `method` must be classic, perceptual, hue-clockwise or hue-counterclockwise `method` musí být classic, perceptual, hue-clockwise nebo hue-counterclockwise @msg `spread` must be pad, repeat or reflect `spread` musí být pad, repeat nebo reflect @msg `repeats` must be a whole number from 1 to {MAX_REPEATS} `repeats` musí být celé číslo od 1 do {MAX_REPEATS} @msg `spread` applies to linear, radial, conic and diamond gradients `spread` platí pro lineární, kruhové, kuželové a kosočtverečné přechody @@ -6554,6 +6559,7 @@ axis Y Axis osa Y Continue Pokračovat Continue Action Pokračovat v akci Delete Action Step Odstranit krok akce + Move Action Step Přesunout krok akce Press Play Current Selection in the Actions panel to go on. Chcete-li pokračovat, stiskněte na panelu Akce tlačítko Přehrát aktuální výběr. Stop: {message} Zastavení: {message} @msg no action is waiting at a stop žádná akce nečeká na zastavení @@ -6725,6 +6731,22 @@ axis Y Axis osa Y Graphite Pencil Grafitová tužka Wax Crayon Vosková pastelka Charcoal Dust Uhlový prach + Notched Ribbon Vroubkovaná stuha + Double Line Dvojitá čára + Wave Vlna + Teardrop Slza + Striped Ribbon Pruhovaná stuha + Fine Nib Jemný hrot + Broad Nib Široký hrot + Chisel Dláto + Round Pen Kulaté pero + Pressure Pen Tlakové pero + Beads Korálky + Dash Dot Čárka-tečka + Scallops Feston + Stars Hvězdy + Triangles Trojúhelníky + Sparkles Jiskry Save Brush Library… Uložit knihovnu štětců… @msg `{_1}` has no brushes to apply `{_1}` nemá žádné štětce k použití @msg missing `library` (see brush.libraries) chybí `library` (viz brush.libraries) diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 9192974eec..3e0130aeb6 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -4246,6 +4246,9 @@ imageTrace Outline Kontur @msg Couldn't open {name}: {e} Kunne ikke åbne {name}: {e} @msg Couldn't place {name}: the document it was dropped on was closed Kunne ikke placere {name}: dokumentet, den blev sluppet på, var lukket @msg Couldn't place {name}: the document it was placed in was closed Kunne ikke placere {name}: dokumentet, den blev placeret i, var lukket +@msg Couldn't place {name}: the document it was dropped on was reverted Kunne ikke placere {name}: dokumentet, den blev sluppet på, blev gendannet +@msg Couldn't place {name}: the document it was placed in was reverted Kunne ikke placere {name}: dokumentet, den blev placeret i, blev gendannet +@msg Couldn't paste: the document it was pasted in was reverted Kunne ikke indsætte: dokumentet, der blev indsat i, blev gendannet @msg Couldn't read {name}: {e} Kunne ikke læse {name}: {e} @msg Couldn't save recovery data: {e} Kunne ikke gemme gendannelsesdata: {e} @msg Create Outlines: select text objects Opret konturer: markér tekstobjekter @@ -5177,6 +5180,8 @@ imageTrace Outline Kontur Vivid Intens Spectrum Spektrum Perceptual Perceptuel + Hue Clockwise Farvetone med uret + Hue Counterclockwise Farvetone mod uret Relative Colorimetric Relativ kolorimetrisk Absolute Colorimetric Absolut kolorimetrisk Exact Eksakt @@ -5991,7 +5996,7 @@ axis Y Axis Y-akse @msg `dither` applies to gradient fills (stroke: false) `dither` gælder for gradientfyld (stroke: false) @msg `dither` applies to gradient fills (paint.setFill) `dither` gælder for gradientfyld (paint.setFill) @msg `dither` must be true or false `dither` skal være true eller false -@msg `method` must be classic or perceptual `method` skal være classic eller perceptual +@msg `method` must be classic, perceptual, hue-clockwise or hue-counterclockwise `method` skal være classic, perceptual, hue-clockwise eller hue-counterclockwise # Heavy plug-in filters (plugin.inspect, plug-in runs) Install “{name}”, which asks for a heavy budget? Installér »{name}«, som beder om et stort beregningsbudget? Each run may take up to {minutes} minutes and do {times} times the work other plug-ins may. It runs in the background, and you can cancel it. Hver kørsel kan tage op til {minutes} minutter og udføre {times} gange så meget arbejde, som andre plug-ins må. Den kører i baggrunden, og du kan annullere den. @@ -6032,6 +6037,7 @@ axis Y Axis Y-akse Continue Fortsæt Continue Action Fortsæt handling Delete Action Step Slet handlingstrin + Move Action Step Flyt handlingstrin Press Play Current Selection in the Actions panel to go on. Tryk på Afspil aktuel markering i panelet Handlinger for at fortsætte. Stop: {message} Stop: {message} @msg no action is waiting at a stop ingen handling venter ved et stop @@ -6192,6 +6198,22 @@ axis Y Axis Y-akse Graphite Pencil Grafitblyant Wax Crayon Vokskridt Charcoal Dust Kulstøv + Notched Ribbon Takket bånd + Double Line Dobbelt linje + Wave Bølge + Teardrop Dråbe + Striped Ribbon Stribet bånd + Fine Nib Fin pen + Broad Nib Bred pen + Chisel Mejsel + Round Pen Rund pen + Pressure Pen Trykpen + Beads Perler + Dash Dot Streg-prik + Scallops Bølgekant + Stars Stjerner + Triangles Trekanter + Sparkles Gnister Save Brush Library… Gem penselbibliotek… @msg no empty artboards to delete ingen tomme tegneflader at slette Scale Presets Skaleringsforudindstillinger diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 78e7fe186b..25874389f7 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4264,6 +4264,9 @@ theme Appearance Erscheinungsbild @msg Couldn't open {name}: {e} {name} konnte nicht geöffnet werden: {e} @msg Couldn't place {name}: the document it was dropped on was closed {name} konnte nicht platziert werden: Das Dokument, auf das die Datei gezogen wurde, wurde geschlossen @msg Couldn't place {name}: the document it was placed in was closed {name} konnte nicht platziert werden: Das Dokument, in dem die Datei platziert wurde, wurde geschlossen +@msg Couldn't place {name}: the document it was dropped on was reverted {name} konnte nicht platziert werden: Das Dokument, auf das die Datei gezogen wurde, wurde auf die letzte Version zurückgesetzt +@msg Couldn't place {name}: the document it was placed in was reverted {name} konnte nicht platziert werden: Das Dokument, in dem die Datei platziert wurde, wurde auf die letzte Version zurückgesetzt +@msg Couldn't paste: the document it was pasted in was reverted Konnte nicht eingefügt werden: Das Dokument, in das eingefügt wurde, wurde auf die letzte Version zurückgesetzt @msg Couldn't read {name}: {e} {name} konnte nicht gelesen werden: {e} @msg Couldn't save recovery data: {e} Wiederherstellungsdaten konnten nicht gespeichert werden: {e} @msg Create Outlines: select text objects In Pfade umwandeln: Wählen Sie Textobjekte aus @@ -5903,7 +5906,9 @@ axis Y Axis Y-Achse @msg `dither` applies to gradient fills (paint.setFill) `dither` gilt für Verlaufsflächen (paint.setFill) @msg `dither` must be true or false `dither` muss true oder false sein Perceptual Perzeptiv -@msg `method` must be classic or perceptual `method` muss classic oder perceptual sein + Hue Clockwise Farbton im Uhrzeigersinn + Hue Counterclockwise Farbton gegen den Uhrzeigersinn +@msg `method` must be classic, perceptual, hue-clockwise or hue-counterclockwise `method` muss classic, perceptual, hue-clockwise oder hue-counterclockwise sein @msg `spread` must be pad, repeat or reflect `spread` muss pad, repeat oder reflect sein @msg `repeats` must be a whole number from 1 to {MAX_REPEATS} `repeats` muss eine ganze Zahl von 1 bis {MAX_REPEATS} sein @msg `spread` applies to linear, radial, conic and diamond gradients `spread` gilt für lineare, radiale, konische Verläufe und Rautenverläufe @@ -6146,6 +6151,7 @@ axis Y Axis Y-Achse Continue Fortsetzen Continue Action Aktion fortsetzen Delete Action Step Aktionsschritt löschen + Move Action Step Aktionsschritt verschieben Press Play Current Selection in the Actions panel to go on. Klicken Sie im Bedienfeld „Aktionen“ auf „Aktuelle Auswahl abspielen“, um fortzufahren. Stop: {message} Stopp: {message} @msg no action is waiting at a stop keine Aktion wartet an einem Stopp @@ -6317,6 +6323,22 @@ axis Y Axis Y-Achse Graphite Pencil Graphitstift Wax Crayon Wachsmalstift Charcoal Dust Kohlestaub + Notched Ribbon Gekerbtes Band + Double Line Doppellinie + Wave Welle + Teardrop Tropfen + Striped Ribbon Gestreiftes Band + Fine Nib Feine Feder + Broad Nib Breite Feder + Chisel Meißel + Round Pen Runde Feder + Pressure Pen Druckfeder + Beads Perlen + Dash Dot Strich-Punkt + Scallops Bogenkante + Stars Sterne + Triangles Dreiecke + Sparkles Funkeln Save Brush Library… Pinsel-Bibliothek speichern… @msg `{_1}` has no brushes to apply `{_1}` hat keine Pinsel zum Anwenden @msg missing `library` (see brush.libraries) `library` fehlt (siehe brush.libraries) diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 82f265b702..ed558ed20b 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2421,6 +2421,9 @@ axis Both Και τα δύο @msg Couldn't open {name}: {e} Δεν ήταν δυνατό το άνοιγμα του {name}: {e} @msg Couldn't place {name}: the document it was dropped on was closed Δεν ήταν δυνατή η τοποθέτηση του {name}: το έγγραφο στο οποίο αποθέσατε το αρχείο έκλεισε @msg Couldn't place {name}: the document it was placed in was closed Δεν ήταν δυνατή η τοποθέτηση του {name}: το έγγραφο στο οποίο τοποθετούνταν το αρχείο έκλεισε +@msg Couldn't place {name}: the document it was dropped on was reverted Δεν ήταν δυνατή η τοποθέτηση του {name}: το έγγραφο στο οποίο αποθέσατε το αρχείο επανήλθε στην αποθηκευμένη έκδοση +@msg Couldn't place {name}: the document it was placed in was reverted Δεν ήταν δυνατή η τοποθέτηση του {name}: το έγγραφο στο οποίο τοποθετούνταν το αρχείο επανήλθε στην αποθηκευμένη έκδοση +@msg Couldn't paste: the document it was pasted in was reverted Δεν ήταν δυνατή η επικόλληση: το έγγραφο στο οποίο γινόταν η επικόλληση επανήλθε στην αποθηκευμένη έκδοση @msg Couldn't read {name}: {e} Δεν ήταν δυνατή η ανάγνωση του {name}: {e} @msg Couldn't save recovery data: {e} Δεν ήταν δυνατή η αποθήκευση δεδομένων ανάκτησης: {e} @msg Create Outlines: select text objects Δημιουργία περιγραμμάτων: επιλέξτε αντικείμενα κειμένου @@ -2748,6 +2751,8 @@ lighting Light Φως Oval Οβάλ Pen Πένα (Pen Tool) Perceptual Αντιληπτικό + Hue Clockwise Απόχρωση δεξιόστροφα + Hue Counterclockwise Απόχρωση αριστερόστροφα Pixel Εικονοστοιχείο Points: Σημεία: Preserve Διατήρηση @@ -6263,7 +6268,7 @@ axis Y Axis Άξονας Y @msg `dither` applies to gradient fills (stroke: false) Το `dither` ισχύει για γεμίσματα ντεγκραντέ (stroke: false) @msg `dither` applies to gradient fills (paint.setFill) Το `dither` ισχύει για γεμίσματα ντεγκραντέ (paint.setFill) @msg `dither` must be true or false Το `dither` πρέπει να είναι true ή false -@msg `method` must be classic or perceptual Το `method` πρέπει να είναι classic ή perceptual +@msg `method` must be classic, perceptual, hue-clockwise or hue-counterclockwise Το `method` πρέπει να είναι classic, perceptual, hue-clockwise ή hue-counterclockwise @msg `spread` must be pad, repeat or reflect Το `spread` πρέπει να είναι pad, repeat ή reflect @msg `repeats` must be a whole number from 1 to {MAX_REPEATS} Το `repeats` πρέπει να είναι ακέραιος από 1 έως {MAX_REPEATS} @msg `spread` applies to linear, radial, conic and diamond gradients Το `spread` ισχύει για γραμμικά, ακτινικά, κωνικά και ρομβοειδή ντεγκραντέ @@ -6506,6 +6511,7 @@ axis Y Axis Άξονας Y Continue Συνέχεια Continue Action Συνέχεια ενέργειας Delete Action Step Διαγραφή βήματος ενέργειας + Move Action Step Μετακίνηση βήματος ενέργειας Press Play Current Selection in the Actions panel to go on. Για να συνεχίσετε, πατήστε «Αναπαραγωγή τρέχουσας επιλογής» στο πάνελ Ενέργειες. Stop: {message} Διακοπή: {message} @msg no action is waiting at a stop καμία ενέργεια δεν περιμένει σε διακοπή @@ -6677,6 +6683,22 @@ axis Y Axis Άξονας Y Graphite Pencil Μολύβι γραφίτη Wax Crayon Κηρομπογιά Charcoal Dust Σκόνη κάρβουνου + Notched Ribbon Οδοντωτή κορδέλα + Double Line Διπλή γραμμή + Wave Κύμα + Teardrop Δάκρυ + Striped Ribbon Ριγέ κορδέλα + Fine Nib Λεπτή πένα + Broad Nib Φαρδιά πένα + Chisel Σμίλη + Round Pen Στρογγυλή πένα + Pressure Pen Πένα πίεσης + Beads Χάντρες + Dash Dot Παύλα-τελεία + Scallops Φεστόνια + Stars Αστέρια + Triangles Τρίγωνα + Sparkles Σπίθες Save Brush Library… Αποθήκευση βιβλιοθήκης πινέλων… @msg `{_1}` has no brushes to apply Η `{_1}` δεν έχει πινέλα για εφαρμογή @msg missing `library` (see brush.libraries) λείπει το `library` (δείτε brush.libraries) diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index e0aaffde87..fc3a4217cd 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4341,6 +4341,9 @@ axis Both Ambos @msg Couldn't open {name}: {e} No se pudo abrir {name}: {e} @msg Couldn't place {name}: the document it was dropped on was closed No se pudo colocar {name}: se cerró el documento en el que se soltó @msg Couldn't place {name}: the document it was placed in was closed No se pudo colocar {name}: se cerró el documento en el que se estaba colocando +@msg Couldn't place {name}: the document it was dropped on was reverted No se pudo colocar {name}: se revirtió el documento en el que se soltó +@msg Couldn't place {name}: the document it was placed in was reverted No se pudo colocar {name}: se revirtió el documento en el que se estaba colocando +@msg Couldn't paste: the document it was pasted in was reverted No se pudo pegar: se revirtió el documento en el que se estaba pegando @msg Couldn't read {name}: {e} No se pudo leer {name}: {e} @msg Couldn't save recovery data: {e} No se pudieron guardar los datos de recuperación: {e} @msg Create Outlines: select text objects Crear contornos: selecciona objetos de texto @@ -5630,6 +5633,8 @@ effect Regular Regular High Contrast 3 Alto contraste 3 Pentagram Pentagrama Perceptual Perceptual + Hue Clockwise Tono en sentido horario + Hue Counterclockwise Tono en sentido antihorario Relative Colorimetric Colorimétrico relativo Absolute Colorimetric Colorimétrico absoluto Exact Exacto @@ -6254,7 +6259,7 @@ axis Y Axis Eje Y @msg `dither` applies to gradient fills (stroke: false) `dither` se aplica a rellenos de degradado (stroke: false) @msg `dither` applies to gradient fills (paint.setFill) `dither` se aplica a rellenos de degradado (paint.setFill) @msg `dither` must be true or false `dither` debe ser true o false -@msg `method` must be classic or perceptual `method` debe ser classic o perceptual +@msg `method` must be classic, perceptual, hue-clockwise or hue-counterclockwise `method` debe ser classic, perceptual, hue-clockwise o hue-counterclockwise @msg `spread` must be pad, repeat or reflect `spread` debe ser pad, repeat o reflect @msg `repeats` must be a whole number from 1 to {MAX_REPEATS} `repeats` debe ser un número entero de 1 a {MAX_REPEATS} @msg `spread` applies to linear, radial, conic and diamond gradients `spread` se aplica a los degradados lineales, radiales, cónicos y de rombo @@ -6497,6 +6502,7 @@ axis Y Axis Eje Y Continue Continuar Continue Action Continuar acción Delete Action Step Eliminar paso de la acción + Move Action Step Mover paso de la acción Press Play Current Selection in the Actions panel to go on. Para continuar, pulse Reproducir la selección actual en el panel Acciones. Stop: {message} Parada: {message} @msg no action is waiting at a stop ninguna acción está esperando en una parada @@ -6668,6 +6674,22 @@ axis Y Axis Eje Y Graphite Pencil Lápiz de grafito Wax Crayon Cera de colores Charcoal Dust Polvo de carboncillo + Notched Ribbon Cinta dentada + Double Line Línea doble + Wave Onda + Teardrop Lágrima + Striped Ribbon Cinta a rayas + Fine Nib Plumilla fina + Broad Nib Plumilla ancha + Chisel Cincel + Round Pen Pluma redonda + Pressure Pen Pluma de presión + Beads Cuentas + Dash Dot Raya y punto + Scallops Festones + Stars Estrellas + Triangles Triángulos + Sparkles Destellos Save Brush Library… Guardar biblioteca de pinceles… @msg `{_1}` has no brushes to apply `{_1}` no tiene pinceles para aplicar @msg missing `library` (see brush.libraries) falta `library` (consulte brush.libraries) diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 1ea537adbe..da54e0fbdc 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4565,6 +4565,9 @@ imageTrace Outline Ääriviiva @msg Couldn't open {name}: {e} Tiedostoa {name} ei voitu avata: {e} @msg Couldn't place {name}: the document it was dropped on was closed Kohdetta {name} ei voitu sijoittaa: asiakirja, johon se pudotettiin, on suljettu @msg Couldn't place {name}: the document it was placed in was closed Kohdetta {name} ei voitu sijoittaa: asiakirja, johon sitä sijoitettiin, on suljettu +@msg Couldn't place {name}: the document it was dropped on was reverted Kohdetta {name} ei voitu sijoittaa: asiakirja, johon se pudotettiin, on palautettu tallennettuun versioon +@msg Couldn't place {name}: the document it was placed in was reverted Kohdetta {name} ei voitu sijoittaa: asiakirja, johon sitä sijoitettiin, on palautettu tallennettuun versioon +@msg Couldn't paste: the document it was pasted in was reverted Liittäminen ei onnistunut: asiakirja, johon liitettiin, on palautettu tallennettuun versioon @msg Couldn't read {name}: {e} Tiedostoa {name} ei voitu lukea: {e} @msg Couldn't save recovery data: {e} Palautustietoja ei voitu tallentaa: {e} @msg Create Outlines: select text objects Muunna ääriviivoiksi: valitse tekstiobjekteja @@ -5606,6 +5609,8 @@ imageTrace Outline Ääriviiva Vivid Eloisa Spectrum Spektri Perceptual Havainnollinen + Hue Clockwise Sävy myötäpäivään + Hue Counterclockwise Sävy vastapäivään Relative Colorimetric Suhteellinen kolorimetrinen Absolute Colorimetric Absoluuttinen kolorimetrinen Exact Tarkka @@ -6341,7 +6346,7 @@ axis Y Axis Y-akseli @msg `dither` applies to gradient fills (stroke: false) `dither` koskee liukuväritäyttöjä (stroke: false) @msg `dither` applies to gradient fills (paint.setFill) `dither` koskee liukuväritäyttöjä (paint.setFill) @msg `dither` must be true or false `dither` on oltava true tai false -@msg `method` must be classic or perceptual `method` on oltava classic tai perceptual +@msg `method` must be classic, perceptual, hue-clockwise or hue-counterclockwise `method` on oltava classic, perceptual, hue-clockwise tai hue-counterclockwise @msg `spread` must be pad, repeat or reflect `spread` on oltava pad, repeat tai reflect @msg `repeats` must be a whole number from 1 to {MAX_REPEATS} `repeats` on oltava kokonaisluku väliltä 1–{MAX_REPEATS} @msg `spread` applies to linear, radial, conic and diamond gradients `spread` koskee lineaarisia, säteittäisiä ja kartiomaisia liukuvärejä sekä vinoneliöliukuvärejä @@ -6584,6 +6589,7 @@ axis Y Axis Y-akseli Continue Jatka Continue Action Jatka toimintoa Delete Action Step Poista toiminnon vaihe + Move Action Step Siirrä toiminnon vaihe Press Play Current Selection in the Actions panel to go on. Jatka valitsemalla Toiminnot-paneelista Toista nykyinen valinta. Stop: {message} Pysäytys: {message} @msg no action is waiting at a stop mikään toiminto ei odota pysäytyksessä @@ -6755,6 +6761,22 @@ axis Y Axis Y-akseli Graphite Pencil Grafiittikynä Wax Crayon Vahaliitu Charcoal Dust Hiilipöly + Notched Ribbon Lovettu nauha + Double Line Kaksoisviiva + Wave Aalto + Teardrop Pisara + Striped Ribbon Raidallinen nauha + Fine Nib Ohut kärki + Broad Nib Leveä kärki + Chisel Taltta + Round Pen Pyöreä kynä + Pressure Pen Painekynä + Beads Helmet + Dash Dot Viiva-piste + Scallops Kaarireunus + Stars Tähdet + Triangles Kolmiot + Sparkles Kipinät Save Brush Library… Tallenna sivellinkirjasto… @msg `{_1}` has no brushes to apply Kohteessa `{_1}` ei ole käytettäviä siveltimiä @msg missing `library` (see brush.libraries) `library` puuttuu (katso brush.libraries) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 96d6f7dd13..37399110f1 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4330,6 +4330,9 @@ axis Both Les deux @msg Couldn't open {name}: {e} Impossible d’ouvrir {name} : {e} @msg Couldn't place {name}: the document it was dropped on was closed Impossible d’importer {name} : le document sur lequel il a été déposé a été fermé @msg Couldn't place {name}: the document it was placed in was closed Impossible d’importer {name} : le document dans lequel il était importé a été fermé +@msg Couldn't place {name}: the document it was dropped on was reverted Impossible d’importer {name} : le document sur lequel il a été déposé a été rétabli à la version précédente +@msg Couldn't place {name}: the document it was placed in was reverted Impossible d’importer {name} : le document dans lequel il était importé a été rétabli à la version précédente +@msg Couldn't paste: the document it was pasted in was reverted Impossible de coller, car le document de destination a été rétabli à la version précédente @msg Couldn't read {name}: {e} Impossible de lire {name} : {e} @msg Couldn't save recovery data: {e} Impossible d’enregistrer les données de récupération : {e} @msg Create Outlines: select text objects Vectoriser : sélectionnez des objets texte @@ -5777,6 +5780,8 @@ lighting Light Lumière Pen Plume Pentagram Pentagramme Perceptual Perceptif + Hue Clockwise Teinte en sens horaire + Hue Counterclockwise Teinte en sens antihoraire Phone 360×800 Téléphone 360×800 Phone 375×667 Téléphone 375×667 Phone 375×812 Téléphone 375×812 @@ -6306,7 +6311,7 @@ axis Y Axis Axe Y @msg `dither` applies to gradient fills (stroke: false) `dither` s’applique aux fonds en dégradé (stroke: false) @msg `dither` applies to gradient fills (paint.setFill) `dither` s’applique aux fonds en dégradé (paint.setFill) @msg `dither` must be true or false `dither` doit valoir true ou false -@msg `method` must be classic or perceptual `method` doit être classic ou perceptual +@msg `method` must be classic, perceptual, hue-clockwise or hue-counterclockwise `method` doit être classic, perceptual, hue-clockwise ou hue-counterclockwise @msg `spread` must be pad, repeat or reflect `spread` doit être pad, repeat ou reflect @msg `repeats` must be a whole number from 1 to {MAX_REPEATS} `repeats` doit être un nombre entier de 1 à {MAX_REPEATS} @msg `spread` applies to linear, radial, conic and diamond gradients `spread` s’applique aux dégradés linéaires, radiaux, coniques et en losange @@ -6549,6 +6554,7 @@ axis Y Axis Axe Y Continue Continuer Continue Action Continuer le script Delete Action Step Supprimer l’étape du script + Move Action Step Déplacer l’étape du script Press Play Current Selection in the Actions panel to go on. Pour continuer, cliquez sur Exécuter la sélection actuelle dans le panneau Scripts. Stop: {message} Arrêt : {message} @msg no action is waiting at a stop aucun script n’attend à un arrêt @@ -6720,6 +6726,22 @@ axis Y Axis Axe Y Graphite Pencil Crayon graphite Wax Crayon Craie grasse Charcoal Dust Poussière de fusain + Notched Ribbon Ruban cranté + Double Line Double ligne + Wave Vague + Teardrop Goutte + Striped Ribbon Ruban rayé + Fine Nib Plume fine + Broad Nib Plume large + Chisel Ciseau + Round Pen Plume ronde + Pressure Pen Plume à pression + Beads Perles + Dash Dot Tiret-point + Scallops Festons + Stars Étoiles + Triangles Triangles + Sparkles Étincelles Save Brush Library… Enregistrer la bibliothèque de formes… @msg `{_1}` has no brushes to apply `{_1}` n'a aucune forme à appliquer @msg missing `library` (see brush.libraries) `library` manquant (voir brush.libraries) diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index b9401b2b77..f7c2dfc1d2 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -444,6 +444,22 @@ antiAlias Sharp शार्प Graphite Pencil ग्रेफाइट पेंसिल Wax Crayon मोम क्रेयॉन Charcoal Dust चारकोल धूल + Notched Ribbon नोकदार रिबन + Double Line दोहरी लाइन + Wave लहर + Teardrop आंसू की बूंद + Striped Ribbon धारीदार रिबन + Fine Nib बारीक निब + Broad Nib चौड़ी निब + Chisel छेनी + Round Pen गोल पेन + Pressure Pen प्रेशर पेन + Beads मोती + Dash Dot डैश डॉट + Scallops स्कैलप + Stars तारे + Triangles त्रिभुज + Sparkles चमक Art using a deleted global swatch keeps its colour. हटाए गए ग्लोबल स्वॉच वाला आर्टवर्क अपना रंग बनाए रखता है। Artboard आर्टबोर्ड Artboard {n} of {total} {total} में से आर्टबोर्ड {n} @@ -3412,6 +3428,8 @@ antiAlias Sharp शार्प per slice प्रति स्लाइस Percent: प्रतिशत: Perceptual परसेप्चुअल + Hue Clockwise ह्यू घड़ी की दिशा में + Hue Counterclockwise ह्यू घड़ी की विपरीत दिशा में Perceptual Scales अवधारणात्मक स्केल Performance प्रदर्शन Permissions अनुमतियां @@ -3480,6 +3498,7 @@ antiAlias Sharp शार्प Continue जारी रखें Continue Action एक्शन जारी रखें Delete Action Step एक्शन का चरण हटाएं + Move Action Step एक्शन का चरण खिसकाएं Press Play Current Selection in the Actions panel to go on. आगे बढ़ने के लिए एक्शन्स पैनल में वर्तमान सिलेक्शन प्ले करें दबाएँ। Stop: {message} स्टॉप: {message} @msg no action is waiting at a stop कोई एक्शन स्टॉप पर प्रतीक्षा नहीं कर रहा है @@ -6077,7 +6096,7 @@ antiAlias Sharp शार्प @msg `length` must be a number of at most 1000000 pt either way `length` को 1000000 pt में से एक होना चाहिए। @msg `library` is a library id or name (see {list}) `library` एक लाइब्रेरी आईडी या नाम है ( {list} देखें) @msg `line` must be true or false `line` को true या false होना चाहिए -@msg `method` must be classic or perceptual `method` क्लासिक या अवधारणात्मक होना चाहिए +@msg `method` must be classic, perceptual, hue-clockwise or hue-counterclockwise `method` classic, perceptual, hue-clockwise या hue-counterclockwise होना चाहिए @msg `spread` must be pad, repeat or reflect `spread` pad, repeat या reflect होना चाहिए @msg `repeats` must be a whole number from 1 to {MAX_REPEATS} `repeats` 1 से {MAX_REPEATS} तक की पूर्ण संख्या होनी चाहिए @msg `spread` applies to linear, radial, conic and diamond gradients `spread` रैखिक, रेडियल, शंक्वाकार और डायमंड ग्रेडिएंट्स पर लागू होता है @@ -6640,6 +6659,9 @@ antiAlias Sharp शार्प @msg Couldn't place {name}: {e} नहीं रह सकता {name}: {e} @msg Couldn't place {name}: the document it was dropped on was closed नहीं था {name}: यह डॉक्यूमेंट बंद हो गया था @msg Couldn't place {name}: the document it was placed in was closed नहीं था {name}: यह डॉक्यूमेंट बंद किया गया था +@msg Couldn't place {name}: the document it was dropped on was reverted {name} प्लेस नहीं कर सका: जिस डॉक्यूमेंट पर इसे छोड़ा गया था, उसे मूल स्थिति में लाया गया +@msg Couldn't place {name}: the document it was placed in was reverted {name} प्लेस नहीं कर सका: जिस डॉक्यूमेंट में इसे प्लेस किया जा रहा था, उसे मूल स्थिति में लाया गया +@msg Couldn't paste: the document it was pasted in was reverted पेस्ट नहीं कर सका: जिस डॉक्यूमेंट में पेस्ट किया जा रहा था, उसे मूल स्थिति में लाया गया @msg Couldn't read {name}: {e} नहीं पढ़ सकता {name}: {e} @msg Couldn't save recovery data: {e} रिकवरी डेटा सेव नहीं किया जा सका: {e} @msg counterPer `{c}`: item or file counterPer `{c}`: item या file diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 89b517cdb2..d349dece9f 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -3032,6 +3032,8 @@ file-filter Templates Sablonok per slice szeletenként Percent: Százalék: Perceptual Észlelési + Hue Clockwise Színárnyalat az óramutató járásával megegyezően + Hue Counterclockwise Színárnyalat az óramutató járásával ellentétesen Perceptual Scales Észlelési skálák Performance Teljesítmény diagnostics render renderelés @@ -5147,6 +5149,9 @@ imageTrace Outline Körvonal @msg Couldn't paste: the document it was pasted in was closed Nem sikerült beilleszteni: a dokumentumot, amelybe a beillesztés történt, bezárták @msg Couldn't place {name}: the document it was dropped on was closed Nem sikerült elhelyezni: {name}; a céldokumentumot bezárták @msg Couldn't place {name}: the document it was placed in was closed Nem sikerült elhelyezni: {name}; a dokumentumot, amelybe került volna, bezárták +@msg Couldn't place {name}: the document it was dropped on was reverted Nem sikerült elhelyezni: {name}; a céldokumentumot visszaállították a mentett változatra +@msg Couldn't place {name}: the document it was placed in was reverted Nem sikerült elhelyezni: {name}; a dokumentumot, amelybe került volna, visszaállították a mentett változatra +@msg Couldn't paste: the document it was pasted in was reverted Nem sikerült beilleszteni: a dokumentumot, amelybe a beillesztés történt, visszaállították a mentett változatra @msg Couldn't place {name}: {e} Nem sikerült elhelyezni: {name}: {e} @msg Couldn't read {name}: {e} Nem sikerült beolvasni: {name}: {e} @msg Couldn't save recovery data: {e} Nem sikerült menteni a helyreállítási adatokat: {e} @@ -6294,7 +6299,7 @@ axis Y Axis Y tengely @msg `dither` applies to gradient fills (stroke: false) A `dither` színátmenetes kitöltésekre vonatkozik (stroke: false) @msg `dither` applies to gradient fills (paint.setFill) A `dither` színátmenetes kitöltésekre vonatkozik (paint.setFill) @msg `dither` must be true or false `dither`: true vagy false kell -@msg `method` must be classic or perceptual a `method` értéke classic vagy perceptual lehet +@msg `method` must be classic, perceptual, hue-clockwise or hue-counterclockwise a `method` értéke classic, perceptual, hue-clockwise vagy hue-counterclockwise lehet @msg `spread` must be pad, repeat or reflect a `spread` értéke pad, repeat vagy reflect lehet @msg `repeats` must be a whole number from 1 to {MAX_REPEATS} a `repeats` értéke 1 és {MAX_REPEATS} közötti egész szám lehet @msg `spread` applies to linear, radial, conic and diamond gradients a `spread` a lineáris, sugaras, kúpos és rombusz színátmenetekre vonatkozik @@ -6537,6 +6542,7 @@ axis Y Axis Y tengely Continue Folytatás Continue Action Művelet folytatása Delete Action Step Műveletlépés törlése + Move Action Step Műveletlépés áthelyezése Press Play Current Selection in the Actions panel to go on. A folytatáshoz nyomja meg a Műveletek panelen a Kijelölt művelet lejátszása gombot. Stop: {message} Megállás: {message} @msg no action is waiting at a stop egyetlen művelet sem várakozik megállásnál @@ -6708,6 +6714,22 @@ axis Y Axis Y tengely Graphite Pencil Grafitceruza Wax Crayon Zsírkréta Charcoal Dust Szénpor + Notched Ribbon Csipkézett szalag + Double Line Dupla vonal + Wave Hullám + Teardrop Csepp + Striped Ribbon Csíkos szalag + Fine Nib Finom tollhegy + Broad Nib Széles tollhegy + Chisel Véső + Round Pen Kerek toll + Pressure Pen Nyomásérzékeny toll + Beads Gyöngyök + Dash Dot Pont-vonal + Scallops Hullámos szegély + Stars Csillagok + Triangles Háromszögek + Sparkles Szikrák Save Brush Library… Ecsetkönyvtár mentése… @msg `{_1}` has no brushes to apply A(z) `{_1}` nem tartalmaz alkalmazható ecsetet @msg missing `library` (see brush.libraries) hiányzik a `library` (lásd: brush.libraries) diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 543723217f..90f036bfd6 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -4246,6 +4246,9 @@ imageTrace Outline Kontur @msg Couldn't open {name}: {e} Tidak dapat membuka {name}: {e} @msg Couldn't place {name}: the document it was dropped on was closed Tidak dapat menempatkan {name}: dokumen tempatnya dijatuhkan sudah ditutup @msg Couldn't place {name}: the document it was placed in was closed Tidak dapat menempatkan {name}: dokumen tempatnya ditempatkan sudah ditutup +@msg Couldn't place {name}: the document it was dropped on was reverted Tidak dapat menempatkan {name}: dokumen tempatnya dijatuhkan sudah dikembalikan +@msg Couldn't place {name}: the document it was placed in was reverted Tidak dapat menempatkan {name}: dokumen tempatnya ditempatkan sudah dikembalikan +@msg Couldn't paste: the document it was pasted in was reverted Tidak dapat menempel: dokumen tempatnya ditempel sudah dikembalikan @msg Couldn't read {name}: {e} Tidak dapat membaca {name}: {e} @msg Couldn't save recovery data: {e} Tidak dapat menyimpan data pemulihan: {e} @msg Create Outlines: select text objects Buat kontur: pilih objek teks @@ -5177,6 +5180,8 @@ imageTrace Outline Kontur Vivid Cerah Spectrum Spektrum Perceptual Perseptual + Hue Clockwise Rona searah jarum jam + Hue Counterclockwise Rona berlawanan arah jarum jam Relative Colorimetric Kolorimetrik relatif Absolute Colorimetric Kolorimetrik absolut Exact Eksak @@ -5991,7 +5996,7 @@ axis Y Axis Sumbu Y @msg `dither` applies to gradient fills (stroke: false) `dither` berlaku untuk isian gradien (stroke: false) @msg `dither` applies to gradient fills (paint.setFill) `dither` berlaku untuk isian gradien (paint.setFill) @msg `dither` must be true or false `dither` harus true atau false -@msg `method` must be classic or perceptual `method` harus classic atau perceptual +@msg `method` must be classic, perceptual, hue-clockwise or hue-counterclockwise `method` harus classic, perceptual, hue-clockwise atau hue-counterclockwise # Heavy plug-in filters (plugin.inspect, plug-in runs) Install “{name}”, which asks for a heavy budget? Instal “{name}”, yang meminta anggaran komputasi besar? Each run may take up to {minutes} minutes and do {times} times the work other plug-ins may. It runs in the background, and you can cancel it. Setiap kali dijalankan, plug-in ini bisa memakan waktu hingga {minutes} menit dan melakukan {times} kali pekerjaan yang diizinkan untuk plug-in lain. Plug-in ini berjalan di latar belakang, dan Anda dapat membatalkannya. @@ -6032,6 +6037,7 @@ axis Y Axis Sumbu Y Continue Lanjutkan Continue Action Lanjutkan tindakan Delete Action Step Hapus langkah tindakan + Move Action Step Pindahkan langkah tindakan Press Play Current Selection in the Actions panel to go on. Untuk melanjutkan, tekan Putar seleksi saat ini di panel Tindakan. Stop: {message} Henti: {message} @msg no action is waiting at a stop tidak ada tindakan yang menunggu di titik henti @@ -6192,6 +6198,22 @@ axis Y Axis Sumbu Y Graphite Pencil Pensil grafit Wax Crayon Krayon lilin Charcoal Dust Debu arang + Notched Ribbon Pita bertakik + Double Line Garis ganda + Wave Gelombang + Teardrop Tetesan + Striped Ribbon Pita bergaris + Fine Nib Mata pena halus + Broad Nib Mata pena lebar + Chisel Pahat + Round Pen Pena bulat + Pressure Pen Pena tekanan + Beads Manik-manik + Dash Dot Garis titik + Scallops Lekuk kerang + Stars Bintang + Triangles Segitiga + Sparkles Kilauan Save Brush Library… Simpan pustaka kuas… @msg no empty artboards to delete tidak ada artboard kosong untuk dihapus Scale Presets Preset skala diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 2b17326766..feafcc94d8 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4393,6 +4393,9 @@ axis Both Entrambi @msg Couldn't open {name}: {e} Impossibile aprire {name}: {e} @msg Couldn't place {name}: the document it was dropped on was closed Impossibile inserire {name}: il documento su cui è stato rilasciato è stato chiuso @msg Couldn't place {name}: the document it was placed in was closed Impossibile inserire {name}: il documento in cui veniva inserito è stato chiuso +@msg Couldn't place {name}: the document it was dropped on was reverted Impossibile inserire {name}: il documento su cui è stato rilasciato è stato ripristinato +@msg Couldn't place {name}: the document it was placed in was reverted Impossibile inserire {name}: il documento in cui veniva inserito è stato ripristinato +@msg Couldn't paste: the document it was pasted in was reverted Impossibile incollare: il documento in cui si incollava è stato ripristinato @msg Couldn't read {name}: {e} Impossibile leggere {name}: {e} @msg Couldn't save recovery data: {e} Impossibile salvare i dati di recupero: {e} @msg Create Outlines: select text objects Crea contorni: seleziona oggetti di testo @@ -5937,7 +5940,9 @@ axis Y Axis Asse Y @msg `dither` applies to gradient fills (paint.setFill) `dither` si applica ai riempimenti sfumati (paint.setFill) @msg `dither` must be true or false `dither` deve essere true o false Perceptual Percettivo -@msg `method` must be classic or perceptual `method` deve essere classic o perceptual + Hue Clockwise Tonalità in senso orario + Hue Counterclockwise Tonalità in senso antiorario +@msg `method` must be classic, perceptual, hue-clockwise or hue-counterclockwise `method` deve essere classic, perceptual, hue-clockwise o hue-counterclockwise @msg `spread` must be pad, repeat or reflect `spread` deve essere pad, repeat o reflect @msg `repeats` must be a whole number from 1 to {MAX_REPEATS} `repeats` deve essere un numero intero da 1 a {MAX_REPEATS} @msg `spread` applies to linear, radial, conic and diamond gradients `spread` si applica alle sfumature lineari, radiali, coniche e a rombo @@ -6180,6 +6185,7 @@ axis Y Axis Asse Y Continue Continua Continue Action Continua azione Delete Action Step Elimina passaggio dell’azione + Move Action Step Sposta passaggio dell’azione Press Play Current Selection in the Actions panel to go on. Per continuare, premi Esegui selezione corrente nel pannello Azioni. Stop: {message} Interruzione: {message} @msg no action is waiting at a stop nessuna azione è in attesa a un'interruzione @@ -6351,6 +6357,22 @@ axis Y Axis Asse Y Graphite Pencil Matita di grafite Wax Crayon Pastello a cera Charcoal Dust Polvere di carboncino + Notched Ribbon Nastro dentellato + Double Line Doppia linea + Wave Onda + Teardrop Goccia + Striped Ribbon Nastro a righe + Fine Nib Pennino fine + Broad Nib Pennino largo + Chisel Scalpello + Round Pen Penna tonda + Pressure Pen Penna a pressione + Beads Perline + Dash Dot Tratto-punto + Scallops Smerlo + Stars Stelle + Triangles Triangoli + Sparkles Scintille Save Brush Library… Salva libreria pennelli… @msg `{_1}` has no brushes to apply `{_1}` non ha pennelli da applicare @msg missing `library` (see brush.libraries) manca `library` (vedi brush.libraries) diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 3d71e2eb0e..2d87f8914f 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5182,6 +5182,9 @@ swatch Bright Violet ビビッドバイオレット @msg no user library folder here この環境にはユーザーライブラリフォルダーがありません @msg Couldn't place {name}: the document it was dropped on was closed {name} を配置できませんでした: ドロップ先のドキュメントは閉じられています @msg Couldn't place {name}: the document it was placed in was closed {name} を配置できませんでした: 配置先のドキュメントは閉じられています +@msg Couldn't place {name}: the document it was dropped on was reverted {name} を配置できませんでした: ドロップ先のドキュメントは保存済みの状態に戻されました +@msg Couldn't place {name}: the document it was placed in was reverted {name} を配置できませんでした: 配置先のドキュメントは保存済みの状態に戻されました +@msg Couldn't paste: the document it was pasted in was reverted 貼り付けられませんでした: 貼り付け先のドキュメントは保存済みの状態に戻されました @msg no files to place 配置するファイルがありません @msg `{file}` isn't a VectorCraft document, a PDF or a PDF-compatible .ai file `{file}` は VectorCraft ドキュメント、PDF、PDF 互換の .ai ファイルのいずれでもありません @msg paths: give at least one file paths: ファイルを 1 つ以上指定してください @@ -6003,7 +6006,9 @@ axis Y Axis Y 軸 @msg `dither` applies to gradient fills (paint.setFill) `dither` はグラデーションの塗りに適用されます (paint.setFill) @msg `dither` must be true or false `dither` には true または false を指定してください Perceptual 知覚的 -@msg `method` must be classic or perceptual `method` には classic または perceptual を指定してください + Hue Clockwise 時計回りの色相 + Hue Counterclockwise 反時計回りの色相 +@msg `method` must be classic, perceptual, hue-clockwise or hue-counterclockwise `method` には classic、perceptual、hue-clockwise または hue-counterclockwise を指定してください @msg `spread` must be pad, repeat or reflect `spread` には pad、repeat または reflect を指定してください @msg `repeats` must be a whole number from 1 to {MAX_REPEATS} `repeats` には 1 から {MAX_REPEATS} までの整数を指定してください @msg `spread` applies to linear, radial, conic and diamond gradients `spread` は線形、円形、円錐およびひし形グラデーションに適用されます @@ -6246,6 +6251,7 @@ axis Y Axis Y 軸 Continue 続行 Continue Action アクションを続行 Delete Action Step アクションステップを削除 + Move Action Step アクションステップを移動 Press Play Current Selection in the Actions panel to go on. 続行するには、アクションパネルの「選択項目を再生」を押します。 Stop: {message} 停止: {message} @msg no action is waiting at a stop 停止で待機中のアクションはありません @@ -6417,6 +6423,22 @@ axis Y Axis Y 軸 Graphite Pencil 黒鉛鉛筆 Wax Crayon ワックスクレヨン Charcoal Dust 木炭の粉 + Notched Ribbon ノッチリボン + Double Line 二重線 + Wave 波 + Teardrop しずく + Striped Ribbon ストライプリボン + Fine Nib 細いペン先 + Broad Nib 太いペン先 + Chisel 平ノミ + Round Pen 丸ペン + Pressure Pen 筆圧ペン + Beads ビーズ + Dash Dot 一点鎖線 + Scallops スカラップ + Stars 星 + Triangles 三角形 + Sparkles きらめき Save Brush Library… ブラシライブラリを保存… @msg `{_1}` has no brushes to apply `{_1}` に適用できるブラシがありません @msg missing `library` (see brush.libraries) `library` がありません (brush.libraries を参照) diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 0c228dfb32..03f9f9e773 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -4045,6 +4045,9 @@ font-technology Variable ცვლადი @msg Couldn't open {name}: {e} {name} ვერ გაიხსნა: {e} @msg Couldn't place {name}: the document it was dropped on was closed {name} ვერ განთავსდა: დოკუმენტი, რომელზეც ის ჩამოაგდეს, დაიხურა @msg Couldn't place {name}: the document it was placed in was closed {name} ვერ განთავსდა: დოკუმენტი, რომელშიც ის თავსდებოდა, დაიხურა +@msg Couldn't place {name}: the document it was dropped on was reverted {name} ვერ განთავსდა: დოკუმენტი, რომელზეც ის ჩამოაგდეს, წინა ვერსიაზე დაბრუნდა +@msg Couldn't place {name}: the document it was placed in was reverted {name} ვერ განთავსდა: დოკუმენტი, რომელშიც ის თავსდებოდა, წინა ვერსიაზე დაბრუნდა +@msg Couldn't paste: the document it was pasted in was reverted ჩასმა ვერ მოხერხდა: დოკუმენტი, რომელშიც ის ჩაისმებოდა, წინა ვერსიაზე დაბრუნდა @msg Couldn't read {name}: {e} {name} ვერ წაიკითხა: {e} @msg Couldn't save recovery data: {e} აღდგენის მონაცემები ვერ შეინახა: {e} @msg Create Outlines: select text objects კონტურების შექმნა: მონიშნეთ ტექსტური ობიექტები @@ -5025,6 +5028,8 @@ font-technology Variable ცვლადი High Contrast 3 მაღალი კონტრასტი 3 Pentagram პენტაგრამა Perceptual აღქმითი + Hue Clockwise ფერის ტონი საათის ისრის მიმართულებით + Hue Counterclockwise ფერის ტონი საათის ისრის საწინააღმდეგოდ Relative Colorimetric ფარდობითი კოლორიმეტრიული Absolute Colorimetric აბსოლუტური კოლორიმეტრიული Exact ზუსტი @@ -6262,7 +6267,7 @@ axis Y Axis Y ღერძი @msg `dither` applies to gradient fills (stroke: false) `dither` ვრცელდება გრადიენტულ შევსებებზე (stroke: false) @msg `dither` applies to gradient fills (paint.setFill) `dither` ვრცელდება გრადიენტულ შევსებებზე (paint.setFill) @msg `dither` must be true or false `dither` უნდა იყოს true ან false -@msg `method` must be classic or perceptual `method` უნდა იყოს classic ან perceptual +@msg `method` must be classic, perceptual, hue-clockwise or hue-counterclockwise `method` უნდა იყოს classic, perceptual, hue-clockwise ან hue-counterclockwise @msg `spread` must be pad, repeat or reflect `spread` უნდა იყოს pad, repeat ან reflect @msg `repeats` must be a whole number from 1 to {MAX_REPEATS} `repeats` უნდა იყოს მთელი რიცხვი 1-დან {MAX_REPEATS}-მდე @msg `spread` applies to linear, radial, conic and diamond gradients `spread` ეხება წრფივ, რადიალურ, კონუსურ და რომბულ გრადიენტებს @@ -6505,6 +6510,7 @@ axis Y Axis Y ღერძი Continue გაგრძელება Continue Action მოქმედების გაგრძელება Delete Action Step მოქმედების ნაბიჯის წაშლა + Move Action Step მოქმედების ნაბიჯის გადატანა Press Play Current Selection in the Actions panel to go on. გასაგრძელებლად მოქმედებების პანელზე დააჭირეთ „მიმდინარე მონიშნულის შესრულებას“. Stop: {message} გაჩერება: {message} @msg no action is waiting at a stop გაჩერებაზე არცერთი მოქმედება არ ელოდება @@ -6676,6 +6682,22 @@ axis Y Axis Y ღერძი Graphite Pencil გრაფიტის ფანქარი Wax Crayon ცვილის ფანქარი Charcoal Dust ნახშირის მტვერი + Notched Ribbon დაკბილული ლენტი + Double Line ორმაგი ხაზი + Wave ტალღა + Teardrop წვეთი + Striped Ribbon ზოლიანი ლენტი + Fine Nib წვრილი წვერი + Broad Nib განიერი წვერი + Chisel საჭრეთელი + Round Pen მრგვალი კალამი + Pressure Pen დაწოლის კალამი + Beads მძივები + Dash Dot ტირე-წერტილი + Scallops ფესტონები + Stars ვარსკვლავები + Triangles სამკუთხედები + Sparkles ნაპერწკლები Save Brush Library… ფუნჯების ბიბლიოთეკის შენახვა… @msg `{_1}` has no brushes to apply `{_1}`-ში გამოსაყენებელი ფუნჯები არ არის @msg missing `library` (see brush.libraries) `library` აკლია (იხ. brush.libraries) diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 53b8b5ed47..c682411364 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5109,6 +5109,9 @@ theme Appearance 외관 @msg no user library folder here 여기에는 사용자 라이브러리 폴더가 없습니다 @msg Couldn't place {name}: the document it was dropped on was closed {name}을(를) 가져올 수 없습니다: 놓은 문서가 닫혔습니다 @msg Couldn't place {name}: the document it was placed in was closed {name}을(를) 가져올 수 없습니다: 가져오던 문서가 닫혔습니다 +@msg Couldn't place {name}: the document it was dropped on was reverted {name}을(를) 가져올 수 없습니다: 놓은 문서가 되돌려졌습니다 +@msg Couldn't place {name}: the document it was placed in was reverted {name}을(를) 가져올 수 없습니다: 가져오던 문서가 되돌려졌습니다 +@msg Couldn't paste: the document it was pasted in was reverted 붙여넣을 수 없습니다: 붙여넣던 문서가 되돌려졌습니다 @msg no files to place 가져올 파일이 없습니다 @msg `{file}` isn't a VectorCraft document, a PDF or a PDF-compatible .ai file `{file}`은(는) VectorCraft 문서, PDF 또는 PDF 호환 .ai 파일이 아닙니다 @msg paths: give at least one file paths: 파일을 하나 이상 지정하세요 @@ -5898,7 +5901,9 @@ axis Y Axis Y축 @msg `dither` applies to gradient fills (paint.setFill) `dither`는 그레이디언트 칠에 적용됩니다 (paint.setFill) @msg `dither` must be true or false `dither`은(는) true 또는 false여야 합니다 Perceptual 지각적 -@msg `method` must be classic or perceptual `method`는 classic 또는 perceptual이어야 합니다 + Hue Clockwise 색조 시계 방향 + Hue Counterclockwise 색조 시계 반대 방향 +@msg `method` must be classic, perceptual, hue-clockwise or hue-counterclockwise `method`는 classic, perceptual, hue-clockwise 또는 hue-counterclockwise여야 합니다 @msg `spread` must be pad, repeat or reflect `spread`는 pad, repeat 또는 reflect여야 합니다 @msg `repeats` must be a whole number from 1 to {MAX_REPEATS} `repeats`는 1에서 {MAX_REPEATS} 사이의 정수여야 합니다 @msg `spread` applies to linear, radial, conic and diamond gradients `spread`는 선형, 방사형, 원뿔형 및 다이아몬드 그레이디언트에 적용됩니다 @@ -6141,6 +6146,7 @@ axis Y Axis Y축 Continue 계속 Continue Action 액션 계속 Delete Action Step 액션 단계 삭제 + Move Action Step 액션 단계 이동 Press Play Current Selection in the Actions panel to go on. 계속하려면 액션 패널에서 현재 선택 항목 재생을 누르세요. Stop: {message} 중지: {message} @msg no action is waiting at a stop 중지에서 대기 중인 액션이 없습니다 @@ -6312,6 +6318,22 @@ axis Y Axis Y축 Graphite Pencil 흑연 연필 Wax Crayon 왁스 크레용 Charcoal Dust 목탄 가루 + Notched Ribbon 노치 리본 + Double Line 이중선 + Wave 물결 + Teardrop 눈물방울 + Striped Ribbon 줄무늬 리본 + Fine Nib 가는 펜촉 + Broad Nib 넓은 펜촉 + Chisel 끌 + Round Pen 둥근 펜 + Pressure Pen 필압 펜 + Beads 구슬 + Dash Dot 일점쇄선 + Scallops 스캘럽 + Stars 별 + Triangles 삼각형 + Sparkles 반짝임 Save Brush Library… 브러시 라이브러리 저장… @msg `{_1}` has no brushes to apply `{_1}`에 적용할 브러시가 없습니다 @msg missing `library` (see brush.libraries) `library`가 없습니다(brush.libraries 참조) diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index d38e0c113f..3d2b7a1dc4 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -4762,6 +4762,9 @@ imageTrace Outline Contour @msg Couldn't open {name}: {e} Kon {name} niet openen: {e} @msg Couldn't place {name}: the document it was dropped on was closed Kon {name} niet plaatsen: het document waarop het werd neergezet, is gesloten @msg Couldn't place {name}: the document it was placed in was closed Kon {name} niet plaatsen: het document waarin het werd geplaatst, is gesloten +@msg Couldn't place {name}: the document it was dropped on was reverted Kon {name} niet plaatsen: het document waarop het werd neergezet, is teruggezet +@msg Couldn't place {name}: the document it was placed in was reverted Kon {name} niet plaatsen: het document waarin het werd geplaatst, is teruggezet +@msg Couldn't paste: the document it was pasted in was reverted Kon niet plakken: het document waarin werd geplakt, is teruggezet @msg Couldn't read {name}: {e} Kon {name} niet lezen: {e} @msg Couldn't save recovery data: {e} Kon herstelgegevens niet opslaan: {e} @msg Create Outlines: select text objects Contouren maken: selecteer tekstobjecten @@ -5693,6 +5696,8 @@ imageTrace Outline Contour Vivid Levendig Spectrum Spectrum Perceptual Perceptueel + Hue Clockwise Tint met de klok mee + Hue Counterclockwise Tint tegen de klok in Relative Colorimetric Relatief colorimetrisch Absolute Colorimetric Absoluut colorimetrisch Exact Exact @@ -6608,7 +6613,7 @@ axis Y Axis Y-as @msg `dither` applies to gradient fills (stroke: false) `dither` geldt voor verloopvullingen (stroke: false) @msg `dither` applies to gradient fills (paint.setFill) `dither` geldt voor verloopvullingen (paint.setFill) @msg `dither` must be true or false `dither` moet true of false zijn -@msg `method` must be classic or perceptual `method` moet classic of perceptual zijn +@msg `method` must be classic, perceptual, hue-clockwise or hue-counterclockwise `method` moet classic, perceptual, hue-clockwise of hue-counterclockwise zijn # Heavy plug-in filters (plugin.inspect, plug-in runs) Install “{name}”, which asks for a heavy budget? „{name}” installeren, dat om een groot rekenbudget vraagt? Each run may take up to {minutes} minutes and do {times} times the work other plug-ins may. It runs in the background, and you can cancel it. Elke run kan tot {minutes} minuten duren en {times} keer zoveel werk doen als andere plug-ins mogen. Hij draait op de achtergrond en je kunt hem annuleren. @@ -6649,6 +6654,7 @@ axis Y Axis Y-as Continue Doorgaan Continue Action Actie voortzetten Delete Action Step Actiestap verwijderen + Move Action Step Actiestap verplaatsen Press Play Current Selection in the Actions panel to go on. Druk in het paneel Acties op Huidige selectie afspelen om door te gaan. Stop: {message} Stop: {message} @msg no action is waiting at a stop geen actie wacht bij een stop @@ -6809,6 +6815,22 @@ axis Y Axis Y-as Graphite Pencil Grafietpotlood Wax Crayon Waskrijt Charcoal Dust Houtskoolstof + Notched Ribbon Gekerfd lint + Double Line Dubbele lijn + Wave Golf + Teardrop Traan + Striped Ribbon Gestreept lint + Fine Nib Fijne penpunt + Broad Nib Brede penpunt + Chisel Beitel + Round Pen Ronde pen + Pressure Pen Drukpen + Beads Kralen + Dash Dot Streep-punt + Scallops Schulprand + Stars Sterren + Triangles Driehoeken + Sparkles Fonkelingen Save Brush Library… Penseelbibliotheek opslaan… @msg no empty artboards to delete geen lege tekengebieden om te verwijderen Scale Presets Schaalvoorinstellingen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 0ae5431a81..6be55a4fa7 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4475,6 +4475,9 @@ imageTrace Outline Kontur @msg Couldn't open {name}: {e} Nie udało się otworzyć {name}: {e} @msg Couldn't place {name}: the document it was dropped on was closed Nie udało się umieścić {name}: dokument, na który go upuszczono, został zamknięty @msg Couldn't place {name}: the document it was placed in was closed Nie udało się umieścić {name}: dokument, w którym był umieszczany, został zamknięty +@msg Couldn't place {name}: the document it was dropped on was reverted Nie udało się umieścić {name}: dokument, na który go upuszczono, został przywrócony +@msg Couldn't place {name}: the document it was placed in was reverted Nie udało się umieścić {name}: dokument, w którym był umieszczany, został przywrócony +@msg Couldn't paste: the document it was pasted in was reverted Nie udało się wkleić: dokument, do którego wklejano, został przywrócony @msg Couldn't read {name}: {e} Nie udało się odczytać {name}: {e} @msg Couldn't save recovery data: {e} Nie udało się zapisać danych odzyskiwania: {e} @msg Create Outlines: select text objects Utwórz kontury: zaznacz obiekty tekstowe @@ -5566,6 +5569,8 @@ imageTrace Outline Kontur High Contrast 3 Wysoki kontrast 3 Pentagram Pentagram Perceptual Percepcyjna + Hue Clockwise Barwa zgodnie z ruchem wskazówek zegara + Hue Counterclockwise Barwa przeciwnie do ruchu wskazówek zegara Relative Colorimetric Kolorymetryczna względna Absolute Colorimetric Kolorymetryczna bezwzględna Exact Dokładne @@ -6166,7 +6171,7 @@ axis Y Axis Oś Y @msg `dither` applies to gradient fills (stroke: false) `dither` dotyczy wypełnień gradientem (stroke: false) @msg `dither` applies to gradient fills (paint.setFill) `dither` dotyczy wypełnień gradientem (paint.setFill) @msg `dither` must be true or false `dither` musi mieć wartość true lub false -@msg `method` must be classic or perceptual `method` musi mieć wartość classic lub perceptual +@msg `method` must be classic, perceptual, hue-clockwise or hue-counterclockwise `method` musi mieć wartość classic, perceptual, hue-clockwise lub hue-counterclockwise @msg `spread` must be pad, repeat or reflect `spread` musi mieć wartość pad, repeat lub reflect @msg `repeats` must be a whole number from 1 to {MAX_REPEATS} `repeats` musi być liczbą całkowitą od 1 do {MAX_REPEATS} @msg `spread` applies to linear, radial, conic and diamond gradients `spread` dotyczy gradientów liniowych, radialnych, stożkowych i rombowych @@ -6409,6 +6414,7 @@ axis Y Axis Oś Y Continue Kontynuuj Continue Action Kontynuuj operację Delete Action Step Usuń krok operacji + Move Action Step Przenieś krok operacji Press Play Current Selection in the Actions panel to go on. Aby kontynuować, naciśnij Odtwórz bieżące zaznaczenie w panelu Operacje. Stop: {message} Zatrzymanie: {message} @msg no action is waiting at a stop żadna operacja nie czeka na zatrzymaniu @@ -6580,6 +6586,22 @@ axis Y Axis Oś Y Graphite Pencil Ołówek grafitowy Wax Crayon Kredka woskowa Charcoal Dust Pył węglowy + Notched Ribbon Wstęga z nacięciami + Double Line Podwójna linia + Wave Fala + Teardrop Łza + Striped Ribbon Wstęga w paski + Fine Nib Cienka stalówka + Broad Nib Szeroka stalówka + Chisel Dłuto + Round Pen Okrągłe pióro + Pressure Pen Pióro z naciskiem + Beads Koraliki + Dash Dot Kreska-kropka + Scallops Feston + Stars Gwiazdy + Triangles Trójkąty + Sparkles Iskry Save Brush Library… Zapisz bibliotekę pędzli… @msg `{_1}` has no brushes to apply `{_1}` nie ma pędzli do zastosowania @msg missing `library` (see brush.libraries) brak `library` (zobacz brush.libraries) diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 854894cb68..f923f46e81 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -3810,6 +3810,9 @@ axis Both Ambos @msg Couldn't open {name}: {e} Não foi possível abrir {name}: {e} @msg Couldn't place {name}: the document it was dropped on was closed Não foi possível inserir {name}: o documento em que foi solto foi fechado @msg Couldn't place {name}: the document it was placed in was closed Não foi possível inserir {name}: o documento em que estava sendo inserido foi fechado +@msg Couldn't place {name}: the document it was dropped on was reverted Não foi possível inserir {name}: o documento em que foi solto foi revertido +@msg Couldn't place {name}: the document it was placed in was reverted Não foi possível inserir {name}: o documento em que estava sendo inserido foi revertido +@msg Couldn't paste: the document it was pasted in was reverted Não foi possível colar: o documento em que estava sendo colado foi revertido @msg Couldn't read {name}: {e} Não foi possível ler {name}: {e} @msg Couldn't save recovery data: {e} Não foi possível salvar os dados de recuperação: {e} @msg Create Outlines: select text objects Criar contornos: selecione objetos de texto @@ -5641,6 +5644,8 @@ effect Regular Regular High Contrast 3 Alto Contraste 3 Pentagram Pentagrama Perceptual Perceptual + Hue Clockwise Tom em sentido horário + Hue Counterclockwise Tom em sentido anti-horário Relative Colorimetric Colorimétrico Relativo Absolute Colorimetric Colorimétrico Absoluto Exact Exato @@ -6226,7 +6231,7 @@ axis Y Axis Eixo Y @msg `dither` applies to gradient fills (stroke: false) `dither` se aplica a preenchimentos em gradiente (stroke: false) @msg `dither` applies to gradient fills (paint.setFill) `dither` se aplica a preenchimentos em gradiente (paint.setFill) @msg `dither` must be true or false `dither` deve ser true ou false -@msg `method` must be classic or perceptual `method` deve ser classic ou perceptual +@msg `method` must be classic, perceptual, hue-clockwise or hue-counterclockwise `method` deve ser classic, perceptual, hue-clockwise ou hue-counterclockwise @msg `spread` must be pad, repeat or reflect `spread` deve ser pad, repeat ou reflect @msg `repeats` must be a whole number from 1 to {MAX_REPEATS} `repeats` deve ser um número inteiro de 1 a {MAX_REPEATS} @msg `spread` applies to linear, radial, conic and diamond gradients `spread` se aplica a gradientes lineares, radiais, cônicos e em losango @@ -6469,6 +6474,7 @@ axis Y Axis Eixo Y Continue Continuar Continue Action Continuar Ação Delete Action Step Excluir Etapa da Ação + Move Action Step Mover Etapa da Ação Press Play Current Selection in the Actions panel to go on. Para continuar, pressione Reproduzir Seleção Atual no painel Ações. Stop: {message} Parada: {message} @msg no action is waiting at a stop nenhuma ação está aguardando em uma parada @@ -6640,6 +6646,22 @@ axis Y Axis Eixo Y Graphite Pencil Lápis de Grafite Wax Crayon Giz de Cera Charcoal Dust Pó de Carvão + Notched Ribbon Fita Entalhada + Double Line Linha Dupla + Wave Onda + Teardrop Lágrima + Striped Ribbon Fita Listrada + Fine Nib Pena Fina + Broad Nib Pena Larga + Chisel Cinzel + Round Pen Pena Redonda + Pressure Pen Pena de Pressão + Beads Contas + Dash Dot Traço-Ponto + Scallops Festões + Stars Estrelas + Triangles Triângulos + Sparkles Brilhos Save Brush Library… Salvar Biblioteca de Pincéis… @msg `{_1}` has no brushes to apply `{_1}` não tem pincéis para aplicar @msg missing `library` (see brush.libraries) falta `library` (consulte brush.libraries) diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 9af5f4ceb9..bcdcdd0989 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4378,6 +4378,9 @@ axis Both Оба @msg Couldn't open {name}: {e} Не удалось открыть {name}: {e} @msg Couldn't place {name}: the document it was dropped on was closed Не удалось поместить {name}: документ, в который его перетащили, был закрыт @msg Couldn't place {name}: the document it was placed in was closed Не удалось поместить {name}: документ, в который его помещали, был закрыт +@msg Couldn't place {name}: the document it was dropped on was reverted Не удалось поместить {name}: документ, в который его перетащили, был возвращён к сохранённой версии +@msg Couldn't place {name}: the document it was placed in was reverted Не удалось поместить {name}: документ, в который его помещали, был возвращён к сохранённой версии +@msg Couldn't paste: the document it was pasted in was reverted Не удалось вставить: документ, в который выполнялась вставка, был возвращён к сохранённой версии @msg Couldn't read {name}: {e} Не удалось прочитать {name}: {e} @msg Couldn't save recovery data: {e} Не удалось сохранить данные восстановления: {e} @msg Create Outlines: select text objects Создание контуров: выделите текстовые объекты @@ -5922,7 +5925,9 @@ axis Y Axis Ось Y @msg `dither` applies to gradient fills (paint.setFill) `dither` применяется к градиентным заливкам (paint.setFill) @msg `dither` must be true or false `dither` должно быть true или false Perceptual Перцепционный -@msg `method` must be classic or perceptual `method` должен быть classic или perceptual + Hue Clockwise Оттенок по часовой стрелке + Hue Counterclockwise Оттенок против часовой стрелки +@msg `method` must be classic, perceptual, hue-clockwise or hue-counterclockwise `method` должен быть classic, perceptual, hue-clockwise или hue-counterclockwise @msg `spread` must be pad, repeat or reflect `spread` должен быть pad, repeat или reflect @msg `repeats` must be a whole number from 1 to {MAX_REPEATS} `repeats` должен быть целым числом от 1 до {MAX_REPEATS} @msg `spread` applies to linear, radial, conic and diamond gradients `spread` применяется к линейным, радиальным, коническим и ромбовидным градиентам @@ -6165,6 +6170,7 @@ axis Y Axis Ось Y Continue Продолжить Continue Action Продолжить действие Delete Action Step Удалить шаг действия + Move Action Step Переместить шаг действия Press Play Current Selection in the Actions panel to go on. Чтобы продолжить, нажмите «Воспроизвести текущее выделение» на панели «Действия». Stop: {message} Остановка: {message} @msg no action is waiting at a stop ни одно действие не ожидает на остановке @@ -6336,6 +6342,22 @@ axis Y Axis Ось Y Graphite Pencil Графитный карандаш Wax Crayon Восковой мелок Charcoal Dust Угольная пыль + Notched Ribbon Лента с насечками + Double Line Двойная линия + Wave Волна + Teardrop Капля + Striped Ribbon Полосатая лента + Fine Nib Тонкое перо + Broad Nib Широкое перо + Chisel Стамеска + Round Pen Круглое перо + Pressure Pen Перо с нажимом + Beads Бусины + Dash Dot Штрихпунктир + Scallops Фестоны + Stars Звёзды + Triangles Треугольники + Sparkles Искры Save Brush Library… Сохранить библиотеку кистей… @msg `{_1}` has no brushes to apply В `{_1}` нет кистей для применения @msg missing `library` (see brush.libraries) не указан `library` (см. brush.libraries) diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 7c9d977648..1091182cf1 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4251,6 +4251,9 @@ axis Both Båda @msg Couldn't open {name}: {e} Kunde inte öppna {name}: {e} @msg Couldn't place {name}: the document it was dropped on was closed Kunde inte placera {name}: dokumentet det släpptes på har stängts @msg Couldn't place {name}: the document it was placed in was closed Kunde inte placera {name}: dokumentet det placerades i har stängts +@msg Couldn't place {name}: the document it was dropped on was reverted Kunde inte placera {name}: dokumentet det släpptes på har återgått till sparad version +@msg Couldn't place {name}: the document it was placed in was reverted Kunde inte placera {name}: dokumentet det placerades i har återgått till sparad version +@msg Couldn't paste: the document it was pasted in was reverted Kunde inte klistra in: dokumentet det klistrades in i har återgått till sparad version @msg Couldn't read {name}: {e} Kunde inte läsa {name}: {e} @msg Couldn't save recovery data: {e} Kunde inte spara återställningsdata: {e} @msg Create Outlines: select text objects Skapa konturer: markera textobjekt @@ -5677,6 +5680,8 @@ lighting Light Ljus Pen Penna Pentagram Pentagram Perceptual Perceptuell + Hue Clockwise Nyans medurs + Hue Counterclockwise Nyans moturs Phone 360×800 Telefon 360×800 Phone 375×667 Telefon 375×667 Phone 375×812 Telefon 375×812 @@ -6333,7 +6338,7 @@ axis Y Axis Y-axel @msg `dither` applies to gradient fills (stroke: false) `dither` gäller gradientfyllningar (stroke: false) @msg `dither` applies to gradient fills (paint.setFill) `dither` gäller gradientfyllningar (paint.setFill) @msg `dither` must be true or false `dither` måste vara true eller false -@msg `method` must be classic or perceptual `method` måste vara classic eller perceptual +@msg `method` must be classic, perceptual, hue-clockwise or hue-counterclockwise `method` måste vara classic, perceptual, hue-clockwise eller hue-counterclockwise @msg `spread` must be pad, repeat or reflect `spread` måste vara pad, repeat eller reflect @msg `repeats` must be a whole number from 1 to {MAX_REPEATS} `repeats` måste vara ett heltal från 1 till {MAX_REPEATS} @msg `spread` applies to linear, radial, conic and diamond gradients `spread` gäller för linjära, radiella och koniska gradienter och rombgradienter @@ -6535,6 +6540,7 @@ axis Y Axis Y-axel Continue Fortsätt Continue Action Fortsätt åtgärd Delete Action Step Radera åtgärdssteg + Move Action Step Flytta åtgärdssteg Press Play Current Selection in the Actions panel to go on. Fortsätt genom att trycka på Spela upp aktuell markering i panelen Åtgärder. Stop: {message} Stopp: {message} @msg no action is waiting at a stop ingen åtgärd väntar vid ett stopp @@ -6706,6 +6712,22 @@ axis Y Axis Y-axel Graphite Pencil Grafitpenna Wax Crayon Vaxkrita Charcoal Dust Koldamm + Notched Ribbon Hackat band + Double Line Dubbellinje + Wave Våg + Teardrop Droppe + Striped Ribbon Randigt band + Fine Nib Fin spets + Broad Nib Bred spets + Chisel Mejsel + Round Pen Rund penna + Pressure Pen Tryckpenna + Beads Pärlor + Dash Dot Streck-punkt + Scallops Bågkant + Stars Stjärnor + Triangles Trianglar + Sparkles Gnistor Save Brush Library… Spara penselbibliotek… @msg `{_1}` has no brushes to apply `{_1}` har inga penslar att använda @msg missing `library` (see brush.libraries) `library` saknas (se brush.libraries) diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index a18f4d1a58..4ac03011ac 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -268,6 +268,30 @@ fn built_in_brush_library_names_are_in_complete_catalogs() { assert!(bad.is_empty(), "{}", bad.join("\n")); } +/// A built-in brush library's panel lists its brushes in the UI language, so every brush of every +/// built-in library has a row in each complete catalog. +#[test] +fn built_in_library_brush_names_are_in_complete_catalogs() { + use vectorcraft_engine::cmd::brushlib; + let session = vectorcraft_engine::Session::new(); + let mut names: Vec = brushlib::BUILTIN + .iter() + .filter_map(|b| brushlib::library(&session, b.id)) + .flat_map(|(_, lib)| lib.brushes.iter().map(|b| b.name.clone()).collect::>()) + .collect(); + names.sort(); + names.dedup(); + assert_eq!(names.len(), 43, "{names:?}"); + let mut bad = vec![]; + for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { + let missing: Vec<&String> = names.iter().filter(|n| lang.catalog().plain(n).is_none()).collect(); + if !missing.is_empty() { + bad.push(format!("{} is missing {missing:?}", lang.code)); + } + } + assert!(bad.is_empty(), "{}", bad.join("\n")); +} + /// Preference choices and the marquee's E hint share the same translated labels. #[test] fn marquee_selection_labels_are_in_complete_catalogs() { diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 6a9f8d51fc..d3dcd0c7f7 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4129,6 +4129,9 @@ axis Both Her İkisi @msg Couldn't open {name}: {e} {name} açılamadı: {e} @msg Couldn't place {name}: the document it was dropped on was closed {name} yerleştirilemedi: bırakıldığı belge kapatıldı @msg Couldn't place {name}: the document it was placed in was closed {name} yerleştirilemedi: yerleştirildiği belge kapatıldı +@msg Couldn't place {name}: the document it was dropped on was reverted {name} yerleştirilemedi: bırakıldığı belge geri döndürüldü +@msg Couldn't place {name}: the document it was placed in was reverted {name} yerleştirilemedi: yerleştirildiği belge geri döndürüldü +@msg Couldn't paste: the document it was pasted in was reverted Yapıştırılamadı: yapıştırıldığı belge geri döndürüldü @msg Couldn't read {name}: {e} {name} okunamadı: {e} @msg Couldn't save recovery data: {e} Kurtarma verileri kaydedilemedi: {e} @msg Create Outlines: select text objects Anahatlar Oluştur: metin nesnelerini seçin @@ -5470,6 +5473,8 @@ lighting Light Işık Pen Kalem Pentagram Pentagram Perceptual algısal + Hue Clockwise Renk tonu saat yönünde + Hue Counterclockwise Renk tonu saat yönünün tersine Phone 360×800 Telefon 360×800 Phone 375×667 Telefon 375×667 Phone 375×812 Telefon 375×812 @@ -6267,7 +6272,7 @@ axis Y Axis Y ekseni Optical Effects Optik Efektler Geometric Patterns Geometrik Desenler Grit Textures Grenli Dokular -@msg `method` must be classic or perceptual `method` classic veya perceptual olmalıdır +@msg `method` must be classic, perceptual, hue-clockwise or hue-counterclockwise `method` classic, perceptual, hue-clockwise veya hue-counterclockwise olmalıdır @msg `spread` must be pad, repeat or reflect `spread` pad, repeat veya reflect olmalıdır @msg `repeats` must be a whole number from 1 to {MAX_REPEATS} `repeats` 1 ile {MAX_REPEATS} arasında bir tam sayı olmalıdır @msg `spread` applies to linear, radial, conic and diamond gradients `spread` doğrusal, radyal, konik ve elmas degradeler için geçerlidir @@ -6510,6 +6515,7 @@ axis Y Axis Y ekseni Continue Devam Et Continue Action Eyleme Devam Et Delete Action Step Eylem Adımını Sil + Move Action Step Eylem Adımını Taşı Press Play Current Selection in the Actions panel to go on. Devam etmek için Eylemler panelinde Geçerli Seçimi Oynat'a basın. Stop: {message} Durak: {message} @msg no action is waiting at a stop durakta bekleyen eylem yok @@ -6681,6 +6687,22 @@ axis Y Axis Y ekseni Graphite Pencil Grafit Kalem Wax Crayon Mum Boya Charcoal Dust Kömür Tozu + Notched Ribbon Çentikli Şerit + Double Line Çift Çizgi + Wave Dalga + Teardrop Gözyaşı + Striped Ribbon Çizgili Şerit + Fine Nib İnce Uç + Broad Nib Geniş Uç + Chisel Keski + Round Pen Yuvarlak Kalem + Pressure Pen Basınçlı Kalem + Beads Boncuklar + Dash Dot Çizgi Nokta + Scallops Fistolar + Stars Yıldızlar + Triangles Üçgenler + Sparkles Parıltılar Save Brush Library… Fırça Kitaplığını Kaydet… @msg `{_1}` has no brushes to apply `{_1}` içinde uygulanacak fırça yok @msg missing `library` (see brush.libraries) `library` eksik (bkz. brush.libraries) diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 8681297977..6f790c2d30 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4377,6 +4377,9 @@ axis Both Обидві @msg Couldn't open {name}: {e} Не вдалося відкрити {name}: {e} @msg Couldn't place {name}: the document it was dropped on was closed Не вдалося помістити {name}: документ, у який його перетягли, було закрито @msg Couldn't place {name}: the document it was placed in was closed Не вдалося помістити {name}: документ, у який його поміщали, було закрито +@msg Couldn't place {name}: the document it was dropped on was reverted Не вдалося помістити {name}: документ, у який його перетягли, було повернуто до збереженої версії +@msg Couldn't place {name}: the document it was placed in was reverted Не вдалося помістити {name}: документ, у який його поміщали, було повернуто до збереженої версії +@msg Couldn't paste: the document it was pasted in was reverted Не вдалося вставити: документ, у який виконувалося вставлення, було повернуто до збереженої версії @msg Couldn't read {name}: {e} Неможливо прочитати {name}: {e} @msg Couldn't save recovery data: {e} Не вдалося зберегти дані відновлення: {e} @msg Create Outlines: select text objects Створення контурів: виділіть текстові об’єкти @@ -5917,7 +5920,9 @@ axis Y Axis Вісь Y @msg `dither` applies to gradient fills (paint.setFill) `dither` застосовується до градієнтних заливок (paint.setFill) @msg `dither` must be true or false `dither` має бути true або false Perceptual Перцептивний -@msg `method` must be classic or perceptual `method` має бути classic або perceptual + Hue Clockwise Відтінок за годинниковою стрілкою + Hue Counterclockwise Відтінок проти годинникової стрілки +@msg `method` must be classic, perceptual, hue-clockwise or hue-counterclockwise `method` має бути classic, perceptual, hue-clockwise або hue-counterclockwise @msg `spread` must be pad, repeat or reflect `spread` має бути pad, repeat або reflect @msg `repeats` must be a whole number from 1 to {MAX_REPEATS} `repeats` має бути цілим числом від 1 до {MAX_REPEATS} @msg `spread` applies to linear, radial, conic and diamond gradients `spread` застосовується до лінійних, радіальних, конічних і ромбоподібних градієнтів @@ -6160,6 +6165,7 @@ axis Y Axis Вісь Y Continue Продовжити Continue Action Продовжити дію Delete Action Step Видалити крок дії + Move Action Step Перемістити крок дії Press Play Current Selection in the Actions panel to go on. Щоб продовжити, натисніть «Відтворити поточне виділення» на панелі «Дії». Stop: {message} Зупинка: {message} @msg no action is waiting at a stop жодна дія не очікує на зупинці @@ -6331,6 +6337,22 @@ axis Y Axis Вісь Y Graphite Pencil Графітний олівець Wax Crayon Восковий олівець Charcoal Dust Вугільний пил + Notched Ribbon Стрічка з насічками + Double Line Подвійна лінія + Wave Хвиля + Teardrop Крапля + Striped Ribbon Смугаста стрічка + Fine Nib Тонке перо + Broad Nib Широке перо + Chisel Стамеска + Round Pen Кругле перо + Pressure Pen Перо з натиском + Beads Намистини + Dash Dot Штрихпунктир + Scallops Фестони + Stars Зірки + Triangles Трикутники + Sparkles Іскри Save Brush Library… Зберегти бібліотеку пензлів… @msg `{_1}` has no brushes to apply У `{_1}` немає пензлів для застосування @msg missing `library` (see brush.libraries) не вказано `library` (див. brush.libraries) diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 516ba15672..f1502b385c 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -4805,6 +4805,9 @@ theme Appearance Giao diện @msg Couldn't paste: the document it was pasted in was closed Không thể dán: tài liệu mà nó được dán vào đã đóng @msg Couldn't place {name}: the document it was dropped on was closed Không thể đặt {name}: tài liệu mà nó được thả vào đã đóng @msg Couldn't place {name}: the document it was placed in was closed Không thể đặt {name}: tài liệu mà nó được đặt vào đã đóng +@msg Couldn't place {name}: the document it was dropped on was reverted Không thể đặt {name}: tài liệu mà nó được thả vào đã được hoàn về +@msg Couldn't place {name}: the document it was placed in was reverted Không thể đặt {name}: tài liệu mà nó được đặt vào đã được hoàn về +@msg Couldn't paste: the document it was pasted in was reverted Không thể dán: tài liệu mà nó được dán vào đã được hoàn về @msg Couldn't place {name}: {e} Không thể đặt {name}: {e} @msg Couldn't read {name}: {e} Không thể đọc {name}: {e} @msg Couldn't save recovery data: {e} Không thể lưu dữ liệu phục hồi: {e} @@ -5918,7 +5921,9 @@ axis Y Axis Trục Y @msg `dither` applies to gradient fills (paint.setFill) `dither` áp dụng cho vùng tô chuyển sắc (paint.setFill) @msg `dither` must be true or false `dither` phải là true hoặc false Perceptual Theo cảm nhận -@msg `method` must be classic or perceptual `method` phải là classic hoặc perceptual + Hue Clockwise Sắc độ theo chiều kim đồng hồ + Hue Counterclockwise Sắc độ ngược chiều kim đồng hồ +@msg `method` must be classic, perceptual, hue-clockwise or hue-counterclockwise `method` phải là classic, perceptual, hue-clockwise hoặc hue-counterclockwise @msg `spread` must be pad, repeat or reflect `spread` phải là pad, repeat hoặc reflect @msg `repeats` must be a whole number from 1 to {MAX_REPEATS} `repeats` phải là số nguyên từ 1 đến {MAX_REPEATS} @msg `spread` applies to linear, radial, conic and diamond gradients `spread` áp dụng cho chuyển sắc tuyến tính, tỏa tròn, hình nón và hình thoi @@ -6161,6 +6166,7 @@ axis Y Axis Trục Y Continue Tiếp tục Continue Action Tiếp tục hành động Delete Action Step Xóa bước hành động + Move Action Step Di chuyển bước hành động Press Play Current Selection in the Actions panel to go on. Để tiếp tục, nhấn Phát vùng chọn hiện tại trong bảng Hành động. Stop: {message} Điểm dừng: {message} @msg no action is waiting at a stop không có hành động nào đang chờ ở điểm dừng @@ -6332,6 +6338,22 @@ axis Y Axis Trục Y Graphite Pencil Bút chì than chì Wax Crayon Bút sáp màu Charcoal Dust Bụi than + Notched Ribbon Dải băng khía + Double Line Đường đôi + Wave Sóng + Teardrop Giọt lệ + Striped Ribbon Dải băng sọc + Fine Nib Ngòi mảnh + Broad Nib Ngòi rộng + Chisel Đục + Round Pen Bút tròn + Pressure Pen Bút áp lực + Beads Hạt cườm + Dash Dot Gạch chấm + Scallops Viền vỏ sò + Stars Ngôi sao + Triangles Tam giác + Sparkles Lấp lánh Save Brush Library… Lưu thư viện cọ… @msg `{_1}` has no brushes to apply `{_1}` không có cọ nào để áp dụng @msg missing `library` (see brush.libraries) thiếu `library` (xem brush.libraries) diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 35d92d6434..bd60d1b80d 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -4865,6 +4865,9 @@ imageTrace Outline 轮廓 @msg no user library folder here 此处没有用户库文件夹 @msg Couldn't place {name}: the document it was dropped on was closed 无法置入 {name}:将它拖放到的文档已关闭 @msg Couldn't place {name}: the document it was placed in was closed 无法置入 {name}:要置入的文档已关闭 +@msg Couldn't place {name}: the document it was dropped on was reverted 无法置入 {name}:将它拖放到的文档已恢复 +@msg Couldn't place {name}: the document it was placed in was reverted 无法置入 {name}:要置入的文档已恢复 +@msg Couldn't paste: the document it was pasted in was reverted 无法粘贴:要粘贴到的文档已恢复 @msg no files to place 没有要置入的文件 @msg `{file}` isn't a VectorCraft document, a PDF or a PDF-compatible .ai file `{file}` 不是 VectorCraft 文档、PDF 或 PDF 兼容的 .ai 文件 @msg paths: give at least one file paths:请至少给出一个文件 @@ -5266,6 +5269,8 @@ imageTrace Outline 轮廓 Outlined Text 轮廓化的文字 All Rasterized Regions 所有栅格化区域 Perceptual 可感知 + Hue Clockwise 色相顺时针 + Hue Counterclockwise 色相逆时针 Relative Colorimetric 相对比色 Absolute Colorimetric 绝对比色 Simulate 模拟 @@ -6150,7 +6155,7 @@ axis Y Axis Y 轴 @msg `dither` applies to gradient fills (stroke: false) `dither` 适用于渐变填色 (stroke: false) @msg `dither` applies to gradient fills (paint.setFill) `dither` 适用于渐变填色 (paint.setFill) @msg `dither` must be true or false `dither` 必须是 true 或 false -@msg `method` must be classic or perceptual `method` 必须是 classic 或 perceptual +@msg `method` must be classic, perceptual, hue-clockwise or hue-counterclockwise `method` 必须是 classic、perceptual、hue-clockwise 或 hue-counterclockwise @msg `spread` must be pad, repeat or reflect `spread` 必须是 pad、repeat 或 reflect @msg `repeats` must be a whole number from 1 to {MAX_REPEATS} `repeats` 必须是 1 到 {MAX_REPEATS} 之间的整数 @msg `spread` applies to linear, radial, conic and diamond gradients `spread` 适用于线性、径向、圆锥和菱形渐变 @@ -6393,6 +6398,7 @@ axis Y Axis Y 轴 Continue 继续 Continue Action 继续动作 Delete Action Step 删除动作步骤 + Move Action Step 移动动作步骤 Press Play Current Selection in the Actions panel to go on. 要继续,请按“动作”面板中的“播放当前选择项目”。 Stop: {message} 停止:{message} @msg no action is waiting at a stop 没有动作在停止处等待 @@ -6564,6 +6570,22 @@ axis Y Axis Y 轴 Graphite Pencil 石墨铅笔 Wax Crayon 蜡笔 Charcoal Dust 炭粉 + Notched Ribbon 凹口丝带 + Double Line 双线 + Wave 波浪 + Teardrop 泪滴 + Striped Ribbon 条纹丝带 + Fine Nib 细笔尖 + Broad Nib 宽笔尖 + Chisel 凿形 + Round Pen 圆头笔 + Pressure Pen 压感笔 + Beads 珠串 + Dash Dot 点划线 + Scallops 扇贝边 + Stars 星形 + Triangles 三角形 + Sparkles 闪光 Save Brush Library… 保存画笔库… @msg `{_1}` has no brushes to apply `{_1}` 中没有可应用的画笔 @msg missing `library` (see brush.libraries) 缺少 `library`(请参阅 brush.libraries) diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index dafc57aa29..b5ad17c5d8 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2614,6 +2614,9 @@ file-filter Templates 範本 @msg no user library folder here 此處沒有使用者資料庫資料夾 @msg Couldn't place {name}: the document it was dropped on was closed 無法置入 {name}:放置它的文件已關閉 @msg Couldn't place {name}: the document it was placed in was closed 無法置入 {name}:要置入的文件已關閉 +@msg Couldn't place {name}: the document it was dropped on was reverted 無法置入 {name}:放置它的文件已回復 +@msg Couldn't place {name}: the document it was placed in was reverted 無法置入 {name}:要置入的文件已回復 +@msg Couldn't paste: the document it was pasted in was reverted 無法貼上:要貼上的文件已回復 @msg no files to place 沒有要置入的檔案 @msg `{file}` isn't a VectorCraft document, a PDF or a PDF-compatible .ai file `{file}` 不是 VectorCraft 文件、PDF 或 PDF 相容的 .ai 檔案 @msg paths: give at least one file paths:請提供至少一個檔案 @@ -5956,7 +5959,9 @@ axis Y Axis Y 軸 @msg `dither` applies to gradient fills (paint.setFill) `dither` 適用於漸層填色 (paint.setFill) @msg `dither` must be true or false `dither` 必須是 true 或 false Perceptual 感知 -@msg `method` must be classic or perceptual `method` 必須是 classic 或 perceptual + Hue Clockwise 色相順時針 + Hue Counterclockwise 色相逆時針 +@msg `method` must be classic, perceptual, hue-clockwise or hue-counterclockwise `method` 必須是 classic、perceptual、hue-clockwise 或 hue-counterclockwise @msg `spread` must be pad, repeat or reflect `spread` 必須是 pad、repeat 或 reflect @msg `repeats` must be a whole number from 1 to {MAX_REPEATS} `repeats` 必須是 1 到 {MAX_REPEATS} 之間的整數 @msg `spread` applies to linear, radial, conic and diamond gradients `spread` 適用於線性、放射狀、圓錐和菱形漸層 @@ -6199,6 +6204,7 @@ axis Y Axis Y 軸 Continue 繼續 Continue Action 繼續動作 Delete Action Step 刪除動作步驟 + Move Action Step 移動動作步驟 Press Play Current Selection in the Actions panel to go on. 若要繼續,請按「動作」面板中的「播放目前選取項目」。 Stop: {message} 停止:{message} @msg no action is waiting at a stop 沒有動作在停止處等待 @@ -6370,6 +6376,22 @@ axis Y Axis Y 軸 Graphite Pencil 石墨鉛筆 Wax Crayon 蠟筆 Charcoal Dust 炭粉 + Notched Ribbon 凹口緞帶 + Double Line 雙線 + Wave 波浪 + Teardrop 淚滴 + Striped Ribbon 條紋緞帶 + Fine Nib 細筆尖 + Broad Nib 寬筆尖 + Chisel 鑿形 + Round Pen 圓頭筆 + Pressure Pen 壓感筆 + Beads 珠串 + Dash Dot 點劃線 + Scallops 扇貝邊 + Stars 星形 + Triangles 三角形 + Sparkles 閃光 Save Brush Library… 儲存筆刷資料庫… @msg `{_1}` has no brushes to apply `{_1}` 中沒有可套用的筆刷 @msg missing `library` (see brush.libraries) 未提供 `library`(請參閱 brush.libraries) diff --git a/crates/ui-egui/src/io/export.rs b/crates/ui-egui/src/io/export.rs index 5050529039..aaf2bd5b1f 100644 --- a/crates/ui-egui/src/io/export.rs +++ b/crates/ui-egui/src/io/export.rs @@ -28,7 +28,8 @@ pub fn hide_exports(app: &mut VectorcraftApp) -> Value { /// `document.export` options in `params` (artboard, range, useArtboards, selectedOnly, ppi, SVG /// options…): every file it writes (one per artboard, linked images) goes next to `path`. The /// document keeps its path. → `{path, warnings, files?}` (`files`: every file when there are -/// several). +/// several). When automation asked for the export, `warnings` also name each option the written +/// format doesn't read, as `document.export`'s do. pub fn export(app: &mut VectorcraftApp, format: Option<&str>, path: Option, params: &Value) -> Result { // Options given as anything but an object are none: the path and format still reach the // encoder (an exporter plug-in is told the file it writes). @@ -62,6 +63,10 @@ pub fn export(app: &mut VectorcraftApp, format: Option<&str>, path: Option z, _ => f, }; + // An export that automation asked for, also through a save panel it opened, names the options + // the file doesn't read, as `document.export` does. A person's export gets no such notes. + let unused = if app.automation_asked() { fileio::unused_option_notes("document.export", f, params) } else { Vec::new() }; + let noted = unused.clone(); // Background Export: encoded and written from this snapshot while editing goes on. The // encoder is told the file it writes (an exporter plug-in gets its name and extension). let label = format!("Exporting {}", fileio::file_name(&path)); @@ -93,7 +98,13 @@ pub fn export(app: &mut VectorcraftApp, format: Option<&str>, path: Option 1 { out["files"] = json!(files); } @@ -132,6 +143,11 @@ pub fn export(app: &mut VectorcraftApp, format: Option<&str>, path: Option Option crate::panels::actions::insert_select_object(app, p), crate::panels::actions::CONTINUE_PLAYBACK => crate::panels::actions::continue_playback(app, p), crate::panels::actions::DELETE_STEP => crate::panels::actions::delete_step(app, p), + crate::panels::actions::MOVE_STEP => crate::panels::actions::move_step(app, p), "ui.batchDialog" => { let index = |k: &str| opt_index(p, k).map(|i| i.unwrap_or(0)); index("set").and_then(|set| Ok((set, index("action")?))).and_then(|(set, action)| crate::dialogs::action_batch::open(app, set, action)) diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 5f6da1ca36..37cdcb2d56 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1478,13 +1478,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ crate::panels::actions::START_RECORDING, "Begin Recording", "", - "{set?: index} begin recording an automatically named Action N in the Actions panel's set at set (0 is the top set), by default the current set or the first set; with no sets, make Set 1. The set becomes current, and ui.action.stop adds the recorded action after that set's existing actions. An explicit invalid set, an existing recording, or a set where the new action would give it more than 1,000 actions or an action set file larger than 8 MiB is an error and changes nothing. While an action records, a recorded command whose step would give the action more than 10,000 steps or its set's action set file more than 8 MiB is an error and does not run, and the recording goes on. A recorded command whose step passes a limit only as it runs, from values it adds to its step, keeps its edit and result; the status bar names the limit, later recorded commands are an error and do not run, and ui.action.stop leaves its step out → {set, name}", + "{set?: index, action?: index, after?: index} begin recording an automatically named Action N in the Actions panel's set at set (0 is the top set), by default the current set or the first set; with no sets, make Set 1. The set becomes current, and ui.action.stop adds the recorded action after that set's existing actions. With action, record into the action at action in set instead: ui.action.stop puts the recorded steps after step after of that action, else after its last step, and the steps after them keep whether they are excluded. The panel's Begin Recording button passes the selected action and its selected step. action without set, after without action, an index past the last set, action or step, an explicit invalid set, an existing recording, or a set where the new action would give it more than 1,000 actions or an action set file larger than 8 MiB is an error and changes nothing. While an action records, a recorded command whose step would give the action more than 10,000 steps or its set's action set file more than 8 MiB is an error and does not run, and the recording goes on. A recorded command whose step passes a limit only as it runs, from values it adds to its step, keeps its edit and result; the status bar names the limit, later recorded commands are an error and do not run, and ui.action.stop leaves its step out → {set, name}, or with action {set, action, name}", ), ( crate::panels::actions::STOP_RECORDING, "Stop Playing/Recording", "", - "{} end the Actions panel's recording and keep its steps, in the action ui.action.new made for it, else in a new action after the last action of its set, as the panel's Stop Playing/Recording button does. It also ends an action playing step by step or with pauses, or one waiting at a stop, whose message box closes: the steps played stay and the rest do not run. Recorded steps still past 10,000 in the action, or past 8 MiB in its set's action set file, are left out, and the status bar names the limit. With nothing recording or playing it changes nothing → {stopped}", + "{} end the Actions panel's recording and keep its steps, in the action ui.action.new made for it or the action ui.action.record named, at the place it named, else in a new action after the last action of its set, as the panel's Stop Playing/Recording button does. It also ends an action playing step by step or with pauses, or one waiting at a stop, whose message box closes: the steps played stay and the rest do not run. Recorded steps still past 10,000 in the action, or past 8 MiB in its set's action set file, are left out, and the status bar names the limit. With nothing recording or playing it changes nothing → {stopped}", ), ( crate::panels::actions::INSERT_STOP, @@ -1522,6 +1522,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{set: index, action: index, step: index} delete one step, a stop or a command, of the Actions panel's action at action in set (0 is the top set, action or step). The steps after it keep whether they are excluded, and no step of that action stays selected. A Record Stop dialog open on that step closes, and one open on a later step of the action follows it up. A missing or invalid index is an error and changes nothing. Undo does not bring the step back. The panel's Delete Selection runs this for the selected step → {set, action, step}", ), + ( + crate::panels::actions::MOVE_STEP, + "Move Action Step", + "", + "{set: index, action: index, step: index, toSet?: index, toAction?: index, before: index} move one step, a stop or a command, of the Actions panel's action at action in set (0 is the top set, action or step) into the action at toAction in toSet (default: the same set and action), before the step at index before there, or after its last step when before is its number of steps; before counts the steps as they are before the move. The step keeps its params and whether it is excluded, and the other steps keep theirs. A selected step stays selected, and a moved selected step makes its new action the selected one and its set the current one. A Record Stop dialog open on a step follows the step, and the steps that the recording in progress adds to either action stay after the steps that were before them. A step put back just before or just after itself does not move. A missing or invalid index, or a move that would give the action more than 10,000 steps or its set's file more than 8 MiB, counting the steps that the recording in progress adds to the set, is an error and changes nothing. Undo does not move the step back. Dragging a step row in the panel runs this → {set, action, step, moved}", + ), ( "ui.batchDialog", "Batch…", diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 4f42eea008..1971834a07 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -894,16 +894,27 @@ pub const STOP_RECORDING: &str = "ui.action.stop"; /// The command that begins a plain recording ([`record`]). pub const START_RECORDING: &str = "ui.action.record"; -/// `ui.action.record {set?}`: begins recording an automatically named Action N in `set`, or in -/// the current set (the first if none is current). With no sets, makes Set 1. Stop adds the action -/// after the set's existing actions. An explicit invalid set, an existing recording, or a set whose -/// new action would pass a limit of Load Actions… ([`edit_keeps_set_loadable`]: 1,000 actions, -/// 8 MiB) is an error and leaves the panel unchanged. While it records, a command whose step does not fit in the action -/// ([`recording_room`]) does not run. → {set, name} +/// `ui.action.record {set?, action?, after?}`: begins recording an automatically named Action N in +/// `set`, or in the current set (the first if none is current). With no sets, makes Set 1. Stop +/// adds the action after the set's existing actions. With `action`, it records into the action at +/// that index of set `set` instead: Stop puts the recorded steps after step `after` of that action, +/// else after its last step, and the steps after them keep whether they are excluded. The Begin +/// Recording button passes the selected action and step. `action` without `set`, `after` without +/// `action`, an index past the last set, action or step, an explicit invalid set, an existing +/// recording, or a set whose new action would pass a limit of Load Actions… +/// ([`edit_keeps_set_loadable`]: 1,000 actions, 8 MiB) is an error and leaves the panel unchanged. +/// While it records, a command whose step does not fit in the action ([`recording_room`]) does not +/// run. → {set, name}, and with `action` {set, action, name} pub fn record(app: &mut VectorcraftApp, p: &Value) -> Result { if app.ui.recording.is_some() { return Err("an action is already recording".into()); } + if p.get("action").is_some() { + return record_into(app, p); + } + if p.get("after").is_some() { + return Err("no such action".into()); + } let set = match p.get("set") { Some(v) => v.as_u64().and_then(|i| usize::try_from(i).ok()).filter(|&i| i < app.ui.action_sets.len()).ok_or("no such action set")?, _ => { @@ -931,8 +942,32 @@ pub fn record(app: &mut VectorcraftApp, p: &Value) -> Result { Ok(json!({ "set": set, "name": name })) } +/// [`record`] with `action`: records into the action at index `action` of set `set`, after step +/// `after` or after its last step. The set becomes current and the only selected set, and the +/// action stays selected. → {set, action, name} +fn record_into(app: &mut VectorcraftApp, p: &Value) -> Result { + let index = |k: &str| p.get(k).and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()); + let (set, at) = + index("set").zip(index("action")).filter(|&(s, a)| app.ui.action_sets.get(s).is_some_and(|s| a < s.actions.len())).ok_or("no such action")?; + let action = &app.ui.action_sets[set].actions[at]; + let slot = match p.get("after") { + None => None, + Some(_) => Some(index("after").filter(|&s| s < action.steps.len()).ok_or("no such action step")? + 1), + }; + let (id, name) = (action.id, action.name.clone()); + app.ui.action_set = Some(set); + app.ui.action_sets_selected = vec![set]; + start_recording(app, set, name.clone(), Some(id)); + app.ui.recording_at = slot; + if let Some(ctx) = app.ui_ctx.clone() { + set_pstate::>(&ctx, "actions-selected", Some((set, at))); + } + Ok(json!({ "set": set, "action": at, "name": name })) +} + /// `ui.action.stop {}`: ends the recording in progress and keeps its steps, in the action New -/// Action made for it, else in a new action after the last action of its set, as the bottom bar's +/// Action made for it or the action [`record`] named, at the place it named, else in a new action +/// after the last action of its set, as the bottom bar's /// Stop Playing/Recording does. It also ends a playback at Step by Step or Pause For, or one that /// waits at a stop, whose message box closes: the steps already played stay, and the rest do not /// run. With nothing recording or playing it changes nothing. Recorded steps past the limits of an @@ -951,6 +986,13 @@ pub const INSERT_STOP: &str = "ui.action.insertStop"; /// The panel state that holds the selected step as (the action's [`Action::id`], the step's index). const SELECTED_STEP: &str = "actions-selected-step"; +/// The panel state that holds the step being dragged as a [`DraggedStep`]. +const DRAGGED_STEP: &str = "actions-dragged-step"; + +/// A step being dragged: the action's [`Action::id`], the step's index, and the action's steps and +/// excluded steps as they were when the drag started. +type DraggedStep = (u64, usize, std::sync::Arc<(Vec<(String, Value)>, BTreeSet)>); + /// `ui.action.insertStop {set?, action?, step?, message?, allowContinue?}`: inserts a stop. With `set` /// and `action`, it goes into that action, after step `step`, else after its last step. Without /// them, it goes into the recording in progress, after the steps recorded so far. `message` is @@ -1083,9 +1125,9 @@ fn recording_start(app: &VectorcraftApp) -> Option { } /// Where Stop Playing/Recording puts the steps of the recording in progress: the index of the set, -/// and of the action New Action made for it, or None for the new action Stop adds after the set's -/// last action. None when there is no recording, no set to put them in, or the action New Action -/// made for it was deleted, so that Stop keeps none of them. +/// and of the action it records into ([`crate::UiState::recording_into`]), or None for the new +/// action Stop adds after the set's last action. None when there is no recording, no set to put +/// them in, or the action it records into was deleted, so that Stop keeps none of them. fn recording_target(app: &VectorcraftApp) -> Option<(usize, Option)> { let (set, ..) = app.ui.recording.as_ref()?; let Some(id) = app.ui.recording_into else { @@ -1107,7 +1149,7 @@ fn set_with_recorded(app: &VectorcraftApp, steps: Vec<(String, Value)>) -> Optio s.actions.len() - 1 } }; - extend_recorded(s.actions.get_mut(at)?, steps); + put_recorded(s.actions.get_mut(at)?, steps, app.ui.recording_at); Some((s, at)) } @@ -1144,7 +1186,7 @@ fn set_sizes(app: &VectorcraftApp, at: Option, set: &ActionSet) -> [usize let mut s = set.clone(); let steps = app.session.journal_for_action(start); match app.ui.recording_into.and_then(|id| s.actions.iter().position(|a| a.id == id)) { - Some(i) => extend_recorded(&mut s.actions[i], steps), + Some(i) => put_recorded(&mut s.actions[i], steps, app.ui.recording_at), None => s.actions.push(Action::new(name, steps)), } with = s; @@ -1359,12 +1401,17 @@ fn insert(app: &mut VectorcraftApp, p: &Value, step: (String, Value)) -> Result< let excluded = action.excluded_steps.clone(); action.insert_step(after, step); let id = action.id; + // The recording's steps stay after the steps that were before them. + let slot = match (&recorded, app.ui.recording_at) { + (Some(r), Some(slot)) if r.into == Some(at) && after <= slot => Some(slot + 1), + (_, slot) => slot, + }; let file_len = match recorded { None => files::write_set(s).len(), Some(Recorded { into, name, steps }) => { let mut kept = s.clone(); match into { - Some(into) => kept.actions[into].steps.extend(steps), + Some(into) => put_recorded(&mut kept.actions[into], steps, slot), None => kept.actions.push(Action::new(name, steps)), } files::write_set(&kept).len() @@ -1376,6 +1423,7 @@ fn insert(app: &mut VectorcraftApp, p: &Value, step: (String, Value)) -> Result< action.excluded_steps = excluded; return Err("the action set would be larger than 8 MiB".into()); } + app.ui.recording_at = slot; app.ui.action_set = Some(set); app.ui.action_sets_selected = vec![set]; if let Some(ctx) = app.ui_ctx.clone() { @@ -1415,6 +1463,12 @@ pub fn delete_step(app: &mut VectorcraftApp, p: &Value) -> Result let step = index("step").filter(|&s| s < action.steps.len()).ok_or("no such action step")?; action.remove_step(step); let id = action.id; + // The recording's steps stay after the steps that were before them. + if app.ui.recording_into == Some(id) + && let Some(slot) = app.ui.recording_at.filter(|&slot| step < slot) + { + app.ui.recording_at = Some(slot - 1); + } if let Some(ctx) = app.ui_ctx.clone() && pstate::>(&ctx, SELECTED_STEP).is_some_and(|(selected, _)| selected == id) { @@ -1437,6 +1491,115 @@ pub fn delete_step(app: &mut VectorcraftApp, p: &Value) -> Result Ok(json!({"set": set, "action": at, "step": step})) } +/// The command that moves one step of an action ([`move_step`]). +pub const MOVE_STEP: &str = "ui.action.moveStep"; + +/// `ui.action.moveStep {set, action, step, toSet?, toAction?, before}`: moves step `step`, a stop or +/// a command, of the action at index `action` of set `set` into the action at index `toAction` of +/// set `toSet` (default: the same set and action), before the step at index `before` there, or +/// after its last step when `before` is its number of steps. `before` counts the steps as they are +/// before the move. The step keeps its params and whether it is excluded, and the other steps keep +/// theirs. A selected step stays selected: a moved selected step makes its new action the selected +/// one and its set the current one. A Record Stop, Insert Menu Item or Set Selection dialog open on +/// a step follows the step, and the steps a recording adds to either action stay after the steps +/// that were before them. A step put back just before or just after itself does not move. A missing +/// or invalid index, or a move that would give a set a file that Load Actions… refuses +/// ([`edit_keeps_set_loadable`]: 10,000 steps in an action, 8 MiB), is an error, and then nothing +/// changes. Undo does not move the step back. A drag of a step row in the panel runs this. +/// → {set, action, step, moved}: where the step is now +pub fn move_step(app: &mut VectorcraftApp, p: &Value) -> Result { + let number = |v: &Value| v.as_u64().and_then(|i| usize::try_from(i).ok()); + let index = |k: &str| p.get(k).and_then(number); + let (set, at) = index("set").zip(index("action")).ok_or("no such action")?; + let source = app.ui.action_sets.get(set).and_then(|s| s.actions.get(at)).ok_or("no such action")?; + let step = index("step").filter(|&s| s < source.steps.len()).ok_or("no such action step")?; + let source_id = source.id; + let to_set = match p.get("toSet") { + None => set, + Some(v) => number(v).filter(|&s| s < app.ui.action_sets.len()).ok_or("no such action set")?, + }; + let to_action = match p.get("toAction") { + None => at, + Some(v) => number(v).ok_or("no such action")?, + }; + let dest = app.ui.action_sets[to_set].actions.get(to_action).ok_or("no such action")?; + let dest_id = dest.id; + let before = index("before").filter(|&b| b <= dest.steps.len()).ok_or("no such action step")?; + let same = (set, at) == (to_set, to_action); + if same && (before == step || before == step + 1) { + return Ok(json!({"set": set, "action": at, "step": step, "moved": false})); + } + // The step's index once it is in place, counted without it in its own action. + let to = if same && before > step { before - 1 } else { before }; + let mut from_edit = app.ui.action_sets[set].clone(); + let moved = from_edit.actions[at].steps[step].clone(); + let excluded = from_edit.actions[at].excluded_steps.contains(&step); + from_edit.actions[at].remove_step(step); + let put = |a: &mut Action| { + a.insert_step(to, moved); + if excluded { + a.excluded_steps.insert(to); + } + }; + let to_edit = if to_set == set { + put(&mut from_edit.actions[to_action]); + None + } else { + let mut edit = app.ui.action_sets[to_set].clone(); + put(&mut edit.actions[to_action]); + Some(edit) + }; + edit_keeps_set_loadable(app, Some(set), &from_edit)?; + if let Some(edit) = &to_edit { + edit_keeps_set_loadable(app, Some(to_set), edit)?; + } + app.ui.action_sets[set] = from_edit; + if let Some(edit) = to_edit { + app.ui.action_sets[to_set] = edit; + } + // A step index in `source_id` or `dest_id` as (the action's id, the step) after the move. + let follow = |(id, s): (u64, usize)| -> (u64, usize) { + if (id, s) == (source_id, step) { + return (dest_id, to); + } + let s = if id == source_id && s > step { s - 1 } else { s }; + (id, if id == dest_id && s >= to { s + 1 } else { s }) + }; + // The recording's steps stay after the steps that were before them. + if let Some(slot) = app.ui.recording_at { + let slot = if app.ui.recording_into == Some(source_id) && step < slot { slot - 1 } else { slot }; + app.ui.recording_at = Some(if app.ui.recording_into == Some(dest_id) && to <= slot { slot + 1 } else { slot }); + } + if let Some(ctx) = app.ui_ctx.clone() + && let Some(selected) = pstate::>(&ctx, SELECTED_STEP) + { + set_pstate::>(&ctx, SELECTED_STEP, Some(follow(selected))); + if selected == (source_id, step) { + set_pstate::>(&ctx, "actions-selected", Some((to_set, to_action))); + let mut expanded: BTreeSet = pstate(&ctx, "actions-expanded"); + expanded.insert(dest_id); + set_pstate(&ctx, "actions-expanded", expanded); + app.ui.action_set = Some(to_set); + app.ui.action_sets_selected = vec![to_set]; + } + } + // A Record Stop, Insert Menu Item or Set Selection dialog open on a step of either action follows it. + let either = |s: usize, a: usize| (s, a) == (set, at) || (s, a) == (to_set, to_action); + if let Some(d) = app.ui.dialog.as_mut().filter(|d| holds_step(d)) + && let (Some(ds), Some(da), Some(ds_step)) = + (d.fields.get("set").and_then(number), d.fields.get("action").and_then(number), d.fields.get("step").and_then(number)) + && either(ds, da) + { + let id = if (ds, da) == (set, at) { source_id } else { dest_id }; + let (id, s) = follow((id, ds_step)); + let (ds, da) = if id == dest_id { (to_set, to_action) } else { (set, at) }; + d.fields.insert("set".into(), json!(ds)); + d.fields.insert("action".into(), json!(da)); + d.fields.insert("step".into(), json!(s)); + } + Ok(json!({"set": to_set, "action": to_action, "step": to, "moved": true})) +} + /// The command that `chord` runs under `km`, pressed once or pressed twice. #[cfg(test)] fn command_on(km: &craft_keymap::Keymap, chord: &craft_keymap::Chord) -> Option { @@ -1471,6 +1634,7 @@ fn start_recording(app: &mut VectorcraftApp, set: usize, name: String, into: Opt app.session.journal.hold(Some(start)); app.ui.recording = Some((set, name, start)); app.ui.recording_into = into; + app.ui.recording_at = None; app.ui.recording_base = None; app.ui.recording_tail = None; app.ui.recording_checked = Some((app.session.journal.rewrites(), start)); @@ -1498,12 +1662,15 @@ fn steps_that_fit(app: &VectorcraftApp, steps: &[(String, Value)]) -> (usize, Op (keep, (keep < steps.len()).then_some("the action already has 10,000 steps")) } -/// Adds the recorded `steps` after the steps of `action`, included in playback. An exclusion past -/// the action's last step, which saved preferences can hold, goes. -fn extend_recorded(action: &mut Action, steps: Vec<(String, Value)>) { +/// Puts the recorded `steps` into `action` before its step at index `at`, or after its last step +/// when `at` is None or past it, included in playback. The steps after them keep whether they are +/// excluded. An exclusion past the action's last step, which saved preferences can hold, goes. +fn put_recorded(action: &mut Action, steps: Vec<(String, Value)>, at: Option) { let len = action.steps.len(); - action.excluded_steps.retain(|&i| i < len); - action.steps.extend(steps); + let at = at.map_or(len, |at| at.min(len)); + let added = steps.len(); + action.excluded_steps = action.excluded_steps.iter().filter(|&&i| i < len).map(|&i| if i >= at { i + added } else { i }).collect(); + action.steps.splice(at..at, steps); } /// Stop Playing/Recording: ends the recording and keeps its steps (see [`start_recording`]). An @@ -1522,10 +1689,16 @@ fn stop_recording(app: &mut VectorcraftApp) { app.ui.recording_tail = None; app.ui.recording_checked = None; app.session.journal.hold(None); + let at = app.ui.recording_at.take(); match app.ui.recording_into.take() { Some(id) => { - if let Some(a) = app.ui.action_sets.iter_mut().flat_map(|s| s.actions.iter_mut()).find(|a| a.id == id) { - extend_recorded(a, steps); + let found = app.ui.action_sets.iter().enumerate().find_map(|(s, set)| Some((s, set.actions.iter().position(|a| a.id == id)?))); + if let Some((s, a)) = found { + let action = &mut app.ui.action_sets[s].actions[a]; + let len = action.steps.len(); + let (from, added) = (at.map_or(len, |at| at.min(len)), steps.len()); + put_recorded(action, steps, at); + follow_recorded(app, (s, a, id), from, added); } } None => { @@ -1536,6 +1709,28 @@ fn stop_recording(app: &mut VectorcraftApp) { } } +/// After Stop Playing/Recording put `added` steps into the action at `place` (set, action, id) +/// before its step at index `from`: the selected step and a Record Stop, Insert Menu Item or Set +/// Selection dialog open on a later step of the action follow their step down. +fn follow_recorded(app: &mut VectorcraftApp, (set, at, id): (usize, usize, u64), from: usize, added: usize) { + if added == 0 { + return; + } + if let Some(ctx) = app.ui_ctx.clone() + && let Some((step_id, step)) = pstate::>(&ctx, SELECTED_STEP).filter(|&(step_id, step)| step_id == id && step >= from) + { + set_pstate::>(&ctx, SELECTED_STEP, Some((step_id, step + added))); + } + let number = |v: &Value| v.as_u64().and_then(|i| usize::try_from(i).ok()); + if let Some(d) = app.ui.dialog.as_mut().filter(|d| holds_step(d)) + && d.fields.get("set").and_then(number) == Some(set) + && d.fields.get("action").and_then(number) == Some(at) + && let Some(step) = d.fields.get("step").and_then(number).filter(|&step| step >= from) + { + d.fields.insert("step".into(), json!(step + added)); + } +} + crate::shortcut_editor::ui_mirror!(fn function_key_chords() -> Vec); /// Mirrors the actions' function keys for code without app access (cheap when unchanged). @@ -1673,6 +1868,7 @@ pub fn delete_sets(app: &mut VectorcraftApp, p: &Value) -> Result if sets.contains(rec) { app.ui.recording = None; app.ui.recording_into = None; + app.ui.recording_at = None; app.session.journal.hold(None); } else { *rec -= sets.iter().filter(|&&s| s < *rec).count(); @@ -1926,6 +2122,34 @@ fn inclusion_box( (response.on_hover_text(if included { tl!("Exclude from playback") } else { tl!("Include in playback") }).clicked(), hit) } +/// While a step is dragged over the list: where it goes as (set, action, `before` of [`MOVE_STEP`]), +/// shown by a line in `color` on the row under the pointer, or None off every action's rows +/// (`slots`, as [`show`] lists them). Near the list's top or bottom edge, the list scrolls. +fn drop_target(ui: &mut egui::Ui, slots: &[(egui::Rect, usize, usize, usize, usize)], color: egui::Color32) -> Option<(usize, usize, usize)> { + let p = ui.ctx().pointer_interact_pos()?; + let clip = ui.clip_rect(); + if !clip.contains(p) { + return None; + } + let edge = 12.0; + let scroll = if p.y < clip.top() + edge { + 6.0 + } else if p.y > clip.bottom() - edge { + -6.0 + } else { + 0.0 + }; + if scroll != 0.0 && ui.input(|i| i.pointer.any_down()) { + ui.scroll_with_delta(egui::vec2(0.0, scroll)); + ui.ctx().request_repaint(); + } + let half_gap = ui.spacing().item_spacing.y / 2.0; + let &(r, si, ai, upper, lower) = slots.iter().find(|(r, ..)| (r.top() - half_gap..r.bottom() + half_gap).contains(&p.y))?; + let (before, y) = if upper != lower && p.y < r.center().y { (upper, r.top()) } else { (lower, r.bottom()) }; + ui.painter().line_segment([egui::pos2(r.left() + 42.0, y), egui::pos2(r.right(), y)], egui::Stroke::new(2.0, color)); + Some((si, ai, before)) +} + enum InclusionChange { Set(usize), Action(usize, usize), @@ -1954,6 +2178,19 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { let mut expanded: BTreeSet = pstate(ui.ctx(), "actions-expanded"); let mut inclusion_changes = Vec::new(); let mut play_req = None; + // The step being dragged, from the frame its drag started. The drag ends without a move when a + // command since then changed its action's steps or which of them are excluded, or deleted the + // action. + let dragging = pstate::>(ui.ctx(), DRAGGED_STEP).filter(|(id, _, was)| { + let action = app.ui.action_sets.iter().flat_map(|s| &s.actions).find(|a| a.id == *id); + action.is_some_and(|a| (&a.steps, &a.excluded_steps) == (&was.0, &was.1)) + }); + let mut drag_started = None; + let mut drag_stopped = false; + // The rows a dragged step can be dropped on: (row, set, action, where it goes on the row's upper + // half, where on its lower half), as `before` of [`MOVE_STEP`]. + let mut slots: Vec<(egui::Rect, usize, usize, usize, usize)> = Vec::new(); + let mut drop = None; let list_height = widgets::panel_list_height(ui, 260.0, 0.0).min(260.0); egui::ScrollArea::vertical().max_height(list_height).min_scrolled_height(list_height.min(64.0)).show(ui, |ui| { for (si, set) in app.ui.action_sets.iter().enumerate() { @@ -2039,9 +2276,18 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { if resp.double_clicked() && !resp.interact_pointer_pos().is_some_and(|p| check_rect.contains(p) || disclosure.contains(p)) { play_req = Some((si, ai)); } + // A step dropped on an action's row goes first when the action shows its steps, else + // after its last step. + let first = if open && !a.steps.is_empty() { 0 } else { a.steps.len() }; + slots.push((r, si, ai, first, first)); if open { for (step, (command, params)) in a.steps.iter().enumerate() { - let (r, resp) = ui.allocate_exact_size(egui::vec2(ui.available_width(), 20.0), egui::Sense::click()); + let (r, resp) = ui.allocate_exact_size(egui::vec2(ui.available_width(), 20.0), egui::Sense::click_and_drag()); + slots.push((r, si, ai, step, step + 1)); + if resp.drag_started() { + drag_started = Some((a.id, step, std::sync::Arc::new((a.steps.clone(), a.excluded_steps.clone())))); + } + drag_stopped |= resp.drag_stopped(); if step_selected == Some((a.id, step)) { ui.painter().rect_filled(r, 0.0, t.row_selected); } else if resp.hovered() { @@ -2085,7 +2331,18 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { } } } + if dragging.is_some() { + drop = drop_target(ui, &slots, t.accent); + } }); + // A released drag moves the step once, to where the line showed. + let dragged = dragging.as_ref().map(|(id, step, _)| (*id, *step)); + let move_req = drag_stopped.then_some(dragged.zip(drop)).flatten().and_then(|((id, step), (si, ai, before))| { + let (fs, fa) = app.ui.action_sets.iter().enumerate().find_map(|(fs, s)| Some((fs, s.actions.iter().position(|a| a.id == id)?)))?; + Some(json!({"set": fs, "action": fa, "step": step, "toSet": si, "toAction": ai, "before": before})) + }); + let still_dragging = !drag_stopped && ui.input(|i| i.pointer.any_down()); + set_pstate(ui.ctx(), DRAGGED_STEP, drag_started.or(dragging.filter(|_| still_dragging))); if waiting_at_stop(app) { dim_label(ui, tl!("Press Play Current Selection in the Actions panel to go on.")); } @@ -2114,6 +2371,19 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { set_pstate(ui.ctx(), SELECTED_STEP, step_selected); app.ui.action_set = current; app.ui.action_sets_selected = sets_selected; + if let Some(params) = move_req + && let Err(e) = app.run(MOVE_STEP, params) + { + app.status(e); + } + // Begin Recording records into the selected action, after its selected step. + let record_params = match selected.and_then(|(s, a)| Some((s, a, app.ui.action_sets.get(s)?.actions.get(a)?.id))) { + Some((s, a, id)) => match step_selected.filter(|&(step_id, _)| step_id == id) { + Some((_, step)) => json!({"set": s, "action": a, "after": step}), + None => json!({"set": s, "action": a}), + }, + None => json!({}), + }; if app.ui.action_sets.is_empty() { dim_label(ui, tl!("No actions. Press ● to record.")); } @@ -2129,7 +2399,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { ui.painter().circle_filled(r.center(), 6.0, if recording { egui::Color32::from_rgb(0xe0, 0x30, 0x30) } else { t.icon }); if resp.on_hover_text(tl!("Begin Recording")).clicked() && !recording - && let Err(e) = app.run(START_RECORDING, json!({})) + && let Err(e) = app.run(START_RECORDING, record_params.clone()) { app.status(e); } @@ -5870,6 +6140,350 @@ mod tests { assert_eq!(open_kind(&app), None, "deleting its step closes it"); } + /// The steps of action `action` in set `set`: each command, with its `dx` when it has one. + fn step_names(app: &VectorcraftApp, set: usize, action: usize) -> Vec { + app.ui.action_sets[set].actions[action] + .steps + .iter() + .map(|(c, p)| match p.get("dx") { + Some(dx) => format!("{c} {dx}"), + None => c.clone(), + }) + .collect() + } + + /// The bottom bar's Stop and Begin Recording buttons, as drawn last. + fn stop_and_record(ctx: &egui::Context, app: &mut VectorcraftApp) -> (egui::Pos2, egui::Pos2) { + super::super::tests_appearance::frame_events(ctx, app, vec![], show); + let mut bar = crate::toolbar::tests::widget_rects(ctx, egui::vec2(24.0, 24.0)); + bar.sort_by(|a, b| a.left().total_cmp(&b.left())); + let [stop, record, ..] = bar[..] else { panic!("the bottom bar: {bar:?}") }; + (stop.center(), record.center()) + } + + #[test] + fn begin_recording_selected_action_adds_steps_without_new_action() { + use super::super::tests_appearance::{click, frame_events, text_rect}; + let (mut app, _) = app_with_three_moves(); + app.ui.action_set = Some(0); + let ctx = egui::Context::default(); + app.ui_ctx = Some(ctx.clone()); + let texts = frame_events(&ctx, &mut app, vec![], show); + click(&ctx, &mut app, text_rect(&texts, "Three Moves").center(), show); + let (stop, record) = stop_and_record(&ctx, &mut app); + click(&ctx, &mut app, record, show); + app.run("object.move", json!({"dx": 8, "dy": 0})).unwrap(); + click(&ctx, &mut app, stop, show); + assert_eq!(app.ui.action_sets[0].actions.len(), 1, "no new action"); + assert_eq!(step_names(&app, 0, 0), ["object.move 1", "object.move 2", "object.move 4", "object.move 8"], "added at the end"); + + // With a step selected, the recorded steps go after it. + click_first_step(&ctx, &mut app); + // The steps shown move the bottom bar down. + let (stop, record) = stop_and_record(&ctx, &mut app); + click(&ctx, &mut app, record, show); + app.run("object.move", json!({"dx": 16, "dy": 0})).unwrap(); + click(&ctx, &mut app, stop, show); + assert_eq!(step_names(&app, 0, 0), ["object.move 1", "object.move 16", "object.move 2", "object.move 4", "object.move 8"]); + + // With no action selected, Begin Recording still adds a new action. + let texts = frame_events(&ctx, &mut app, vec![], show); + click(&ctx, &mut app, text_rect(&texts, "▾ Moves").center(), show); + let (stop, record) = stop_and_record(&ctx, &mut app); + click(&ctx, &mut app, record, show); + app.run("object.move", json!({"dx": 32, "dy": 0})).unwrap(); + click(&ctx, &mut app, stop, show); + let names: Vec<&str> = app.ui.action_sets[0].actions.iter().map(|a| a.name.as_str()).collect(); + assert_eq!(names, ["Three Moves", "Action 2"]); + assert_eq!(step_names(&app, 0, 1), ["object.move 32"]); + } + + #[test] + fn begin_recording_after_selected_step_preserves_order_and_exclusions() { + let (mut app, _) = app_with_three_moves(); + app.ui.action_sets[0].actions[0].excluded_steps = BTreeSet::from([0, 2]); + for (params, want) in [ + (json!({"action": 0}), "no such action"), + (json!({"set": 0, "after": 0}), "no such action"), + (json!({"set": 1, "action": 0}), "no such action"), + (json!({"set": 0, "action": 1}), "no such action"), + (json!({"set": 0, "action": "0"}), "no such action"), + (json!({"set": 0, "action": 0, "after": 3}), "no such action step"), + (json!({"set": 0, "action": 0, "after": null}), "no such action step"), + (json!({"set": 0, "action": 0, "after": -1}), "no such action step"), + ] { + assert_eq!(app.run(START_RECORDING, params.clone()).unwrap_err(), want, "{params}"); + assert!(app.ui.recording.is_none(), "{params}"); + } + assert_eq!( + app.run(START_RECORDING, json!({"set": 0, "action": 0, "after": 0})).unwrap(), + json!({"set": 0, "action": 0, "name": "Three Moves"}) + ); + app.run("object.move", json!({"dx": 8, "dy": 0})).unwrap(); + app.run("object.move", json!({"dx": 16, "dy": 0})).unwrap(); + app.run(STOP_RECORDING, json!({})).unwrap(); + assert_eq!(app.ui.action_sets[0].actions.len(), 1, "no new action"); + assert_eq!(step_names(&app, 0, 0), ["object.move 1", "object.move 8", "object.move 16", "object.move 2", "object.move 4"]); + assert_eq!(app.ui.action_sets[0].actions[0].excluded_steps, BTreeSet::from([0, 4]), "the steps keep whether they are excluded"); + } + + #[test] + fn steps_recorded_into_the_middle_of_an_action_keep_the_selected_step_and_dialog_on_their_steps() { + let (mut app, _) = app_with_three_moves(); + let ctx = egui::Context::default(); + app.ui_ctx = Some(ctx.clone()); + let id = app.ui.action_sets[0].actions[0].id; + app.run(START_RECORDING, json!({"set": 0, "action": 0, "after": 0})).unwrap(); + app.run("object.move", json!({"dx": 8, "dy": 0})).unwrap(); + app.run("object.move", json!({"dx": 16, "dy": 0})).unwrap(); + set_pstate::>(&ctx, SELECTED_STEP, Some((id, 2))); + crate::dialogs::action_stop::open_record(&mut app, Some((0, 0)), Some(1)); + app.run(STOP_RECORDING, json!({})).unwrap(); + assert_eq!(step_names(&app, 0, 0), ["object.move 1", "object.move 8", "object.move 16", "object.move 2", "object.move 4"]); + assert_eq!(pstate::>(&ctx, SELECTED_STEP), Some((id, 4)), "the move by 4 stays selected"); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["step"], json!(3), "Record Stop stays after the move by 2"); + } + + #[test] + fn step_edits_while_recording_into_an_action_keep_the_recording_in_place() { + let (mut app, _) = app_with_three_moves(); + // The recording goes between the moves by 2 and 4. + app.run(START_RECORDING, json!({"set": 0, "action": 0, "after": 1})).unwrap(); + app.run("object.move", json!({"dx": 8, "dy": 0})).unwrap(); + app.run(DELETE_STEP, json!({"set": 0, "action": 0, "step": 0})).unwrap(); + app.run(INSERT_STOP, json!({"set": 0, "action": 0, "step": 0})).unwrap(); + app.run(MOVE_STEP, json!({"set": 0, "action": 0, "step": 2, "before": 0})).unwrap(); + app.run(STOP_RECORDING, json!({})).unwrap(); + assert_eq!(step_names(&app, 0, 0), ["object.move 4", "object.move 2", STOP_STEP, "object.move 8"]); + + let (mut app, _) = app_with_three_moves(); + app.run(START_RECORDING, json!({"set": 0, "action": 0, "after": 1})).unwrap(); + app.run("object.move", json!({"dx": 8, "dy": 0})).unwrap(); + app.run(DELETE_STEP, json!({"set": 0, "action": 0, "step": 0})).unwrap(); + app.run(STOP_RECORDING, json!({})).unwrap(); + assert_eq!(step_names(&app, 0, 0), ["object.move 2", "object.move 8", "object.move 4"], "a step deleted before the place"); + } + + #[test] + fn move_step_within_action_updates_order_exclusions_and_selection() { + let (mut app, _) = app_with_three_moves(); + app.ui.action_sets[0].actions[0].steps.push(("object.move".into(), json!({"dx": 8, "dy": 0}))); + app.ui.action_sets[0].actions[0].excluded_steps = BTreeSet::from([1]); + let ctx = egui::Context::default(); + app.ui_ctx = Some(ctx.clone()); + let id = app.ui.action_sets[0].actions[0].id; + set_pstate::>(&ctx, SELECTED_STEP, Some((id, 3))); + let selected_step = |ctx: &egui::Context| pstate::>(ctx, SELECTED_STEP); + assert_eq!( + app.run(MOVE_STEP, json!({"set": 0, "action": 0, "step": 1, "before": 4})).unwrap(), + json!({"set": 0, "action": 0, "step": 3, "moved": true}) + ); + assert_eq!(step_names(&app, 0, 0), ["object.move 1", "object.move 4", "object.move 8", "object.move 2"]); + assert_eq!(app.ui.action_sets[0].actions[0].excluded_steps, BTreeSet::from([3]), "the moved step stays excluded"); + assert_eq!(selected_step(&ctx), Some((id, 2)), "the selected step stays selected"); + assert_eq!( + app.run(MOVE_STEP, json!({"set": 0, "action": 0, "step": 2, "before": 0})).unwrap(), + json!({"set": 0, "action": 0, "step": 0, "moved": true}) + ); + assert_eq!(step_names(&app, 0, 0), ["object.move 8", "object.move 1", "object.move 4", "object.move 2"]); + assert_eq!(app.ui.action_sets[0].actions[0].excluded_steps, BTreeSet::from([3])); + assert_eq!(selected_step(&ctx), Some((id, 0)), "the moved selected step is selected where it went"); + for before in [1, 2] { + assert_eq!( + app.run(MOVE_STEP, json!({"set": 0, "action": 0, "step": 1, "before": before})).unwrap(), + json!({"set": 0, "action": 0, "step": 1, "moved": false}) + ); + } + assert_eq!(step_names(&app, 0, 0), ["object.move 8", "object.move 1", "object.move 4", "object.move 2"], "a drop on itself moves nothing"); + crate::dialogs::action_stop::open_record(&mut app, Some((0, 0)), Some(3)); + app.run(MOVE_STEP, json!({"set": 0, "action": 0, "step": 3, "before": 0})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["step"], json!(0), "an open Record Stop follows its step"); + } + + #[test] + fn move_step_between_actions_and_sets_keeps_file_roundtrip() { + let (mut app, _) = app_with_three_moves(); + app.ui.action_sets[0].actions[0].excluded_steps = BTreeSet::from([2]); + let rotate = ("object.rotate".to_string(), json!({"angle": 5})); + app.ui.action_sets.push(ActionSet::new("Other", vec![Action::new("Empty", vec![]), Action::new("One", vec![rotate])])); + app.ui.action_set = Some(0); + let ctx = egui::Context::default(); + app.ui_ctx = Some(ctx.clone()); + let (id, empty) = (app.ui.action_sets[0].actions[0].id, app.ui.action_sets[1].actions[0].id); + set_pstate::>(&ctx, "actions-selected", Some((0, 0))); + set_pstate::>(&ctx, SELECTED_STEP, Some((id, 2))); + assert_eq!( + app.run(MOVE_STEP, json!({"set": 0, "action": 0, "step": 2, "toSet": 1, "toAction": 0, "before": 0})).unwrap(), + json!({"set": 1, "action": 0, "step": 0, "moved": true}) + ); + assert_eq!(step_names(&app, 0, 0), ["object.move 1", "object.move 2"]); + assert!(app.ui.action_sets[0].actions[0].excluded_steps.is_empty()); + assert_eq!(step_names(&app, 1, 0), ["object.move 4"], "an empty action takes a step"); + assert_eq!(app.ui.action_sets[1].actions[0].excluded_steps, BTreeSet::from([0]), "the moved step stays excluded"); + assert_eq!(pstate::>(&ctx, SELECTED_STEP), Some((empty, 0))); + assert_eq!(pstate::>(&ctx, "actions-selected"), Some((1, 0))); + assert_eq!((app.ui.action_set, app.ui.action_sets_selected.as_slice()), (Some(1), &[1][..])); + assert!(pstate::>(&ctx, "actions-expanded").contains(&empty), "the step's new action shows its steps"); + app.run(MOVE_STEP, json!({"set": 0, "action": 0, "step": 0, "toSet": 1, "toAction": 1, "before": 0})).unwrap(); + assert_eq!(step_names(&app, 1, 1), ["object.move 1", "object.rotate"]); + assert_eq!(pstate::>(&ctx, SELECTED_STEP), Some((empty, 0)), "an unmoved selected step stays"); + let loaded = files::read_set(&files::write_set(&app.ui.action_sets[1]), "Other").unwrap(); + for (a, b) in loaded.actions.iter().zip(&app.ui.action_sets[1].actions) { + assert_eq!((&a.name, &a.steps, &a.excluded_steps), (&b.name, &b.steps, &b.excluded_steps)); + } + } + + #[test] + fn move_step_rejects_invalid_and_oversize_destinations_without_changes() { + let (mut app, _) = app_with_three_moves(); + let full = Action::new("Full", vec![("object.move".to_string(), json!({"dx": 0})); files::MAX_ACTION_STEPS]); + let big = |text: String| ActionSet::new("Big", vec![Action::new("Big", vec![("document.note".to_string(), json!({ "s": text }))])]); + let room = files::MAX_SET_FILE - files::write_set(&big(String::new())).len() - 4; + app.ui.action_sets.push(ActionSet::new("Full", vec![full])); + app.ui.action_sets.push(big("x".repeat(room))); + assert!(files::write_set(&app.ui.action_sets[2]).len() <= files::MAX_SET_FILE); + let before: Vec = app.ui.action_sets.iter().map(files::write_set).collect(); + for (params, want) in [ + (json!({}), "no such action"), + (json!({"set": 0, "action": 1, "step": 0, "before": 0}), "no such action"), + (json!({"set": 3, "action": 0, "step": 0, "before": 0}), "no such action"), + (json!({"set": 0, "action": 0, "step": 3, "before": 0}), "no such action step"), + (json!({"set": 0, "action": 0, "before": 0}), "no such action step"), + (json!({"set": 0, "action": 0, "step": 0}), "no such action step"), + (json!({"set": 0, "action": 0, "step": 0, "before": 4}), "no such action step"), + (json!({"set": 0, "action": 0, "step": 0, "before": "1"}), "no such action step"), + (json!({"set": 0, "action": 0, "step": 0, "toSet": 3, "before": 0}), "no such action set"), + (json!({"set": 0, "action": 0, "step": 0, "toSet": null, "before": 0}), "no such action set"), + (json!({"set": 0, "action": 0, "step": 0, "toSet": 1, "toAction": 1, "before": 0}), "no such action"), + (json!({"set": 0, "action": 0, "step": 0, "toSet": 1, "toAction": 0, "before": 0}), "the action already has 10,000 steps"), + (json!({"set": 0, "action": 0, "step": 0, "toSet": 2, "toAction": 0, "before": 1}), "the action set would be larger than 8 MiB"), + ] { + assert_eq!(app.run(MOVE_STEP, params.clone()).unwrap_err(), want, "{params}"); + assert_eq!(app.ui.action_sets.iter().map(files::write_set).collect::>(), before, "{params}"); + } + } + + #[test] + fn drag_step_shows_insertion_line_and_moves_once() { + use egui::{Event, PointerButton}; + let (mut app, _) = app_with_three_moves(); + app.ui.action_set = Some(0); + let ctx = egui::Context::default(); + app.ui_ctx = Some(ctx.clone()); + set_pstate(&ctx, "actions-expanded", BTreeSet::from([app.ui.action_sets[0].actions[0].id])); + let texts = super::super::tests_appearance::frame_events(&ctx, &mut app, vec![], show); + let mut rows: Vec = texts.iter().filter(|(s, _)| s == "object.move").map(|(_, r)| *r).collect(); + rows.sort_by(|a, b| a.top().total_cmp(&b.top())); + let (from, to) = (rows[0].center(), egui::pos2(rows[0].center().x, rows[2].center().y + 4.0)); + let accent = Tokens::get(&ctx).accent; + // Whether a frame with `events` draws the insertion line. + let frame = |app: &mut VectorcraftApp, events: Vec| { + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + fn line(s: &egui::Shape, accent: egui::Color32) -> bool { + match s { + egui::Shape::LineSegment { stroke, .. } => stroke.width == 2.0 && stroke.color == accent, + egui::Shape::Vec(v) => v.iter().any(|s| line(s, accent)), + _ => false, + } + } + out.shapes.iter().any(|c| line(&c.shape, accent)) + }; + let button = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + assert!(!frame(&mut app, vec![Event::PointerMoved(from)]), "no line before a drag"); + frame(&mut app, vec![button(from, true)]); + frame(&mut app, vec![Event::PointerMoved(from + egui::vec2(0.0, 12.0))]); + assert!(frame(&mut app, vec![Event::PointerMoved(to)]), "the line shows where the step goes"); + assert_eq!(step_names(&app, 0, 0), ["object.move 1", "object.move 2", "object.move 4"], "nothing moves while dragging"); + frame(&mut app, vec![button(to, false)]); + assert_eq!(step_names(&app, 0, 0), ["object.move 2", "object.move 4", "object.move 1"], "the release moves the step"); + for _ in 0..3 { + assert!(!frame(&mut app, vec![]), "no line after the drop"); + } + assert_eq!(step_names(&app, 0, 0), ["object.move 2", "object.move 4", "object.move 1"], "the step moves once"); + } + + #[test] + fn drag_step_released_off_the_rows_leaves_it_in_place_without_an_undo_step() { + use egui::{Event, PointerButton}; + let (mut app, _) = app_with_three_moves(); + app.ui.action_set = Some(0); + let ctx = egui::Context::default(); + app.ui_ctx = Some(ctx.clone()); + set_pstate(&ctx, "actions-expanded", BTreeSet::from([app.ui.action_sets[0].actions[0].id])); + let texts = super::super::tests_appearance::frame_events(&ctx, &mut app, vec![], show); + let mut rows: Vec = texts.iter().filter(|(s, _)| s == "object.move").map(|(_, r)| *r).collect(); + rows.sort_by(|a, b| a.top().total_cmp(&b.top())); + let from = rows[0].center(); + let over = egui::pos2(from.x, rows[2].center().y + 4.0); + let off = egui::pos2(from.x, rows[2].bottom() + 2_000.0); + let undo = undo_steps(&app); + let frame = |app: &mut VectorcraftApp, events: Vec| { + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + }; + let button = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(&mut app, vec![button(from, true)]); + frame(&mut app, vec![Event::PointerMoved(from + egui::vec2(0.0, 12.0))]); + frame(&mut app, vec![Event::PointerMoved(over)]); + frame(&mut app, vec![Event::PointerMoved(off)]); + frame(&mut app, vec![button(off, false)]); + for _ in 0..3 { + frame(&mut app, vec![]); + } + assert_eq!(step_names(&app, 0, 0), ["object.move 1", "object.move 2", "object.move 4"], "the step stays where it was"); + assert_eq!(undo_steps(&app), undo, "no undo step"); + assert_eq!(pstate::>(&ctx, DRAGGED_STEP), None, "the drag ends"); + } + + #[test] + fn drag_step_ends_without_a_move_when_a_command_changes_its_action() { + use egui::{Event, PointerButton}; + let (mut app, _) = app_with_three_moves(); + let rotate = |angle: u32| ("object.rotate".to_string(), json!({"angle": angle})); + app.ui.action_sets[0].actions.push(Action::new("Turns", vec![rotate(5), rotate(6)])); + app.ui.action_set = Some(0); + let ctx = egui::Context::default(); + app.ui_ctx = Some(ctx.clone()); + set_pstate(&ctx, "actions-expanded", BTreeSet::from([app.ui.action_sets[0].actions[0].id])); + let texts = super::super::tests_appearance::frame_events(&ctx, &mut app, vec![], show); + let mut rows: Vec = texts.iter().filter(|(s, _)| s == "object.move").map(|(_, r)| *r).collect(); + rows.sort_by(|a, b| a.top().total_cmp(&b.top())); + let (from, to) = (rows[0].center(), egui::pos2(rows[0].center().x, rows[1].center().y + 4.0)); + let frame = |app: &mut VectorcraftApp, events: Vec| { + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + }; + let button = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + let start_drag = |app: &mut VectorcraftApp| { + frame(app, vec![button(from, true)]); + frame(app, vec![Event::PointerMoved(from + egui::vec2(0.0, 12.0))]); + }; + // A command on another action leaves the drag as it is. + start_drag(&mut app); + app.run(DELETE_STEP, json!({"set": 0, "action": 1, "step": 0})).unwrap(); + frame(&mut app, vec![Event::PointerMoved(to)]); + frame(&mut app, vec![button(to, false)]); + assert_eq!(step_names(&app, 0, 0), ["object.move 2", "object.move 1", "object.move 4"], "the dragged step moves"); + // A command that deletes the dragged step's action's first step puts another step at the + // dragged index. + start_drag(&mut app); + app.run(DELETE_STEP, json!({"set": 0, "action": 0, "step": 0})).unwrap(); + frame(&mut app, vec![Event::PointerMoved(to)]); + assert_eq!(pstate::>(&ctx, DRAGGED_STEP), None, "the drag ends"); + frame(&mut app, vec![button(to, false)]); + assert_eq!(step_names(&app, 0, 0), ["object.move 1", "object.move 4"], "no other step moves"); + // Two equal steps, one excluded, that change places put the other one at the dragged index. + let same = ("object.move".to_string(), json!({"dx": 1, "dy": 0})); + app.ui.action_sets[0].actions[0].steps = vec![same.clone(), same]; + app.ui.action_sets[0].actions[0].excluded_steps = BTreeSet::from([1]); + start_drag(&mut app); + app.run(MOVE_STEP, json!({"set": 0, "action": 0, "step": 1, "before": 0})).unwrap(); + frame(&mut app, vec![Event::PointerMoved(to)]); + frame(&mut app, vec![button(to, false)]); + assert_eq!(app.ui.action_sets[0].actions[0].excluded_steps, BTreeSet::from([0]), "the excluded step stays first"); + } + #[test] fn step_and_set_edits_keep_an_open_insert_menu_item_on_its_place() { let (mut app, _) = app_with_three_moves(); diff --git a/crates/ui-egui/src/panels/brushes.rs b/crates/ui-egui/src/panels/brushes.rs index 8f29c70475..82991005ab 100644 --- a/crates/ui-egui/src/panels/brushes.rs +++ b/crates/ui-egui/src/panels/brushes.rs @@ -637,10 +637,16 @@ impl LibraryKind for BrushLibraries { fn path(app: &VectorcraftApp, id: &str) -> Option { app.session.brush_libraries.path(id).map(str::to_string) } - fn rows<'a>(lib: &'a Self::Lib, query: &str) -> Vec> { - let found = |n: &str| query.is_empty() || n.to_lowercase().contains(query); + /// Find matches a brush's name as shown and as stored. + fn rows<'a>(lib: &'a Self::Lib, id: &str, query: &str) -> Vec> { + let found = |n: &str| query.is_empty() || n.to_lowercase().contains(query) || Self::label(id, n).to_lowercase().contains(query); lib.iter().filter(|b| found(b.name())).map(|b| Row { name: b.name(), item: Some(b) }).collect() } + /// A built-in library's brush in the UI language; a User Defined or loaded library's brush as + /// it is named. + fn label<'a>(id: &str, name: &'a str) -> &'a str { + super::label_or_name(name, brushlib::BUILTIN.iter().any(|b| b.id == id)) + } /// The brush's stroke preview, drawn with the library's resources. fn draw(_: &VectorcraftApp, ui: &Ui, r: egui::Rect, b: &LibBrush, selected: bool, hovered: bool) { chip(ui, r, &b.lib.doc, &b.shown.def, b.shown.key); diff --git a/crates/ui-egui/src/panels/character.rs b/crates/ui-egui/src/panels/character.rs index e744640a72..c7a3e818cd 100644 --- a/crates/ui-egui/src/panels/character.rs +++ b/crates/ui-egui/src/panels/character.rs @@ -929,8 +929,13 @@ fn set_anti_alias(app: &mut VectorcraftApp, m: TypeAntiAlias) { /// The Font Size combo (Character and Properties panels, Control bar): typed, stepped, scrubbed or /// picked from the presets, in the type unit, blank where the selected text's sizes differ. pub(crate) fn size_field(app: &mut VectorcraftApp, ui: &mut Ui, id: &str, width: f32) { + size_field_named(app, ui, id, None, width); +} + +/// [`size_field`] named `name` for screen readers, where no label stands beside it. +fn size_field_named(app: &mut VectorcraftApp, ui: &mut Ui, id: &str, name: Option<&str>, width: f32) { let size = shared_effective(app, |s| s.size); - if let Some(v) = widgets::spin_field(ui, id, size, app.session.type_unit(), width, 1.0, 0.1, &SIZE_PRESETS) { + if let Some(v) = widgets::spin_field_named(ui, id, name, size, app.session.type_unit(), width, 1.0, 0.1, &SIZE_PRESETS) { style(app, json!({"size": v})); } } @@ -1043,7 +1048,7 @@ pub(crate) fn font_pickers(app: &mut VectorcraftApp, ui: &mut Ui, s: &CharStyle, "cb-font" => Some(crate::font_menu::WheelOwner::Control), _ => None, }; - font_pickers_owned(app, ui, s, ids, widths, wheel_owner); + font_pickers_owned(app, ui, s, ids, widths, wheel_owner, (None, None)); } fn font_pickers_owned( @@ -1053,16 +1058,17 @@ fn font_pickers_owned( ids: (&str, &str), widths: (f32, f32), wheel_owner: Option, + a11y: (Option<&str>, Option<&str>), ) { crate::font_menu::sync_wheel_target(app, ui.ctx(), ui.ctx().viewport_id()); let sample = crate::font_menu::sample_text(app); - let look = crate::font_menu::MenuLook { wheel: true, wheel_owner, ..crate::font_menu::MenuLook::of(app) }; + let look = crate::font_menu::MenuLook { wheel: true, wheel_owner, name: a11y.0, ..crate::font_menu::MenuLook::of(app) }; if let Some(pick) = crate::font_menu::font_menu(ui, ids.0, &s.font_family, widths.0, sample.as_deref(), look) { crate::font_menu::apply(app, ui.ctx(), pick); } let styles = vectorcraft_text::FontDb::global().styles(&s.font_family); let names: Vec<&str> = styles.iter().map(String::as_str).collect(); - if let Some(name) = widgets::dropdown_names(ui, ids.1, &s.font_style, &names, widths.1).and_then(|i| names.get(i)) { + if let Some(name) = widgets::dropdown_names_named(ui, ids.1, a11y.1, &s.font_style, &names, widths.1).and_then(|i| names.get(i)) { style(app, json!({"style": name})); } } @@ -1157,6 +1163,35 @@ pub(crate) fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) { crate::chrome::group_separator(ui); } +/// The Contextual Task Bar's widths of the font family menu, the font style dropdown and the +/// Font Size combo. +pub(crate) const TASK_BAR_WIDTHS: [f32; 3] = [140.0, 90.0, 76.0]; + +/// The smallest share of [`TASK_BAR_WIDTHS`] the Contextual Task Bar's type controls narrow to. +const TASK_BAR_MIN_SCALE: f32 = 0.4; + +/// The gaps between the Contextual Task Bar's type controls. +fn task_bar_gaps() -> f32 { + 6.0 * (TASK_BAR_WIDTHS.len() - 1) as f32 +} + +/// The narrowest room the Contextual Task Bar's type controls fit in, with their spacing. +pub(crate) fn task_bar_min_room() -> f32 { + TASK_BAR_MIN_SCALE * TASK_BAR_WIDTHS.iter().sum::() + task_bar_gaps() +} + +/// The Contextual Task Bar's type controls while type is selected or edited: the font family and +/// style menus and the Font Size combo, as the Control bar has them, named for screen readers. +/// They narrow, down to 40% of their widths, to fit in `room` points with their spacing. +pub(crate) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, room: f32) { + let Some((s, _)) = text_style(app) else { return }; + let k = ((room - task_bar_gaps()) / TASK_BAR_WIDTHS.iter().sum::()).clamp(TASK_BAR_MIN_SCALE, 1.0); + let [family, style, size] = TASK_BAR_WIDTHS.map(|w| w * k); + let owner = Some(crate::font_menu::WheelOwner::TaskBar); + font_pickers_owned(app, ui, &s, ("tb-font", "tb-font-style"), (family, style), owner, (Some(tl!("Font Family")), Some(tl!("Style")))); + size_field_named(app, ui, "tb-font-size", Some(tl!("Font Size")), size); +} + /// The panel state key of the panel menu's Show Snap to Glyph Options. const SNAP_TO_GLYPH_OPTIONS: &str = "ch-snap-to-glyph-options"; /// Set when Show Snap to Glyph Options is chosen: the next frame scrolls the panel to the options, @@ -1227,7 +1262,7 @@ fn attributes(app: &mut VectorcraftApp, ui: &mut Ui, owner: crate::font_menu::Wh if let Some(f) = app.character_focus { widgets::arm_field_focus(ui.ctx(), f.salt()); } - font_pickers_owned(app, ui, &s, ("ch-font", "ch-style"), (w - 4.0, w - 4.0), Some(owner)); + font_pickers_owned(app, ui, &s, ("ch-font", "ch-style"), (w - 4.0, w - 4.0), Some(owner), (None, None)); variable_font(app, ui, &s, w - 4.0); ui.add_space(2.0); let hidden = pstate::(ui.ctx(), "ch-hide-options"); diff --git a/crates/ui-egui/src/panels/color.rs b/crates/ui-egui/src/panels/color.rs index a28fba02e5..0ad9c369fd 100644 --- a/crates/ui-egui/src/panels/color.rs +++ b/crates/ui-egui/src/panels/color.rs @@ -248,8 +248,9 @@ pub(crate) fn warning_chip(ui: &mut Ui, (icon, warning): (&str, &str), fix: &Col .inner } -/// The printable colour closest to `c` (its working-CMYK reproduction, back in RGB) when `c` is out -/// of the CMYK gamut, through `color.convert`. +/// The printable color closest to `c` (its reproduction in the active CMYK space, the document's +/// assigned CMYK profile or else the working CMYK space, back in RGB) when `c` is out of that +/// space's gamut, through `color.convert`. pub(crate) fn in_gamut(app: &mut VectorcraftApp, c: &Color) -> Option { let r = app.run("color.convert", json!({"color": color_json(c), "to": "cmyk"})).ok()?; if !r["outOfGamut"].as_bool()? { @@ -261,18 +262,25 @@ pub(crate) fn in_gamut(app: &mut VectorcraftApp, c: &Color) -> Option { Some(Color::rgb(v(&rgb, 0)? as f32, v(&rgb, 1)? as f32, v(&rgb, 2)? as f32)) } -/// [`in_gamut`], cached under `key` for the last colour asked (panels ask every frame). +/// [`in_gamut`], cached under `key` for the last color asked (panels ask every frame) together with +/// the active color settings and profiles generation it was asked under, so a change of Color +/// Settings or of the document's assigned profiles updates the warning while the color stays the same. pub(crate) fn gamut_fix(app: &mut VectorcraftApp, ctx: &egui::Context, key: &str, c: &Color) -> Option { - match pstate::)>>(ctx, key) { - Some((k, fix)) if k == *c => fix, + let under = (cms::active_settings(), cms::profiles_generation()); + match pstate::>(ctx, key) { + Some((k, at, fix)) if k == *c && at == under => fix, _ => { let fix = in_gamut(app, c); - set_pstate(ctx, key, Some((*c, fix))); + set_pstate(ctx, key, Some((*c, under, fix))); fix } } } +/// A [`gamut_fix`] cache entry: the color, the active color settings and profiles generation it was +/// asked under, and its correction. +pub(crate) type GamutFix = (Color, (cms::ColorSettings, u64), Option); + /// Serde reader for the saved panel mode ([`crate::UiState::color_mode`]): a menu mode, else none, /// so an unknown value doesn't lose the rest of the preferences. pub fn deserialize_mode<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { diff --git a/crates/ui-egui/src/panels/color/tests.rs b/crates/ui-egui/src/panels/color/tests.rs index 4538a8e5ce..cd7b88cdd0 100644 --- a/crates/ui-egui/src/panels/color/tests.rs +++ b/crates/ui-egui/src/panels/color/tests.rs @@ -349,12 +349,12 @@ fn pure_blue_is_out_of_gamut_in_rgb() { let ctx = egui::Context::default(); app.run("paint.setFill", json!({"color": "#0000ff"})).unwrap(); frame(&mut app, &ctx, vec![], egui::Modifiers::NONE); - let (of, fix) = pstate::)>>(&ctx, "color-gamut").expect("RGB mode checks the gamut"); + let (of, _, fix) = pstate::>(&ctx, "color-gamut").expect("RGB mode checks the gamut"); assert_eq!(of.to_hex(), "#0000ff"); assert!(fix.is_some_and(|f| !f.out_of_gamut())); app.run("paint.setFill", json!({"color": "#808080"})).unwrap(); frame(&mut app, &ctx, vec![], egui::Modifiers::NONE); - assert_eq!(pstate::)>>(&ctx, "color-gamut").unwrap().1, None); + assert_eq!(pstate::>(&ctx, "color-gamut").unwrap().2, None); } #[test] diff --git a/crates/ui-egui/src/panels/gradient.rs b/crates/ui-egui/src/panels/gradient.rs index 83f003e150..777db05811 100644 --- a/crates/ui-egui/src/panels/gradient.rs +++ b/crates/ui-egui/src/panels/gradient.rs @@ -380,20 +380,35 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } } +/// The narrowest the Method menu is drawn (points): the width it had for Classic and Perceptual. +const METHOD_MENU_MIN: f32 = 104.0; +/// The room the Method menu keeps beside its longest name for its arrow and margins (points). +const METHOD_MENU_PAD: f32 = 40.0; + /// The Method row (Illustrator 30): how a linear or radial gradient mixes the colours between its -/// stops, Classic or Perceptual. +/// stops, Classic or Perceptual. Hue Clockwise and Hue Counterclockwise, VectorCraft's own +/// methods, mix them around the hue wheel one way or the other. fn method_row(app: &mut VectorcraftApp, ui: &mut Ui, g: &GradientPaint, is_grad: bool) { - let methods = [(GradientMethod::Classic, tl!("Classic")), (GradientMethod::Perceptual, tl!("Perceptual"))]; + let methods = [ + (GradientMethod::Classic, tl!("Classic")), + (GradientMethod::Perceptual, tl!("Perceptual")), + (GradientMethod::HueClockwise, tl!("Hue Clockwise")), + (GradientMethod::HueCounterclockwise, tl!("Hue Counterclockwise")), + ]; let current = g.gradient.method; let shown = methods.iter().find(|(m, _)| *m == current).map_or("", |(_, l)| *l); ui.horizontal(|ui| { widgets::dim_label(ui, tl!("Method:")); let labels = methods.map(|(_, l)| l); - let chosen = ui.add_enabled_ui(is_grad, |ui| widgets::dropdown_names(ui, "grad-method", shown, &labels, 104.0)).inner; + // Wide enough for the longest method name in the interface language and the arrow beside + // it, within the room the row has. + let widest = labels.iter().map(|l| widgets::text_width(ui, egui::RichText::new(*l).size(12.0))).fold(0.0, f32::max); + let width = (widest + METHOD_MENU_PAD).clamp(METHOD_MENU_MIN, ui.available_width().max(METHOD_MENU_MIN)); + let chosen = ui.add_enabled_ui(is_grad, |ui| widgets::dropdown_names(ui, "grad-method", shown, &labels, width)).inner; if let Some((m, _)) = chosen.and_then(|i| methods.get(i)) && *m != current { - edit(app, json!({"method": m.label().to_lowercase()}), Live::Released); + edit(app, json!({"method": m.id()}), Live::Released); } }); } diff --git a/crates/ui-egui/src/panels/gradient/tests.rs b/crates/ui-egui/src/panels/gradient/tests.rs index 589dbc523a..d5362b8bab 100644 --- a/crates/ui-egui/src/panels/gradient/tests.rs +++ b/crates/ui-egui/src/panels/gradient/tests.rs @@ -328,6 +328,31 @@ fn the_method_menu_makes_the_gradient_perceptual() { assert_eq!(fill(&app).gradient.method, GradientMethod::Classic); } +/// The Method menu lists the two hue methods after Classic and Perceptual; choosing one mixes +/// the gradient around the hue wheel that way, as one undo step, and the menu then shows it. +#[test] +fn the_method_menu_mixes_the_gradient_around_the_hue_wheel() { + for (label, method) in [("Hue Clockwise", GradientMethod::HueClockwise), ("Hue Counterclockwise", GradientMethod::HueCounterclockwise)] { + let mut app = app(json!({"gradient": {}})); + let mut p = Panel::new(); + let texts = p.frame(&mut app, vec![], Modifiers::NONE); + let shown = texts.iter().find(|(t, _)| t == "Classic").expect("Classic shown").1; + let undo = app.session.doc().unwrap().history.undo.len(); + let texts = p.click(&mut app, shown); + for listed in ["Classic", "Perceptual", "Hue Clockwise", "Hue Counterclockwise"] { + assert!(texts.iter().any(|(t, _)| t == listed), "the menu lists {listed}: {texts:?}"); + } + let option = texts.iter().find(|(t, _)| t == label).expect("the menu lists the method").1; + p.click(&mut app, option); + assert_eq!(fill(&app).gradient.method, method, "{label}"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1, "{label}: one undo step"); + let texts = p.frame(&mut app, vec![], Modifiers::NONE); + assert!(texts.iter().any(|(t, _)| t == label), "the menu shows the method: {texts:?}"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(fill(&app).gradient.method, GradientMethod::Classic); + } +} + /// The Spread menu makes the gradient repeat (one undo step), and the Repeats field, dimmed while /// it pads, then sets the count. #[test] diff --git a/crates/ui-egui/src/panels/graphic_styles.rs b/crates/ui-egui/src/panels/graphic_styles.rs index fe38851b44..b87f291e67 100644 --- a/crates/ui-egui/src/panels/graphic_styles.rs +++ b/crates/ui-egui/src/panels/graphic_styles.rs @@ -726,7 +726,7 @@ impl LibraryKind for GraphicStyleLibraries { fn path(app: &VectorcraftApp, id: &str) -> Option { app.session.style_libraries.path(id).map(str::to_string) } - fn rows<'a>(lib: &'a Self::Lib, query: &str) -> Vec> { + fn rows<'a>(lib: &'a Self::Lib, _: &str, query: &str) -> Vec> { let found = |n: &str| query.is_empty() || n.to_lowercase().contains(query); lib.iter().filter(|s| found(&s.style().name)).map(|s| Row { name: &s.style().name, item: Some(s) }).collect() } diff --git a/crates/ui-egui/src/panels/library_panel.rs b/crates/ui-egui/src/panels/library_panel.rs index a4d9b4c0d8..fdfb2f7c3b 100644 --- a/crates/ui-egui/src/panels/library_panel.rs +++ b/crates/ui-egui/src/panels/library_panel.rs @@ -104,8 +104,13 @@ pub(crate) trait LibraryKind { fn find(app: &VectorcraftApp, key: &str) -> Found; /// The file library `id` was read from, if any. fn path(app: &VectorcraftApp, id: &str) -> Option; - /// The rows matching the find field's `query` (lower case; empty: all). - fn rows<'a>(lib: &'a Self::Lib, query: &str) -> Vec>; + /// The rows of library `id` matching the find field's `query` (lower case; empty: all). + fn rows<'a>(lib: &'a Self::Lib, id: &str, query: &str) -> Vec>; + /// Row `name` of library `id` as its list row and tooltips show it (by default as it is). The + /// row keeps `name` for its tile, selection, clicks, drags and the commands they run. + fn label<'a>(_id: &str, name: &'a str) -> &'a str { + name + } /// An item's thumbnail in `r`. fn draw(app: &VectorcraftApp, ui: &Ui, r: Rect, item: &Self::Item, selected: bool, hovered: bool); /// The icons at the right of list row `r`. @@ -626,7 +631,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { let (view, hide_find) = settings(&app.ui, K::KIND, id).map_or((K::VIEW, false), |s| (s.view.unwrap_or(K::VIEW), s.hide_find)); let query = if hide_find { String::new() } else { widgets::search_field(ui, egui::Id::unique(key(&panel, "find")), tl!("Find")) }; ui.add_space(4.0); - let rows = K::rows(&lib, &query.trim().to_lowercase()); + let rows = K::rows(&lib, id, &query.trim().to_lowercase()); let selected = selection(ui.ctx(), &panel); let is_sel = |n: &str| selected.iter().any(|s| s == n); let mut clicked: Option<(String, bool, egui::Modifiers)> = None; @@ -659,9 +664,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { } None => super::swatches::draw_folder(ui, chip), } - list_row_name(ui, r, chip, row.name); + let label = K::label(id, row.name); + list_row_name(ui, r, chip, label); drag_out::(ui, &resp, id, row); - let tip = || row.item.map_or_else(|| row.name.to_string(), |i| format!("{} ({})", row.name, K::describe(i))); + let tip = || row.item.map_or_else(|| label.to_string(), |i| format!("{label} ({})", K::describe(i))); click(ui, resp, row, &tip); } } else { @@ -672,7 +678,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { None => folder_tile(ui, cell, is_sel(row.name)), } drag_out::(ui, &resp, id, row); - click(ui, resp, row, &|| row.name.to_string()); + click(ui, resp, row, &|| K::label(id, row.name).to_string()); } } }); diff --git a/crates/ui-egui/src/panels/library_panel/tests.rs b/crates/ui-egui/src/panels/library_panel/tests.rs index 034a90e5b0..5d6fef049b 100644 --- a/crates/ui-egui/src/panels/library_panel/tests.rs +++ b/crates/ui-egui/src/panels/library_panel/tests.rs @@ -127,7 +127,7 @@ fn a_plain_click_sets_where_a_shift_click_range_starts() { let ctx = context(); app.run("window.swatchLibrary", json!({"library": "pastels"})).unwrap(); let (_, lib) = SwatchLibraries::get(&app, "pastels").unwrap(); - let order: Vec = SwatchLibraries::rows(&lib, "").iter().map(|r| r.name.to_string()).collect(); + let order: Vec = SwatchLibraries::rows(&lib, "pastels", "").iter().map(|r| r.name.to_string()).collect(); click(&mut app, &ctx, &order[1], Modifiers::NONE, 0.0); click(&mut app, &ctx, &order[4], Modifiers::SHIFT, 2.0); assert_eq!(selection(&ctx, "library:swatches:pastels"), order[1..=4], "the range starts at the plain click"); diff --git a/crates/ui-egui/src/panels/swatches/libraries.rs b/crates/ui-egui/src/panels/swatches/libraries.rs index 772bc8e28d..864f6ae7e0 100644 --- a/crates/ui-egui/src/panels/swatches/libraries.rs +++ b/crates/ui-egui/src/panels/swatches/libraries.rs @@ -83,7 +83,7 @@ impl LibraryKind for SwatchLibraries { } /// Ungrouped swatches, then each colour group's folder and swatches (a group whose name /// matches shows all of them), as in the Swatches panel. - fn rows<'a>(lib: &'a Self::Lib, query: &str) -> Vec> { + fn rows<'a>(lib: &'a Self::Lib, _: &str, query: &str) -> Vec> { let found = |n: &str| query.is_empty() || n.to_lowercase().contains(query); let row = |w: &'a Swatch| Row { name: &w.name, item: Some(w) }; let mut out: Vec> = lib.swatches.iter().filter(|w| found(&w.name)).map(row).collect(); diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index 04f99c3c1f..ad081ddfcd 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -496,7 +496,7 @@ impl LibraryKind for SymbolLibraries { fn path(app: &VectorcraftApp, id: &str) -> Option { app.session.symbol_libraries.path(id).map(str::to_string) } - fn rows<'a>(lib: &'a Self::Lib, query: &str) -> Vec> { + fn rows<'a>(lib: &'a Self::Lib, _: &str, query: &str) -> Vec> { let found = |n: &str| query.is_empty() || n.to_lowercase().contains(query); lib.iter().filter(|s| found(s.name())).map(|s| Row { name: s.name(), item: Some(s) }).collect() } diff --git a/crates/ui-egui/src/panels/tests_brush_libraries.rs b/crates/ui-egui/src/panels/tests_brush_libraries.rs index 263342741a..6da376c7ca 100644 --- a/crates/ui-egui/src/panels/tests_brush_libraries.rs +++ b/crates/ui-egui/src/panels/tests_brush_libraries.rs @@ -103,7 +103,7 @@ fn clicking_a_library_brush_adds_it_to_the_documents_brushes_in_one_step() { assert!(has(&app, "Teardrop") && has(&app, "Double Line")); // Find filters by name; list rows give the type. let lib = BrushLibraries::get(&app, "art-ribbons").unwrap().1; - let rows = BrushLibraries::rows(&lib, "tear"); + let rows = BrushLibraries::rows(&lib, "art-ribbons", "tear"); assert_eq!(rows.iter().map(|r| r.name).collect::>(), ["Teardrop"]); assert_eq!(BrushLibraries::describe(rows[0].item.unwrap()), "Art"); // Dragging a brush out of the panel carries it. @@ -127,7 +127,7 @@ fn the_ink_and_wash_library_opens_and_a_click_adds_and_applies_its_brush() { let r = app.run("window.brushLibrary", json!({"library": "ink-and-wash"})).unwrap(); assert_eq!((r["open"].as_str(), r["count"].as_u64()), (Some("ink-and-wash"), Some(4))); let lib = BrushLibraries::get(&app, "ink-and-wash").unwrap().1; - let rows = BrushLibraries::rows(&lib, ""); + let rows = BrushLibraries::rows(&lib, "ink-and-wash", ""); assert_eq!(rows.iter().map(|r| r.name).collect::>(), ["Tapered Ink", "Brush Pen", "Soft Wash", "Pooling Wash"]); let path = app.run("shape.line", json!({"x1": 10, "y1": 10, "x2": 150, "y2": 60})).unwrap()["id"].as_u64().unwrap(); let (undo, brushes) = (undo_len(&app), count(&app)); @@ -140,6 +140,48 @@ fn the_ink_and_wash_library_opens_and_a_click_adds_and_applies_its_brush() { assert_eq!(app.run("brush.list", json!({})).unwrap()["current"], "Brush Pen"); } +/// A built-in library lists its brushes in the UI language, and Find matches the name shown and +/// the brush's own name. The brush keeps its own name for its tile, a click and the document's +/// Brushes. A library loaded from a document lists its brushes as they are named. +#[test] +fn built_in_library_brushes_are_listed_in_the_ui_language() { + let dir = std::env::temp_dir().join(format!("vc-brush-names-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut app = app(); + let ctx = context(); + crate::i18n::set_current(crate::i18n::Lang::from_code("fr").expect("fr registered")); + let list = |app: &mut VectorcraftApp, t: f64| { + let panel = last_open(&app.ui).map(LibraryPanel::panel).unwrap_or_default(); + app.run("ui.libraryPanel", json!({"panel": panel, "view": "smallList"})).unwrap(); + frame(&ctx, vec![], t, |ui| library_panel::show_window(app, ui.ctx())); + frame(&ctx, vec![], t + 0.25, |ui| library_panel::show_window(app, ui.ctx())) + }; + app.run("window.brushLibrary", json!({"library": "ink-and-wash"})).unwrap(); + let texts = list(&mut app, 0.0); + assert!(texts.iter().any(|t| t == "Encre effilée"), "{texts:?}"); + assert!(!texts.iter().any(|t| t == "Tapered Ink"), "{texts:?}"); + let lib = BrushLibraries::get(&app, "ink-and-wash").unwrap().1; + for query in ["effil", "tapered"] { + let rows = BrushLibraries::rows(&lib, "ink-and-wash", query); + assert_eq!(rows.iter().map(|r| r.name).collect::>(), ["Tapered Ink"], "{query}"); + } + assert!(BrushLibraries::rows(&lib, "loaded/1", "effil").is_empty(), "another library's brush is matched by its own name only"); + click(&mut app, &ctx, "Tapered Ink", Modifiers::NONE, 1.0); + assert!(has(&app, "Tapered Ink")); + assert_eq!(app.run("brush.list", json!({})).unwrap()["current"], "Tapered Ink"); + // The document's brushes, opened as a library, keep their names. + let doc = dir.join("Inks.vectorcraft"); + let b64 = app.run("document.serialize", json!({})).unwrap()["dataBase64"].as_str().unwrap().to_string(); + std::fs::write(&doc, vectorcraft_format::base64_decode(&b64).unwrap()).unwrap(); + app.run("window.brushLibrary.other", json!({"path": doc.to_string_lossy()})).unwrap(); + let texts = list(&mut app, 2.0); + assert!(texts.iter().any(|t| t == "Tapered Ink"), "{texts:?}"); + assert!(!texts.iter().any(|t| t == "Encre effilée"), "{texts:?}"); + crate::i18n::set_current(crate::i18n::Lang::EN); + let _ = std::fs::remove_dir_all(dir); +} + #[test] fn the_window_menu_and_the_brushes_panel_open_brush_libraries() { let mut app = app(); diff --git a/crates/ui-egui/src/panels/tests_style_libraries.rs b/crates/ui-egui/src/panels/tests_style_libraries.rs index 46c274dee6..2adeda9812 100644 --- a/crates/ui-egui/src/panels/tests_style_libraries.rs +++ b/crates/ui-egui/src/panels/tests_style_libraries.rs @@ -92,7 +92,7 @@ fn clicking_a_library_style_adds_and_applies_it_in_one_step() { assert!(d.graphic_style("Feathered").is_some() && d.graphic_style("Haze").is_some()); // Find filters by name; list rows describe the styles; looks are computed once per library. let lib = GraphicStyleLibraries::get(&app, "shadows-glows").unwrap().1; - let rows = GraphicStyleLibraries::rows(&lib, "ember"); + let rows = GraphicStyleLibraries::rows(&lib, "shadows-glows", "ember"); assert_eq!(rows.iter().map(|r| r.name).collect::>(), ["Ember"]); assert_eq!(GraphicStyleLibraries::describe(rows[0].item.unwrap()), "1 fill, Inner Glow, Outer Glow"); assert!(std::sync::Arc::ptr_eq(&lib, &GraphicStyleLibraries::get(&app, "shadows-glows").unwrap().1)); @@ -121,7 +121,7 @@ fn painted_and_sketched_opens_from_the_window_menu_and_a_click_applies_its_style let node = app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(rect)).unwrap().appearance.effects.clone(); assert_eq!(node.iter().map(|e| e.id.as_str()).collect::>(), ["sketch.charcoal"]); let lib = GraphicStyleLibraries::get(&app, "painted-sketched").unwrap().1; - let rows = GraphicStyleLibraries::rows(&lib, "ink"); + let rows = GraphicStyleLibraries::rows(&lib, "painted-sketched", "ink"); assert_eq!(rows.iter().map(|r| r.name).collect::>(), ["Ink Contour", "Wet Ink"]); } diff --git a/crates/ui-egui/src/panels/tests_symbol_libraries.rs b/crates/ui-egui/src/panels/tests_symbol_libraries.rs index 0d70425e81..9c58bc49c7 100644 --- a/crates/ui-egui/src/panels/tests_symbol_libraries.rs +++ b/crates/ui-egui/src/panels/tests_symbol_libraries.rs @@ -89,7 +89,7 @@ fn clicking_a_library_symbol_adds_it_to_the_documents_symbols_in_one_step() { assert_eq!(symbols(&app), ["Star", "Hexagon", "Arrow"]); // Find filters by name; list rows give the natural size. let lib = SymbolLibraries::get(&app, "basic-shapes").unwrap().1; - let rows = SymbolLibraries::rows(&lib, "arr"); + let rows = SymbolLibraries::rows(&lib, "basic-shapes", "arr"); assert_eq!(rows.iter().map(|r| r.name).collect::>(), ["Arrow"]); assert_eq!(SymbolLibraries::describe(rows[0].item.unwrap()), "48 × 32 pt"); // Dragging a symbol out of the panel carries it to the canvas. diff --git a/crates/ui-egui/src/place.rs b/crates/ui-egui/src/place.rs index 94ae695ca4..fff3587182 100644 --- a/crates/ui-egui/src/place.rs +++ b/crates/ui-egui/src/place.rs @@ -33,6 +33,9 @@ pub type PlaceInbox = Arc>>; #[derive(Clone, Copy, Debug, PartialEq)] pub struct DropAt { pub doc: u64, + /// The document's [`vectorcraft_engine::DocState::reverts`] at the drop: files that arrive + /// after File → Revert threw that content away are not placed. + pub reverts: u64, pub at: Point, pub embed: bool, } @@ -455,7 +458,7 @@ impl VectorcraftApp { None if is_document(name) => return DropTarget::Open, None => v.center, }; - DropTarget::Place(DropAt { doc: st.uid, at, embed: shift }) + DropTarget::Place(DropAt { doc: st.uid, reverts: st.reverts, at, embed: shift }) } } @@ -473,7 +476,7 @@ pub type DropFile = (String, Option, Vec); /// Files dropped on the window, each placed on a canvas or opened (and added to Open Recent /// Files) as its target says: the placed ones first, so the last document opened is the one /// shown. A file for a canvas goes to the document it was dropped on, which becomes active again; -/// it isn't placed when that document has closed since. +/// it isn't placed when that document has closed or been reverted since. pub fn drop_files(app: &mut VectorcraftApp, mut files: Vec<(DropTarget, DropFile)>) { files.sort_by_key(|(target, _)| *target == DropTarget::Open); for (target, (name, path, bytes)) in files { @@ -482,6 +485,10 @@ pub fn drop_files(app: &mut VectorcraftApp, mut files: Vec<(DropTarget, DropFile app.status(format!("Couldn't place {name}: the document it was dropped on was closed")); continue; }; + if app.session.documents().get(i).is_some_and(|st| st.reverts != d.reverts) { + app.status(format!("Couldn't place {name}: the document it was dropped on was reverted")); + continue; + } app.session.set_active(i); } let r = match target { diff --git a/crates/ui-egui/src/placing.rs b/crates/ui-egui/src/placing.rs index 3eacb28322..11ae770d5d 100644 --- a/crates/ui-egui/src/placing.rs +++ b/crates/ui-egui/src/placing.rs @@ -111,6 +111,9 @@ struct Chain { left: Option>, /// How many of its pastes wait. waiting: usize, + /// The document's [`vectorcraft_engine::DocState::reverts`] when the chain started: a paste + /// given after a File → Revert does not join it. + reverts: u64, } /// What a paste whose bitmap was decoded off the UI thread pastes. @@ -129,6 +132,9 @@ pub struct Pending { pub label: String, /// The document they are placed in ([`vectorcraft_engine::DocState::uid`]). doc: u64, + /// Its [`vectorcraft_engine::DocState::reverts`] when the read started: a read for content that + /// File → Revert has since thrown away is dropped. + reverts: u64, /// Whether the file was dropped on the canvas (its messages say so, as /// [`crate::place::drop_files`]'s do). dropped: bool, @@ -177,6 +183,8 @@ struct PendingSwatch { insertion: Insertion, selection: Vec, doc: u64, + /// The document's [`vectorcraft_engine::DocState::reverts`] when the dialog opened. + reverts: u64, chain: u64, } @@ -254,14 +262,19 @@ pub fn adopt_for_paste(app: &mut VectorcraftApp, id: &str, p: &Value) -> Result< return Ok(None); } let copied = app.clipboard_publishing.latest(); - let (doc, objects) = app.session.doc().map(|st| (st.uid, st.selection.objects.clone())).map_err(|e| e.to_string())?; + let (doc, reverts, objects) = app.session.doc().map(|st| (st.uid, st.reverts, st.selection.objects.clone())).map_err(|e| e.to_string())?; let insertion = Insertion::of(app).ok_or("no document")?; // A paste given while one of the document's latest chain waits, with the selection and the // insertion context that chain expects, joins it: it goes next to what the paste before it - // leaves selected, as at once. Otherwise it starts a chain. + // leaves selected, as at once. Otherwise (also when the document was reverted since the chain + // started) it starts a chain. let context = (objects, insertion.clone()); - let joins = - app.placing.latest_chain.get(&doc).copied().filter(|c| app.placing.chains.get(c).is_some_and(|ch| ch.waiting > 0 && ch.context == context)); + let joins = app + .placing + .latest_chain + .get(&doc) + .copied() + .filter(|c| app.placing.chains.get(c).is_some_and(|ch| ch.waiting > 0 && ch.reverts == reverts && ch.context == context)); let (chain, selection) = match joins { Some(chain) => (chain, None), None => (app.placing.next_chain, Some(context.0.clone())), @@ -285,7 +298,7 @@ pub fn adopt_for_paste(app: &mut VectorcraftApp, id: &str, p: &Value) -> Result< if started.is_some() { if joins.is_none() { app.placing.next_chain += 1; - app.placing.chains.insert(chain, Chain { context, left: None, waiting: 0 }); + app.placing.chains.insert(chain, Chain { context, left: None, waiting: 0, reverts }); app.placing.latest_chain.insert(doc, chain); } if let Some(ch) = app.placing.chains.get_mut(&chain) { @@ -321,7 +334,7 @@ fn spawn_labeled( chain: Option, read: impl FnOnce() -> Result + Send + 'static, ) -> Result, String> { - let doc = app.session.doc().map_err(|e| e.to_string())?.uid; + let (doc, reverts) = app.session.doc().map(|st| (st.uid, st.reverts)).map_err(|e| e.to_string())?; let (tx, done) = channel(); // The automation roots in force here are in force there. let scope = ScopeHandle::capture(); @@ -360,7 +373,7 @@ fn spawn_labeled( let _ = reader.send(job); app.placing.reader = Some(reader); } - app.placing.pending.push(Pending { name, label: label.clone(), doc, dropped, paste: chain.is_some(), chain, done, scope: completion }); + app.placing.pending.push(Pending { name, label: label.clone(), doc, reverts, dropped, paste: chain.is_some(), chain, done, scope: completion }); let status = format!("{label}…"); app.status(status.clone()); Ok(Some(json!({ "background": true, "status": status }))) @@ -416,6 +429,19 @@ fn finish(app: &mut VectorcraftApp, p: &Pending, r: Result) { } return; }; + // File → Revert threw away the content the read was started for: what was read is dropped, + // with the document, its selection, the clipboard and the tools as they are. + if app.session.documents().get(i).is_some_and(|st| st.reverts != p.reverts) { + let name = &p.name; + if p.paste { + app.status("Couldn't paste: the document it was pasted in was reverted"); + } else if p.dropped { + app.status(format!("Couldn't place {name}: the document it was dropped on was reverted")); + } else { + app.status(format!("Couldn't place {name}: the document it was placed in was reverted")); + } + return; + } if p.paste { let error = match &r { Ok(Read::Paste(paste)) => match &paste.pasted { @@ -508,6 +534,7 @@ fn finish_paste(app: &mut VectorcraftApp, paste: Paste) { insertion: paste.insertion.clone(), selection: requested_selection, doc: st.uid, + reverts: st.reverts, chain, }); deferred = true; @@ -579,6 +606,12 @@ pub(crate) fn confirm_swatch_paste(app: &mut VectorcraftApp, id: &str, params: V finish_chain(app, waiting.chain); return Err("Couldn't paste: the document it was pasted in was closed".into()); }; + // File → Revert threw away the content the paste was given in: nothing is pasted, and the + // clipboard, selection and insertion context stay as they are. + if app.session.documents().get(index).is_some_and(|st| st.reverts != waiting.reverts) { + finish_chain(app, waiting.chain); + return Err("Couldn't paste: the document it was pasted in was reverted".into()); + } app.session.set_active(index); app.sync_views(); let current = std::mem::replace(&mut app.session.clipboard, waiting.clipboard); diff --git a/crates/ui-egui/src/placing/tests.rs b/crates/ui-egui/src/placing/tests.rs index 9afe94b9ee..dbb37ff446 100644 --- a/crates/ui-egui/src/placing/tests.rs +++ b/crates/ui-egui/src/placing/tests.rs @@ -971,7 +971,7 @@ fn what_the_user_places_is_read_off_the_ui_thread_and_commands_read_at_once() { app.select_tool("selection"); // A drop and bytes placed without a path. let doc = app.session.doc().unwrap().uid; - let drop = DropTarget::Place(DropAt { doc, at: vectorcraft_geom::Point::new(100.0, 100.0), embed: false }); + let drop = DropTarget::Place(DropAt { doc, reverts: 0, at: vectorcraft_geom::Point::new(100.0, 100.0), embed: false }); crate::place::drop_files(&mut app, vec![(drop, ("b.bmp".into(), Some(b.clone()), vec![]))]); crate::io::place_bytes(&mut app, "c.png", &picture(Png, 10, 10)).unwrap(); assert_eq!(app.placing.pending.len(), 2); @@ -1044,7 +1044,7 @@ fn files_dropped_together_are_placed_in_the_order_dropped() { let small = [saved("order", "small1.png", &picture(Png, 8, 8)), saved("order", "small2.png", &picture(Png, 8, 8))]; let mut app = app(true); let doc = app.session.doc().unwrap().uid; - let drop = DropTarget::Place(DropAt { doc, at: vectorcraft_geom::Point::new(200.0, 150.0), embed: false }); + let drop = DropTarget::Place(DropAt { doc, reverts: 0, at: vectorcraft_geom::Point::new(200.0, 150.0), embed: false }); let files = [&large, &small[0], &small[1]].map(|p| (drop, (vectorcraft_engine::cmd::fileio::file_name(p), Some(p.clone()), vec![]))); crate::place::drop_files(&mut app, files.into()); assert_eq!(app.placing.pending.len(), 3); @@ -1059,7 +1059,7 @@ fn files_dropped_together_are_read_one_at_a_time() { let files: Vec = (0..4).map(|i| saved("one-at-a-time", &format!("large{i}.tif"), &picture(Tiff, 1500, 1500))).collect(); let mut app = app(true); let doc = app.session.doc().unwrap().uid; - let drop = DropTarget::Place(DropAt { doc, at: vectorcraft_geom::Point::new(200.0, 150.0), embed: false }); + let drop = DropTarget::Place(DropAt { doc, reverts: 0, at: vectorcraft_geom::Point::new(200.0, 150.0), embed: false }); let dropped = files.iter().map(|p| (drop, (vectorcraft_engine::cmd::fileio::file_name(p), Some(p.clone()), vec![]))).collect(); crate::place::drop_files(&mut app, dropped); placed(&mut app); @@ -1123,7 +1123,7 @@ fn a_file_that_cant_be_read_off_the_ui_thread_reports_as_at_once() { let name = vectorcraft_engine::cmd::fileio::file_name(&path); for app in [&mut at_once, &mut app] { let doc = app.session.doc().unwrap().uid; - let drop = DropTarget::Place(DropAt { doc, at: vectorcraft_geom::Point::new(100.0, 100.0), embed: false }); + let drop = DropTarget::Place(DropAt { doc, reverts: 0, at: vectorcraft_geom::Point::new(100.0, 100.0), embed: false }); crate::place::drop_files(app, vec![(drop, (name.clone(), Some(path.clone()), vec![]))]); placed(app); } @@ -1152,6 +1152,164 @@ fn a_file_whose_document_closed_meanwhile_is_not_placed() { } } +/// `app`, which also writes files, with its active document saved to a file in a folder of +/// `test`'s own and then changed (a rectangle drawn since the save) → the app and the file. +fn saved_and_changed(mut app: VectorcraftApp, test: &str) -> (VectorcraftApp, String) { + app.services.write = Some(Box::new(|p: &str, b: &[u8]| std::fs::write(p, b).map_err(|e| e.to_string()))); + let path = saved(test, "saved.vectorcraft", b""); + std::fs::remove_file(&path).unwrap(); + app.run("file.saveAs", json!({"path": path})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + (app, path) +} + +/// A file read for Place, for the place cursor or dropped on the canvas is not placed when File › +/// Revert threw away the content of its document before it was read: the reverted document, its +/// undo steps and the tool stay as they are, and the status bar says why. A file read after the +/// Revert is placed. +#[test] +fn a_file_whose_document_was_reverted_meanwhile_is_not_placed() { + let tif = saved("reverted", "photo.tif", &picture(Tiff, 60, 40)); + for kind in ["place", "drop", "queue"] { + let (mut app, _) = saved_and_changed(app(true), &format!("reverted-{kind}")); + let read = |app: &mut VectorcraftApp| match kind { + "queue" => start_queue(app, &json!({"paths": [tif]})), + _ => start(app, &json!({"path": tif}), kind == "drop"), + }; + read(&mut app).unwrap(); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let reverted = state(&app); + placed(&mut app); + let why = if kind == "drop" { "dropped on" } else { "placed in" }; + assert_eq!(app.ui.status, format!("Couldn't place photo.tif: the document it was {why} was reverted"), "{kind}"); + assert!(state(&app) == reverted, "{kind}: nothing is placed"); + assert_ne!(app.session.tool_id(), "place", "{kind}: the place cursor is not loaded"); + read(&mut app).unwrap(); + placed(&mut app); + if kind == "queue" { + assert_eq!((app.session.tool_id(), app.session.tool_options()["count"].as_u64()), ("place", Some(1))); + } else { + assert_eq!(names(&app), ["photo.tif"], "{kind}: a file read after the Revert is placed"); + } + } +} + +/// A Revert that fails, or that a batch rolls back, leaves a file being read for its document to +/// be placed, and a Revert of one document leaves the files read for another to be placed. +#[test] +fn a_file_is_placed_after_a_revert_that_failed_or_of_another_document() { + let tif = saved("revert-failed", "photo.tif", &picture(Tiff, 60, 40)); + let (mut first, path) = saved_and_changed(app(true), "revert-failed"); + start(&mut first, &json!({"path": tif}), false).unwrap(); + let revert = json!({"command": "file.revert", "params": {"confirmed": true}}); + let failing = json!({"command": "select.set", "params": {"ids": [999999]}}); + assert!(first.run("command.batch", json!({"commands": [revert, failing]})).is_err(), "the batch is rolled back"); + std::fs::remove_file(&path).unwrap(); + assert!(first.run("file.revert", json!({"confirmed": true})).is_err(), "the saved file is gone"); + placed(&mut first); + assert_eq!(names(&first), ["photo.tif"]); + let (mut second, _) = saved_and_changed(app(true), "revert-other"); + second.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + start(&mut second, &json!({"path": tif}), false).unwrap(); + second.session.set_active(0); + second.sync_views(); + second.run("file.revert", json!({"confirmed": true})).unwrap(); + placed(&mut second); + assert_eq!(second.session.active_index(), Some(1)); + assert_eq!(names(&second), ["photo.tif"], "the other document's file is placed"); +} + +/// Files dropped on a canvas that arrive after File › Revert threw away the content of their +/// document (the web reads dropped files asynchronously) are not placed. +#[test] +fn files_dropped_on_a_document_reverted_before_they_arrive_are_not_placed() { + let tif = saved("revert-drop", "photo.tif", &picture(Tiff, 60, 40)); + let (mut app, _) = saved_and_changed(app(true), "revert-drop"); + let (doc, reverts) = app.session.doc().map(|st| (st.uid, st.reverts)).unwrap(); + let drop = DropTarget::Place(DropAt { doc, reverts, at: vectorcraft_geom::Point::new(100.0, 100.0), embed: false }); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let reverted = state(&app); + crate::place::drop_files(&mut app, vec![(drop, ("photo.tif".into(), Some(tif), vec![]))]); + placed(&mut app); + assert_eq!(app.ui.status, "Couldn't place photo.tif: the document it was dropped on was reverted"); + assert!(state(&app) == reverted, "nothing is placed"); +} + +/// Pastes whose bitmaps are read off the UI thread paste nothing when File › Revert threw away the +/// content of their document before they were read: the clipboard and the selection stay as they +/// are, and the status bar says why. A Paste in Front given after the Revert, while a paste given +/// before it waits, does not follow that paste: it goes in front of what was selected when it was +/// given. +#[test] +fn a_paste_whose_document_was_reverted_meanwhile_pastes_nothing() { + let bitmap = Some(Flavour { mime: PNG, data: picture(Png, 60, 40) }); + let (pasting, _) = pasting_app(true, bitmap, None, true); + let (mut app, _) = saved_and_changed(pasting, "revert-paste"); + app.run("select.set", json!({"ids": []})).unwrap(); + crate::menus::invoke(&mut app, "edit.paste", json!({})); + crate::menus::invoke(&mut app, "edit.paste", json!({})); + assert_eq!(app.placing.pending.len(), 2); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let (reverted, clipboard) = (state(&app), app.session.clipboard.clone()); + placed(&mut app); + assert_eq!(app.ui.status, "Couldn't paste: the document it was pasted in was reverted"); + assert!(state(&app) == reverted, "nothing is pasted"); + assert!(app.session.clipboard == clipboard, "the clipboard is unchanged"); + assert!(app.placing.chains.is_empty() && app.placing.latest_chain.is_empty(), "no paste waits"); + // A paste given before a Revert, and one given after it with the same (empty) selection. + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + app.run("select.set", json!({"ids": []})).unwrap(); + crate::menus::invoke(&mut app, "edit.pasteInFront", json!({})); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + crate::menus::invoke(&mut app, "edit.pasteInFront", json!({})); + assert_eq!(app.placing.pending.len(), 2); + let below = app.run("shape.rectangle", json!({"x": 100, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + app.run("shape.rectangle", json!({"x": 200, "y": 10, "width": 20, "height": 20})).unwrap(); + app.run("select.set", json!({"ids": [below]})).unwrap(); + placed(&mut app); + let st = app.session.doc().unwrap(); + let order: Vec<_> = st.doc.layers[0].children().unwrap().iter().map(|n| n.id).collect(); + assert_eq!(order.len(), 3, "one picture is pasted"); + assert_eq!(st.selection.objects, [order[2]], "pasted on top, with nothing selected as when it was given"); + assert!(matches!(st.doc.node(order[2]).map(|n| &n.kind), Some(vectorcraft_doc::NodeKind::Image(_)))); +} + +/// A paste that waits for its own Swatch Conflict dialog pastes nothing once File › Revert (on its +/// own or in a batch) threw away the content of its document: confirming the dialog gives an +/// error, and the document and the clipboard stay as they are. +#[test] +fn a_deferred_swatch_paste_is_dropped_when_its_document_is_reverted() { + for batch in [false, true] { + let (mut app, _) = pasting_app(true, None, None, true); + app.run("swatch.new", json!({"name": "Brand", "color": "#ff0000", "global": true})).unwrap(); + let source = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].clone(); + app.run("paint.setFill", json!({"ids": [source], "swatch": "Brand"})).unwrap(); + app.run("edit.copy", json!({})).unwrap(); + let clipboard = app.session.clipboard.clone(); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("swatch.new", json!({"name": "Brand", "color": "#0000ff", "global": true})).unwrap(); + let (mut app, _) = saved_and_changed(app, &format!("revert-swatch-{batch}")); + crate::menus::invoke(&mut app, "edit.pasteInPlace", json!({})); + placed(&mut app); + assert_eq!(app.ui.dialog.as_ref().unwrap().kind, crate::dialogs::swatch_conflict::KIND); + let revert = json!({"command": "file.revert", "params": {"confirmed": true}}); + if batch { + app.run("command.batch", json!({"commands": [revert]})).unwrap(); + } else { + app.run("file.revert", json!({"confirmed": true})).unwrap(); + } + let reverted = state(&app); + assert_eq!(app.ui.dialog.as_ref().unwrap().kind, crate::dialogs::swatch_conflict::KIND, "batch {batch}"); + app.ui.dialog.as_mut().unwrap().fields.insert("choice".into(), json!("add")); + let error = crate::dialogs::confirm(&mut app).unwrap_err(); + assert_eq!(error, "Couldn't paste: the document it was pasted in was reverted"); + assert!(app.ui.dialog.is_none() && app.placing.swatch_paste.is_none()); + assert!(app.placing.chains.is_empty() && app.placing.latest_chain.is_empty()); + assert!(app.session.clipboard == clipboard); + assert!(state(&app) == reverted, "batch {batch}: nothing is pasted"); + } +} + /// Replace swaps the object selected when Place started; when that object was deleted before the /// file was read, nothing is placed and the status bar says why. #[test] diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index be804f0347..a06dc2f1df 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -621,11 +621,16 @@ pub struct UiState { /// Recording in progress: (set index, action name, journal length when recording started). #[serde(skip)] pub recording: Option<(usize, String, usize)>, - /// The id of the action New Action made for the recording in progress - /// ([`crate::panels::actions::Action::id`]): Stop gives it the recorded steps. None when Stop - /// adds a new action, as after Begin Recording. + /// The id of the action the recording in progress records into, the one New Action made or the + /// one selected when Begin Recording started it ([`crate::panels::actions::Action::id`]): Stop + /// gives it the recorded steps. None when Stop adds a new action, as after Begin Recording with + /// no action selected. #[serde(skip)] pub recording_into: Option, + /// Where in the action [`UiState::recording_into`] names Stop puts the recorded steps: before + /// the step at this index, or None after its last step. + #[serde(skip)] + pub recording_at: Option, /// The length of the action set file that Stop Playing/Recording would leave without the steps /// recorded so far, once measured; None until then, and again after an app command, which may /// change the sets. @@ -1168,6 +1173,7 @@ impl Default for UiState { action_sets_selected: vec![], recording: None, recording_into: None, + recording_at: None, recording_base: None, recording_tail: None, recording_checked: None, diff --git a/crates/ui-egui/src/tests/automation.rs b/crates/ui-egui/src/tests/automation.rs index d7f438d285..6d7c7075c5 100644 --- a/crates/ui-egui/src/tests/automation.rs +++ b/crates/ui-egui/src/tests/automation.rs @@ -242,6 +242,51 @@ fn control_export_refuses_an_option_no_format_takes() { let _ = std::fs::remove_dir_all(base); } +/// `app.export` with a path writes the file when given an option only another format reads, and +/// its warnings name that option, as `document.export`'s do without a path. `file.exportAs` run +/// as a command does the same; an export that automation did not ask for gets no such note. +#[test] +fn control_export_notes_an_option_the_format_does_not_read() { + let (mut app, tx, base) = confined("export-unused"); + let r = request(&mut app, &tx, "app.open", json!({"path": s(base.join("in/a.svg"))})); + assert_eq!(r["ok"], true, "{r}"); + let note = json!("`quality` was not used: PDF files don't read it"); + let path = base.join("out/a.pdf"); + let r = request(&mut app, &tx, "app.export", json!({"format": "pdf", "quality": 80, "path": s(path.clone()), "wait": true})); + assert_eq!(r["ok"], true, "{r}"); + assert!(path.is_file() && r["result"]["warnings"].as_array().is_some_and(|w| w.contains(¬e)), "{r}"); + let r = request(&mut app, &tx, "app.export", json!({"format": "pdf", "quality": 80})); + assert!(r["result"]["warnings"].as_array().is_some_and(|w| w.contains(¬e)), "{r}"); + let r = request(&mut app, &tx, "app.export", json!({"format": "jpg", "quality": 80, "path": s(base.join("out/a.jpg")), "wait": true})); + assert!(r["result"]["warnings"].as_array().is_some_and(|w| !w.iter().any(|w| w.to_string().contains("was not used"))), "{r}"); + let params = json!({"format": "pdf", "quality": 80, "path": s(base.join("out/b.pdf"))}); + let r = request(&mut app, &tx, "engine.execute", json!({"command": "file.exportAs", "params": params})); + assert!(r["result"]["warnings"].as_array().is_some_and(|w| w.contains(¬e)), "{r}"); + assert!(app.ui.status.contains("`quality` was not used"), "{}", app.ui.status); + let r = crate::io::export(&mut app, Some("pdf"), Some(s(base.join("out/c.pdf"))), &json!({"quality": 80})).unwrap(); + assert!(r["warnings"].as_array().is_some_and(|w| !w.contains(¬e)), "{r}"); + let _ = std::fs::remove_dir_all(base); +} + +/// A Background Export replies before the file is written: its reply names the options the format +/// does not read at once, as a background save's does, and has no `warnings` when there are none. +#[test] +fn control_background_export_notes_an_option_the_format_does_not_read() { + let shared: SharedWriteFn = std::sync::Arc::new(|p: &str, b: &[u8]| vectorcraft_format::write_atomic(Path::new(p), b).map_err(|e| e.to_string())); + let (mut app, tx, base) = confined_with("export-unused-background", Some(shared)); + app.run("file.new", json!({"width": 100, "height": 50})).unwrap(); + let r = request(&mut app, &tx, "app.export", json!({"format": "pdf", "quality": 80, "path": s(base.join("out/a.pdf"))})); + assert_eq!(r["result"]["background"], true, "{r}"); + assert_eq!(r["result"]["warnings"], json!(["`quality` was not used: PDF files don't read it"]), "{r}"); + crate::background::wait_all(&mut app); + let r = request(&mut app, &tx, "app.export", json!({"format": "jpg", "quality": 80, "path": s(base.join("out/a.jpg"))})); + assert_eq!(r["result"]["background"], true, "{r}"); + assert!(r["result"].get("warnings").is_none(), "{r}"); + crate::background::wait_all(&mut app); + assert!(base.join("out/a.pdf").is_file() && base.join("out/a.jpg").is_file()); + let _ = std::fs::remove_dir_all(base); +} + /// `app.save`, and `file.save` and `file.exportForScreens` run as commands, refuse a key no save /// format or no format takes before anything is written. #[test] diff --git a/crates/ui-egui/src/tests/picks.rs b/crates/ui-egui/src/tests/picks.rs index e808cf2463..ff290952fb 100644 --- a/crates/ui-egui/src/tests/picks.rs +++ b/crates/ui-egui/src/tests/picks.rs @@ -862,6 +862,28 @@ fn save_changes_answers_for_its_own_document() { assert_eq!((d.kind.as_str(), &d.fields["uid"]), (crate::unsaved::KIND, &json!(uids[2]))); } +/// Closing a modified background tab whose Save opens a Save dialog: once the dialog answers, +/// the document closes and the document that was in front before the question is in front again. +#[test] +fn save_changes_answered_by_a_save_dialog_keeps_the_front_document() { + let (mut app, shown, written) = with_dialogs(false); + // A clean and in front, B modified and untitled, C clean. + app.run("file.new", json!({"width": 100, "height": 80})).unwrap(); + app.run("file.new", json!({"width": 100, "height": 80})).unwrap(); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + app.run("file.new", json!({"width": 100, "height": 80})).unwrap(); + app.session.set_active(0); + let uids: Vec = app.session.documents().iter().map(|d| d.uid).collect(); + app.run("file.close", json!({"index": 1})).unwrap(); + assert!(crate::dialogs::confirm(&mut app).is_err()); + assert!(matches!(shown.requests().as_slice(), [PickRequest::Save(_)])); + shown.answer(&["/art/b.vectorcraft"]); + poll(&mut app); + assert_eq!(*written.borrow(), ["/art/b.vectorcraft"], "{}", app.ui.status); + assert_eq!(app.session.documents().iter().map(|d| d.uid).collect::>(), [uids[0], uids[2]]); + assert_eq!(app.session.active().map(|d| d.uid), Some(uids[0]), "A is in front again"); +} + /// A dialog asked for while another is open is refused, and the status bar says so rather than /// "cancelled". #[test] diff --git a/crates/ui-egui/src/tests/place.rs b/crates/ui-egui/src/tests/place.rs index 9c67861eeb..19c39879af 100644 --- a/crates/ui-egui/src/tests/place.rs +++ b/crates/ui-egui/src/tests/place.rs @@ -111,7 +111,7 @@ fn a_drop_with_a_position_places_on_the_canvas_and_opens_off_it() { let want = Xf::new(rect, app.view().unwrap()).to_doc(pos); let uid = app.session.active().unwrap().uid; for name in ["a.png", "a.svg", "a.ai", "a.vectorcraft"] { - assert_eq!(app.drop_target(name, Some(pos), true), DropTarget::Place(DropAt { doc: uid, at: want, embed: true }), "{name}"); + assert_eq!(app.drop_target(name, Some(pos), true), DropTarget::Place(DropAt { doc: uid, reverts: 0, at: want, embed: true }), "{name}"); assert_eq!(app.drop_target(name, Some(Pos2::new(300.0, rect.top() - 10.0)), false), DropTarget::Open, "{name} on the tab bar"); } } @@ -129,7 +129,7 @@ fn a_drop_without_a_position_opens_documents_and_places_pictures() { assert_eq!(app.drop_target(name, None, false), DropTarget::Open, "{name}"); } for name in ["a.png", "a.jpg", "a.tiff", "a.webp", "a.txt"] { - assert_eq!(app.drop_target(name, None, false), DropTarget::Place(DropAt { doc: uid, at: center, embed: false }), "{name}"); + assert_eq!(app.drop_target(name, None, false), DropTarget::Place(DropAt { doc: uid, reverts: 0, at: center, embed: false }), "{name}"); } } diff --git a/crates/ui-egui/src/tests/saveext.rs b/crates/ui-egui/src/tests/saveext.rs index b8bb2ee6e4..815c1c8493 100644 --- a/crates/ui-egui/src/tests/saveext.rs +++ b/crates/ui-egui/src/tests/saveext.rs @@ -392,6 +392,22 @@ fn every_write_through_a_save_panel_asks_before_replacing() { assert!(w.borrow().is_empty()); } +/// Export As to a format without Use Artboards (a template holds the whole document) gives the +/// export no artboard option, so an export that automation confirms gets no note that one was +/// not used. +#[test] +fn export_as_a_template_is_given_no_artboard_option() { + for use_artboards in [false, true] { + let (mut app, w) = saving_app("/tmp/out"); + app.ui.answering_control = true; + app.run("file.exportAs", json!({"format": "template", "useArtboards": use_artboards})).unwrap(); + let r = dialogs::confirm(&mut app).unwrap(); + assert_eq!(last(&w), "/tmp/out.vctemplate"); + assert!(r["warnings"].as_array().is_some_and(|w| !w.iter().any(|w| w.to_string().contains("was not used"))), "{r}"); + assert!(!app.ui.status.contains("was not used"), "{}", app.ui.status); + } +} + #[test] fn typed_extensions_are_kept() { let (mut app, w) = saving_app("/tmp/art.svg"); diff --git a/crates/ui-egui/src/tests/tab_reorder.rs b/crates/ui-egui/src/tests/tab_reorder.rs index c1070fbc70..d658a178c1 100644 --- a/crates/ui-egui/src/tests/tab_reorder.rs +++ b/crates/ui-egui/src/tests/tab_reorder.rs @@ -160,8 +160,8 @@ fn views_follow_closes_and_moves_made_in_one_batch() { .unwrap(); assert_eq!(order(&app), ["Delta", "Charlie"]); assert_eq!(zooms(&app), [4.0, 3.0], "Delta does not take the closed Alpha's view"); - // Closing by index made the document in the closed one's place current (Charlie); it shows its own view. - assert_eq!((current(&app), app.view().map(|v| v.zoom)), ("Charlie".into(), Some(3.0))); + // Closing other documents by index leaves the current one (Delta) current; it shows its own view. + assert_eq!((current(&app), app.view().map(|v| v.zoom)), ("Delta".into(), Some(4.0))); // A document opened afterwards starts with a view of its own. app.run("file.new", json!({"width": 100, "height": 100, "name": "Echo"})).unwrap(); app.sync_views(); diff --git a/crates/ui-egui/src/tests/taskbar.rs b/crates/ui-egui/src/tests/taskbar.rs index d5199e0220..68ef8a3f15 100644 --- a/crates/ui-egui/src/tests/taskbar.rs +++ b/crates/ui-egui/src/tests/taskbar.rs @@ -1,7 +1,8 @@ //! The Contextual Task Bar's actions for each kind of selection: open paths offer Join and Edit //! Path, compound paths and clipping masks their Release, images selected with vector art Make //! Clipping Mask, type converts between point and area type, type on a path opens its options, and -//! a basic shape shows its properties in place of Lock. +//! a basic shape shows its properties in place of Lock. Type, and the Type tools while they edit it, +//! show the font family, font style and Font Size controls. use egui::{Event, PointerButton, Pos2, Rect, vec2}; use serde_json::json; @@ -535,6 +536,304 @@ fn the_task_bar_follows_the_active_document() { assert!(!locked(&app, rect), "the button doesn't lock the shape"); } +/// The Type tools whose bar shows the font and Fill controls. +const TYPE_TOOLS: [&str; 6] = ["type", "areaType", "typeOnPath", "verticalType", "verticalAreaType", "verticalTypeOnPath"]; + +/// The labels drawn inside the task bar (none while it isn't shown), with the context. +fn bar_texts(app: &mut VectorcraftApp) -> (egui::Context, Vec<(String, Rect)>) { + let (ctx, texts) = bar(app); + let Some(r) = canvas::task_bar_rect(&ctx) else { return (ctx, vec![]) }; + (ctx, texts.into_iter().filter(|(_, t)| r.contains(t.center())).collect()) +} + +/// Point type "Hello" at 20 pt, made with `tool` and edited by it as after a click with it. +fn edited_type(app: &mut VectorcraftApp, tool: &str) -> u64 { + app.run("tool.select", json!({ "tool": tool })).unwrap(); + let t = id(app.run("text.create", json!({"x": 60, "y": 80, "text": "Hello", "size": 20})).unwrap()); + app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap(); + assert!(crate::panels::character::text_editing(app).is_some(), "{tool} edits the type"); + t +} + +/// The font family and style of type `t`'s first character. +fn font_of(app: &VectorcraftApp, t: u64) -> (String, String) { + match kind(app, t) { + NodeKind::Text(t) => (t.first_style().font_family, t.first_style().font_style), + k => panic!("{k:?}"), + } +} + +/// The size of each run of type `t`, with its text. +fn sizes(app: &VectorcraftApp, t: u64) -> Vec<(String, f64)> { + match kind(app, t) { + NodeKind::Text(t) => t.runs.iter().map(|r| (r.text.clone(), r.style.size)).collect(), + k => panic!("{k:?}"), + } +} + +/// Each Type tool that adds or edits type shows the font family, font style and Font Size controls +/// and the Fill, without the selection tools' object actions, the Stroke chip or Lock. +#[test] +fn the_type_tools_show_font_and_fill_controls() { + for tool in TYPE_TOOLS { + let mut app = app(); + let t = edited_type(&mut app, tool); + let (family, style) = font_of(&app, t); + let (_, texts) = bar_texts(&mut app); + for label in [family.as_str(), style.as_str(), "20 pt"] { + assert!(has(&texts, label), "{tool}: {label} in {texts:?}"); + } + for label in ["Create Outlines", "Convert To Area Type", "Dynamic Text", "Duplicate"] { + assert!(!has(&texts, label), "{tool}: {label} in {texts:?}"); + } + let tree = crate::widgets::accessibility_tests::tree(|ui| canvas::show(&mut app, ui)); + let named = |label: &str| tree.iter().any(|n| n.label().is_some_and(|l| l.starts_with(label))); + assert!(named("Fill"), "{tool}: the Fill shows"); + for label in ["Stroke", "Recolor Artwork", "Lock"] { + assert!(!named(label), "{tool}: {label} is left out"); + } + } +} + +/// A Type tool shows no bar before it adds type, nor with other art selected; the Touch Type tool +/// shows none with type selected. +#[test] +fn the_type_tools_show_no_bar_without_type() { + let mut app = app(); + app.run("tool.select", json!({"tool": "type"})).unwrap(); + let (ctx, _) = bar(&mut app); + assert!(canvas::task_bar_rect(&ctx).is_none(), "nothing to format"); + let rect = id(app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 80, "height": 60})).unwrap()); + select(&mut app, &[rect]); + app.run("tool.select", json!({"tool": "type"})).unwrap(); + let (ctx, _) = bar(&mut app); + assert!(canvas::task_bar_rect(&ctx).is_none(), "a rectangle is not type"); + let t = id(app.run("text.create", json!({"x": 60, "y": 180, "text": "Hello", "size": 20})).unwrap()); + app.run("tool.select", json!({"tool": "touchType"})).unwrap(); + select(&mut app, &[t]); + let (ctx, _) = bar(&mut app); + assert!(canvas::task_bar_rect(&ctx).is_none(), "Touch Type has its own handles"); +} + +/// Selected type keeps its actions and gains the font controls, for one type object or several; +/// type selected with other art does not. +#[test] +fn selected_type_shows_font_controls_beside_its_actions() { + let mut app = app(); + app.run("tool.select", json!({"tool": "selection"})).unwrap(); + let a = id(app.run("text.create", json!({"x": 60, "y": 80, "text": "Hello", "size": 20})).unwrap()); + let b = id(app.run("text.create", json!({"x": 60, "y": 160, "text": "World", "size": 20})).unwrap()); + let rect = id(app.run("shape.rectangle", json!({"x": 200, "y": 40, "width": 80, "height": 60})).unwrap()); + let (family, _) = font_of(&app, a); + select(&mut app, &[a]); + let (_, texts) = bar_texts(&mut app); + for label in ["Create Outlines", "Convert To Area Type", "Duplicate", family.as_str(), "20 pt"] { + assert!(has(&texts, label), "{label} in {texts:?}"); + } + select(&mut app, &[a, b]); + let (_, texts) = bar_texts(&mut app); + assert!(has(&texts, family.as_str()) && has(&texts, "20 pt"), "{texts:?}"); + select(&mut app, &[a, rect]); + let (_, texts) = bar_texts(&mut app); + assert!(has(&texts, "Group") && !has(&texts, family.as_str()) && !has(&texts, "20 pt"), "{texts:?}"); + select(&mut app, &[rect]); + let (_, texts) = bar_texts(&mut app); + assert!(!has(&texts, family.as_str()) && !has(&texts, "20 pt"), "{texts:?}"); +} + +/// The bar's Font Size sets the characters a Type tool selects, one undo step; with type selected +/// it sets every selected type object, as the Character panel's does. +#[test] +fn the_task_bars_font_size_sets_what_the_character_panel_would() { + let mut app = app(); + let t = edited_type(&mut app, "type"); + app.session.set_tool_option("select", &json!({"start": 0, "end": 2})); + let (ctx, texts) = bar_texts(&mut app); + type_into(&mut app, &ctx, &texts, "20 pt", "30"); + assert_eq!(sizes(&app, t), [("He".to_string(), 30.0), ("llo".to_string(), 20.0)]); + // Mixed sizes leave the field blank, as in the Character panel. + app.session.set_tool_option("select", &json!({"start": 0, "end": 5})); + let (_, texts) = bar_texts(&mut app); + assert!(!has(&texts, "20 pt") && !has(&texts, "30 pt"), "{texts:?}"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(sizes(&app, t), [("Hello".to_string(), 20.0)]); + + let mut app = self::app(); + app.run("tool.select", json!({"tool": "selection"})).unwrap(); + let a = id(app.run("text.create", json!({"x": 60, "y": 80, "text": "Hello", "size": 20})).unwrap()); + let b = id(app.run("text.create", json!({"x": 60, "y": 160, "text": "World", "size": 20})).unwrap()); + select(&mut app, &[a, b]); + let (ctx, texts) = bar_texts(&mut app); + type_into(&mut app, &ctx, &texts, "20 pt", "14"); + assert_eq!(sizes(&app, a), [("Hello".to_string(), 14.0)]); + assert_eq!(sizes(&app, b), [("World".to_string(), 14.0)]); +} + +/// At a caret, with no characters selected, the bar's Font Size sets the edited type as the +/// Character panel's does, and the characters typed next take it. +#[test] +fn the_task_bars_font_size_at_a_caret_sets_what_is_typed_next() { + let mut app = app(); + let t = edited_type(&mut app, "type"); + app.session.set_tool_option("select", &json!({"start": 5, "end": 5})); + assert_eq!(crate::panels::character::text_editing(&app), Some((NodeId(t), 5, 5)), "a caret after the type"); + let (ctx, texts) = bar_texts(&mut app); + type_into(&mut app, &ctx, &texts, "20 pt", "30"); + app.session.tool_typed_text("!", app.view_info()).unwrap(); + assert_eq!(sizes(&app, t), [("Hello!".to_string(), 30.0)]); +} + +/// The Type tool's Fill chip makes the Fill active and brings up the Swatches panel. +#[test] +fn the_type_tools_fill_chip_activates_the_fill() { + let mut app = app(); + edited_type(&mut app, "type"); + app.session.fill_active = false; + let (ctx, _) = bar_texts(&mut app); + let r = canvas::task_bar_rect(&ctx).expect("the task bar shows"); + // Right to left: the frame's margin, More Options, then the Fill chip. + let p = Pos2::new(r.right() - 8.0 - 30.0 - 6.0 - 13.0, r.center().y); + let press = |pressed| Event::PointerButton { pos: p, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(&mut app, &ctx, vec![Event::PointerMoved(p)]); + frame(&mut app, &ctx, vec![press(true)]); + frame(&mut app, &ctx, vec![press(false)]); + assert!(app.session.fill_active, "the Fill is active"); + assert!(crate::panels::character::text_editing(&app).is_some(), "the type is still edited"); +} + +/// Screen readers name the Type tool bar's controls, and the bar stays on the canvas for type at +/// its lower right corner. +#[test] +fn the_type_tools_bar_is_named_and_stays_on_the_canvas() { + use crate::widgets::accessibility_tests::{named, tree}; + let mut app = app(); + edited_type(&mut app, "type"); + let tree = tree(|ui| canvas::show(&mut app, ui)); + for label in ["Font Family", "Style", "Font Size", "Fill"] { + named(&tree, label); + } + let mut app = self::app(); + app.run("tool.select", json!({"tool": "type"})).unwrap(); + app.run("text.create", json!({"x": 380, "y": 290, "text": "Corner", "size": 20})).unwrap(); + app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap(); + // The type near the canvas's lower edge, so the bar's place under it is off the canvas. + let view = app.view_mut().unwrap(); + (view.center, view.zoom) = (vectorcraft_geom::Point::new(200.0, 20.0), 1.0); + let (ctx, _) = bar(&mut app); + let r = canvas::task_bar_rect(&ctx).expect("the task bar shows"); + let canvas = app.canvas_rect.expect("the canvas is laid out"); + assert!(canvas.contains_rect(r), "{r:?} in {canvas:?}"); +} + +/// The task bar's rect after a few frames on a `width` by 700 screen, and the canvas's rect. +fn bar_on_screen(app: &mut VectorcraftApp, width: f32) -> (Rect, Rect) { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let screen = Rect::from_min_size(Pos2::ZERO, vec2(width, 700.0)); + for _ in 0..3 { + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| canvas::show(app, ui)); + out.textures_delta.clear(); + } + (canvas::task_bar_rect(&ctx).expect("the task bar shows"), app.canvas_rect.expect("the canvas is laid out")) +} + +/// On a canvas narrower than one row of the bar, the font controls go on a second row, narrowed to +/// fit, and the bar stays whole on the canvas: selected type's actions, and a Type tool's Fill. +#[test] +fn selected_types_font_controls_take_a_second_row_on_a_narrow_canvas() { + let mut app = app(); + app.run("tool.select", json!({"tool": "selection"})).unwrap(); + let t = id(app.run("text.create", json!({"x": 20, "y": 60, "text": "Hello", "size": 20})).unwrap()); + select(&mut app, &[t]); + let (r, canvas) = bar_on_screen(&mut app, 760.0); + assert!(canvas.contains_rect(r), "{r:?} in {canvas:?}"); + assert!(r.height() > 60.0, "the font controls take a second row: {r:?}"); + + let mut app = self::app(); + app.run("tool.select", json!({"tool": "type"})).unwrap(); + app.run("text.create", json!({"x": 20, "y": 60, "text": "Hello", "size": 20})).unwrap(); + app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap(); + // Narrower than the font controls at their full widths too. + let (r, canvas) = bar_on_screen(&mut app, 300.0); + assert!(canvas.contains_rect(r), "{r:?} in {canvas:?}"); + assert!(r.height() > 60.0, "the font controls take a second row: {r:?}"); + let (r, _) = bar_on_screen(&mut app, 1000.0); + assert!(r.height() < 60.0, "one row where it fits: {r:?}"); + // The Type tool's bar has only the Fill and More Options beside the controls: one row fits. + let (r, canvas) = bar_on_screen(&mut app, 460.0); + assert!(canvas.contains_rect(r) && r.height() < 60.0, "one row on a 460 px screen: {r:?} in {canvas:?}"); + // Too narrow for the controls at their narrowest: the bar leaves them out. + let (r, canvas) = bar_on_screen(&mut app, 160.0); + assert!(canvas.contains_rect(r) && r.height() < 60.0, "no font controls on a 160 px screen: {r:?} in {canvas:?}"); +} + +/// When the canvas narrows so far that the bar leaves its font controls out, the font family +/// field it drew before no longer takes the mouse wheel. +#[test] +fn a_task_bar_without_its_font_controls_leaves_their_wheel() { + let mut app = app(); + app.run("tool.select", json!({"tool": "type"})).unwrap(); + app.run("text.create", json!({"x": 20, "y": 60, "text": "Hello", "size": 20})).unwrap(); + app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let draw = |app: &mut VectorcraftApp, width: f32| { + let screen = Rect::from_min_size(Pos2::ZERO, vec2(width, 700.0)); + for _ in 0..3 { + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| canvas::show(app, ui)); + out.textures_delta.clear(); + } + }; + draw(&mut app, 1000.0); + let bar = canvas::task_bar_rect(&ctx).expect("the task bar shows"); + let viewport = egui::ViewportId::ROOT; + let points = (0..(bar.width() / 4.0) as usize).flat_map(|x| (0..(bar.height() / 4.0) as usize).map(move |y| (x, y))); + let field = points + .map(|(x, y)| bar.min + vec2(x as f32 * 4.0, y as f32 * 4.0)) + .find(|p| crate::font_menu::wheel_field_layer_for_test(&ctx, viewport, *p).is_some()) + .expect("the bar's font family field takes the wheel"); + draw(&mut app, 160.0); + assert!(canvas::task_bar_rect(&ctx).is_some(), "the bar still shows, without its font controls"); + crate::font_menu::sync_wheel_target(&app, &ctx, viewport); + assert!(crate::font_menu::wheel_field_layer_for_test(&ctx, viewport, field).is_none(), "the left-out field at {field:?} still takes the wheel"); + + // Hiding the bar (Window › Contextual Task Bar) releases the field before the next layout. + draw(&mut app, 1000.0); + assert!(crate::font_menu::wheel_field_layer_for_test(&ctx, viewport, field).is_some(), "the field is back"); + app.run("window.taskBar", json!({})).unwrap(); + crate::font_menu::sync_wheel_target(&app, &ctx, viewport); + assert!( + crate::font_menu::wheel_field_layer_for_test(&ctx, viewport, field).is_none(), + "the hidden bar's field at {field:?} still takes the wheel" + ); +} + +/// While a Type tool edits type, the Fill chip shows the selected characters' fill, and "?" where +/// their fills differ. +#[test] +fn the_type_tools_fill_chip_shows_the_edited_characters_fill() { + let mut app = app(); + let t = edited_type(&mut app, "type"); + app.session.set_tool_option("select", &json!({"start": 2, "end": 5})); + app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap(); + let fills: Vec<_> = match kind(&app, t) { + NodeKind::Text(t) => t.runs.iter().map(|r| (r.text.clone(), r.style.fill.clone())).collect(), + k => panic!("{k:?}"), + }; + let [(he, he_fill), (llo, llo_fill)] = &fills[..] else { panic!("{fills:?}") }; + assert_eq!((he.as_str(), llo.as_str()), ("He", "llo")); + assert_ne!(he_fill, llo_fill); + let ctx = egui::Context::default(); + let (fill, _, mixed, _) = canvas::chip_paints(&app, &ctx); + assert!(fill == *llo_fill && !mixed, "{fill:?} {mixed}"); + app.session.set_tool_option("select", &json!({"start": 0, "end": 2})); + let (fill, _, mixed, _) = canvas::chip_paints(&app, &ctx); + assert!(fill == *he_fill && !mixed, "{fill:?} {mixed}"); + app.session.set_tool_option("select", &json!({"start": 0, "end": 5})); + let (_, _, mixed, _) = canvas::chip_paints(&app, &ctx); + assert!(mixed, "the fills differ"); +} + /// The task bar shows the selection as it is after an edit and after Undo: Join leaves once the /// open path is closed and comes back with Undo, and Shape Properties shows a rectangle's new /// corner radius and then its old one. diff --git a/crates/ui-egui/src/unsaved.rs b/crates/ui-egui/src/unsaved.rs index 7b068bc7e4..04bdc1e56e 100644 --- a/crates/ui-egui/src/unsaved.rs +++ b/crates/ui-egui/src/unsaved.rs @@ -14,9 +14,15 @@ use crate::{VectorcraftApp, io}; /// Dialog kind. Fields: `index` (document), `uid` (the same document, which `index` may no longer /// point at once a file dialog answers), `name` (its title), `then` (`close`, `closeAll` or `quit`: -/// what continues after this document) and `discard` (Don't Save). +/// what continues after this document) and `discard` (Don't Save). With `then` = `close`, the +/// protected field [`FRONT`] holds the uid of the document that was in front before the question. pub const KIND: &str = "saveChanges"; +/// Field of a [`KIND`] dialog asked by File → Close or a tab's ×: the uid of the document in front +/// before the question showed the asked one. Once the asked document closes, that document is in +/// front again while it is still open. +const FRONT: &str = "__front"; + /// Nothing closes while a file dialog's sheet is on the window (macOS): what asked for it runs /// again when it answers. (Elsewhere the dialog is a window of its own, and closing goes on.) pub(crate) fn refuse_while_picking(app: &VectorcraftApp) -> Result<(), String> { @@ -37,7 +43,7 @@ pub fn close(app: &mut VectorcraftApp, i: usize) -> Result { refuse_while_picking(app)?; finish_pending(app); let dirty = app.session.documents().get(i).ok_or("no such document")?.is_dirty(); - if dirty { ask(app, i, "close") } else { close_now(app, i) } + if dirty { ask(app, i, "close") } else { close_now(app, i, None) } } /// File → Close All (`then` = `closeAll`) or Quit (`quit`): ask about the next modified document, @@ -68,18 +74,28 @@ pub fn any_dirty(app: &VectorcraftApp) -> bool { app.session.documents().iter().any(|d| d.is_dirty()) } -/// Show document `i` and ask whether to save it. +/// Show document `i` and ask whether to save it. For a single close (`then` = `close`), the +/// dialog also remembers the document in front before it ([`FRONT`]). fn ask(app: &mut VectorcraftApp, i: usize, then: &str) -> Result { + let front = app.session.active().map(|d| d.uid); app.session.set_active(i); let doc = &app.session.documents()[i]; let (name, uid) = (doc.title(), doc.uid); - app.ui.dialog = Some(Dialog::new(KIND, json!({ "index": i, "uid": uid, "name": name, "then": then }))); + let mut fields = json!({ "index": i, "uid": uid, "name": name, "then": then }); + if let Some(front) = front.filter(|f| then == "close" && *f != uid) { + fields[FRONT] = json!(front); + } + app.ui.dialog = Some(Dialog::new(KIND, fields)); Ok(json!({ "pending": KIND })) } /// Close document `i` through the engine command; [`VectorcraftApp::sync_views`] drops its view. -fn close_now(app: &mut VectorcraftApp, i: usize) -> Result { +/// When `front` names a document that is still open, that document is in front afterwards. +fn close_now(app: &mut VectorcraftApp, i: usize, front: Option) -> Result { let r = app.session.execute("file.close", &json!({ "index": i })).map_err(|e| e.to_string())?; + if let Some(j) = front.and_then(|uid| app.session.documents().iter().position(|d| d.uid == uid)) { + app.session.set_active(j); + } app.sync_views(); if app.session.tool_id() == "artboard" && let Some(n) = app.session.active().map(|d| d.doc.artboards.len()) @@ -117,7 +133,7 @@ pub fn confirm(app: &mut VectorcraftApp) -> Result { } } } - close_now(app, i)?; + close_now(app, i, d.fields.get(FRONT).and_then(Value::as_u64))?; match d.str("then").as_str() { "close" => Ok(Value::Null), then => close_all(app, then), @@ -195,6 +211,98 @@ mod tests { assert_eq!((docs(&app), app.views.len()), (1, 1)); } + /// Three documents, A clean, B modified and C clean, with A in front: their uids. + fn front_and_modified_background_tab(app: &mut VectorcraftApp) -> [u64; 3] { + new_doc(app, false); + new_doc(app, true); + new_doc(app, false); + app.session.set_active(0); + let uids: Vec = app.session.documents().iter().map(|d| d.uid).collect(); + [uids[0], uids[1], uids[2]] + } + + fn front_uid(app: &VectorcraftApp) -> Option { + app.session.active().map(|d| d.uid) + } + + #[test] + fn closing_a_modified_background_tab_keeps_the_front_document_after_dont_save() { + let (mut app, written) = app(); + let [a, _, c] = front_and_modified_background_tab(&mut app); + assert_eq!(app.run("file.close", json!({ "index": 1 })).unwrap(), json!({ "pending": KIND })); + // The question shows the document it asks about. + assert_eq!((pending(&app), app.session.active_index()), (Some(1), Some(1))); + app.ui.dialog.as_mut().unwrap().fields.insert("discard".into(), json!(true)); + confirm(&mut app).unwrap(); + let uids: Vec = app.session.documents().iter().map(|d| d.uid).collect(); + assert_eq!((uids, front_uid(&app), app.views.len()), (vec![a, c], Some(a), 2)); + assert!(written.lock().unwrap().is_empty()); + } + + #[test] + fn closing_a_modified_background_tab_keeps_the_front_document_after_save() { + let (mut app, written) = app(); + let [a, _, c] = front_and_modified_background_tab(&mut app); + close(&mut app, 1).unwrap(); + confirm(&mut app).unwrap(); + assert_eq!(*written.lock().unwrap(), vec!["out.vectorcraft".to_string()]); + let uids: Vec = app.session.documents().iter().map(|d| d.uid).collect(); + assert_eq!((uids, front_uid(&app)), (vec![a, c], Some(a))); + } + + #[test] + fn cancel_keeps_the_asked_background_tab_in_front() { + let (mut app, _) = app(); + let [_, b, _] = front_and_modified_background_tab(&mut app); + close(&mut app, 1).unwrap(); + app.ui.dialog = None; + assert_eq!((docs(&app), front_uid(&app)), (3, Some(b))); + // A later close of the tab in front brings its neighbor to the front. + close(&mut app, 1).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("discard".into(), json!(true)); + confirm(&mut app).unwrap(); + assert_eq!((docs(&app), app.session.active_index()), (2, Some(1))); + } + + #[test] + fn closing_the_modified_front_document_brings_its_neighbor_to_the_front() { + let (mut app, _) = app(); + new_doc(&mut app, false); + new_doc(&mut app, true); + new_doc(&mut app, false); + let c = app.session.documents()[2].uid; + app.session.set_active(1); + close(&mut app, 1).unwrap(); + assert!(app.ui.dialog.as_ref().is_some_and(|d| !d.fields.contains_key(FRONT))); + app.ui.dialog.as_mut().unwrap().fields.insert("discard".into(), json!(true)); + confirm(&mut app).unwrap(); + assert_eq!((docs(&app), front_uid(&app)), (2, Some(c))); + } + + /// The document in front before the question is remembered by its uid: when it closed while + /// the question was open, the closed document's neighbor comes to the front as before. + #[test] + fn a_front_document_closed_meanwhile_is_not_brought_back() { + let (mut app, _) = app(); + let [a, _, c] = front_and_modified_background_tab(&mut app); + close(&mut app, 1).unwrap(); + let d = app.ui.dialog.take().unwrap(); + assert_eq!(d.fields.get(FRONT), Some(&json!(a))); + close(&mut app, 0).unwrap(); + app.ui.dialog = Some(d); + app.ui.dialog.as_mut().unwrap().fields.insert("discard".into(), json!(true)); + confirm(&mut app).unwrap(); + assert_eq!((docs(&app), front_uid(&app)), (1, Some(c))); + } + + #[test] + fn close_all_does_not_remember_a_front_document() { + let (mut app, _) = app(); + front_and_modified_background_tab(&mut app); + app.run("file.closeAll", json!({})).unwrap(); + assert!(app.ui.dialog.as_ref().is_some_and(|d| d.kind == KIND && !d.fields.contains_key(FRONT))); + } + #[test] fn a_cancelled_save_as_keeps_the_document_open() { let (mut app, _) = app(); diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 52849bc2bc..4e1bc4f6a5 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -45,7 +45,7 @@ pub use drag::{ }; #[cfg(test)] use dropdowns::combo_button_id; -pub(crate) use dropdowns::{combo, combo_menu, combo_menu_field, combo_named, field_focused_in, popover_is_open}; +pub(crate) use dropdowns::{combo, combo_menu, combo_menu_field_named, combo_named, field_focused_in, popover_is_open}; pub use dropdowns::{ dropdown, dropdown_icon_names, dropdown_named, dropdown_names, dropdown_names_named, dropdown_with, dropdown_with_named, list_scroll_style, menu_room, menu_scroll, panel_scroll, popover, set_menu_floor, strip_scroll, diff --git a/crates/ui-egui/src/widgets/dropdowns.rs b/crates/ui-egui/src/widgets/dropdowns.rs index a2741ff1cb..1539be8700 100644 --- a/crates/ui-egui/src/widgets/dropdowns.rs +++ b/crates/ui-egui/src/widgets/dropdowns.rs @@ -196,6 +196,18 @@ pub(crate) fn combo_menu_field( current: &str, width: f32, menu: impl FnOnce(craft_ui::combo::Menu<'_>) -> Option, +) -> (Response, Option) { + combo_menu_field_named(ui, id, None, current, width, menu) +} + +/// [`combo_menu_field`] for a field whose visible label is not an adjacent label widget. +pub(crate) fn combo_menu_field_named( + ui: &mut Ui, + id: impl std::hash::Hash, + name: Option<&str>, + current: &str, + width: f32, + menu: impl FnOnce(craft_ui::combo::Menu<'_>) -> Option, ) -> (Response, Option) { let t = Tokens::get(ui.ctx()); let label = take_previous_label(ui); @@ -205,7 +217,7 @@ pub(crate) fn combo_menu_field( .corner_radius(CornerRadius::same(3)) .show(ui, |ui| { let armed = take_armed_focus(ui, &id); - let resp = combo_field(ui, id_with(ui.scope_id(), id), label, None, current, width - 4.0); + let resp = combo_field(ui, id_with(ui.scope_id(), id), label, name, current, width - 4.0); if armed { egui::Popup::open_id(ui.ctx(), egui::Popup::default_response_id(&resp)); ui.memory_mut(|m| m.stop_text_input()); diff --git a/crates/ui-egui/tests/font_wheel.rs b/crates/ui-egui/tests/font_wheel.rs index 3cdb017d77..cfa63c31de 100644 --- a/crates/ui-egui/tests/font_wheel.rs +++ b/crates/ui-egui/tests/font_wheel.rs @@ -90,18 +90,24 @@ fn a_font_field_that_appears_under_a_still_pointer_leaves_the_wheel_until_the_po #[test] fn artboard_controls_leave_replaced_font_fields_wheel_available() { - let (ctx, mut app) = selected_type_with_control(); - let mut texts = Vec::new(); - for _ in 0..8 { - texts = frame(&mut app, &ctx, vec![]); - } - let fields: Vec<_> = texts.iter().filter(|(t, _)| t == "Inter").map(|(_, point)| *point).collect(); - assert_eq!(fields.len(), 2, "Control and Properties each show a font field"); - app.select_tool("artboard"); + let laid_out = || { + let (ctx, mut app) = selected_type_with_control(); + let mut texts = Vec::new(); + for _ in 0..8 { + texts = frame(&mut app, &ctx, vec![]); + } + let fields: Vec<_> = texts.iter().filter(|(t, _)| t == "Inter").map(|(_, point)| *point).collect(); + (ctx, app, fields) + }; + let (_, _, fields) = laid_out(); + assert_eq!(fields.len(), 3, "Control, Properties and the Contextual Task Bar each show a font field"); + // Each field gets its own app, so a wheel stream begun over one field cannot decide another. for point in fields { + let (ctx, mut app, _) = laid_out(); + app.select_tool("artboard"); let mut raw = wheel_input(point); app.raw_input_hook(&ctx, &mut raw); - assert!(raw.events.iter().any(|e| matches!(e, Event::MouseWheel { .. })), "the Artboard tool replaces this font field"); + assert!(raw.events.iter().any(|e| matches!(e, Event::MouseWheel { .. })), "the Artboard tool replaces the font field at {point:?}"); } } diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 1a0d5c7d7d..c2d4c39b06 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -107,7 +107,7 @@ the two can still win that race. | `ui.render` | `{path?, scale?, artboard?, data?, traceViews?}` | render an artboard headlessly (PNG with the pixels of `app.export {format: "png", background: "white"}` at the same scale; `artboard`: its 0-based index, default the first; `traceViews: true`: Image Trace objects draw in their View, as on the canvas, instead of their tracing result): written to `path`, else (or with `data: true` as well) sent back as `pngBase64` | | `ui.render` | `{path?, scale?, artboard?, data?}` | render an artboard headlessly (PNG with the pixels of `app.export {format: "png", background: "white"}` at the same scale; `artboard`: its 0-based index, default the first): written to `path`, else (or with `data: true` as well) sent back as `pngBase64` | | `ui.resize` / `ui.focus` | | | -| `app.open` / `app.save` / `app.export` / `app.quit` | `{path, importer?, params?}` / `{path?}` / `{path?, format?, artboard?, range?, scale?, …}` | `app.open` reads every format `document.open` reads (see `document.formats`) and returns its result (`{index, title, format, warnings, …}`; `warnings` say what didn't come in as it was, such as an EPS shown as its preview image and why its PostScript couldn't be read), or null when a dialog asks first or a library loads. The status bar (`ui.inspect` → `ui.status`) counts the `warnings` and names the first that says reading the file left something out (the notes that make Save ask before writing over it), else the first; with several, hovering it lists them in that order, as many as fit in the window (at most 30), then how many more. After `app.save`, and `app.export` with a `path`, the status bar counts the reply's `warnings` and names the first, and with several, hovering it lists them in the reply's order (a save's notes start with what the format loses). With `importer` (an importer plug-in's format id, `plugin.`) it runs `file.openWith`: the file opens with that importer, also when a built-in format reads its extension, with the importer's parameters `params` (their defaults when omitted; no dialog asks for them). Without `importer`, `params` go to the importer that opens the file, and a built-in format does not read them. `app.export` encodes through the engine's `document.export` (same options; the document keeps its path) and writes `path` through the host; without `path` it returns `{dataBase64, format, bytes}`, as headless mode does. It refuses a key that no format takes, and an unknown key inside a PDF or EPS option object, before it writes anything (`docs/mcp.md`, Parameter keys). `app.save` refuses a key that no save format takes, beside the path or in `options`, the same way. `app.quit`, `file.close` and `file.closeAll` first open a `saveChanges` dialog for each modified document (they return `{"pending": "saveChanges"}`): `ui.dialog.confirm` saves, `ui.dialog.set {field: "discard", value: true}` then confirm discards, `ui.dialog.cancel` cancels the whole close or quit | +| `app.open` / `app.save` / `app.export` / `app.quit` | `{path, importer?, params?}` / `{path?}` / `{path?, format?, artboard?, range?, scale?, …}` | `app.open` reads every format `document.open` reads (see `document.formats`) and returns its result (`{index, title, format, warnings, …}`; `warnings` say what didn't come in as it was, such as an EPS shown as its preview image and why its PostScript couldn't be read), or null when a dialog asks first or a library loads. The status bar (`ui.inspect` → `ui.status`) counts the `warnings` and names the first that says reading the file left something out (the notes that make Save ask before writing over it), else the first; with several, hovering it lists them in that order, as many as fit in the window (at most 30), then how many more. After `app.save`, and `app.export` with a `path`, the status bar counts the reply's `warnings` and names the first, and with several, hovering it lists them in the reply's order (a save's notes start with what the format loses). With `importer` (an importer plug-in's format id, `plugin.`) it runs `file.openWith`: the file opens with that importer, also when a built-in format reads its extension, with the importer's parameters `params` (their defaults when omitted; no dialog asks for them). Without `importer`, `params` go to the importer that opens the file, and a built-in format does not read them. `app.export` encodes through the engine's `document.export` (same options; the document keeps its path) and writes `path` through the host; without `path` it returns `{dataBase64, format, bytes}`, as headless mode does. It refuses a key that no format takes, and an unknown key inside a PDF or EPS option object, before it writes anything (`docs/mcp.md`, Parameter keys). It accepts a key that only another format takes and does not use it: the reply's `warnings` and the status bar name the key ("`quality` was not used: PDF files don't read it"). `app.save` refuses a key that no save format takes, beside the path or in `options`, the same way. `app.quit`, `file.close` and `file.closeAll` first open a `saveChanges` dialog for each modified document (they return `{"pending": "saveChanges"}`): `ui.dialog.confirm` saves, `ui.dialog.set {field: "discard", value: true}` then confirm discards, `ui.dialog.cancel` cancels the whole close or quit | | `app.export` with `useArtboards` | `{path, useArtboards: true, range? \| artboards?, …}` | Export As: PNG, JPEG and WebP write one file per chosen artboard (default all; SVG does so for a `range`), `-.`, and return `{path, files: [path…]}`; a PDF keeps them as pages of `path`. `useArtboards: false` covers the bounds of the visible art. The menu's Export As… is `file.exportAs`: the `exportAs` dialog (`format`, `useArtboards`, `all`, `range`), then a save dialog and the format's options: `pngOptions` / `jpgOptions` / `webpOptions`, `svgOptions`, or `savePdf` for a PDF | | `ui.dialog.*` on `gradientStop` | `{field: "color" \| "opacity" \| "location", value}` | double-clicking a stop on the Gradient tool's annotator opens its popover (fields `index`, `x`, `y`, `tab`); set `color` (hex), `opacity` or `location` (percentages) and `ui.dialog.confirm` to apply them to the selected stop. `gradient.selectStop {index}` picks the stop the annotator, the panels and Delete/←/→ (`ui.key`) act on | | `engine.execute` `ui.savePdfDialog` | `{path?, preset?, range?, …document.exportPdf options}` | opens the Save PDF dialog (`file.export.pdf` with no params opens it too). Its fields are the `document.exportPdf` options: set `compatibility` with `ui.dialog.set {field: "compatibility", value: "1.5"}`, a whole section with `{field: "compression", value: {…}}`, the artboards with `__allArtboards: false` and `range`, the visible section with `__section` (General, Compression, Marks and Bleeds, Output, Advanced, Security, Summary). `useArtboards: false` opens it for one page of the visible art's bounds, as Export As with Use Artboards off does: the dialog has no Artboards section and its `__artBounds` field is true. `ui.dialog.confirm` writes `path` (else asks for one), returns `{path, bytes, warnings}` and opens the file when `viewAfterSaving` is set. With `useArtboards: false` it writes the page as `app.export` does and returns `{path, warnings}`, or `{background: true, status}` while Background Export writes it | @@ -120,7 +120,7 @@ the two can still win that race. | `app.export` Text and WebP | `{path?, format: txt, encoding?: utf8 \| utf16, lineEndings?: lf \| crlf, selectionOnly?}` / `{format: webp, lossless?, quality?}` | Text writes the stories in stacking order (back to front; a thread once; hidden objects and template layers left out), each line ended by `lineEndings`; `utf16` is little-endian with a byte order mark. Export As → Text opens `txtOptions` (fields `path`, `encoding`, `lineEndings`, `selectionOnly`; OK writes the file). WebP is always lossless: `lossless: false` adds a warning | | `engine.execute` `document.exportForOffice` | `{}` / `{path?, ppi?: 72 \| 150 \| 300, transparent?, artboard?}` | File → Save for Office Documents…: without params opens `saveForOffice` (fields `ppi`, `transparent`, `artboard`; OK picks the file); with params writes the artboard as a PNG (`path`, else a picked file) → `{path}`, and the status bar shows the export's `warnings` as Save As shows a save's notes. Headless it returns `{dataBase64, width, height, warnings}` | | Native file dialogs | any command with no `path` that needs one (`file.open`, `file.saveAs`, `file.place`, exports…) | on macOS (a sheet on the window) and Linux the dialog doesn't hold the window: the call returns `"cancelled"` at once, `ui.inspect` reports `fileDialog`, and when the person at the computer picks a file the command runs again on the document it was asked for. While it is open another dialog is refused: that call returns `"cancelled"` too, and the status bar (`ui.inspect` → `ui.status`) says `"A file dialog is open: choose there first"`; on macOS `app.quit`, `file.close` and `file.closeAll` return that message and the menu bar does nothing (#592, #867). On Windows the dialog is shown in line: the call returns once it closes. Pass `path` to skip the dialog | -| Background Save / Export | `app.save`, `app.export {path}`, `file.save`, `file.saveAs`, `file.saveCopy`, `file.exportForScreens {folder, …}` | with the `backgroundSave` / `backgroundExport` preferences on (the default) the desktop app writes the file from a snapshot on a worker thread: the call returns `{path, background: true, status}` at once (`file.exportForScreens`: `{background: true, status}`, and the files are written into the folder from a snapshot taken at the call), `ui.inspect` lists the jobs still running in `background` (labels such as `"Saving a.vectorcraft"`), and the document counts as saved (as of the snapshot) once its file is written. Quit and Close wait for them. A job that fails reports the error in the status bar only (`ui.inspect` → `ui.status`), a path outside `--automation-write-root` included. With the preferences off (`prefs.set`), saves return once written. `app.save {path?, wait: true}` and `app.export {path, wait: true}` wait for the jobs already running, write the file before they reply whatever the preferences are set to, and return its result or the error. When the save asks first (the question before replacing a file that opened with losses, or on macOS and Linux the file dialog for an untitled document without `path`), the reply is `{pending}` or `"cancelled"` as before, and the save that runs after the answer uses the preferences. A `wait` that is not `true`, `false` or `null` is refused with "`wait` must be true or false", and nothing is written | +| Background Save / Export | `app.save`, `app.export {path}`, `file.save`, `file.saveAs`, `file.saveCopy`, `file.exportForScreens {folder, …}` | with the `backgroundSave` / `backgroundExport` preferences on (the default) the desktop app writes the file from a snapshot on a worker thread: the call returns `{path, background: true, status}` at once (`file.exportForScreens`: `{background: true, status}`, and the files are written into the folder from a snapshot taken at the call; an `app.export` given an option the format doesn't read: also `warnings`, naming the option), `ui.inspect` lists the jobs still running in `background` (labels such as `"Saving a.vectorcraft"`), and the document counts as saved (as of the snapshot) once its file is written. Quit and Close wait for them. A job that fails reports the error in the status bar only (`ui.inspect` → `ui.status`), a path outside `--automation-write-root` included. With the preferences off (`prefs.set`), saves return once written. `app.save {path?, wait: true}` and `app.export {path, wait: true}` wait for the jobs already running, write the file before they reply whatever the preferences are set to, and return its result or the error. When the save asks first (the question before replacing a file that opened with losses, or on macOS and Linux the file dialog for an untitled document without `path`), the reply is `{pending}` or `"cancelled"` as before, and the save that runs after the answer uses the preferences. A `wait` that is not `true`, `false` or `null` is refused with "`wait` must be true or false", and nothing is written | | `engine.execute` `file.exportForScreens` | `{}` / `{…document.exportForScreens params}` | without params opens `exportForScreens` on the settings the document last exported with (`document.exportSettings`). While the Artboard tool is in use, the artboards it has selected (its `selected` option, the rows the Artboards panel highlights) are checked instead, and `select` is `range`, or `all` when every artboard is selected. Fields: `tab` (`artboards` \| `assets` \| `layers` \| `selection`; OK reads Export Layer or Export Selection on those), `layers` ([layer id…] checked), `selectionMode` (`one` \| `each`), `name` (the file name pattern of `document.exportForScreens`), `counterStart`, `folders` (`none` \| `rows` \| `format` \| `item` \| `itemFormat`), `exportPreset` (the preset applied last), `__savePreset` (the name typed to save one), `select` (`all` \| `range` \| `full`), `range` ("1-3, 5"), `boards` (a bool per artboard; checking them sets `select` and `range`), `includeBleed`, `folder` (desktop; default the Desktop, else home), `openLocation`, `subfolders`, `prefix`, `preset` (`""` \| `mobile` \| `density`), `formats` (rows `{format, scale: "2x" \| "100w" \| "100h" \| "72ppi", suffix, quality?, folder?}`), `settings` (`{png \| png8 \| jpg \| webp \| gif \| svg \| pdf: {…options}}`, the gear's Format Settings; `__settings` names the format shown). `ui.dialog.confirm` exports (a bad range or no folder keeps it open); on the web OK reads "Download" and the files download (several as one `.zip`). With params it runs `document.exportForScreens`: no `folder` returns the files (or with `zip: true` one zip) as `dataBase64`; with `openLocation` the first file is shown in the file manager. When `warnings` is not empty, an export into a folder or a download shows the first in the status bar as Save As shows a save's notes | | Export for Screens' Assets tab, Asset Export panel | `ui.dialog.set` `tab: "assets"`, `assets: [asset id…]`; `window.panel {panel: "assetExport"}` | on the Assets tab of `exportForScreens` the `assets` field lists the checked asset ids (all of them when it opens); `ui.dialog.confirm` runs `document.exportForScreens {assets}` (nothing checked keeps it open) and OK reads "Export Asset". The Asset Export panel acts through `assets.*` and shares the format rows with the dialog (`assets.settings.set`). The dialog has the format presets menu (☰). In the dialog, `exportPreset` names the preset applied last (`ui.dialog.set` of it applies the preset it names, as picking it does; a name that is not a preset's is an error and leaves the dialog as it was), `__exportPresets` lists the presets, and `__savePreset` holds the name being typed after Save Preset…. The panel menu applies presets through `assets.settings.set {exportPreset}` and holds Save As Preset…, Save Changes, Delete Preset, Import Preset… and Export Preset…. Import and Export use picked files. | | `engine.execute` `file.exportSelection` | `{multiple?}` | File › Export Selection…: collects the selected objects as one asset (`assets.add`; one per object with `multiple: true`) and opens `exportForScreens` on its Assets tab with just them checked → `{assets}`. `document.exportSelection` still exports the selection in one go, without the dialog | diff --git a/docs/development.md b/docs/development.md index cbb20e3b8a..05062e18b8 100644 --- a/docs/development.md +++ b/docs/development.md @@ -125,7 +125,7 @@ On GNOME/Wayland, enable **Preferences › User Interface › System Title Bar** The window runs natively on Wayland (eframe's `wayland` feature) and on X11. On machines with two GPUs it renders on the one the desktop runs on unless Preferences say otherwise; see [Desktop graphics processor](#desktop-graphics-processor) (#502). The system clipboard (`apps/vectorcraft/src/clipboard.rs`) is arboard with its `wayland-data-control` feature: -- **Clipboard:** under Wayland arboard talks to the compositor through the data-control protocol (wlroots compositors such as Sway and Hyprland, KDE Plasma), so bitmaps (`image/png`), SVG markup and text copied in any app paste (#398). Where the compositor lacks the protocol (GNOME's Mutter, [arboard#223](https://github.com/1Password/arboard/issues/223)), arboard falls back to the X11 clipboard through XWayland, which only holds what X11 apps copied. Where there is no X11 either (the Flatpak on a Wayland session: `--socket=fallback-x11` gives it none), Copy and Paste use the compositor's core data-device protocol on the window's own connection through smithay-clipboard: text only (a copy's text or its SVG markup), and only while the window has focus. smithay-clipboard waits for the owner's data with no limit, so its reads run on a worker thread and the UI thread waits 2 s at most: an owner that never sends its data costs one read 2 s, and later reads return at once until it answers. When a read gets no answer in its 2 s, such as a paste's check whether the clipboard still holds what VectorCraft copied, the paste waits on its background thread for that read's answer, up to 10 s after the read was sent, and pastes the text unless it is empty or what VectorCraft copied. A clipboard neither backend opens is tried again after 1 s, doubling to a minute (a Copy or Paste of the user's at most once a second), and logged once when it goes and once when it comes back: before, the background Paste check reconnected and logged a warning every 250 ms. egui's own text paste into fields goes through smithay-clipboard and works either way. +- **Clipboard:** under Wayland arboard talks to the compositor through the data-control protocol (wlroots compositors such as Sway and Hyprland, KDE Plasma), so bitmaps (`image/png`), SVG markup and text copied in any app paste (#398). Where the compositor lacks the protocol (GNOME's Mutter, [arboard#223](https://github.com/1Password/arboard/issues/223)), arboard falls back to the X11 clipboard through XWayland, which only holds what X11 apps copied. Where there is no X11 either (the Flatpak on a Wayland session: `--socket=fallback-x11` gives it none), Copy and Paste use the compositor's core data-device protocol (`wl_data_device`) on the window's own connection, and only while the window has focus. One Copy offers the PNG as `image/png`, the SVG as `image/svg+xml` (with Include SVG Code on) and the text as `text/plain;charset=utf-8`, `UTF8_STRING` and `text/plain`; a format with no data is not offered. Paste reads `image/svg+xml`, then text, then `image/png`, and blank text or text that only names a picture gives way to the PNG; the Paste menu item is enabled by the types offered, without reading any data. Whether the clipboard still holds VectorCraft's Copy is told by its data source, which the compositor cancels when another app copies. A read takes 64 MiB at most and fails beyond that. Reads run on a worker thread: text waits 2 s at most on the UI thread, SVG and PNG 10 s on the paste's background thread. An owner that never sends its data costs one read its wait, and later reads return at once until it answers. When a text read gets no answer in its 2 s, the paste waits on its background thread for that read's answer, up to 10 s after the read was sent, then reads the clipboard again unless it holds VectorCraft's Copy. Another app's paste of a Copy is sent on a thread of its own, 8 at once at most; a paste beyond them gets nothing. A clipboard neither backend opens is tried again after 1 s, doubling to a minute (a Copy or Paste of the user's at most once a second), and logged once when it goes and once when it comes back: before, the background Paste check reconnected and logged a warning every 250 ms. egui's own text paste into fields goes through smithay-clipboard and works either way. - **Clipboard owners that never answer (#510):** reading the clipboard waits on the app that owns it: arboard gives up on an X11 owner after 4 s for each format it tries, and a Wayland read waits for the owner to send its data. So on Linux the check that enables the Paste menu items runs on a background thread with a second clipboard handle (`crates/ui-egui/src/clipboard_probe.rs`, installed as `Services::clipboard_probe`), only while nothing is copied in the app and a document is open, and the window keeps drawing. Every arboard read on Linux and the BSDs, including the UI thread's (a paste, and a Copy or Cut checking what the clipboard held), runs on a worker thread with a handle of its own and waits 2 s at most: an owner that never sends its data costs one read that wait, and later reads fail at once until it answers. A paste's bitmap read waits up to 10 s on the paste's background thread, so the UI thread does not wait for it. When one of a paste's reads gets no answer in its 2 s, or a paste follows a read that has not been answered yet, such as the paste's own check whether the clipboard still holds what VectorCraft copied, the paste waits on that thread for that read's answer, up to 10 s after the read was sent, and pastes what it holds. When the answer is what VectorCraft copied, holds nothing to paste, or does not come, the paste takes the internal clipboard. On X11, quitting within 25 s of a read that got no answer waits for that read to end, so the app's own handle is the last one and hands what it copied to the clipboard manager when one runs. That includes a read of the Paste menu check's handle: quitting waits up to 27 s for the background thread to drop it before the app drops its own, and quits after that wait even when the handle has not been dropped. The app hides its main window before these waits (`hide_before_teardown` in `apps/vectorcraft/src/app.rs`), so an X11 window, an XWayland one included, closes at once; winit cannot hide a native Wayland window, which stays on screen until the waits end. Windows and macOS keep the check on the UI thread: Windows only asks which formats the clipboard holds, macOS asks the pasteboard server. - **Copied files:** files copied in a file manager (`text/uri-list`; `CF_HDROP` on Windows, file URLs on macOS) paste as the first one that is art (SVG, PDF, EPS, EMF/WMF or a bitmap; a `.ai` or `.ait` file from the editing data it holds, else as the PDF or PostScript it holds), before the clipboard's other formats (which include the files' paths as text). - **Dropping files on the window does not work under Wayland:** winit 0.30, which eframe 0.37 runs on, has no Wayland drag and drop ([winit#1881](https://github.com/rust-windowing/winit/issues/1881), added in winit 0.31; [egui#1563](https://github.com/emilk/egui/issues/1563)), so no `dropped_files` arrive. Until eframe moves to winit 0.31: copy the files in the file manager and paste them, use File › Place or Open, or open the window through XWayland, where drops work: set **Preferences › Performance › Linux Display Server** to **X11 (XWayland)** and restart (#1151), or start the app with `WAYLAND_DISPLAY= vectorcraft`. The preference (`linuxDisplayServer`, read at startup in `apps/vectorcraft/src/main.rs`, shown on Linux only) has winit open the window on X11 (`EventLoopBuilderExtX11::with_x11`) when the session is Wayland, `DISPLAY` is set and the X11 libraries winit loads are installed (`apps/vectorcraft/src/xwayland.rs` reads `ldconfig -p` and the usual library directories); otherwise the window opens on Wayland and the log says why. Unlike clearing `WAYLAND_DISPLAY`, it leaves the clipboard on the compositor's own. diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index f752a8973b..1232e3ea49 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-13 · **Change:** minor (`.ai` and EPS import: a top-object envelope whose mesh saves its sides' curves in pieces draws its contents along each whole curve, as its drawn art does, #7097; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: `.ai` and EPS import: type from the text document, type a PostScript program sets and legacy `.ai` type are set in an installed face of their font's PostScript name, exact name first, in the version a text document's record keeps; the `.ai` save writes a static font's version when its name alone gives another copy, #6983; `.ai` and EPS import: type keeps the manual kerning of its text document, #6899; `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, its strokes' miter tips and strokes a Transform effect moves included, after its glyphs grown by half its strokes' weight, #6824; `.ai` and EPS import: type filled or stroked with a pattern swatch keeps its pattern, from the art style its text document paint names, #6856; #6865: explicitly requested oversized editing artboard; PDF import: Indic type keeps its marks on their line, and a line whose type would not draw as the file does keeps the file's glyphs as outlines, #5235; previously: newly imported SVG/SVGZ titles are filtered and bounded without changing restored titles, #3626; `.ai` and EPS import, and what every export and `.ai` save draw: type's strokes in an envelope paint at their own weight along its bent outlines, Distort Appearance on or off, #6644; `.ai` and EPS import: centred and right-aligned lines of tracked type are aligned without the tracking after their last character, as the file's page aligns them, #6610; `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art, #6570; `.ai` save and open: layer colour presets Yellow, Magenta and Cyan keep their colour, as the `Lb` colour index now follows the file's numbering, #6502; `.ai` save: stroked type keeps its stroke's cap, join and miter limit in the text document, #6472; `.ai` and EPS import, PDF import: tracking and manual kerning in horizontally scaled type take the Horizontal Scale, as the file's page spaces such type; `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke, #3179; `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid, #3179; `.ai` and EPS import: stroked type keeps its stroke's cap, join and miter limit from the text document, #6472; `.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page, #3179; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-13 · **Change:** minor (`.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; `.ai` and EPS import: a top-object envelope whose mesh saves its sides' curves in pieces draws its contents along each whole curve, as its drawn art does, #7097; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: `.ai` and EPS import: type from the text document, type a PostScript program sets and legacy `.ai` type are set in an installed face of their font's PostScript name, exact name first, in the version a text document's record keeps; the `.ai` save writes a static font's version when its name alone gives another copy, #6983; `.ai` and EPS import: type keeps the manual kerning of its text document, #6899; `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, its strokes' miter tips and strokes a Transform effect moves included, after its glyphs grown by half its strokes' weight, #6824; `.ai` and EPS import: type filled or stroked with a pattern swatch keeps its pattern, from the art style its text document paint names, #6856; #6865: explicitly requested oversized editing artboard; PDF import: Indic type keeps its marks on their line, and a line whose type would not draw as the file does keeps the file's glyphs as outlines, #5235; previously: newly imported SVG/SVGZ titles are filtered and bounded without changing restored titles, #3626; `.ai` and EPS import, and what every export and `.ai` save draw: type's strokes in an envelope paint at their own weight along its bent outlines, Distort Appearance on or off, #6644; `.ai` and EPS import: centred and right-aligned lines of tracked type are aligned without the tracking after their last character, as the file's page aligns them, #6610; `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art, #6570; `.ai` save and open: layer colour presets Yellow, Magenta and Cyan keep their colour, as the `Lb` colour index now follows the file's numbering, #6502; `.ai` save: stroked type keeps its stroke's cap, join and miter limit in the text document, #6472; `.ai` and EPS import, PDF import: tracking and manual kerning in horizontally scaled type take the Horizontal Scale, as the file's page spaces such type; `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke, #3179; `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid, #3179; `.ai` and EPS import: stroked type keeps its stroke's cap, join and miter limit from the text document, #6472; `.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page, #3179; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) > > Oversized artboard import update (2026-11-12): Explicit editing-data import retains a single artboard beyond a capped 14,400 pt PDF page (#6865). @@ -323,6 +323,7 @@ Stop opacity on translated artboards remains outside this regression coverage. | Date | Change | Summary | |---|---|---| +| 2026-11-13 | minor | `.ai` and EPS import: layers that don't draw as the page, even with the drawn art of every live envelope put back, no longer put back the drawn art of every envelope of type. Each live envelope of type is weighed in the page check's own drawing of the pages it lies on, on the pixels that it and its drawn art ink there (the two drawn together on a layer of their own, without the rest of the layers; a pixel inks with an alpha above 8 of 255): it keeps its drawn art and its type, hidden, with the note, where the layers with it differ from the page in more of those pixels than its own check allows against its drawn art (10% of them, or 3% differing with all their neighbours, away from type), or where the envelopes of type that stay live, in the order they were read, would together differ there in more of a page than half of what the page check allows (a budget of the same size as the one their own checks share, kept apart from it). Art that differs elsewhere on the page no longer costs them their editable type; art that differs on their pixels still does. An envelope of type that a clip group or a clipping sublayer clips, an opacity mask masks, or a group with an appearance of its own, another envelope, a repeat or a blend holds keeps its drawn art as before, wherever it lies: drawn on its own it would be weighed elsewhere than it draws, and what holds it can draw it onto the page from off it. An envelope on no page stays live, as the page check doesn't see it, unless the page holds all the art that prints (an EPS's page that is its art's box, where art past the page is compared too): there one reaching past the page keeps its drawn art. Past 12 of them on the pages, all keep it. This holds where the editing data is trusted, where the objects that differ come in as the page's art (the placed files' other placement weighed on its own, as it draws them elsewhere under or over the envelopes; layers that draw as the page with only the envelopes the page holds put back are used as they are; where none of the objects that differ can then come in as the page's art, because an object holds type, the drawn art of every envelope of type is put back and that is tried again, as before), and for a `.ai` whose layers would open alone, which still opens alone: its envelopes of type are all settled again as they were with the page, in the same order and with the same checks, so each that opens live draws as it was weighed, and those the page held get their drawn art back. Where putting the drawn art of every live envelope back makes the layers draw as the page, it is still put back (#5065). In 224 users' files (used locally, never committed): envelopes of type that open live go from 174 to 186, in 8 files, none fewer in any file; no file changes between its layers and its PDF part; 7 renders change, by at most 0.7% of their pixels at 40 ppi (1 closer to the page, 1 alike, 5 further, by at most 0.7 of a percentage point, where VectorCraft's own envelope draws a little apart from the drawn art, within its check); the note for type in an envelope goes from 6 files. Of the 14 envelopes of type that had opened live and lost it to the page check, 2 keep their drawn art: one where the page draws something else where it is, and one in a file that comes in as its PDF part (#7141). Tests `build::candidate_tests::the_page_holds_back_only_envelopes_of_type_where_it_differs_from_them`, `envelopes_of_type_stay_live_within_half_of_what_the_page_check_allows`, `an_envelope_of_type_differing_in_more_of_its_pixels_than_its_check_allows_is_held_back`, `envelopes_of_type_the_layers_dont_draw_in_place_are_held_back`, `on_a_page_that_holds_all_the_art_an_envelope_of_type_past_it_is_held_back`, `objects_come_in_as_the_page_art_with_every_envelope_of_type_put_back_where_a_live_one_holds_a_difference`, `tests_native::layers_that_would_open_alone_keep_an_envelope_of_type_live_where_other_art_differs_from_the_page`, `layers_that_would_open_alone_keep_live_only_the_envelopes_of_type_the_page_doesnt_hold`, `trusted_layers_that_would_open_alone_open_alone_with_an_envelope_of_type_the_page_doesnt_hold_live`, `layers_with_objects_that_come_in_as_the_page_art_keep_an_envelope_of_type_that_draws_as_the_page_live`, `trusted_layers_keep_an_envelope_of_type_live_where_other_art_differs_from_the_page`, `trusted_layers_leave_an_envelope_of_type_the_page_draws_otherwise_its_drawn_art`, `build::candidate_tests::the_other_placement_of_placed_files_is_weighed_on_its_own`, `layers_that_draw_as_the_page_with_the_held_envelopes_of_type_put_back_are_used_so` | | 2026-11-13 | minor | PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke instead of being left out, adding no text (#6971; `empty_actual_text_keeps_the_glyphs_art` in `crates/pdf/src/tests/actual_text.rs`). Scores and estimates unchanged. | | 2026-11-13 | minor | `.ai` and EPS import, and what the canvas, every export and `.ai` save draw: a top-object envelope's mesh can save a side's curve in pieces. In users' files (used locally, never committed), 10 top objects save a grid of three patches across whose top and bottom edges are each one cubic split into thirds, and their drawn art follows the whole curve's parameter. VectorCraft gave each piece the share of its control polygon, so their type came out up to about half a point off the drawn art along the side, and one envelope of type kept its drawn art instead of opening live. A side whose pieces are all one curve split at anchors (each within 0.02 pt of that curve's piece) now follows that curve's parameter (#7097). Synthetic test: `a_top_object_whose_top_is_one_curve_split_in_thirds_opens_live`. Scores unchanged. | | 2026-11-12 | minor | `.ai` and EPS import (#6983): type from the text document is set in an installed face of the PostScript name its font record gives, one of exactly that name first. That face's family is no longer swapped for another family spelled alike but for case and punctuation (`FontDb::find_family`, which picked `SAMPLE INK` for `SampleInk`, the PostScript name of `Sample/Ink`); among the faces `FontDb::postscript_faces` lists for the name, the import takes one whose name matches in case and punctuation before one that matches only without them; and when the family and style alone resolve to another installed copy, the type names the face's version. A font record's key 5, the version string (name ID 5), picks that version among the faces of its PostScript name, also when the record spells the name with other punctuation (`Sample-Slab` for faces named `SampleSlab`); each record is resolved once. Type a PostScript program sets and legacy `.ai` type take the face of their font's name the same way. The `.ai` save writes a static font's version (`/5`) when its PostScript name alone would give the reader another installed copy (another version, or the same name in another family), so two such copies are two fonts of the set, and checks that the type comes back in the same family, style and face, taking the record's version as the reader does (up to 256 bytes): such type round-trips without the type attributes note, and so does a version that isn't installed, which draws in the face the font resolves to anyway. In 224 users' files (used locally, never committed; all PDF-compatible, so the PostScript and legacy paths are not exercised), 16 files set some type in another installed face; 12 render differently against their own page, 10 closer (in one from 2.55% to 0.01% of the page differing) and 2 further by 0.03% of the page (an envelope of type that now opens live, and a copy of the same widths in the version the record names); envelopes of type that open live go from 154 to 159, none fewer in any file; no file opens in another way. The notes of how far a file's layers differ from its page shrink in 2 files and appear in 2 where an envelope of type now opens live, so the file is compared with its page. Two installed copies of one PostScript name, family and style that differ in widths, in files whose records keep no version, still take the copy the family and style resolve to: only the page's widths tell them apart. Tests: `tests_native::type_from_the_text_document_takes_the_face_of_its_exact_postscript_name`, `tests_native::type_from_the_text_document_takes_the_version_its_font_record_keeps`, `tests_fontnames::shown_type_takes_the_face_of_its_exact_postscript_name`, `ai::tests::legacy_type_takes_the_face_of_its_exact_postscript_name`, `ai_editing::tests::type_in_a_font_beside_a_family_spelled_alike_keeps_its_font`, `ai_editing::tests::type_in_another_version_of_a_static_font_keeps_it`, `ai_editing::tests::type_in_a_copy_its_postscript_name_alone_doesnt_give_keeps_it`, `ai_editing::tests::a_version_longer_than_the_reader_takes_is_reported`, `vectorcraft-text` `tests::versions::every_face_of_a_postscript_name_is_found`. Scores unchanged. | diff --git a/docs/gaps.md b/docs/gaps.md index dc573d41e6..1c33281d10 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-12 · **Change:** minor (icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: oversized editing artboard import; Glyphs panel: Alternates for Current Selection applies an OpenType feature value (`salt=2`) to the selected letter alone, so an Arabic word stays joined, and Entire Font lists the unencoded glyphs, #5514; #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-13 · **Change:** minor (PDF import: preserve Type 3 font text runs as named groups , or as live text in TextAs::Text mode if ToUnicode exists on non-colour fonts (TextAs::Outlines produces grouped outlines), #6740; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: oversized editing artboard import; Glyphs panel: Alternates for Current Selection applies an OpenType feature value (`salt=2`) to the selected letter alone, so an Arabic word stays joined, and Entire Font lists the unencoded glyphs, #5514; #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -34,6 +34,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-13 | minor | PDF import: preserve Type 3 font text runs as named groups ``, or as live text in `TextAs::Text` mode if `/ToUnicode` exists on non-colour fonts (`TextAs::Outlines` produces grouped outlines) (#6740); scores and estimates unchanged. | | 2026-11-08 | minor | #3380, deletion only: preserve gradient placement and exact surviving geometry; consume owned subpaths with a shared original-node snapshot; consolidate status/evidence and document command/helper contracts. Compound behavior and the existing M2 status entry are retained. Endpoint highlighting remains open; scores and estimates unchanged. | | 2026-11-07 | minor | #3380 (deletion only): independent surviving path objects; transformed appearance, stacking, selection, cubic handles and Undo/Redo covered by `delete_path_pieces`; compound semantics retained. Endpoint highlighting remains open; scores and estimates unchanged. | | 2026-11-07 | minor | Indian-language hyphenation (#4947): eleven MIT-licensed pattern sets, with grapheme and shaping-cluster protection in both composers and existing paragraph limits. Assamese and Sanskrit are selectable; Sanskrit automatic patterns remain pending an allowlisted source. Scores and estimates unchanged. | @@ -192,6 +193,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G9 Illustrator `.ai` and EPS files from real users +- **Done (#6740, 2026-11-13):** PDF import preserves Type 3 font text runs as named groups `` when drawn as outlines or color graphics, and reconstructs live text objects in `TextAs::Text` mode when `/ToUnicode` exists and the font is not a colour font (`TextAs::Outlines` produces grouped outlines; `crates/pdf/src/tests/text_placement.rs`). Scores and estimates unchanged. + - **Done (#6388, 2026-11-10):** a saved `.ai`'s text document names, for type in a variable font, where in the font's design space it is set (each axis, the named instance's or the run's own setting) and the font's version, so Montserrat Bold no longer opens as the font's default instance (Thin); two settings of one font are two fonts of the set. Test `ai_editing::tests::variable_font_instances_name_their_design_space`. The PDF part's font naming (#4548) remains with craft-libs. Estimate unchanged. - **Narrowed (#6165, 2026-11-09):** editable PDF import preserves explicit ActualText once, with empty/nested spans, authored order and glyph advances covered by `crates/pdf/src/tests/actual_text.rs`. One replacement uses the first placed glyph's line/style; exact redistribution across lines/styles and general mixed-direction layout remain. Input is bounded to depth 128 and 64 KiB encoded per accepted replacement. This does not close G9's broader `.ai`/EPS gaps or change its estimate. @@ -243,7 +246,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Done (2026-11-04):** a first frame the app is slow to build no longer costs the window its graphics adapter (#5160). The first-frame watchdog gave the frame 20 s from the app's start and then started again without the adapter, so a slow machine (antivirus reading every file, a large font library) ended with no adapter left and no window. A frame counts once its UI pass ends, before it is painted, so the 20 s now run from there; a frame still being built is waited for, with a note in the log (`a_first_frame_that_never_reaches_the_screen_hangs_its_adapter`; checked on Linux with the first frame held 35 s: the window opened with no restart). Estimate unchanged. - **Done (2026-11-04):** a large font library no longer keeps the window from opening (#5483). The menu bar's Type › Font, drawn in the first frame, waited for the scan of every installed font; when that took longer than the 20 s first-frame watchdog (thousands of fonts on a slow disk, or with each file checked by antivirus) the app took the graphics adapter for hung and started again without it until none was left. The menu now lists the fonts already loaded until the scan ends, then all of them (`the_menu_family_list_now_does_not_wait_for_the_scan`; checked on Linux with 3,923 extra font files, each open delayed 8 ms: the window opened in 1.5 s, where it never did before). Estimate unchanged. - **Done (2026-10-29):** the Linux Flatpak on GNOME no longer reconnects to the compositor and logs a warning every 250 ms when arboard has neither data-control nor X11 (267k warnings in 18 h filled the 16 MB log in 3 h): a clipboard that can't be opened is retried with a wait growing to a minute and logged once. Copy and Paste of text with other apps work there through the core Wayland protocol. -- **Missing:** pictures (`image/png`) and SVG as `image/svg+xml` on the clipboard of the Flatpak on GNOME, where only text travels (smithay-clipboard 0.7 carries text only); the app not starting or staying in the background on some Windows 11 machines (#858, #964 fixed +- **Unconfirmed (2026-11-13):** pictures and SVG on the clipboard of the Flatpak on GNOME. Copy there offers the PNG as `image/png`, the SVG as `image/svg+xml` (with Include SVG Code on) and the text, all from one Copy; Paste takes SVG, then text, then the PNG (blank text, or text that only names a picture, gives way to the PNG), and the Paste menu item is enabled by the types offered. A read takes 64 MiB at most (`clipboard::wayland` tests; not yet run in the Flatpak on a GNOME session). +- **Missing:** the app not starting or staying in the background on some Windows 11 machines (#858, #964 fixed 2026-10-10, #620, #818), slow pointer on a Linux AppImage (#575), macOS paste from other apps (#954), a web-free crash/hang reporter, a field record. - **Evidence:** open issues; the never-crash lints and `guard` stop panics, not driver, windowing or packaging @@ -617,6 +621,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi them in proportion, as one undo step ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-similar-objects.html)); on a group (#4939), the groups like it (the same objects at the same places, moved or scaled) take an edit made to an object inside it at the object in the same place ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-groups-with-similar-objects.html)); + a group that holds type or an image is not taken, as Global Edit does not take images or text + ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-similar-objects.html)); with one such object or group selected with the Selection tool, the objects Start Global Edit would take are highlighted on the canvas before it starts (`selecting_one_object_highlights_the_similar_objects_before_global_edit_starts`); dynamic symbols (#4938): Symbol Options › Symbol Type (Dynamic Symbol / Static Symbol; `type` on @@ -663,7 +669,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi `graphicStyle.addFromLibrary`). - **Missing:** more built-in brush libraries beyond the eight shipped (and further graphic-style libraries beyond the ten shipped, and further symbol libraries beyond Basic Shapes, UI Frames, Map Markers, Inventory Icons and Skill Icons; original, generated in code, never Adobe's); dynamic symbols' `.ai` read and write; - Global Edit of groups holding type or images, and rotated copies as matches. + Global Edit of rotated copies as matches. - **Estimate:** 5–15 h. ## G3 3D and Materials diff --git a/docs/image-trace-quality.md b/docs/image-trace-quality.md index f949d06071..40f6fe43b9 100644 --- a/docs/image-trace-quality.md +++ b/docs/image-trace-quality.md @@ -156,6 +156,34 @@ under 0.9 px RMS from the gradient's contours, 1.13 px when smoothed as edges, a four corners); `layers::tests` (a ramp, flat colors in palette entries far apart, close flat colors, a thin flat stroke, colors off the line between their entries, and Grayscale's grays, each read from both sides of the crack) and `subpixel::tests` (the rule, and one decision for a whole piece from either side). +## Blurred edges +`settled` moved a blend pixel to a side of its edge only when the picture's own colors on both sides lay +within 2 px of it, so the middle of an edge blurred over more than about 4 px kept the palette's +in-between tones and traced as rings of thin paths around the edge. In Color with a Limited palette of +at most 16 colors and in Grayscale with at most 16 grays, `cut_edge::settled_wide` now does the work, by +VectorCraft's own rule (RGB distances, 0 to 255 a channel; Grayscale reads each pixel as its gray). A +blend pixel with no own pixel of its color within 4 px pairs the 8 own colors within 8 px that are nearest +to its color. It takes the nearer side of the pair it is best a blend of when that pair explains it twice +as well as its own color, or when it lies between the two and off the line between them by less than 0.15 +of their distance apart. Of two pairs that fit equally well it takes the closer pair. Other palettes, +High Fidelity Photo, Low Fidelity Photo and Black and White keep `settled`. +Measured with the harness below on `main` at `77970c6924`, before and after the change (256 px variants +unless stated): 16 Colors on blurred flat art 9.0 paths to 3.0, 158 anchors to 34, 0.239 px off to 0.069; +6 Colors 6.0 paths to 3.0, 118 anchors to 33, 0.226 px off to 0.071; scanned, 16 Colors 8.0 paths to 3.0 +and 0.259 px off to 0.110, 6 Colors 7.5 paths to 3.0 and 0.235 px off to 0.093. On each preset's own +inputs (section 1), 6 Colors went from 4.1 paths to 3.0 and 0.143 px off to 0.101, and 16 Colors from 4.6 +paths to 3.0 and 0.145 px off to 0.100. Auto Color does not change. Worse by more than 5% (25 of 211 rows +that moved, most of them variants of the same inputs): askew shapes, odd px 11 to 22 with 6 Colors (paths +4.0 to 4.3, odd colours 0.3 to 0.7), 23 to 26 with 3 Colors, 17 to 22 with 16 Colors and 27 to 30 with +Shades of Gray; thin lines, missed max 23.5 to 45.3 px with 16 Colors, and with Shades of Gray paths 5.3 to +7.3, anchors 36 to 41 and odd colours 3.0 to 5.0; linear gradients with 3 Colors, paths 3.0 to 3.3, and +with 6 Colors with Gradients, paths 1.3 to 1.5 and anchors 13 to 16; two- and three-stop gradients with 6 +Colors with Gradients, paths 1.2 to 1.3; gradient and photo with 16 Colors, overlap px 0.0 to 0.2 and +specks 0.8 to 1.0. The tables below are the previous measurement, not a rerun. +Tests on code-drawn images: `tests::a_blurred_edge_is_no_ring_of_a_tone_between_its_sides` (a disc +blurred into a 10 px ramp, 16 Colors), `tests::grayscale_settles_a_blurred_edge_between_its_own_two_grays`, +`tests::grayscale_settles_a_tinted_blurred_edge_by_its_lightness`, +`tests::the_photo_presets_keep_the_tones_of_a_blurred_edge` and `quantize::cut_edge::tests`. ## Staircases in smooth areas Where a band border in a gradient or a shaded area runs at a slant, its pixels form a staircase whose steps are two or more pixels long. One piece of outline can run along a sharp edge in the image and then diff --git a/docs/mcp.md b/docs/mcp.md index 6800d7d7e5..4344210285 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -267,7 +267,8 @@ the suite) keep the agent to the folders you give it: Links in an opened document that point outside the read roots show as missing. - An error names a path the client gave as given. A path the client did not give (the document's own file in a save without `path` and in `file.revert`, also inside `action.batch`, an export preset's folder, the - Scripts folder, the document's folder in `links.relink {copy}`) is named + Scripts folder, the document's folder in `links.relink {copy}`, a New Document profile's file in + `file.newProfiles.edit` and `file.newProfiles.reset`) is named whole only inside the read roots; outside them the error names it by its file name, or as `a file or folder outside the read roots` when it has none, and keeps the roots and the reason, for example `automation path rejected: outside the write root /work/project/out: poster.vectorcraft`. @@ -1279,7 +1280,7 @@ canvas draws it as pixels, out to the miters, caps and arrowheads of a stroke. P have no diamond gradient: one of opaque stops is written as four linear gradients, one for each quarter of the square, clipped to the shape (PDF as axial shadings). In PDF and SVG, one with translucent stops, a dithered fill or a square with no area is an image, and so is a Perceptual one, except in PDF when its stops are spot colors that the -Method paragraph below describes. SVG writes one on type characters as a radial gradient through the square's +Method paragraph below describes. One mixed around the hue wheel is always an image in PDF and SVG. SVG writes one on type characters as a radial gradient through the square's corners. PDF import reads a function-based shading (type 1) whose color is the same along each square about the origin of its space, with corners on its axes, as a diamond gradient. CSS writes a radial gradient through the square's corners. A swatch library saved as CSS gets four `linear-gradient` layers, one for each quarter of the box, @@ -1323,7 +1324,7 @@ change its colors least. Each run keeps its ends; sharp steps and swatch-linked but a run with more of them than its share of the limit loses some. The same applies to a gradient along or across a stroke, and to CSS's conic gradient, past 16,384 stops, and to Outline Stroke's mesh past 1,024. For CSS the 16,384 counts the gradient's stops before they are written: CSS then adds a stop for each midpoint, and for a Perceptual -gradient stops along each span's curve, so the written gradient can hold more. PDF +gradient or one mixed around the hue wheel stops along each span's curve, so the written gradient can hold more. PDF import finds a sharp step between two colors in an axial or radial shading by halving the spans between its samples, so the step reads back where it is in the file (to 1/64 × 2^-14 of the axis) instead of blurred across the samples around it. A shading takes at most 16,384 samples, so the steps past the point where that budget runs out stay @@ -1352,10 +1353,26 @@ stops whose other stops are all paper white or written in CMYK or gray, that is does not have too many stops (a diamond as four such shadings). An export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile. PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading. +`hue-clockwise` and `hue-counterclockwise` (VectorCraft's own methods) mix a linear, radial, conic or diamond +gradient's colors around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next. +With `hue-clockwise` the hue angle falls (red, magenta, blue, cyan, green, yellow, red), which is clockwise on the +app's color wheels, and with `hue-counterclockwise` it rises. The angle keeps one direction between two stops, as the +fixed-direction rules of [CSS Color 4](https://www.w3.org/TR/css-color-4/#hue-interpolation) do, so red to blue passes +through green one way and through magenta the other. Two stops whose hues are less than half a color level apart +count as one hue and keep it, so a color and a tint or shade of it do not turn the wheel; their saturation and +brightness still change evenly, which is not the mix `classic` gives. A stop whose RGB numbers are less than half a +color level apart is gray: it takes the hue of the stop it mixes with, and a black stop takes that stop's saturation +too. SVG and PDF exports write such a gradient as an RGB image at the Document Raster Effects resolution, in a CMYK +document and with CMYK stops too, and with spot color stops (with a warning). EPS writes it as a shading in process +colors, and a legacy `.ai` file and the `.ai` editing data get the colors between its stops as stops of their own, in +process colors (at most 256, with a warning). `reverse` turns a hue method the other way with the stops, so the ramp +keeps its colors, and a Reflect spread mirrors the colors of each run. The names also read in any case, and with a +space or an underscore for the hyphen, or without it. `paint.setFill`/`paint.setStroke` take it in `gradient` too: ```json {"name":"run_command","arguments":{"command":"paint.editGradient","params":{"method":"perceptual"}}} +{"name":"run_command","arguments":{"command":"paint.editGradient","params":{"method":"hue-clockwise"}}} ``` Freeform gradients: `paint.editGradient {kind: "freeform"}` places four or more colour points inside each selected @@ -1465,7 +1482,9 @@ preferences (the folder the desktop app uses, so both see the same ones; `VECTOR working spaces and the file stay as they are. The profiles in use are those of the document in front, after `file.new`, `document.open`, `document.activate`, `file.close`, `file.revert`, `edit.undo`, `edit.redo` and a failed `command.batch` too; with none assigned, or no document open, the working spaces are. The `workingCmyk` - target of `view.proofSetup` simulates the working CMYK space in such a document too. + target of `view.proofSetup` simulates the working CMYK space in such a document too. `color.convert`'s + `outOfGamut` and `deltaE`, `color.gamutCheck`, and the out-of-gamut warning of the Color panel and Color Picker + check against the assigned CMYK profile, else the working CMYK space; the warning updates when either changes. Not remembered: the document, anything else. Nothing is read or written when `VECTORCRAFT_NO_PREFS` is set, and a server confined with `--automation-read-root` or @@ -1604,8 +1623,18 @@ hides the dock, no panel is checked, and the panel shows again with the dock in Control bar stay as they are. The export commands limit those keys. `document.export`, `document.exportSelection`, `document.serialize`, `app.export` -and `file.export` refuse a key that no format takes, and ignore a key that only another format takes -(`{"format": "pdf", "quality": 80}` writes the PDF). `document.exportPdf`, `document.pdfSettings` and `pdf.preset.save` +and `file.export` refuse a key that no format takes. They accept a key that only another format takes and do not use +it: `{"format": "pdf", "quality": 80}` writes the PDF, and the reply's `warnings` name the key +("`quality` was not used: PDF files don't read it"), in the wording of a save's note. The warning names the kind of +file written. A legacy `.ai` file (`aiVersion: "7"`) reads `outlineText`, `hiddenObjects`, `transparentImages`, the +artboard choice and `useArtboards`, and beside `aiVersion` no other option +("`compress` was not used: legacy .ai (version 7) files don't read it"). The other `.ai` files don't read those three +options or `preserveEditing`, which is always on for a `.ai` file. An export doesn't read `separateArtboards`, or +`range` for a `vectorcraft` or `template` file: a save reads them to write each artboard to a file of its own. In the +desktop app, `app.export` and `file.exportAs` give these warnings in the reply and the status bar +when automation asked for the export. An `app.export` that returns before the file is written (`background: true`) +gives them in that reply. An export that first asks a question (the one before replacing a file) and that a person +then answers gives none. `document.exportPdf`, `document.pdfSettings` and `pdf.preset.save` refuse a key that PDF doesn't take, `document.exportEps` one that EPS doesn't take and `document.exportDxf` one that DXF doesn't take. Each of them refuses an unknown key inside an option object it takes (`marks`, `bleed`, `compression`, `output`, `advanced`, `security`, `flattener`, `svg`), naming its path: @@ -3167,10 +3196,15 @@ already walks Image Trace. Short agent entry points: would give the set more than 1,000 actions (`the action set file holds more than 1,000 actions`) or a file larger than 8 MiB (`the action set would be larger than 8 MiB`), and then no recording starts. The panel's Create New Action button and menu's New Action… open the `actionNew` dialog, whose Record runs this. -- Actions: `ui.action.record {set?}` starts recording a new action in the chosen set, or the current set when `set` - is left out, and returns `{set, name}`. With no sets, it creates Set 1. The action gets the next available - `Action N` name in that set. The Actions panel's Begin Recording button runs this command. An invalid set or an - existing recording is an error and leaves the sets and recording unchanged, and so is a set where the new action +- Actions: `ui.action.record {set?, action?, after?}` starts recording a new action in the chosen set, or the current + set when `set` is left out, and returns `{set, name}`. With no sets, it creates Set 1. The action gets the next + available `Action N` name in that set. With `action`, it records into the action at `action` in set `set` instead + and returns `{set, action, name}`: `ui.action.stop` puts the recorded steps after step `after` of that action, or + after its last step when `after` is left out, and the steps after them keep whether they are excluded. The Actions + panel's Begin Recording button runs this command with the selected action and its selected step, and with neither + when no action is selected. `action` without `set`, `after` without `action`, an index past the last set, action or + step, an invalid set or an existing recording is an error and leaves the sets and recording unchanged, and so is a + set where the new action would give it more than 1,000 actions or an action set file larger than 8 MiB. While a recording (this one or `ui.action.new`'s) is in progress, a recorded command whose step would give the action more than 10,000 steps, or its set's action set file more than 8 MiB, is an error with the reason (`the action already has 10,000 steps`, `the @@ -3296,6 +3330,20 @@ already walks Image Trace. Short agent entry points: they are excluded, and no step of that action stays selected. A Record Stop dialog open on that step closes, and one open on a later step of the action follows it up. A missing or invalid index is an error, and then nothing changes. Undo does not restore a deleted step. The panel's Delete Selection runs this for the selected step. +- Actions: `ui.action.moveStep {set, action, step, toSet?, toAction?, before}` moves one step, a stop or a command, of + the action at `action` in set `set` into the action at `toAction` in set `toSet` (by default the same set and + action), before the step at index `before` there, or after its last step when `before` is its number of steps. + `before` counts the steps as they are before the move. It returns `{set, action, step, moved}` with the step's new + place. The step keeps its params and whether it is excluded, and the other steps keep theirs. A selected step stays + selected; a moved selected step makes its new action the selected one and its set the current one. A Record Stop + dialog open on a step follows the step, and the steps that the recording in progress adds to either action stay + after the steps that were before them. A step put back just before or just after itself does not move, and + `moved` is `false`. A missing or invalid index, or a move that would give the action more than 10,000 steps or its + set's action set file more than 8 MiB, counting the steps that the recording in progress adds to the set, is an + error, and then nothing changes. Undo does not move the step back. In the Actions panel, dragging a step row moves + the step: a line shows where it goes, before or after the row under the pointer, or first in an action whose name + row it is over (after the last step when the action's steps are hidden), and releasing the button off those rows + leaves the step where it was. - Actions: `ui.action.playbackOptions {speed?, seconds?}` sets how the Actions panel plays actions and returns `{speed, seconds}`. `speed` is `accelerated` (the default: every step at once), `step` (one step at a time, with the window drawn after each step before the next runs) or `pause` (a pause of `seconds` between steps). `seconds` is a @@ -3304,8 +3352,8 @@ already walks Image Trace. Short agent entry points: preferences. The panel menu's Playback Options… opens the `actionPlayback` dialog (`speed`, `seconds`), whose OK runs this. Batch… (`action.batch`) plays every step at once whatever the setting. - Actions: `ui.action.stop {}` ends the recording in progress and keeps its steps, in the action `ui.action.new` made - for it, else in a new action after the last action of its set, and returns `{stopped}`. It also ends an action - playing at Step by Step or Pause For, or one waiting at a stop, whose message box closes: the steps already played + for it or the action `ui.action.record` named, at the place it named, else in a new action after the last action of + its set, and returns `{stopped}`. It also ends an action playing at Step by Step or Pause For, or one waiting at a stop, whose message box closes: the steps already played stay, and the rest do not play. With nothing recording or playing it changes nothing. The panel's Stop Playing/Recording button runs this. - Action sets: `ui.actionSet.delete {sets?: [index], ids?: [id]}` deletes the Actions panel's sets at these indexes @@ -3381,7 +3429,9 @@ already walks Image Trace. Short agent entry points: nothing when it touches none. `selectFills` off leaves the faces out, and `selectStrokes` off leaves the edges out. A click and a marquee run their command on the release, and Escape between the press and the release removes the marquee so that the release runs nothing. The tool does not highlight or select the faces and edges of a Live Paint group that is locked, on a locked layer or on - a locked artboard, or in isolation mode outside the isolated art. + a locked artboard, or in isolation mode outside the isolated art. In the app, the tool's cursor shows what a click + at the pointer selects under these rules: the arrow with a filled square for a face, with a short line for an edge, + and with an x for nothing. It keeps the look it had at the press until the release. The Live Paint Bucket's options (`tool.setOption {tool: "livePaintBucket", values}`; double-clicking the tool opens them, dialog `livePaintBucketOptions`) are `paintFills` (on), `paintStrokes` (off), `highlight` (on), `color` (the highlight color, `#rrggbb` or a layer color's name; `#ff2a2a`) and `width` (the face highlight's width, 1 to 20 screen @@ -4617,7 +4667,7 @@ paper white, 0 %) exports to PDF as a Separation shading, and one that mixes spo inks exports as a DeviceN shading. A gradient that mixes a spot ink with colors written in RGB or Lab is written in process colors, with a warning; an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile. Freeform gradients and dithered fills export to PDF as images in process colors, and Method -above covers Perceptual gradients. +above covers Perceptual gradients and gradients mixed around the hue wheel. ```json {"name":"run_command","arguments":{"command":"paint.editGradient","params":{"stops":[{"offset":0,"swatch":"Ink"},{"offset":1,"swatch":"Ink","tint":20}]}}} @@ -4690,6 +4740,14 @@ tip, has more than 65,536 anchors in its art or in the shapes it paints, has sha or has more than 4,096 anchors once united is listed in `skipped`. `stroke.arrowheads.list` returns each head's `name`, `reach` and `halfWidth`, the `file` path, the `skipped` symbols and any read `error`. +Under automation read roots (see the automation roots section above), the arrowheads file counts as a path the client +did not give. `stroke.arrowheads.list` returns `file` as `null` when the file is outside the read roots, and its +`error` names the file by its file name; the heads, `skipped` and the reason stay. `stroke.arrowheads.edit` and +`stroke.arrowheads.reload` refuse a file outside the read roots with the root-check error, naming the file by its file +name: `edit` then makes no folder or file and neither opens the file nor brings it to the front, and `reload` does not +read it. Inside the read roots, `edit` opens the file under the client's roots. The Stroke panel menu's Edit +Arrowheads… is not confined. + `stroke.set {endArrow: {"custom": name}}` puts a custom head on a stroke. The stroke keeps a copy of the head's art, so the document draws it, saves it and exports it to SVG and PDF the same way without the arrowheads file. `document.inspect` reports such a head as `{"Custom": {name, path}}`, which `stroke.set` takes back unchanged. It @@ -5549,11 +5607,12 @@ the selected artboards (those the Artboard tool has selected, else the active on Artboards panel menu's Fit to Artwork Bounds also passes the selected artboards. A batch passes its `artboard` on to each of their steps that names no `index`, as the step's `index`. When the document a step runs in has no artboard at that index, the step gets that document's last artboard. An `artboard.fitToArt` step that names neither `index` nor -`indices`, while the Artboard tool is chosen with several artboards selected when the step runs, gets those artboards -as its `indices` instead, and the batch's journal entry records them, so a replay of the journal fits the same -artboards. A step's own `index` or `indices` is kept. An action recorded in the Actions panel leaves `index` and -`indices` out of these steps: when the action plays, Fit to Artwork Bounds resizes the artboards the Artboard tool then -has selected (two or more), else the active artboard, and Fit to Selected Art resizes the active artboard. +`indices`, while the Artboard tool is chosen with two or more artboards selected when the step runs, gets those +artboards as its `indices` instead. The batch's journal entry records the `indices` or `index` such a step got, so a +replay of the journal fits the same artboards. A step's own `index` or `indices` is kept. An action recorded in the +Actions panel leaves `index` and `indices` out of these steps: when the action plays, Fit to Artwork Bounds resizes the +artboards the Artboard tool then has selected (two or more), else the active artboard, and Fit to Selected Art resizes +the active artboard. ```json {"name":"run_command","arguments":{"command":"object.align","params":{"horizontal":"left","to":"artboard","artboard":1}}} @@ -6121,7 +6180,10 @@ document. With no document open they fail with "no document open". `document.act the current one. `document.move {from?, to}` reorders open documents the way dragging a document tab along the tab strip does: `from` defaults to the current document, `to` is the destination index, documents between them shift by one, the current document stays current, and each document keeps its own view (#5663). It is an engine command, so headless and -remote `command_list` both list it. +remote `command_list` both list it. `file.close {index}` on a document other than the current one leaves the current +document current, and its tool keeps its state; closing the current document makes the document in the next tab +current, or the one before it when it was the last tab. In the desktop app a modified document comes to the front first, +to ask whether to save it. `window.arrange.tile` (Window › Arrange › Tile) shows every open document in its own pane, edge to edge in the document area, in a grid of as many columns as the square root of the number of documents, rounded up, and fits each document to its pane; with fewer than two documents open it leaves the view and `tiled` as they are. It returns `{tiled, panes}`. @@ -6224,6 +6286,9 @@ with the defaults. them. - `file.newProfiles.reset {name}` deletes the category's file, so the shipped profile applies again, and returns `{name, reset}`. `reset` is false when there was no file. A copy of the profile that is open stays open. +- Under automation roots, `file.newProfiles.edit` needs write and read access to the profile's file and + `file.newProfiles.reset` needs write access. An error names the file whole only inside the read roots, and + otherwise by its file name. The profile is read on every `file.new`, so a replayed journal or a recorded action uses the profile as it is when it runs, as `document.open` reads its file when it runs. A file larger than 64 MiB (VectorCraft's own limit) is not read. @@ -7083,6 +7148,10 @@ color, even one of the same color, and Registration are not spot colors; the spo Color Objects and `objects.spots` counts them; spot swatches no art uses are not listed; with `selectionOnly`, those in the selection), `spotColorNames` and `spotColors` (the spot colors those objects use) and `pathLength` (pt: the total length of the paths, compound paths' pieces included and guides left out, which objects lists as Path Length in the document's units, say for a cut line or an LED strip along the letters); +`brushNames`, `brushes`, `spotObjects`, `patternObjects` and `gradientObjects` leave out hidden objects, objects at an +opacity of 0 and the objects inside a hidden group or layer or one at an opacity of 0, their characters' paints and +colorized images included, and so does `selectionOnly` for an object selected inside such a group or layer, while +`objects` still counts them as paths, groups and the other kinds; `format: "text"` returns the plain-text report Document Info › Save… (`docInfo.save {path?, selectionOnly?, category?}`: only `category` when given, else every category) and the package report write. diff --git a/docs/plugins.md b/docs/plugins.md index 5284dee98f..5f1479748e 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -617,7 +617,7 @@ An **importer** gets the bytes of the file being opened, as they are (not JSON), `paint`, `width` in points, `join` (`"miter"`, `"round"` or `"bevel"`), `cap` (`"butt"`, `"round"` or `"square"`) and `miterLimit`. Paints use the native file format's form: `{"type": "solid", "color", "swatch"?, "tint"?}`, `{"type": "gradient", "gradient": {"kind": "Linear"|"Radial"|"Freeform", "stops": [{offset, color, opacity, - midpoint}], "dither"?, "method"?: "Perceptual"}, "geom"?, "angle", "freeform"?}`, `{"type": "pattern", "pattern", + midpoint}], "dither"?, "method"?: "Perceptual"|"HueClockwise"|"HueCounterclockwise"}, "geom"?, "angle", "freeform"?}`, `{"type": "pattern", "pattern", "xf"?}`. Colours are `{"model": "rgb", r, g, b}`, `{"model": "cmyk", c, m, y, k}`, `{"model": "gray", k}` (ink: 0 white, 1 black) or `{"model": "lab", l, a, b}`; components 0–1 except Lab's. - `effects` (filters): the object's own effects in order, as its effect records: `id` (as `effect.list` lists it, or diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e1a1e13115..32d2b6834b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-13 · **Change:** minor (Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-13 · **Change:** minor (`.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Oversized artboard import update (2026-11-12): Explicit editing-data import retains a single artboard beyond a capped 14,400 pt PDF page (#6865). > @@ -257,7 +257,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Export for Screens, Asset Export, slices, Save for Web | 3 | 85% | anti-aliasing ghost borders (#983); TIFF choices and settings are implemented | 2–4 | estimated | | Print, colour management, separations, flattener | 3 | 80% | print preview fidelity | 2–4 | estimated | | Automation (Actions, Variables, scripting, batch) | 3 | 60% | a scripting surface (Illustrator: JavaScript/ExtendScript), Batch, image and graph variables, dataset import/export | 8–14 | estimated; MCP `add_text` exposes existing vertical type; score and hours unchanged | -| UI chrome (panels, Properties, workspaces, preferences) | 6 | 80% | Properties per context, 3 Preferences options stored but unused (#394, audited 2026-10-30: Open Documents As Tabs, Scratch Disks, legacy vector clipboard), context menus in the panels that have none, accessibility | 13–20 | estimated; floating panels in OS windows of their own on the desktop (#4135), score and hours unchanged; macOS save Format menu implemented (#866), score and hours unchanged; Eyedropper cursor and precise setting checked (#1269), OS visual QA unverified; numeric-field focus and normal text drags regression-tested (#1326); a focus click released more than 1 pt from its press keeps the caret and a tap within 1 pt selects all (#6659); artboard navigation synchronizes the tool selection before destructive actions; status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates (sample widths cached by language/unit/DPI; regression and contributor original-file evidence below; scores/hours unchanged); effect dialogs' colour fields show a swatch that opens the Color Picker (#5365), score and hours unchanged; icon-strip flyouts retain user sizes (#5713); floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), scores and hours unchanged ; interim macOS cursor delivery (#2292), headless coverage only; native validation pending, score and hours unchanged | +| UI chrome (panels, Properties, workspaces, preferences) | 6 | 80% | Properties per context, 2 Preferences options stored but unused (#394, audited 2026-10-30: Scratch Disks, legacy vector clipboard), context menus in the panels that have none, accessibility | 13–20 | estimated; floating panels in OS windows of their own on the desktop (#4135), score and hours unchanged; macOS save Format menu implemented (#866), score and hours unchanged; Eyedropper cursor and precise setting checked (#1269), OS visual QA unverified; numeric-field focus and normal text drags regression-tested (#1326); a focus click released more than 1 pt from its press keeps the caret and a tap within 1 pt selects all (#6659); artboard navigation synchronizes the tool selection before destructive actions; status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates (sample widths cached by language/unit/DPI; regression and contributor original-file evidence below; scores/hours unchanged); effect dialogs' colour fields show a swatch that opens the Color Picker (#5365), score and hours unchanged; icon-strip flyouts retain user sizes (#5713); floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), scores and hours unchanged ; interim macOS cursor delivery (#2292), headless coverage only; native validation pending, score and hours unchanged | | Libraries, Links, Package | 2 | 82% | shared libraries, linked graphics, gradients and patterns as library items (no cloud by design) | 2–3 | estimated | | Generative AI (Text to Vector, Generative Recolor, Shape Fill, Concept to Vector, Prompt to Edit, Rewrite Text) | 2 | 0% | a pluggable provider and the panels; needs an owner decision on models | 30–60 | measured (absent) | | **Feature depth** | **105** | **~75%** | | **~250–420** | | @@ -607,6 +607,7 @@ since 2026-10-01. - **Selected Mirror Repeat handles:** a headless canvas regression creates the default mirror repeat and drags its Top bounding-box handle where the axis crosses it; the repeat grows vertically while its width stays fixed. Existing mirror-axis checks cover center movement and end-handle hit priority. The focused UI mirror tests pass. Scores and hours unchanged. - **Transform effect options (#885):** Effect › Distort & Transform › Transform… has visible Transform Objects, Transform Patterns and Scale Strokes & Effects checkboxes (`distort.transform` params `objects`, `patterns`, `strokes`; files without them draw as before). With Transform Objects off the geometry stays and makes no copies; Scale Strokes & Effects scales stroke weights, dashes and the fills' and strokes' effect distances by the mean scale, and Transform Patterns moves pattern tiles, each copy `k` by the transformation `k` times. Such objects draw, export and expand through the same per-copy art, so the canvas and Expand Appearance agree (engine `tests_transformfx`, effects `tests_transformfx`, the dialog test). A Transform effect in a fill's or stroke's own effects applies the same options to that fill or stroke: its weight and dashes and its pattern follow the transformation, and with copies each copy is an object of its own; the canvas, export, Expand Appearance and Use Preview Bounds use the same art (effects `tests_transformfx`). The effects listed after it in that fill's or stroke's list keep their own distances and apply to the transformed art and to each copy, as an object's later effects do after the object's Transform effect: a Drop Shadow after it keeps its offset, an Offset Path after it offsets by its own distance, and an SVG filter after it keeps its scale and the origin of its user space. With Transform Objects off, the effects before it keep their distances too. Before, Scale Strokes & Effects scaled a fill's or stroke's later effects by the mean scale, so existing documents with such effects draw differently. Effects apply in the order they are listed ([Appearance attributes](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/appearance-attributes-in-illustrator.html)); how the two options treat the effects after a fill's or stroke's own Transform effect is VectorCraft's own rule, following that order (effects `tests::rasterfollow::a_fills_own_transform_leaves_the_shadow_after_it`, `tests::rasterfollow::a_fills_own_transform_leaves_the_offset_after_it`, `tests::rasterfollow::a_fills_own_transform_leaves_the_svg_filter_after_it`, `tests::transformfx::a_fills_own_transform_with_scale_strokes_and_effects_leaves_its_later_effects`; engine `plugins::a_transform_after_a_painted_fill_effect_leaves_the_later_shadow_on_every_paint`). Public reference: [Scale objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-objects.html), [How to apply effects](https://helpx.adobe.com/illustrator/using/effects.html), [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html). Scores and hours unchanged. - **Raster effects before a Transform effect:** effects apply in the order they are listed ([Appearance attributes](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/appearance-attributes-in-illustrator.html)). A Drop Shadow, glow, blur, Feather or pixel filter listed before a Transform effect in the same list (an object's effects, or a fill's or stroke's own) now follows that Transform effect: its sizes scale by the mean scale, and a Drop Shadow's offset turns, reflects and scales with the art. VectorCraft applies this rule with Scale Strokes & Effects on or off. Before, such an effect was drawn at its own distances around the transformed art. The canvas, export, Expand Appearance, Object › Expand, Outline Stroke and the 3D effects use the same values (effects `tests::rasterfollow`; render `a_transform_after_a_drop_shadow_scales_the_shadow_with_the_art`; engine `objexpand::a_shadow_before_a_transform_expands_as_the_canvas_draws_it`, `outlinestroke::a_shadow_before_a_transform_outlines_as_the_canvas_draws_it`). Not yet: a Transform effect that makes copies or moves at random leaves the raster effects before it as they are; a Rasterize effect before a Transform effect keeps its pixel grid and room around the art; the angles and light directions of pixel filters do not turn or reflect with the art. Scores and hours unchanged. +- **Raster effects before a Transform effect past the effect budget:** VectorCraft leaves out a Transform effect whose result would pass its geometry budget of 2 million anchors or 8 million lines drawn, and the art stays where it was. The raster effects listed before that Transform effect now stay with the art too: a Drop Shadow keeps its own offset and blur, and the Transform effects after it that fit still move both. Before, the art stayed while the shadow scaled with the Transform effect it did not take. This is VectorCraft's own rule. It applies to a path's own effects and to its fills' and strokes' own, also when the path is in a group whose geometry effects run after its members' own, on the canvas and in its bounds, in export, Expand Appearance, Object › Expand and Outline Stroke, and a hidden shadow keeps its values once shown (effects `tests::rasterfollow::a_transform_past_the_line_budget_moves_the_art_with_its_shadow`, `tests::rasterfollow::only_transforms_that_ran_move_a_preceding_shadow`, `tests::rasterfollow::a_skipped_item_transform_keeps_its_shadow`, `tests::rasterfollow::the_shape_art_of_a_skipped_transform_keeps_its_shadows`, `tests::rasterfollow::a_members_skipped_transform_keeps_its_shadow_under_its_groups_effects`; render `objectfx::a_shadow_before_a_skipped_transform_reaches_as_far_as_it_is_drawn`, `fx::renderer::tests::a_path_paints_from_the_transforms_that_moved_it`; engine `objexpand::a_shadow_before_a_skipped_transform_expands_with_its_own_offset`). Not yet: the shadow of type, an image, a symbol instance or a group whose art a Transform effect leaves in place past the budget still follows that effect. Scores and hours unchanged. - **Raster effects inside an object or group with a Transform effect:** effects applied to a group affect everything in it ([Appearance attributes](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/appearance-attributes-in-illustrator.html)). How a Transform effect changes the raster effects inside a group or object is VectorCraft's own rule. A group's Transform effect that moves it once now transforms the raster effects of its members, of their fills and strokes, of nested groups and of the art of the linked opacity masks in it, after the members' own Transform effects. A raster effect that a member's own Transform effect with copies or random holds back keeps its value through that effect and still transforms with the group's. VectorCraft applies the same rule to the raster effects of an object's fills and strokes under the object's Transform effect. Sizes scale by the mean scale and a Drop Shadow's offset turns, reflects and scales, with Scale Strokes & Effects on or off. Before, they kept their values, or with Scale Strokes & Effects on scaled by the mean scale with the offset unturned. A group's or object's Transform effect that makes copies or moves at random leaves them as before. The canvas, the redraw region, export, Expand Appearance, Object › Expand and Outline Stroke use the same values (effects `tests::rasterfollow`, `group::tests::a_compound_shapes_transform_turns_its_fills_shadow`; render `a_transform_scales_the_shadows_of_fills_and_members_with_the_art`; engine `objexpand::a_fills_shadow_under_the_objects_transform_expands_as_the_canvas_draws_it`, `objexpand::shadows_under_a_groups_or_an_objects_transform_expand_appearance_as_the_canvas_draws_them`, `outlinestroke::a_strokes_shadow_under_the_objects_transform_outlines_as_the_canvas_draws_it`). Scores and hours unchanged. - **A group's geometry effects after its members' own:** effects applied to a group affect everything in it, and effects apply in the order they are listed ([Appearance attributes](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/appearance-attributes-in-illustrator.html)). Running a group's effects after its members' own is VectorCraft's own rule. The geometry effects of a group or layer (the effects that reshape outlines, such as Distort & Transform, Offset Path and Warp) now reshape what its members draw: the geometry effects of each visible path and compound path in it and of their fills and strokes, and a nested group's own geometry and Pathfinder effects, run first, at any depth. A symbol instance's own geometry effects run after those of its symbol's members in the same way. Before, the group's effects reshaped the members' outlines and the members' own effects ran afterwards: a 100 pt square with its own 10 pt Offset Path in a group with a 50% Transform drew 70 pt wide, and it now draws 60 pt wide. Existing documents with such groups draw differently. The canvas, export, Expand Appearance and the art that Pathfinder operations and compound shapes take from such a group use the same order (effects `group::tests::a_members_own_offset_runs_before_its_groups_scale`, `group::tests::a_members_own_scale_runs_before_its_groups_offset`, `group::tests::a_member_of_a_plain_nested_group_takes_its_own_effects_first`, `group::tests::a_nested_groups_own_effects_run_before_its_groups`, `group::tests::a_nested_groups_pathfinder_runs_before_its_groups_effects`, `group::tests::a_members_fill_effects_run_before_its_groups`, `group::tests::shape_art_of_a_group_applies_its_members_effects_first`, `group::tests::a_symbol_instances_effects_run_after_its_symbols_members_own`, `group::tests::a_baked_group_applies_its_members_effects_first`, `group::tests::a_baked_group_that_keeps_its_type_applies_its_members_effects_first`, `tests::rasterfollow::a_groups_transform_applies_after_its_members_own`; engine `objexpand::a_groups_effects_after_its_members_own_expand_as_the_canvas_draws_them`). Not yet: the own geometry effects of images, symbol instances, paths with a linked opacity mask or a 3D effect, and nested groups with a 3D effect in the group still run after the group's. Scores and hours unchanged. - **Warp Options (#1760):** Effect > Warp and existing Appearance effect links share the fifteen existing styles, original schematic previews, orientation choices and percent Bend/Distortion controls. Focused tests passed for real numeric entry and slider input, Preview/Cancel, immediate Enter/OK, mixed-style edits, target/slot/visibility preservation and Undo/Redo. Each applied style stays unchanged until an explicit Style choice. Original style-menu and live-preview captures were reviewed; their numeric values were supplied programmatically. Public references: [Reshaping with effects](https://helpx.adobe.com/illustrator/using/reshaping-objects-effects.html) and [Using effects](https://helpx.adobe.com/illustrator/using/effects.html). Warp geometry, optional Properties integration and remembered defaults are unchanged; no broader parity claim. @@ -626,6 +627,7 @@ since 2026-10-01. - **Escape in Selection tool drags:** Escape during a Selection tool move or Alt-drag copy, a bounding-box scale or rotation, a marquee, or a corner widget, pie widget or bracket drag cancels it: the art returns to its state at the press, no copy is left, no undo step is added, the release does nothing, and the tool stays chosen. This is VectorCraft's own behavior. Regression tests: `escape_cancels_*` in `select/tests.rs` and `pie.rs`, and `escape_cancels_a_selection_tool_move_copy_scale_or_rotation` in `tests/selectescape.rs`. - **Selection passes through raster effects:** clicks with the Selection, Direct Selection and Group Selection tools (Group Selection's repeated click included), the Selection tool's pointer and marquee, Direct Selection's marquee, pointer and anchor highlight, and Group Selection's marquee (E for enclosed objects included) leave out the area that a drop shadow, a glow, a blur or another raster effect paints beyond an object. A click on a shadow selects the object under it, or nothing over an empty canvas, a repeated Group Selection click there adds the groups of the object under it, and a press on the shadow of a selected object does not move it ([the help page](https://helpx.adobe.com/illustrator/using/selecting-objects.html)). Over a shadow, Direct Selection highlights only the anchors of the object under it, and Group Selection keeps its own pointer and highlights no anchor, as it does everywhere (VectorCraft's own rule). No setting changes this. This covers paths, groups, type, symbol instances and images. Regression tests: `crates/engine/src/tests/select_effects.rs`. - **Global Edit: Shift-click leaves a match out:** while Global Edit is on, a Shift-click with the Selection tool on a highlighted match, or on an object inside a matched group, leaves that match out (`select.globalEditExclude`): it is no longer highlighted and later edits leave it as it is; the object the edit started from stays, and Global Edit ends when fewer than two matches are left ([Update assets quickly with Global Edit](https://helpx.adobe.com/ph_fil/illustrator/how-to/global-editing-sensei.html)). Regression tests: `a_shift_click_*`, `an_object_left_out_*`, `a_group_left_out_*` and `leaving_out_all_but_one_*` in `crates/engine/src/tests/globaledit.rs`. +- **Global Edit leaves out groups holding type or images:** Select › Start Global Edit on a group that holds type or an image, at any depth, refuses to start, and such a group is not taken as a match, as Global Edit does not take images or text ([Edit similar objects globally](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-similar-objects.html)). The menu item checks only that the selection is a group; starting checks its contents. Regression test for a group holding type: `global_edit_needs_one_supported_object` in `crates/engine/src/tests/globaledit.rs`. - **Global Edit Options in the Control bar:** while Select › Start Global Edit can run, the Control bar shows a Global Edit Options dropdown that opens the same options as the Properties panel's (Match: Appearance, Size; On Artboards; Include Objects On Canvas; Result(s)); both set the same options. The dropdown is off while Global Edit is on; it sits after Recolor Artwork, ahead of the X/Y/W/H fields ([Edit similar objects globally](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-similar-objects.html)). Regression test: `the_control_bar_shows_the_global_edit_options` in `crates/ui-egui/src/chrome/tests.rs`. - **Global Edit's enabled check on large paths:** the check that decides whether Select › Start Global Edit can run on the selected path, compound path or symbol instance (which the Control bar makes every frame) measures the box of its anchors and handles instead of building and normalizing a copy of every anchor, with the same answer. On a 200,000-anchor path the check takes 0.7 ms instead of 2.2 to 3.0 ms. Regression tests: `support_*` in `crates/engine/src/cmd/globaledit.rs`. - **Control bar's inline X, Y, W and H fields fit the bar:** the Control bar shows the inline X, Y, W and H fields only when all four, their labels as drawn in the current language and the W/H link fit inside the bar's margin; otherwise it shows the Transform link alone. This is VectorCraft's own layout rule. Regression test: `the_control_bar_shows_the_inline_transform_fields_only_when_they_fit` in `crates/ui-egui/src/chrome/tests.rs`. @@ -702,6 +704,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Window › Arrange › Float in Window, Float All in Windows and Cascade (G7):** documents float in windows of their own, out of the tab strip ([public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html)). Float in Window (`window.arrange.floatInWindow`) floats the current document, Float All in Windows (`window.arrange.floatAllInWindows`) every tabbed one, and Cascade (`window.arrange.cascade`) floats every document and stacks the windows from the upper left to the lower right ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)). On the desktop each window is an OS window; on the web and on Wayland it is a window inside the app's window. The window of the current document holds the canvas; the others draw their documents as Tile's panes do, and a press in one makes its document the current one. Closing a window closes its document, asking to save unsaved changes. Consolidate All Windows brings every document back under the tabs, and Tile brings them back into its grid. The cascade's 30 pt step, the windows' size and when the items are enabled (Cascade with two documents or more, Float in Window for a tabbed current document, Float All in Windows while a document is tabbed, Consolidate All Windows while documents are tiled or floating) are VectorCraft's own. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. - **Dragging a document tab out and a document window back (G7):** a document tab dragged more than 24 pt above or below the tab strip floats its document in a window under the pointer, and a document window dragged onto the tab strip goes back under the tabs ([public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html)). A window inside the app's window is dragged by its title bar; an OS window by the document's tab at its top, and the window follows the pointer. The 24 pt distance and the tab at the top of an OS window are VectorCraft's own. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. - **Reordering document tabs (G7, #5663):** a document tab dragged along the tab strip moves its document among the others ([public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html)); a line marks the gap it goes in. The current document stays current, each document keeps its own zoom, centre and artboard, the views Window › New Window opened move with their document, and Window › Next/Previous Document follow the new order. `document.move` (`{from?, to}`) does the same from MCP, the control channel and recordings. `crates/ui-egui/src/tests/tab_reorder.rs`, `crates/engine/src/tests/document_move.rs`. +- **Closing a background document tab:** closing a tab other than the current one (`file.close {index}`) keeps the current document current, and its tool keeps its state; closing the current tab still makes its neighbor current. `crates/engine/src/tests/document_close.rs`. - **Export and Import Preferences (#6435):** an optional VectorCraft feature. The Preferences dialog's Export Preferences… saves the applied preferences to a JSON file (`prefs.export`; the web build downloads it), and Import Preferences… applies such a file (`prefs.import`). The file leaves out the folder preferences. The import checks every value first and changes nothing on an error; it keeps the open document's units and records no undo step. The file format is VectorCraft's own. Tests: `crates/engine/src/tests/prefs_file.rs`, `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Preferences › User Interface › Open Documents As Tabs (G7, #394):** checked by default, documents open under tabs in one document window ([public source](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/workspace-overview.html)). With the box cleared, each document opened or created afterwards opens in a floating window of its own, at the next cascade place, as Float in Window floats it; documents already open stay where they are, and checking the box again leaves floating documents in their windows. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. - **Preferences search:** a Search Preferences field above the category list has the keyboard focus when the dialog opens, and Cmd/Ctrl+F gives it back; typing lists the settings it finds, and choosing one shows its category, as the [help page](https://helpx.adobe.com/illustrator/desktop/get-started/preferences-and-settings/set-app-preferences.html) describes. VectorCraft's own rules: the field matches a setting's label, section or category, ignoring case, in the interface language or in English; the list replaces the categories while the field has text and shows every match, or "No settings found"; the chosen setting's row is highlighted and scrolled into view; Escape in the field with text clears it, and Escape in the empty field closes the dialog. The dialog's `__search` field (`ui.dialog.set`) holds the text. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. @@ -710,9 +713,10 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Document Setup modal handoff:** Document Setup → Edit Artboards applies valid settings, closes the dialog and activates the Artboard tool. Pointer-click tests cover successful handoff, invalid settings, OK, Cancel and Undo in `dialogs/document_setup.rs`. - **Document Setup › Color:** a Color tab shows the document color mode (RGB Color or CMYK Color), a Convert to CMYK or Convert to RGB box for a mode change (cleared: the colors keep their numbers), and the RGB and CMYK profiles assigned to the document, with a working-space entry for none. OK runs `edit.assignProfile` and then `file.documentColorMode` with the dialog's other changes in one `command.batch`, and the document's changes are one undo step. An unchanged Color tab adds no color commands, and Cancel, or OK with nothing changed, records no undo step. A Color tab field with a value of the wrong kind is an error, and the dialog stays open. The tab is VectorCraft's own layout; File › Document Color Mode and Edit › Assign Profile… stay as they are. Tests in `dialogs/document_setup.rs`. +- **Out-of-gamut warning after a profile change:** the out-of-gamut warning and its closest-color correction in the Color panel and Color Picker ([the help page](https://helpx.adobe.com/illustrator/using/adjusting-colors.html)) check the color against the document's assigned CMYK profile, else the working CMYK space, and update when Edit › Assign Profile… or Edit › Color Settings… changes that space or a loaded profile changes, without a change of color. Which CMYK space the warning uses is VectorCraft's own rule. Tests: `gamut_warning_follows_a_profile_change` and `gamut_warning_follows_a_profile_loaded_again` in `dialogs/color_picker/tests.rs`. - **Assign Profile and the working spaces:** Edit › Assign Profile… tags the document and leaves the working spaces of Edit › Color Settings… as they are, in Color Settings, the Separations panel and the settings saved for the next start. Colors show and convert through the profiles assigned; a change in Color Settings keeps the profiles the document in front is assigned in use, and removing an assigned profile in use puts the working space back in its place. The profiles in use follow the document in front: a new, opened or reverted document, a switch to another tab, a close, Undo and Redo of Assign Profile, a failed batch, each step of a batch, Export All Open and the update of placed documents put that document's profiles in use, and the working spaces where it is assigned none or no document is open. View › Proof Setup › Working CMYK simulates the working CMYK space of Color Settings in Proof Colors and Separations Preview, also in a document assigned another CMYK profile. Public references: [Changing the color profile for a document and About color working spaces](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=150) and [Soft-proof presets](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=134). Tests in `engine/tests/color_settings.rs`. - **New Document's More Settings and Save Preset:** More Settings opens a pop-up over New Document with only Number of Artboards, the artboard layout, Change to Right-to-Left Layout, Spacing and Columns; Done, Escape or a click outside closes it and keeps the values. Save Preset turns the top of Preset Details into a Save Document Preset heading with the preset's name, Cancel and Save, and hides the document's name, Close and Create until the preset is saved or canceled; nothing in that mode creates a document. Save Preset's default name is the first "Preset N" no saved preset has. VectorCraft's own layout. Harness tests in `dialogs/new_document.rs` cover both. -- **New Document profiles:** each built-in category's presets start documents from that category's profile, a native document holding the starting swatches, graphic styles, brushes, symbols and other assets, the ruler and Document Setup options and the print settings ([Create a custom new document profile](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/start-a-new-file/create-a-custom-new-document-profile.html)). New Document's Manage Profiles pop-up opens a profile to edit and resets one to the shipped profile (`file.newProfiles`, `file.newProfiles.edit`, `file.newProfiles.reset`; `file.new {profile}`). The profiles live in VectorCraft's own `New Document Profiles` folder next to the preferences; a profile that cannot be read or is larger than 64 MiB leaves the defaults and is reported. Tests: `tests::newdoc::an_edited_profile_starts_the_documents_of_its_category`, `the_profile_follows_the_preset_access_and_reset`, `a_damaged_or_oversized_profile_leaves_the_defaults_and_is_reported`, `profile_names_are_checked_and_editing_needs_the_folder`, `dialogs::new_document::tests::manage_profiles_edits_and_resets_the_profiles`. +- **New Document profiles:** each built-in category's presets start documents from that category's profile, a native document holding the starting swatches, graphic styles, brushes, symbols and other assets, the ruler and Document Setup options and the print settings ([Create a custom new document profile](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/start-a-new-file/create-a-custom-new-document-profile.html)). New Document's Manage Profiles pop-up opens a profile to edit and resets one to the shipped profile (`file.newProfiles`, `file.newProfiles.edit`, `file.newProfiles.reset`; `file.new {profile}`). The profiles live in VectorCraft's own `New Document Profiles` folder next to the preferences; a profile that cannot be read or is larger than 64 MiB leaves the defaults and is reported. Tests: `tests::newdoc::an_edited_profile_starts_the_documents_of_its_category`, `the_profile_follows_the_preset_access_and_reset`, `profile_errors_name_the_file_by_its_name_outside_the_read_roots`, `a_damaged_or_oversized_profile_leaves_the_defaults_and_is_reported`, `profile_names_are_checked_and_editing_needs_the_folder`, `dialogs::new_document::tests::manage_profiles_edits_and_resets_the_profiles`. - **Control bar with the Artboard tool:** while the Artboard tool is in use, the Control bar shows the active artboard's controls in place of the object controls: Preset, Portrait and Landscape, New Artboard, Delete Artboard, the Name field, Artboard Options, Rearrange All Artboards, the Transform link, Move and Scale Artwork with Artboard and, while the bar has room, the reference point with X and Y, and W and H with the Constrain Width and Height Proportions link. Each runs the command its Properties or Transform panel counterpart runs (`artboard.setProps`, `artboard.new`, `artboard.delete`, `tool.options {tool: "artboard"}`), and the reference point is the one the Transform panel uses. In an 800-point window the controls up to the Transform link fit, Move and Scale Artwork with Artboard show as their boxes alone with their names in tooltips, and the link opens the Transform panel with the artboard's position and size. Pointer and key tests in `panels/artboards.rs` cover the controls, W about the reference point, the orientation and the name. Public reference: [Using multiple artboards](https://web.archive.org/web/20210925094818/https://helpx.adobe.com/illustrator/using/using-multiple-artboards.html) (archived copy). - **Names of new and renamed artboards, brushes and patterns:** `artboard.new` and `artboard.setProps` trim the white space around the name they are given, as the Artboards panel's rename does, and a blank name gives the artboard its default name, Artboard N for the Nth artboard. `brush.new`, `brush.duplicate`, `brush.options`, `object.pattern.make`, `object.pattern.saveCopy` and `pattern.options` trim the name as the Brush Options dialog and the Pattern Options panel do, and compare the trimmed name with the names there are; a blank name gives the name each command gives when there is none, and Brush Options and Pattern Options keep the name. Tests in `tests/panelcmds.rs`, `tests/brushsym.rs` and `tests/pattern.rs` cover each command. Public references: [Using multiple artboards](https://web.archive.org/web/20210925094818/https://helpx.adobe.com/illustrator/using/using-multiple-artboards.html), [Brushes](https://web.archive.org/web/20251018101754/https://helpx.adobe.com/illustrator/using/brushes.html) and [Create and edit patterns](https://web.archive.org/web/20211031180358/https://helpx.adobe.com/illustrator/using/create-edit-patterns.html) (archived copies). - **Pattern names and swatch names:** `pattern.options` refuses a new name that another pattern, a swatch or a color group has. It takes a name that only the pattern's own swatches have. The reference page does not say what happens when the new name is taken; the refusal follows VectorCraft's rule that swatches and color groups share one namespace (`Document::swatch_name_taken`), which `swatch.new` and `swatch.edit` also follow. A rename gives the new name only to the pattern's swatches that had the old one; any other swatch with the old name keeps it, and art linked to that swatch stays linked. `object.pattern.make` and `object.pattern.saveCopy` number a color group's name as they number a swatch's. Tests in `tests/pattern.rs` cover each command. Public reference: [Create and edit patterns](https://web.archive.org/web/20211031180358/https://helpx.adobe.com/illustrator/using/create-edit-patterns.html) (archived copy). @@ -748,6 +752,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Actions panel menu: Load Actions… also reads action sets saved as `.aia` files ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html); `actionSet.read`, `ui.actionSet.load`). VectorCraft's own rules: the set comes in with all its actions. A step with a label and no recorded values comes in as the one menu command with the step's label, when that command is directly in a top menu, is what its menu bar item runs with no values and opens no dialog. A step that is off in the file stays excluded from playback. The other steps, recorded menu items included, are left out, and the status bar says how many. - Actions panel: the panel menu's Action Options… renames the selected action and keeps its steps ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html): the menu item opens a dialog that renames the action or gives it a function key and color; `ui.action.options`). It also sets the action's function key and color. - Actions panel: Create New Action (bottom bar) and the panel menu's New Action… ask for the new action's name, set, function key and color, and Record adds the action and starts recording into it ([Create new actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/record-actions.html): the New Action dialog takes the action's name and the set it goes in; `ui.action.new`, `ui.action.play`). The function key (F1 to F15, with Ctrl or Command and Shift) plays the action. An action's function key plays the action even when a command has the same shortcut, and the command keeps it. VectorCraft's own rules, which the page does not cover: when several actions have the same key the first in panel order plays; a copied action has no key; New Action does not open while an action is recording. The color is kept with the action for Button Mode, which VectorCraft does not have yet. + - Actions panel: with an action selected, Begin Recording adds the commands recorded to that action, after its selected step or at its end, and a step dragged within its action or to another action goes where a highlighted line shows when the button is released ([the help page](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/add-commands-to-actions.html); `ui.action.record`, `ui.action.moveStep`). VectorCraft's own rules, which the page does not cover: with no action selected Begin Recording adds a new action; a step can go into an empty action or an action in another set; a release off the actions' rows leaves the step where it was; a moved step keeps whether it is excluded; Undo does not move it back. - Actions panel (record/playback, persisted), generic parameter dialogs for every "…" command. - Actions panel: the current set is kept with the UI preferences, so after a restart a recording goes into the set that was current, not into the first set. With no set current, Begin Recording records into the first set and makes it current. - Actions panel: expand an action to show its recorded steps, then clear a step's checkmark to keep it in the action but skip it during playback. The action and set checkmarks include or exclude all their steps; a mixed checkmark includes all. Alt/Option-clicking a step checkmark keeps that step as it was and applies the opposite inclusion state to the other steps in its action. This follows the public [Exclude commands from an action](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/exclude-commands-from-actions.html) guide; the scope of the mixed-state and Alt-click behavior is VectorCraft's design. The exclusion survives UI restart, action duplication, and `.vcactions` save/load. Existing version 1 action set files load with every step included. @@ -805,6 +810,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Linked-file and font-file searches under `--automation-read-root`: `links.findFiles` and `text.findFontFiles` replies, also later polls and stops of a search another client started, leave out the files found, a link's saved path and the folder searched outside the caller's read roots, and a failed search gives its reason without the path; `image.info` gives `link: null` for a linked file outside them; `text.addFontFiles` gives `folder: null` and the copies' file names when the Fonts folder is outside them. `crates/engine/src/tests/linkfiles.rs`, `crates/engine/src/tests/fontfiles.rs`, `crates/engine/tests/font_folder.rs`. - Swatch, brush, symbol and graphic style library lists under `--automation-read-root`: every library stays listed, the paths of library files and the user library folder outside the read roots are `null`, a library loaded from outside them is listed and found as `loaded/` and keeps that id for the session unless a library loaded later without a file shows that id itself, which moves it to the next free `loaded/ (N)`, and the app's own list is not changed. `crates/engine/src/tests/library_roots.rs`. - Preferences commands under `--automation-read-root`: `prefs.get`, `prefs.list`, `prefs.set` and `prefs.reset` show folder preferences outside the read roots as `null` and leave out an export preset's folder outside them, and the preferences are not changed. `crates/engine/src/tests/prefs_roots.rs`. + - Custom arrowheads under `--automation-read-root`: `stroke.arrowheads.list` gives `file` as `null` for an arrowheads file outside the read roots and names it by its file name in `error`, and `stroke.arrowheads.edit` and `stroke.arrowheads.reload` refuse such a file before anything is made, opened, brought to the front or read; inside the roots `edit` opens the file under the client's roots. `crates/engine/src/tests/arrowheads.rs` (`an_agent_outside_the_arrowheads_files_folder_sees_its_file_name_alone_and_cannot_reload_it`, `an_agent_edits_the_arrowheads_file_only_inside_its_read_roots`). - Plug-in, recovery and script report replies under `--automation-read-root`: `plugin.list`, `plugin.info` and `plugin.safeMode` name the plug-in folder, failed files, plug-in sources and disabled plug-ins' files outside the read roots by file name or `null`, `file.recovery.*` leave out a document's original file and the recovery folder outside them, and `ui.inspect`'s `scriptReport` names files a run wrote outside them by file name. `crates/engine/src/tests/plugins.rs` (`plugin_list_leaves_out_paths_outside_the_read_root`), `crates/engine/src/tests/recovery.rs` (`recovery_replies_leave_out_paths_outside_the_read_root`), `crates/ui-egui/src/tests/automation.rs` (`ui_inspect_script_report_leaves_out_files_outside_the_read_root`). - Scripts: `alert`, `confirm` and `prompt` open dialogs during a run, each with a Stop button that ends the run and puts every document back. In the app the run waits at the call for the person's answer; a run over MCP or the command line takes its answers in order from `script.run`'s `answers`, and the report lists each dialog with its answer. `crates/engine/src/tests/script_dialogs.rs`, `crates/ui-egui/src/tests/script_dialogs.rs`. - Parameter keys: the engine refuses a key that a command's params description doesn't name before the command runs, in every build and for every caller, including the app's own calls, the commands a command runs and the steps of `command.batch` and `action.batch`. An action recorded by an older version still plays from the Actions panel and the Batch dialog (`Session::replay`). `crates/engine/tests/it/param_keys.rs`. @@ -830,11 +836,12 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Window › SVG Interactivity attaches JavaScript to the selected objects' events (`onclick`, `onmouseover` and 17 more) and links JavaScript files to the document (Link JavaScript Files…); SVG export writes the events as event attributes and the files as `