diff --git a/.github/workflows/freebsd.yml b/.github/workflows/freebsd.yml index 007fcfec09..c74a3e83ab 100644 --- a/.github/workflows/freebsd.yml +++ b/.github/workflows/freebsd.yml @@ -31,3 +31,8 @@ jobs: require-craft-fonts: true craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 run-package-check: true + # The test builds of this workspace's largest crates (engine, ui-egui) need more than the + # VM's 12 GB when two compile at once: the build was killed (exit 137) every night with + # four jobs and again with two. One rustc at a time; it still uses every core. + cargo-build-extra-args: "-j 1" + cargo-test-extra-args: "-j 1" diff --git a/Cargo.lock b/Cargo.lock index f3e85a08a7..32fcfc62ad 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1043,6 +1043,17 @@ dependencies = [ "serde_json", ] +[[package]] +name = "craft-metafile" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2#6d620e971e820b517b11a99cad040ebac670e1e2" +dependencies = [ + "encoding_rs", + "image", + "kurbo 0.13.1", + "thiserror 2.0.21", +] + [[package]] name = "craft-pdf" version = "0.1.0" @@ -6681,6 +6692,7 @@ dependencies = [ name = "vectorcraft-metafile" version = "0.24.1" dependencies = [ + "craft-metafile", "image", "kurbo 0.13.1", "vectorcraft-brush", diff --git a/Cargo.toml b/Cargo.toml index c7856d589e..610e2b462c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,6 +31,8 @@ craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2" } # DXF tags, reader and writer (craft-libs#778, #926, #927). craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2" } +# WMF, EMF and EMF+ reader (craft-libs#778). +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2" } craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", features = ["egui"] } # internal vectorcraft-geom = { path = "crates/geom" } diff --git a/ROADMAP.md b/ROADMAP.md index dabed3eb94..283d7d7dff 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -129,6 +129,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-05: Window › Toolbars › Keep Tools Beside the Canvas, off by default, docks the Tools panel between left-side panels and the canvas instead of at the window's left edge, and the canvas's left edge then also docks a floating Tools panel (`window.toolsBesideCanvas`, #5395). Workspaces keep the setting; workspaces saved without it keep Tools at the window's edge. An optional VectorCraft layout choice; headline numbers unchanged. - 2026-11-12: Stencil Bridges in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): strips of a set width are cut out of the selected art so that every island of a stencil cut from it (the inside of an O, a hole in a shape) stays attached to the sheet, by the shortest crossings first, vertical, horizontal or the shortest among 12 directions 15° apart, with up to 16 bridges per island; type is measured by its glyph outlines and stays type, and the original goes to a hidden layer or is replaced. One undo step (`addon.cutting.bridges`). A VectorCraft addition: headline numbers unchanged. - 2026-11-13: Banner Hems and Grommets in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): on the chosen sides of the selected art's bounds, or of each artboard, a hem line at a set depth inside the edge and grommet marks (a circle with a cross) at a set inset, one at each end of a side and the rest spread evenly at most a set spacing apart, stroked in a chosen swatch; a dialog with Preview, one undo step (`addon.cutting.banner`). A VectorCraft addition: headline numbers unchanged. +- 2026-11-14: Nest Shapes in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): the selected objects move close together onto an artboard, a sheet of a set size or a roll of a set width, packed by their bounding boxes with a margin inside the edges and a spacing between them, optionally turning objects 90° to fit; objects that do not fit go in a column beside the sheet; a dialog with Preview, one undo step (`addon.cutting.nest`). A VectorCraft addition: headline numbers unchanged. - 2026-11-05: Release Type on a Path joins the Type Tools add-on (Object › Plug-ins › Type Tools): each selected type on a path splits into point type with the same text and attributes, on one straight line starting where its first character sat, and the plain path it was set on, with its exact shape and place in the stacking order and no paint; or keeps only the path or only the text, optionally leaving the original. A dialog with Preview, one undo step (`addon.type.releasePath`, #5532). A VectorCraft addition: headline numbers unchanged. - 2026-11-04: New Document: the units chosen in Preset Details now belong to the chosen document, as the pane's options are listed for the selected preset; the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units, so switching between inches and millimetres no longer restyles every recent template. Scores and estimates unchanged. - 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged. diff --git a/apps/vectorcraft-web/src/locks.rs b/apps/vectorcraft-web/src/locks.rs index 7eb2e6cdb7..dffd87868a 100644 --- a/apps/vectorcraft-web/src/locks.rs +++ b/apps/vectorcraft-web/src/locks.rs @@ -8,23 +8,40 @@ //! Pages that aren't secure (plain `http://` other than localhost) and older browsers have none: //! heartbeats alone decide there. +#[cfg(target_arch = "wasm32")] use std::cell::RefCell; +#[cfg(target_arch = "wasm32")] use std::collections::{BTreeMap, BTreeSet}; +#[cfg(target_arch = "wasm32")] use std::sync::{Arc, Mutex}; +#[cfg(target_arch = "wasm32")] use js_sys::{Function, Promise, Reflect}; +#[cfg(target_arch = "wasm32")] use vectorcraft_engine::cmd::recovery::Hold; +#[cfg(target_arch = "wasm32")] use wasm_bindgen::JsCast as _; +#[cfg(target_arch = "wasm32")] use wasm_bindgen::JsValue; +#[cfg(target_arch = "wasm32")] use wasm_bindgen::closure::Closure; /// How often the snapshot of the locks held is refreshed (ms). +#[cfg(target_arch = "wasm32")] const REFRESH_MS: i32 = 10_000; /// How old a snapshot may be and still be trusted (ms). A lock asked for after the snapshot was /// taken comes with a heartbeat, which stays fresh for at least three minutes, so anything under /// that is safe; an older snapshot counts every area as held. const FRESH_MS: f64 = 60_000.0; +/// Whether a snapshot asked for at `asked` can still be trusted at `now`, both in ms on +/// [`vectorcraft_ui_egui::now_ms`]'s clock: it is at most [`FRESH_MS`] old, and not stamped later +/// than `now`. +fn trusted(asked: f64, now: f64) -> bool { + (0.0..=FRESH_MS).contains(&(now - asked)) +} + +#[cfg(target_arch = "wasm32")] thread_local! { /// What releases each lock this tab holds, by name: it resolves the promise the lock is held /// by (wasm runs on one thread). @@ -32,26 +49,31 @@ thread_local! { } /// The locks of the page, named ``. +#[cfg(target_arch = "wasm32")] #[derive(Clone)] pub struct WebLocks { prefix: &'static str, - /// The areas whose locks were held at the last snapshot, and when it was asked for (ms since - /// the epoch). `navigator.locks.query()` is asynchronous, so the snapshot is refreshed every + /// The areas whose locks were held at the last snapshot, and when it was asked for (ms on + /// [`vectorcraft_ui_egui::now_ms`]'s monotonic clock, which a change to the system clock does + /// not move). `navigator.locks.query()` is asynchronous, so the snapshot is refreshed every /// [`REFRESH_MS`] and read from here. seen: Arc)>>, } /// `navigator.locks`, if the browser has it here. +#[cfg(target_arch = "wasm32")] fn manager() -> Option { let locks = Reflect::get(&web_sys::window()?.navigator(), &"locks".into()).ok()?; locks.is_object().then_some(locks) } /// Method `name` of `obj`. +#[cfg(target_arch = "wasm32")] fn method(obj: &JsValue, name: &str) -> Option { Reflect::get(obj, &name.into()).ok()?.dyn_into().ok() } +#[cfg(target_arch = "wasm32")] impl WebLocks { /// The page's Web Locks with a first snapshot of them, kept fresh from then on; `None` when /// the browser has none or won't say which are held (heartbeats alone decide then). @@ -75,7 +97,7 @@ impl WebLocks { /// Take a new snapshot of the locks held. async fn refresh(&self) -> Option<()> { let m = manager()?; - let asked = js_sys::Date::now(); + let asked = vectorcraft_ui_egui::now_ms(); let query: Promise = method(&m, "query")?.call0(&m).ok()?.dyn_into().ok()?; let snapshot = wasm_bindgen_futures::JsFuture::from(query).await.ok()?; let held = js_sys::Array::from(&Reflect::get(&snapshot, &"held".into()).ok()?); @@ -91,7 +113,7 @@ impl WebLocks { /// Does a tab hold `area`'s lock? Yes when the last snapshot is too old to tell. pub fn held(&self, area: &str) -> bool { let seen = self.seen.lock().unwrap_or_else(|e| e.into_inner()); - js_sys::Date::now() - seen.0 > FRESH_MS || seen.1.contains(area) + !trusted(seen.0, vectorcraft_ui_egui::now_ms()) || seen.1.contains(area) } /// Hold `area`'s lock until the returned hold is dropped (or the page goes). @@ -110,8 +132,10 @@ impl WebLocks { } /// A lock this tab holds (by name), released when dropped. +#[cfg(target_arch = "wasm32")] struct LockHold(String); +#[cfg(target_arch = "wasm32")] impl Drop for LockHold { fn drop(&mut self) { if let Some(resolve) = RELEASE.with(|r| r.borrow_mut().remove(&self.0)) { @@ -120,3 +144,24 @@ impl Drop for LockHold { } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_snapshot_is_trusted_for_a_minute() { + assert!(trusted(1_000.0, 1_000.0)); + assert!(trusted(1_000.0, 1_000.0 + FRESH_MS)); + assert!(!trusted(1_000.0, 1_001.0 + FRESH_MS)); + // Before the first snapshot every area counts as held. + assert!(!trusted(f64::NEG_INFINITY, 0.0)); + } + + #[test] + fn a_snapshot_stamped_later_than_now_is_not_trusted() { + // A clock that went back reads an old snapshot as taken in the future. + assert!(!trusted(5_000_000.0, 1_000.0)); + assert!(!trusted(1_001.0, 1_000.0)); + } +} diff --git a/apps/vectorcraft-web/src/main.rs b/apps/vectorcraft-web/src/main.rs index 3808c281f9..457d8d4640 100644 --- a/apps/vectorcraft-web/src/main.rs +++ b/apps/vectorcraft-web/src/main.rs @@ -25,7 +25,7 @@ mod api; mod fonts; #[cfg(any(target_arch = "wasm32", test))] mod keys; -#[cfg(target_arch = "wasm32")] +#[cfg(any(target_arch = "wasm32", test))] mod locks; #[cfg(any(target_arch = "wasm32", test))] mod pencil; diff --git a/apps/vectorcraft/src/clipboard.rs b/apps/vectorcraft/src/clipboard.rs index 17b9327956..ec6256a114 100644 --- a/apps/vectorcraft/src/clipboard.rs +++ b/apps/vectorcraft/src/clipboard.rs @@ -11,13 +11,14 @@ //! 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: -//! 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 +//! Copy offers SVG (`image/svg+xml`), PNG (`image/png`) and text together, and Paste reads copied +//! files (`text/uri-list`), 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. //! - Everywhere: files copied in a file manager paste as the first one that is art (SVG, PDF, EPS, -//! a metafile or a bitmap), before the clipboard's other formats (the files' paths as text). +//! a metafile or a bitmap), before the clipboard's other formats (the files' paths as text). A +//! file of more than 64 MiB is skipped before it is read. use std::io::{Cursor, Read}; use std::path::PathBuf; @@ -144,9 +145,18 @@ fn dib_image(dib: &[u8]) -> Option { Some(img) } +/// The most bytes a paste takes from another app (untrusted data), VectorCraft's own limit: a copied +/// file of more is skipped, and on Wayland a read of more fails. +const MAX_BYTES: usize = 64 << 20; + /// The first of `paths` (files copied in a file manager) that pastes as one of `mimes`, read -/// whole. Only its first bytes are read to tell, so other files cost little. +/// whole, at most [`MAX_BYTES`]. Only its first bytes are read to tell, so other files cost little. fn copied_file(paths: Vec, mimes: &[&'static str]) -> Option { + copied_file_within(paths, mimes, MAX_BYTES) +} + +/// [`copied_file`] with a file of more than `limit` bytes skipped. +fn copied_file_within(paths: Vec, mimes: &[&'static str], limit: usize) -> Option { paths.into_iter().find_map(|path| { // text/uri-list lines end in CRLF (RFC 2483), but arboard splits them on LF only. let path = match path.to_str() { @@ -164,14 +174,108 @@ fn copied_file(paths: Vec, mimes: &[&'static str]) -> Option { if !std::fs::metadata(&path).ok()?.is_file() { return None; } + let mut file = std::fs::File::open(&path).ok()?; + // The file opened may not be the one looked at: its size is checked before any read. + let meta = file.metadata().ok()?; + if !meta.is_file() || meta.len() > limit as u64 { + return None; + } let mut head = Vec::with_capacity(FILE_HEAD); - std::fs::File::open(&path).ok()?.take(FILE_HEAD as u64).read_to_end(&mut head).ok()?; + (&mut file).take(FILE_HEAD as u64).read_to_end(&mut head).ok()?; let mime = file_flavour(&path.to_string_lossy(), &head, mimes)?; - let data = std::fs::read(&path).ok()?; + let data = read_rest(file, head, limit)?; (!data.is_empty()).then_some(Flavour { mime, data }) }) } +/// `data` (the first bytes read of `file`) followed by the rest of `file`, or `None` when they come +/// to more than `limit` bytes, as when the file grew after its size was checked. At most one byte +/// past `limit` is read. +fn read_rest(file: impl Read, mut data: Vec, limit: usize) -> Option> { + let more = (limit + 1).saturating_sub(data.len()); + file.take(more as u64).read_to_end(&mut data).ok()?; + (data.len() <= limit).then_some(data) +} + +/// The most URIs a copied file list may hold, VectorCraft's own limit: a longer list (untrusted +/// data) names no files. +const MAX_URIS: usize = 1024; + +/// The local files a `text/uri-list` names, in order ([`file_uri_path`]). Each line holds one URI +/// and a line that starts with `#` is a comment (RFC 2483, section 5); lines end in CRLF or LF. +/// Lines that are not UTF-8 and URIs that don't name a local file are skipped. A list of more than +/// [`MAX_URIS`] URIs names none. +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +fn uri_list_paths(list: &[u8]) -> Vec { + let uris: Vec<&[u8]> = list + .split(|&b| b == b'\n') + .map(|line| line.strip_suffix(b"\r").unwrap_or(line)) + .filter(|line| !line.is_empty() && !line.starts_with(b"#")) + .take(MAX_URIS + 1) + .collect(); + if uris.len() > MAX_URIS { + return vec![]; + } + uris.into_iter().filter_map(|uri| file_uri_path(std::str::from_utf8(uri).ok()?)).collect() +} + +/// The local files GNOME Files' `x-special/gnome-copied-files` names: a first line of `copy` or +/// `cut`, then one URI a line, read as [`uri_list_paths`] reads them. A paste places the files' +/// art either way and leaves the files where they are. No files when the first line is neither. +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +fn gnome_copied_paths(list: &[u8]) -> Vec { + let (action, uris) = match list.iter().position(|&b| b == b'\n') { + Some(end) => (list.get(..end).unwrap_or_default(), list.get(end + 1..).unwrap_or_default()), + None => (list, &[][..]), + }; + match action.strip_suffix(b"\r").unwrap_or(action) { + b"copy" | b"cut" => uri_list_paths(uris), + _ => vec![], + } +} + +/// The absolute path a `file:` URI names on this machine: `file:/path`, `file:///path` or +/// `file://localhost/path` (RFC 8089, section 2; scheme and host in any letter case), its percent +/// escapes decoded once (RFC 3986, section 2.1) and a fragment (`#…`) left out. None for another +/// scheme, another host, a relative path, a query (`?…`), a bad escape, an escaped NUL or a path +/// that is not UTF-8 once decoded. +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +fn file_uri_path(uri: &str) -> Option { + let uri = uri.trim_matches(|c: char| c.is_ascii_whitespace()); + let uri = uri.split_once('#').map_or(uri, |(before, _)| before); + if uri.contains('?') { + return None; + } + let scheme = uri.get(..5).filter(|s| s.eq_ignore_ascii_case("file:"))?; + let rest = uri.get(scheme.len()..)?; + let path = match rest.strip_prefix("//") { + Some(authority_and_path) => { + let slash = authority_and_path.find('/')?; + let host = authority_and_path.get(..slash)?; + if !host.is_empty() && !host.eq_ignore_ascii_case("localhost") { + return None; + } + authority_and_path.get(slash..)? + } + None => rest.starts_with('/').then_some(rest)?, + }; + let mut bytes = Vec::with_capacity(path.len()); + let mut it = path.bytes(); + while let Some(b) = it.next() { + if b == b'%' { + let hex = |d: Option| char::from(d?).to_digit(16); + let (hi, lo) = (hex(it.next())?, hex(it.next())?); + bytes.push(u8::try_from(hi * 16 + lo).ok()?); + } else { + bytes.push(b); + } + } + if bytes.contains(&0) { + return None; + } + String::from_utf8(bytes).ok().map(PathBuf::from) +} + #[cfg(windows)] mod win { use std::num::NonZeroU32; @@ -1094,7 +1198,9 @@ mod portable { } } - /// Files copied in a file manager (none where the backend can't read a file list). + /// Files copied in a file manager, read through arboard. The Wayland core protocol reads + /// its file list with the rest of a paste + /// ([`DataClipboard::read`](super::wayland::DataClipboard::read)). fn file_list(&mut self) -> Vec { match self { Self::Arboard(cb) => cb.read(Request::Files).files(), @@ -1233,8 +1339,9 @@ mod portable { } /// 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. + /// the Wayland core protocol the copied files, else the first of `mimes` the clipboard + /// offers, is read: text here, file lists, 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")] @@ -1335,9 +1442,9 @@ mod portable { } /// 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. + /// core protocol copied files, 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 { #[cfg(target_os = "macos")] if super::mac::has(mimes) { @@ -1784,12 +1891,13 @@ mod portable { /// 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). 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 +/// text under each of [`TEXT_TYPES`]; Paste reads the files a file manager copied +/// ([`FILE_LISTS`]), then 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, file lists, 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. A read or send whose pipe moves no data /// for [`IDLE_WAIT`] fails and closes the pipe, which frees its worker or thread. #[cfg(target_os = "linux")] @@ -1817,14 +1925,17 @@ mod wayland { 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}; + use super::{BITMAP, Flavour, MAX_BYTES, PNG, PathBuf, SVG, TEXT, copied_file, gnome_copied_paths, uri_list_paths}; /// 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; + /// What reads the files a file list names. + type PathsOf = fn(&[u8]) -> Vec; + /// The types files copied in a file manager are offered under, each with what reads its files, + /// best first: `text/uri-list` (RFC 2483), and GNOME Files' own list, read only when the first + /// names no file. + const FILE_LISTS: [(&str, PathsOf); 2] = [("text/uri-list", uri_list_paths), ("x-special/gnome-copied-files", gnome_copied_paths)]; /// 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). @@ -1905,6 +2016,35 @@ mod wayland { Some(first) } + /// Whether a paste of one of `mimes` can take a copied file: one of them is not text. + fn takes_files(mimes: &[&'static str]) -> bool { + mimes.iter().any(|&m| m != TEXT) + } + + /// The first type among `offered` that lists copied files ([`FILE_LISTS`]), in any letter case. + fn file_list_type(offered: &[String]) -> Option<&str> { + FILE_LISTS.iter().find_map(|(list, _)| offered.iter().find(|o| o.eq_ignore_ascii_case(list))).map(String::as_str) + } + + /// The first file a file manager copied that pastes as one of `mimes` ([`copied_file`]), from + /// the first of [`FILE_LISTS`] among `offered` that names a file, `read` reading each list. + fn copied(offered: &[String], mimes: &[&'static str], mut read: impl FnMut(&str) -> Option>) -> Option { + if !takes_files(mimes) { + return None; + } + let paths = FILE_LISTS.iter().find_map(|(list, paths_of)| { + let wire = offered.iter().find(|o| o.eq_ignore_ascii_case(list))?; + Some(paths_of(&read(wire)?)).filter(|paths| !paths.is_empty()) + })?; + copied_file(paths, mimes) + } + + /// What a paste of one of `mimes` takes: the first copied file that is art ([`copied`]), else + /// what [`pick`] takes. + fn pick_pasted(offered: &[String], mimes: &[&'static str], mut read: impl FnMut(&str) -> Option>) -> Option { + copied(offered, mimes, &mut read).or_else(|| pick(offered, mimes, read)) + } + /// The time `idle` from now; None when that is past the clock's range (no limit). fn idle_until(idle: Duration) -> Option { Instant::now().checked_add(idle) @@ -2089,9 +2229,9 @@ mod wayland { impl Unanswered { /// 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 + /// `limit` after the read was sent: the clipboard read again as [`pick_pasted`] 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); @@ -2103,7 +2243,9 @@ mod wayland { } 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()) + pick_pasted(&offered, mimes, |wire| { + wait_for_answer(&self.reads.ask(wire.to_string()).ok()?, LOAD_WAIT.max(left(Instant::now()))).ok()?.ok() + }) } } @@ -2136,12 +2278,36 @@ mod wayland { } } - /// 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. + /// What a paste of one of `mimes` reads: the files a file manager copied, else the first of + /// `mimes` the clipboard offers. A file list is asked for here and read, with the files, + /// by the work that comes back, which pastes the first file that is art ([`copied`]) and + /// else reads `mimes` as [`pick`] does. 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 the work makes after the first waits until `wait` + /// after the first was sent, [`LOAD_WAIT`] at least. pub(super) fn read(&mut self, mimes: &[&'static str], wait: Duration) -> Option { + if takes_files(mimes) { + let offered = lock(&self.seen).offered.clone(); + if let Some(list) = file_list_type(&offered).map(str::to_string) { + let sent = Instant::now(); + let answer = self.loads.ask(list.clone()).ok()?; + self.unanswered = None; + let (reads, mimes) = (self.loads.asker(), mimes.to_vec()); + return Some(ClipboardRead::Later(Box::new(move || { + let left = || LOAD_WAIT.max((sent + wait).saturating_duration_since(Instant::now())); + // The list asked for here is read from its answer, every other type anew. + let mut first = Some((list, answer)); + pick_pasted(&offered, &mimes, |wire| { + let answer = match first.take_if(|(list, _)| list.as_str() == wire) { + Some((_, answer)) => answer, + None => reads.ask(wire.to_string()).ok()?, + }; + wait_for_answer(&answer, left()).ok()?.ok() + }) + }))); + } + } mimes.iter().enumerate().find_map(|(i, &mime)| { let wire = self.wire(mime)?; if mime == TEXT { @@ -2163,10 +2329,11 @@ mod wayland { }) } - /// Whether the clipboard offers one of `mimes`; nothing is read. + /// Whether the clipboard offers one of `mimes`, or files a file manager copied when a paste + /// of `mimes` can take a file; 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()) + (takes_files(mimes) && file_list_type(&seen.offered).is_some()) || mimes.iter().any(|m| wire_type(m, &seen.offered).is_some()) } /// Whether the clipboard holds this connection's last Copy. @@ -2835,6 +3002,85 @@ mod wayland { let Some(ClipboardRead::Later(work)) = reads.read(&[BITMAP], Duration::from_secs(600)) else { panic!("the PNG is asked for") }; assert!(work().is_none()); } + + /// Reads of a clipboard holding `data` by type, answered at once. + fn reads_holding(data: Vec<(String, Vec)>) -> Reads { + let types: Vec = data.iter().map(|(t, _)| t.clone()).collect(); + let loads = Loads::spawn("test", Duration::ZERO, move |wire: String| { + data.iter().find(|(t, _)| *t == wire).map(|(_, d)| d.clone()).ok_or_else(|| "not offered".to_string()) + }) + .unwrap(); + let types: Vec<&str> = types.iter().map(String::as_str).collect(); + Reads::new(loads, Arc::new(Mutex::new(Seen::offering(&types)))) + } + + /// The `file:` URI of `path`, its spaces escaped. + fn file_uri(path: &std::path::Path) -> String { + format!("file://{}", path.display().to_string().replace(' ', "%20")) + } + + /// What a paste of `mimes` takes from `reads`. + fn paste(reads: &mut Reads, mimes: &[&'static str]) -> Option<(&'static str, Vec)> { + match reads.read(mimes, Duration::from_secs(600))? { + ClipboardRead::Now(f) => Some((f.mime, f.data)), + ClipboardRead::Later(work) => work().map(|f| (f.mime, f.data)), + } + } + + #[test] + fn files_copied_in_a_file_manager_paste_as_their_art() { + use vectorcraft_engine::cmd::clipboard::PASTE_ORDER; + let d = tempfile::Builder::new().prefix("vectorcraft-wayland-files-").tempdir().unwrap(); + let (notes, red) = (d.path().join("notes.txt"), d.path().join("red image.png")); + let mut png = vec![]; + image::RgbaImage::new(2, 2).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + std::fs::write(¬es, "not art").unwrap(); + std::fs::write(&red, &png).unwrap(); + let list = |paths: &[&std::path::Path]| paths.iter().map(|p| file_uri(p) + "\r\n").collect::().into_bytes(); + let held = |types: &[(&str, Vec)]| reads_holding(types.iter().map(|(t, d)| (t.to_string(), d.clone())).collect()); + let text = ("text/plain;charset=utf-8", b"the files' paths".to_vec()); + // A file list alone enables Paste and pastes the first file that is art. + let mut reads = held(&[("text/uri-list", list(&[¬es, &red]))]); + assert!(reads.has(&PASTE_ORDER) && reads.has(&[BITMAP])); + assert_eq!(paste(&mut reads, &PASTE_ORDER), Some((PNG, png.clone()))); + // A paste of text alone takes no file. + assert!(!reads.has(&[TEXT])); + assert_eq!(paste(&mut reads, &[TEXT]), None); + // The files come before the other types offered, as on the other platforms; the type in + // any letter case. + let mut reads = held(&[(SVG, b"".to_vec()), text.clone(), ("Text/URI-List", list(&[&red]))]); + assert_eq!(paste(&mut reads, &PASTE_ORDER), Some((PNG, png.clone()))); + assert_eq!(paste(&mut reads, &[TEXT]), Some((TEXT, text.1.clone()))); + // With no file that is art, the paste takes the other types. + let mut reads = held(&[("text/uri-list", list(&[¬es, &d.path().join("gone.png")])), text.clone()]); + assert_eq!(paste(&mut reads, &PASTE_ORDER), Some((TEXT, text.1.clone()))); + let mut reads = held(&[("text/uri-list", b"https://example.com/art.png\r\n".to_vec())]); + assert_eq!(paste(&mut reads, &PASTE_ORDER), None); + // GNOME Files' own list, alone or when the URI list names no local file. + let gnome = [b"copy\n".to_vec(), file_uri(&red).into_bytes()].concat(); + let mut reads = held(&[("x-special/gnome-copied-files", gnome.clone())]); + assert!(reads.has(&PASTE_ORDER)); + assert_eq!(paste(&mut reads, &PASTE_ORDER), Some((PNG, png.clone()))); + let mut reads = held(&[("text/uri-list", b"file://server/art.png\r\n".to_vec()), ("x-special/gnome-copied-files", gnome)]); + assert_eq!(paste(&mut reads, &PASTE_ORDER), Some((PNG, png.clone()))); + // KDE's cut marker is not a file list. + let mut reads = held(&[("application/x-kde-cutselection", b"1".to_vec())]); + assert!(!reads.has(&PASTE_ORDER)); + assert_eq!(paste(&mut reads, &PASTE_ORDER), None); + } + + #[test] + fn a_file_list_that_cant_be_read_gives_way_to_the_other_types() { + use vectorcraft_engine::cmd::clipboard::PASTE_ORDER; + let offered = offered(&["text/uri-list", "text/plain"]); + let mut asked = vec![]; + let f = pick_pasted(&offered, &PASTE_ORDER, |wire| { + asked.push(wire.to_string()); + (wire == "text/plain").then(|| b"words".to_vec()) + }); + assert_eq!(f.map(|f| (f.mime, f.data)), Some((TEXT, b"words".to_vec()))); + assert_eq!(asked, ["text/uri-list", "text/plain"]); + } } } @@ -2952,6 +3198,115 @@ mod tests { assert_eq!(copied_file(vec![with_cr], &PASTE_ORDER).map(|f| f.mime), Some(PNG)); } + /// A copied file of more than 64 MiB is skipped before it is read, and the next one pastes. + #[test] + fn an_oversized_copied_file_is_skipped_before_it_is_read() { + let d = dir("oversized"); + let (big, small) = (d.path().join("big.png"), d.path().join("small.png")); + std::fs::write(&big, png(2, 2)).unwrap(); + // Sparse where the file system allows: no 64 MiB is written. + std::fs::OpenOptions::new().write(true).open(&big).unwrap().set_len(MAX_BYTES as u64 + 1).unwrap(); + std::fs::write(&small, png(3, 2)).unwrap(); + assert!(copied_file(vec![big.clone()], &PASTE_ORDER).is_none()); + let f = copied_file(vec![big, small], &PASTE_ORDER).unwrap(); + assert_eq!((f.mime, f.data), (PNG, png(3, 2))); + } + + /// A copied file of exactly the limit pastes; one byte more and it is skipped. + #[test] + fn a_copied_file_pastes_up_to_the_limit() { + let d = dir("limit"); + let art = d.path().join("art.svg"); + let svg = ""; + std::fs::write(&art, svg).unwrap(); + let read = |limit| copied_file_within(vec![art.clone()], &PASTE_ORDER, limit).map(|f| f.data); + assert_eq!(read(svg.len()), Some(svg.as_bytes().to_vec())); + assert_eq!(read(svg.len() - 1), None); + } + + /// A file that grows past the limit after its size was checked is read to one byte past the + /// limit and refused. + #[test] + fn the_rest_of_a_file_is_read_to_the_limit_at_most() { + let read = |len: usize, head: usize| { + let bytes = vec![7u8; len]; + let mut file = Cursor::new(bytes); + let mut first = vec![0; head]; + file.read_exact(&mut first).unwrap(); + (read_rest(&mut file, first, 16).map(|d| d.len()), file.position()) + }; + assert_eq!(read(16, 4), (Some(16), 16)); + assert_eq!(read(0, 0), (Some(0), 0)); + assert_eq!(read(17, 4), (None, 17)); + assert_eq!(read(1000, 4), (None, 17)); + // First bytes already past the limit: nothing more is read. + assert_eq!(read(1000, 20), (None, 20)); + } + + fn uri_paths(list: &[u8]) -> Vec { + uri_list_paths(list).into_iter().map(|p| p.to_string_lossy().into_owned()).collect() + } + + #[test] + fn a_uri_list_names_the_local_files_of_its_lines() { + // CRLF or LF, comment lines and blank lines. + assert_eq!(uri_paths(b"# copied\r\nfile:///home/a/one.svg\r\n\r\nfile:///home/a/two.png\n"), ["/home/a/one.svg", "/home/a/two.png"]); + assert_eq!(uri_paths(b"file:///a.svg"), ["/a.svg"]); + // Percent escapes are decoded once; `+` and an escaped `#` are part of the name. + assert_eq!(uri_paths(b"file:///home/a/red%20image.png"), ["/home/a/red image.png"]); + assert_eq!(uri_paths(b"file:///home/a/caf%C3%A9.svg\nfile:///home/a/caf\xC3\xA9.svg"), ["/home/a/café.svg", "/home/a/café.svg"]); + assert_eq!(uri_paths(b"file:///a/%231+2.svg"), ["/a/#1+2.svg"]); + assert_eq!(uri_paths(b"file:///a/100%2525.svg"), ["/a/100%25.svg"]); + // No host, `localhost` in any case, and the short form name this machine; a fragment is + // left out. + assert_eq!( + uri_paths(b"file://localhost/a.svg\nFILE://LocalHost/b.svg\nfile:/c.svg\nfile:///d.svg#page=2"), + ["/a.svg", "/b.svg", "/c.svg", "/d.svg"] + ); + // Other hosts and schemes, relative paths, queries, bad escapes, an escaped NUL, a name + // that is not UTF-8 once decoded and a line that is not UTF-8 name no file. + for uri in [ + &b"file://server/a.svg"[..], + b"https://example.com/a.svg", + b"file:a.svg", + b"file://", + b"file://localhost", + b"file:///a.svg?x=1", + b"file:///a%2", + b"file:///a%zz.svg", + b"file:///a%00b.svg", + b"file:///a%FF.svg", + b"file:///a\xFF.svg", + b"/home/a/one.svg", + b"#file:///a.svg", + ] { + assert!(uri_list_paths(uri).is_empty(), "{}", String::from_utf8_lossy(uri)); + } + // The files beside a URI that names none are kept. + assert_eq!(uri_paths(b"https://example.com/a.svg\r\nfile:///b.svg\r\n"), ["/b.svg"]); + assert!(uri_list_paths(b"").is_empty()); + } + + #[test] + fn a_uri_list_longer_than_the_limit_names_no_file() { + assert_eq!(MAX_URIS, 1024); + let list = |n: usize| (0..n).map(|i| format!("# file {i}\r\nfile:///f{i}.svg\r\n")).collect::(); + // Comment lines don't count. + assert_eq!(uri_list_paths(list(MAX_URIS).as_bytes()).len(), MAX_URIS); + assert!(uri_list_paths(list(MAX_URIS + 1).as_bytes()).is_empty()); + } + + #[test] + fn gnome_files_list_names_its_files_after_copy_or_cut() { + let paths = |list: &[u8]| gnome_copied_paths(list).into_iter().map(|p| p.to_string_lossy().into_owned()).collect::>(); + assert_eq!(paths(b"copy\nfile:///a.svg\nfile:///b%20c.png"), ["/a.svg", "/b c.png"]); + assert_eq!(paths(b"cut\r\nfile:///a.svg\r\n"), ["/a.svg"]); + // Another first line, none, or no files. + for list in [&b"move\nfile:///a.svg"[..], b"file:///a.svg\nfile:///b.svg", b"copy", b"", b"Copy\nfile:///a.svg"] { + assert!(gnome_copied_paths(list).is_empty(), "{}", String::from_utf8_lossy(list)); + } + } + /// A DIB of `w`×`h` pixels (top row first when `h` is negative): a `header`-byte header (40, /// or 124 for a BITMAPV5HEADER with BGRA masks), `extra` (the masks after a 40-byte header, a /// colour table), then `rows`, each padded to 4 bytes. diff --git a/crates/brush/src/lib.rs b/crates/brush/src/lib.rs index 851afc9e7a..0b48f586cd 100644 --- a/crates/brush/src/lib.rs +++ b/crates/brush/src/lib.rs @@ -13,6 +13,7 @@ mod calli; mod colorize; mod defaults; +pub mod stored_art; pub mod track; mod warp; @@ -799,9 +800,15 @@ fn number_repeated_names(lib: &mut [Brush]) { } } -/// Store `lib` as the document's brush library. +/// Store `lib` as the document's brush library. When the art of a brush holds images or placed +/// documents, each object in that art whose id is 0 or repeats another object's is given a new +/// id ([`stored_art::StoredArt::persist_ids`]), so the Links panel lists it by the same id until it +/// changes. pub fn store(doc: &mut Document, lib: &[Brush]) { doc.unknown.insert(DOC_KEY.into(), serde_json::to_value(lib).unwrap_or_default()); + if lib.iter().any(|b| b.art().into_iter().any(stored_art::holds_files)) { + stored_art::StoredArt::persist_ids(doc); + } } /// Find a brush by name. @@ -1001,6 +1008,33 @@ pub fn has_brush(n: &Node) -> bool { n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(s) if s.brush.is_some() && s.visible)) } +/// How far brush art can paint past the visual box of `n`: `16 × w + 8`, where `w` is the widest +/// stroke of `n` (at least 1), when `n` has a visible brushed stroke with a paint; 0 when it has +/// none, as a brushed stroke without a paint draws no brush art. This is the room the renderer and +/// the exports leave for brush art when they cull. +pub fn reach(n: &Node) -> f64 { + let paints = |i: &AppearanceItem| matches!(i, AppearanceItem::Stroke(s) if s.visible && s.brush.is_some() && !s.paint.is_none()); + if !n.appearance.items.iter().any(paints) { + return 0.0; + } + let w = n.appearance.items.iter().filter_map(|i| if let AppearanceItem::Stroke(s) = i { Some(s.width) } else { None }).fold(1.0, f64::max); + 16.0 * w + 8.0 +} + +/// The largest [`reach`] of `n` and of the objects in it: the members of its groups, layers and +/// live objects. Of a group or layer with a clipping path only the clipping path counts, as the +/// clip keeps its members' brush art inside it. A compound path counts its own strokes only, as +/// it is painted with its own appearance and not its paths'. Symbol art is not looked into +/// ([`vectorcraft_doc::SymbolBoxes::with_brush_art`] measures it). +pub fn reach_within(n: &Node) -> f64 { + let members = match &n.kind { + NodeKind::Group { children, clip: true } | NodeKind::Layer { children, clip: true, .. } => children.get(..1).unwrap_or_default(), + NodeKind::Compound { .. } => &[], + _ => n.children().map_or(&[][..], |c| &c[..]), + }; + members.iter().map(|c| reach_within(c)).fold(reach(n), f64::max) +} + /// Expand a brushed path: a group of [the path with its fills and unbrushed strokes (if any /// paint remains), the brush art…]. Ids are 0 (the caller re-ids). `None` if not brushed. pub fn expand(doc: &Document, n: &Node) -> Option { diff --git a/crates/brush/src/stored_art.rs b/crates/brush/src/stored_art.rs new file mode 100644 index 0000000000..a386e2e181 --- /dev/null +++ b/crates/brush/src/stored_art.rs @@ -0,0 +1,176 @@ +//! The art of the stored brushes (a scatter or art brush's art, a pattern brush's tiles) as stored +//! art of the document ([`Document::mounted_art`]): set on the document while a command looks it up +//! by id or changes it, then written back into the library entries whose art changed. The Links +//! panel finds the images and placed documents in that art this way. + +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, Node, NodeKind}; + +use crate::{Brush, BrushKind, DOC_KEY}; + +/// The brushes of a document's stored library whose art holds images or placed documents. +#[derive(Default)] +pub struct StoredArt { + entries: Vec, + /// How many entries the stored library had when it was read. + read_entries: usize, +} + +/// A library entry whose brush's art holds images or placed documents. +struct Entry { + /// Its index in the stored library. + slot: usize, + /// The entry as it was read. + raw: Value, + brush: Brush, + /// The brush's art ([`Brush::art`]), each root with the `owner` the Links panel names for it. + art: Vec<(Arc, Value)>, +} + +/// What names each root of [`Brush::art`] among the brush's art: a pattern brush's tile, in the +/// same order; nothing for the one root of a scatter or art brush. +fn tiles(b: &Brush) -> Vec> { + match &b.kind { + BrushKind::Pattern(p) => std::iter::once(Some("side")) + .chain( + [ + (p.outer_corner.is_some(), "outerCorner"), + (p.inner_corner.is_some(), "innerCorner"), + (p.start.is_some(), "start"), + (p.end.is_some(), "end"), + ] + .into_iter() + .filter(|(held, _)| *held) + .map(|(_, tile)| Some(tile)), + ) + .collect(), + _ => vec![None], + } +} + +/// Whether `n` or its subtree, opacity-mask art included, holds an image or a placed document. +pub(crate) fn holds_files(n: &Node) -> bool { + let mut found = false; + vectorcraft_doc::swatches::walk_with_masks(n, &mut |c| found |= matches!(c.kind, NodeKind::Image(_) | NodeKind::PlacedDocument(_))); + found +} + +impl StoredArt { + /// The brushes of `doc`'s stored library whose art holds an image or a placed document (opacity + /// masks included). An entry that does not read as a brush is left out, and so is left as it + /// is. A root's owner is + /// `{kind: "brush", name, index, tile?}`, with the name and index the brush has in the library as + /// the Brushes panel lists it ([`crate::library`], a repeated name numbered). + pub fn read(doc: &Document) -> Self { + let Some(stored) = doc.unknown.get(DOC_KEY) else { return Self::default() }; + let Some(list) = stored.as_array() else { return Self::default() }; + let listed = crate::parse_library(stored); + let parsed = list.iter().enumerate().filter_map(|(slot, raw)| Brush::from_json(raw.clone()).ok().map(|b| (slot, raw, b))); + let mut entries = vec![]; + for (index, (slot, raw, brush)) in parsed.enumerate() { + if !brush.art().into_iter().any(holds_files) { + continue; + } + let name = listed.get(index).map_or(brush.name.as_str(), |b| b.name.as_str()); + let art: Vec<(Arc, Value)> = brush + .art() + .into_iter() + .zip(tiles(&brush)) + .map(|(n, tile)| { + let mut owner = json!({ "kind": "brush", "name": name, "index": index }); + if let Some(tile) = tile { + owner["tile"] = json!(tile); + } + (Arc::new(n.clone()), owner) + }) + .collect(); + if !art.is_empty() { + entries.push(Entry { slot, raw: raw.clone(), brush, art }); + } + } + Self { entries, read_entries: list.len() } + } + + /// Gives the objects of the stored brushes' art that holds images or placed documents ids of + /// their own in `doc`'s library, as [`Self::mount`] gives them, and writes the brushes whose + /// ids changed back. Does nothing while art is set on `doc` ([`Document::mounted_art`]). + pub fn persist_ids(doc: &mut Document) { + if !doc.mounted_art.is_empty() { + return; + } + let art = Self::read(doc); + if !art.is_empty() { + art.mount(doc); + art.write_entries(doc); + } + } + + /// No stored brush's art holds an image or a placed document. + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } + + /// Sets the art on `doc` as [`Document::mounted_art`], each object with an id of its own + /// ([`Document::number_mounted_art`]: an id another stored object has, or none, is replaced, and + /// the id counter stands above them all). + pub fn mount(&self, doc: &mut Document) { + doc.mounted_art = self.entries.iter().flat_map(|e| e.art.iter().cloned()).collect(); + doc.number_mounted_art(); + } + + /// Takes [`Document::mounted_art`] off `doc` and writes each brush whose art changed (new ids + /// included) back into its library entry: the entry at its index when that entry is as it was + /// read or reads as the brush as it was apart from its name, else the first entry that reads as + /// the brush as it was, else the first that does apart from its name. An entry found apart from + /// its name keeps that name (the library was written again meanwhile, as placing a document's + /// brushes into it does, numbering a repeated name). The other entries are left as + /// they are. Then the art of brushes added meanwhile gets ids of its own + /// ([`Self::persist_ids`]). + pub fn write_back(self, doc: &mut Document) { + let read_entries = self.read_entries; + self.write_entries(doc); + if doc.unknown.get(DOC_KEY).and_then(Value::as_array).map(Vec::len) != Some(read_entries) { + Self::persist_ids(doc); + } + } + + /// [`Self::write_back`] without giving ids to the art of brushes added meanwhile. + fn write_entries(self, doc: &mut Document) { + let mut mounted = std::mem::take(&mut doc.mounted_art).into_iter(); + let mut changed = vec![]; + for e in self.entries { + let now: Vec> = mounted.by_ref().take(e.art.len()).map(|(n, _)| n).collect(); + if now.len() != e.art.len() || now.iter().zip(&e.art).all(|(a, (b, _))| Arc::ptr_eq(a, b)) { + continue; + } + let mut brush = e.brush.clone(); + for (slot, art) in brush.art_mut().into_iter().zip(now) { + *slot = Arc::unwrap_or_clone(art); + } + changed.push((e.slot, e.raw, e.brush, brush)); + } + let Some(list) = doc.unknown.get_mut(DOC_KEY).and_then(Value::as_array_mut) else { return }; + for (slot, raw, was, mut brush) in changed { + // The entry's name when it reads as `was` apart from its name. + let name_of = |entry: &Value| { + Brush::from_json(entry.clone()).ok().and_then(|mut b| { + let name = std::mem::replace(&mut b.name, was.name.clone()); + (b == was).then_some(name) + }) + }; + let at = match list.get(slot) { + Some(entry) if *entry == raw || name_of(entry).is_some() => Some(slot), + _ => list.iter().position(|e| name_of(e).as_ref() == Some(&was.name)).or_else(|| list.iter().position(|e| name_of(e).is_some())), + }; + let Some(entry) = at.and_then(|i| list.get_mut(i)) else { continue }; + if let Some(name) = name_of(entry) { + brush.name = name; + } + if let Ok(v) = serde_json::to_value(&brush) { + *entry = v; + } + } + } +} diff --git a/crates/brush/src/tests.rs b/crates/brush/src/tests.rs index ecaba1266a..de178c76ac 100644 --- a/crates/brush/src/tests.rs +++ b/crates/brush/src/tests.rs @@ -1017,6 +1017,159 @@ fn repeated_brush_names_are_numbered_when_read() { assert_eq!(names.iter().collect::>().len(), names.len()); } +/// Art of `w`×`h` points holding a linked image: a group of [`rect_art`] and the image, both with id 0. +fn linked_art(w: f64, h: f64) -> Node { + let image = Node::new( + NodeId(0), + NodeKind::Image(Box::new(vectorcraft_doc::ImageObject { + key: "k".into(), + width: 4, + height: 4, + xf: Affine::IDENTITY, + link: Some(vectorcraft_doc::LinkInfo::new("/art/a.png")), + placement: Default::default(), + pixels: None, + })), + ); + Node::group(NodeId(0), vec![std::sync::Arc::new(rect_art(w, h)), std::sync::Arc::new(image)]) +} + +/// The art of the stored brushes that holds images mounts on the document as stored art, each tile +/// with the brush, its place in the library and the tile as owner, its objects with ids of their +/// own; writing it back changes only the entries whose art changed, and leaves an entry that does +/// not read as a brush, a brush without art and a brush whose art holds no image as they were stored. +#[test] +fn stored_brush_art_mounts_and_writes_back_only_what_changed() { + use stored_art::StoredArt; + let mut d = Document::new(100.0, 100.0); + let layer_object = d.layers[0].id; + let mut side = linked_art(10.0, 4.0); + side.id = layer_object; + let pattern = + Brush { name: "Frame".into(), kind: BrushKind::Pattern(PatternBrush { side, start: Some(linked_art(4.0, 4.0)), ..Default::default() }) }; + let scatter = Brush { + name: "Dots".into(), + kind: BrushKind::Scatter(Scatter { art: linked_art(2.0, 2.0), colorization: Colorization::None, ..Default::default() }), + }; + // Written as a file holds it, without the ids `store` gives. + let lib = [calli(0.0, 100.0, 3.0), pattern, scatter, art_brush(rect_art(10.0, 4.0), ArtScale::Stretch)]; + d.unknown.insert(DOC_KEY.into(), serde_json::to_value(lib).unwrap()); + let odd = serde_json::json!({ "name": "Odd", "type": "unknown" }); + if let Some(list) = d.unknown.get_mut(DOC_KEY).and_then(serde_json::Value::as_array_mut) { + list.insert(1, odd.clone()); + } + let stored = d.unknown[DOC_KEY].clone(); + let art = StoredArt::read(&d); + art.mount(&mut d); + let owners: Vec<&serde_json::Value> = d.mounted_art.iter().map(|(_, o)| o).collect(); + assert_eq!( + owners, + [ + &serde_json::json!({ "kind": "brush", "name": "Frame", "index": 1, "tile": "side" }), + &serde_json::json!({ "kind": "brush", "name": "Frame", "index": 1, "tile": "start" }), + &serde_json::json!({ "kind": "brush", "name": "Dots", "index": 2 }), + ] + ); + let ids: Vec = d.mounted_art.iter().map(|(n, _)| n.id).collect(); + let mut all = vec![]; + d.visit_stored(|n, _| all.push(n.id)); + assert!(all.iter().all(|id| id.0 != 0) && !all[1..].contains(&layer_object), "{all:?}"); + assert_eq!(all.iter().collect::>().len(), all.len(), "{all:?}"); + // The scatter brush's art changes; the pattern brush's tiles keep the ids mounting gave them. + d.stored_node_mut(ids[2]).unwrap().name = Some("changed".into()); + art.write_back(&mut d); + assert!(d.mounted_art.is_empty()); + let now = d.unknown[DOC_KEY].as_array().unwrap(); + assert_eq!(now.len(), 5); + assert_eq!((&now[0], &now[1], &now[4]), (&stored[0], &odd, &stored[4]), "the entries without images stay as stored"); + assert_ne!(now[2], stored[2], "the pattern brush keeps the ids its art was given"); + let lib = library(&d); + let Some(BrushKind::Pattern(p)) = lib.iter().find(|b| b.name == "Frame").map(|b| &b.kind) else { panic!("no pattern brush") }; + assert_eq!((p.side.id, p.start.as_ref().map(|n| n.id)), (ids[0], Some(ids[1]))); + assert_eq!(find(&d, "Dots").unwrap().art()[0].name.as_deref(), Some("changed")); + // Mounting again gives the same ids and changes nothing, so writing back leaves the library as it is. + let again = d.unknown[DOC_KEY].clone(); + let art = StoredArt::read(&d); + art.mount(&mut d); + assert_eq!(d.mounted_art.iter().map(|(n, _)| n.id).collect::>(), ids); + art.write_back(&mut d); + assert_eq!(d.unknown[DOC_KEY], again); +} + +/// A brush whose stored name repeats an earlier brush's is named in its art's owner as the Brushes +/// panel lists it, numbered. +#[test] +fn stored_brush_art_owner_names_a_repeated_name_as_listed() { + use stored_art::StoredArt; + let mut d = Document::new(100.0, 100.0); + let scatter = Brush { name: "Dots".into(), kind: BrushKind::Scatter(Scatter { art: linked_art(2.0, 2.0), ..Default::default() }) }; + store(&mut d, &[scatter.clone(), scatter]); + StoredArt::read(&d).mount(&mut d); + let names: Vec<&serde_json::Value> = d.mounted_art.iter().map(|(_, o)| &o["name"]).collect(); + assert_eq!(names, ["Dots", "Dots 2"]); +} + +/// Storing a library whose brush art holds an image gives that art ids of its own, so mounting it +/// later gives the same ids whatever the document allocated in between; art without images keeps +/// the ids it was stored with. +#[test] +fn storing_brush_art_with_images_keeps_ids_of_its_own() { + use stored_art::StoredArt; + let mut d = Document::new(100.0, 100.0); + let mut art = linked_art(2.0, 2.0); + art.id = d.layers[0].id; + let scatter = Brush { name: "Dots".into(), kind: BrushKind::Scatter(Scatter { art, ..Default::default() }) }; + store(&mut d, &[scatter, art_brush(rect_art(10.0, 4.0), ArtScale::Stretch)]); + let lib = library(&d); + let stored = lib[0].art()[0].id; + assert_ne!(stored, d.layers[0].id); + assert_eq!(lib[1].art()[0].id, NodeId(0), "art without images is stored as it was"); + d.alloc_id(); + StoredArt::read(&d).mount(&mut d); + assert_eq!(d.mounted_art[0].0.id, stored); +} + +/// When the library is written again while the art is mounted, numbering a repeated name and +/// adding a brush (as placing a document's brushes into it does), writing back changes the entry +/// at its own place that reads as the brush apart from its new name, keeping that name, even when +/// an earlier brush is the same as the one it was, and gives the added brush's art ids of its own. +#[test] +fn brush_art_written_back_finds_its_renamed_entry_and_numbers_added_art() { + use stored_art::StoredArt; + /// `n` with ids from `next` on, in paint order. + fn numbered(mut n: Node, next: &mut u64) -> Node { + n.id = NodeId(*next); + *next += 1; + for c in n.children_mut().into_iter().flatten() { + *c = std::sync::Arc::new(numbered((**c).clone(), next)); + } + n + } + let mut d = Document::new(100.0, 100.0); + let scatter = + |n: &str| Brush { name: n.into(), kind: BrushKind::Scatter(Scatter { art: numbered(linked_art(2.0, 2.0), &mut 50), ..Default::default() }) }; + // Two brushes the same apart from the ids mounting gives the second. + d.unknown.insert(DOC_KEY.into(), serde_json::to_value([scatter("Dots"), scatter("Dots")]).unwrap()); + let art = StoredArt::read(&d); + art.mount(&mut d); + assert_eq!(d.mounted_art[0].0.id, NodeId(50)); + let second = d.mounted_art[1].0.id; + // The library is written again: the repeated name numbered, a brush whose art repeats an id added. + let mut added = scatter("New"); + if let BrushKind::Scatter(s) = &mut added.kind { + s.art.id = d.layers[0].id; + } + let lib = [library(&d), vec![added]].concat(); + d.unknown.insert(DOC_KEY.into(), serde_json::to_value(&lib).unwrap()); + assert_eq!(lib[1].name, "Dots 2"); + d.stored_node_mut(second).unwrap().name = Some("changed".into()); + art.write_back(&mut d); + let lib = library(&d); + assert_eq!(lib.iter().map(|b| b.name.as_str()).collect::>(), ["Dots", "Dots 2", "New"]); + assert_eq!((lib[0].art()[0].name.as_deref(), lib[1].art()[0].name.as_deref()), (None, Some("changed"))); + assert_ne!(lib[2].art()[0].id, d.layers[0].id, "the added brush's art has ids of its own"); +} + #[test] fn brushes_serde_round_trip() { let lib = defaults().to_vec(); diff --git a/crates/cad/src/hpgl/write.rs b/crates/cad/src/hpgl/write.rs index 6ab80c8ba0..95c8ecfb7a 100644 --- a/crates/cad/src/hpgl/write.rs +++ b/crates/cad/src/hpgl/write.rs @@ -1024,6 +1024,26 @@ fn overlaps(a: Rect, b: Rect) -> bool { a.x0 <= b.x1 && b.x0 <= a.x1 && a.y0 <= b.y1 && b.y0 <= a.y1 } +/// Whether a plot draws nothing of `n` wherever it is, apart from what every export leaves out +/// (hidden objects, guides and template layers): an object at 0% opacity, a non-printing layer, a +/// placed image, a gradient mesh whose every point is at 0% opacity, or a path or compound path +/// without effects whose fills and strokes paint nothing. An image or a mesh in `doc` with a +/// visible Crop Marks effect, or with a Vector Halftone effect that makes dots, is not one of them. +/// A clipping path still clips when the plot draws nothing of it. +pub fn plots_nothing(doc: &Document, n: &Node) -> bool { + let unpainted = || n.appearance.effects.is_empty() && top_stroke(n).is_none() && top_fill(n).is_none(); + let dots = || vectorcraft_effects::addons::halftone::halftone_art(doc, n).is_some_and(|g| g.children().is_some_and(|c| !c.is_empty())); + let adds_art = || vectorcraft_effects::has_crop_marks(n) || dots(); + n.opacity <= 0.0 + || match &n.kind { + NodeKind::Layer { printable, .. } => !printable, + NodeKind::Image(_) => !adds_art(), + NodeKind::Mesh(m) => !adds_art() && m.points.iter().all(|p| p.opacity <= 0.0), + NodeKind::Path { .. } | NodeKind::Compound { .. } => unpainted(), + _ => false, + } +} + /// `nodes` (the children of a clipping container when `clipping`) without the layers and /// sublayers a plot leaves out (hidden, non-printing, template or at 0% opacity) and without /// guides, in layers and groups at any depth, so that baking can't wrap one in art that is drawn diff --git a/crates/cad/src/hpgl/write/tests.rs b/crates/cad/src/hpgl/write/tests.rs index 9cb4f7d727..60f7cf5b3d 100644 --- a/crates/cad/src/hpgl/write/tests.rs +++ b/crates/cad/src/hpgl/write/tests.rs @@ -177,6 +177,90 @@ fn meshes_in_blends_are_outlines_and_clear_meshes_draw_nothing() { assert_eq!(t.matches("PD").count(), 3, "{t}"); } +/// `plots_nothing` picks the objects and layers that a plot draws nothing of: a path that paints +/// nothing, objects at 0% opacity, placed images, meshes with every point at 0% opacity and +/// non-printing layers, and not a painted path or a mesh. +#[test] +fn plots_nothing_picks_what_a_plot_draws_nothing_of() { + type Make = fn(&mut Document) -> Node; + let cases: [(&str, Make, bool); 7] = [ + ("stroked", |d| stroked(d, rect(10.0, 10.0, 40.0, 40.0), Color::BLACK), false), + ("unpainted", |d| Node::path(d.alloc_id(), rect(10.0, 10.0, 40.0, 40.0), Appearance::basic(Paint::None, Paint::None, 1.0)), true), + ( + "clear", + |d| { + let mut n = filled(d, rect(10.0, 10.0, 40.0, 40.0), Color::BLACK); + n.opacity = 0.0; + n + }, + true, + ), + ( + "image", + |d| { + let image = vectorcraft_doc::ImageObject { + key: "raster-1".into(), + width: 4, + height: 2, + xf: Affine::translate((10.0, 20.0)) * Affine::scale(5.0), + link: None, + placement: Default::default(), + pixels: None, + }; + Node::new(d.alloc_id(), NodeKind::Image(Box::new(image))) + }, + true, + ), + ( + "image with Crop Marks", + |d| { + let image = vectorcraft_doc::ImageObject { + key: "raster-1".into(), + width: 4, + height: 2, + xf: Affine::translate((10.0, 20.0)) * Affine::scale(5.0), + link: None, + placement: Default::default(), + pixels: None, + }; + let mut n = Node::new(d.alloc_id(), NodeKind::Image(Box::new(image))); + n.appearance.effects.push(vectorcraft_doc::Effect { id: "cropMarks".into(), params: serde_json::json!({}), visible: true }); + n + }, + false, + ), + ("mesh", |d| Node::new(d.alloc_id(), NodeKind::Mesh(mesh_at(10.0))), false), + ( + "clear mesh", + |d| { + let mut clear = mesh_at(10.0); + clear.points.iter_mut().for_each(|p| p.opacity = 0.0); + Node::new(d.alloc_id(), NodeKind::Mesh(clear)) + }, + true, + ), + ]; + for (name, make, nothing) in cases { + let mut held = None; + let d = doc_with(|d| { + let n = make(d); + held = Some(n.clone()); + vec![n] + }); + let Some(n) = held else { panic!("{name}") }; + assert_eq!(plots_nothing(&d, &n), nothing, "{name}"); + assert_eq!(text(&plot(&d, &opts(&d))) == "IN;PU;SP0;", nothing, "{name}"); + } + let mut d = doc_with(|d| vec![stroked(d, rect(10.0, 10.0, 40.0, 40.0), Color::BLACK)]); + let layer = d.layers[0].id; + assert!(!plots_nothing(&d, &d.layers[0])); + if let Some(NodeKind::Layer { printable, .. }) = d.node_mut(layer).map(|n| &mut n.kind) { + *printable = false; + } + assert!(plots_nothing(&d, &d.layers[0])); + assert_eq!(text(&plot(&d, &opts(&d))), "IN;PU;SP0;"); +} + /// Live art that makes more objects than the plot's limit (1,000 in tests) is left out with a /// warning. #[test] diff --git a/crates/cad/src/lib.rs b/crates/cad/src/lib.rs index 66a6a36baa..bb752267aa 100644 --- a/crates/cad/src/lib.rs +++ b/crates/cad/src/lib.rs @@ -428,7 +428,9 @@ pub fn export(doc: &Document, opts: &DxfOptions) -> Result { if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) { return Err("the export region is not finite".into()); } - let baked = vectorcraft_effects::bake_document(doc); + // Symbols' art is placed without clipping, as the scene places it. + let baked = + vectorcraft_effects::bake_document_placing_symbols(doc, false, vectorcraft_effects::WrittenLayers { hidden: true, non_printing: true }); let doc = baked.as_ref().unwrap_or(doc); Ok(scene::Scene::new(doc, opts).run()) } diff --git a/crates/cad/src/tests.rs b/crates/cad/src/tests.rs index a14af8d929..84e547709d 100644 --- a/crates/cad/src/tests.rs +++ b/crates/cad/src/tests.rs @@ -1410,6 +1410,29 @@ fn a_stained_instance_is_written_in_its_stained_color() { assert!(!colors.is_empty() && colors.iter().all(|c| c.as_deref() == Some("255")), "{colors:?}"); } +#[test] +fn symbol_art_effects_are_written_where_they_draw() { + // A line and the symbol's line below it, each moved 100 pt right by a Transform effect, start + // at the same x. + let moved = |mut n: Node| { + n.appearance.effects.push(vectorcraft_doc::Effect { + id: "distort.transform".into(), + params: serde_json::json!({"moveH": 100.0}), + visible: true, + }); + n + }; + let mut d = doc_with(|d| { + let line = path(d, shapes::line((10.0, 10.0).into(), (20.0, 10.0).into()), Paint::None, Paint::solid(Color::BLACK), 1.0); + vec![moved(line), Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Moved".into(), xf: Affine::IDENTITY })] + }); + let art = path(&mut d, shapes::line((10.0, 40.0).into(), (20.0, 40.0).into()), Paint::None, Paint::solid(Color::BLACK), 1.0); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Moved".into(), art: Arc::new(moved(art)) }); + let starts: Vec = entities(&export(&d, &opts(&d)).unwrap()).iter().map(|e| all(e, 10).into_iter().fold(f64::INFINITY, f64::min)).collect(); + assert_eq!(starts.len(), 2, "{starts:?}"); + assert!((starts[0] - starts[1]).abs() < 1e-6, "{starts:?}"); +} + #[test] fn symbols_fanning_out_into_empty_symbols_stop_at_the_symbol_budget() { // Five levels of 100 instances of the level below, ending in an empty symbol: 10^10 empty diff --git a/crates/color/src/cms.rs b/crates/color/src/cms.rs index f4297343a6..7fd8707a99 100644 --- a/crates/color/src/cms.rs +++ b/crates/color/src/cms.rs @@ -9,13 +9,16 @@ //! any CMYK `.icc` the user loads goes through `moxcms` (LUT-based profiles). //! * The **active settings** are process-wide: the working settings (Edit → Color Settings), with //! the profiles [`use_document_profiles`] last put in place of the working spaces; -//! [`crate::Color::to_rgb`] uses them. Code that needs deterministic numbers builds its own [`Cms`] with [`Cms::new`]. +//! [`crate::Color::to_rgb`] uses them. [`with_active`] puts other settings in their place on one +//! thread, as for a document drawn through its own profiles ([`for_document`]). Code that needs +//! deterministic numbers builds its own [`Cms`] with [`Cms::new`]. pub mod display; pub mod generic; pub mod icc; pub mod lab; +use std::cell::{Cell, RefCell}; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Arc, Mutex, OnceLock, RwLock}; @@ -910,9 +913,32 @@ static WORKING: RwLock>> = RwLock::new(None); static RGB_IS_SRGB: AtomicBool = AtomicBool::new(true); static CMYK_IS_DEVICE: AtomicBool = AtomicBool::new(false); +thread_local! { + /// The settings [`with_active`] put in place of the active settings on this thread. + static SCOPED: RefCell>> = const { RefCell::new(None) }; + /// [`SCOPED`]'s flags for the fast paths: [`SCOPED_SET`] while it is set, [`SCOPED_SRGB`] when + /// its RGB space is sRGB, and [`SCOPED_DEVICE`] when its CMYK space is device CMYK. + static SCOPED_FLAGS: Cell = const { Cell::new(0) }; +} +const SCOPED_SET: u8 = 1; +const SCOPED_SRGB: u8 = 2; +const SCOPED_DEVICE: u8 = 4; + /// The active color-management context: the working settings, with the profiles -/// [`use_document_profiles`] last put in place of the working spaces. +/// [`use_document_profiles`] last put in place of the working spaces. Inside [`with_active`] on +/// this thread: the settings it was given. pub fn active() -> Arc { + if SCOPED_FLAGS.with(Cell::get) & SCOPED_SET != 0 + && let Some(c) = SCOPED.with(|s| s.borrow().clone()) + { + return c; + } + installed() +} + +/// The active settings of the process, as [`use_document_profiles`] or [`set_active`] last put them +/// in place. +fn installed() -> Arc { if let Some(c) = ACTIVE.read().unwrap_or_else(|e| e.into_inner()).as_ref() { return c.clone(); } @@ -954,14 +980,8 @@ pub fn set_active(settings: &ColorSettings) -> Result<(), CmsError> { /// the active settings changed. pub fn use_document_profiles(rgb: Option<&str>, cmyk: Option<&str>) -> bool { let working = working(); - let mut st = working.settings.clone(); - if let Some(p) = rgb.and_then(profile).filter(|p| p.kind == ProfileKind::Rgb) { - st.rgb = p.name; - } - if let Some(p) = cmyk.and_then(profile).filter(|p| p.kind == ProfileKind::Cmyk) { - st.cmyk = p.name; - } - if st == active().settings { + let st = document_settings(&working.settings, rgb, cmyk); + if st == installed().settings { return false; } if st == working.settings { @@ -976,6 +996,72 @@ pub fn use_document_profiles(rgb: Option<&str>, cmyk: Option<&str>) -> bool { true } +/// The working settings `working` with the profiles a document is assigned (`None`: none) in place +/// of the working spaces, as [`use_document_profiles`] takes them. +fn document_settings(working: &ColorSettings, rgb: Option<&str>, cmyk: Option<&str>) -> ColorSettings { + let mut st = working.clone(); + if let Some(p) = rgb.and_then(profile).filter(|p| p.kind == ProfileKind::Rgb) { + st.rgb = p.name; + } + if let Some(p) = cmyk.and_then(profile).filter(|p| p.kind == ProfileKind::Cmyk) { + st.cmyk = p.name; + } + st +} + +/// How many contexts [`for_document`] keeps. +const DOCUMENT_CONTEXTS: usize = 8; + +/// The color-management context a document assigned the profiles `rgb` and `cmyk` (`None`: none) +/// draws through: the one [`use_document_profiles`] would make active for it. A context that is the +/// active or the working one is that one; the others are kept for the same working settings and +/// loaded profiles, so the same document gets the same context again. A profile that cannot be +/// loaded gives the working settings. +pub fn for_document(rgb: Option<&str>, cmyk: Option<&str>) -> Arc { + static KEPT: Mutex)>> = Mutex::new(Vec::new()); + let working = working(); + let st = document_settings(&working.settings, rgb, cmyk); + let installed = installed(); + if st == installed.settings { + return installed; + } + if st == working.settings { + return working; + } + let generation = profiles_generation(); + let mut kept = KEPT.lock().unwrap_or_else(|e| e.into_inner()); + kept.retain(|(g, c)| *g == generation && c.working.as_ref().is_some_and(|w| Arc::ptr_eq(w, &working))); + if let Some((_, c)) = kept.iter().find(|(_, c)| c.settings == st) { + return c.clone(); + } + let Ok(mut cms) = Cms::new(&st) else { return working }; + cms.working = Some(working); + let cms = Arc::new(cms); + if kept.len() >= DOCUMENT_CONTEXTS { + kept.remove(0); + } + kept.push((generation, cms.clone())); + cms +} + +/// Run `f` with `cms` as the active settings on this thread ([`active`], [`crate::Color::to_rgb`] +/// and the conversions that read them), as when drawing a document other than the front one +/// through its own profiles. Other threads, and this thread after `f`, keep the settings they had. +pub fn with_active(cms: Arc, f: impl FnOnce() -> R) -> R { + /// Puts back the settings this thread had before, when `f` returns or unwinds. + struct Restore(Option>, u8); + impl Drop for Restore { + fn drop(&mut self) { + SCOPED.with(|s| *s.borrow_mut() = self.0.take()); + SCOPED_FLAGS.with(|c| c.set(self.1)); + } + } + let flags = SCOPED_SET | if cms.rgb_is_srgb() { SCOPED_SRGB } else { 0 } | if matches!(cms.cmyk, CmykSpace::Device) { SCOPED_DEVICE } else { 0 }; + let before = SCOPED.with(|s| s.borrow_mut().replace(cms)); + let _restore = Restore(before, SCOPED_FLAGS.with(|c| c.replace(flags))); + f() +} + fn install(cms: Arc) { RGB_IS_SRGB.store(cms.rgb_is_srgb(), Ordering::Relaxed); CMYK_IS_DEVICE.store(matches!(cms.cmyk, CmykSpace::Device), Ordering::Relaxed); @@ -984,10 +1070,16 @@ fn install(cms: Arc) { /// Fast path for [`Color::to_rgb`]: RGB colours need no conversion while the working space is sRGB. pub(crate) fn rgb_is_srgb() -> bool { - RGB_IS_SRGB.load(Ordering::Relaxed) + match SCOPED_FLAGS.with(Cell::get) { + f if f & SCOPED_SET != 0 => f & SCOPED_SRGB != 0, + _ => RGB_IS_SRGB.load(Ordering::Relaxed), + } } pub(crate) fn cmyk_is_device() -> bool { - CMYK_IS_DEVICE.load(Ordering::Relaxed) + match SCOPED_FLAGS.with(Cell::get) { + f if f & SCOPED_SET != 0 => f & SCOPED_DEVICE != 0, + _ => CMYK_IS_DEVICE.load(Ordering::Relaxed), + } } #[cfg(test)] diff --git a/crates/color/src/cms/tests.rs b/crates/color/src/cms/tests.rs index 57709abe66..7b22163525 100644 --- a/crates/color/src/cms/tests.rs +++ b/crates/color/src/cms/tests.rs @@ -403,3 +403,42 @@ fn lab_colours_round_trip_through_the_cms() { let Color::Gray { k } = c.convert(&Color::lab(50.0, 0.0, 0.0), Model::Gray, ri) else { panic!("Gray") }; assert!((k - 0.53).abs() < 0.01, "{k}"); } + +#[test] +fn with_active_puts_settings_in_place_on_this_thread_only() { + let p3 = Arc::new(Cms::new(&ColorSettings { rgb: DISPLAY_P3.into(), cmyk: DEVICE_CMYK.into(), ..Default::default() }).unwrap()); + let (rgb, ink) = (Color::Rgb { r: 0.2, g: 0.6, b: 0.4 }, Color::Cmyk { c: 0.2, m: 0.3, y: 0.4, k: 0.1 }); + let before = (rgb.to_rgb(), ink.to_rgb()); + let (inside, ink_inside, other_thread, nested) = with_active(p3.clone(), || { + let other = std::thread::spawn(move || rgb.to_rgb()).join().unwrap(); + let nested = with_active(Arc::new(cms()), || rgb.to_rgb()); + (rgb.to_rgb(), ink.to_rgb(), other, nested) + }); + assert_eq!(inside, p3.display_rgb(&rgb), "RGB is drawn through the settings given"); + assert_ne!(inside, before.0); + assert_eq!(ink_inside, naive_cmyk_to_rgb([0.2, 0.3, 0.4, 0.1]), "CMYK takes the device formula of the settings given"); + assert_eq!(other_thread, before.0, "another thread keeps the active settings"); + assert_eq!(nested, before.0, "an inner call puts its own settings in place"); + assert_eq!((rgb.to_rgb(), ink.to_rgb()), before, "the active settings come back after"); + let unwound = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| with_active(p3.clone(), || panic!("unwinds")))); + assert!(unwound.is_err()); + assert_eq!((rgb.to_rgb(), ink.to_rgb()), before, "the active settings come back after a panic"); +} + +#[test] +fn a_document_gets_the_same_context_for_the_same_profiles() { + // Other tests load profiles meanwhile, and a load makes the contexts again: try until one pair + // of calls sees none. + let same = (0..100).any(|_| { + let generation = profiles_generation(); + let (a, b) = (for_document(Some(DISPLAY_P3), None), for_document(Some(DISPLAY_P3), None)); + profiles_generation() == generation && Arc::ptr_eq(&a, &b) + }); + assert!(same, "the same profiles give the same context"); + let p3 = for_document(Some(DISPLAY_P3), None); + assert_eq!(p3.settings().rgb, DISPLAY_P3); + assert_eq!(p3.settings().cmyk, working_settings().cmyk, "the working CMYK space stays"); + assert_eq!(for_document(None, None).settings(), &working_settings(), "no profiles: the working settings"); + let unknown = for_document(Some("no such profile"), Some(SRGB)); + assert_eq!(unknown.settings(), &working_settings(), "an unknown profile or one of the other model leaves the working space"); +} diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rs index 3afca8063c..fa8cd564f2 100644 --- a/crates/color/src/lib.rs +++ b/crates/color/src/lib.rs @@ -435,9 +435,10 @@ impl Paint { } /// Apply `f` to the colours of this paint that can link to a swatch (a solid colour, each /// gradient stop) with their link and tint; `f` returns true when it changed them. A colour - /// left without a link gets tint 1. A freeform gradient's points, which it draws from, go - /// through `f` too, as unlinked colours (a link `f` gives them is dropped). Returns whether - /// anything changed. + /// left without a link gets tint 1, and a stop left without one also loses its process plates + /// ([`GradientStop::plates`], which print with a linked spot tint). A freeform gradient's + /// points, which it draws from, go through `f` too, as unlinked colours (a link `f` gives them + /// is dropped). Returns whether anything changed. pub fn map_links(&mut self, f: &mut dyn FnMut(&mut Color, &mut Option, &mut f32) -> bool) -> bool { let mut one = |c: &mut Color, link: &mut Option, tint: &mut f32| { let changed = f(c, link, tint); @@ -449,7 +450,11 @@ impl Paint { match self { Paint::Solid { color, swatch, tint } => one(color, swatch, tint), Paint::Gradient(g) => { - let stops = g.gradient.stops.iter_mut().fold(false, |ch, s| one(&mut s.color, &mut s.swatch, &mut s.tint) | ch); + let stops = g.gradient.stops.iter_mut().fold(false, |ch, s| { + let changed = one(&mut s.color, &mut s.swatch, &mut s.tint); + let unplated = s.swatch.is_none() && s.plates.take().is_some(); + changed | unplated | ch + }); let points = g.freeform.iter_mut().flat_map(|ff| ff.points.iter_mut()).fold(false, |ch, p| one(&mut p.color, &mut None, &mut 1.0) | ch); stops | points @@ -593,6 +598,34 @@ mod tests { assert!(g.gradient.stops.iter().all(|s| s.swatch.as_deref() == Some("Ink") && s.tint == 0.5)); } + #[test] + fn mapping_links_drops_the_process_plates_of_unlinked_stops() { + let mut gradient = Gradient::default(); + let ink = Color::cmyk(0.0, 0.4, 0.0, 0.0); + gradient.stops[0].swatch = Some("Ink".into()); + (gradient.stops[0].color, gradient.stops[0].tint, gradient.stops[0].plates) = (ink, 0.4, Some([0.3, 0.0, 0.0, 0.0])); + let mut g = Paint::Gradient(Box::new(GradientPaint::new(gradient))); + // Unlinking the stop takes its plates with its tint and keeps the colour it shows. + assert!(g.map_links(&mut |_, l, _| l.take().is_some())); + let Paint::Gradient(gp) = &g else { panic!("a gradient") }; + let st = &gp.gradient.stops[0]; + assert_eq!((st.color, st.swatch.as_deref(), st.tint, st.plates), (ink, None, 1.0, None)); + // A linked stop keeps its plates. + let mut linked = Gradient::default(); + (linked.stops[0].swatch, linked.stops[0].plates) = (Some("Ink".into()), Some([0.3, 0.0, 0.0, 0.0])); + let mut l = Paint::Gradient(Box::new(GradientPaint::new(linked))); + assert!(!l.map_links(&mut |_, _, _| false)); + let Paint::Gradient(lp) = &l else { panic!("a gradient") }; + assert_eq!(lp.gradient.stops[0].plates, Some([0.3, 0.0, 0.0, 0.0])); + // An unlinked stop that still has plates loses them, and that counts as a change. + let mut stale = Gradient::default(); + stale.stops[1].plates = Some([0.0, 0.0, 0.2, 0.0]); + let mut p = Paint::Gradient(Box::new(GradientPaint::new(stale))); + assert!(p.map_links(&mut |_, _, _| false)); + let Paint::Gradient(pp) = &p else { panic!("a gradient") }; + assert!(pp.gradient.stops.iter().all(|s| s.plates.is_none())); + } + #[test] fn lab_colours_serialize_with_their_tag_and_keep_their_model() { let c = Color::lab(52.5, 70.0, -30.0); diff --git a/crates/doc/Cargo.toml b/crates/doc/Cargo.toml index 0ee88bf3b7..3a5626054b 100644 --- a/crates/doc/Cargo.toml +++ b/crates/doc/Cargo.toml @@ -8,6 +8,10 @@ description = "VectorCraft document model: artboards, layers, objects, appearanc [lints] workspace = true +[features] +# `vectorcraft_doc::blend::spines_built` for other crates' tests (dev-dependencies only). +spine-count = [] + [dependencies] vectorcraft-geom = { workspace = true } vectorcraft-color = { workspace = true } diff --git a/crates/doc/src/blend.rs b/crates/doc/src/blend.rs index b84de1cac3..c7c3e408b4 100644 --- a/crates/doc/src/blend.rs +++ b/crates/doc/src/blend.rs @@ -19,11 +19,11 @@ use std::f64::consts::PI; use std::sync::Arc; -use vectorcraft_color::{Color, Gradient, GradientPaint, GradientStop, Paint}; +use vectorcraft_color::{Color, Gradient, GradientMethod, GradientPaint, GradientSpread, GradientStop, Paint}; use vectorcraft_geom::kurbo::{ParamCurve, ParamCurveArclen, ParamCurveDeriv}; use vectorcraft_geom::{Affine, Anchor, BezPath, FillRule, PathData, Point, Rect, SubPath, Vec2}; -use crate::appearance::{AngleProfile, Appearance, AppearanceItem, Dash, PressureProfile, StrokeLayer, WidthProfile}; +use crate::appearance::{AngleProfile, Appearance, AppearanceItem, Dash, PressureProfile, StrokeGradientMode, StrokeLayer, WidthProfile}; use crate::live::{BlendOrientation, BlendSpacing, BlendSpec}; use crate::node::{Node, NodeId, NodeKind}; use crate::text::TextObject; @@ -45,7 +45,24 @@ fn lerp_f64(x: f64, y: f64, t: f64) -> f64 { x + (y - x) * t } -/// `like` with every stop painting `c`, linked as the solid is (`swatch` at `tint`). +/// The process plates between two stops linked to one spot swatch: each of C, M, Y and K in turn, +/// a stop without plates counting as none of each. The ends keep their own plates. +fn lerp_plates(a: Option<[f32; 4]>, b: Option<[f32; 4]>, t: f32) -> Option<[f32; 4]> { + if t <= 0.0 { + return a; + } + if t >= 1.0 { + return b; + } + if a.is_none() && b.is_none() { + return None; + } + let (a, b) = (a.unwrap_or_default(), b.unwrap_or_default()); + Some(std::array::from_fn(|i| lerp_f32(a[i], b[i], t))) +} + +/// `like` with every stop painting `c`, linked as the solid is (`swatch` at `tint`), with no +/// process plates (a solid has none). fn solid_gradient(c: Color, swatch: Option<&str>, tint: f32, like: &Gradient) -> Gradient { let mut g = like.clone(); for s in &mut g.stops { @@ -53,16 +70,22 @@ fn solid_gradient(c: Color, swatch: Option<&str>, tint: f32, like: &Gradient) -> s.opacity = 1.0; s.swatch = swatch.map(str::to_string); s.tint = tint; + s.plates = None; } g } -/// The swatch and tint `g` paints at `t`: a stop's own link, or the shared swatch of the two stops -/// around `t` at the tint between theirs (unlinked when they differ), as [`Gradient::sample_with`] walks. -fn link_at(g: &Gradient, t: f32) -> (Option, f32) { - let stops = &g.stops; - let link = |s: &GradientStop| (s.swatch.clone(), s.tint); - let Some(first) = stops.first() else { return (None, 1.0) }; +/// The swatch, tint and process plates `g` paints at `t`: a stop's own link, or the shared swatch +/// of the two stops around `t` at the tint and plates between theirs (unlinked when they differ), +/// as [`Gradient::sample_with`] walks. +fn link_at(g: &Gradient, t: f32) -> (Option, f32, Option<[f32; 4]>) { + link_in(&g.stops, t) +} + +/// [`link_at`] of a gradient's `stops`. +fn link_in(stops: &[GradientStop], t: f32) -> (Option, f32, Option<[f32; 4]>) { + let link = |s: &GradientStop| (s.swatch.clone(), s.tint, s.plates); + let Some(first) = stops.first() else { return (None, 1.0, None) }; if t <= first.offset { return link(first); } @@ -74,25 +97,42 @@ fn link_at(g: &Gradient, t: f32) -> (Option, f32) { let m = a.midpoint.clamp(0.01, 0.99); let v = if u < m { 0.5 * u / m } else { 0.5 + 0.5 * (u - m) / (1.0 - m) }; return match (&a.swatch, &b.swatch) { - (Some(x), Some(y)) if x == y => (Some(x.clone()), lerp_f32(a.tint, b.tint, v)), _ if v <= 0.0 => link(a), _ if v >= 1.0 => link(b), - _ => (None, 1.0), + (Some(x), Some(y)) if x == y => (Some(x.clone()), lerp_f32(a.tint, b.tint, v), lerp_plates(a.plates, b.plates, v)), + _ => (None, 1.0, None), }; } } - stops.last().map_or((None, 1.0), link) + stops.last().map_or((None, 1.0, None), link) } -/// `g` with its stops at `offsets`, each painting what `g` paints there (midpoints centred). +/// How close two places a gradient changes are for [`common_stops`] to give them one stop (two +/// where either gradient steps there: two of its stops at the same offset). +const STEP: f32 = 1e-4; + +/// `g` with its stops at `offsets`, each painting what `g` paints there (midpoints centred). An +/// offset given twice is a step: the second stop paints what `g` steps to there (the last of its +/// stops at one offset within [`STEP`] of it), or what it paints there when it does not step. fn resample_stops(g: &Gradient, offsets: &[f32]) -> Gradient { let mut out = g.clone(); out.stops = offsets .iter() - .map(|&o| { - let (color, opacity) = g.sample_keep_model(o); - let (swatch, tint) = link_at(g, o); - GradientStop { opacity, swatch, tint, ..GradientStop::new(o, color) } + .enumerate() + .map(|(i, &o)| { + let after = i.checked_sub(1).and_then(|j| offsets.get(j)) == Some(&o); + let stepped = + if after { g.stops.windows(2).rfind(|w| w[0].offset == w[1].offset && (w[0].offset - o).abs() < STEP).map(|w| &w[1]) } else { None }; + match stepped { + Some(s) => { + GradientStop { opacity: s.opacity, swatch: s.swatch.clone(), tint: s.tint, plates: s.plates, ..GradientStop::new(o, s.color) } + } + None => { + let (color, opacity) = g.sample_keep_model(o); + let (swatch, tint, plates) = link_at(g, o); + GradientStop { opacity, swatch, tint, plates, ..GradientStop::new(o, color) } + } + } }) .collect(); out @@ -111,7 +151,7 @@ fn gradient_breaks(g: &Gradient, out: &mut Vec) { } /// Two gradients of one kind with the same number of stops: as they are when the counts match, -/// else both resampled at every place either changes. +/// else both resampled at every place either changes, with two stops where either steps. fn common_stops(a: &Gradient, b: &Gradient) -> Option<(Gradient, Gradient)> { if a.kind != b.kind { return None; @@ -127,8 +167,22 @@ fn common_stops(a: &Gradient, b: &Gradient) -> Option<(Gradient, Gradient)> { gradient_breaks(b, &mut offs); offs.retain(|o| o.is_finite()); offs.sort_by(f32::total_cmp); - offs.dedup_by(|x, y| (*x - *y).abs() < 1e-4); - Some((resample_stops(a, &offs), resample_stops(b, &offs))) + offs.dedup_by(|x, y| (*x - *y).abs() < STEP); + let mut steps: Vec = + [a, b].into_iter().flat_map(|g| g.stops.windows(2).filter(|w| w[1].offset == w[0].offset).map(|w| w[0].offset)).collect(); + steps.sort_by(f32::total_cmp); + let mut at = Vec::with_capacity(offs.len() + steps.len()); + let mut k = 0; + for o in offs { + at.push(o); + while steps.get(k).is_some_and(|&s| s <= o - STEP) { + k += 1; + } + if steps.get(k).is_some_and(|&s| (s - o).abs() < STEP) { + at.push(o); + } + } + Some((resample_stops(a, &at), resample_stops(b, &at))) } fn lerp_gradient(a: &GradientPaint, b: &GradientPaint, t: f32) -> Option { @@ -139,16 +193,18 @@ fn lerp_gradient(a: &GradientPaint, b: &GradientPaint, t: f32) -> Option (Some(x.clone()), lerp_f32(sa.tint, sb.tint, t)), - _ => (None, 1.0), + // Stops on two tints of one swatch stay linked to it, as solids do (#3234), and keep + // the process plates printed with it. + let (swatch, tint, plates) = match (&sa.swatch, &sb.swatch) { + (Some(x), Some(y)) if x == y => (Some(x.clone()), lerp_f32(sa.tint, sb.tint, t), lerp_plates(sa.plates, sb.plates, t)), + _ => (None, 1.0, None), }; GradientStop { opacity: lerp_f32(sa.opacity, sb.opacity, t), midpoint: lerp_f32(sa.midpoint, sb.midpoint, t), swatch, tint, + plates, ..GradientStop::new(lerp_f32(sa.offset, sb.offset, t), lerp_color(&sa.color, &sb.color, t)) } }) @@ -606,13 +662,128 @@ fn reoriented(points: &[(f64, V)], o: Orient, at: impl Fn(f64) -> V, wr out } -/// A key's stroke read along its subpath turned as `o` says: its width profile (whose sides swap -/// when reversed), pen pressure, tilt, bearing and rotation, and on a reversed open path its -/// arrowheads. -fn reorient_stroke(s: &mut StrokeLayer, o: Orient) { +/// Gradient `g` laid along a closed subpath that now starts at fraction `s` of its length: the +/// part from `s` on runs first, then the part before it, stepping where the old start now falls. +/// The stops follow its colors as [`Gradient::span`] reads them, mixed linearly, and run once. +/// One of `g`'s own stops keeps its swatch link (each stop of a step its own), and a stop between +/// two of them the link [`link_at`] reads there. +fn gradient_from(g: &Gradient, s: f32) -> Gradient { + // A hue gradient that reflects unrolls through its curve, whose stops have no links: the links + // come from its own stops unrolled as a Classic gradient's, which keep them. + let hue_reflect = g.is_spread() && g.spread == GradientSpread::Reflect && g.method.is_hue(); + let classic = hue_reflect.then(|| Gradient { method: GradientMethod::Classic, ..g.clone() }); + let g = g.unrolled(); + let mut own = classic.as_ref().map_or_else(|| g.stops.clone(), |c| c.unrolled().stops.clone()); + own.sort_by(|a, b| a.offset.total_cmp(&b.offset)); + let mut stops = Vec::new(); + // The part from `s` to the end runs first, then the part up to `s`. + for (from, to, at) in [(s, 1.0, 0.0), (0.0, s, 1.0 - s)] { + // The first of `own` not yet matched: the parts' stops run in order, so the links are + // found in one pass. + let mut j = 0; + for (k, st) in g.span(from, to).stops.into_iter().enumerate() { + let p = from + (to - from) * st.offset; + while own.get(j).is_some_and(|o| o.offset <= p - STEP) { + j += 1; + } + let same = |i: usize| own.get(i).is_some_and(|o| o.color == st.color && o.opacity == st.opacity); + let near = (j..own.len()).take_while(|&i| own.get(i).is_some_and(|o| o.offset < p + STEP)); + let mut hit = near.clone().find(|&i| same(i)); + // A part starting on a step starts with the color after it, so its first stop takes + // the link of the step's last stop of that color. + if k == 0 + && let Some(at) = hit.and_then(|i| own.get(i)).map(|o| o.offset) + { + hit = near.filter(|&i| own.get(i).is_some_and(|o| o.offset == at) && same(i)).last().or(hit); + } + let (swatch, tint, plates) = match hit.and_then(|i| own.get(i).map(|o| (i, o))) { + Some((i, o)) => { + j = i + 1; + (o.swatch.clone(), o.tint, o.plates) + } + None => link_in(own.get(j.saturating_sub(1)..(j + 1).min(own.len())).unwrap_or_default(), p), + }; + stops.push(GradientStop { offset: at + (to - from) * st.offset, swatch, tint, plates, ..st }); + } + } + Gradient { stops, method: GradientMethod::Classic, spread: GradientSpread::Pad, repeats: 1, ..g.into_owned() } +} + +/// Dash pattern `d` read along subpaths of lengths `lens` turned as `o` says. Reversed, the +/// pattern runs backwards: from the start of a dash, that is the dash and then the other entries +/// in reverse order. Exact dashes also start where the turned subpaths now start. The pattern +/// restarts on every subpath at the one offset, so the offset moves only when every subpath needs +/// the same one (as subpaths whose lengths differ by whole periods do); dashes fitted to corners +/// ignore the offset, which stays as it is. A dash pattern starts once per subpath, so on a closed +/// subpath started elsewhere the dashes match the key's as far as its own start, and past it run +/// on without restarting there. +fn reorient_dash(d: &mut Dash, o: Orient, lens: &[f64]) { + if !d.is_dashed() || !d.offset.is_finite() { + return; + } + let mut pat = d.pattern.clone(); + // An odd pattern repeats twice per period (dash, gap, dash / gap, dash, gap). + if pat.len() % 2 == 1 { + pat.extend_from_within(..); + } + let period: f64 = pat.iter().sum(); + // Where along the key's own subpath the turned one starts (a closed one wraps round). A + // closed one reversed from its own start runs back from its end. + let at = match (o.closed, o.seam()) { + (true, s) if s == 0.0 && o.reversed => 1.0, + (true, s) => s, + (false, _) => o.start, + }; + let first = pat.first().copied().unwrap_or(0.0); + let offset = |len: f64| if o.reversed { first - at * len - d.offset } else { d.offset + at * len }; + let offsets: Vec = lens.iter().map(|&len| offset(len)).collect(); + let agree = offsets.first().is_some_and(|&a| { + offsets.iter().all(|&b| { + let r = (b - a).rem_euclid(period); + r.is_finite() && r.min(period - r) <= 1e-6 + }) + }); + if o.reversed { + if let Some(rest) = pat.get_mut(1..) { + rest.reverse(); + } + d.pattern = pat; + } + if let Some(&off) = offsets.first().filter(|_| agree && !d.align_corners) { + d.offset = off; + } +} + +/// A key's stroke read along its subpaths turned as `o` says (`lens`: their lengths): its width +/// profile (whose sides swap when reversed), pen pressure, tilt, bearing and rotation, its dashes, +/// a gradient along the path or across it (whose sides swap when reversed). Its arrowheads stay as +/// they are. +fn reorient_stroke(s: &mut StrokeLayer, o: Orient, lens: &[f64]) { if o.is_identity() { return; } + if let Some(d) = &mut s.dash { + reorient_dash(d, o, lens); + } + let along = s.gradient_mode == StrokeGradientMode::Along; + if s.path_gradient().is_some() + && let Paint::Gradient(g) = &mut s.paint + { + let start = along && o.seam() > 0.0; + if start { + g.gradient = gradient_from(&g.gradient, o.seam() as f32); + } + // Stops that reflect an even number of times read the same either way. + let (spread, runs) = g.gradient.painted_spread(); + let reverse = o.reversed && !(spread == GradientSpread::Reflect && runs % 2 == 0); + if reverse { + g.gradient.reverse(); + } + if start || reverse { + // The turned gradient is no longer the swatch's. + g.swatch = None; + } + } let same = |v: f64| v; if let Some(p) = &mut s.profile { let mut pts: Vec<(f64, (f64, f64))> = p.points.iter().map(|&(t, l, r)| (t, (l, r))).collect(); @@ -648,20 +819,58 @@ fn reorient_stroke(s: &mut StrokeLayer, o: Orient) { let out = reoriented(&p.points, o, |f| p.unwrapped_at(f), |v| v + turns, same); p.points = out; } - if o.reversed && !o.closed { - std::mem::swap(&mut s.start_arrow, &mut s.end_arrow); - s.arrow_scale = (s.arrow_scale.1, s.arrow_scale.0); - } } -/// `n` with every stroke read along its subpaths turned as `o` says. +/// `n` with every stroke read along its subpaths turned as `o` says, and on a reversed open path +/// its arrowheads swapped. fn reorient_strokes(n: &mut Node, o: Orient) { if o.is_identity() { return; } + let lens: Vec = + node_path(n).map(|(p, ..)| p.subpaths.iter().map(|sp| PathData::new(vec![sp.clone()]).length()).collect()).unwrap_or_default(); for it in n.appearance.items.iter_mut() { if let AppearanceItem::Stroke(s) = it { - reorient_stroke(s, o); + reorient_stroke(s, o, &lens); + if o.reversed && !o.closed { + std::mem::swap(&mut s.start_arrow, &mut s.end_arrow); + s.arrow_scale = (s.arrow_scale.1, s.arrow_scale.0); + } + } + } +} + +/// Turn the strokes of path or compound path `n` for Reverse Path Direction, before its subpaths +/// flagged in `reversed` are reversed with [`SubPath::reverse`] (a closed one then starts at its +/// last anchor): each stroke's width profile (sides swapped), pen pressure, tilt, bearing and +/// rotation then run the new way, so the stroke draws as it did. A compound path's subpaths are +/// its members' subpaths in order. A stroke reads one profile along every subpath, so it turns +/// only when all of them turn alike. Arrowheads stay at the path's start and end. +pub fn reverse_stroke_records(n: &mut Node, reversed: &[bool]) { + let subpaths: Vec<&SubPath> = match &n.kind { + NodeKind::Path { path, .. } => path.subpaths.iter().collect(), + NodeKind::Compound { children, .. } => children.iter().filter_map(|c| c.path_data()).flat_map(|pd| &pd.subpaths).collect(), + _ => return, + }; + let mut turns = subpaths.into_iter().enumerate().map(|(i, sp)| { + let mut o = Orient::of(sp); + if reversed.get(i).copied().unwrap_or(false) { + if sp.closed { + o.start_at(sp, sp.anchors.len().saturating_sub(1)); + } + o.reverse(); + } + o + }); + let Some(o) = turns.next() else { return }; + if o.is_identity() || !turns.all(|t| t.same_turn(&o)) { + return; + } + let lens: Vec = + node_path(n).map(|(p, ..)| p.subpaths.iter().map(|sp| PathData::new(vec![sp.clone()]).length()).collect()).unwrap_or_default(); + for it in n.appearance.items.iter_mut() { + if let AppearanceItem::Stroke(s) = it { + reorient_stroke(s, o, &lens); } } } @@ -1205,13 +1414,21 @@ pub fn blend_step_count(a: &Node, b: &Node, spacing: BlendSpacing, len: f64) -> // Spine // ===================================================================================== -#[cfg(test)] +#[cfg(any(test, feature = "spine-count"))] thread_local! { /// How many times [`Spine::new`] has run on this thread, for tests that count how often a path /// is flattened. pub(crate) static SPINES_BUILT: std::cell::Cell = const { std::cell::Cell::new(0) }; } +/// How many times [`Spine::new`] has run on this thread, for other crates' tests that count how +/// often a path is flattened (the `spine-count` feature, dev-dependencies only). +#[cfg(any(test, feature = "spine-count"))] +#[doc(hidden)] +pub fn spines_built() -> usize { + SPINES_BUILT.with(|n| n.get()) +} + /// A spine (the first subpath of a path) flattened to a polyline, with cumulative lengths and the /// arc length at each of its anchors. pub struct Spine { @@ -1230,7 +1447,7 @@ impl Spine { /// arc lengths, and the arc length at each anchor. `None` when `path` has no subpath, or when /// the first one flattens to fewer than two points (so it has no length to walk). pub fn new(path: &PathData) -> Option { - #[cfg(test)] + #[cfg(any(test, feature = "spine-count"))] SPINES_BUILT.with(|n| n.set(n.get() + 1)); let sp = path.subpaths.first()?; let mut pts: Vec = Vec::new(); @@ -2462,6 +2679,112 @@ mod tests { assert!(m.gradient.stops.iter().any(|s| s.swatch.is_none()), "{:?}", m.gradient.stops); } + /// A stop linked to the spot swatch "Spot" at `tint`, printed with process `plates`. + fn spot_stop(offset: f32, tint: f32, plates: Option<[f32; 4]>) -> GradientStop { + let mut stop = GradientStop::new(offset, Color::cmyk(1.0, 0.7, 0.0, 0.4).tinted(tint)); + stop.swatch = Some("Spot".into()); + stop.tint = tint; + stop.plates = plates; + stop + } + + fn gradient_paint(stops: Vec) -> Paint { + Paint::Gradient(Box::new(GradientPaint::new(Gradient { stops, ..Gradient::default() }))) + } + + fn assert_plates(got: Option<[f32; 4]>, want: [f32; 4]) { + let got = got.unwrap_or_else(|| panic!("plates {want:?}, not none")); + assert!(got.iter().zip(&want).all(|(g, w)| (g - w).abs() < 1e-5), "{got:?} != {want:?}"); + } + + #[test] + fn blend_gradient_spot_process_plates_interpolate() { + let (p, q) = ([0.2, 0.4, 0.0, 0.0], [0.6, 0.0, 0.8, 1.0]); + let a = gradient_paint(vec![spot_stop(0.0, 0.2, Some(p)), spot_stop(1.0, 0.2, Some(p))]); + let b = gradient_paint(vec![spot_stop(0.0, 1.0, Some(q)), spot_stop(1.0, 1.0, Some(q))]); + let Paint::Gradient(m) = lerp_paint(&a, &b, 0.25) else { panic!() }; + for s in &m.gradient.stops { + assert_eq!(s.swatch.as_deref(), Some("Spot")); + assert!((s.tint - 0.4).abs() < 1e-6, "{}", s.tint); + assert_plates(s.plates, [0.3, 0.3, 0.2, 0.25]); + } + // Without plates on either side the steps print the spot ink alone, as before. + let bare = |tint| gradient_paint(vec![spot_stop(0.0, tint, None), spot_stop(1.0, tint, None)]); + let Paint::Gradient(m) = lerp_paint(&bare(0.2), &bare(1.0), 0.5) else { panic!() }; + assert!(m.gradient.stops.iter().all(|s| s.plates.is_none()), "{:?}", m.gradient.stops); + } + + #[test] + fn resampled_gradient_spot_process_plates_interpolate() { + let (p, q, r) = ([0.0, 0.4, 0.0, 0.0], [0.6, 0.4, 0.3, 0.0], [0.2, 0.2, 0.2, 0.2]); + let mut first = spot_stop(0.0, 0.2, Some(p)); + first.midpoint = 0.25; + let two = Gradient { stops: vec![first, spot_stop(1.0, 0.8, Some(q))], ..Gradient::default() }; + let three = + Gradient { stops: vec![spot_stop(0.0, 1.0, Some(r)), spot_stop(0.5, 1.0, Some(r)), spot_stop(1.0, 1.0, Some(r))], ..Gradient::default() }; + let Some((ra, rb)) = common_stops(&two, &three) else { panic!() }; + let offsets: Vec = ra.stops.iter().map(|s| s.offset).collect(); + assert_eq!(offsets, [0.0, 0.25, 0.5, 1.0]); + // The original stops keep their plates; between them, the midpoint at 0.25 puts 0.5 two + // thirds of the way along the inks. + assert_eq!((ra.stops[0].plates, ra.stops[3].plates), (Some(p), Some(q))); + assert_plates(ra.stops[1].plates, [0.3, 0.4, 0.15, 0.0]); + assert_plates(ra.stops[2].plates, [0.4, 0.4, 0.2, 0.0]); + assert!((ra.stops[2].tint - 0.6).abs() < 1e-5, "{}", ra.stops[2].tint); + assert!(rb.stops.iter().all(|s| s.plates == Some(r)), "{:?}", rb.stops); + + let Paint::Gradient(m) = lerp_paint(&gradient_paint(two.stops), &gradient_paint(three.stops), 0.5) else { panic!() }; + assert_eq!(m.gradient.stops.len(), 4); + assert!(m.gradient.stops.iter().all(|s| s.swatch.as_deref() == Some("Spot")), "{:?}", m.gradient.stops); + assert_plates(m.gradient.stops[2].plates, [0.3, 0.3, 0.2, 0.1]); + } + + #[test] + fn blend_gradient_missing_plates_mean_zero() { + let p = [0.4, 0.8, 0.0, 0.2]; + let with = gradient_paint(vec![spot_stop(0.0, 1.0, Some(p)), spot_stop(1.0, 1.0, Some(p))]); + let without = gradient_paint(vec![spot_stop(0.0, 1.0, None), spot_stop(1.0, 1.0, None)]); + let Paint::Gradient(m) = lerp_paint(&without, &with, 0.25) else { panic!() }; + assert!(m.gradient.stops.iter().all(|s| s.swatch.as_deref() == Some("Spot")), "{:?}", m.gradient.stops); + m.gradient.stops.iter().for_each(|s| assert_plates(s.plates, [0.1, 0.2, 0.0, 0.05])); + // The ends keep their own plates. + let Paint::Gradient(m) = lerp_paint(&without, &with, 0.0) else { panic!() }; + assert!(m.gradient.stops.iter().all(|s| s.plates.is_none()), "{:?}", m.gradient.stops); + + // Another swatch, or an unlinked stop: process steps with no plates, as before. + let mut other = spot_stop(0.0, 1.0, Some(p)); + other.swatch = Some("Other".into()); + let other = gradient_paint(vec![other.clone(), GradientStop { offset: 1.0, ..other }]); + let mut plain = spot_stop(0.0, 1.0, None); + plain.swatch = None; + let plain = gradient_paint(vec![plain.clone(), GradientStop { offset: 1.0, ..plain }]); + for b in [&other, &plain] { + let Paint::Gradient(m) = lerp_paint(&with, b, 0.5) else { panic!() }; + assert!(m.gradient.stops.iter().all(|s| s.swatch.is_none() && s.plates.is_none()), "{:?}", m.gradient.stops); + } + } + + #[test] + fn blend_solid_to_spot_gradient_does_not_copy_plates() { + let p = [0.4, 0.8, 0.0, 0.2]; + let gradient = gradient_paint(vec![spot_stop(0.0, 1.0, Some(p)), spot_stop(1.0, 1.0, Some(p))]); + let Paint::Gradient(g) = &gradient else { panic!() }; + assert!(solid_gradient(Color::BLACK, Some("Spot"), 0.2, &g.gradient).stops.iter().all(|s| s.plates.is_none())); + let solid = Paint::Solid { color: Color::cmyk(1.0, 0.7, 0.0, 0.4).tinted(0.2), swatch: Some("Spot".into()), tint: 0.2 }; + // The solid's end has no plates: they grow from none toward the gradient's, both ways round. + for (a, b, t) in [(&solid, &gradient, 0.25), (&gradient, &solid, 0.75)] { + let Paint::Gradient(m) = lerp_paint(a, b, t) else { panic!() }; + for s in &m.gradient.stops { + assert_eq!(s.swatch.as_deref(), Some("Spot")); + assert!((s.tint - 0.4).abs() < 1e-6, "{}", s.tint); + assert_plates(s.plates, [0.1, 0.2, 0.0, 0.05]); + } + } + // A process solid unlinks the steps, and they take no plates. + let Paint::Gradient(m) = lerp_paint(&Paint::solid(Color::BLACK), &gradient, 0.5) else { panic!() }; + assert!(m.gradient.stops.iter().all(|s| s.swatch.is_none() && s.plates.is_none()), "{:?}", m.gradient.stops); + } + #[test] fn gradients_with_different_stop_counts_interpolate() { let g = |stops: &[(f32, Color)]| { @@ -2627,6 +2950,275 @@ mod tests { assert!((rot(0.5, 0.499) - rot(0.5, 0.501)).abs() < 1.0, "no jump where the key started: {:?}", stroke(&blend.at(0.5)).rotation); } + #[test] + fn stroke_gradients_and_dashes_turn_with_a_key_path_started_elsewhere() { + let keyed = |path: PathData, edit: &dyn Fn(&mut StrokeLayer)| { + let mut ap = Appearance::default(); + ap.set_stroke(Paint::solid(Color::BLACK)); + if let Some(s) = ap.stroke_mut() { + edit(s); + } + Node::path(NodeId(1), path, ap) + }; + let stroke = |n: &Node| n.appearance.stroke().cloned().unwrap_or_else(|| panic!("a stroke")); + // How light the stroke's gradient is at `u` (0 black, 3 white). + let light = |s: &StrokeLayer, u: f32| match &s.paint { + Paint::Gradient(g) => g.gradient.sample(u).0.to_rgb().iter().sum::(), + p => panic!("a gradient: {p:?}"), + }; + // Whether dash pattern `d` draws a dash `at` this far along its subpath. + let dash_at = |d: &Dash, at: f64| { + let p = if d.pattern.len() % 2 == 1 { d.pattern.repeat(2) } else { d.pattern.clone() }; + let mut x = (at + d.offset).rem_euclid(p.iter().sum()); + for (i, v) in p.iter().enumerate() { + if x < *v { + return i % 2 == 0; + } + x -= v; + } + false + }; + let graded = |mode: StrokeGradientMode| { + move |s: &mut StrokeLayer| { + s.paint = Paint::Gradient(Box::new(GradientPaint::new(Gradient::default()))); + s.gradient_mode = mode; + s.dash = Some(Dash { pattern: vec![1.0, 2.0, 3.0, 1.5], offset: 0.75, align_corners: false }); + } + }; + // An open key clicked at its last anchor runs the other way: a gradient along it or across + // it (whose sides swap) runs the other way too, and its dashes are read from its end. + let line = |x: f64| PathData::single(SubPath::polyline(&[Point::new(x, 0.0), Point::new(x + 13.0, 0.0)], false)); + let plain = keyed(line(0.0), &|_| {}); + for mode in [StrokeGradientMode::Along, StrokeGradientMode::Across] { + let key = keyed(line(100.0), &graded(mode)); + let s = stroke(&Lerp::new(&plain, &key, (None, Some(1))).at(1.0)); + assert!(light(&s, 0.0) < 0.01 && light(&s, 1.0) > 2.99, "{mode:?}: {:?}", s.paint); + let (own, d) = (stroke(&key).dash.unwrap_or_default(), s.dash.unwrap_or_default()); + for k in 1..130 { + let u = k as f64 / 10.0 + 0.03; + assert_eq!(dash_at(&d, u), dash_at(&own, 13.0 - u), "at {u}: {d:?}"); + } + } + // A closed key started half way round starts its gradient along it there too, stepping + // where its own start was, and its dashes start there. + let square = |x: f64| shapes::rectangle(Rect::new(x, 0.0, x + 10.0, 10.0)); + let key = keyed(square(100.0), &graded(StrokeGradientMode::Along)); + let s = stroke(&Lerp::new(&keyed(square(0.0), &|_| {}), &key, (Some(0), Some(2))).at(1.0)); + for (u, want) in [(0.0, 1.5), (0.25, 0.75), (0.499, 0.0), (0.501, 3.0), (0.75, 2.25), (1.0, 1.5)] { + assert!((light(&s, u) - want).abs() < 0.02, "at {u}: {} for {want}: {:?}", light(&s, u), s.paint); + } + let (own, d) = (stroke(&key).dash.unwrap_or_default(), s.dash.unwrap_or_default()); + for k in 1..200 { + let u = k as f64 / 10.0 + 0.03; + assert_eq!(dash_at(&d, u), dash_at(&own, u + 20.0), "at {u}: {d:?}"); + } + // A closed key that winds the other way runs the other way from the same anchor: its + // dashes are read back from the end of its own subpath, which is 40 long and not a whole + // number of periods. + let wound = |x: f64| { + let mut p = square(x); + for sp in &mut p.subpaths { + sp.reverse(); + } + p + }; + let back = keyed(wound(100.0), &graded(StrokeGradientMode::Along)); + let s = stroke(&Lerp::new(&keyed(square(0.0), &|_| {}), &back, (Some(0), Some(0))).at(1.0)); + let (own, d) = (stroke(&back).dash.unwrap_or_default(), s.dash.unwrap_or_default()); + for k in 1..400 { + let u = k as f64 / 10.0 + 0.03; + assert_eq!(dash_at(&d, u), dash_at(&own, 40.0 - u), "at {u}: {d:?}"); + } + // Stops that reflect twice read the same either way; a link to a swatch stays. + let reflected = keyed(line(100.0), &|s| { + let mut g = Gradient { spread: GradientSpread::Reflect, repeats: 2, ..Gradient::default() }; + g.stops[1].swatch = Some("Ink".into()); + s.paint = Paint::Gradient(Box::new(GradientPaint::new(g))); + s.gradient_mode = StrokeGradientMode::Along; + }); + assert_eq!(stroke(&Lerp::new(&plain, &reflected, (None, Some(1))).b).paint, stroke(&reflected).paint); + let linked = keyed(square(100.0), &|s| { + let mut g = Gradient::default(); + g.stops[1].swatch = Some("Ink".into()); + s.paint = Paint::Gradient(Box::new(GradientPaint::new(g))); + s.gradient_mode = StrokeGradientMode::Along; + }); + let s = stroke(&Lerp::new(&keyed(square(0.0), &|_| {}), &linked, (Some(0), Some(2))).b); + let links = match &s.paint { + Paint::Gradient(g) => g.gradient.stops.iter().filter(|st| st.swatch.as_deref() == Some("Ink")).map(|st| st.offset).collect::>(), + p => panic!("a gradient: {p:?}"), + }; + assert!(links.contains(&0.5), "the stop the old start ended on keeps its link: {:?}", s.paint); + // Each stop of a step keeps its own link. + let step = keyed(square(100.0), &|s| { + let mut g = Gradient::default(); + let (mut before, mut after) = (GradientStop::new(0.25, Color::BLACK), GradientStop::new(0.25, Color::WHITE)); + (before.swatch, after.swatch) = (Some("Ink".into()), Some("Paper".into())); + g.stops.splice(1..1, [before, after]); + s.paint = Paint::Gradient(Box::new(GradientPaint::new(g))); + s.gradient_mode = StrokeGradientMode::Along; + }); + let s = stroke(&Lerp::new(&keyed(square(0.0), &|_| {}), &step, (Some(0), Some(2))).b); + let links = match &s.paint { + Paint::Gradient(g) => g.gradient.stops.iter().filter(|st| st.offset == 0.75).map(|st| st.swatch.clone()).collect::>(), + p => panic!("a gradient: {p:?}"), + }; + assert_eq!(links, vec![Some("Ink".into()), Some("Paper".into())], "{:?}", s.paint); + // A step of one color between two swatches, where the turned subpath now starts: the + // start takes the link after the step and the end the link before it. + let seam_step = keyed(square(100.0), &|s| { + let mut g = Gradient::default(); + let gray = Color::rgb8(128, 128, 128); + let (mut before, mut after) = (GradientStop::new(0.5, gray), GradientStop::new(0.5, gray)); + (before.swatch, after.swatch) = (Some("Ink".into()), Some("Paper".into())); + g.stops.splice(1..1, [before, after]); + s.paint = Paint::Gradient(Box::new(GradientPaint::new(g))); + s.gradient_mode = StrokeGradientMode::Along; + }); + let s = stroke(&Lerp::new(&keyed(square(0.0), &|_| {}), &seam_step, (Some(0), Some(2))).b); + let ends = match &s.paint { + Paint::Gradient(g) => (g.gradient.stops.first().map(|st| st.swatch.clone()), g.gradient.stops.last().map(|st| st.swatch.clone())), + p => panic!("a gradient: {p:?}"), + }; + assert_eq!(ends, (Some(Some("Paper".into())), Some(Some("Ink".into()))), "{:?}", s.paint); + // A hue gradient that reflects keeps its links on the repeated stops. + let hue = keyed(square(100.0), &|s| { + let (mut red, mut blue) = + (GradientStop::new(0.0, Color::Rgb { r: 1.0, g: 0.0, b: 0.0 }), GradientStop::new(1.0, Color::Rgb { r: 0.0, g: 0.0, b: 1.0 })); + (red.swatch, blue.swatch) = (Some("Ink".into()), Some("Paper".into())); + let g = Gradient { + method: GradientMethod::HueClockwise, + spread: GradientSpread::Reflect, + repeats: 2, + ..Gradient::new(vectorcraft_color::GradientKind::Linear, vec![red, blue]) + }; + s.paint = Paint::Gradient(Box::new(GradientPaint::new(g))); + s.gradient_mode = StrokeGradientMode::Along; + }); + let s = stroke(&Lerp::new(&keyed(square(0.0), &|_| {}), &hue, (Some(0), Some(2))).b); + let linked = |name: &str| match &s.paint { + Paint::Gradient(g) => g.gradient.stops.iter().filter(|st| st.swatch.as_deref() == Some(name)).map(|st| st.offset).collect::>(), + p => panic!("a gradient: {p:?}"), + }; + assert!(linked("Paper").contains(&0.0) && linked("Paper").contains(&1.0), "{:?}", s.paint); + assert!(linked("Ink").contains(&0.5), "{:?}", s.paint); + // Two stops of one color at one place keep their own links, in reverse in a mirrored run. + let hue_step = keyed(square(100.0), &|s| { + let green = Color::Rgb { r: 0.0, g: 1.0, b: 0.0 }; + let (mut before, mut after) = (GradientStop::new(0.5, green), GradientStop::new(0.5, green)); + (before.swatch, after.swatch) = (Some("Ink".into()), Some("Paper".into())); + let stops = vec![ + GradientStop::new(0.0, Color::Rgb { r: 1.0, g: 0.0, b: 0.0 }), + before, + after, + GradientStop::new(1.0, Color::Rgb { r: 0.0, g: 0.0, b: 1.0 }), + ]; + let g = Gradient { + method: GradientMethod::HueClockwise, + spread: GradientSpread::Reflect, + repeats: 2, + ..Gradient::new(vectorcraft_color::GradientKind::Linear, stops) + }; + s.paint = Paint::Gradient(Box::new(GradientPaint::new(g))); + s.gradient_mode = StrokeGradientMode::Along; + }); + let s = stroke(&Lerp::new(&keyed(square(0.0), &|_| {}), &hue_step, (Some(0), Some(2))).b); + // The links at `u` in order, a link repeated by the next stop listed once. + let links_at = |u: f32| match &s.paint { + Paint::Gradient(g) => { + let mut links = + g.gradient.stops.iter().filter(|st| (st.offset - u).abs() < 1e-4).filter_map(|st| st.swatch.clone()).collect::>(); + links.dedup(); + links + } + p => panic!("a gradient: {p:?}"), + }; + assert_eq!(links_at(0.25), vec!["Paper".to_string(), "Ink".to_string()], "{:?}", s.paint); + assert_eq!(links_at(0.75), vec!["Ink".to_string(), "Paper".to_string()], "{:?}", s.paint); + // Where two runs meet, each run's stops keep their own links. + let hue_end = keyed(square(100.0), &|s| { + let green = Color::Rgb { r: 0.0, g: 1.0, b: 0.0 }; + let (mut a, mut b) = (GradientStop::new(1.0, green), GradientStop::new(1.0, green)); + (a.swatch, b.swatch) = (Some("Ink".into()), Some("Paper".into())); + let g = Gradient { + method: GradientMethod::HueClockwise, + spread: GradientSpread::Reflect, + repeats: 2, + ..Gradient::new(vectorcraft_color::GradientKind::Linear, vec![GradientStop::new(0.0, Color::Rgb { r: 1.0, g: 0.0, b: 0.0 }), a, b]) + }; + s.paint = Paint::Gradient(Box::new(GradientPaint::new(g))); + s.gradient_mode = StrokeGradientMode::Along; + }); + let s = stroke(&Lerp::new(&keyed(square(0.0), &|_| {}), &hue_end, (Some(0), Some(1))).b); + let links_at = |u: f32| match &s.paint { + Paint::Gradient(g) => { + let mut links = + g.gradient.stops.iter().filter(|st| (st.offset - u).abs() < 1e-4).filter_map(|st| st.swatch.clone()).collect::>(); + links.dedup(); + links + } + p => panic!("a gradient: {p:?}"), + }; + assert_eq!(links_at(0.25), vec!["Ink".to_string(), "Paper".to_string(), "Ink".to_string()], "{:?}", s.paint); + // Blended with a gradient of other stops, the steps keep that step. + let three = keyed(square(0.0), &|s| { + let mut g = Gradient::default(); + g.stops.insert(1, GradientStop::new(0.5, Color::BLACK)); + s.paint = Paint::Gradient(Box::new(GradientPaint::new(g))); + s.gradient_mode = StrokeGradientMode::Along; + }); + let s = stroke(&Lerp::new(&three, &key, (Some(0), Some(2))).at(0.75)); + assert!(light(&s, 0.501) - light(&s, 0.499) > 1.5, "{:?}", s.paint); + // Subpaths whose lengths call for different dash offsets keep the offset. + let rings = |x: f64, turn: usize| { + let mut inner = shapes::rectangle(Rect::new(x, 20.0, x + 7.0, 27.0)).subpaths.remove(0); + inner.anchors.rotate_left(turn); + PathData::new(vec![square(x).subpaths.remove(0), inner]) + }; + let key = keyed(rings(100.0, 2), &graded(StrokeGradientMode::Along)); + let blend = Lerp::new(&keyed(rings(0.0, 0), &|_| {}), &key, (Some(0), Some(2))); + let turned = match &blend.shape { + Shape::Path { pair, .. } => pair.orient.1, + _ => panic!("a path blend"), + }; + assert!((turned.seam() - 0.5).abs() < 1e-9, "both rings turn half way round: {turned:?}"); + let s = stroke(&blend.at(1.0)); + assert_eq!(s.dash.map(|d| d.offset), Some(0.75)); + } + + #[test] + fn gradients_of_other_stop_counts_keep_their_steps() { + let red = Color::Rgb { r: 1.0, g: 0.0, b: 0.0 }; + let stepped = Gradient::new( + vectorcraft_color::GradientKind::Linear, + vec![ + GradientStop::new(0.0, Color::WHITE), + GradientStop::new(0.5, Color::BLACK), + GradientStop::new(0.5, Color::WHITE), + GradientStop::new(0.50015, red), + GradientStop::new(1.0, Color::BLACK), + ], + ); + let (a, b) = common_stops(&stepped, &Gradient::default()).unwrap_or_else(|| panic!("one kind")); + let at = |g: &Gradient| g.stops.iter().map(|s| (s.offset, s.color)).collect::>(); + assert_eq!(at(&a), vec![(0.0, Color::WHITE), (0.5, Color::BLACK), (0.5, Color::WHITE), (0.50015, red), (1.0, Color::BLACK)]); + assert_eq!(b.stops.len(), 5); + assert_eq!(b.stops.get(1).map(|s| s.color), b.stops.get(2).map(|s| s.color), "a gradient without the step paints one color there"); + // A gradient with two stops close to the other's step, but no step of its own, does not step there. + let close = Gradient::new( + vectorcraft_color::GradientKind::Linear, + vec![ + GradientStop::new(0.0, Color::WHITE), + GradientStop::new(0.5, Color::BLACK), + GradientStop::new(0.50005, red), + GradientStop::new(1.0, Color::BLACK), + ], + ); + let (_, b) = common_stops(&stepped, &close).unwrap_or_else(|| panic!("one kind")); + assert_eq!(b.stops.get(1).map(|s| s.color), Some(Color::BLACK)); + assert_eq!(b.stops.get(2).map(|s| s.color), Some(Color::BLACK), "{:?}", b.stops); + } + #[test] fn odd_dash_blends_to_solid_with_closed_gaps() { let d = lerp_dash(Some(&Dash { pattern: vec![2.0, 3.0, 4.0], ..Default::default() }), None, 1.0).unwrap(); diff --git a/crates/doc/src/cmyk.rs b/crates/doc/src/cmyk.rs index ad52eea1a2..71c6642846 100644 --- a/crates/doc/src/cmyk.rs +++ b/crates/doc/src/cmyk.rs @@ -56,19 +56,114 @@ fn is_tiff(bytes: &[u8]) -> bool { bytes.starts_with(b"II*\0") || bytes.starts_with(b"MM\0*") } -/// The width and height of the first image of TIFF `bytes` when it has more strips or tiles than -/// the `tiff` decoder can count: strips per plane times planes past `u32::MAX`, or tiles per plane -/// times planes past `usize::MAX`. A file that stores one plane per channel (PlanarConfiguration 2) -/// has a plane for each channel; other files have one. The decoder multiplies these counts without -/// a check, which panics where overflow checks are on. Such an image, when it is at least a pixel -/// wide, claims at least 2^32 samples. -/// Where a tag repeats, the value giving the most strips or tiles counts. `None` for other images +/// What [`jpeg_frames`] found in a JPEG's headers. +enum Frames { + /// Every frame header declares a size the check accepts, or there is none. + Fit, + /// The width and height of the first frame header the check refuses. + Misfit(u16, u16), + /// The steps ran past [`MAX_JPEG_HEADER_STEPS`]. + OverBudget, +} + +/// Checks the width and height each 8-bit baseline, extended or progressive frame header in the +/// headers of a JPEG declares with `fits`. The JPEG is the bytes after its start-of-image marker: +/// `parts[0]` followed by `parts[1]`. The headers are read as the decoder reads them, up to the +/// first start-of-scan or end-of-image marker: every other marker is followed by its segment's +/// length, and bytes between segments are passed over, as are fill bytes (0xFF, and 0x00 after +/// one) before a marker. `steps` counts each byte looked at and each segment passed over. +fn jpeg_frames(parts: [&[u8]; 2], steps: &mut u64, fits: impl Fn(u16, u16) -> bool) -> Frames { + let byte = |i: usize| match i.checked_sub(parts[0].len()) { + None => parts[0].get(i).copied(), + Some(j) => parts[1].get(j).copied(), + }; + let u16_at = |i: usize| Some(u16::from_be_bytes([byte(i)?, byte(i.checked_add(1)?)?])); + let mut p = 0usize; + loop { + *steps += 1; + if *steps > MAX_JPEG_HEADER_STEPS { + return Frames::OverBudget; + } + let Some(b) = byte(p) else { return Frames::Fit }; + p += 1; + if b != 0xFF { + continue; + } + while matches!(byte(p), Some(0xFF | 0)) { + p += 1; + *steps += 1; + if *steps > MAX_JPEG_HEADER_STEPS { + return Frames::OverBudget; + } + } + let Some(marker) = byte(p) else { return Frames::Fit }; + p += 1; + if matches!(marker, 0xDA | 0xD9) { + return Frames::Fit; + } + // Length (2 bytes), then for a frame header its precision, height and width. + let Some(len) = u16_at(p) else { return Frames::Fit }; + if matches!(marker, 0xC0..=0xC2) + && byte(p.saturating_add(2)) == Some(8) + && let (Some(h), Some(w)) = (u16_at(p.saturating_add(3)), u16_at(p.saturating_add(5))) + && !fits(w, h) + { + return Frames::Misfit(w, h); + } + if len < 2 { + return Frames::Fit; + } + p = p.saturating_add(usize::from(len)); + } +} + +/// Most strips or tiles the first image of a TIFF may have: VectorCraft's own limit, 1/1024 of +/// [`crate::MAX_RASTER_ALLOC`] (524,288 in the web app, 2,097,152 on the desktop). The decoder +/// reads an offset and a byte count of 8 bytes each for every one into memory before anything else. +pub const MAX_TIFF_CHUNKS: u64 = crate::MAX_RASTER_ALLOC / 1024; + +/// Most pixels the JPEG of a JPEG-compressed TIFF tile may declare when it declares more pixels +/// than the whole image has: VectorCraft's own limit (2048 × 2048, 16 MB as CMYK). +pub const MAX_JPEG_TILE_PIXELS: u64 = 1 << 22; + +/// Most steps reading the JPEG headers of a TIFF's strips or tiles may take (a byte looked at, a +/// segment passed over or a strip offset read): VectorCraft's own limit. +const MAX_JPEG_HEADER_STEPS: u64 = 1 << 24; + +/// The width and height of the first image of TIFF or BigTIFF `bytes` when it has more strips or +/// tiles than the `tiff` decoder can count: strips per plane times planes past `u32::MAX`, or tiles +/// per plane times planes past `usize::MAX`. A file that stores one plane per channel +/// (PlanarConfiguration 2) has a plane for each channel; other files have one. The decoder +/// multiplies these counts without a check, which panics where overflow checks are on. Such an +/// image, when it is at least a pixel wide, claims at least 2^32 samples. +/// It also gives them for an image with more than [`MAX_TIFF_CHUNKS`] strips or tiles, counted from +/// its size or from the number of values its StripOffsets and StripByteCounts tags hold, or its +/// TileOffsets and TileByteCounts tags for a tiled image. An image the decoder reads as strips (it +/// has both strip tables and neither tile table) counts strips, and one it reads as tiles counts +/// tiles; the decoder refuses an image with any other mix of these tags before it reads a table. +/// For a JPEG-compressed image (Compression 7) it gives the width and height a strip's or tile's +/// JPEG declares in a frame header (in the JPEGTables, or in the strip or tile before its first +/// scan) when they are wider or taller than the strip or tile, or, for a tile, when they make more +/// than [`MAX_JPEG_TILE_PIXELS`] pixels and more than the image has. The decoder allocates the +/// pixels the JPEG declares. It gives the image's width and height when reading those headers +/// takes more than 16,777,216 steps (a byte looked at, a segment passed over or a strip offset +/// read), when the strip or tile offsets are of a type other than BYTE, UNDEFINED, SHORT, LONG, +/// IFD, LONG8 or IFD8, and when the image's width and height, a striped image's RowsPerStrip or a +/// tiled image's tile size isn't a single value of one of those types. +/// Where a tag repeats, the value giving the most strips or tiles counts, and the JPEG check uses +/// the last entry of a field type the decoder knows, as the decoder does. `None` for other images /// and for bytes that aren't a TIFF. pub fn oversized_tiff(bytes: &[u8]) -> Option<(u32, u32)> { - let le = bytes.starts_with(b"II*\0"); - if !le && !bytes.starts_with(b"MM\0*") { + let le = bytes.starts_with(b"II"); + let head = bytes.get(..4)?; + // A BigTIFF counts and points with 8 bytes where a TIFF uses 4, so its entries are 20 bytes. + let big = if head == b"II*\0" || head == b"MM\0*" { + false + } else if head == b"II+\0" || head == b"MM\0+" { + true + } else { return None; - } + }; let u16_at = |at: usize| -> Option { let b: [u8; 2] = bytes.get(at..at.checked_add(2)?)?.try_into().ok()?; Some(if le { u16::from_le_bytes(b) } else { u16::from_be_bytes(b) }) @@ -77,32 +172,71 @@ pub fn oversized_tiff(bytes: &[u8]) -> Option<(u32, u32)> { let b: [u8; 4] = bytes.get(at..at.checked_add(4)?)?.try_into().ok()?; Some(if le { u32::from_le_bytes(b) } else { u32::from_be_bytes(b) }) }; - let ifd = usize::try_from(u32_at(4)?).ok()?; - // (tag, the entry's single BYTE, SHORT, LONG or IFD value, which sits in the entry, or its - // single LONG8 or IFD8 value that fits in 32 bits, which sits where the entry points) - let entry = |i: usize| -> Option<(u16, Option)> { - let e = ifd.checked_add(i.checked_mul(12)?.checked_add(2)?)?; - let (ty, count, at) = (u16_at(e.checked_add(2)?)?, u32_at(e.checked_add(4)?)?, e.checked_add(8)?); - let value = match (ty, count) { - (1, 1) => bytes.get(at).map(|&b| u32::from(b)), - (3, 1) => u16_at(at).map(u32::from), - (4 | 13, 1) => u32_at(at), - (16 | 18, 1) => { - let at = usize::try_from(u32_at(at)?).ok()?; - let (lo, hi) = (u32_at(at)?, u32_at(at.checked_add(4)?)?); - let wide = if le { u64::from(hi) << 32 | u64::from(lo) } else { u64::from(lo) << 32 | u64::from(hi) }; - u32::try_from(wide).ok() - } + let u64_at = |at: usize| -> Option { + let b: [u8; 8] = bytes.get(at..at.checked_add(8)?)?.try_into().ok()?; + Some(if le { u64::from_le_bytes(b) } else { u64::from_be_bytes(b) }) + }; + let word_len: usize = if big { 8 } else { 4 }; + let word = |at: usize| if big { u64_at(at) } else { u32_at(at).map(u64::from) }; + // The bytes one value of each field type takes; 0 for types the decoder doesn't know. + let width_of = |ty: u16| -> usize { + match ty { + 1 | 2 | 6 | 7 => 1, + 3 | 8 => 2, + 4 | 9 | 11 | 13 => 4, + 5 | 10 | 12 | 16..=18 => 8, + _ => 0, + } + }; + let ifd = usize::try_from(word(if big { 8 } else { 4 })?).ok()?; + let entries = if big { u64_at(ifd)? } else { u64::from(u16_at(ifd)?) }; + let first = ifd.checked_add(if big { 8 } else { 2 })?; + // (tag, field type, number of values, where the values are: in the entry when they fit in its + // last word, otherwise where that word points) + let entry = |i: usize| -> Option<(u16, u16, u64, Option)> { + let e = first.checked_add(i.checked_mul(4 + 2 * word_len)?)?; + let (tag, ty, count) = (u16_at(e)?, u16_at(e.checked_add(2)?)?, word(e.checked_add(4)?)?); + let at = e.checked_add(4 + word_len)?; + let fits = u64::try_from(width_of(ty)).ok()?.checked_mul(count).is_some_and(|n| n <= word_len as u64); + let values = if fits { Some(at) } else { word(at).and_then(|p| usize::try_from(p).ok()) }; + Some((tag, ty, count, values)) + }; + // Value `i` of an entry's BYTE, UNDEFINED, SHORT, LONG, IFD, LONG8 or IFD8 values at `at`. + let nth = |ty: u16, at: usize, i: u64| -> Option { + let p = at.checked_add(usize::try_from(i).ok()?.checked_mul(width_of(ty))?)?; + match ty { + 1 | 7 => bytes.get(p).map(|&b| u64::from(b)), + 3 => u16_at(p).map(u64::from), + 4 | 13 => u32_at(p).map(u64::from), + 16 | 18 => u64_at(p), _ => None, - }; - Some((u16_at(e)?, value)) + } }; let (mut width, mut height, mut planes, mut planar) = (0u32, 0u32, 1u32, false); let (mut rows, mut tile_w, mut tile_h) = (None::, None::, None::); + // The most values a strip table and a tile table hold. + let (mut strip_chunks, mut tile_chunks) = (0u64, 0u64); + // The decoder keeps the last entry of a tag whose field type it knows. These are the last such + // entries (type, count, where) of the tags `LAST` lists. + const LAST: [u16; 11] = [256, 257, 259, 278, 322, 323, 273, 279, 324, 325, 347]; + let mut last = [None::<(u16, u64, Option)>; LAST.len()]; let least = |was: Option, v: u32| Some(was.map_or(v, |w| w.min(v))); - for i in 0..usize::from(u16_at(ifd)?) { - let Some((tag, value)) = entry(i) else { break }; - let Some(v) = value else { continue }; + // The entry's single BYTE, UNDEFINED, SHORT, LONG or IFD value, or its single LONG8 or IFD8 + // value when that fits in 32 bits. + let single = |ty: u16, count: u64, at: Option| at.filter(|_| count == 1).and_then(|at| nth(ty, at, 0)).and_then(|v| u32::try_from(v).ok()); + for i in 0..usize::try_from(entries).unwrap_or(usize::MAX) { + let Some((tag, ty, count, at)) = entry(i) else { break }; + match tag { + 273 | 279 => strip_chunks = strip_chunks.max(count), + 324 | 325 => tile_chunks = tile_chunks.max(count), + _ => {} + } + if width_of(ty) > 0 + && let Some(slot) = LAST.iter().position(|&t| t == tag).and_then(|k| last.get_mut(k)) + { + *slot = Some((ty, count, at)); + } + let Some(v) = single(ty, count, at) else { continue }; match tag { 256 => width = width.max(v), 257 => height = height.max(v), @@ -115,29 +249,107 @@ pub fn oversized_tiff(bytes: &[u8]) -> Option<(u32, u32)> { } } let planes = if planar { u128::from(planes) } else { 1 }; - let tiles = match (tile_w, tile_h) { - (Some(tw @ 1..), Some(th @ 1..)) => u128::from(width.div_ceil(tw)) * u128::from(height.div_ceil(th)) * planes > usize::MAX as u128, - _ => false, + let tiled = match (tile_w, tile_h) { + (Some(tw @ 1..), Some(th @ 1..)) => u128::from(width.div_ceil(tw)) * u128::from(height.div_ceil(th)) * planes, + _ => 0, }; + let tiles = tiled > usize::MAX as u128; let rows = rows.unwrap_or(height); - let strips = rows > 0 && u128::from(height.saturating_sub(1) / rows + 1) * planes > u128::from(u32::MAX); - (tiles || strips).then_some((width, height)) + let striped = height.saturating_sub(1).checked_div(rows).map_or(0, |n| u128::from(n + 1) * planes); + let strips = striped > u128::from(u32::MAX); + if tiles || strips { + return Some((width, height)); + } + let last_of = |tag: u16| LAST.iter().position(|&t| t == tag).and_then(|k| last.get(k).copied().flatten()); + // The single value the decoder reads from the last entry of `tag`: `None` without one, and + // `Some(None)` when that entry doesn't hold a single value read here. + let value_of = |tag: u16| last_of(tag).map(|(ty, count, at)| single(ty, count, at)); + // The decoder reads strips when the image has both strip tables and neither tile table, tiles + // in the opposite case, and refuses every other image before it reads a table. + let layout = match [273, 279, 324, 325].map(|tag| last_of(tag).is_some()) { + [true, true, false, false] => Some((273, striped.max(u128::from(strip_chunks)))), + [false, false, true, true] => Some((324, tiled.max(u128::from(tile_chunks)))), + _ => None, + }; + let (offsets_tag, chunks) = layout?; + if chunks > u128::from(MAX_TIFF_CHUNKS) { + return Some((width, height)); + } + if value_of(259) != Some(Some(7)) { + return None; + } + // The JPEG check uses the sizes the decoder reads. A size it needs that isn't a single value + // read here refuses the image. + let (Some(Some(w_img)), Some(Some(h_img))) = (value_of(256), value_of(257)) else { return Some((width, height)) }; + let tile = offsets_tag == 324; + // RowsPerStrip, which the decoder reads only for strips. + let rows = if tile { Some(h_img) } else { value_of(278).unwrap_or(Some(h_img)) }; + let Some(rows) = rows else { return Some((width, height)) }; + let (tw, th) = match (value_of(322).flatten(), value_of(323).flatten()) { + (Some(tw), Some(th)) => (tw, th), + _ if tile => return Some((width, height)), + _ => (0, 0), + }; + // A strip is as wide as the image and RowsPerStrip tall (at most the image's height); a tile's + // JPEG may be as large as the tile, which the edge tiles of the image overhang. + let fits = |w: u16, h: u16| { + let (w, h) = (u32::from(w), u32::from(h)); + if tile { + let pixels = u64::from(w) * u64::from(h); + w <= tw && h <= th && (pixels <= MAX_JPEG_TILE_PIXELS || pixels <= u64::from(w_img) * u64::from(h_img)) + } else { + w <= w_img && h <= rows.min(h_img) + } + }; + // The decoder reads the JPEGTables after their start-of-image marker and without their last two + // bytes, followed by each strip or tile after its first two bytes; without JPEGTables, each + // strip or tile after its start-of-image marker. + let tables = last_of(347) + .and_then(|(_, count, at)| { + let at = at?; + let end = at.checked_add(usize::try_from(count).ok()?)?.min(bytes.len()); + bytes.get(at.checked_add(2)?..end.checked_sub(2)?) + }) + .unwrap_or_default(); + let (ty, count, at) = last_of(offsets_tag)?; + let at = at?; + // The decoder also takes offsets of other types (a RATIONAL or ASCII value), which aren't read + // here: such an image is refused. + if !matches!(ty, 1 | 3 | 4 | 7 | 13 | 16 | 18) { + return Some((width, height)); + } + let mut steps = 0u64; + for i in 0..count { + steps += 1; + let Some(at) = nth(ty, at, i).and_then(|o| usize::try_from(o).ok()) else { break }; + let part = bytes.get(at.saturating_add(2)..).unwrap_or_default(); + match jpeg_frames([tables, part], &mut steps, fits) { + Frames::Fit => {} + Frames::Misfit(w, h) => return Some((u32::from(w), u32::from(h))), + Frames::OverBudget => return Some((width, height)), + } + } + None +} + +/// The decoder of TIFF `bytes`' first image; `None` for other bytes and [`oversized_tiff`] images. +fn tiff_decoder(bytes: &[u8]) -> Option>> { + if !is_tiff(bytes) || oversized_tiff(bytes).is_some() { + return None; + } + tiff::decoder::Decoder::new(Cursor::new(bytes)).ok() } /// The color type of TIFF `bytes` and its decoder; `None` for [`oversized_tiff`] images too. pub(crate) fn tiff(bytes: &[u8]) -> Option<(tiff::ColorType, tiff::decoder::Decoder>)> { - if !is_tiff(bytes) || oversized_tiff(bytes).is_some() { - return None; - } - let mut d = tiff::decoder::Decoder::new(Cursor::new(bytes)).ok()?; + let mut d = tiff_decoder(bytes)?; Some((d.colortype().ok()?, d)) } /// The Orientation tag of TIFF `bytes`' first image, of any unsigned type; `None` for other images -/// and TIFFs without one. Reads only its header. +/// and TIFFs without one. Reads only its header, for any color type. pub fn tiff_orientation(bytes: &[u8]) -> Option { - let (_, mut d) = tiff(bytes)?; - d.find_tag_unsigned::(tiff::tags::Tag::Orientation).ok().flatten() + tiff_decoder(bytes)?.find_tag_unsigned::(tiff::tags::Tag::Orientation).ok().flatten() } /// The EXIF orientation of encoded image `bytes` when it turns or flips the pixels; `None` when @@ -155,8 +367,160 @@ pub fn exif_orientation(bytes: &[u8]) -> Option { decoded().or_else(tagged).filter(|o| *o != Orientation::NoTransforms) } +/// TIFF bytes as a reader sees them with some of them replaced: each patch is an offset and the +/// bytes read there instead, at most four, in order of offset without overlaps. The file is not +/// copied. +struct Patched<'a> { + bytes: Cursor<&'a [u8]>, + patches: Vec<(usize, &'static [u8])>, +} + +impl std::io::Read for Patched<'_> { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + let start = usize::try_from(self.bytes.position()).unwrap_or(usize::MAX); + let read = std::io::Read::read(&mut self.bytes, buf)?; + let got = buf.get_mut(..read).unwrap_or_default(); + let end = start.saturating_add(read); + // The patches are in order and apart, and each is at most four bytes long. + let first = self.patches.partition_point(|&(at, _)| at.saturating_add(4) <= start); + for &(at, with) in self.patches.get(first..).unwrap_or_default().iter().take_while(|&&(at, _)| at < end) { + for (k, &b) in with.iter().enumerate() { + if let Some(slot) = at.checked_add(k).and_then(|i| i.checked_sub(start)).and_then(|i| got.get_mut(i)) { + *slot = b; + } + } + } + Ok(read) + } +} + +impl std::io::Seek for Patched<'_> { + fn seek(&mut self, to: std::io::SeekFrom) -> std::io::Result { + std::io::Seek::seek(&mut self.bytes, to) + } +} + +/// TIFF `bytes` read with the PhotometricInterpretation (tag 262) of their first image set to 1 +/// (black is zero) in each of its entries that holds one SHORT or LONG value. The decoder gives +/// every sample of a grayscale image's pixels, in the order the file stores them, where it gives a +/// CMYK image's inks and at most the first extra sample, and doesn't read a white-is-zero image +/// with extra samples. `None` for bytes that aren't a TIFF and when the first image has no such +/// entry. +fn as_black_is_zero(bytes: &[u8]) -> Option> { + let le = bytes.starts_with(b"II*\0"); + if !le && !bytes.starts_with(b"MM\0*") { + return None; + } + let u16_at = |at: usize| -> Option { + let b: [u8; 2] = bytes.get(at..at.checked_add(2)?)?.try_into().ok()?; + Some(if le { u16::from_le_bytes(b) } else { u16::from_be_bytes(b) }) + }; + let u32_at = |at: usize| -> Option { + let b: [u8; 4] = bytes.get(at..at.checked_add(4)?)?.try_into().ok()?; + Some(if le { u32::from_le_bytes(b) } else { u32::from_be_bytes(b) }) + }; + let ifd = usize::try_from(u32_at(4)?).ok()?; + let mut patches = Vec::new(); + for i in 0..usize::from(u16_at(ifd)?) { + let e = ifd.checked_add(i.checked_mul(12)?.checked_add(2)?)?; + let (Some(tag), Some(ty), Some(count)) = (u16_at(e), u16_at(e.checked_add(2)?), u32_at(e.checked_add(4)?)) else { break }; + if tag != 262 || count != 1 { + continue; + } + // The value sits in the entry, in the file's byte order. + let one: &'static [u8] = match (ty, le) { + (3, true) => &[1, 0], + (3, false) => &[0, 1], + (4, true) => &[1, 0, 0, 0], + (4, false) => &[0, 0, 0, 1], + _ => continue, + }; + let at = e.checked_add(8)?; + bytes.get(at..at.checked_add(one.len())?)?; + patches.push((at, one)); + } + (!patches.is_empty()).then(|| Patched { bytes: Cursor::new(bytes), patches }) +} + +/// The ExtraSamples values of the image `d` reads, one for each sample after its color, in order: +/// 0 not alpha, 1 associated alpha, 2 unassociated alpha. Empty without the tag. +fn extra_samples(d: &mut tiff::decoder::Decoder>) -> Vec { + d.find_tag_unsigned_vec::(tiff::tags::Tag::ExtraSamples).ok().flatten().unwrap_or_default() +} + +/// Does `kind`, the color type of the TIFF `d` reads, hold inks that Open and Place keep: CMYK of 8 +/// or 16 bits, with no extra sample that the file names as alpha? The decoder gives a CMYK color +/// type to a file whose alpha follows another extra sample. [`ImageBlob::cmyk`] reads the inks of +/// such a file all the same: a document saved with one as a CMYK image keeps it. +fn cmyk_inks(kind: tiff::ColorType, d: &mut tiff::decoder::Decoder>) -> bool { + matches!(kind, tiff::ColorType::CMYK(8 | 16)) && !extra_samples(d).iter().any(|e| matches!(e, 1 | 2)) +} + +/// Most samples a pixel of a TIFF is read with, its color and extra samples included, as the +/// file's SamplesPerPixel counts them: VectorCraft's own limit. +const MAX_EXTRA_SAMPLES_PIXEL: usize = 64; + +/// The bytes of the row the decoder of the TIFF `d` reads takes before it reads each strip or tile +/// of a file that stores a pixel's samples together and has more of them (its SamplesPerPixel) +/// than the decoder gives: one row of the strip or tile, every sample of each pixel. 0 for other +/// files. `None` when the file has more than [`MAX_EXTRA_SAMPLES_PIXEL`] samples a pixel, when its +/// samples aren't unsigned integers (a SampleFormat other than 1, which the readers don't take, and +/// which the floating-point predictor needs) and when its color type isn't read. Reads only the +/// file's tags. +fn row_buffer(d: &mut tiff::decoder::Decoder) -> Option { + use tiff::tags::Tag; + let kind = d.colortype().ok()?; + let all = d.find_tag_unsigned::(Tag::SamplesPerPixel).ok()?.unwrap_or(1); + if usize::from(all) > MAX_EXTRA_SAMPLES_PIXEL { + return None; + } + if d.find_tag_unsigned_vec::(Tag::SampleFormat).ok()?.is_some_and(|f| f.iter().any(|&f| f != 1)) { + return None; + } + if all <= kind.num_samples() || planar(d) { + return Some(0); + } + // A strip is as wide as the image, a tile as its TileWidth. + let width = match d.get_chunk_type() { + tiff::decoder::ChunkType::Tile => d.find_tag_unsigned::(Tag::TileWidth).ok()??, + tiff::decoder::ChunkType::Strip => d.dimensions().ok()?.0, + }; + u64::from(width).checked_mul(u64::from(all))?.checked_mul(u64::from(kind.bit_depth().div_ceil(8))) +} + +/// `d`, the decoder of a TIFF of `file` bytes, set to decode `n` pixels of `per` samples of `bits` +/// bits each into RGBA. `None` when the file has more than [`MAX_EXTRA_SAMPLES_PIXEL`] samples a +/// pixel, when its samples aren't unsigned integers (a SampleFormat other than 1), and when the +/// decoded samples, the copy that puts a planar file's samples pixel by pixel, the row the decoder +/// reads each strip or tile into ([`row_buffer`]) and the RGBA pixels together take more than +/// [`crate::MAX_RASTER_ALLOC`]. The decoder may then decode no more than those samples, and read no +/// strip or tile of more compressed bytes than the file holds (nor more than its own limit of +/// 128 MiB). +fn with_room( + mut d: tiff::decoder::Decoder, + file: usize, + n: usize, + per: usize, + bits: u8, +) -> Option> { + if per > MAX_EXTRA_SAMPLES_PIXEL { + return None; + } + let row = row_buffer(&mut d)?; + let need = n.checked_mul(per)?.checked_mul(usize::from(bits.div_ceil(8)))?; + let copies = if per > 1 && planar(&mut d) { 2 } else { 1 }; + let peak = u64::try_from(need).ok()?.checked_mul(copies)?.checked_add(u64::try_from(n).ok()?.checked_mul(4)?)?.checked_add(row)?; + if peak > crate::MAX_RASTER_ALLOC { + return None; + } + let mut limits = tiff::decoder::Limits::default(); + limits.decoding_buffer_size = need; + limits.intermediate_buffer_size = limits.intermediate_buffer_size.min(file); + Some(d.with_limits(limits)) +} + /// Does the TIFF `d` reads store one plane per channel (PlanarConfiguration 2)? -fn planar(d: &mut tiff::decoder::Decoder>) -> bool { +fn planar(d: &mut tiff::decoder::Decoder) -> bool { d.find_tag_unsigned::(tiff::tags::Tag::PlanarConfiguration).ok().flatten().is_some_and(|p| p != 1) } @@ -164,7 +528,10 @@ fn planar(d: &mut tiff::decoder::Decoder>) -> bool { /// type has), pixel by pixel and 8 bits each (16-bit samples to their high byte), whether the file /// stores each pixel's samples together or one plane per channel. `None` when they don't decode to /// that many samples, which includes images whose planes together need more than the decoder's -/// limit (256 MB of samples). +/// limit (256 MiB of samples), and, before any decoding, files with more than +/// [`MAX_EXTRA_SAMPLES_PIXEL`] samples a pixel, files whose samples aren't unsigned integers (a +/// SampleFormat other than 1) and ones whose samples with the row the decoder reads each strip or +/// tile into ([`row_buffer`]) take more than [`crate::MAX_RASTER_ALLOC`]. pub(crate) fn read_samples(d: &mut tiff::decoder::Decoder>, n: usize, per: usize) -> Option> { Some(match read_samples_at_depth(d, n, per)? { Samples::Eight(v) => v, @@ -196,7 +563,20 @@ enum SampleSlice<'a> { } /// [`read_samples`], keeping 16-bit samples at 16 bits. -fn read_samples_at_depth(d: &mut tiff::decoder::Decoder>, n: usize, per: usize) -> Option { +fn read_samples_at_depth(d: &mut tiff::decoder::Decoder, n: usize, per: usize) -> Option { + // Checked from the tags, before anything is decoded. + let row = row_buffer(d)?; + let bytes = u64::from(d.colortype().ok()?.bit_depth().div_ceil(8)); + let need = u64::try_from(n).ok()?.checked_mul(u64::try_from(per).ok()?)?.checked_mul(bytes)?; + if need.checked_add(row)? > crate::MAX_RASTER_ALLOC { + return None; + } + decode_samples(d, n, per) +} + +/// [`read_samples_at_depth`] without its checks, for a decoder that [`with_room`] made. Its tags +/// can't be read once its limits are set: the decoder holds a tag's values to its decoding limit. +fn decode_samples(d: &mut tiff::decoder::Decoder, n: usize, per: usize) -> Option { let mut buf = tiff::decoder::DecodingResult::U8(Vec::new()); let layout = d.read_image_to_buffer(&mut buf).ok()?; match buf { @@ -207,7 +587,8 @@ fn read_samples_at_depth(d: &mut tiff::decoder::Decoder>, n: usize } /// `data`, the samples of `n` pixels, `per` to a pixel, stored in `planes` planes, as the samples -/// pixel by pixel; `None` when it doesn't hold that many samples or a plane per sample. +/// pixel by pixel; `None` when it doesn't hold that many samples or a plane per sample. The copy +/// of a planar file's samples is allocated once, at its length. fn chunky(data: Vec, planes: usize, n: usize, per: usize) -> Option> { if Some(data.len()) != n.checked_mul(per) { return None; @@ -219,7 +600,13 @@ fn chunky(data: Vec, planes: usize, n: usize, per: usize) -> Option< return None; } let planes: Vec<&[T]> = data.chunks_exact(n).collect(); - Some((0..n).flat_map(|i| planes.iter().filter_map(move |p| p.get(i).copied())).collect()) + let mut out = Vec::with_capacity(data.len()); + for i in 0..n { + for p in &planes { + out.push(*p.get(i)?); + } + } + Some(out) } /// The color space an ICC profile's header names (bytes 16 to 19, such as `RGB `, `GRAY` or @@ -265,10 +652,14 @@ struct CmykSource { } /// The samples of CMYK TIFF `bytes` (8 or 16 bits), their inks together or one plane per ink, with -/// the TIFF's CMYK ICC profile; `None` for other images and ones larger than [`MAX_CMYK_PIXELS`]. +/// the TIFF's CMYK ICC profile; `None` for other images, CMYK ones with alpha, ones larger than +/// [`MAX_CMYK_PIXELS`], and, before any decoding, ones with more than [`MAX_EXTRA_SAMPLES_PIXEL`] +/// samples a pixel (their SamplesPerPixel), ones whose samples aren't unsigned integers (a +/// SampleFormat other than 1) and ones whose samples with the row the decoder reads each strip or +/// tile into ([`row_buffer`]) take more than [`crate::MAX_RASTER_ALLOC`]. fn tiff_source(bytes: &[u8]) -> Option { let (kind, mut d) = tiff(bytes)?; - if !matches!(kind, tiff::ColorType::CMYK(8 | 16)) { + if !cmyk_inks(kind, &mut d) { return None; } let (width, height) = d.dimensions().ok()?; @@ -386,6 +777,21 @@ impl ImageBlob { if bytes.starts_with(&[0xFF, 0xD8]) { jpeg_inks(bytes) } else { tiff_inks(bytes) } } + /// The CMYK ICC profile a CMYK image carries: a four-component JPEG's `ICC_PROFILE` APP2 + /// segments put together, or a CMYK TIFF's tag 34675. `None` for other images, and for a + /// profile that isn't one of CMYK colors. Reads only the file's headers and tags. + pub fn cmyk_icc_profile(&self) -> Option> { + let bytes = self.bytes.as_slice(); + if jpeg_components(bytes) == Some(4) { + return cmyk_icc(jpeg_icc(bytes)); + } + let (kind, mut d) = tiff(bytes)?; + if !matches!(kind, tiff::ColorType::CMYK(8 | 16)) { + return None; + } + cmyk_icc(tiff_icc(&mut d)) + } + /// The ink amounts around pixel (`x`, `y`) of a CMYK image, in the pixel space of an image /// object of `object` (width, height) pixels: the average of the `size` × `size` pixels centered /// on it, clipped to the image, as C, M, Y and K bytes. `None` outside the image and for images @@ -464,7 +870,10 @@ fn jpeg_inks(bytes: &[u8]) -> Option { } /// The ink amounts of a CMYK TIFF (16-bit samples to 8 bits), its inks stored together or one plane -/// per ink. +/// per ink. `None` for other images, ones larger than [`MAX_CMYK_PIXELS`], and the files +/// [`read_samples`] refuses: more than [`MAX_EXTRA_SAMPLES_PIXEL`] samples a pixel, samples that +/// aren't unsigned integers, or samples that with the decoder's row take more than +/// [`crate::MAX_RASTER_ALLOC`]. fn tiff_inks(bytes: &[u8]) -> Option { let (kind, mut d) = tiff(bytes)?; let (w, h) = d.dimensions().ok()?; @@ -478,8 +887,8 @@ fn tiff_inks(bytes: &[u8]) -> Option { /// CMYK TIFF `bytes` that no orientation turns ([`turned_cmyk`] stores the others) as Open and /// Place store them: as they are, or, when they store one plane per ink, which the image decoder /// doesn't read, their inks together in a CMYK TIFF with the resolution `ppi`, at the 8 or 16 bits -/// the file has, carrying the file's CMYK ICC profile. `None` for other images and for CMYK TIFFs -/// whose inks [`ImageBlob::cmyk`] doesn't read. +/// the file has, carrying the file's CMYK ICC profile. `None` for other images, for CMYK TIFFs +/// with an extra sample named as alpha and for ones whose inks [`ImageBlob::cmyk`] doesn't read. pub fn stored_cmyk_tiff(bytes: &[u8], ppi: Option<(f64, f64)>) -> Option> { let source = tiff_source(bytes)?; let (_, mut d) = tiff(bytes)?; @@ -493,7 +902,8 @@ pub fn stored_cmyk_tiff(bytes: &[u8], ppi: Option<(f64, f64)>) -> Option /// inks turned and written again as a CMYK TIFF with the resolution `ppi` of the turned pixels, /// with the turned width and height. A TIFF keeps its 8 or 16 bits, a JPEG has 8, and both keep /// their CMYK ICC profile (a JPEG's put together from all its APP2 segments). `None` for other -/// images and for CMYK images whose inks [`ImageBlob::cmyk`] doesn't read. +/// images, for CMYK TIFFs with an extra sample named as alpha and for CMYK images whose inks +/// [`ImageBlob::cmyk`] doesn't read. pub fn turned_cmyk(bytes: &[u8], orientation: image::metadata::Orientation, ppi: Option<(f64, f64)>) -> Option<(Vec, (u32, u32))> { let CmykSource { width, height, samples, icc } = if bytes.starts_with(&[0xFF, 0xD8]) { jpeg_source(bytes) } else { tiff_source(bytes) }?; // Four inks to a pixel, turned as four channels of the same depth are. @@ -512,31 +922,58 @@ pub fn turned_cmyk(bytes: &[u8], orientation: image::metadata::Orientation, ppi: } /// A TIFF whose pixels have samples after their colour, which the image decoder doesn't read at -/// all, as RGBA pixels: CMYK with an alpha channel (5 samples), each colour converted by `rgb` (ink -/// amounts 0..1 → sRGB 0..1; the inks can't be kept with the transparency, so they show as RGB), -/// and grayscale with extra samples, of which the first is the alpha when the file says so (other -/// channels are left out). Associated (premultiplied) alpha is divided back out, and a pixel with -/// no associated alpha has no color. 16-bit samples are converted at 16 bits, and only the result -/// is rounded to 8 bits. The samples may be stored together or one plane per channel. `None` for -/// other images and ones larger than [`MAX_CMYK_PIXELS`]. +/// all, as RGBA pixels: CMYK with an alpha channel, each color converted by `rgb` (ink amounts +/// 0..1 → sRGB 0..1; the inks can't be kept with the transparency, so they show as RGB), and +/// grayscale with extra samples. The alpha is the first extra sample whose ExtraSamples value +/// names it (1 or 2), whatever extra samples come before it; the other extra samples are left out, +/// and without such a value the pixels are opaque. A CMYK file with a fifth sample and no +/// ExtraSamples tag has that sample as unassociated alpha. Associated (premultiplied) alpha is +/// divided back out, and a pixel with no associated alpha has no color. 16-bit samples are +/// converted at 16 bits, and only the result is rounded to 8 bits. The samples may be stored +/// together or one plane per channel. A CMYK file with two or more samples past its inks and its +/// ExtraSamples values (or with no ExtraSamples tag) is read too, opaque when none of those values +/// names an alpha. `None` for other images, CMYK ones without alpha (their inks are read by +/// [`ImageBlob::cmyk`]), ones larger than [`MAX_CMYK_PIXELS`], ones whose SamplesPerPixel is more +/// than [`MAX_EXTRA_SAMPLES_PIXEL`], ones whose samples aren't unsigned integers (a SampleFormat +/// other than 1) and ones whose samples, with the copy a planar file needs, the row the decoder +/// reads each strip or tile into and the RGBA pixels, take more than [`crate::MAX_RASTER_ALLOC`]; +/// those are refused from the file's tags, before any decoding. pub fn extra_samples_tiff_rgba(bytes: &[u8], rgb: impl Fn([f32; 4]) -> [f32; 3]) -> Option { use tiff::tags::Tag; - let (kind, mut d) = tiff(bytes)?; + let mut d = tiff_decoder(bytes)?; + // The decoder gives no color type to a CMYK file that has six or more samples besides the + // ones its ExtraSamples values count. + let kind = d.colortype().ok(); let (w, h) = d.dimensions().ok()?; - // 0: white is zero, 1: black is zero (the two grayscales). + // 0: white is zero, 1: black is zero (the two grayscales), 5: CMYK. let photometric = d.find_tag_unsigned::(Tag::PhotometricInterpretation).ok().flatten(); - // ExtraSamples 1: associated alpha (premultiplied colour), 2: unassociated alpha, 0: not alpha. - let extra = d.find_tag_unsigned_vec::(Tag::ExtraSamples).ok().flatten().and_then(|v| v.first().copied()); - // (samples in a pixel, how many of them are its colour, is the next one alpha?) - let (samples, colour, alpha) = match kind { - tiff::ColorType::CMYKA(8 | 16) => (5, 4, true), - tiff::ColorType::Multiband { bit_depth: 8 | 16, num_samples: n @ 2.. } if matches!(photometric, Some(0 | 1)) => { - (usize::from(n), 1, matches!(extra, Some(1 | 2))) - } + let extras = extra_samples(&mut d); + // The first extra sample named as alpha: (its place among the extra samples, is it associated?) + let named = extras.iter().position(|e| matches!(e, 1 | 2)).map(|i| (i, extras.get(i) == Some(&1))); + // The samples of a pixel that no ExtraSamples value counts. + let uncounted = d.find_tag_unsigned::(Tag::SamplesPerPixel).ok().flatten().and_then(|all| usize::from(all).checked_sub(extras.len())); + // (how many of a pixel's samples are its color, the alpha among the extra samples) + let (colour, alpha) = match kind { + Some(tiff::ColorType::CMYKA(8 | 16)) => (4, if extras.is_empty() { Some((0, false)) } else { named }), + Some(tiff::ColorType::CMYK(8 | 16)) if named.is_some() => (4, named), + Some(tiff::ColorType::Multiband { bit_depth: 8 | 16, num_samples: 2.. }) if matches!(photometric, Some(0 | 1)) => (1, named), + None if photometric == Some(5) && uncounted.is_some_and(|c| c > 5) => (4, named), _ => return None, }; let n = usize::try_from(pixels(w, h)?).ok()?; - let data = read_samples_at_depth(&mut d, n, samples)?; + // The decoder gives a CMYK pixel its inks and at most one extra sample, and doesn't read + // white-is-zero gray with extra samples: those are read as black-is-zero gray, every sample. + let given = kind.map_or(0, |k| usize::from(k.num_samples())); + let (data, samples) = if photometric == Some(0) || kind.is_none() || alpha.is_some_and(|(i, _)| colour + i >= given) { + let mut d = tiff::decoder::Decoder::new(as_black_is_zero(bytes)?).ok()?; + let tiff::ColorType::Multiband { bit_depth: bits @ (8 | 16), num_samples } = d.colortype().ok()? else { return None }; + let samples = usize::from(num_samples); + (decode_samples(&mut with_room(d, bytes.len(), n, samples, bits)?, n, samples)?, samples) + } else { + (decode_samples(&mut with_room(d, bytes.len(), n, given, kind?.bit_depth())?, n, given)?, given) + }; + // (the alpha's sample in a pixel, is it associated?), when the pixel has that sample. + let alpha = alpha.map(|(i, associated)| (colour + i, associated)).filter(|(at, _)| *at < samples); // Sample `i` of the image, 0..1. let level_at = |i: usize| match &data { Samples::Eight(v) => v.get(i).map(|&s| f32::from(s) / 255.0), @@ -549,13 +986,16 @@ pub fn extra_samples_tiff_rgba(bytes: &[u8], rgb: impl Fn([f32; 4]) -> [f32; 3]) }; let mut out = Vec::with_capacity(n.checked_mul(4)?); for first in (0..n).map(|p| p * samples) { - let (opacity, a) = if alpha { (byte_at(first + colour).unwrap_or(u8::MAX), level_at(first + colour).unwrap_or(1.0)) } else { (u8::MAX, 1.0) }; + let (opacity, a) = match alpha { + Some((at, _)) => (byte_at(first + at).unwrap_or(u8::MAX), level_at(first + at).unwrap_or(1.0)), + None => (u8::MAX, 1.0), + }; let level = |s: usize| { let v = level_at(first + s).unwrap_or(0.0); - match extra { - Some(1) if a > 0.0 => (v / a).min(1.0), + match alpha { + Some((_, true)) if a > 0.0 => (v / a).min(1.0), // No associated alpha: the color is zero (TIFF 6.0, Associated Alpha Handling). - Some(1) if alpha => 0.0, + Some((_, true)) => 0.0, _ => v, } }; @@ -860,6 +1300,380 @@ mod tests { assert_eq!(gray.into_raw(), [0, 0, 0, 0], "a gray of zero"); } + /// A pixel type of `$n` samples of `$inner`, `$bits` bits each, in color space `$space`. + macro_rules! samples { + ($name:ident, $inner:ty, $space:ident, $bits:literal, $n:literal) => { + struct $name; + impl tiff::encoder::colortype::ColorType for $name { + type Inner = $inner; + const TIFF_VALUE: tiff::tags::PhotometricInterpretation = tiff::tags::PhotometricInterpretation::$space; + const BITS_PER_SAMPLE: &'static [u16] = &[$bits; $n]; + const SAMPLE_FORMAT: &'static [tiff::tags::SampleFormat] = &[tiff::tags::SampleFormat::Uint; $n]; + fn horizontal_predict(row: &[$inner], result: &mut Vec<$inner>) { + result.extend_from_slice(row); + } + } + }; + } + samples!(Cmyk6x8, u8, CMYK, 8, 6); + samples!(Cmyk6x16, u16, CMYK, 16, 6); + samples!(Cmyk7x8, u8, CMYK, 8, 7); + samples!(Cmyk8x8, u8, CMYK, 8, 8); + samples!(Gray3x8, u8, BlackIsZero, 8, 3); + samples!(WhiteGray2x8, u8, WhiteIsZero, 8, 2); + + /// A one-row TIFF of `C`'s pixels `data`, with the ExtraSamples values `extra`. + fn extras_tiff(extra: &[u16], data: &[C::Inner]) -> Vec + where + [C::Inner]: tiff::encoder::TiffValue, + { + let samples = C::BITS_PER_SAMPLE.len(); + let mut file = Cursor::new(Vec::new()); + let mut enc = tiff::encoder::TiffEncoder::new(&mut file).unwrap(); + let mut img = enc.new_image::(u32::try_from(data.len() / samples).unwrap(), 1).unwrap(); + img.encoder().write_tag(tiff::tags::Tag::ExtraSamples, extra).unwrap(); + img.write_data(data).unwrap(); + file.into_inner() + } + + /// Two pixels of four inks with an alpha sample and another extra sample, the alpha first when + /// `alpha_first`: cyan at an alpha of 128 (or premultiplied, at 128 of cyan when `associated`) + /// with an extra sample of 9, then black, opaque, with an extra sample of 64. + fn inks_alpha_and_extra(alpha_first: bool, associated: bool) -> Vec { + let cyan = if associated { 128 } else { 255 }; + let px = |inks: [u16; 4], alpha: u16, other: u16| { + let extras = if alpha_first { [alpha, other] } else { [other, alpha] }; + [&inks[..], &extras[..]].concat() + }; + [px([cyan, 0, 0, 0], 128, 9), px([0, 0, 0, 255], 255, 64)].concat() + } + + /// A CMYK TIFF whose pixels have alpha and another extra sample reads the sample its + /// ExtraSamples names as alpha, first or second, at 8 and 16 bits, and leaves the other out. + /// Open and Place don't keep its inks. A blob that holds the file, as a document saved with it + /// as a CMYK image does, is a CMYK image with those inks when the alpha is the second extra + /// sample. + #[test] + fn a_cmyk_tiff_with_alpha_and_another_extra_sample_reads_its_alpha() { + let naive = |[c, m, y, k]: [f32; 4]| [(1.0 - c) * (1.0 - k), (1.0 - m) * (1.0 - k), (1.0 - y) * (1.0 - k)]; + for extra in [[1, 0], [2, 0], [0, 1], [0, 2]] { + let data = inks_alpha_and_extra(extra[0] != 0, extra.contains(&1)); + let eight: Vec = data.iter().map(|&v| u8::try_from(v).unwrap()).collect(); + let sixteen: Vec = data.iter().map(|&v| v * 257).collect(); + for (bits, bytes) in [(8, extras_tiff::(&extra, &eight)), (16, extras_tiff::(&extra, &sixteen))] { + let px = extra_samples_tiff_rgba(&bytes, naive).unwrap_or_else(|| panic!("{extra:?}, {bits} bits: reads")); + assert_eq!(px.into_raw(), [0, 255, 255, 128, 0, 0, 0, 255], "{extra:?}, {bits} bits: cyan at half alpha, then black"); + assert!(stored_cmyk_tiff(&bytes, None).is_none(), "{extra:?}, {bits} bits: the inks can't be kept with the alpha"); + let b = ImageBlob::new("image/tiff", bytes); + if extra[0] != 0 { + // The decoder gives these the color type of CMYK with alpha. + assert!(!b.is_cmyk() && b.cmyk().is_none(), "{extra:?}, {bits} bits: never stored as inks"); + continue; + } + assert!(b.is_cmyk(), "{extra:?}, {bits} bits: a stored one stays a CMYK image"); + assert_eq!(b.is_cmyk16(), bits == 16, "{extra:?}, {bits} bits"); + let cyan = u8::try_from(data[0]).unwrap(); + assert_eq!(b.cmyk().map(|i| i.data), Some(vec![cyan, 0, 0, 0, 0, 0, 0, 255]), "{extra:?}, {bits} bits: a stored one keeps its inks"); + } + } + // Two extra samples, neither of them alpha: the inks are kept, as with one. + let bytes = extras_tiff::(&[0, 0], &[255, 0, 0, 0, 9, 128, 0, 0, 0, 255, 64, 255]); + assert!(extra_samples_tiff_rgba(&bytes, naive).is_none(), "not alpha: not this reader's"); + assert!(stored_cmyk_tiff(&bytes, None).is_some()); + let b = ImageBlob::new("image/tiff", bytes); + assert!(b.is_cmyk() && !b.is_cmyk16()); + assert_eq!(b.cmyk().map(|i| i.data), Some(vec![255, 0, 0, 0, 0, 0, 0, 255])); + } + + /// A CMYK TIFF of six samples a pixel whose ExtraSamples has only one value: the sample after + /// the inks is alpha only when that value says so, and the sample after it is never alpha. Files + /// with more samples than the decoder gives a color type read the same way, opaque when no + /// value names an alpha. + #[test] + fn a_cmyk_tiff_with_fewer_extra_sample_values_than_samples_reads_only_a_named_alpha() { + let naive = |[c, m, y, k]: [f32; 4]| [(1.0 - c) * (1.0 - k), (1.0 - m) * (1.0 - k), (1.0 - y) * (1.0 - k)]; + let data = [255, 0, 0, 0, 128, 9, 0, 0, 0, 255, 255, 64]; + let read = |extra: u16| extra_samples_tiff_rgba(&extras_tiff::(&[extra], &data), naive).expect("reads").into_raw(); + assert_eq!(read(2), [0, 255, 255, 128, 0, 0, 0, 255], "the sample after the inks is the alpha"); + assert_eq!(read(0), [0, 255, 255, 255, 0, 0, 0, 255], "not alpha: opaque"); + // Eight samples with two values: the decoder gives the file no color type. The second + // value names the sixth sample as the alpha. + let wide = [255, 0, 0, 0, 9, 128, 17, 18]; + let px = extra_samples_tiff_rgba(&extras_tiff::(&[0, 2], &wide), naive).expect("reads"); + assert_eq!(px.into_raw(), [0, 255, 255, 128], "cyan at the alpha the second value names"); + let px = extra_samples_tiff_rgba(&extras_tiff::(&[0, 0], &wide), naive).expect("no value names an alpha: reads"); + assert_eq!(px.into_raw(), [0, 255, 255, 255], "no value names an alpha: opaque cyan"); + // Six samples and no ExtraSamples tag: the decoder gives the file no color type either. + let mut file = Cursor::new(Vec::new()); + let mut enc = tiff::encoder::TiffEncoder::new(&mut file).unwrap(); + enc.write_image::(1, 1, &wide[..6]).unwrap(); + let px = extra_samples_tiff_rgba(&file.into_inner(), naive).expect("no ExtraSamples tag: reads"); + assert_eq!(px.into_raw(), [0, 255, 255, 255], "no ExtraSamples tag: opaque cyan"); + // Seven samples with two values: the decoder reads it as CMYK with alpha. + let px = extra_samples_tiff_rgba(&extras_tiff::(&[0, 2], &wide[..7]), naive).expect("reads"); + assert_eq!(px.into_raw(), [0, 255, 255, 128], "seven samples: cyan at the alpha the second value names"); + // Its Orientation tag is read too. + let mut file = Cursor::new(Vec::new()); + let mut enc = tiff::encoder::TiffEncoder::new(&mut file).unwrap(); + let mut img = enc.new_image::(1, 1).unwrap(); + img.encoder().write_tag(tiff::tags::Tag::ExtraSamples, &[0u16, 2][..]).unwrap(); + img.encoder().write_tag(tiff::tags::Tag::Orientation, 6u16).unwrap(); + img.write_data(&wide).unwrap(); + let turned = file.into_inner(); + assert_eq!(tiff_orientation(&turned), Some(6)); + assert_eq!(exif_orientation(&turned), Some(image::metadata::Orientation::Rotate90)); + } + + /// A white-is-zero grayscale TIFF `width` pixels wide and `rows` tall (2 or more), each pixel + /// `samples` samples of 8 bits: a level of 0, an unassociated alpha of 128, then zeros. Each + /// row is a strip, and every strip is the same bytes of the file. + fn tall_gray_tiff(width: u32, rows: u32, samples: u16) -> Vec { + gray_tiff(width, rows, samples, false) + } + + /// [`tall_gray_tiff`], or with `planar` one plane per sample, each row of each plane a strip + /// of zeros, every strip the same bytes of the file. + fn gray_tiff(width: u32, rows: u32, samples: u16, planar: bool) -> Vec { + let at = |f: &Vec| u32::try_from(f.len()).unwrap(); + let mut f = b"II*\0\0\0\0\0".to_vec(); + let row = at(&f); + if planar { + f.resize(f.len() + usize::try_from(width).unwrap(), 0); + } else { + for _ in 0..width { + f.extend([0, 128]); + f.resize(f.len() + usize::from(samples) - 2, 0); + } + } + let (strips, strip) = if planar { (rows * u32::from(samples), width) } else { (rows, width * u32::from(samples)) }; + let offsets = at(&f); + f.extend((0..strips).flat_map(|_| row.to_le_bytes())); + let counts = at(&f); + f.extend((0..strips).flat_map(|_| strip.to_le_bytes())); + let ifd = at(&f); + f[4..8].copy_from_slice(&ifd.to_le_bytes()); + // (tag, type (3 SHORT, 4 LONG), count, value or offset) + let entries = [ + (256u16, 4u16, 1, width), + (257, 4, 1, rows), + (258, 3, 1, 8), + (259, 3, 1, 1), + (262, 3, 1, 0), + (273, 4, strips, offsets), + (277, 3, 1, u32::from(samples)), + (278, 4, 1, 1), + (279, 4, strips, counts), + (284, 3, 1, if planar { 2 } else { 1 }), + (338, 3, 1, 2), + ]; + f.extend(u16::try_from(entries.len()).unwrap().to_le_bytes()); + for (tag, ty, count, value) in entries { + f.extend([tag.to_le_bytes(), ty.to_le_bytes()].concat()); + f.extend([count.to_le_bytes(), value.to_le_bytes()].concat()); + } + f.extend([0; 4]); + f + } + + /// A TIFF with extra samples whose samples take more than the decoder's own limit of 256 MiB + /// reads: here 256 × 16,385 pixels of 64 samples, 16,384 bytes more than the limit. + #[test] + fn a_tiff_with_extra_samples_past_the_decoders_limit_reads() { + let (width, rows, samples) = (256, 16_385, 64); + assert!(u64::from(width * rows) * u64::from(samples) > 256 << 20); + let px = extra_samples_tiff_rgba(&tall_gray_tiff(width, rows, samples), |_| [0.0; 3]).expect("reads"); + assert_eq!((px.width(), px.height()), (width, rows)); + assert!(px.pixels().all(|p| p.0 == [255, 255, 255, 128]), "white at an alpha of 128"); + } + + /// A pixel of more than [`MAX_EXTRA_SAMPLES_PIXEL`] samples is not read. + #[test] + fn a_tiff_with_too_many_samples_a_pixel_is_not_read() { + let samples = u16::try_from(MAX_EXTRA_SAMPLES_PIXEL).unwrap(); + assert!(extra_samples_tiff_rgba(&tall_gray_tiff(2, 2, samples), |_| [0.0; 3]).is_some(), "at the limit: reads"); + assert!(extra_samples_tiff_rgba(&tall_gray_tiff(2, 2, samples + 1), |_| [0.0; 3]).is_none(), "past it: not read"); + } + + /// The header of a one-row CMYK TIFF `width` pixels wide, each pixel `samples` samples of + /// `bits` bits stored together, with the ExtraSamples values `extras` (more than two). Its one + /// strip claims every sample of the row, uncompressed, and holds four bytes of zeros. + fn cmyk_header(width: u32, samples: u16, bits: u16, extras: &[u16]) -> Vec { + assert!(extras.len() > 2, "the values sit outside the entry"); + let mut f = b"II*\0\0\0\0\0".to_vec(); + f.extend([0; 4]); + let at = u32::try_from(f.len()).unwrap(); + f.extend(extras.iter().flat_map(|e| e.to_le_bytes())); + let ifd = u32::try_from(f.len()).unwrap(); + f[4..8].copy_from_slice(&ifd.to_le_bytes()); + let strip = u32::try_from(u64::from(width) * u64::from(samples) * u64::from(bits / 8)).unwrap(); + // (tag, type (3 SHORT, 4 LONG), count, value or offset) + let entries = [ + (256u16, 4u16, 1, width), + (257, 4, 1, 1), + (258, 3, 1, u32::from(bits)), + (259, 3, 1, 1), + (262, 3, 1, 5), + (273, 4, 1, 8), + (277, 3, 1, u32::from(samples)), + (278, 4, 1, 1), + (279, 4, 1, strip), + (284, 3, 1, 1), + (338, 3, u32::try_from(extras.len()).unwrap(), at), + ]; + f.extend(u16::try_from(entries.len()).unwrap().to_le_bytes()); + for (tag, ty, count, value) in entries { + f.extend([tag.to_le_bytes(), ty.to_le_bytes()].concat()); + f.extend([count.to_le_bytes(), value.to_le_bytes()].concat()); + } + f.extend([0; 4]); + f + } + + /// A CMYK TIFF whose first ExtraSamples value is alpha has the color type of CMYK with alpha, + /// five samples, however many samples its pixels have; one with more than + /// [`MAX_EXTRA_SAMPLES_PIXEL`] is refused from its tags, before the decoder takes a row of + /// every sample (here 8,192 × 65,535 × 2 bytes, 1 GiB). Neither is it read as inks. + #[test] + fn a_cmyk_tiff_with_more_samples_a_pixel_than_the_limit_is_refused_before_decoding() { + let (width, samples) = (8192u32, u16::MAX); + for first in [1u16, 0] { + let extras: Vec = std::iter::once(first).chain(std::iter::repeat_n(0, usize::from(samples) - 5)).collect(); + let bytes = cmyk_header(width, samples, 16, &extras); + let mut d = tiff::decoder::Decoder::new(Cursor::new(&bytes[..])).unwrap(); + let kind = d.colortype().unwrap(); + assert_eq!(kind, if first == 1 { tiff::ColorType::CMYKA(16) } else { tiff::ColorType::CMYK(16) }); + assert_eq!(row_buffer(&mut d), None, "{kind:?}: refused from the tags"); + let given = usize::from(kind.num_samples()); + assert!(with_room(d, bytes.len(), usize::try_from(width).unwrap(), given, 16).is_none(), "{kind:?}: refused before the decode"); + assert!(extra_samples_tiff_rgba(&bytes, |_| [0.0; 3]).is_none(), "{kind:?}"); + assert!(ImageBlob::new("image/tiff", bytes).cmyk().is_none(), "{kind:?}: no inks"); + } + } + + /// The row the decoder reads each strip of a CMYK TIFF with alpha into, every sample of the + /// row, counts in the allowance: 2²⁴ pixels of 64 16-bit samples, whose five decoded samples + /// and RGBA pixels fit but not with that row of 2 GiB. + #[test] + fn the_decoders_row_of_every_sample_counts_in_the_allowance() { + let width = 1u32 << 24; + let samples = u16::try_from(MAX_EXTRA_SAMPLES_PIXEL).unwrap(); + let extras: Vec = std::iter::once(2).chain(std::iter::repeat_n(0, usize::from(samples) - 5)).collect(); + let bytes = cmyk_header(width, samples, 16, &extras); + let n = usize::try_from(width).unwrap(); + let (need, rgba, row) = (u64::from(width) * 5 * 2, u64::from(width) * 4, u64::from(width) * u64::from(samples) * 2); + assert!(need + rgba <= crate::MAX_RASTER_ALLOC && need + rgba + row > crate::MAX_RASTER_ALLOC); + let mut d = tiff::decoder::Decoder::new(Cursor::new(&bytes[..])).unwrap(); + assert_eq!(d.colortype().unwrap(), tiff::ColorType::CMYKA(16)); + assert_eq!(row_buffer(&mut d), Some(row)); + assert!(with_room(d, bytes.len(), n, 5, 16).is_none(), "refused before the decode"); + assert!(extra_samples_tiff_rgba(&bytes, |_| [0.0; 3]).is_none()); + } + + /// A TIFF whose samples aren't unsigned integers is refused from its tags. + #[test] + fn a_tiff_of_float_samples_is_refused_from_its_tags() { + use tiff::encoder::colortype::{Gray8, Gray32Float}; + let mut file = Cursor::new(Vec::new()); + tiff::encoder::TiffEncoder::new(&mut file).unwrap().write_image::(2, 1, &[0.25, 0.5]).unwrap(); + let float = file.into_inner(); + let mut d = tiff::decoder::Decoder::new(Cursor::new(&float[..])).unwrap(); + assert_eq!(row_buffer(&mut d), None, "floats: refused"); + assert!(read_samples_at_depth(&mut d, 2, 1).is_none()); + let mut file = Cursor::new(Vec::new()); + tiff::encoder::TiffEncoder::new(&mut file).unwrap().write_image::(2, 1, &[64, 128]).unwrap(); + let bytes = file.into_inner(); + let mut d = tiff::decoder::Decoder::new(Cursor::new(&bytes[..])).unwrap(); + assert_eq!(row_buffer(&mut d), Some(0), "unsigned: no extra row"); + assert_eq!(read_samples_at_depth(&mut d, 2, 1), Some(Samples::Eight(vec![64, 128]))); + } + + /// The copy that puts a planar file's samples pixel by pixel is allocated at its length, so + /// the reader holds no more than the allowance counts. 33 samples: a copy that grew as it + /// was filled would hold room for 64. + #[test] + fn the_planar_copy_is_allocated_at_its_length() { + let (n, per) = (11u8, 3u8); + let data: Vec = (0..n * per).collect(); + let len = data.len(); + let out = chunky(data, usize::from(per), usize::from(n), usize::from(per)).unwrap(); + let pixel_by_pixel: Vec = (0..n).flat_map(|i| (0..per).map(move |p| p * n + i)).collect(); + assert_eq!(out, pixel_by_pixel); + assert!(out.capacity() >= len && out.capacity() < len.next_power_of_two(), "capacity {} for {len} samples", out.capacity()); + } + + /// A TIFF whose decoded samples fit [`crate::MAX_RASTER_ALLOC`] but not with its RGBA pixels + /// beside them is refused before its samples are decoded; so is one whose samples fit with + /// the RGBA pixels but not with the copy a planar file needs. The file holds one row of pixels, + /// which every strip reuses. + #[test] + fn a_tiff_whose_decode_with_its_rgba_takes_more_than_the_allowance_is_refused() { + let side = 8192u32; + let n = usize::try_from(u64::from(side) * u64::from(side)).unwrap(); + assert_eq!(u64::try_from(n).unwrap(), MAX_CMYK_PIXELS); + let max = usize::try_from(crate::MAX_RASTER_ALLOC).unwrap(); + // One sample fewer than fills the allowance: the samples alone fit. + let per = max / n - 1; + assert!(n * per <= max && n * per + 4 * n > max); + let bytes = tall_gray_tiff(side, side, u16::try_from(per).unwrap()); + let decoder = || tiff::decoder::Decoder::new(Cursor::new(&bytes[..])).unwrap(); + assert!(with_room(decoder(), bytes.len(), n, per, 8).is_none(), "refused before the decode"); + assert!(extra_samples_tiff_rgba(&bytes, |_| [0.0; 3]).is_none()); + // Half the allowance in samples fits with the RGBA pixels, but not twice over. + let half = max / n / 2; + assert!(with_room(decoder(), bytes.len(), n, half, 8).is_some(), "stored together: fits"); + let planar = gray_tiff(side, side, u16::try_from(half).unwrap(), true); + let decoder = tiff::decoder::Decoder::new(Cursor::new(&planar[..])).unwrap(); + assert!(with_room(decoder, planar.len(), n, half, 8).is_none(), "one plane per sample: refused"); + } + + /// Patched bytes read the same whole, a byte at a time and after a seek into a patch. + #[test] + fn patched_bytes_read_with_their_patches() { + use std::io::{Read, Seek, SeekFrom}; + let bytes: Vec = (10..30).collect(); + let patched = || Patched { bytes: Cursor::new(&bytes[..]), patches: vec![(4, &[1, 0]), (19, &[7, 7])] }; + let want = [10, 11, 12, 13, 1, 0, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 7]; + let mut whole = Vec::new(); + patched().read_to_end(&mut whole).unwrap(); + assert_eq!(whole, want); + let mut one = patched(); + let bytewise: Vec = (0..want.len()) + .map(|_| { + let mut b = [0]; + assert_eq!(one.read(&mut b).unwrap(), 1); + b[0] + }) + .collect(); + assert_eq!(bytewise, want); + let mut from = patched(); + from.seek(SeekFrom::Start(5)).unwrap(); + let mut b = [9; 3]; + from.read_exact(&mut b).unwrap(); + assert_eq!(b, [0, 16, 17], "the second byte of the first patch, then the file"); + } + + /// A grayscale TIFF whose alpha follows another extra sample reads that alpha. + #[test] + fn a_grayscale_tiff_with_alpha_after_another_extra_sample_reads_its_alpha() { + let read = + |extra: [u16; 2], data: &[u8]| extra_samples_tiff_rgba(&extras_tiff::(&extra, data), |_| [0.0; 3]).expect("reads").into_raw(); + // A gray of 64 at an alpha of 204 (premultiplied: 51), with an extra sample of 9. + assert_eq!(read([0, 2], &[64, 9, 204]), [64, 64, 64, 204], "unassociated"); + assert_eq!(read([0, 1], &[51, 9, 204]), [64, 64, 64, 204], "associated, divided back out"); + assert_eq!(read([2, 0], &[64, 204, 9]), [64, 64, 64, 204], "the alpha first"); + assert_eq!(read([0, 0], &[64, 9, 204]), [64, 64, 64, 255], "no alpha: opaque"); + } + + /// A grayscale TIFF whose white is zero (PhotometricInterpretation 0), with alpha, reads with + /// its levels turned around. + #[test] + fn a_white_is_zero_grayscale_tiff_with_alpha_reads_as_rgba() { + // White, opaque; black at an alpha of 128. + let bytes = extras_tiff::(&[2], &[0, 255, 255, 128]); + let px = extra_samples_tiff_rgba(&bytes, |_| [0.0; 3]).expect("reads"); + assert_eq!(px.into_raw(), [255, 255, 255, 255, 0, 0, 0, 128]); + } + /// A header claiming more tiles than can be counted: (2^32 − 1)² pixels in tiles of one pixel, /// times 2 planes. #[test] @@ -876,7 +1690,7 @@ mod tests { f }; assert_eq!(oversized_tiff(&header(2)), Some((u32::MAX, u32::MAX))); - assert_eq!(oversized_tiff(&header(1)), None, "one plane: (2^32 − 1)² tiles can be counted in 64 bits"); + assert_eq!(oversized_tiff(&header(1)), Some((u32::MAX, u32::MAX)), "one plane: countable, but past MAX_TIFF_CHUNKS"); assert!(tiff(&header(2)).is_none(), "not decoded"); } @@ -918,6 +1732,227 @@ mod tests { } } + /// A little-endian TIFF, or BigTIFF when `big`, holding `data` right after its header (from + /// byte 8, or 16 in a BigTIFF), then one directory of `entries` (tag, field type, values). An + /// entry's values sit in the entry when they fit, otherwise after the directory. + fn tiff_file(big: bool, entries: &[(u16, u16, Vec)], data: &[u8]) -> Vec { + let (word, head) = if big { (8, 16) } else { (4, 8) }; + let put = |f: &mut Vec, v: u64, n: usize| f.extend(&v.to_le_bytes()[..n]); + let mut f = if big { b"II+\0\x08\0\0\0".to_vec() } else { b"II*\0".to_vec() }; + let ifd = head + data.len(); + put(&mut f, ifd as u64, word); + f.extend(data); + put(&mut f, entries.len() as u64, if big { 8 } else { 2 }); + let after = f.len() + entries.len() * (4 + 2 * word) + word; + let mut tail = vec![]; + for (tag, ty, values) in entries { + let width = match ty { + 1 | 7 => 1, + 3 => 2, + 4 => 4, + _ => 8, + }; + f.extend([tag.to_le_bytes(), ty.to_le_bytes()].concat()); + put(&mut f, values.len() as u64, word); + let mut v = vec![]; + for &x in values { + put(&mut v, x, width); + } + if v.len() <= word { + v.resize(word, 0); + f.extend(v); + } else { + put(&mut f, (after + tail.len()) as u64, word); + tail.extend(v); + } + } + put(&mut f, 0, word); + f.extend(tail); + f + } + + /// A JPEG of four components whose progressive frame header declares `w` × `h` pixels, with a + /// scan header and no scan data. + fn jpeg_header(w: u16, h: u16) -> Vec { + let mut j = vec![0xFF, 0xD8, 0xFF, 0xC2, 0, 20, 8]; + j.extend(h.to_be_bytes()); + j.extend(w.to_be_bytes()); + j.push(4); + for id in 1..=4 { + j.extend([id, 0x11, 0]); + } + j.extend([0xFF, 0xDA, 0, 14, 4, 1, 0, 2, 0, 3, 0, 4, 0, 0, 63, 0, 0xFF, 0xD9]); + j + } + + /// The directory of a 1 × 1 CMYK image with alpha, JPEG-compressed in one strip of `len` bytes + /// at byte `at`. + fn jpeg_strip_entries(at: u64, len: u64) -> Vec<(u16, u16, Vec)> { + vec![ + (256, 4, vec![1]), + (257, 4, vec![1]), + (258, 3, vec![8; 5]), + (259, 3, vec![7]), + (262, 3, vec![5]), + (273, 4, vec![at]), + (277, 3, vec![5]), + (278, 4, vec![1]), + (279, 4, vec![len]), + (338, 3, vec![2]), + ] + } + + /// A strip's JPEG that declares more pixels than the strip holds would have the decoder + /// allocate them: a 1 × 1 image whose JPEG claims 16384 × 16384 is refused before any decoder + /// opens it, in a TIFF or a BigTIFF, with fill bytes or other bytes before the frame header, + /// and with the frame header in the JPEGTables. + #[test] + fn a_jpeg_strip_declaring_more_than_its_strip_is_refused() { + let big = jpeg_header(16384, 16384); + let file = tiff_file(false, &jpeg_strip_entries(8, big.len() as u64), &big); + assert_eq!(oversized_tiff(&file), Some((16384, 16384))); + assert!(tiff(&file).is_none(), "not decoded"); + let bigtiff = tiff_file(true, &jpeg_strip_entries(16, big.len() as u64), &big); + assert_eq!(oversized_tiff(&bigtiff), Some((16384, 16384)), "BigTIFF"); + // The decoder reads the last ImageWidth and ImageLength: 1 × 1 after 16384 × 16384, in one + // strip without RowsPerStrip. + let mut entries = jpeg_strip_entries(8, big.len() as u64); + entries.retain(|e| e.0 != 278); + entries.splice(0..0, [(256, 4, vec![16384]), (257, 4, vec![16384])]); + assert_eq!(oversized_tiff(&tiff_file(false, &entries, &big)), Some((16384, 16384)), "repeated sizes"); + // StripOffsets as a BYTE, which the decoder reads, and as a RATIONAL, which it reads as two + // offsets. + for (ty, expected) in [(1, (16384, 16384)), (5, (1, 1))] { + let mut entries = jpeg_strip_entries(8, big.len() as u64); + for e in &mut entries { + if e.0 == 273 { + e.1 = ty; + } + } + assert_eq!(oversized_tiff(&tiff_file(false, &entries, &big)), Some(expected), "StripOffsets of type {ty}"); + } + let one = jpeg_header(1, 1); + assert_eq!(oversized_tiff(&tiff_file(false, &jpeg_strip_entries(8, one.len() as u64), &one)), None, "a JPEG as large as its strip"); + let wide = jpeg_header(2, 1); + assert_eq!(oversized_tiff(&tiff_file(false, &jpeg_strip_entries(8, wide.len() as u64), &wide)), Some((2, 1)), "one pixel too wide"); + for (what, prefix) in [("fill bytes", &[0xFF, 0x00, 0xFF][..]), ("other bytes", &[0x12, 0x34][..])] { + let mut j = big[..2].to_vec(); + j.extend(prefix); + j.extend(&big[2..]); + let file = tiff_file(false, &jpeg_strip_entries(8, j.len() as u64), &j); + assert_eq!(oversized_tiff(&file), Some((16384, 16384)), "{what} before the frame header"); + } + // The JPEGTables hold the frame header; the strip holds only the scan. + let tables = [&big[..24], &[0xFF, 0xD9][..]].concat(); + let scan = [&[0xFF, 0xD8][..], &big[24..]].concat(); + let mut entries = jpeg_strip_entries(8 + tables.len() as u64, scan.len() as u64); + entries.push((347, 7, tables.iter().map(|&b| u64::from(b)).collect())); + let file = tiff_file(false, &entries, &[tables, scan].concat()); + assert_eq!(oversized_tiff(&file), Some((16384, 16384)), "frame header in the JPEGTables"); + // An encoder's 8 × 8 RGB JPEG, with its own segments before the frame header, in an + // 8 × 8 image of one strip, and of strips 4 rows tall. + let mut real = Vec::new(); + image::codecs::jpeg::JpegEncoder::new(&mut real).encode(&[90; 8 * 8 * 3], 8, 8, image::ExtendedColorType::Rgb8).unwrap(); + let rgb = |rows: u64| { + let entries = [ + (256, 4, vec![8]), + (257, 4, vec![8]), + (258, 3, vec![8; 3]), + (259, 3, vec![7]), + (262, 3, vec![2]), + (273, 4, vec![8]), + (277, 3, vec![3]), + (278, 4, vec![rows]), + (279, 4, vec![real.len() as u64]), + ]; + oversized_tiff(&tiff_file(false, &entries, &real)) + }; + assert_eq!(rgb(8), None, "an encoder's JPEG as large as its strip"); + assert_eq!(rgb(4), Some((8, 8)), "an encoder's JPEG taller than its strip"); + } + + /// A tile's JPEG may be as large as the tile, which overhangs the image, and when it is more + /// than MAX_JPEG_TILE_PIXELS, no larger than the image. + #[test] + fn a_jpeg_tile_declaring_more_than_its_tile_is_refused() { + let tiled_with = |tile: u64, j: &[u8], rows: Vec| { + let mut entries: Vec<_> = jpeg_strip_entries(0, 0).into_iter().filter(|e| !matches!(e.0, 273 | 278 | 279)).collect(); + if !rows.is_empty() { + entries.push((278, 4, rows)); + } + entries.extend([(322, 4, vec![tile]), (323, 4, vec![tile]), (324, 4, vec![8]), (325, 4, vec![j.len() as u64])]); + oversized_tiff(&tiff_file(false, &entries, j)) + }; + let tiled = |tile: u64, j: &[u8]| tiled_with(tile, j, vec![]); + assert_eq!(tiled_with(16, &jpeg_header(16, 16), vec![1, 1]), None, "RowsPerStrip, unread in a tiled image"); + assert_eq!(tiled(16, &jpeg_header(16, 16)), None, "as large as the tile"); + assert_eq!(tiled(16, &jpeg_header(17, 16)), Some((17, 16)), "wider than the tile"); + assert_eq!(tiled(16, &jpeg_header(16, 17)), Some((16, 17)), "taller than the tile"); + assert_eq!(tiled(4096, &jpeg_header(2048, 2048)), None, "MAX_JPEG_TILE_PIXELS"); + assert_eq!(tiled(4096, &jpeg_header(2048, 2049)), Some((2048, 2049)), "past MAX_JPEG_TILE_PIXELS and the image"); + } + + /// The decoder reads every strip's offset and byte count before anything else: an image with + /// more than MAX_TIFF_CHUNKS strips, counted from its size or from its tables, is refused. + #[test] + fn tiffs_with_more_strips_than_their_tables_may_hold_are_refused() { + let file = |height: u64, count: u32| { + let entries = [ + (256, 4, vec![1]), + (257, 4, vec![height]), + (258, 3, vec![8]), + (262, 3, vec![1]), + (273, 4, vec![8]), + (278, 4, vec![1]), + (279, 4, vec![1]), + ]; + let mut f = tiff_file(false, &entries, &[0]); + // StripOffsets' count, its values left out of the file. + let at = 8 + 1 + 2 + 4 * 12 + 4; + f[at..at + 4].copy_from_slice(&count.to_le_bytes()); + f + }; + let most = MAX_TIFF_CHUNKS; + assert_eq!(oversized_tiff(&file(most, 1)), None, "MAX_TIFF_CHUNKS rows of a strip each"); + assert_eq!(oversized_tiff(&file(most + 1, 1)), Some((1, u32::try_from(most + 1).unwrap())), "one strip more"); + assert_eq!(oversized_tiff(&file(1, u32::try_from(most).unwrap())), None, "MAX_TIFF_CHUNKS offsets"); + assert_eq!(oversized_tiff(&file(1, u32::try_from(most + 1).unwrap())), Some((1, 1)), "one offset more"); + assert!(tiff(&file(1, 1 << 25)).is_none(), "not decoded"); + // Tile sizes without tile tables: the decoder reads the strips and never counts the + // 4,194,304 tiles of a pixel the sizes give. + let strips_with_tile_sizes = |offsets: Option| { + let mut entries = vec![ + (256, 4, vec![2048]), + (257, 4, vec![2048]), + (258, 3, vec![8]), + (262, 3, vec![1]), + (273, 4, vec![8]), + (279, 4, vec![2048 * 2048]), + (322, 4, vec![1]), + (323, 4, vec![1]), + ]; + entries.extend(offsets.map(|tag| (tag, 4, vec![8]))); + entries.sort_by_key(|e| e.0); + oversized_tiff(&tiff_file(false, &entries, &[0])) + }; + assert_eq!(strips_with_tile_sizes(None), None, "a strip image with tile sizes of one pixel"); + assert_eq!(strips_with_tile_sizes(Some(324)), None, "strip and tile tables: the decoder refuses it unread"); + } + + /// Strips whose JPEG headers take more than MAX_JPEG_HEADER_STEPS steps to read refuse the + /// file: here every strip points at the same 1 MB without a marker. + #[test] + fn jpeg_strips_that_take_too_long_to_read_are_refused() { + let file = |strips: u64| { + let mut entries = jpeg_strip_entries(0, 0); + entries.retain(|e| !matches!(e.0, 257 | 273 | 279)); + entries.extend([(257, 4, vec![strips]), (273, 4, vec![8; strips as usize]), (279, 4, vec![1 << 20; strips as usize])]); + tiff_file(false, &entries, &std::iter::repeat_n(0, 1 << 20).collect::>()) + }; + assert_eq!(oversized_tiff(&file(8)), None, "about 8 million steps"); + assert_eq!(oversized_tiff(&file(17)), Some((1, 17)), "about 17 million steps"); + } + fn inks() -> Inks { Inks::new(3, 2, vec![0, 40, 100, 0, 255, 0, 0, 0, 0, 255, 0, 0, 0, 0, 255, 0, 0, 0, 0, 255, 12, 34, 56, 78]).unwrap() } diff --git a/crates/doc/src/depth.rs b/crates/doc/src/depth.rs index 63b7e0ce7c..c846dfc1c6 100644 --- a/crates/doc/src/depth.rs +++ b/crates/doc/src/depth.rs @@ -251,6 +251,45 @@ fn undrawable(heights: &Heights, used: Def, depth: usize) -> bool { heights.get(&used).is_some_and(|h| h.is_none_or(|h| depth + h > MAX_DRAWN_DEPTH)) } +/// How deep the art of a document's symbols and patterns draws, to measure objects that use them +/// outside the document's layers ([`Self::deepest`]). +#[derive(Clone, Debug, Default)] +pub struct DrawnHeights { + symbols: HashMap, + patterns: HashMap, +} + +impl DrawnHeights { + /// The heights of `doc`'s symbols and patterns, as [`Document::too_deep`] counts them: the art + /// is 1 deep, and what it uses is counted under it. A symbol or pattern that uses itself, or + /// draws deeper than [`MAX_DRAWN_DEPTH`], has none. + pub fn of(doc: &Document) -> Self { + let mut out = Self::default(); + for ((pattern, name), h) in heights(doc) { + if let Some(h) = h { + let map = if pattern { &mut out.patterns } else { &mut out.symbols }; + map.insert(name.to_string(), h); + } + } + out + } + + /// The deepest `n`, placed `depth` deep, draws: its own objects and the art of their opacity + /// masks, and under the objects the art of the symbols and patterns they use. A use of a + /// symbol or pattern without a height ([`Self::of`]) counts as the object alone. `n`'s own + /// nesting may pass [`MAX_DEPTH`]. Without recursion. + pub fn deepest(&self, n: &Node, depth: usize) -> usize { + let mut out = depth; + let mut stack = vec![(n, depth)]; + while let Some((n, d)) = stack.pop() { + let used = uses(n).filter_map(|(pattern, name)| if pattern { self.patterns.get(name) } else { self.symbols.get(name) }).max(); + out = out.max(d + used.copied().unwrap_or(0)); + stack.extend(n.children().into_iter().flatten().chain(n.extras().mask.as_ref().map(|m| &m.art)).map(|c| (&**c, d + 1))); + } + out + } +} + /// Take out of `nodes` (each `depth` deep) the uses `bad` picks (given the depth of the object): /// an instance goes, a pattern paint becomes no paint. Returns whether anything changed. For trees /// within [`MAX_DEPTH`]. @@ -623,4 +662,23 @@ mod tests { d.patterns.push(crate::PatternDef::new("q", vec![painted(3, "none")])); assert!(!d.too_deep(None) && !d.limit_depth()); } + + #[test] + fn drawn_heights_measure_objects_outside_the_layers() { + // s0 holds s1 two groups deep, which holds s2, which holds an instance of nothing known: + // s2 draws 3 deep, s1 6 and s0 9. + let d = symbols(3, 2, "none"); + let heights = DrawnHeights::of(&d); + let on_layer = instance(1, "s0"); + assert_eq!(heights.deepest(&on_layer, 2), 2 + 9); + // An object's own nesting and its mask's art count past MAX_DEPTH. + let mut deep = Node::group(NodeId(5), vec![nested(MAX_DEPTH + 10)]); + deep.extras_mut().mask = Some(Box::new(OpacityMask::new((*instance(6, "s2")).clone(), true))); + assert_eq!(heights.deepest(&deep, 1), 1 + 1 + MAX_DEPTH + 10); + let shallow = Node::group(NodeId(5), vec![instance(7, "s1")]); + assert_eq!(heights.deepest(&shallow, 100), 101 + 6); + // A symbol that holds itself has no height, so its instance counts alone. + let looped = DrawnHeights::of(&symbols(2, 1, "s0")); + assert_eq!(looped.deepest(&instance(1, "s0"), 2), 2); + } } diff --git a/crates/doc/src/dimension.rs b/crates/doc/src/dimension.rs index 89df899743..e803d867fc 100644 --- a/crates/doc/src/dimension.rs +++ b/crates/doc/src/dimension.rs @@ -815,6 +815,10 @@ impl Dimension { if self.line_between_points() && !old.line_between_points() { self.keep_gap(&old); } + } else if self.mode == DimensionMode::Linear && xf.determinant() < 0.0 && (self.b - self.a).hypot() > 1e-9 { + // A reflection turns the left normal of a → b to the other side, so an aligned + // dimension's line stays on the reflected side of its points. + self.offset = -self.offset; } if self.mode == DimensionMode::Linear { self.length = self.measured(); diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 418e454b92..54130788e1 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -79,6 +79,7 @@ impl Document { index: _, guide_cache: _, inline_cycles: _, + mounted_art: _, } = self; *version == other.version && *title == other.title @@ -264,6 +265,7 @@ impl Document { index: Default::default(), guide_cache: Default::default(), inline_cycles: Default::default(), + mounted_art: vec![], }; let id = d.alloc_id(); d.layers.push(Arc::new(Node::layer(id, "Layer 1", LayerColor::Preset(0)))); diff --git a/crates/doc/src/document_ext.rs b/crates/doc/src/document_ext.rs index 0f1ec463c4..c29e8464ea 100644 --- a/crates/doc/src/document_ext.rs +++ b/crates/doc/src/document_ext.rs @@ -128,8 +128,8 @@ impl Document { } /// The roots of every tree of the document's art: the layers, symbol definitions, graph designs, - /// pattern swatches and the original of the pattern being edited. Opacity masks hang off nodes - /// in these trees. + /// pattern swatches, the original of the pattern being edited and [`Self::mounted_art`]. + /// Opacity masks hang off nodes in these trees. pub fn art_roots(&self) -> impl Iterator> { self.layers .iter() @@ -137,6 +137,7 @@ impl Document { .chain(self.graph_designs.iter().map(|g| &g.art)) .chain(self.patterns.iter().flat_map(|p| p.art.iter())) .chain(self.pattern_edit.iter().filter_map(|pe| pe.original.as_ref()).flat_map(|p| p.art.iter())) + .chain(self.mounted_art.iter().map(|(n, _)| n)) } /// [`Self::art_roots`], to change. @@ -147,6 +148,7 @@ impl Document { .chain(self.graph_designs.iter_mut().map(|g| &mut g.art)) .chain(self.patterns.iter_mut().flat_map(|p| p.art.iter_mut())) .chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()).flat_map(|p| p.art.iter_mut())) + .chain(self.mounted_art.iter_mut().map(|(n, _)| n)) } /// Does `wants` hold for a node anywhere in the document's art ([`Self::art_roots`]) or its diff --git a/crates/doc/src/document_guides.rs b/crates/doc/src/document_guides.rs index df336fe09e..ba6e4dc428 100644 --- a/crates/doc/src/document_guides.rs +++ b/crates/doc/src/document_guides.rs @@ -1,6 +1,7 @@ use super::document_ext::free_id; use super::guides::Guide; use super::limits::MAX_NEXT_ID; +use super::node::{held_guides, map_held, strip_held}; use super::{Affine, Arc, Document, Node, NodeId, NodeKind, PatternDef, Point, Rect, Selection, SymbolBoxes, Vec2, artboard_holds}; use std::collections::{BTreeMap, HashSet}; @@ -272,8 +273,8 @@ impl Document { return; } for l in &mut self.layers { - if let Some(held) = picked_in_layers(l, &Node::is_ruler_guide) { - drop_picked(l, held); + if let Some(held) = held_guides(l, &Node::is_ruler_guide) { + strip_held(Arc::make_mut(l), held); } } self.saved_guides.extend(guides); @@ -347,14 +348,14 @@ impl Document { /// saved guide whose layer is gone opens. Returns the removed node, without the guides. pub fn remove_edit_layer(&mut self, id: NodeId) -> Result, crate::DocError> { let mut layer = self.remove(id)?; - let Some(held) = picked_in_layers(&layer, &Node::is_ruler_guide) else { return Ok(layer) }; + let Some(held) = held_guides(&layer, &Node::is_ruler_guide) else { return Ok(layer) }; let mut guides = vec![]; layer.walk(&mut |c| { if c.is_ruler_guide() { guides.push(Arc::new(c.clone())); } }); - drop_picked(&mut layer, held); + strip_held(Arc::make_mut(&mut layer), held); let home = self.default_layer().unwrap_or_else(|| self.add_layer(None)); self.children_mut(Some(home))?.extend(guides); Ok(layer) @@ -418,8 +419,8 @@ impl Document { } let pick = |n: &Node| n.is_ruler_guide() && gone.contains(&n.id); for l in &mut self.layers { - if let Some(held) = picked_in_layers(l, &pick) { - drop_picked(l, held); + if let Some(held) = held_guides(l, &pick) { + strip_held(Arc::make_mut(l), held); } } sel.guides.retain(|id| !gone.contains(id)); @@ -434,8 +435,8 @@ impl Document { fn edit_artboard_guides(&mut self, id: u32, f: &mut impl FnMut(bool, &mut f64)) { let pick = |n: &Node| matches!(n.kind, NodeKind::RulerGuide { artboard: Some(a), .. } if a == id); for l in &mut self.layers { - if let Some(held) = picked_in_layers(l, &pick) { - edit_picked(l, held, f); + if let Some(held) = held_guides(l, &pick) { + map_held(Arc::make_mut(l), held, f); } } } @@ -569,57 +570,6 @@ impl Picked { } } -/// The children of `n`, if it is a layer, that `pick` picks (with nothing inside), and its -/// sublayers holding one (with what they hold), or `None` when it holds none. `pick` looks at -/// each child of the layers once. -fn picked_in_layers(n: &Node, pick: &impl Fn(&Node) -> bool) -> Option { - if !n.is_layer() { - return None; - } - let children = n - .children() - .into_iter() - .flatten() - .enumerate() - .filter_map(|(i, c)| if pick(c) { Some((i, Picked::default())) } else { picked_in_layers(c, pick).map(|p| (i, p)) }) - .collect(); - Picked { children, mask: None }.some() -} - -/// Remove the children of `layer` and of its sublayers that [`picked_in_layers`] picked (`held`). -/// Only the layers holding one are copied, and only those are visited. -fn drop_picked(layer: &mut Arc, held: Picked) { - let Some(ch) = Arc::make_mut(layer).children_mut() else { return }; - let mut held = held.children.into_iter().peekable(); - let mut next = 0; - ch.retain_mut(|c| { - let at = next; - next += 1; - let Some((_, inner)) = held.next_if(|(i, _)| *i == at) else { return true }; - // A sublayer holds something; a child picked itself has nothing inside. - if inner.is_empty() { - return false; - } - drop_picked(c, inner); - true - }); -} - -/// Change with `f` (whether it is vertical, its position) the line of each ruler guide of `layer` -/// and of its sublayers that [`picked_in_layers`] picked (`held`), in the order they lie in. Only -/// the layers holding one, and the guides, are copied, and only those layers are visited. -fn edit_picked(layer: &mut Arc, held: Picked, f: &mut impl FnMut(bool, &mut f64)) { - let Some(ch) = Arc::make_mut(layer).children_mut() else { return }; - for (i, inner) in held.children { - let Some(c) = ch.get_mut(i) else { continue }; - if !inner.is_empty() { - edit_picked(c, inner, f); - } else if let NodeKind::RulerGuide { vertical, pos, .. } = &mut Arc::make_mut(c).kind { - f(*vertical, pos); - } - } -} - /// `n` picked itself when it is a ruler guide by `is_guide`, else the ruler guides below it /// ([`guides_below`]). fn guide_or_below(n: &Node, is_guide: &impl Fn(&Node) -> bool) -> Option { @@ -872,9 +822,9 @@ mod tests { looked.set(looked.get() + 1); on_artboard_7(n) }; - let held = picked_in_layers(&d.layers[0], &pick).unwrap(); + let held = held_guides(&d.layers[0], &pick).unwrap(); assert_eq!(looked.get(), NESTED_CHILDREN, "each child of the layers is looked at once"); - drop_picked(&mut d.layers[0], held); + strip_held(Arc::make_mut(&mut d.layers[0]), held); assert_eq!(looked.get(), NESTED_CHILDREN, "removing looks at nothing again"); assert!(d.layers[0].children().is_some_and(|c| Arc::ptr_eq(&c[1], &still)), "a sublayer with nothing to remove is not copied"); @@ -932,10 +882,10 @@ mod tests { looked.set(looked.get() + 1); on_artboard_7(n) }; - let held = picked_in_layers(&d.layers[0], &pick).unwrap(); + let held = held_guides(&d.layers[0], &pick).unwrap(); assert_eq!(looked.get(), NESTED_CHILDREN, "each child of the layers is looked at once"); let mut seen = vec![]; - edit_picked(&mut d.layers[0], held, &mut |vertical, pos: &mut f64| { + map_held(Arc::make_mut(&mut d.layers[0]), held, &mut |vertical, pos: &mut f64| { seen.push((vertical, *pos)); *pos += 9.0; }); diff --git a/crates/doc/src/graph.rs b/crates/doc/src/graph.rs index d561663524..58b52dd651 100644 --- a/crates/doc/src/graph.rs +++ b/crates/doc/src/graph.rs @@ -150,6 +150,10 @@ pub struct LabelStyles { pub categories: Option, #[serde(skip_serializing_if = "Option::is_none")] pub legend: Option, + /// The fill of [`Self::legend`] was set on the legend labels, so it is drawn on every pie wedge with Legends in + /// Wedges. `false`: a black fill there is the default, and the labels on dark wedges are drawn white. + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub legend_fill_set: bool, #[serde(skip_serializing_if = "Option::is_none")] pub values_para: Option, #[serde(skip_serializing_if = "Option::is_none")] @@ -182,6 +186,18 @@ impl LabelStyles { fn is_default(&self) -> bool { *self == Self::default() } + + /// Is the kept legend fill the legend labels' own: set on them ([`Self::legend_fill_set`]), or not black (a file + /// saved without the mark)? Otherwise it is the default black, which edits that map the kept paints leave as it is. + pub fn legend_fill_is_own(&self) -> bool { + self.legend.as_ref().is_some_and(|st| self.legend_fill_set || st.fill != vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK)) + } + + /// Mark a kept legend fill that is the labels' own ([`Self::legend_fill_is_own`]) as set on them, before an edit + /// that maps the kept paints can turn it black. + pub fn mark_own_legend_fill(&mut self) { + self.legend_fill_set = self.legend_fill_is_own(); + } } /// Graph Type › Position for pie graphs with several pies: the same size (Even), sized by their totals (Ratio), or @@ -363,6 +379,22 @@ pub struct SeriesPaint { /// Object blend mode of each path directly in the series group, as [`Self::opacity`]. Absent: Normal. #[serde(skip_serializing_if = "Option::is_none")] pub blend: Option, + /// Object opacity (0..1) of the series group itself, taken from the transparency set on the group. Absent: fully opaque. + /// Graph labels keep none. + #[serde(skip_serializing_if = "Option::is_none")] + pub group_opacity: Option, + /// Object blend mode of the series group itself, as [`Self::group_opacity`]. Absent: Normal. + #[serde(skip_serializing_if = "Option::is_none")] + pub group_blend: Option, + /// Isolate Blending of the series group itself, as [`Self::group_opacity`]. Absent: off. + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub group_isolate: bool, + /// Knockout Group state of the series group itself, as [`Self::group_opacity`]. Absent: neutral. + #[serde(skip_serializing_if = "Option::is_none")] + pub group_knockout: Option, + /// Knockout Shape of the series group itself, as [`Self::group_opacity`]. Absent: off. + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub group_knockout_shape: bool, /// A gradient in [`Self::fill`] is placed relative to the unit box (0, 0)–(1, 1), and each mark takes it on its own /// geometric bounds. False: the gradient is in document coordinates, and every mark takes it unchanged. #[serde(skip_serializing_if = "std::ops::Not::not")] @@ -511,6 +543,10 @@ pub struct GraphSpec { /// Bounds of the art when it was last generated (detects moves/scales of the graph group). #[serde(skip_serializing_if = "Option::is_none")] pub placed: Option, + /// Bounds of the art other than type when it was last generated ([`graph_art_without_type`]). Moves and scales of the graph + /// group are measured on these when present; graphs saved without them are measured on [`Self::placed`]. + #[serde(skip_serializing_if = "Option::is_none")] + pub placed_art: Option, } fn at_most_one(n: &usize) -> bool { @@ -526,12 +562,57 @@ fn edge_to_edge_before_the_option() -> bool { true } +/// The geometric bounds of a graph's art `children` leaving out their type: the plot, axes, tick marks and legend +/// swatches without the labels. None when there is nothing else. [`GraphSpec::placed_art`] keeps these. +pub fn graph_art_without_type(children: &[std::sync::Arc]) -> Option { + children.iter().filter_map(|c| without_type(c).0).reduce(|a, b| a.union(b)) +} + +/// The geometric bounds of `n` leaving out the type in it, and whether its own geometric bounds depend on that type. A +/// group without such type gives its own bounds, and a clipping group whose clip does not depend on type gives the +/// bounds of its clip. Objects other than groups, layers and compound paths, blends, envelopes and repeats among them, +/// give their own bounds. +fn without_type(n: &crate::Node) -> (Option, bool) { + use crate::NodeKind::{Compound, Group, Layer, Text}; + if matches!(n.kind, Text(_)) { + return (None, true); + } + let children: &[std::sync::Arc] = match &n.kind { + Group { clip: true, children } | Layer { clip: true, children, .. } => children, + Group { .. } | Layer { .. } | Compound { .. } => n.editing_children(), + _ => return (n.geometric_bounds(), false), + }; + let mut bounds: Option = None; + let mut had_type = false; + let mut clip_has_type = false; + let hidden_layer_member = |c: &crate::Node| !c.visible && matches!(n.kind, Layer { clip: false, .. }); + for (i, c) in children.iter().enumerate().filter(|(_, c)| !hidden_layer_member(c)) { + let (b, t) = without_type(c); + had_type |= t; + clip_has_type |= i == 0 && t; + bounds = match (bounds, b) { + (Some(a), Some(b)) => Some(a.union(b)), + (a, b) => a.or(b), + }; + } + let clip = matches!(n.kind, Group { clip: true, .. } | Layer { clip: true, .. }); + if had_type && (!clip || clip_has_type) { (bounds, true) } else { (n.geometric_bounds(), false) } +} + impl GraphSpec { /// The type series `s` is drawn as: its own type when it combines with the graph's, else the graph's. pub fn series_kind(&self, s: usize) -> GraphKind { self.series_kinds.get(s).copied().flatten().filter(|k| k.combines_with(self.kind)).unwrap_or(self.kind) } + /// Does the graph pick the fill of its legend labels itself, white on a dark wedge and black on the others: a pie + /// with Legends in Wedges whose legend labels keep no fill of their own ([`LabelStyles::legend_fill_is_own`])? Only + /// then is a black legend fill it keeps the default, which edits that map the kept paints leave as it is; other + /// graphs draw the kept fill as it is. + pub fn picks_legend_fill(&self) -> bool { + self.kind == GraphKind::Pie && self.legend && self.pie_legend_in_wedges && !self.label_styles.legend_fill_is_own() + } + /// The data with blank cells as `None`, every row as long as the longest (at most [`MAX_GRAPH_CATEGORIES`] rows /// of [`MAX_GRAPH_SERIES`] cells). pub fn cells(&self) -> Vec>> { @@ -635,6 +716,7 @@ impl Default for GraphSpec { connect_points: true, edge_to_edge: false, placed: None, + placed_art: None, } } } diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index fd907a26cc..5885a0ff54 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -1,7 +1,7 @@ //! Hit testing over the document tree. use std::cell::RefCell; -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use std::rc::Rc; use std::sync::{Arc, OnceLock}; @@ -279,13 +279,16 @@ pub fn selected_hidden_at(doc: &Document, p: Point, opt: HitOptions, selected: & return false; } // How a click reaches it, if one does. + let start = opt; let Some(opt) = path_options(&nodes, &chain, opt) else { return false }; - // Hidden by a mask: one of the containers around it clips, and not to `p`. - let masked = nodes - .iter() - .rev() - .skip(1) - .any(|n| n.clips() && n.children().and_then(|c| c.first()).is_some_and(|clip| clip.id != id && !clip_contains(clip, p))); + // Hidden by a mask: one of the containers around it clips, and not to `p`. A container + // tests its clipping path in outline from the first layer with Preview off down to it, as + // a click going down to it does ([`path_options`]). + let below = start.scope.and_then(|s| chain.iter().position(|a| *a == s)).map_or(0, |i| i + 1); + let masked = nodes.iter().enumerate().rev().skip(1).any(|(k, n)| { + let outline = start.outline || nodes.get(below..=k).is_some_and(|ns| ns.iter().any(|n| previews_off(n))); + n.clips() && n.children().and_then(|c| c.first()).is_some_and(|clip| clip.id != id && !clip_contains(clip, p, outline)) + }); // A click may reach it there ([`may_hit`]: not a guide while guides are locked or // hidden, nor a Shaper group's hidden part), and its own art is what a click would hit // in it: a group's hidden, locked or masked contents don't count. @@ -359,6 +362,7 @@ pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option, seen: &mut HashSet) -> bool { let Some(children) = layer.children() else { return true }; + let opt = if matches!(layer.kind, NodeKind::Layer { preview: false, .. }) { HitOptions { outline: true, ..opt } } else { opt }; if layer.clips() && let Some(clip) = children.first() { @@ -366,11 +370,10 @@ fn objects_at_layer(layer: &Node, p: Point, opt: HitOptions, symbols: &SymbolBox if clip_outline_hit(layer, clip, p, opt, symbols, true).is_some() && seen.insert(clip.id) { tops.push(clip.id); } - if !clip_contains(clip, p) { + if !clip_contains(clip, p, opt.outline) { return true; } } - let opt = if matches!(layer.kind, NodeKind::Layer { preview: false, .. }) { HitOptions { outline: true, ..opt } } else { opt }; for (i, c) in children.iter().enumerate().rev() { if !may_hit(layer, i, c, p, opt, symbols, true) || seen.contains(&c.id) { continue; @@ -452,7 +455,7 @@ pub fn locked_objects_at(doc: &Document, p: Point, opt: HitOptions) -> Vec) { let Some(children) = parent.children() else { return }; - if parent.clips() && !edits_inside(parent, opt.scope) && children.first().is_some_and(|clip| !clip_contains(clip, p)) { + if parent.clips() && !edits_inside(parent, opt.scope) && children.first().is_some_and(|clip| !clip_contains(clip, p, opt.outline)) { return; } for i in hit_order(parent, children, p) { @@ -561,14 +564,170 @@ fn edits_contents(n: &Node) -> bool { matches!(n.kind, NodeKind::Envelope { editing: true, .. }) } -/// Is `p` inside the region `clip` clips to ([`Node::clip_shapes`])? Text counts by its frame: -/// glyph outlines need the font engine, above this crate. -fn clip_contains(clip: &Node, p: Point) -> bool { - clip_regions(clip).iter().any(|(bp, rule)| fill_contains(bp, *rule, p)) +/// Is `p` inside the region `clip` clips to ([`clip_areas`])? In outline mode ([`HitOptions::outline`]) +/// the canvas draws no effects, so the plain shapes of `clip` ([`clip_regions`]) count. +fn clip_contains(clip: &Node, p: Point, outline: bool) -> bool { + let areas = if outline { clip_regions(clip) } else { clip_areas(clip) }; + areas.iter().any(|(bp, rule)| fill_contains(bp, *rule, p)) } -/// The regions `clip` clips to ([`Node::clip_shapes`]), text counted by its frame as in -/// [`clip_contains`]. +/// The region of a clip group's clipping path as the canvas clips by it, with the live geometry +/// effects of the clipping path and of what it clips by applied, as one path and fill rule +/// (`Some(None)` when nothing is left to clip by). `None` when nothing in the clipping path has a +/// live geometry effect: its plain shapes ([`clip_regions`]) count then. Effects are evaluated +/// above this crate, so the engine registers one with [`set_clip_region`]. +pub type ClipRegion = fn(&Node) -> Option>; + +static CLIP_REGION: OnceLock = OnceLock::new(); + +/// Register how the region of a clipping path with live effects is found (the first registration +/// stays). +pub fn set_clip_region(f: ClipRegion) { + // Already set: the same engine, registered by another session. + let _ = CLIP_REGION.set(f); +} + +/// Does `clip`, or anything it holds, have a visible effect of its own or on a fill or stroke? Only +/// then can the registered [`ClipRegion`] find a geometry effect in it. +fn has_effects(clip: &Node) -> bool { + let mut found = false; + clip.walk(&mut |n| { + let visible = |e: &crate::Effect| e.visible; + found |= n.appearance.effects.iter().any(visible) || n.appearance.items.iter().any(|i| i.effects().iter().any(visible)); + }); + found +} + +/// A clipping path's region evaluated by [`clip_region`] on this thread: the clipping path and the +/// [`LiveInputs`] as they were, the region (`None` without geometry effects) and the number of its +/// path elements. +struct EvaluatedClip { + clip: Node, + inputs: u64, + region: Option>>, + size: usize, +} + +/// How many regions [`clip_region`] keeps on each thread: every click and every hover over a clip +/// group whose clipping path has live effects asks for its region, and clip groups can be nested. +const CLIPS_KEPT: usize = 16; + +thread_local! { + /// The regions [`clip_region`] keeps, the latest first. + static CLIPS: RefCell> = const { RefCell::new(Vec::new()) }; +} + +#[cfg(test)] +thread_local! { + /// How many regions [`clip_region`] evaluated on this thread. + static CLIPS_EVALUATED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The region clipping path `clip` clips to with its live geometry effects applied +/// ([`set_clip_region`]), or `None` when it has none or nothing is registered; its plain shapes +/// ([`clip_regions`]) are the region then. The region is evaluated again when `clip` or the +/// [`LiveInputs`] have changed since. +fn clip_region(clip: &Node) -> Option>> { + let f = CLIP_REGION.get()?; + if !has_effects(clip) { + return None; + } + let inputs = live_inputs(); + let kept = CLIPS.with_borrow_mut(|kept| { + let i = kept.iter().position(|e| e.inputs == inputs && e.clip == *clip)?; + let e = kept.remove(i); + let region = e.region.clone(); + kept.insert(0, e); + Some(region) + }); + if let Some(region) = kept { + return region; + } + #[cfg(test)] + CLIPS_EVALUATED.with(|c| c.set(c.get() + 1)); + let region = f(clip).map(Rc::new); + let elements = region.as_deref().and_then(Option::as_ref).map_or(0, |(bp, _)| bp.elements().len()); + let size = elements.saturating_add(art_size(std::slice::from_ref(clip))); + if size <= LIVE_KEPT_SIZE { + let e = EvaluatedClip { clip: clip.clone(), inputs, region: region.clone(), size }; + CLIPS.with_borrow_mut(|kept| { + kept.insert(0, e); + kept.truncate(CLIPS_KEPT); + let mut total = 0usize; + kept.retain(|e| { + total = total.saturating_add(e.size); + total <= LIVE_KEPT_SIZE + }); + }); + } + region +} + +/// The box of a clipping path's region found by [`reshaped_clip_box`]: the clipping path and the +/// [`LiveInputs`] as they were, the box and the [`art_size`] of the clipping path. +struct ClipBox { + clip: Node, + inputs: u64, + rect: Option, + size: usize, +} + +/// How many boxes [`reshaped_clip_box`] keeps on each thread. Every pointer move measures every clip +/// group it passes, so the boxes of all of a document's clip groups with live effects are kept, not +/// only the latest few as with the regions. +const CLIP_BOXES_KEPT: usize = 4096; + +thread_local! { + /// The boxes [`reshaped_clip_box`] keeps, by clipping path, and the sum of their sizes. + static CLIP_BOXES: RefCell<(HashMap, usize)> = RefCell::new((HashMap::new(), 0)); +} + +/// The box of the region `clip` clips to with its live geometry effects applied ([`clip_region`]), +/// `None` when it has none or no region. The box is kept until `clip` or the [`LiveInputs`] change. +/// When the boxes kept are full, a new box replaces as many others as it needs room for, so the +/// pointer moving over more clip groups than fit still finds most of their boxes. +pub(crate) fn reshaped_clip_box(clip: &Node) -> Option { + use vectorcraft_geom::kurbo::Shape; + CLIP_REGION.get()?; + if !has_effects(clip) { + return None; + } + let inputs = live_inputs(); + let kept = CLIP_BOXES.with_borrow(|(boxes, _)| boxes.get(&clip.id).filter(|b| b.inputs == inputs && b.clip == *clip).map(|b| b.rect)); + if let Some(rect) = kept { + return rect; + } + let rect = clip_region(clip).and_then(|r| r.as_ref().as_ref().filter(|(bp, _)| !bp.elements().is_empty()).map(|(bp, _)| bp.bounding_box())); + let size = art_size(std::slice::from_ref(clip)); + if size <= LIVE_KEPT_SIZE { + CLIP_BOXES.with_borrow_mut(|(boxes, total)| { + if let Some(old) = boxes.remove(&clip.id) { + *total = total.saturating_sub(old.size); + } + while boxes.len() >= CLIP_BOXES_KEPT || total.saturating_add(size) > LIVE_KEPT_SIZE { + let Some(other) = boxes.keys().next().copied() else { break }; + if let Some(old) = boxes.remove(&other) { + *total = total.saturating_sub(old.size); + } + } + boxes.insert(clip.id, ClipBox { clip: clip.clone(), inputs, rect, size }); + *total = total.saturating_add(size); + }); + } + rect +} + +/// The regions a click inside a clip group must fall in: those `clip` clips to with its live +/// effects applied, as the canvas clips ([`clip_region`]), else its plain shapes ([`clip_regions`]). +fn clip_areas(clip: &Node) -> Vec<(BezPath, FillRule)> { + match clip_region(clip) { + Some(region) => region.as_ref().iter().cloned().collect(), + None => clip_regions(clip), + } +} + +/// The regions `clip` clips to by its plain shapes ([`Node::clip_shapes`]), without its live +/// effects. Text counts by its frame: glyph outlines need the font engine, above this crate. pub fn clip_regions(clip: &Node) -> Vec<(vectorcraft_geom::BezPath, vectorcraft_geom::FillRule)> { let frame = |n: &Node| { let b = n.geometric_bounds()?; @@ -698,7 +857,7 @@ fn hit_children( // Elsewhere a clip group (or a layer with a clipping mask) only hits inside it, except for // the selection tools in isolation mode within it. let edited = opt.clip_outlines && editable_only && edits_inside(parent, opt.scope); - if !edited && !clip_contains(clip, p) { + if !edited && !clip_contains(clip, p, opt.outline) { return None; } } @@ -960,7 +1119,7 @@ fn hit_any(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option match &n.kind { // A clip group only hits inside its clipping path. NodeKind::Group { children, clip } => { - if *clip && children.first().is_some_and(|c| !clip_contains(c, p)) { + if *clip && children.first().is_some_and(|c| !clip_contains(c, p, opt.outline)) { return None; } children.iter().rev().find_map(|c| hit_any(c, p, opt, symbols)) @@ -974,43 +1133,45 @@ fn hit_any(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option /// The art of a symbol instance with its own appearance changes, in the symbol's coordinates, and /// how the canvas places each object of it: through the symbol's 9-slice guides when the instance /// is scaled by them ([`Document::place_symbol_art`]), otherwise by the instance's transform. -struct InstanceArt { +struct InstanceArt<'a> { art: Node, map: Option, xf: vectorcraft_geom::Affine, + /// Quick boxes, which measure the instances in the art as it is placed through the guides. + boxes: SymbolBoxes<'a>, } -impl InstanceArt { +impl<'a> InstanceArt<'a> { /// The art of symbol instance `inst`. `None` for anything else, a missing symbol, or art that /// placing through the guides could make more than [`crate::MAX_SYMBOL_NODES`] objects of, /// which [`Document::place_symbol_art`] does not place and the canvas does not draw. - fn of(doc: &Document, inst: &Node) -> Option { + fn of(doc: &'a Document, inst: &Node) -> Option { let NodeKind::SymbolInstance { symbol, xf } = &inst.kind else { return None }; - let sym = doc.symbols.iter().find(|s| s.name == *symbol)?; - let art = crate::symbol_overrides::dynamic_art(&sym.art, inst); - let map = doc.symbol_slice_map(symbol, *xf); - if map.as_ref().is_some_and(|m| m.most_placed(&art, doc) > crate::MAX_SYMBOL_NODES) { + let boxes = doc.symbol_boxes().quick(); + let art = crate::symbol_overrides::dynamic_art(boxes.symbol_art(symbol)?, inst); + let map = boxes.slice_map(symbol, *xf); + if map.as_ref().is_some_and(|m| m.most_placed_with(&art, &boxes) > crate::MAX_SYMBOL_NODES) { return None; } - Some(Self { art, map, xf: *xf }) + Some(Self { art, map, xf: *xf, boxes }) } /// The map that the objects inside group or layer `n` are moved by as one piece: `whole`, the /// map of an object around `n` that is moved as one piece, or else the map of the 9-slice cell /// `n` lies in ([`crate::NineSliceMap::one_cell`]). `None` when `n` is placed through the guides /// object by object. - fn whole(&self, n: &Node, doc: &Document, whole: Option) -> Option { - whole.or_else(|| self.map.as_ref()?.one_cell(n, doc)) + fn whole(&self, n: &Node, whole: Option) -> Option { + whole.or_else(|| self.map.as_ref()?.one_cell_with(n, &self.boxes)) } /// Object `n` of the art placed on the canvas as it is drawn, clip groups included: moved by /// `whole` when an object around it is moved as one piece ([`Self::whole`]). `None` when /// placing it through the guides could make more than [`crate::MAX_SYMBOL_NODES`] objects, as /// [`Document::place_symbol_art`] refuses it. - fn place(&self, n: &Node, doc: &Document, whole: Option) -> Option { + fn place(&self, n: &Node, whole: Option) -> Option { match (&self.map, whole) { (_, Some(a)) => Some(moved(n, a)), - (Some(m), None) => (m.most_placed(n, doc) <= crate::MAX_SYMBOL_NODES).then(|| m.place(n, doc)), + (Some(m), None) => (m.most_placed_with(n, &self.boxes) <= crate::MAX_SYMBOL_NODES).then(|| m.place_with(n, &self.boxes)), (None, None) => Some(moved(n, self.xf)), } } @@ -1018,10 +1179,13 @@ impl InstanceArt { /// Object `n` of the art placed on the canvas without clip groups /// ([`crate::NineSliceMap::place_unclipped`]), as [`Self::place`] places it and within the /// same limit ([`Document::place_symbol_art_unclipped`]). - fn place_unclipped(&self, n: &Node, doc: &Document, whole: Option) -> Option { + fn place_unclipped(&self, n: &Node, whole: Option) -> Option { match (&self.map, whole) { (_, Some(a)) => Some(moved(n, a)), - (Some(m), None) => (m.most_placed_unclipped(n, doc) <= crate::MAX_SYMBOL_NODES).then(|| m.place_unclipped(n, doc)), + (Some(m), None) => { + let m = m.unclipped(); + (m.most_placed_with(n, &self.boxes) <= crate::MAX_SYMBOL_NODES).then(|| m.place_with(n, &self.boxes)) + } (None, None) => Some(moved(n, self.xf)), } } @@ -1043,45 +1207,45 @@ fn moved(n: &Node, xf: vectorcraft_geom::Affine) -> Node { /// group's original shapes, which the canvas does not draw, and guide paths with /// [`HitOptions::skip_guides`]. Nothing is picked in art that placing through the symbol's 9-slice /// guides could make more than [`crate::MAX_SYMBOL_NODES`] objects of, which the canvas does not -/// draw. `None` when `inst` is not a symbol instance or no editable object of its art is under `p`. +/// draw. Art in a layer of the symbol whose Preview is off, and the art of an instance below such a +/// layer, is tested in outline ([`HitOptions::outline`]), as the canvas draws it. `None` when `inst` is not a symbol instance or +/// no editable object of its art is under `p`. pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> Option> { struct Find<'a> { - doc: &'a Document, - art: &'a InstanceArt, + art: &'a InstanceArt<'a>, p: Point, opt: HitOptions, symbols: &'a SymbolBoxes<'a>, } impl Find<'_> { - fn hit(&self, n: &Node, whole: Option) -> bool { - self.art.place(n, self.doc, whole).is_some_and(|n| hit_any(&n, self.p, self.opt, self.symbols).is_some()) + fn hit(&self, n: &Node, whole: Option, opt: HitOptions) -> bool { + self.art.place(n, whole).is_some_and(|n| hit_any(&n, self.p, opt, self.symbols).is_some()) } fn skips_guide(&self, n: &Node) -> bool { self.opt.skip_guides && matches!(n.kind, NodeKind::Path { guide: true, .. }) } - fn find(&self, n: &Node, path: &mut Vec, whole: Option) -> bool { + /// `outline`: the view is in Outline, or a layer around `n` has Preview off. + fn find(&self, n: &Node, path: &mut Vec, whole: Option, outline: bool) -> bool { if !n.visible || n.locked || n.is_template() || self.skips_guide(n) { return false; } - let (NodeKind::Group { children, .. } | NodeKind::Layer { children, .. }) = &n.kind else { return self.hit(n, whole) }; + let outline = outline || previews_off(n); + let opt = HitOptions { outline, ..self.opt }; + let (NodeKind::Group { children, .. } | NodeKind::Layer { children, .. }) = &n.kind else { return self.hit(n, whole, opt) }; if path.len() >= crate::symbol_overrides::MAX_PATH_DEPTH { - return self.hit(n, whole); + return self.hit(n, whole, opt); } - let whole = self.art.whole(n, self.doc, whole); + let whole = self.art.whole(n, whole); if n.clips() && let Some(first) = children.first() { - let Some(clip) = self.art.place_unclipped(first, self.doc, whole) else { return false }; - if self.opt.clip_outlines - && first.visible - && !first.locked - && !self.skips_guide(first) - && clip_outline(&clip, self.p, self.opt).is_some() + let Some(clip) = self.art.place_unclipped(first, whole) else { return false }; + if self.opt.clip_outlines && first.visible && !first.locked && !self.skips_guide(first) && clip_outline(&clip, self.p, opt).is_some() { path.push(0); return true; } - if !clip_contains(&clip, self.p) { + if !clip_contains(&clip, self.p, outline) { return false; } } @@ -1092,7 +1256,7 @@ pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> } let Ok(i) = u32::try_from(i) else { continue }; path.push(i); - if self.find(c, path, whole) { + if self.find(c, path, whole, outline) { return true; } path.pop(); @@ -1103,7 +1267,17 @@ pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> let art = InstanceArt::of(doc, inst)?; let symbols = doc.symbol_boxes(); let mut path = vec![]; - Find { doc, art: &art, p, opt, symbols: &symbols }.find(&art.art, &mut path, None).then_some(path) + let outline = opt.outline || below_preview_off(doc, inst, opt.scope); + Find { art: &art, p, opt, symbols: &symbols }.find(&art.art, &mut path, None, outline).then_some(path) +} + +/// Is `n` below a layer whose Preview is off, so that the canvas draws it in outline? As for clicks +/// ([`path_options`]), the Preview of the isolated container `scope` and of the layers around it +/// does not count. +fn below_preview_off(doc: &Document, n: &Node, scope: Option) -> bool { + let Some(chain) = doc.ancestry(n.id) else { return false }; + let below = scope.and_then(|s| chain.iter().position(|a| *a == s)).map_or(0, |i| i + 1); + chain.iter().skip(below).any(|a| doc.node(*a).is_some_and(previews_off)) } /// The outlines of the object at `path` in symbol instance `inst`'s art (see [`symbol_part_at`]), @@ -1112,36 +1286,64 @@ pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> /// group per cell) they are cut to the bounds of the group's clip path, which is not outlined. An /// object inside a clip group or a clipping layer of the art, other than its clipping path, is cut /// to the bounds of that clipping path as well, which contain the region where [`symbol_part_at`] -/// picks it. +/// picks it: the bounds of the region its live geometry effects give it ([`clip_region`]) when it +/// has any. /// `None` for art past the 9-slice object limit that [`symbol_part_at`] applies. pub fn symbol_part_outline(doc: &Document, inst: &Node, path: &[u32]) -> Option { + symbol_part_outline_in_view(doc, inst, path, HitOptions::default()) +} + +/// [`symbol_part_outline`] in the view the canvas shows, for the clicks of `opt`: in Outline view +/// ([`HitOptions::outline`]) and below a layer whose Preview is off, in the art or around the +/// instance (the isolated container [`HitOptions::scope`] and the layers around it apart), the +/// outlines are cut to the bounds of the plain clipping paths, without their live effects, as +/// [`symbol_part_at`] counts them. The outline is empty when the effects of a clipping path around +/// the object leave no region. +pub fn symbol_part_outline_in_view(doc: &Document, inst: &Node, path: &[u32], opt: HitOptions) -> Option { let art = InstanceArt::of(doc, inst)?; let part = crate::symbol_overrides::part(&art.art, path)?; + let mut outline = opt.outline || below_preview_off(doc, inst, opt.scope); let mut out = BezPath::new(); let mut limit = None; let mut whole = None; let mut n = &art.art; for &i in path { let children = n.children()?; - whole = art.whole(n, doc, whole); + whole = art.whole(n, whole); + outline = outline || previews_off(n); if i != 0 && n.clips() && let Some(first) = children.first() - && let Some(clip) = art.place_unclipped(first, doc, whole)?.geometric_bounds() { - match meet(Some(clip), limit) { - Some(r) => limit = Some(r), - None => return Some(out), - } + let Some(within) = limit_within(&art.place_unclipped(first, whole)?, limit, outline) else { return Some(out) }; + limit = within; } n = children.get(usize::try_from(i).ok()?)?; } - outline_within(&art.place(part, doc, whole)?, limit, &mut out); + outline_within(&art.place(part, whole)?, limit, outline, &mut out); Some(out) } -/// [`symbol_part_outline`] for placed object `n`, cut to `limit` when there is one. -fn outline_within(n: &Node, limit: Option, out: &mut BezPath) { +/// `limit` cut to the box that the art clipped by `clip` is drawn in: the bounds of the region the +/// live geometry effects of `clip` give it ([`clip_region`]), or the bounds of `clip` when it has no +/// such effects and with `outline`, where the canvas draws no effects. `None` when none of that art +/// is drawn: the effects leave no region, or the box is outside `limit`. +fn limit_within(clip: &Node, limit: Option, outline: bool) -> Option> { + use vectorcraft_geom::kurbo::Shape; + let region = if outline { None } else { clip_region(clip) }; + let bounds = match region.as_deref() { + Some(Some((bp, _))) if !bp.elements().is_empty() => Some(bp.bounding_box()), + Some(_) => return None, + None => clip.geometric_bounds(), + }; + match bounds { + Some(b) => meet(Some(b), limit).map(Some), + None => Some(limit), + } +} + +/// [`symbol_part_outline_in_view`] for placed object `n`, cut to `limit` when there is one. +fn outline_within(n: &Node, limit: Option, outline: bool, out: &mut BezPath) { use vectorcraft_geom::kurbo::Shape; if let Some(pd) = n.path_data() { match limit { @@ -1155,20 +1357,15 @@ fn outline_within(n: &Node, limit: Option, out: &mut BezPath) { out.extend(b.to_path(0.1)); } let Some(children) = n.children() else { return }; + let outline = outline || previews_off(n); if n.clips() && let Some((first, rest)) = children.split_first() { - let inner = match first.geometric_bounds() { - Some(c) => match meet(Some(c), limit) { - Some(r) => Some(r), - None => return, - }, - None => limit, - }; - rest.iter().for_each(|c| outline_within(c, inner, out)); + let Some(inner) = limit_within(first, limit, outline) else { return }; + rest.iter().for_each(|c| outline_within(c, inner, outline, out)); return; } - children.iter().for_each(|c| outline_within(c, limit, out)); + children.iter().for_each(|c| outline_within(c, limit, outline, out)); } /// The overlap of `a` and `b` (`a` alone without `b`), `None` when they do not overlap. @@ -1244,31 +1441,48 @@ pub fn compound_part_at(n: &Node, p: Point, tol: f64) -> Option { /// or of the parent of the single object isolated, does not limit the marquee, as it does not limit /// the selection tools' clicks. pub fn marquee(doc: &Document, r: Rect, scope: Option, leaves: bool) -> Vec { - marquee_with(doc, r, scope, leaves, false) + marquee_with(doc, r, scope, leaves, false, false) +} + +/// [`marquee`] in the view the canvas shows: with `outline` (Outline view), and below a layer +/// whose Preview is off, a clipping path counts by its plain shapes, without its live effects, as +/// the clicks of [`HitOptions::outline`] do. +pub fn marquee_in_view(doc: &Document, r: Rect, scope: Option, leaves: bool, outline: bool) -> Vec { + marquee_with(doc, r, scope, leaves, false, outline) } /// Candidates for whole-object enclosure by a loop bounded by `r`. Eligibility and group -/// traversal follow [`marquee`]; compounds contribute the complete path they paint. -pub fn enclosure_candidates(doc: &Document, r: Rect, scope: Option) -> Vec { - marquee_with(doc, r, scope, true, true) +/// traversal follow [`marquee_in_view`]; compounds contribute the complete path they paint. +pub fn enclosure_candidates(doc: &Document, r: Rect, scope: Option, outline: bool) -> Vec { + marquee_with(doc, r, scope, true, true, outline) } -fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, whole_compounds: bool) -> Vec { +/// Is `n` a layer whose Preview is off (its art is drawn and clicked in outline)? +fn previews_off(n: &Node) -> bool { + matches!(n.kind, NodeKind::Layer { preview: false, .. }) +} + +fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, whole_compounds: bool, outline: bool) -> Vec { let mut out = Vec::new(); - // `tops` pairs each object with the part of `r` in which the marquee can touch it. - let tops: Vec<(&std::sync::Arc, Rect)> = match scope.and_then(|s| doc.node(s)) { + // The objects the marquee may touch ([`Top`]). + let tops: Vec = match scope.and_then(|s| doc.node(s)) { // Isolated art whose layer, or a group around it, was locked or hidden afterwards: the // marquee touches none of it, as clicks don't (#5309). Some(s) if !doc.is_editable(s.id) => vec![], Some(s) => match s.children() { - Some(c) => c.iter().enumerate().filter(|(i, c)| !c.is_ruler_guide() && !shaper_hides(s, *i, scope)).map(|(_, c)| (c, r)).collect(), + Some(c) => c + .iter() + .enumerate() + .filter(|(i, c)| !c.is_ruler_guide() && !shaper_hides(s, *i, scope)) + .map(|(_, c)| (c, Some(r), outline, None)) + .collect(), // A single object isolated: only it. None => doc .parent_of(s.id) .and_then(|p| doc.node(p)) .and_then(|p| p.children()) .into_iter() - .flat_map(|c| c.iter().filter(|c| c.id == s.id).map(|c| (c, r))) + .flat_map(|c| c.iter().filter(|c| c.id == s.id).map(|c| (c, Some(r), outline, None))) .collect(), }, // The objects of the layers, looking through sublayers (hidden, locked and template ones @@ -1277,42 +1491,88 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh .layers .iter() .filter(|l| l.visible && !l.locked && !l.is_template() && doc.pattern_edit.as_ref().is_none_or(|e| e.layer == l.id)) - .flat_map(|l| layer_objects(l, r)) + .flat_map(|l| layer_objects(l, r, outline)) .collect(), }; /// The objects of layer `l`, each with the part of `r` that the clipping masks of `l` and of - /// the sublayers it is in leave. - fn layer_objects(l: &Node, r: Rect) -> Vec<(&std::sync::Arc, Rect)> { + /// the sublayers it is in leave, whether it is in outline, and for the clipping mask of `l`, + /// `r` for its edge test. The clipping mask itself counts by its own geometry within its plain + /// shapes ([`mask_marquee`]). + fn layer_objects(l: &Node, r: Rect, outline: bool) -> Vec> { let mut out = vec![]; - let Some(r) = marquee_in(l, r) else { return out }; - for c in l.children().into_iter().flatten() { + let outline = outline || previews_off(l); + let inner = marquee_in_parent(l, r, outline); + for (i, c) in l.children().into_iter().flatten().enumerate() { if c.is_layer() { - if c.visible && !c.locked && !c.is_template() { - out.extend(layer_objects(c, r)); + if let Some(inner) = inner + && c.visible + && !c.locked + && !c.is_template() + { + out.extend(layer_objects(c, inner, outline)); } } else if !c.is_ruler_guide() { - out.push((c, r)); + if i == 0 && l.clips() { + out.push((c, mask_marquee(l, r), outline, Some(r))); + } else if inner.is_some() { + out.push((c, inner, outline, None)); + } } } out } + /// The part of `r` in which the marquee can touch the clipping path of `parent` by its own + /// geometry: within the bounds of its plain shapes ([`marquee_in`]), where clicks find its + /// outline too ([`clip_outline_hit`]), whatever its live effects do to the region it clips to. + fn mask_marquee(parent: &Node, r: Rect) -> Option { + marquee_in_parent(parent, r, true) + } + /// Does the marquee `r` touch `clip`, the clipping path of a clip group or of a layer with a + /// clipping mask, on the edge of the region its live effects give it ([`clip_region`]), where + /// the clip shows? Never in outline, nor without live effects: its own geometry counts then. + fn clip_edge_touches(clip: &Node, r: Rect, outline: bool) -> bool { + if outline { + return false; + } + clip_region(clip).is_some_and(|region| { + region.as_ref().as_ref().is_some_and(|(bp, _)| { + // The edge of the region is its outline with each open subpath closed, as `fill_contains` fills it. + let mut edge = PathData::from_bezpath(bp); + edge.subpaths.iter_mut().for_each(|sp| sp.closed = true); + vectorcraft_geom::hit::intersects_rect(&edge, r) + }) + }) + } + /// Is `n` collected whole by [`collect_leaves`], not by its members? + fn is_leaf(n: &Node) -> bool { + !matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Intertwine { .. }) + } /// Does the marquee `r` touch `n`? It skips the children of a Shaper Group that clicks skip /// ([`shaper_hides`]). An Intertwine group is touched by its members, and a repeat is touched /// by the copies it draws, as clicks hit them. Objects of every other kind except paths, - /// compound paths, layers and groups are touched by their box. - fn touches(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option, whole_compounds: bool) -> bool { + /// compound paths, layers and groups are touched by their box. A clipping path is touched by + /// its own geometry ([`mask_marquee`]) and on the edge of its region ([`clip_edge_touches`]). + fn touches(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option, whole_compounds: bool, outline: bool) -> bool { match &n.kind { NodeKind::Path { path, .. } => vectorcraft_geom::hit::intersects_rect(path, r), NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Intertwine { children } => { - marquee_in(n, r).is_some_and(|r| { - children.iter().enumerate().any(|(i, c)| c.visible && !shaper_hides(n, i, scope) && touches(c, s, r, scope, whole_compounds)) + let outline = outline || previews_off(n); + let inner = marquee_in_parent(n, r, outline); + children.iter().enumerate().any(|(i, c)| { + c.visible + && !shaper_hides(n, i, scope) + && if i == 0 && n.clips() { + mask_marquee(n, r).is_some_and(|r| touches(c, s, r, scope, whole_compounds, outline)) || clip_edge_touches(c, r, outline) + } else { + inner.is_some_and(|r| touches(c, s, r, scope, whole_compounds, outline)) + } }) } NodeKind::Compound { children, .. } if whole_compounds => { children.iter().filter_map(|c| c.path_data()).any(|path| vectorcraft_geom::hit::intersects_rect(path, r)) } - NodeKind::Compound { children, .. } => children.iter().any(|c| c.visible && touches(c, s, r, scope, whole_compounds)), - NodeKind::Repeat(spec) => spec.expand(Some(s.document())).iter().any(|copy| touches(copy, s, r, scope, whole_compounds)), + NodeKind::Compound { children, .. } => children.iter().any(|c| c.visible && touches(c, s, r, scope, whole_compounds, outline)), + NodeKind::Repeat(spec) => spec.expand(Some(s.document())).iter().any(|copy| touches(copy, s, r, scope, whole_compounds, outline)), // A box with no width or no height (an instance of a symbol that draws a straight // line) is touched where the marquee crosses it. _ => n.geometric_bounds_with(s).is_some_and(|b| { @@ -1321,18 +1581,30 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh }), } } - fn collect_leaves(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option, whole_compounds: bool, out: &mut Vec) { + fn collect_leaves(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option, whole_compounds: bool, outline: bool, out: &mut Vec) { match &n.kind { NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Intertwine { children } => { - let Some(r) = marquee_in(n, r) else { return }; + let outline = outline || previews_off(n); + let inner = marquee_in_parent(n, r, outline); for (i, c) in children.iter().enumerate() { - if c.visible && !c.locked && !shaper_hides(n, i, scope) { - collect_leaves(c, s, r, scope, whole_compounds, out); + if !c.visible || c.locked || shaper_hides(n, i, scope) { + continue; + } + if i == 0 && n.clips() { + let before = out.len(); + if let Some(r) = mask_marquee(n, r) { + collect_leaves(c, s, r, scope, whole_compounds, outline, out); + } + if out.len() == before && is_leaf(c) && clip_edge_touches(c, r, outline) { + out.push(c.id); + } + } else if let Some(r) = inner { + collect_leaves(c, s, r, scope, whole_compounds, outline, out); } } } _ => { - if touches(n, s, r, scope, whole_compounds) { + if touches(n, s, r, scope, whole_compounds, outline) { out.push(n.id); } } @@ -1340,36 +1612,56 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh } let symbols = doc.symbol_boxes(); let locks = doc.locked_artboards(); - for (t, r) in tops { + for (t, r, outline, edge) in tops { if !t.visible || t.locked || locks.holds_id(t.id) { continue; } if leaves { - collect_leaves(t, &symbols, r, scope, whole_compounds, &mut out); - } else if touches(t, &symbols, r, scope, whole_compounds) { + let before = out.len(); + if let Some(r) = r { + collect_leaves(t, &symbols, r, scope, whole_compounds, outline, &mut out); + } + if edge.is_some_and(|e| out.len() == before && is_leaf(t) && clip_edge_touches(t, e, outline)) { + out.push(t.id); + } + } else if r.is_some_and(|r| touches(t, &symbols, r, scope, whole_compounds, outline)) + || edge.is_some_and(|e| clip_edge_touches(t, e, outline)) + { out.push(t.id); } } out } +/// An object a marquee may touch ([`marquee_with`]): the object, the part of the marquee in which +/// it can be touched (`None` when nowhere), whether it is in outline, and for the clipping mask of a +/// layer, the marquee whose edge test it also takes (`clip_edge_touches`). +type Top<'a> = (&'a std::sync::Arc, Option, bool, Option); + /// The part of a marquee `r` in which it can touch the children of `parent`. For a clip group or a -/// layer with a clipping mask, this is what [`marquee_in_clip`] returns for its clipping path (None -/// when the marquee misses it); otherwise it is all of `r`. +/// layer with a clipping mask, this is what [`marquee_in_clip`] returns for the plain shapes of its +/// clipping path ([`clip_regions`]; None when the marquee misses them); otherwise it is all of `r`. pub fn marquee_in(parent: &Node, r: Rect) -> Option { + marquee_in_parent(parent, r, true) +} + +/// The part of a marquee `r` in which it can touch the children of `parent`, by the region its +/// clipping path clips to ([`clip_areas`]), or by that path's plain shapes with `outline` +/// ([`marquee_in_view`]). +fn marquee_in_parent(parent: &Node, r: Rect, outline: bool) -> Option { match parent.children().and_then(|c| c.first()) { - Some(clip) if parent.clips() => marquee_in_clip(clip, r), + Some(clip) if parent.clips() => marquee_in_clip(clip, r, outline), _ => Some(r), } } /// The part of a marquee `r` in which it can touch the art that `clip` clips (the clipping path of /// a clip group or of a layer with a clipping mask): `r` cut to the bounds of the regions `clip` -/// clips to ([`clip_regions`]), or `None` when `r` meets none of those regions. Within those -/// bounds, art outside a region that is not a rectangle still counts. -fn marquee_in_clip(clip: &Node, r: Rect) -> Option { +/// clips to ([`clip_areas`], its plain shapes with `outline`), or `None` when `r` meets none of +/// those regions. Within those bounds, art outside a region that is not a rectangle still counts. +fn marquee_in_clip(clip: &Node, r: Rect, outline: bool) -> Option { use vectorcraft_geom::kurbo::Shape; - let regions = clip_regions(clip); + let regions = if outline { clip_regions(clip) } else { clip_areas(clip) }; // The edge of a region is its outline with each open subpath closed, as `fill_contains` fills it. let meets = |(bp, rule): &(vectorcraft_geom::BezPath, vectorcraft_geom::FillRule)| { let mut edge = vectorcraft_geom::PathData::from_bezpath(bp); diff --git a/crates/doc/src/hit/tests.rs b/crates/doc/src/hit/tests.rs index 3eac4202b6..dde7365424 100644 --- a/crates/doc/src/hit/tests.rs +++ b/crates/doc/src/hit/tests.rs @@ -110,6 +110,252 @@ fn half_clipped(d: &mut Document) -> (Node, Node) { (mask, art) } +/// A stand-in for the engine's [`ClipRegion`]: with an effect named `test.move` in the clipping +/// path, its first shape moved 100 pt right; with one named `test.empty`, no region left to clip +/// by; without either, no geometry effect. +fn moved_clip_region(clip: &Node) -> Option> { + let (mut moves, mut empty) = (false, false); + clip.walk(&mut |n| { + moves |= n.appearance.effects.iter().any(|e| e.visible && e.id == "test.move"); + empty |= n.appearance.effects.iter().any(|e| e.visible && e.id == "test.empty"); + }); + if empty { + return Some(None); + } + if !moves { + return None; + } + Some(clip_regions(clip).into_iter().next().map(|(mut bp, rule)| { + bp.apply_affine(vectorcraft_geom::Affine::translate((100.0, 0.0))); + (bp, rule) + })) +} + +/// A visible effect named `test.move`, which [`moved_clip_region`] reads as moving the region. +fn test_move() -> crate::Effect { + crate::Effect { id: "test.move".into(), params: serde_json::json!({}), visible: true } +} + +/// Clicks inside a clip group whose clipping path has a live effect fall in the region the +/// registered [`ClipRegion`] gives it. The pointer moving over it evaluates the region once, and +/// again after the clipping path changes; a clipping path without effects is not evaluated. +#[test] +fn clicks_in_a_clip_group_evaluate_its_clipping_paths_region_once_until_it_changes() { + set_clip_region(moved_clip_region); + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + let (mut mask, art) = half_clipped(&mut d); + mask.appearance.effects.push(crate::Effect { id: "test.move".into(), params: serde_json::json!({}), visible: true }); + let (g, mask_id, art_id) = (d.alloc_id(), mask.id, art.id); + let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]); + clip.set_clips(true); + d.insert(Some(l), 0, clip).unwrap(); + let evaluated = || CLIPS_EVALUATED.with(std::cell::Cell::get); + let before = evaluated(); + let leaf = |d: &Document, x: f64| hit_test(d, Point::new(x, 50.0), HitOptions::default()).map(|h| h.leaf); + for x in [148.0, 150.0, 152.0] { + assert_eq!(leaf(&d, x), Some(art_id), "in the moved region"); + } + assert_eq!(leaf(&d, 50.0), None, "the clipping path's own place"); + assert_eq!(evaluated(), before + 1); + // Outline mode draws no effects: the art's edge shows within the clipping path's own shape. + let outline = HitOptions { outline: true, ..HitOptions::default() }; + assert_eq!(hit_test(&d, Point::new(50.0, 0.5), outline).map(|h| h.leaf), Some(art_id), "outline mode"); + // So with a marquee across the art's left edge: in the view, only in Outline view. The + // clipping path's own left edge lies there too, and counts in both. + let edge = Rect::new(-5.0, 40.0, 5.0, 60.0); + assert_eq!(marquee_in_view(&d, edge, None, true, false), [mask_id]); + assert_eq!(marquee_in_view(&d, edge, None, true, true), [mask_id, art_id]); + // `marquee_in` measures by the plain shapes, as its callers clip by them. + assert!(marquee_in(d.node(g).unwrap(), edge).is_some()); + // Hidden, the effect no longer moves the region. + d.node_mut(mask_id).unwrap().appearance.effects[0].visible = false; + assert_eq!(leaf(&d, 50.0), Some(art_id)); + assert_eq!(leaf(&d, 150.0), None); + assert_eq!(evaluated(), before + 1); + // Shown again and widened, the region is evaluated again. + let mask = d.node_mut(mask_id).unwrap(); + mask.appearance.effects[0].visible = true; + if let NodeKind::Path { path, .. } = &mut mask.kind { + *path = shapes::rectangle(Rect::new(0.0, 0.0, 90.0, 100.0)); + } + assert_eq!(leaf(&d, 180.0), Some(art_id)); + assert_eq!(leaf(&d, 195.0), None); + assert_eq!(evaluated(), before + 2); +} + +/// A marquee around a clipping path that an effect moved into the middle of large art touches the +/// clipping path on the edge of its moved region, in a clip group and in a clipping layer. +#[test] +fn a_marquee_touches_a_moved_clipping_path_on_its_region() { + set_clip_region(moved_clip_region); + let parts = |d: &mut Document| { + let mut mask = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(20.0, 20.0, 60.0, 60.0)), Appearance::default()); + mask.appearance.effects.push(crate::Effect { id: "test.move".into(), params: serde_json::json!({}), visible: true }); + let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 300.0, 300.0)), Appearance::default_art()); + (mask, art) + }; + // Around the moved region (120..160) and the clipping path's own place, inside the art. + let around = Rect::new(10.0, 10.0, 170.0, 70.0); + let mut d = Document::new(400.0, 400.0); + let l = d.layers[0].id; + let (mask, art) = parts(&mut d); + let (g, mask_id) = (d.alloc_id(), mask.id); + let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]); + clip.set_clips(true); + d.insert(Some(l), 0, clip).unwrap(); + assert_eq!(marquee(&d, around, None, false), [g]); + assert_eq!(marquee(&d, around, None, true), [mask_id]); + // Only over the clipping path's own place, the marquee misses the region but touches the + // clipping path's anchors, which a click on its outline also finds. + let own = Rect::new(10.0, 10.0, 70.0, 70.0); + assert_eq!(marquee(&d, own, None, false), [g]); + assert_eq!(marquee(&d, own, None, true), [mask_id]); + // Away from both, nothing. + assert!(marquee(&d, Rect::new(70.0, 10.0, 110.0, 70.0), None, true).is_empty()); + + let mut d = Document::new(400.0, 400.0); + let top = d.layers[0].id; + let (mask, art) = parts(&mut d); + let mask_id = mask.id; + let mut sublayer = (*d.layers[0]).clone(); + sublayer.id = d.alloc_id(); + if let NodeKind::Layer { children, clip, .. } = &mut sublayer.kind { + (*children, *clip) = (vec![Arc::new(mask), Arc::new(art)], true); + } + d.insert(Some(top), 0, sublayer).unwrap(); + assert_eq!(marquee(&d, around, None, false), [mask_id]); +} + +/// A clipping layer whose Preview is off draws its art in outline: clicks, the objects at a point +/// and marquees count its clipping path by its plain shape, without the effect that moves it. +#[test] +fn a_clipping_layer_with_preview_off_counts_its_plain_clipping_path() { + set_clip_region(moved_clip_region); + let mut d = Document::new(300.0, 200.0); + let top = d.layers[0].id; + let (mut mask, art) = half_clipped(&mut d); + mask.appearance.effects.push(crate::Effect { id: "test.move".into(), params: serde_json::json!({}), visible: true }); + let art_id = art.id; + let mut sublayer = (*d.layers[0]).clone(); + sublayer.id = d.alloc_id(); + if let NodeKind::Layer { children, clip, preview, .. } = &mut sublayer.kind { + (*children, *clip, *preview) = (vec![Arc::new(mask), Arc::new(art)], true, false); + } + d.insert(Some(top), 0, sublayer).unwrap(); + // The art's top edge, within the clipping path's own shape. + let p = Point::new(50.0, 0.5); + assert_eq!(hit_test(&d, p, HitOptions::default()).map(|h| h.leaf), Some(art_id)); + assert_eq!(objects_at(&d, p, HitOptions::default(), None).first(), Some(&art_id)); + assert!(marquee(&d, Rect::new(45.0, -5.0, 55.0, 5.0), None, true).contains(&art_id)); +} + +/// The pointer moving over empty canvas past more clip groups with live effects than the regions +/// kept measures each group's box once: the boxes are kept for every clip group. +#[test] +fn hovers_past_many_clip_groups_evaluate_each_clipping_path_once() { + set_clip_region(moved_clip_region); + let mut d = Document::new(1000.0, 1000.0); + let l = d.layers[0].id; + for i in 0..(2 * CLIPS_KEPT) { + let x = 20.0 * i as f64; + let mut mask = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, 0.0, x + 10.0, 10.0)), Appearance::default()); + mask.appearance.effects.push(crate::Effect { id: "test.move".into(), params: serde_json::json!({}), visible: true }); + let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, 0.0, x + 20.0, 10.0)), Appearance::default_art()); + let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(art)]); + clip.set_clips(true); + d.insert(Some(l), 0, clip).unwrap(); + } + let evaluated = || CLIPS_EVALUATED.with(std::cell::Cell::get); + let empty = Point::new(500.0, 500.0); + assert!(hit_test(&d, empty, HitOptions::default()).is_none()); + let first = evaluated(); + for _ in 0..3 { + assert!(hit_test(&d, empty, HitOptions::default()).is_none()); + } + assert_eq!(evaluated(), first); +} + +/// With more clip groups with live effects than the boxes kept, a new box replaces only as many +/// others as it needs room for: the next hover finds most of the boxes and evaluates few regions. +#[test] +fn hovers_past_more_clip_groups_than_the_boxes_kept_evaluate_few_again() { + set_clip_region(moved_clip_region); + let mut d = Document::new(1000.0, 1000.0); + let l = d.layers[0].id; + let groups = CLIP_BOXES_KEPT + 64; + let mut members = Vec::with_capacity(groups); + for i in 0..groups { + let x = (i % 100) as f64 * 5.0; + let y = (i / 100) as f64 * 5.0; + let mut mask = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, y, x + 2.0, y + 2.0)), Appearance::default()); + mask.appearance.effects.push(test_move()); + let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, y, x + 4.0, y + 2.0)), Appearance::default_art()); + let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(art)]); + clip.set_clips(true); + members.push(Arc::new(clip)); + } + if let Some(children) = d.node_mut(l).and_then(|n| n.children_mut()) { + *children = members; + } + let evaluated = || CLIPS_EVALUATED.with(std::cell::Cell::get); + let empty = Point::new(900.0, 900.0); + assert!(hit_test(&d, empty, HitOptions::default()).is_none()); + let first = evaluated(); + assert!(hit_test(&d, empty, HitOptions::default()).is_none()); + let again = evaluated() - first; + assert!(again < groups / 8, "{again} of {groups} regions evaluated again"); +} + +/// Every test of a clip group by its clipping path follows the region a live effect moved it to: +/// the selected art hidden by the mask, a click into a group holding the clip group, the locked +/// objects under the pointer, and, below a clipping layer whose Preview is on, art on a sublayer +/// whose Preview is off, which is clicked in outline while the layer above clips by its region. +#[test] +fn every_clip_test_follows_the_moved_region() { + set_clip_region(moved_clip_region); + let (moved, own) = (Point::new(150.0, 50.0), Point::new(50.0, 50.0)); + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + let (mut mask, art) = half_clipped(&mut d); + mask.appearance.effects.push(test_move()); + let (g, art_id) = (d.alloc_id(), art.id); + let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]); + clip.set_clips(true); + let outer = Node::group(d.alloc_id(), vec![Arc::new(clip)]); + d.insert(Some(l), 0, outer.clone()).unwrap(); + let opt = HitOptions::default(); + assert_eq!(selected_hidden_at(&d, own, opt, &[art_id]), Some(art_id), "hidden at the clipping path's own place"); + assert_eq!(selected_hidden_at(&d, moved, opt, &[art_id]), None, "shown in the moved region"); + let symbols = d.symbol_boxes(); + assert_eq!(hit_any(&outer, moved, opt, &symbols), Some(HitKind::Fill)); + assert_eq!(hit_any(&outer, own, opt, &symbols), None); + d.node_mut(art_id).unwrap().locked = true; + assert_eq!(locked_objects_at(&d, moved, opt), [art_id]); + assert!(locked_objects_at(&d, own, opt).is_empty()); + + // A clipping layer holding the mask and a sublayer whose Preview is off, with the art. + let mut d = Document::new(300.0, 200.0); + let top = d.layers[0].id; + let (mut mask, art) = half_clipped(&mut d); + mask.appearance.effects.push(test_move()); + let art_id = art.id; + let mut sublayer = (*d.layers[0]).clone(); + sublayer.id = d.alloc_id(); + if let NodeKind::Layer { children, preview, .. } = &mut sublayer.kind { + (*children, *preview) = (vec![Arc::new(art)], false); + } + d.insert(Some(top), 0, sublayer).unwrap(); + d.insert(Some(top), 0, mask).unwrap(); + d.node_mut(top).unwrap().set_clips(true); + // The art's top edge, at the clipping path's own place and in the moved region. + let (own, moved) = (Point::new(50.0, 0.5), Point::new(150.0, 0.5)); + assert!(hit_test(&d, own, opt).is_none()); + assert_eq!(hit_test(&d, moved, opt).map(|h| h.leaf), Some(art_id)); + assert_eq!(selected_hidden_at(&d, own, opt, &[art_id]), Some(art_id)); + assert_eq!(selected_hidden_at(&d, moved, opt, &[art_id]), None); +} + /// The art a mask hides counts only for a selected object: there a click hits nothing, and the /// selection tools grab the selection by that art. Not where the art shows (the click hits it), /// beyond the art, for the clip group selected as a whole, nor for art a click can't hit (locked, @@ -1549,6 +1795,63 @@ fn an_object_a_clipping_layer_in_symbol_art_hides_is_not_picked_there() { assert!((b.x1 - 100.0).abs() < 1e-6, "the layer's outline is cut to the mask: {b:?}"); } +/// In a dynamic symbol's art, an object in a clipping layer whose clipping path has a live effect +/// is picked and outlined in the region the effect gives the clipping path. In Outline view, and +/// when Preview is off for the layer in the art or for the layer the instance is on, the plain +/// clipping path counts, as the canvas draws it. An effect that leaves no region leaves no outline. +#[test] +fn a_symbol_part_follows_the_region_its_clipping_layers_effects_give_it() { + set_clip_region(moved_clip_region); + // The instance of a symbol whose art is a clipping layer; `preview` is the Preview of that + // layer and of the document layer the instance is on. + let instance = |effect: &str, preview: [bool; 2]| { + let mut d = Document::new(300.0, 200.0); + if let NodeKind::Layer { preview: p, .. } = &mut Arc::make_mut(&mut d.layers[0]).kind { + *p = preview[1]; + } + let l = d.layers[0].id; + let (mut mask, art) = half_clipped(&mut d); + mask.appearance.effects.push(crate::Effect { id: effect.into(), ..test_move() }); + let mut layer = Node::layer(d.alloc_id(), "Masked", crate::LayerColor::Preset(2)); + if let NodeKind::Layer { children, preview: p, .. } = &mut layer.kind { + (*children, *p) = (vec![Arc::new(mask), Arc::new(art)], preview[0]); + } + layer.set_clips(true); + let root = Node::group(d.alloc_id(), vec![Arc::new(layer)]); + d.symbols.push(crate::Symbol { dynamic: true, name: "Clipped".into(), art: Arc::new(root) }); + let inst = d.alloc_id(); + d.insert(Some(l), 0, Node::new(inst, NodeKind::SymbolInstance { symbol: "Clipped".into(), xf: vectorcraft_geom::Affine::IDENTITY })).unwrap(); + (d, inst) + }; + let outline_box = |d: &Document, inst: NodeId, opt: HitOptions| { + let o = symbol_part_outline_in_view(d, d.node(inst).unwrap(), &[0, 1], opt).unwrap(); + vectorcraft_geom::kurbo::Shape::bounding_box(&o) + }; + let opt = HitOptions::default(); + let (d, inst) = instance("test.move", [true, true]); + let n = d.node(inst).unwrap(); + assert_eq!(symbol_part_at(&d, n, Point::new(150.0, 50.0), opt), Some(vec![0, 1]), "in the moved region"); + assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 50.0), opt), None, "where the clipping path was"); + let b = outline_box(&d, inst, opt); + assert!((b.x0 - 100.0).abs() < 1e-6 && (b.x1 - 200.0).abs() < 1e-6, "the outline is cut to the moved region: {b:?}"); + let b = outline_box(&d, inst, HitOptions { outline: true, ..opt }); + assert!(b.x0.abs() < 1e-6 && (b.x1 - 100.0).abs() < 1e-6, "in Outline view, to the plain clipping path: {b:?}"); + // With Preview off, the art's top edge counts within the plain clipping path. + for (preview, what) in [([false, true], "the layer in the art"), ([true, false], "the layer the instance is on")] { + let (d, inst) = instance("test.move", preview); + let n = d.node(inst).unwrap(); + assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 0.5), opt), Some(vec![0, 1]), "on the edge the canvas draws, Preview off for {what}"); + assert_eq!(symbol_part_at(&d, n, Point::new(150.0, 0.5), opt), None, "past the plain clipping path, Preview off for {what}"); + let b = outline_box(&d, inst, opt); + assert!(b.x0.abs() < 1e-6 && (b.x1 - 100.0).abs() < 1e-6, "Preview off for {what}: the plain clipping path: {b:?}"); + } + // An effect that leaves the clipping path no region hides the art: no pick and no outline. + let (d, inst) = instance("test.empty", [true, true]); + let n = d.node(inst).unwrap(); + assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 50.0), opt), None); + assert!(symbol_part_outline(&d, n, &[0, 1]).unwrap().elements().is_empty(), "nothing is drawn, so nothing is outlined"); +} + /// In a dynamic symbol's art that placing through its 9-slice guides could make more than /// [`crate::MAX_SYMBOL_NODES`] objects of, Direct Selection picks and outlines nothing, as the /// canvas draws nothing of it. At the art's natural size the same art is picked. @@ -1586,6 +1889,53 @@ fn symbol_art_past_the_object_limit_picks_nothing() { assert!(symbol_part_outline(&d, n, &[0]).is_some()); } +/// Picking and outlining an object of a 9-slice instance's art, and placing that art, read the +/// symbol list once for each call, however many instances the art holds. +#[test] +fn picking_in_9_slice_art_reads_the_symbol_list_once() { + let mut d = Document::new(400.0, 400.0); + for i in 0..2_000 { + let dot = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), Appearance::default_art()); + d.symbols.push(crate::Symbol { dynamic: false, name: format!("Dot {i}"), art: Arc::new(dot) }); + } + // A frame, a group of 20 squares in its top left cell, and 20 instances of the dots across + // the guides. + let square = |d: &mut Document, x: f64, y: f64| { + Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, y, x + 4.0, y + 4.0)), Appearance::default_art())) + }; + let corner: Vec<_> = (0..20).map(|i| square(&mut d, f64::from(i % 5) * 4.0, f64::from(i / 5) * 4.0)).collect(); + let dot = |d: &mut Document, i: u32| { + let xf = vectorcraft_geom::Affine::translate((f64::from(i) * 4.5 + 5.0, 48.0)) * vectorcraft_geom::Affine::scale(4.0); + Arc::new(Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: format!("Dot {i}"), xf })) + }; + let across: Vec<_> = (0..20).map(|i| dot(&mut d, i)).collect(); + let frame = Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default_art())); + let mut kids = vec![frame, Arc::new(Node::group(d.alloc_id(), corner))]; + kids.extend(across); + let root = Node::group(d.alloc_id(), kids); + d.symbols.push(crate::Symbol { dynamic: true, name: "Panel".into(), art: Arc::new(root) }); + d.set_symbol_nine_slice("Panel", Some(crate::SymbolNineSlice::default())); + let xf = vectorcraft_geom::Affine::scale_non_uniform(2.0, 1.5); + let inst = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Panel".into(), xf }); + let art = d.symbols[2_000].art.clone(); + let symbols = d.symbols.len(); + let read = || crate::symbols::SYMBOLS_READ.with(std::cell::Cell::get); + let reads = |f: &dyn Fn()| { + let before = read(); + f(); + read() - before + }; + // Picking also tests the placed art with boxes of its own, as a click outside symbols does. + let n = reads(&|| assert_eq!(symbol_part_at(&d, &inst, Point::new(2.0, 2.0), HitOptions::default()).map(|p| p[0]), Some(1))); + assert!(n <= 2 * symbols, "picking read {n} symbols"); + let n = reads(&|| assert!(symbol_part_outline(&d, &inst, &[2]).is_some())); + assert!(n <= symbols, "outlining read {n} symbols"); + let n = reads(&|| assert!(d.place_symbol_art("Panel", &art, xf).is_some())); + assert!(n <= symbols, "placing read {n} symbols"); + let n = reads(&|| assert!(d.place_symbol_art_unclipped("Panel", &art, xf).is_some())); + assert!(n <= symbols, "placing without clips read {n} symbols"); +} + /// A clip group that lies in one 9-slice cell is moved by that cell as one piece, everything in it /// included, so an object in it is picked and outlined there even when placing that object through /// the guides on its own would pass [`crate::MAX_SYMBOL_NODES`] objects. diff --git a/crates/doc/src/inks.rs b/crates/doc/src/inks.rs index e10c424ee9..a9fa5f3f80 100644 --- a/crates/doc/src/inks.rs +++ b/crates/doc/src/inks.rs @@ -94,25 +94,45 @@ pub fn inks(doc: &Document, c: &Cms, color: &Color, link: Link, intent: Intent) Inks { cmyk: c.to_cmyk(color, intent), spot: None, registration: false } } -/// Visits one colour: the colour, its swatch link and its tint, all of which it may change. -pub type ColorVisitor<'a> = dyn FnMut(&mut Color, &mut Option, &mut f32) + 'a; +/// Process plates a colour prints together with its spot tint (C, M, Y, K, 0..1): a gradient +/// stop's [`vectorcraft_color::GradientStop::plates`]; `None` for every other colour. +pub type StopPlates = Option<[f32; 4]>; + +/// [`inks`] of a colour that may print process plates `plates` with its spot tint. The plates +/// print only beside a spot ink: a colour without a valid spot link, or linked to Registration, +/// prints as [`inks`] separates it. A plate amount that is not a finite number prints no ink. +pub fn stop_inks(doc: &Document, c: &Cms, color: &Color, link: Link, plates: StopPlates, intent: Intent) -> Inks { + let mut ink = inks(doc, c, color, link, intent); + if let (Some(p), Some(_)) = (plates, &ink.spot) { + ink.cmyk = p.map(|v| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }); + } + ink +} + +/// Visits one colour: the colour, its swatch link, its tint and its process plates +/// ([`StopPlates`]), all of which it may change. +pub type ColorVisitor<'a> = dyn FnMut(&mut Color, &mut Option, &mut f32, &mut StopPlates) + 'a; fn visit_paint(p: &mut Paint, f: &mut ColorVisitor) { match p { - Paint::Solid { color, swatch, tint } => f(color, swatch, tint), + Paint::Solid { color, swatch, tint } => f(color, swatch, tint, &mut None), Paint::Gradient(g) => { for s in &mut g.gradient.stops { - f(&mut s.color, &mut s.swatch, &mut s.tint); + f(&mut s.color, &mut s.swatch, &mut s.tint, &mut s.plates); + } + for p in g.freeform.iter_mut().flat_map(|ff| ff.points.iter_mut()) { + f(&mut p.color, &mut None, &mut 1.0, &mut None); } } _ => {} } } -/// Visit every colour of a node tree (fills, strokes, gradient stops, text runs, mesh points, an -/// image's colorize color, the fills and strokes a dynamic symbol instance keeps for objects of its -/// art, not opacity masks) with its swatch link and tint. Mesh points have no link: changes to it -/// are dropped. +/// Visit every colour of a node tree (fills, strokes, gradient stops, a freeform gradient's +/// points, text runs, mesh points, an image's colorize color, the fills and strokes a dynamic +/// symbol instance keeps for objects of its art, not opacity masks) with its swatch link, tint and +/// process plates. Freeform and mesh points have no link or plates: a link or plates `f` gives +/// them are dropped. pub fn visit_node_colors(n: &mut Node, f: &mut ColorVisitor) { for it in &mut n.appearance.items { match it { @@ -137,7 +157,7 @@ pub fn visit_node_colors(n: &mut Node, f: &mut ColorVisitor) { } NodeKind::Mesh(m) => { for p in &mut m.points { - f(&mut p.color, &mut None, &mut 1.0); + f(&mut p.color, &mut None, &mut 1.0, &mut None); } } _ => {} @@ -149,11 +169,16 @@ pub fn visit_node_colors(n: &mut Node, f: &mut ColorVisitor) { } } -/// Apply `f` to every colour of a node tree (fills, strokes, gradient stops, text runs, mesh -/// points, a dynamic symbol instance's own fills and strokes) given its swatch link and tint, -/// keeping the links. +/// Apply `f` to every colour of a node tree (fills, strokes, gradient stops, a freeform +/// gradient's points, text runs, mesh points, a dynamic symbol instance's own fills and strokes) +/// given its swatch link and tint, keeping the links and process plates. pub fn map_node_colors(n: &mut Node, f: &mut dyn FnMut(&Color, Link) -> Color) { - visit_node_colors(n, &mut |c, swatch, tint| *c = f(c, swatch.as_deref().map(|s| (s, *tint)))); + map_node_inks(n, &mut |c, link, _| f(c, link)); +} + +/// [`map_node_colors`], with each colour's process plates ([`StopPlates`]) passed to `f` too. +pub fn map_node_inks(n: &mut Node, f: &mut dyn FnMut(&Color, Link, StopPlates) -> Color) { + visit_node_colors(n, &mut |c, swatch, tint, plates| *c = f(c, swatch.as_deref().map(|s| (s, *tint)), *plates)); } /// Apply `f` to every colour in the document's art and symbol definitions. @@ -170,8 +195,70 @@ pub fn map_document_colors(doc: &mut Document, f: &mut dyn FnMut(&Color, Link) - mod tests { use super::*; use crate::{NodeId, SymbolOverride}; + use vectorcraft_color::{Freeform, FreeformPoint, Gradient, GradientKind, GradientPaint, GradientStop, Swatch}; use vectorcraft_geom::Affine; + /// A document with spot swatch `Gold` and process swatch `Teal`. + fn gold_doc() -> Document { + let mut d = Document::new(100.0, 100.0); + d.swatches.push(Swatch { name: "Gold".into(), paint: Paint::solid(Color::cmyk(0.0, 0.2, 0.8, 0.1)), global: true, spot: true }); + d.swatches.push(Swatch { name: "Teal".into(), paint: Paint::solid(Color::cmyk(0.8, 0.0, 0.3, 0.0)), global: true, spot: false }); + d + } + + #[test] + fn a_spot_stops_process_plates_print_with_its_tint() { + let d = gold_doc(); + let c = vectorcraft_color::cms::active(); + let look = Color::cmyk(0.25, 0.1, 0.8, 0.05); + let ink = |link: Link, plates: StopPlates| stop_inks(&d, &c, &look, link, plates, Intent::RelativeColorimetric); + let mixed = ink(Some(("Gold", 0.5)), Some([0.25, 0.0, 0.4, 0.0])); + assert_eq!(mixed, Inks { cmyk: [0.25, 0.0, 0.4, 0.0], spot: Some(("Gold".into(), 0.5)), registration: false }); + assert_eq!((mixed.on_plate("Cyan"), mixed.on_plate("Gold")), (0.25, 0.5)); + // Amounts outside 0..1 are clamped; one that is not a number prints no ink. + let odd = ink(Some(("Gold", 1.0)), Some([f32::NAN, 2.0, -1.0, f32::INFINITY])); + assert_eq!(odd.cmyk, [0.0, 1.0, 0.0, 0.0]); + // Without plates the spot ink prints alone, as `inks` separates it. + assert_eq!(ink(Some(("Gold", 0.5)), None), inks(&d, &c, &look, Some(("Gold", 0.5)), Intent::RelativeColorimetric)); + // Plates beside no spot ink print nothing of their own: a process swatch, an unknown + // swatch, no link and Registration separate as `inks` does. + for link in [Some(("Teal", 1.0)), Some(("Missing", 1.0)), None, Some((REGISTRATION, 0.5))] { + assert_eq!(ink(link, Some([0.25, 0.0, 0.4, 0.0])), inks(&d, &c, &look, link, Intent::RelativeColorimetric), "{link:?}"); + } + } + + #[test] + fn gradient_stops_pass_their_plates_and_freeform_points_are_visited() { + let mut stop = GradientStop::new(0.0, Color::cmyk(0.25, 0.1, 0.8, 0.05)); + (stop.swatch, stop.tint, stop.plates) = (Some("Gold".into()), 0.5, Some([0.25, 0.0, 0.4, 0.0])); + let mut g = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![stop, GradientStop::new(1.0, Color::rgb(1.0, 1.0, 1.0))])); + let point = FreeformPoint::new(kurbo::Point::new(10.0, 10.0), Color::rgb(0.0, 1.0, 0.0)); + g.freeform = Some(Freeform { points: vec![point], ..Default::default() }); + let mut n = Node::path( + NodeId(1), + vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0)), + crate::Appearance::basic(Paint::Gradient(Box::new(g)), Paint::None, 0.0), + ); + let mut seen = vec![]; + let gray = Color::Gray { k: 0.5 }; + map_node_inks(&mut n, &mut |c, link, plates| { + seen.push((*c, link.map(|(s, t)| (s.to_string(), t)), plates)); + gray + }); + assert_eq!( + seen, + vec![ + (Color::cmyk(0.25, 0.1, 0.8, 0.05), Some(("Gold".to_string(), 0.5)), Some([0.25, 0.0, 0.4, 0.0])), + (Color::rgb(1.0, 1.0, 1.0), None, None), + (Color::rgb(0.0, 1.0, 0.0), None, None), + ] + ); + let Some(Paint::Gradient(g)) = n.appearance.fill().map(|f| f.paint.clone()) else { panic!("no gradient fill") }; + assert_eq!(g.gradient.stops[0].plates, Some([0.25, 0.0, 0.4, 0.0]), "mapping a colour keeps its plates"); + assert!(g.gradient.stops.iter().all(|s| s.color == gray)); + assert_eq!(g.freeform.map(|f| f.points[0].color), Some(gray), "the freeform point is mapped too"); + } + #[test] fn a_dynamic_instances_own_fills_and_strokes_are_visited() { let red = Color::rgb(1.0, 0.0, 0.0); diff --git a/crates/doc/src/inline.rs b/crates/doc/src/inline.rs index a8e3955015..86c26e14f4 100644 --- a/crates/doc/src/inline.rs +++ b/crates/doc/src/inline.rs @@ -8,13 +8,20 @@ use std::sync::{Arc, RwLock, Weak}; use vectorcraft_geom::{Affine, Rect}; -use crate::{Document, Node, NodeId, NodeKind, Symbol, TextObject}; +use crate::symbols::SymbolNames; +use crate::{Document, Node, NodeId, NodeKind, Symbol, SymbolBoxes, TextObject}; /// The document key under which the app records each symbol's natural size (`{name: [w, h]}`). pub const SYMBOL_SIZES: &str = "symbolSizes"; /// Half the side of the square symbol art is normalised to. pub const SYMBOL_HALF: f64 = 10.0; +/// The box symbol art `art` is measured by in [`Document::symbol_art_bounds`]: its visual bounds, +/// or its geometric bounds when it has no visual bounds. +fn art_extent(art: &Node, boxes: &SymbolBoxes) -> Option { + art.visual_bounds_with(boxes).or_else(|| art.geometric_bounds_with(boxes)) +} + /// Usable art bounds: finite, non-degenerate. fn usable(r: Option) -> Option { r.filter(|r| [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) && r.width() >= 0.0 && r.height() > 1e-9) @@ -35,27 +42,38 @@ impl Document { } /// Visual bounds of the art of the symbol named `name` at its natural size (see - /// [`Self::symbol_natural_xf`]), if it exists and has a usable extent. + /// [`Self::symbol_natural_xf`]), if it exists and has a usable extent. The symbol instances in + /// the art are measured by their own symbols' art ([`Node::visual_bounds_with`]), or by the + /// 20 × 20 square where [`crate::SymbolBoxes`] measures them by it. pub fn symbol_art_bounds(&self, name: &str) -> Option { - let s = self.symbols.iter().find(|s| s.name == name)?; - let b = usable(s.art.visual_bounds().or_else(|| s.art.geometric_bounds()))?; + self.symbol_art_bounds_in(name, &self.symbol_boxes()) + } + + /// [`Self::symbol_art_bounds`], with the symbols found and the instances measured by `boxes` + /// (new boxes of this document). + fn symbol_art_bounds_in(&self, name: &str, boxes: &SymbolBoxes) -> Option { + let b = usable(art_extent(boxes.symbol_art(name)?, boxes))?; usable(Some(self.symbol_natural_xf(name).transform_rect_bbox(b))) } /// The art bounds an inline graphic of the symbol named `name` takes: [`Self::symbol_art_bounds`], /// or `None` (an empty slot) when the symbol's art shows the symbol itself inline, directly or - /// through the inline graphics in other symbols' art, so that its size would depend on itself. + /// through the inline graphics and symbol instances in other symbols' art, so that its size + /// would depend on itself. pub fn inline_art_bounds(&self, name: &str) -> Option { - if self.inline_cycles().contains(name) { None } else { self.symbol_art_bounds(name) } + let (cyclic, names) = self.inline_cycles(); + if cyclic.contains(name) { None } else { self.symbol_art_bounds_in(name, &self.symbol_boxes().with_names(&names)) } } - /// The names of the symbols that reach themselves through the inline graphics in symbol art, - /// found once while the symbols stay as they are. - fn inline_cycles(&self) -> Arc> { + /// The names of the symbols that reach themselves through the inline graphics in symbol art + /// ([`InlineGraph`]), with each symbol name → the index of the first symbol of that name, found + /// once while the symbols stay as they are. + fn inline_cycles(&self) -> (Arc>, Arc) { if let Some(found) = self.inline_cycles.get(&self.symbols) { return found; } - let found = Arc::new(InlineGraph::of(self).cyclic); + let graph = InlineGraph::of(self); + let found = (Arc::new(graph.cyclic), graph.names); self.inline_cycles.set(&self.symbols, &found); found } @@ -94,7 +112,8 @@ impl Document { /// of symbols, graph designs and pattern tiles, and the opacity masks and live objects in /// them. Each text whose inline graphics changed has its cached layout cleared and is passed /// to `layout` to be laid out again. The symbols are resolved first, each after the symbols its - /// inline graphics show, so a symbol's art is measured with its type already laid out; a + /// inline graphics and symbol instances show, so a symbol's art is measured with its type, and + /// the type in the art of the symbols its instances show, already laid out; a /// symbol that shows itself inline ([`Self::inline_art_bounds`]) is shown as an empty slot. /// Returns the ids of the texts in the layers that changed. pub fn resolve_inline_art_with(&mut self, layout: &mut dyn FnMut(&mut TextObject)) -> Vec { @@ -241,34 +260,48 @@ fn inline_symbols(n: &Node) -> Vec { out } -/// Each symbol name of `d` → the index of the first symbol of that name (the one a name finds). -fn symbol_index(d: &Document) -> HashMap<&str, usize> { - let mut index = HashMap::with_capacity(d.symbols.len()); - for (i, s) in d.symbols.iter().enumerate() { - index.entry(s.name.as_str()).or_insert(i); - } - index -} - -/// The symbols of a document as their inline graphics depend on each other. +/// The symbols of a document as their sizes depend on each other: a symbol's art depends on the +/// symbols its type shows inline, and on the symbols its instances show when those instances are +/// measured by their symbols' art ([`crate::SymbolBoxes`]). struct InlineGraph { - /// Every symbol index, each after the symbols its art shows inline (except along a cycle). + /// Every symbol index, each after the symbols its art depends on (except along a cycle). order: Vec, - /// The names of the symbols that reach themselves through inline graphics. + /// The names of the symbols that reach themselves through inline graphics. Instances alone make + /// no cycle: an instance of a symbol that holds an instance of itself is measured by the + /// 20 × 20 square, so every cycle passes through an inline graphic. cyclic: HashSet, + /// Each symbol name → the index of the first symbol of that name, which stay the same while + /// [`Document::resolve_inline_art_with`] changes the symbols' art. + names: Arc, } impl InlineGraph { - /// The graph of `d`'s symbols: each symbol's art is walked once, and the order and cycles are - /// found in time linear in the symbols and their inline references (Tarjan's strongly - /// connected components, without recursion). + /// The graph of `d`'s symbols: each symbol's art is walked once, and, when the art of any + /// symbol holds an inline graphic, measured once with the art boxes of the symbols its + /// instances show measured once in all ([`SymbolBoxes::consulted`]: an instance that does not + /// size the art, such as one a clipping path hides, adds nothing). The order and cycles are + /// found in time linear in the symbols and their inline references and instances (Tarjan's + /// strongly connected components, without recursion). fn of(d: &Document) -> Self { - let index = symbol_index(d); + let names = Arc::new(d.symbol_names()); + let boxes = d.symbol_boxes().quick().with_names(&names); + let inline: Vec> = d.symbols.iter().map(|s| inline_symbols(&s.art)).collect(); + // Without inline graphics in symbol art, no symbol's type depends on another symbol. + let any_inline = inline.iter().any(|v| !v.is_empty()); let edges: Vec> = d .symbols .iter() - .map(|s| { - let mut e: Vec = inline_symbols(&s.art).iter().filter_map(|n| index.get(n.as_str()).copied()).collect(); + .zip(inline) + .map(|(s, inline)| { + let measured = if any_inline { + boxes.consulted(|| { + art_extent(&s.art, &boxes); + }) + } else { + HashSet::new() + }; + let shows = inline.into_iter().chain(measured); + let mut e: Vec = shows.filter_map(|n| names.get(n.as_str()).copied()).collect(); e.sort_unstable(); e.dedup(); e @@ -276,12 +309,13 @@ impl InlineGraph { .collect(); let (order, cyclic) = components(&edges); let cyclic = order.iter().filter(|&&i| cyclic[i]).map(|&i| d.symbols[i].name.clone()).collect(); - Self { order, cyclic } + Self { order, cyclic, names } } - /// [`Document::inline_art_bounds`] with the cycles found in this graph. + /// [`Document::inline_art_bounds`] with the cycles found in this graph, for `d` with the + /// symbols' names and order the graph was made with. fn bounds(&self, d: &Document, name: &str) -> Option { - if self.cyclic.contains(name) { None } else { d.symbol_art_bounds(name) } + if self.cyclic.contains(name) { None } else { d.symbol_art_bounds_in(name, &d.symbol_boxes().with_names(&self.names)) } } } @@ -354,12 +388,16 @@ fn components(edges: &[Vec]) -> (Vec, Vec) { #[derive(Default)] pub(crate) struct InlineCycles(RwLock>>); -/// The name and art of each symbol the cycles were found in, and the names of the symbols on one. -type Found = (Vec<(String, Weak)>, Arc>); +/// The names of the symbols on a cycle, and each symbol name → the index of the first symbol of that +/// name. +type Cycles = (Arc>, Arc); + +/// The name and art of each symbol the cycles were found in, and what was found. +type Found = (Vec<(String, Weak)>, Cycles); impl InlineCycles { /// The cached names, when they were found in `symbols`. - fn get(&self, symbols: &[Symbol]) -> Option>> { + fn get(&self, symbols: &[Symbol]) -> Option { let g = self.0.read().ok()?; let (from, found) = &**g.as_ref()?; let same = from.len() == symbols.len() @@ -368,7 +406,7 @@ impl InlineCycles { } /// Keep `found`, found in `symbols`. - fn set(&self, symbols: &[Symbol], found: &Arc>) { + fn set(&self, symbols: &[Symbol], found: &Cycles) { if let Ok(mut g) = self.0.write() { *g = Some(Arc::new((symbols.iter().map(|s| (s.name.clone(), Arc::downgrade(&s.art))).collect(), found.clone()))); } @@ -485,6 +523,109 @@ mod tests { assert_eq!(count.get(), 2); } + /// A rectangle `r` filled black, with a 2 pt black stroke. + fn stroked(d: &mut Document, r: Rect) -> Arc { + use vectorcraft_color::{Color, Paint}; + let look = crate::Appearance::basic(Paint::solid(Color::BLACK), Paint::solid(Color::BLACK), 2.0); + Arc::new(Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(r), look)) + } + + fn instance(d: &mut Document, symbol: &str, xf: Affine) -> Arc { + Arc::new(Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: symbol.into(), xf })) + } + + /// Symbol `name` holding `art` in a group. + fn symbol(d: &mut Document, name: &str, art: Vec>) { + let group = Node::group(d.alloc_id(), art); + d.symbols.push(Symbol { dynamic: false, name: name.into(), art: Arc::new(group) }); + } + + #[test] + fn a_symbol_nested_in_symbol_art_is_measured_by_its_own_art() { + // `Far` is a rectangle from (200, 100) to (240, 130) with a 2 pt stroke, far from the + // 20 × 20 square around the origin. + let mut d = Document::new(500.0, 500.0); + let far = stroked(&mut d, Rect::new(200.0, 100.0, 240.0, 130.0)); + symbol(&mut d, "Far", vec![far]); + let moved = instance(&mut d, "Far", Affine::translate((-100.0, 0.0))); + symbol(&mut d, "Moved", vec![moved.clone()]); + let scaled = instance(&mut d, "Far", Affine::scale(2.0)); + symbol(&mut d, "Scaled", vec![scaled]); + symbol(&mut d, "Sized", vec![moved]); + d.unknown.insert(SYMBOL_SIZES.into(), serde_json::json!({ "Sized": [40.0, 20.0] })); + assert_eq!(d.symbol_art_bounds("Far"), Some(Rect::new(199.0, 99.0, 241.0, 131.0))); + // The stroke paints 1 pt around the moved rectangle. + assert_eq!(d.symbol_art_bounds("Moved"), Some(Rect::new(99.0, 99.0, 141.0, 131.0))); + // Scaled 2 times, the stroke keeps its weight. + assert_eq!(d.symbol_art_bounds("Scaled"), Some(Rect::new(399.0, 199.0, 481.0, 261.0))); + // At its natural size, 40 × 20 for the 20 × 20 square: 2 times across. + assert_eq!(d.symbol_art_bounds("Sized"), Some(Rect::new(198.0, 99.0, 282.0, 131.0))); + assert_eq!(d.inline_art_bounds("Moved"), d.symbol_art_bounds("Moved")); + } + + #[test] + fn nested_instances_without_art_of_their_own_are_measured_by_the_square() { + let mut d = Document::new(500.0, 500.0); + let r = Rect::new(0.0, 0.0, 10.0, 10.0); + // An instance of a missing symbol and one of a symbol with no art, beside a rectangle. + symbol(&mut d, "Empty", vec![]); + let pieces = vec![stroked(&mut d, r), instance(&mut d, "Nowhere", Affine::translate((100.0, 0.0)))]; + symbol(&mut d, "Missing", pieces); + let pieces = vec![stroked(&mut d, r), instance(&mut d, "Empty", Affine::translate((100.0, 0.0)))]; + symbol(&mut d, "Holds empty", pieces); + let with_square = Some(Rect::new(-1.0, -10.0, 110.0, 11.0)); + assert_eq!(d.symbol_art_bounds("Empty"), None); + assert_eq!(d.symbol_art_bounds("Missing"), with_square); + assert_eq!(d.symbol_art_bounds("Holds empty"), with_square); + // A symbol that holds an instance of itself: the instance is measured by the square, and + // an inline graphic of it is not an empty slot. + let pieces = vec![stroked(&mut d, r), instance(&mut d, "Loop", Affine::translate((100.0, 0.0)))]; + symbol(&mut d, "Loop", pieces); + assert_eq!(d.symbol_art_bounds("Loop"), with_square); + assert_eq!(d.inline_art_bounds("Loop"), with_square); + // A chain of 40 symbols, each holding a rectangle and an instance of the next one 1 pt to + // the right: symbols nest 39 deep in Link 0's art, past the limit of 32, so its instance of + // Link 1 is measured by the square. + for i in 0..40 { + let unit = stroked(&mut d, Rect::new(0.0, 0.0, 1.0, 1.0)); + let next = instance(&mut d, &format!("Link {}", i + 1), Affine::translate((1.0, 0.0))); + symbol(&mut d, &format!("Link {i}"), if i < 39 { vec![unit, next] } else { vec![unit] }); + } + assert_eq!(d.symbol_art_bounds("Link 0"), Some(Rect::new(-9.0, -10.0, 11.0, 10.0))); + // Link 8's art nests 31 deep: measured by the art of the links after it. + assert_eq!(d.symbol_art_bounds("Link 8"), Some(Rect::new(-1.0, -1.0, 33.0, 2.0))); + } + + /// Type showing the symbol named `symbol` inline. + fn showing(d: &mut Document, symbol: &str) -> Arc { + let style = crate::CharStyle::default(); + let mut t = TextObject::point(vectorcraft_geom::Point::ZERO, "Type", style.clone()); + t.runs.push(crate::TextRun::new("", style)); + t.runs[1].inline = Some(crate::InlineArt { symbol: symbol.into(), scale: 1.0, baseline_shift: 0.0, bounds: None }); + Arc::new(Node::new(d.alloc_id(), NodeKind::Text(Box::new(t)))) + } + + #[test] + fn only_instances_that_size_a_symbols_art_make_it_depend_on_their_symbol() { + // B's type shows A inline. A's art is a clip group: a clipping rectangle, then an instance + // of B that the rectangle clips, so A's size does not depend on B's. + let mut d = Document::new(500.0, 500.0); + let text = showing(&mut d, "A"); + symbol(&mut d, "B", vec![text]); + let clip = stroked(&mut d, Rect::new(0.0, 0.0, 10.0, 10.0)); + let inner = instance(&mut d, "B", Affine::IDENTITY); + let group = Arc::new(Node::new(d.alloc_id(), NodeKind::Group { children: vec![clip, inner.clone()], clip: true })); + symbol(&mut d, "A", vec![group]); + assert_eq!(d.inline_art_bounds("A"), Some(Rect::new(-1.0, -1.0, 11.0, 11.0))); + // Without the clip, A's size depends on B's and B's on A's: both are empty slots. + let art = Arc::new(Node::group(d.alloc_id(), vec![inner])); + if let Some(a) = d.symbols.iter_mut().find(|s| s.name == "A") { + a.art = art; + } + assert_eq!(d.inline_art_bounds("A"), None); + assert_eq!(d.inline_art_bounds("B"), None); + } + #[test] fn components_handle_a_long_chain_without_recursion() { let n = 200_000; diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index c51e099840..d6b797a371 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -55,12 +55,14 @@ mod pixels; pub use pixels::{GraySource, MAX_RASTER_ALLOC, PixelPick}; pub mod placed_document; pub mod plugin_data; +pub mod ppi; pub mod profiles; pub mod puppet; pub mod range; pub mod rastersettings; mod reach; pub mod recolor; +pub mod resample; pub mod selection; pub mod separated; pub mod setup; @@ -117,6 +119,7 @@ pub use slices::{CellAlign, CellVAlign, Slice, SliceArea, SliceKind, SliceOption pub use style_libs::StyleLibrary; pub use text::FontHeightReference; pub use text::GlyphChoice; +pub use text::GlyphForm; pub use text::WarichuAlign; pub use text::{ AreaFit, AreaOptions, Burasagari, CharAlign, CharPosition, CharStyle, Composer, Digits, FirstBaseline, HyphenationOptions, InlineArt, @@ -367,6 +370,12 @@ pub struct Document { /// saved. #[serde(skip)] inline_cycles: inline::InlineCycles, + /// Art kept elsewhere in the document's data (the art of the stored brushes, which + /// `vectorcraft-brush` reads from [`Self::unknown`]) while it is set here, each root with the + /// `owner` the Links panel names for it, so the stored-art lookups ([`StoredRoot::Mounted`]) + /// find its objects too. Empty otherwise; never saved. + #[serde(skip)] + pub mounted_art: Vec<(Arc, serde_json::Value)>, } fn ppi72() -> f64 { diff --git a/crates/doc/src/links.rs b/crates/doc/src/links.rs index ffa9eac0cd..80740b7cc2 100644 --- a/crates/doc/src/links.rs +++ b/crates/doc/src/links.rs @@ -229,7 +229,8 @@ fn proxy_png(bytes: &[u8]) -> Option> { /// Decoded image `img` shrunk to fit [`PROXY_SIZE`] as a PNG. fn proxy_of(img: &image::DynamicImage) -> Option> { - let small = img.thumbnail(PROXY_SIZE, PROXY_SIZE); + let (w, h) = crate::resample::fit_size(img.width(), img.height(), PROXY_SIZE, PROXY_SIZE); + let small = crate::resample::averaged(img, w, h); let mut png = Vec::new(); small.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).ok()?; Some(png) @@ -248,14 +249,15 @@ fn walk_all<'a>(n: &'a Node, f: &mut impl FnMut(&'a Node)) { impl Document { /// Visit every image object: in the layers, then in symbol definitions and pattern swatches, - /// opacity-mask art included. + /// then in [`Document::mounted_art`], opacity-mask art included. pub fn visit_images<'a>(&'a self, mut f: impl FnMut(&'a Node, &'a ImageObject)) { let roots = self .layers .iter() .chain(self.symbols.iter().map(|s| &s.art)) .chain(self.graph_designs.iter().map(|g| &g.art)) - .chain(self.patterns.iter().flat_map(|p| &p.art)); + .chain(self.patterns.iter().flat_map(|p| &p.art)) + .chain(self.mounted_art.iter().map(|(n, _)| n)); for root in roots { walk_all(root, &mut |n| { if let NodeKind::Image(im) = &n.kind { @@ -384,7 +386,8 @@ impl Align { impl Document { /// Rewrite linked file locations in both raster images and placed VectorCraft documents, - /// including those inside symbols, patterns and opacity masks. Used to make packages portable. + /// including those inside symbols, patterns, opacity masks and [`Document::mounted_art`]. Used to + /// make packages portable. pub fn update_links(&mut self, mut f: impl FnMut(&mut LinkInfo)) { fn walk(n: &mut Arc, f: &mut dyn FnMut(&mut LinkInfo)) { let n = Arc::make_mut(n); @@ -409,7 +412,8 @@ impl Document { .iter_mut() .chain(self.symbols.iter_mut().map(|s| &mut s.art)) .chain(self.graph_designs.iter_mut().map(|g| &mut g.art)) - .chain(self.patterns.iter_mut().flat_map(|p| &mut p.art)); + .chain(self.patterns.iter_mut().flat_map(|p| &mut p.art)) + .chain(self.mounted_art.iter_mut().map(|(n, _)| n)); for root in roots { walk(root, &mut f); } @@ -471,7 +475,8 @@ impl Document { .iter_mut() .chain(self.symbols.iter_mut().map(|s| &mut s.art)) .chain(self.graph_designs.iter_mut().map(|g| &mut g.art)) - .chain(self.patterns.iter_mut().flat_map(|p| &mut p.art)); + .chain(self.patterns.iter_mut().flat_map(|p| &mut p.art)) + .chain(self.mounted_art.iter_mut().map(|(n, _)| n)); for root in roots { update(root, &pick, &mut f); } @@ -728,4 +733,19 @@ mod tests { image(&mut d, "c", None); assert_eq!(d.linked_only_images().into_iter().collect::>(), ["a"]); } + + /// The preview of an image with clear pixels keeps the color of its opaque ones: the clear + /// black beside them does not darken them, whichever way the preview is made. + #[test] + fn a_preview_keeps_the_color_beside_clear_pixels() { + let mut full = vec![]; + image::RgbaImage::from_fn(1024, 4, |x, _| if x % 2 == 0 { image::Rgba([200, 30, 30, 255]) } else { image::Rgba([0, 0, 0, 0]) }) + .write_to(&mut Cursor::new(&mut full), image::ImageFormat::Png) + .unwrap(); + for blob in [ImageBlob::png(full.clone()).with_proxy(), ImageBlob::png(full.clone()).checked_with_proxy(true).unwrap()] { + let p = image::load_from_memory(blob.proxy.as_ref().unwrap()).unwrap().into_rgba8(); + assert_eq!(p.dimensions(), (PROXY_SIZE, 1)); + assert!(p.pixels().all(|q| q.0 == [200, 30, 30, 128]), "{:?}", p.get_pixel(0, 0)); + } + } } diff --git a/crates/doc/src/node.rs b/crates/doc/src/node.rs index eeec6ab162..79ce594212 100644 --- a/crates/doc/src/node.rs +++ b/crates/doc/src/node.rs @@ -32,6 +32,7 @@ pub use kind::{ImageObject, MAX_BUFFERED_VALUES, NodeKind, with_buffered_value_b pub use live_shape::{LiveShape, Scaling}; pub use opacity::{Knockout, OpacityMask, whiten}; pub use ops::{flattens, keeps_gradient_fit}; +pub(crate) use ops::{held_guides, map_held, strip_held}; use wire::NodeWire; pub(crate) use wire::counted_list; pub use wire::{MAX_READ_NODES, with_node_budget}; diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index fb6e8de8d9..1aad3a27cf 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -211,7 +211,9 @@ impl Node { /// A quick box round everything the object can paint, for culling clicks: paths and compound /// paths grow their geometric bounds by the farthest their strokes can reach from any path - /// ([`Appearance::outset`]) instead of measuring along their shape. An image's box takes in + /// ([`Appearance::outset`]) instead of measuring along their shape. A clip group's or a + /// clipping layer's box takes in the region that the live geometry effects of its clipping + /// path give it ([`crate::hit::set_clip_region`]). An image's box takes in /// the shapes its own fills and strokes paint ([`crate::hit::set_image_paint`]). Groups, layers /// without a clipping mask and Intertwine groups take in their members' boxes, grown by their /// own strokes. Symbol instances are measured as in [`Node::visual_bounds`]. A blend's box @@ -261,6 +263,11 @@ impl Node { NodeKind::Blend { children, spec } => { vectorcraft_geom::union_opt(self.visual(symbols), crate::blend::rail_reach(children, spec, symbols)) } + // The live geometry effects of a clipping path can move or grow the region it clips to + // past its plain shape ([`crate::hit::set_clip_region`]). + NodeKind::Layer { children, clip: true, .. } | NodeKind::Group { children, clip: true } => { + vectorcraft_geom::union_opt(self.visual(symbols), children.first().and_then(|c| crate::hit::reshaped_clip_box(c))) + } _ => self.visual(symbols), } } @@ -823,11 +830,11 @@ impl Node { /// The ruler guides a layer holds: its children that are one, by index in order (each with /// nothing inside), and its sublayers holding one (with what they hold). #[derive(Debug, Default)] -pub(super) struct HeldGuides(Vec<(usize, HeldGuides)>); +pub(crate) struct HeldGuides(Vec<(usize, HeldGuides)>); /// The ruler guides, by `is_guide`, that `n` holds if it is a layer, or `None` when it holds /// none. `is_guide` looks at each child of `n` and of its sublayers once. -pub(super) fn held_guides(n: &Node, is_guide: &impl Fn(&Node) -> bool) -> Option { +pub(crate) fn held_guides(n: &Node, is_guide: &impl Fn(&Node) -> bool) -> Option { if !n.is_layer() { return None; } @@ -843,7 +850,7 @@ pub(super) fn held_guides(n: &Node, is_guide: &impl Fn(&Node) -> bool) -> Option /// Remove the ruler guides of `layer` and of its sublayers that [`held_guides`] found (`held`). /// Only the sublayers holding one are copied, and only those are visited. -pub(super) fn strip_held(layer: &mut Node, held: HeldGuides) { +pub(crate) fn strip_held(layer: &mut Node, held: HeldGuides) { let Some(ch) = layer.children_mut() else { return }; let mut held = held.0.into_iter().peekable(); let mut next = 0; @@ -863,7 +870,7 @@ pub(super) fn strip_held(layer: &mut Node, held: HeldGuides) { /// Call `f` (whether it is vertical, its position) on each ruler guide of `layer` and of its /// sublayers that [`held_guides`] found (`held`), in the order they lie in. Only the sublayers /// holding one, and the guides, are copied, and only those sublayers are visited. -pub(super) fn map_held(layer: &mut Node, held: HeldGuides, f: &mut impl FnMut(bool, &mut f64)) { +pub(crate) fn map_held(layer: &mut Node, held: HeldGuides, f: &mut impl FnMut(bool, &mut f64)) { let Some(ch) = layer.children_mut() else { return }; for (i, inner) in held.0 { let Some(c) = ch.get_mut(i) else { continue }; diff --git a/crates/doc/src/objects_on_path.rs b/crates/doc/src/objects_on_path.rs index 35de7cce73..7362f324ea 100644 --- a/crates/doc/src/objects_on_path.rs +++ b/crates/doc/src/objects_on_path.rs @@ -234,8 +234,14 @@ pub fn is_objects_on_path(n: &Node) -> bool { /// The path of `n` if it is a path object an Objects on Path group can attach objects to: a path /// (not a guide) whose first subpath has a length ([`path_length`]). pub fn attachable_path(n: &Node) -> Option<&PathData> { + attachable(n).map(|(path, _)| path) +} + +/// [`attachable_path`] with the path measured ([`Measured`]), from the one flattening that checks +/// its length. +pub fn attachable(n: &Node) -> Option<(&PathData, Measured)> { match &n.kind { - NodeKind::Path { path, guide: false, .. } if path_length(path).is_some() => Some(path), + NodeKind::Path { path, guide: false, .. } => Some((path, Measured::new(path)?)), _ => None, } } @@ -301,20 +307,51 @@ pub fn path_length(path: &PathData) -> Option<(f64, bool)> { /// A path's first subpath flattened ([`Spine`]), with its length and whether it is closed, so that /// one flattening serves both measuring the path and finding points along it. -struct Measured { +pub struct Measured { spine: Spine, len: f64, closed: bool, } +impl std::fmt::Debug for Measured { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Measured").field("len", &self.len).field("closed", &self.closed).finish_non_exhaustive() + } +} + impl Measured { /// `None` for a path without length, or with a length too large to be finite. - fn new(path: &PathData) -> Option { + pub fn new(path: &PathData) -> Option { let spine = Spine::new(path)?; let len = spine.length(); let closed = path.subpaths.first().is_some_and(|s| s.closed); (len.is_finite() && len > 1e-9).then_some(Self { spine, len, closed }) } + /// The flattened first subpath, to measure along. + pub fn spine(&self) -> &Spine { + &self.spine + } + /// The length of the first subpath (points), as [`path_length`] gives it. + pub fn length(&self) -> f64 { + self.len + } + /// Is the first subpath closed? + pub fn closed(&self) -> bool { + self.closed + } + /// [`stops`] on this path. + pub fn stops(&self, n: usize, spacing: Option, start: f64) -> Vec<(Point, f64)> { + let (start, gap) = layout(self.len, self.closed, n, spacing, start); + (0..n).map(|i| self.spine.at_length(nth_length(self.len, self.closed, start, gap, i))).collect() + } + /// [`stop`] on this path: `None` for an `i` of `n` or more. + pub fn stop(&self, n: usize, spacing: Option, start: f64, i: usize) -> Option<(Point, f64)> { + if i >= n { + return None; + } + let (start, gap) = layout(self.len, self.closed, n, spacing, start); + Some(self.spine.at_length(nth_length(self.len, self.closed, start, gap, i))) + } } /// Where the first of `n` objects attaches along a path of length `len` (closed or not), and the @@ -359,9 +396,7 @@ fn wrap(s: f64, len: f64) -> f64 { /// (radians, as `atan2` gives in the document's axes). They go along it as [`layout`] spaces them /// for Space `spacing` (`None`: Auto) from `start`. `None` for a path without length. pub fn stops(path: &PathData, n: usize, spacing: Option, start: f64) -> Option> { - let Measured { spine, len, closed } = Measured::new(path)?; - let (start, gap) = layout(len, closed, n, spacing, start); - Some((0..n).map(|i| spine.at_length(nth_length(len, closed, start, gap, i))).collect()) + Some(Measured::new(path)?.stops(n, spacing, start)) } /// Where object `i` of `n` attaches along `path`, as [`stops`] places it, without the others. @@ -370,9 +405,7 @@ pub fn stop(path: &PathData, n: usize, spacing: Option, start: f64, i: usiz if i >= n { return None; } - let Measured { spine, len, closed } = Measured::new(path)?; - let (start, gap) = layout(len, closed, n, spacing, start); - Some(spine.at_length(nth_length(len, closed, start, gap, i))) + Measured::new(path)?.stop(n, spacing, start, i) } /// The distance along a path of length `len` (closed or not) to object `i`, from `start` and diff --git a/crates/doc/src/placed_document.rs b/crates/doc/src/placed_document.rs index 86f7f6134c..cd423658d7 100644 --- a/crates/doc/src/placed_document.rs +++ b/crates/doc/src/placed_document.rs @@ -166,13 +166,15 @@ fn walk_all<'a>(n: &'a Node, f: &mut impl FnMut(&'a Node)) { } } -/// The roots of `d`'s art: layers, symbol definitions and pattern swatches. +/// The roots of `d`'s art: layers, symbol definitions, pattern swatches and +/// [`Document::mounted_art`]. fn roots(d: &Document) -> impl Iterator> { d.layers .iter() .chain(d.symbols.iter().map(|s| &s.art)) .chain(d.graph_designs.iter().map(|g| &g.art)) .chain(d.patterns.iter().flat_map(|p| &p.art)) + .chain(d.mounted_art.iter().map(|(n, _)| n)) } fn roots_mut(d: &mut Document) -> impl Iterator> { @@ -181,6 +183,7 @@ fn roots_mut(d: &mut Document) -> impl Iterator> { .chain(d.symbols.iter_mut().map(|s| &mut s.art)) .chain(d.graph_designs.iter_mut().map(|g| &mut g.art)) .chain(d.patterns.iter_mut().flat_map(|p| &mut p.art)) + .chain(d.mounted_art.iter_mut().map(|(n, _)| n)) } impl Document { diff --git a/crates/doc/src/ppi.rs b/crates/doc/src/ppi.rs new file mode 100644 index 0000000000..5c3bd24b53 --- /dev/null +++ b/crates/doc/src/ppi.rs @@ -0,0 +1,287 @@ +//! Image resolution metadata (pixels per inch) in the formats the image decoder reads: PNG `pHYs`, +//! JPEG JFIF density or EXIF, TIFF and WebP EXIF resolution tags, and BMP pixels per metre. An image +//! converted to PNG keeps it as a `pHYs` chunk ([`with_png_resolution`]). + +const INCH_M: f64 = 0.0254; +const INCH_CM: f64 = 2.54; + +/// Is `bytes` a PNG, JPEG, TIFF, WebP or BMP file, the formats [`resolution`] reads? +pub fn reads(bytes: &[u8]) -> bool { + bytes.starts_with(b"\x89PNG\r\n\x1a\n") + || bytes.starts_with(&[0xff, 0xd8]) + || bytes.starts_with(b"II*\0") + || bytes.starts_with(b"MM\0*") + || (bytes.len() >= 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP") + || bytes.starts_with(b"BM") +} + +/// The resolution a PNG, JPEG, TIFF, WebP or BMP file declares as (horizontal, vertical) ppi, each +/// from 1 to 100,000; `None` when it declares none (or only an aspect ratio), and for other files. +pub fn resolution(bytes: &[u8]) -> Option<(f64, f64)> { + let r = if bytes.starts_with(b"\x89PNG\r\n\x1a\n") { + png(bytes) + } else if bytes.starts_with(&[0xff, 0xd8]) { + jpeg(bytes) + } else if bytes.starts_with(b"II*\0") || bytes.starts_with(b"MM\0*") { + tiff(bytes) + } else if bytes.len() >= 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" { + webp(bytes) + } else if bytes.starts_with(b"BM") { + bmp(bytes) + } else { + None + }; + r.filter(|(x, y)| [*x, *y].iter().all(|v| v.is_finite() && (1.0..=100_000.0).contains(v))) +} + +/// `n` bytes at `at` (`None` past the end; offsets come from the file, so no overflow either). +fn slice(b: &[u8], at: usize, n: usize) -> Option<&[u8]> { + b.get(at..at.checked_add(n)?) +} +fn bytes(b: &[u8], at: usize) -> Option<[u8; N]> { + slice(b, at, N)?.try_into().ok() +} +fn be16(b: &[u8], at: usize) -> Option { + bytes(b, at).map(u16::from_be_bytes) +} +fn be32(b: &[u8], at: usize) -> Option { + bytes(b, at).map(u32::from_be_bytes) +} +fn le32(b: &[u8], at: usize) -> Option { + bytes(b, at).map(u32::from_le_bytes) +} + +/// Pixels per inch from the whole pixels per metre PNG and BMP store: a whole number of ppi when +/// the metre value is that rounded (300 ppi is stored as 11811 per metre, 299.9994 ppi). +fn per_metre(ppm: u32) -> f64 { + let v = ppm as f64 * INCH_M; + let whole = v.round(); + if (v - whole).abs() <= INCH_M / 2.0 + 1e-9 { whole } else { v } +} + +/// PNG chunks after the signature: (type, data). +pub fn png_chunks(b: &[u8]) -> impl Iterator { + let mut at = 8; + std::iter::from_fn(move || { + let len = be32(b, at)? as usize; + let ty = slice(b, at + 4, 4)?; + let data = slice(b, at + 8, len)?; + at = at.checked_add(12 + len)?; + Some((ty, data)) + }) +} + +fn png(b: &[u8]) -> Option<(f64, f64)> { + let (_, d) = png_chunks(b).take_while(|(ty, _)| *ty != b"IDAT").find(|(ty, _)| *ty == b"pHYs")?; + // Unit 1 = metre; 0 only gives the pixel aspect ratio. + (d.get(8) == Some(&1)).then(|| (per_metre(be32(d, 0).unwrap_or(0)), per_metre(be32(d, 4).unwrap_or(0)))) +} + +fn jpeg(b: &[u8]) -> Option<(f64, f64)> { + let (mut jfif, mut exif) = (None, None); + let mut at = 2; + while at + 4 <= b.len() && b[at] == 0xff { + let marker = b[at + 1]; + // 0xff fill bytes pad between segments. + if marker == 0xff { + at += 1; + continue; + } + if marker == 0xd8 || marker == 0x01 || (0xd0..=0xd7).contains(&marker) { + at += 2; + continue; + } + // Start of scan or end of image: no more metadata. + if marker == 0xda || marker == 0xd9 { + break; + } + let len = be16(b, at + 2)? as usize; + let seg = slice(b, at + 4, len.checked_sub(2)?)?; + match marker { + 0xe0 if seg.starts_with(b"JFIF\0") && seg.len() >= 12 => { + let (x, y) = (be16(seg, 8)? as f64, be16(seg, 10)? as f64); + jfif = match seg[7] { + 1 => Some((x, y)), + 2 => Some((x * INCH_CM, y * INCH_CM)), + _ => None, + }; + } + 0xe1 if seg.starts_with(b"Exif\0\0") => exif = tiff(&seg[6..]), + _ => {} + } + at += 2 + len; + } + jfif.or(exif) +} + +/// TIFF (or EXIF) IFD0 XResolution / YResolution / ResolutionUnit, as (horizontal, vertical) ppi +/// in the stored pixels' axes, unchecked; `None` without an absolute unit. +pub fn tiff(b: &[u8]) -> Option<(f64, f64)> { + let le = b.starts_with(b"II"); + let u16_at = |at: usize| bytes(b, at).map(if le { u16::from_le_bytes } else { u16::from_be_bytes }); + let u32_at = |at: usize| bytes(b, at).map(if le { u32::from_le_bytes } else { u32::from_be_bytes }); + let ifd = u32_at(4)? as usize; + let (mut x, mut y, mut unit) = (None, None, 2); + for i in 0..u16_at(ifd)? as usize { + let e = ifd.checked_add(2 + i * 12)?; + let rational = || -> Option { + let at = u32_at(e + 8)? as usize; + let (n, d) = (u32_at(at)?, u32_at(at.checked_add(4)?)?); + (d != 0).then(|| n as f64 / d as f64) + }; + match u16_at(e)? { + 282 => x = rational(), + 283 => y = rational(), + 296 => unit = u16_at(e + 8)?, + _ => {} + } + } + let k = match unit { + 2 => 1.0, + 3 => INCH_CM, + _ => return None, + }; + let x = x?; + Some((x * k, y.unwrap_or(x) * k)) +} + +fn webp(b: &[u8]) -> Option<(f64, f64)> { + let mut at = 12; + while at + 8 <= b.len() { + let len = le32(b, at + 4)? as usize; + let data = slice(b, at + 8, len)?; + if &b[at..at + 4] == b"EXIF" { + return tiff(data.strip_prefix(b"Exif\0\0").unwrap_or(data)); + } + at += 8 + len + (len & 1); + } + None +} + +fn bmp(b: &[u8]) -> Option<(f64, f64)> { + // BITMAPINFOHEADER (40 bytes or longer) at 14: pixels per metre at +24 and +28. + if le32(b, 14)? < 40 { + return None; + } + let ppm = |at| le32(b, at).filter(|v| (1..=i32::MAX as u32).contains(v)).map(per_metre); + Some((ppm(38)?, ppm(42)?)) +} + +/// Pixels per metre for a resolution in pixels per inch (the unit `pHYs` stores). +pub fn pixels_per_metre(ppi: f64) -> u32 { + (ppi / INCH_M).round().clamp(1.0, u32::MAX as f64) as u32 +} + +/// PNG CRC-32 (the polynomial ZIP uses) of `parts` read one after another. +fn crc32(parts: &[&[u8]]) -> u32 { + let mut crc = !0u32; + for &b in parts.iter().flat_map(|p| p.iter()) { + crc ^= u32::from(b); + for _ in 0..8 { + crc = (crc >> 1) ^ (0xEDB8_8320 & u32::from(crc & 1 != 0).wrapping_neg()); + } + } + !crc +} + +/// A whole `pHYs` chunk (length, type, data, CRC) declaring `x` × `y` pixels per inch. +pub fn phys_chunk(x: f64, y: f64) -> Vec { + let [x, y] = [x, y].map(|v| pixels_per_metre(v).to_be_bytes()); + // x, y, unit 1 = metre. + let data = [x.as_slice(), y.as_slice(), &[1]].concat(); + let mut out = Vec::with_capacity(21); + out.extend_from_slice(&9u32.to_be_bytes()); + out.extend_from_slice(b"pHYs"); + out.extend_from_slice(&data); + out.extend_from_slice(&crc32(&[b"pHYs", &data]).to_be_bytes()); + out +} + +/// `png` with a `pHYs` chunk declaring `ppi` right after the header (any existing one is replaced). +pub fn with_png_resolution(png: &[u8], (x, y): (f64, f64)) -> Vec { + let Some(head) = be32(png, 8).and_then(|len| slice(png, 0, 20usize.checked_add(len as usize)?)) else { return png.to_vec() }; + let chunk = phys_chunk(x, y); + let mut out = Vec::with_capacity(png.len() + chunk.len()); + out.extend_from_slice(head); + out.extend_from_slice(&chunk); + let mut at = head.len(); + while let Some(chunk) = be32(png, at).and_then(|len| slice(png, at, 12usize.checked_add(len as usize)?)) { + if chunk.get(4..8) != Some(b"pHYs") { + out.extend_from_slice(chunk); + } + at += chunk.len(); + } + out.extend_from_slice(png.get(at..).unwrap_or_default()); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn png_of(w: u32, h: u32) -> Vec { + let mut out = Vec::new(); + image::RgbaImage::new(w, h).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + out + } + + /// The `pHYs` chunk carries the CRC a PNG reader checks, and replaces the one already there. + #[test] + fn a_png_takes_its_resolution_and_still_decodes() { + let png = png_of(4, 3); + assert_eq!(resolution(&png), None); + let tagged = with_png_resolution(&png, (300.0, 150.0)); + assert_eq!(resolution(&tagged), Some((300.0, 150.0))); + let again = with_png_resolution(&tagged, (72.0, 72.0)); + assert_eq!(resolution(&again), Some((72.0, 72.0)), "replaced, not duplicated"); + assert_eq!(again.len(), tagged.len()); + let img = image::load_from_memory(&again).unwrap(); + assert_eq!((img.width(), img.height()), (4, 3)); + // Every PNG ends with this IEND chunk CRC. + assert_eq!(crc32(&[b"IEND"]), 0xAE42_6082); + } + + /// RIFF chunk `ty` holding `data`, padded to an even length. + fn riff_chunk(ty: &[u8; 4], len: u32, data: &[u8]) -> Vec { + let mut out = [ty.as_slice(), &len.to_le_bytes(), data].concat(); + if data.len() % 2 == 1 { + out.push(0); + } + out + } + + fn webp_of(chunks: &[Vec]) -> Vec { + let body = chunks.concat(); + let size = u32::try_from(body.len() + 4).unwrap(); + [b"RIFF".as_slice(), &size.to_le_bytes(), b"WEBP", &body].concat() + } + + /// A WebP's EXIF chunk is found past an odd-length chunk and its padding byte, and a chunk whose + /// length runs past the end of the file (up to `u32::MAX`, more than a 32-bit `usize` can add to + /// an offset) gives no resolution. + #[test] + fn a_webp_reads_its_exif_and_rejects_a_chunk_past_the_end() { + // Little-endian TIFF: two IFD0 entries, XResolution 300/1 at offset 38 and ResolutionUnit inch. + let mut tiff = b"II*\0".to_vec(); + tiff.extend_from_slice(&8u32.to_le_bytes()); + tiff.extend_from_slice(&2u16.to_le_bytes()); + for (tag, ty, value) in [(282u16, 5u16, 38u32), (296, 3, 2)] { + tiff.extend_from_slice(&tag.to_le_bytes()); + tiff.extend_from_slice(&ty.to_le_bytes()); + tiff.extend_from_slice(&1u32.to_le_bytes()); + tiff.extend_from_slice(&value.to_le_bytes()); + } + tiff.extend_from_slice(&0u32.to_le_bytes()); + tiff.extend_from_slice(&300u32.to_le_bytes()); + tiff.extend_from_slice(&1u32.to_le_bytes()); + let exif = [b"Exif\0\0".as_slice(), &tiff].concat(); + let exif_len = u32::try_from(exif.len()).unwrap(); + let ok = webp_of(&[riff_chunk(b"VP8X", 3, &[0, 0, 0]), riff_chunk(b"EXIF", exif_len, &exif)]); + assert_eq!(resolution(&ok), Some((300.0, 300.0))); + + for len in [u32::MAX, u32::MAX - 7, 1_000] { + let bad = webp_of(&[riff_chunk(b"VP8X", len, &[0; 10])]); + assert_eq!(resolution(&bad), None, "chunk length {len}"); + } + } +} diff --git a/crates/doc/src/resample.rs b/crates/doc/src/resample.rs new file mode 100644 index 0000000000..bc72cce1db --- /dev/null +++ b/crates/doc/src/resample.rs @@ -0,0 +1,259 @@ +//! Scaling images whose pixels carry straight (not premultiplied) alpha. +//! +//! `image`'s filtered resampling filters each channel on its own, which is correct only for +//! premultiplied pixels, and its thumbnail averages each channel on its own too, so on +//! straight-alpha pixels the color under clear pixels bleeds into the opaque ones next to them +//! (clear black darkens a cut-out's edge). [`resized`], [`fitted`] and [`averaged`] weight each +//! pixel's color by its alpha while scaling, as the streaming shrink in the renderer does. + +use image::imageops::FilterType; +use image::{DynamicImage, RgbaImage}; + +/// How [`resized`] makes each new pixel from the old ones. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Resample { + /// `image`'s filtered resampling with this filter. + Filter(FilterType), + /// The mean of the old pixels each new one covers ([`averaged`]). + Average, +} + +/// `img` scaled to `w` × `h` pixels as `how` says, each pixel's color weighted by its alpha. +/// Filtered or averaged, an image with clear or partly clear pixels comes back as 8-bit RGBA +/// whatever its own pixel format, and a pixel that ends up wholly clear is transparent black. An +/// image without clear pixels is scaled as `image` scales it, in its own pixel format. +/// Nearest-neighbor picking leaves the pixels as they are, in their own format, and is not +/// weighted. Filtered, the colors keep the precision of premultiplied 8-bit pixels, and an 8-bit +/// RGBA image is premultiplied in place. +pub fn resized(img: DynamicImage, w: u32, h: u32, how: Resample) -> DynamicImage { + if (w, h) == (img.width(), img.height()) { + return img; + } + let f = match how { + Resample::Average => return averaged(&img, w, h), + Resample::Filter(f) => f, + }; + if f == FilterType::Nearest || opaque(&img) { + return img.resize_exact(w, h, f); + } + let mut rgba = img.into_rgba8(); + for p in rgba.pixels_mut() { + let [r, g, b, a] = &mut p.0; + for c in [r, g, b] { + *c = times_alpha(*c, *a); + } + } + let mut out = image::imageops::resize(&rgba, w, h, f); + for p in out.pixels_mut() { + let [r, g, b, a] = &mut p.0; + for c in [r, g, b] { + *c = over_alpha(*c, *a); + } + } + DynamicImage::ImageRgba8(out) +} + +/// [`resized`] to the largest size that fits `w` × `h` pixels and keeps `img`'s proportions, the +/// size `image`'s own `resize` and `thumbnail` pick. +pub fn fitted(img: DynamicImage, w: u32, h: u32, how: Resample) -> DynamicImage { + let (nw, nh) = fit_size(img.width(), img.height(), w, h); + resized(img, nw, nh, how) +} + +/// `img` scaled to `w` × `h` pixels, each new pixel the mean of the old pixels it covers, each old +/// pixel counted by the area of it covered and its color weighted by its alpha. `img` is read one +/// row at a time, so besides the result this takes one row of 8-bit RGBA at most. An image +/// without clear pixels is scaled as `image`'s thumbnail scales it. +pub fn averaged(img: &DynamicImage, w: u32, h: u32) -> DynamicImage { + let (sw, sh) = (img.width(), img.height()); + if opaque(img) || w == 0 || h == 0 || sw == 0 || sh == 0 { + return img.thumbnail_exact(w, h); + } + // Per new pixel of the row being made: red, green and blue times alpha, alpha (all times the + // area covered), and the area covered. + let mut sums = vec![([0f64; 4], 0f64); w as usize]; + let mut out = Vec::with_capacity(w as usize * h as usize * 4); + for ty in 0..h { + for (y, wy) in covered(ty, sh, h) { + let row = rgba_row(img, y as u32); + for ((s, area), tx) in sums.iter_mut().zip(0..w) { + for (x, wx) in covered(tx, sw, w) { + let Some(p) = row.get(x * 4..x * 4 + 4) else { continue }; + let k = wx * wy; + let a = f64::from(p[3]) * k; + s[0] += f64::from(p[0]) * a; + s[1] += f64::from(p[1]) * a; + s[2] += f64::from(p[2]) * a; + s[3] += a; + *area += k; + } + } + } + let byte = |v: f64| v.round().clamp(0.0, 255.0) as u8; + for (s, area) in &mut sums { + out.extend(if s[3] <= 0.0 { [0; 4] } else { [byte(s[0] / s[3]), byte(s[1] / s[3]), byte(s[2] / s[3]), byte(s[3] / *area)] }); + (*s, *area) = ([0.0; 4], 0.0); + } + } + RgbaImage::from_raw(w, h, out).map_or_else(|| img.thumbnail_exact(w, h), DynamicImage::ImageRgba8) +} + +/// Row `y` of `img` as 8-bit RGBA: borrowed from an 8-bit RGBA image, converted from others. +fn rgba_row(img: &DynamicImage, y: u32) -> std::borrow::Cow<'_, [u8]> { + let n = img.width() as usize * 4; + match img { + DynamicImage::ImageRgba8(b) => std::borrow::Cow::Borrowed(b.as_raw().get(y as usize * n..(y as usize + 1) * n).unwrap_or_default()), + other => std::borrow::Cow::Owned(other.crop_imm(0, y, other.width(), 1).into_rgba8().into_raw()), + } +} + +/// The old pixels that new pixel `t` of `tn` covers along a side of `n` old pixels, each with the +/// length of it covered (in old pixels), worked out as they are read so that nothing is stored. +fn covered(t: u32, n: u32, tn: u32) -> impl Iterator { + let scale = f64::from(n) / f64::from(tn); + let (a, b) = (f64::from(t) * scale, (f64::from(t) + 1.0) * scale); + let (first, end) = (a.floor() as u32, (b.ceil() as u32).min(n)); + (first..end.max(first + 1).min(n)).filter_map(move |i| { + let len = b.min(f64::from(i) + 1.0) - a.max(f64::from(i)); + (len > 0.0).then_some((i as usize, len)) + }) +} + +/// Each 4-channel pixel of `px` with all four channels multiplied by its value in `alpha` (one +/// sample a pixel, 0 to 255): ink amounts or colors made ready for scaling beside a separate alpha +/// channel. Pixels past the end of `alpha` are left as they are. +pub fn premultiply(px: &mut [u8], alpha: &[u8]) { + for (p, &a) in px.as_chunks_mut::<4>().0.iter_mut().zip(alpha) { + for c in p { + *c = times_alpha(*c, a); + } + } +} + +/// [`premultiply`] undone after scaling: each 4-channel pixel of `px` divided by its value in the +/// scaled `alpha`, and 0 where that is 0. +pub fn unpremultiply(px: &mut [u8], alpha: &[u8]) { + for (p, &a) in px.as_chunks_mut::<4>().0.iter_mut().zip(alpha) { + for c in p { + *c = over_alpha(*c, a); + } + } +} + +/// Does `img` have no alpha channel, or is every pixel of it opaque? +fn opaque(img: &DynamicImage) -> bool { + match img { + DynamicImage::ImageRgba8(b) => b.pixels().all(|p| p[3] == u8::MAX), + DynamicImage::ImageLumaA8(b) => b.pixels().all(|p| p[1] == u8::MAX), + DynamicImage::ImageRgba16(b) => b.pixels().all(|p| p[3] == u16::MAX), + DynamicImage::ImageLumaA16(b) => b.pixels().all(|p| p[1] == u16::MAX), + DynamicImage::ImageRgba32F(b) => b.pixels().all(|p| p[3] >= 1.0), + other => !other.color().has_alpha(), + } +} + +/// Channel `c` times alpha `a`, both 0 to 255. +fn times_alpha(c: u8, a: u8) -> u8 { + ((u16::from(c) * u16::from(a) + 127) / 255) as u8 +} + +/// Premultiplied channel `c` divided by alpha `a` (0 when `a` is 0). +fn over_alpha(c: u8, a: u8) -> u8 { + if a == 0 { + return 0; + } + let a = u32::from(a); + ((u32::from(c) * 255 + a / 2) / a).min(255) as u8 +} + +/// The largest size of at most `nw` × `nh` with the proportions of `w` × `h`, at least a pixel a +/// side. +pub fn fit_size(w: u32, h: u32, nw: u32, nh: u32) -> (u32, u32) { + if w == 0 || h == 0 { + return (nw.max(1), nh.max(1)); + } + let ratio = (f64::from(nw) / f64::from(w)).min(f64::from(nh) / f64::from(h)); + let side = |n: u32| ((f64::from(n) * ratio).round() as u32).max(1); + (side(w), side(h)) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A 4 × 2 image whose left half is opaque red and whose right half is clear black. + fn half_clear() -> DynamicImage { + DynamicImage::ImageRgba8(RgbaImage::from_fn(4, 2, |x, _| if x < 2 { image::Rgba([200, 30, 30, 255]) } else { image::Rgba([0, 0, 0, 0]) })) + } + + /// Is the color of `p`, premultiplied by its alpha, within a step of `rgb` premultiplied by the + /// same alpha (the precision of premultiplied 8-bit pixels)? + fn close(p: [u8; 4], rgb: [u8; 3]) -> bool { + p[..3].iter().zip(rgb).all(|(&c, want)| times_alpha(c, p[3]).abs_diff(times_alpha(want, p[3])) <= 1) + } + + #[test] + fn averaging_keeps_the_color_of_the_opaque_pixels() { + let p = resized(half_clear(), 1, 1, Resample::Average).into_rgba8().get_pixel(0, 0).0; + assert!(close(p, [200, 30, 30]) && p[3].abs_diff(128) <= 1, "{p:?}"); + } + + /// Three pixels averaged into two: each new pixel takes one old pixel whole and half of the + /// clear one in the middle. + #[test] + fn averaging_counts_the_part_of_a_pixel_covered() { + let img = RgbaImage::from_fn(3, 1, |x, _| if x == 1 { image::Rgba([0, 0, 0, 0]) } else { image::Rgba([200, 30, 30, 255]) }); + let out = averaged(&DynamicImage::ImageRgba8(img), 2, 1).into_rgba8(); + assert_eq!(out.into_raw(), [[200, 30, 30, 170], [200, 30, 30, 170]].concat()); + // Gray with alpha is read the same way. + let gray = image::GrayAlphaImage::from_fn(3, 1, |x, _| image::LumaA(if x == 1 { [0, 0] } else { [200, 255] })); + let out = averaged(&DynamicImage::ImageLumaA8(gray), 2, 1).into_rgba8(); + assert_eq!(out.into_raw(), [[200, 200, 200, 170], [200, 200, 200, 170]].concat()); + } + + #[test] + fn filtering_keeps_the_color_of_the_opaque_pixels() { + for f in [FilterType::Triangle, FilterType::CatmullRom, FilterType::Lanczos3] { + let out = resized(half_clear(), 2, 1, Resample::Filter(f)).into_rgba8(); + for x in 0..2 { + let p = out.get_pixel(x, 0).0; + assert!(p[3] == 0 || close(p, [200, 30, 30]), "{f:?} pixel {x}: {p:?}"); + } + } + } + + #[test] + fn fitted_keeps_proportions() { + let img = DynamicImage::ImageRgba8(RgbaImage::new(400, 100)); + let out = fitted(img, 64, 64, Resample::Average); + assert_eq!((out.width(), out.height()), (64, 16)); + } + + #[test] + fn opaque_and_alpha_free_images_scale_as_image_scales_them() { + let rgb = DynamicImage::ImageRgb8(image::RgbImage::from_fn(5, 3, |x, y| image::Rgb([x as u8 * 40, y as u8 * 60, 7]))); + let ours = resized(rgb.clone(), 2, 2, Resample::Filter(FilterType::Triangle)); + assert_eq!(ours, rgb.resize_exact(2, 2, FilterType::Triangle)); + let opaque = DynamicImage::ImageRgba8(rgb.to_rgba8()); + assert_eq!(resized(opaque.clone(), 2, 2, Resample::Average), opaque.thumbnail_exact(2, 2)); + } + + #[test] + fn a_wholly_clear_result_is_transparent_black() { + let img = DynamicImage::ImageRgba8(RgbaImage::from_pixel(4, 4, image::Rgba([90, 90, 90, 0]))); + assert_eq!(resized(img, 1, 1, Resample::Average).into_rgba8().get_pixel(0, 0).0, [0, 0, 0, 0]); + } + + #[test] + fn premultiply_and_unpremultiply_scale_beside_a_separate_alpha() { + // Two pixels of inks, the second clear: averaged, the first one's inks remain. + let mut px = vec![40, 80, 120, 160, 0, 0, 0, 0]; + premultiply(&mut px, &[255, 0]); + let img = RgbaImage::from_raw(2, 1, px).unwrap(); + let mut out = image::imageops::thumbnail(&img, 1, 1).into_raw(); + let alpha = image::imageops::thumbnail(&image::GrayImage::from_raw(2, 1, vec![255, 0]).unwrap(), 1, 1).into_raw(); + unpremultiply(&mut out, &alpha); + let want = [40, 80, 120, 160]; + assert!(out.iter().zip(want).all(|(&c, w)| times_alpha(c, alpha[0]).abs_diff(times_alpha(w, alpha[0])) <= 1), "{out:?} {alpha:?}"); + } +} diff --git a/crates/doc/src/stored_art.rs b/crates/doc/src/stored_art.rs index e623e0ed0e..cc0832b733 100644 --- a/crates/doc/src/stored_art.rs +++ b/crates/doc/src/stored_art.rs @@ -20,6 +20,8 @@ pub enum StoredRoot { GraphDesign(usize), /// Object `art` of pattern swatch `pattern` of [`Document::patterns`]. Pattern { pattern: usize, art: usize }, + /// Root `index` of [`Document::mounted_art`]. + Mounted(usize), } /// Where a stored object is: its root and, inside opacity-mask art, the object that mask belongs @@ -170,10 +172,12 @@ impl Document { .iter() .enumerate() .flat_map(|(p, def)| def.art.iter().enumerate().map(move |(a, n)| (n, StoredRoot::Pattern { pattern: p, art: a }))); - symbols.chain(designs).chain(patterns) + let mounted = self.mounted_art.iter().enumerate().map(|(i, (n, _))| (n, StoredRoot::Mounted(i))); + symbols.chain(designs).chain(patterns).chain(mounted) } - /// Every root of stored art: the layers, then the art of symbols, graph designs and patterns. + /// Every root of stored art: the layers, then the art of symbols, graph designs and patterns, + /// then [`Document::mounted_art`]. fn stored_roots(&self) -> impl Iterator, StoredRoot)> { self.layers.iter().enumerate().map(|(i, l)| (l, StoredRoot::Layer(i))).chain(self.definition_roots()) } @@ -185,12 +189,13 @@ impl Document { StoredRoot::Symbol(i) => self.symbols.get_mut(i).map(|s| &mut s.art), StoredRoot::GraphDesign(i) => self.graph_designs.get_mut(i).map(|g| &mut g.art), StoredRoot::Pattern { pattern, art } => self.patterns.get_mut(pattern)?.art.get_mut(art), + StoredRoot::Mounted(i) => self.mounted_art.get_mut(i).map(|(n, _)| n), } } /// Visit every stored object with its place: the layer tree with the opacity-mask art of its /// objects, then the art of symbols, graph designs and pattern swatches (their definitions, - /// once each, never the copies instances and tiles draw). + /// once each, never the copies instances and tiles draw), then [`Document::mounted_art`]. pub fn visit_stored<'a>(&'a self, mut f: impl FnMut(&'a Node, StoredPlace)) { self.visit_stored_arcs(|n, place| f(n, place)); } @@ -238,6 +243,29 @@ impl Document { /// visited before them (the layer tree's own objects first) a new id, so every stored object /// can be named by its id. Returns how many changed; the id counter then stands above them. pub(crate) fn renumber_stored_duplicates(&mut self) -> usize { + self.renumber_duplicates_in(|_| true) + } + + /// Raises the id counter above the ids of [`Document::mounted_art`]'s objects, then gives those + /// objects whose id is 0, past the id range, or already taken by an object visited before them + /// (every other stored object first) a new id, as [`Self::renumber_stored_duplicates`] gives + /// them. Returns how many changed. + pub fn number_mounted_art(&mut self) -> usize { + let mut max = 0; + for (i, (root, _)) in self.mounted_art.iter().enumerate() { + visit(root, StoredPlace { root: StoredRoot::Mounted(i), mask_of: None }, &mut |n, _| { + if n.id.0 < MAX_NEXT_ID { + max = max.max(n.id.0); + } + }); + } + self.raise_next_id(max.saturating_add(1)); + self.renumber_duplicates_in(|r| matches!(r, StoredRoot::Mounted(_))) + } + + /// [`Self::renumber_stored_duplicates`] for the roots `pick` holds for only; the objects of the + /// others still count as taken. + fn renumber_duplicates_in(&mut self, pick: impl Fn(StoredRoot) -> bool) -> usize { let mut seen: HashSet = HashSet::new(); for l in &self.layers { l.walk(&mut |n| { @@ -250,9 +278,9 @@ impl Document { // Per root, the visiting indices of the nodes that take a new id. let mut fresh: Vec<(StoredRoot, HashSet)> = vec![]; for (root, r) in self.stored_roots() { - let (mut i, mut here) = (0, HashSet::new()); + let (mut i, mut here, take) = (0, HashSet::new(), pick(r)); visit(root, StoredPlace { root: r, mask_of: None }, &mut |n, place| { - if !place.in_layers() && (n.id.0 == 0 || n.id.0 >= MAX_NEXT_ID || !seen.insert(n.id)) { + if !place.in_layers() && (n.id.0 == 0 || n.id.0 >= MAX_NEXT_ID || !seen.insert(n.id)) && take { here.insert(i); } i += 1; @@ -355,6 +383,30 @@ mod tests { assert_eq!(d, again); } + /// Mounted art is found and changed by id after the other stored art, and numbering it gives + /// its objects that repeat another stored object's id, or have none, new ids above the counter, + /// leaving every other object's id and its own unique ones as they are. + #[test] + fn mounted_art_is_found_and_numbered_after_the_rest() { + let mut d = doc([12, 13, 14]); + let owner = serde_json::json!({ "kind": "brush" }); + d.mounted_art = vec![(Arc::new(masked(10, rect(0))), owner.clone()), (Arc::new(rect(15)), owner)]; + assert_eq!(d.stored_node(NodeId(15)).map(|(_, p)| p.root), Some(StoredRoot::Mounted(1))); + let before = d.clone(); + assert_eq!(d.number_mounted_art(), 2); + let mut ids = vec![]; + d.visit_stored(|n, _| ids.push(n.id.0)); + let unique: HashSet = ids.iter().copied().collect(); + assert_eq!(unique.len(), ids.len(), "{ids:?}"); + assert_eq!(&ids[..6], &[d.layers[0].id.0, 10, 11, 12, 13, 14], "the other art keeps its ids"); + assert_eq!(ids[8], 15, "a unique id is kept"); + assert!(ids.iter().all(|id| *id < d.peek_next_id()), "{ids:?} {}", d.peek_next_id()); + assert!(Arc::ptr_eq(&d.symbols[0].art, &before.symbols[0].art) && Arc::ptr_eq(&d.mounted_art[1].0, &before.mounted_art[1].0)); + d.stored_node_mut(NodeId(15)).unwrap().name = Some("changed".into()); + assert_eq!(d.mounted_art[1].0.name.as_deref(), Some("changed")); + assert_eq!(d.number_mounted_art(), 0, "a second pass changes nothing"); + } + #[test] fn renumbered_objects_on_path_keep_their_path_and_members() { // A symbol's Objects on Path group whose path repeats the layer's object 10 and whose diff --git a/crates/doc/src/swatches.rs b/crates/doc/src/swatches.rs index 844aa8c810..63951d8104 100644 --- a/crates/doc/src/swatches.rs +++ b/crates/doc/src/swatches.rs @@ -206,11 +206,13 @@ impl Document { impl Document { /// Visit every paint held by the art (opacity masks included), symbol definitions, pattern /// tiles and graphic styles (fills, strokes and text runs), and the colour of every - /// gradient-mesh point as a solid paint. + /// gradient-mesh point as a solid paint. A graph's default black legend fill is left out. pub fn visit_paints(&self, f: &mut dyn FnMut(&Paint)) { let mut tree = |n: &Node| { walk_with_masks(n, &mut |m| { - node_paints(m).chain(override_paints(m)).chain(graph_paints(m)).for_each(&mut *f); + node_paints(m).chain(override_paints(m)).for_each(&mut *f); + let default_legend = default_legend_fill(m); + graph_paints(m).enumerate().filter(|(i, _)| Some(*i) != default_legend).for_each(|(_, p)| f(p)); if let NodeKind::Mesh(mesh) = &m.kind { mesh.points.iter().for_each(|p| f(&Paint::solid(p.color))); } @@ -404,6 +406,19 @@ fn graph_paints_mut(g: &mut crate::graph::GraphSpec) -> impl Iterator Option { + let g = n.extras().graph.as_deref()?; + let l = &g.label_styles; + if l.legend.is_none() || !g.picks_legend_fill() { + return None; + } + let series: usize = g.series_paints.iter().map(|s| usize::from(s.fill.is_some()) + usize::from(s.stroke.is_some())).sum(); + Some(series + 2 * (usize::from(l.values.is_some()) + usize::from(l.categories.is_some()))) +} + /// Mutable [`node_paints`], in the same order. pub fn node_paints_mut(n: &mut Node) -> impl Iterator { let runs = match &mut n.kind { @@ -446,11 +461,16 @@ fn map_node(n: &Node, f: &mut PaintFn) -> Option<(Node, usize)> { } } // A graph's series and label paints, which its marks and labels take when it is drawn again. - let graph: Vec<(usize, Paint)> = graph_paints(n).enumerate().filter_map(|(i, p)| f(p).map(|q| (i, q))).collect(); + // The default black legend fill, which is not the legend labels' own, stays black. + let default_legend = default_legend_fill(n); + let graph: Vec<(usize, Paint)> = + graph_paints(n).enumerate().filter(|(i, _)| Some(*i) != default_legend).filter_map(|(i, p)| f(p).map(|q| (i, q))).collect(); if !graph.is_empty() { count += graph.len(); let m = out.get_or_insert_with(|| n.clone()); if let Some(spec) = m.extras_if_any().and_then(|e| e.graph.as_deref_mut()) { + // A legend fill of the labels' own stays theirs when the change makes it black. + spec.label_styles.mark_own_legend_fill(); let mut graph = graph.into_iter().peekable(); for (i, p) in graph_paints_mut(spec).enumerate() { if graph.peek().is_some_and(|c| c.0 == i) @@ -720,6 +740,62 @@ mod tests { assert!(graph_paints(d.node(a).unwrap()).all(Paint::is_none)); } + #[test] + fn a_legend_fill_mapped_to_black_stays_the_labels_own() { + let (mut d, a, _) = doc(); + let red = linked(Color::rgb(1.0, 0.0, 0.0), "Brand"); + let spec = crate::graph::GraphSpec { + label_styles: crate::graph::LabelStyles { legend: Some(crate::CharStyle { fill: red, ..Default::default() }), ..Default::default() }, + ..Default::default() + }; + assert!(spec.label_styles.legend_fill_is_own() && !spec.label_styles.legend_fill_set, "not black, saved without the mark"); + d.node_mut(a).unwrap().extras_mut().graph = Some(Box::new(spec)); + let mut to_black = |c: &mut Color, s: &mut Option, _: &mut f32| { + s.as_deref() == Some("Brand") && { + *c = Color::BLACK; + *s = None; + true + } + }; + assert_eq!(d.map_solid_paints(&mut to_black), 2, "the rectangle's fill and the legend fill"); + let styles = d.node(a).unwrap().extras().graph.clone().unwrap().label_styles; + assert_eq!(styles.legend.unwrap().fill, Paint::solid(Color::BLACK)); + assert!(styles.legend_fill_set, "the black fill is still the labels' own"); + } + + #[test] + fn the_default_black_legend_fill_is_left_as_it_is() { + use crate::graph::GraphKind; + // Only a pie with Legends in Wedges picks its legend labels' fill; the other graphs draw the kept black. + for (kind, in_wedges, picks) in [(GraphKind::Pie, true, true), (GraphKind::Pie, false, false), (GraphKind::Column, true, false)] { + let (mut d, a, _) = doc(); + let black = || crate::CharStyle { fill: Paint::solid(Color::BLACK), size: 11.0, ..Default::default() }; + let spec = crate::graph::GraphSpec { + kind, + legend: true, + pie_legend_in_wedges: in_wedges, + series_paints: vec![crate::SeriesPaint { fill: Some(Paint::solid(Color::BLACK)), ..Default::default() }], + label_styles: crate::graph::LabelStyles { values: Some(black()), legend: Some(black()), ..Default::default() }, + ..Default::default() + }; + let blacks = |d: &Document| { + let mut seen = 0; + d.visit_paints(&mut |p| seen += usize::from(*p == Paint::solid(Color::BLACK))); + seen + }; + let before = blacks(&d); + d.node_mut(a).unwrap().extras_mut().graph = Some(Box::new(spec)); + let want = if picks { 2 } else { 3 }; + assert_eq!(blacks(&d) - before, want, "{kind:?}, in wedges {in_wedges}: the series, value labels' and legend fills visited"); + let mut link_black = |c: &mut Color, s: &mut Option, _: &mut f32| *c == Color::BLACK && s.replace("Black".into()).is_none(); + assert_eq!(d.map_solid_paints_in(&[a], &mut link_black), want, "{kind:?}, in wedges {in_wedges}"); + let styles = d.node(a).unwrap().extras().graph.clone().unwrap().label_styles; + let legend = if picks { Paint::solid(Color::BLACK) } else { linked(Color::BLACK, "Black") }; + assert_eq!(styles.legend.unwrap().fill, legend, "{kind:?}, in wedges {in_wedges}: linked unless the pie picks the fill"); + assert_eq!(styles.values.unwrap().fill, linked(Color::BLACK, "Black")); + } + } + #[test] fn mapping_within_ids_visits_each_paint_once() { let (mut d, a, b) = doc(); diff --git a/crates/doc/src/symbol_nine_slice.rs b/crates/doc/src/symbol_nine_slice.rs index 3c8c1b324d..4877ee7b57 100644 --- a/crates/doc/src/symbol_nine_slice.rs +++ b/crates/doc/src/symbol_nine_slice.rs @@ -463,8 +463,13 @@ impl NineSliceMap { /// /// Strokes keep their weight, as they do for any instance. pub fn place(&self, art: &Node, doc: &Document) -> Node { - let boxes = doc.symbol_boxes().quick(); - self.place_at(art, &boxes, 0) + self.place_with(art, &doc.symbol_boxes().quick()) + } + + /// [`Self::place`] with the instances in `art` measured by `boxes`, quick boxes or boxes + /// measuring symbol art. + pub(crate) fn place_with(&self, art: &Node, boxes: &SymbolBoxes) -> Node { + self.place_at(art, boxes, 0) } /// [`Self::place`] without clip groups, for writers that do not apply clipping (DXF, WMF): @@ -480,16 +485,25 @@ impl NineSliceMap { /// object drawn in clip groups counts one group plus a clip path and a copy for each cell its /// box reaches. That is never more than [`MAX_SLICE_GROWTH`] for each object of `art`. pub fn most_placed(&self, art: &Node, doc: &Document) -> u64 { - let boxes = doc.symbol_boxes().quick(); - self.most_at(art, &boxes, 0) + self.most_placed_with(art, &doc.symbol_boxes().quick()) + } + + /// [`Self::most_placed`] with the instances in `art` measured by `boxes`, quick boxes or boxes + /// measuring symbol art. + pub(crate) fn most_placed_with(&self, art: &Node, boxes: &SymbolBoxes) -> u64 { + self.most_at(art, boxes, 0) } /// The affine map that [`Self::place`] and [`Self::place_unclipped`] move object `n` by as one /// piece, with everything in it: the map of the cell its box lies in, or of the cell at the /// origin when it has no box. `None` when its box crosses a guide. pub fn one_cell(&self, n: &Node, doc: &Document) -> Option { - let boxes = doc.symbol_boxes().quick(); - let Some(b) = n.geometric(Some(&boxes)).map(|b| self.natural.transform_rect_bbox(b)).filter(|b| finite(*b)) else { + self.one_cell_with(n, &doc.symbol_boxes().quick()) + } + + /// [`Self::one_cell`] with the instances in `n` measured by `boxes`. + pub(crate) fn one_cell_with(&self, n: &Node, boxes: &SymbolBoxes) -> Option { + let Some(b) = n.geometric(Some(boxes)).map(|b| self.natural.transform_rect_bbox(b)).filter(|b| finite(*b)) else { return Some(self.cell_at(Point::ZERO)); }; let (cols, rows) = (self.x.cells(b.x0, b.x1), self.y.cells(b.y0, b.y1)); @@ -501,6 +515,11 @@ impl NineSliceMap { Self { clips: false, ..*self }.most_placed(art, doc) } + /// This map placing without clip groups, as [`Self::place_unclipped`] does. + pub(crate) fn unclipped(&self) -> Self { + Self { clips: false, ..*self } + } + /// [`Self::most_placed`] for `n` at nesting depth `depth`, following [`Self::place_at`]. fn most_at(&self, n: &Node, boxes: &SymbolBoxes, depth: u32) -> u64 { let whole = n.count_with_masks() as u64; @@ -671,7 +690,7 @@ impl NineSliceMap { } /// `n` moved by `a`, its strokes at their own weight. -fn transformed(n: &Node, a: Affine) -> Node { +pub(crate) fn transformed(n: &Node, a: Affine) -> Node { let mut out = n.clone(); out.transform(a, false); out @@ -765,10 +784,7 @@ impl Document { /// `None` when the symbol has no guides or the instance is at its natural size. The guides cut /// the art's box with the instances in it measured by their own art. pub fn symbol_slice_map(&self, name: &str, xf: Affine) -> Option { - let guides = self.symbol_nine_slice(name)?; - let sym = self.symbols.iter().find(|s| s.name == name)?; - let art = self.symbol_boxes().quick().art_bounds(name).or_else(|| sym.art.geometric_bounds())?; - NineSliceMap::new(guides, art, self.symbol_natural_xf(name), xf) + self.symbol_boxes().quick().slice_map(name, xf) } /// [`Self::symbol_slice_map`] with the guides cutting `art`, the symbol's art box already @@ -782,9 +798,10 @@ impl Document { /// it has them ([`NineSliceMap::place`]), otherwise by `xf`. `None` when placing it through /// the guides could make more than [`MAX_SYMBOL_NODES`] objects ([`NineSliceMap::most_placed`]). pub fn place_symbol_art(&self, name: &str, art: &Node, xf: Affine) -> Option { - match self.symbol_slice_map(name, xf) { - Some(m) if m.most_placed(art, self) > MAX_SYMBOL_NODES => None, - Some(m) => Some(m.place(art, self)), + let boxes = self.symbol_boxes().quick(); + match boxes.slice_map(name, xf) { + Some(m) if m.most_placed_with(art, &boxes) > MAX_SYMBOL_NODES => None, + Some(m) => Some(m.place_with(art, &boxes)), None => Some(transformed(art, xf)), } } @@ -795,8 +812,8 @@ impl Document { pub fn edited_nine_slice(&self) -> Option { let se = self.symbol_edit.as_ref()?; let guides = self.symbol_nine_slice(&se.symbol)?; - let sym = self.symbols.iter().find(|s| s.name == se.symbol)?; - let art = self.symbol_boxes().quick().art_bounds(&se.symbol).or_else(|| sym.art.geometric_bounds())?; + let boxes = self.symbol_boxes().quick(); + let art = boxes.art_bounds(&se.symbol).or_else(|| boxes.symbol_art(&se.symbol)?.geometric_bounds())?; let natural = self.symbol_natural_xf(&se.symbol); let b = natural.transform_rect_bbox(art); if !finite(b) || b.width() <= 1e-9 || b.height() <= 1e-9 || natural.determinant().abs() < 1e-18 { @@ -811,8 +828,9 @@ impl Document { /// [`Self::place_symbol_art`] for writers that do not apply clipping /// ([`NineSliceMap::place_unclipped`]). pub fn place_symbol_art_unclipped(&self, name: &str, art: &Node, xf: Affine) -> Option { - match self.symbol_slice_map(name, xf) { - Some(m) => (m.most_placed_unclipped(art, self) <= MAX_SYMBOL_NODES).then(|| m.place_unclipped(art, self)), + let boxes = self.symbol_boxes().quick(); + match boxes.slice_map(name, xf).map(|m| m.unclipped()) { + Some(m) => (m.most_placed_with(art, &boxes) <= MAX_SYMBOL_NODES).then(|| m.place_with(art, &boxes)), None => Some(transformed(art, xf)), } } diff --git a/crates/doc/src/symbols.rs b/crates/doc/src/symbols.rs index dde6621993..944accfe4b 100644 --- a/crates/doc/src/symbols.rs +++ b/crates/doc/src/symbols.rs @@ -2,13 +2,14 @@ //! the document and measures it once, and an instance's bounds are its art's box placed by the //! instance's transform ([`Node::geometric_bounds_with`]). -use std::cell::{Cell, RefCell}; +use std::cell::{Cell, OnceCell, RefCell}; use std::collections::{HashMap, HashSet}; use std::sync::Arc; use vectorcraft_geom::{Affine, Rect}; -use crate::{AppearanceItem, Document, MAX_SYMBOL_NODES, Node, NodeKind, SYMBOL_HALF}; +use crate::symbol_nine_slice::transformed; +use crate::{AppearanceItem, Document, MAX_SYMBOL_NODES, NineSliceMap, Node, NodeKind, SYMBOL_HALF}; /// The box a symbol instance is measured by when its symbol's art has no box /// ([`SymbolBoxes::art`]), and in [`Node::geometric_bounds`]: the 20 × 20 square around the origin @@ -26,6 +27,9 @@ const MAX_REACHES: usize = 4096; /// A symbol's name and the bits of the linear part of a transform that places its art. type Placing = (String, [u64; 4]); +/// Each symbol name of a document → the index of the first symbol of that name. +pub(crate) type SymbolNames = HashMap; + /// A symbol's art measured in symbol space. #[derive(Clone, Copy, Debug, PartialEq)] pub(crate) struct ArtBox { @@ -51,6 +55,10 @@ pub(crate) struct ArtBox { /// symbols change. pub struct SymbolBoxes<'a> { doc: &'a Document, + /// Each symbol name of the document → the index of the first symbol of that name (the one a + /// name finds), made the first time a name is looked up ([`Self::symbol_art`]) or given by + /// [`Self::with_names`]. + names: OnceCell>, /// The art boxes measured so far, by symbol name (`None` for a symbol whose instances are /// measured by [`SYMBOL_SQUARE`]). measured: RefCell>>, @@ -89,6 +97,9 @@ pub struct SymbolBoxes<'a> { sliced_most: u64, /// The widths [`Self::measured_width`] has measured, by kind and symbol name. widths: RefCell>>, + /// While [`Self::consulted`] runs: the symbols whose art boxes [`Self::art`] has given outside + /// the measuring of symbol art. + consulted: RefCell>>, } impl Document { @@ -96,6 +107,7 @@ impl Document { pub fn symbol_boxes(&self) -> SymbolBoxes<'_> { SymbolBoxes { doc: self, + names: OnceCell::new(), measured: RefCell::default(), depths: RefCell::default(), quick: Cell::new(false), @@ -110,8 +122,27 @@ impl Document { sliced_placed: Cell::new(0), sliced_most: MAX_SYMBOL_NODES, widths: RefCell::default(), + consulted: RefCell::default(), } } + + /// Each symbol name of this document → the index of the first symbol of that name (the one a + /// name finds). + pub(crate) fn symbol_names(&self) -> SymbolNames { + #[cfg(test)] + SYMBOLS_READ.with(|c| c.set(c.get() + self.symbols.len())); + let mut names = HashMap::with_capacity(self.symbols.len()); + for (i, s) in self.symbols.iter().enumerate() { + names.entry(s.name.clone()).or_insert(i); + } + names + } +} + +#[cfg(test)] +thread_local! { + /// How many symbols [`Document::symbol_names`] has read on this thread. + pub(crate) static SYMBOLS_READ: Cell = const { Cell::new(0) }; } impl<'a> SymbolBoxes<'a> { @@ -120,6 +151,26 @@ impl<'a> SymbolBoxes<'a> { self.doc } + /// Makes these boxes find symbols by `names` ([`Document::symbol_names`]), made from the + /// document's symbols while they had the names and order they have now. + pub(crate) fn with_names(self, names: &Arc) -> Self { + let _ = self.names.set(names.clone()); + self + } + + /// The art of the first symbol of the document named `name`, found in time independent of the + /// number of symbols after the first lookup. + pub(crate) fn symbol_art(&self, name: &str) -> Option<&'a Arc> { + let doc: &'a Document = self.doc; + let names = self.names.get_or_init(|| Arc::new(doc.symbol_names())); + let i = *names.get(name)?; + match doc.symbols.get(i) { + Some(s) if s.name == name => Some(&s.art), + // Names that no longer match the symbols: the first symbol of that name. + _ => doc.symbols.iter().find(|s| s.name == name).map(|s| &s.art), + } + } + /// Makes these boxes measure every symbol instance as [`Node::reach_bounds_with`] does, by its /// art box alone. An instance that scales or turns stroked art then measures a little larger /// than with [`Node::visual_bounds_with`], and its art is not transformed to measure it. The @@ -160,21 +211,37 @@ impl<'a> SymbolBoxes<'a> { /// art boxes. Returns `None` when [`Self::depth`] is `None` and when the art has no finite /// bounds: instances of the symbol are then measured by [`SYMBOL_SQUARE`]. pub(crate) fn art(&self, name: &str) -> Option { - if let Some(b) = self.measured.borrow().get(name) { - return *b; + let cached = self.measured.borrow().get(name).copied(); + let b = cached.unwrap_or_else(|| { + let b = self.measure_art(name, |art| self.in_art(|| art_box(art, self))).flatten(); + self.measured.borrow_mut().insert(name.to_string(), b); + b + }); + if b.is_some() + && let Some(seen) = self.consulted.borrow_mut().as_mut() + && !seen.contains(name) + { + seen.insert(name.to_string()); } - let b = self.measure_art(name, |art| self.in_art(|| art_box(art, self))).flatten(); - self.measured.borrow_mut().insert(name.to_string(), b); b } + /// Runs `measure`, and returns the names of the symbols whose art boxes it took from these + /// boxes, the art of symbols it measured left out: the symbols whose art the instances it + /// measured are measured by. + pub(crate) fn consulted(&self, measure: impl FnOnce()) -> HashSet { + let was = self.consulted.replace(Some(HashSet::new())); + measure(); + self.consulted.replace(was).unwrap_or_default() + } + /// Runs `measure` on the art of the symbol named `name`. Returns `None` when [`Self::depth`] /// is `None`, without running it. pub fn measure_art(&self, name: &str, measure: impl FnOnce(&Arc) -> R) -> Option { self.depth(name)?; - let sym = self.doc.symbols.iter().find(|s| s.name == name)?; + let art = self.symbol_art(name)?; self.runs.set(self.runs.get() + 1); - Some(measure(&sym.art)) + Some(measure(art)) } /// How many times [`Self::measure_art`] has run a measure on symbol art for these boxes, the @@ -297,10 +364,9 @@ impl<'a> SymbolBoxes<'a> { /// other symbols it reaches: the depth of each one it walks to the end, and `None` for those on /// the way down to a symbol that holds an instance of itself or nests too deep. fn find_depth(&self, name: &str, learned: &mut HashMap>) -> Option { - let art = |n: &str| self.doc.symbols.iter().find(|s| s.name == n).map(|s| &s.art); // The symbols on the way down from `name`: each with the symbols its art shows that are // still to be walked, and the deepest nesting found under it so far. - let mut path: Vec<(String, Vec, usize)> = vec![(name.to_string(), shown(self.doc, art(name)?), 0)]; + let mut path: Vec<(String, Vec, usize)> = vec![(name.to_string(), self.shown(self.symbol_art(name)?), 0)]; loop { let (_, todo, _) = path.last_mut()?; let Some(next) = todo.pop() else { @@ -330,8 +396,8 @@ impl<'a> SymbolBoxes<'a> { // Symbols nested MAX_DEPTH deep under `name`. None if path.len() >= MAX_DEPTH => return None, None => { - if let Some(a) = art(&next) { - let todo = shown(self.doc, a); + if let Some(a) = self.symbol_art(&next) { + let todo = self.shown(a); path.push((next, todo, 0)); } } @@ -379,9 +445,9 @@ impl<'a> SymbolBoxes<'a> { None => { // The most objects placing makes, the art of opacity masks included, is set aside // while the art is placed and measured, and what placing did not make is given back. - let art = &self.doc.symbols.iter().find(|s| s.name == name)?.art; - let most = match self.doc.symbol_slice_map(name, linear) { - Some(m) => m.most_placed(art, self.doc), + let art = self.symbol_art(name)?; + let most = match self.slice_map(name, linear) { + Some(m) => self.in_art(|| m.most_placed_with(art, self)), None => art.count_with_masks() as u64, }; let used = self.sliced_placed.get(); @@ -398,6 +464,14 @@ impl<'a> SymbolBoxes<'a> { v.map(|v| moved.transform_rect_bbox(v)) } + /// [`Document::symbol_slice_map`] with the guides cutting the art box these boxes measure for + /// the symbol (its geometric part, which does not depend on the mode of the boxes). + pub(crate) fn slice_map(&self, name: &str, xf: Affine) -> Option { + let guides = self.doc.symbol_nine_slice(name)?; + let art = self.art_bounds(name).or_else(|| self.symbol_art(name)?.geometric_bounds())?; + NineSliceMap::new(guides, art, self.doc.symbol_natural_xf(name), xf) + } + /// The box [`Self::placed_visual_within`] returns outside quick boxes. fn place_and_measure(&self, name: &str, xf: Affine, most: u64) -> Option { self.place_and_count(name, xf, most).and_then(|(v, _)| v) @@ -407,10 +481,10 @@ impl<'a> SymbolBoxes<'a> { /// opacity masks included. `None` when the art is not placed. fn place_and_count(&self, name: &str, xf: Affine, most: u64) -> Option<(Option, u64)> { self.measure_art(name, |art| { - let art = match self.doc.symbol_slice_map(name, xf) { - Some(m) if m.most_placed(art, self.doc) > most => return None, - Some(m) => m.place(art, self.doc), - None => self.doc.place_symbol_art(name, art, xf)?, + let art = match self.slice_map(name, xf) { + Some(m) if self.in_art(|| m.most_placed_with(art, self)) > most => return None, + Some(m) => self.in_art(|| m.place_with(art, self)), + None => transformed(art, xf), }; Some((self.in_art(|| art.visual(Some(self))), art.count_with_masks() as u64)) }) @@ -431,11 +505,28 @@ impl<'a> SymbolBoxes<'a> { fn in_art(&self, f: impl FnOnce() -> R) -> R { let pad = self.brush_art.replace(false); let strokes = self.art_strokes.replace(true); + let consulted = self.consulted.take(); let r = self.quickly(f); self.brush_art.set(pad); self.art_strokes.set(strokes); + *self.consulted.borrow_mut() = consulted; r } + + /// The names of the symbols of the document that the instances in `art` show, each once. + fn shown(&self, art: &Node) -> Vec { + let mut seen = HashSet::new(); + let mut names = vec![]; + art.walk(&mut |n| { + if let NodeKind::SymbolInstance { symbol, .. } = &n.kind + && seen.insert(symbol.as_str()) + && self.symbol_art(symbol).is_some() + { + names.push(symbol.clone()); + } + }); + names + } } /// Records every symbol on `path` in `learned` as one whose instances are measured by @@ -447,21 +538,6 @@ fn give_up(path: &[(String, Vec, usize)], learned: &mut HashMap Vec { - let mut seen = HashSet::new(); - let mut names = vec![]; - art.walk(&mut |n| { - if let NodeKind::SymbolInstance { symbol, .. } = &n.kind - && seen.insert(symbol.as_str()) - && doc.symbols.iter().any(|s| s.name == *symbol) - { - names.push(symbol.clone()); - } - }); - names -} - /// Measures symbol art `art`, with the instances in it measured by `symbols`. fn art_box(art: &Arc, symbols: &SymbolBoxes) -> Option { let finite = |r: &Rect| [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()); @@ -630,6 +706,39 @@ mod tests { assert_eq!(s.sliced_placed.get(), 13); } + #[test] + fn measuring_9_slice_instances_reads_the_symbol_list_once() { + // 2,000 symbols, then a frame with guides and a symbol with guides holding the frame + // scaled 2 times across, each shown by 200 instances scaled by different amounts. + let mut d = Document::new(200.0, 200.0); + for i in 0..2000 { + let dot = rect(&mut d, Rect::new(0.0, 0.0, 1.0, 1.0), 0.0); + symbol(&mut d, &format!("Dot {i}"), vec![dot]); + } + let frame = rect(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), 1.0); + symbol(&mut d, "Panel", vec![frame]); + d.set_symbol_nine_slice("Panel", Some(crate::SymbolNineSlice::default())); + let wide = instance(&mut d, "Panel", Affine::scale_non_uniform(2.0, 1.0)); + symbol(&mut d, "Holder", vec![wide]); + d.set_symbol_nine_slice("Holder", Some(crate::SymbolNineSlice::default())); + let scaled = |d: &mut Document, name: &str| -> Vec { + (1..=200).map(|i| instance(d, name, Affine::scale_non_uniform(1.0 + f64::from(i) / 100.0, 1.5))).collect() + }; + let (panels, holders) = (scaled(&mut d, "Panel"), scaled(&mut d, "Holder")); + // What each instance measures in boxes of its own. + let exact: Vec<_> = panels.iter().map(|n| n.visual_bounds_with(&d.symbol_boxes())).collect(); + let quick: Vec<_> = holders.iter().map(|n| n.visual_bounds_with(&d.symbol_boxes().quick())).collect(); + let read = || SYMBOLS_READ.with(Cell::get); + let before = read(); + let s = d.symbol_boxes(); + assert_eq!(panels.iter().map(|n| n.visual_bounds_with(&s)).collect::>(), exact); + let s = d.symbol_boxes().quick(); + assert_eq!(holders.iter().map(|n| n.visual_bounds_with(&s)).collect::>(), quick); + // Each set of boxes reads the list once to find symbols by name. + let symbols = d.symbols.len(); + assert!(read() - before <= 2 * symbols, "{} symbols read", read() - before); + } + #[test] fn missing_symbols_and_symbols_inside_themselves_measure_as_the_square() { let mut d = Document::new(200.0, 200.0); diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index c3c1464cfc..89388d8598 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -18,8 +18,8 @@ mod wrap; pub use area::{AreaFit, AreaOptions, PathAlign, PathEffect, TextFlow, TextWrap, VerticalAlign, WrapShape}; use char_style::yes; pub use char_style::{ - CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, MAX_AKI, MAX_TSUME, MAX_WARICHU_GAP, ScriptMetrics, WARICHU_LINES, - WARICHU_SCALE, WarichuAlign, + CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, GlyphForm, MAX_AKI, MAX_TSUME, MAX_WARICHU_GAP, ScriptMetrics, + WARICHU_LINES, WARICHU_SCALE, WarichuAlign, }; pub use composite::{ COMPOSITE_BASELINE, COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, COMPOSITE_SCALE, COMPOSITE_SIZE, CharClass, CompositeFont, CompositePart, diff --git a/crates/doc/src/text/char_style.rs b/crates/doc/src/text/char_style.rs index ef3cf29dc9..97f744dba8 100644 --- a/crates/doc/src/text/char_style.rs +++ b/crates/doc/src/text/char_style.rs @@ -205,6 +205,99 @@ pub struct CharStyle { /// default glyph otherwise. Saved only when set. #[serde(default, rename = "glyphAlternate", skip_serializing_if = "Option::is_none")] pub glyph_alternate: Option, + /// The East Asian glyph form these characters are drawn in (Glyphs panel menu, with Show East + /// Asian Options): one OpenType feature of the font, such as JIS 78 forms (`jp78`), or the + /// font's default glyphs. The text keeps its characters. Saved only when set. + /// + #[serde(default, rename = "glyphForm", skip_serializing_if = "crate::skip::is_default")] + pub glyph_form: GlyphForm, +} + +/// The East Asian glyph form characters are drawn in ([`CharStyle::glyph_form`]): the font's +/// default glyphs, or the glyphs one OpenType feature substitutes. One form at a time. +/// +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum GlyphForm { + /// The font's default glyphs. + #[default] + Default, + /// Traditional forms (`trad`). + Traditional, + /// Expert forms (`expt`). + Expert, + /// JIS 2004 forms (`jp04`). + Jis04, + /// JIS 90 forms (`jp90`). + Jis90, + /// JIS 78 forms (`jp78`). + Jis78, + /// JIS 83 forms (`jp83`). + Jis83, + /// Monospaced full-width forms (`fwid`). + FullWidth, + /// Monospaced half-width forms (`hwid`). + HalfWidth, + /// Monospaced third-width forms (`twid`). + ThirdWidth, + /// Monospaced quarter-width forms (`qwid`). + QuarterWidth, +} + +impl GlyphForm { + /// Every form, in menu order, the default last. + pub const ALL: [GlyphForm; 11] = [ + GlyphForm::Traditional, + GlyphForm::Expert, + GlyphForm::Jis04, + GlyphForm::Jis90, + GlyphForm::Jis78, + GlyphForm::Jis83, + GlyphForm::FullWidth, + GlyphForm::HalfWidth, + GlyphForm::ThirdWidth, + GlyphForm::QuarterWidth, + GlyphForm::Default, + ]; + + /// The name files and commands give this form (as it is saved). + pub fn id(self) -> &'static str { + match self { + GlyphForm::Default => "default", + GlyphForm::Traditional => "traditional", + GlyphForm::Expert => "expert", + GlyphForm::Jis04 => "jis04", + GlyphForm::Jis90 => "jis90", + GlyphForm::Jis78 => "jis78", + GlyphForm::Jis83 => "jis83", + GlyphForm::FullWidth => "fullWidth", + GlyphForm::HalfWidth => "halfWidth", + GlyphForm::ThirdWidth => "thirdWidth", + GlyphForm::QuarterWidth => "quarterWidth", + } + } + + /// The form [`GlyphForm::id`] names; `None` for any other name. + pub fn from_id(id: &str) -> Option { + GlyphForm::ALL.into_iter().find(|f| f.id() == id) + } + + /// The OpenType feature that draws this form; `None` for the default glyphs. + pub fn feature(self) -> Option<&'static [u8; 4]> { + Some(match self { + GlyphForm::Default => return None, + GlyphForm::Traditional => b"trad", + GlyphForm::Expert => b"expt", + GlyphForm::Jis04 => b"jp04", + GlyphForm::Jis90 => b"jp90", + GlyphForm::Jis78 => b"jp78", + GlyphForm::Jis83 => b"jp83", + GlyphForm::FullWidth => b"fwid", + GlyphForm::HalfWidth => b"hwid", + GlyphForm::ThirdWidth => b"twid", + GlyphForm::QuarterWidth => b"qwid", + }) + } } /// A glyph chosen for one character ([`CharStyle::glyph_alternate`]): the glyph id and the face it @@ -586,6 +679,7 @@ impl Default for CharStyle { no_break: false, language: None, glyph_alternate: None, + glyph_form: GlyphForm::Default, } } } diff --git a/crates/effects/src/bake.rs b/crates/effects/src/bake.rs index 27d3194eb3..54d97a4527 100644 --- a/crates/effects/src/bake.rs +++ b/crates/effects/src/bake.rs @@ -17,7 +17,8 @@ //! object of its own, a stroke a path stroked by it alone (brushed strokes their brush art, made by //! the caller). -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; +use std::rc::Rc; use std::sync::Arc; use vectorcraft_doc::color::Paint; @@ -26,7 +27,7 @@ use vectorcraft_geom::{Affine, FillRule, PathData, Rect, Vec2}; use crate::distort::{transform_move, transform_offsets}; use crate::group::{has_own_paint, paints}; -use crate::reshape::{as_art, clipping_text_outline, geometry_effects, glyph_outlines, outline_nested_text, reshape_leaves}; +use crate::reshape::{as_art, clipping_text_outline, dressed, geometry_effects, glyph_outlines, outline_nested_text, reshape_leaves}; use crate::{ GeomContext, adjust_in_document, apply_geometry_carrying, crop_marks_art, evaluate_container, has_adjustment, has_crop_marks, has_geometry, has_instance_row_raster, has_item_geometry, has_pathfinder, is_pathfinder, merged_params, needs_outline, reshape, @@ -114,13 +115,218 @@ thread_local! { /// The objects of symbol art that [`bake_document`] has baked for instances inside the art of /// other instances, counted against [`crate::SYMBOL_ART_MAX_NODES`]. static NESTED_NODES: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// While [`bake_document_placing_symbols`] bakes: the symbols whose instances become their + /// placed art ([`placed_symbol_art`]). + static PLACING: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; + /// The objects in the baked art of the instances that [`bake_node`] has replaced by their + /// placed art for one export ([`placed_symbol_art`]), counted against [`Placing::most_nodes`]. + static PLACED_NODES: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// The objects in the baked art of the instances that [`bake_node`] baked for one export and + /// then left as they are ([`placed_fits`] refused the art), counted with [`PLACED_NODES`] + /// against [`Placing::most_nodes`] before more art is baked. Never given back. + static DROPPED_NODES: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// How deep the object [`bake_node`] is baking sits in the tree it returns: a top-level layer + /// is 1 deep. + static LEVEL: std::cell::Cell = const { std::cell::Cell::new(1) }; + /// Whether [`bake_node`] is baking inside an object the export does not write ([`unwritten`]), + /// where no instance is placed. + static UNWRITTEN: std::cell::Cell = const { std::cell::Cell::new(false) }; } -/// `n` with its geometry effects evaluated (`None` = unchanged). +/// `f` run for an object one level deeper ([`LEVEL`]) than the one being baked. +fn one_deeper(f: impl FnOnce() -> T) -> T { + LEVEL.with(|c| c.set(c.get() + 1)); + let out = f(); + LEVEL.with(|c| c.set(c.get().saturating_sub(1))); + out +} + +/// The symbols whose instances [`bake_document_placing_symbols`] replaces by their placed art, and +/// how that art is placed through 9-slice guides. +struct Placing { + /// The names of the symbols whose art draws something that baking changes, directly or through + /// the instances of other such symbols in it ([`drawn_symbols`]). + symbols: HashSet, + /// Whether 9-slice cells are clipped ([`Document::place_symbol_art`]) or not + /// ([`Document::place_symbol_art_unclipped`]). + clip_slices: bool, + /// Most objects the baked art of all placed instances may hold together: + /// [`vectorcraft_doc::MAX_SYMBOL_NODES`] for an export. + most_nodes: u64, + /// How deep the document's symbols and patterns draw, for the instances and pattern paints + /// left in placed art. + heights: vectorcraft_doc::depth::DrawnHeights, + /// The hidden layers and layers that do not print that the export writes. + layers: WrittenLayers, +} + +/// The layers an exporter writes besides the shown, printing ones +/// ([`bake_document_placing_symbols`]). Template layers are never written. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct WrittenLayers { + /// Hidden layers (written turned off, as PDF layers and DXF write them). + pub hidden: bool, + /// Layers that do not print. + pub non_printing: bool, +} + +/// Does the export leave `n` and everything in it out, while [`bake_document_placing_symbols`] +/// bakes? A hidden object other than a layer, a template layer, and a hidden layer or a layer +/// that does not print when the export leaves those out ([`WrittenLayers`]). +fn unwritten(n: &Node) -> bool { + PLACING.with(|p| { + p.borrow().as_ref().is_some_and(|p| match n.kind { + NodeKind::Layer { template, printable, .. } => template || !(printable || p.layers.non_printing) || !(n.visible || p.layers.hidden), + _ => !n.visible, + }) + }) +} + +/// Can `baked`, the baked art of a placed instance, take the instance's place [`LEVEL`] deep, +/// when the art placed for the export so far holds `spent` objects and the art baked for +/// instances left as they are holds `dropped` ([`DROPPED_NODES`])? `Some` with the +/// objects placed then, when its objects (opacity masks' art included) fit with those within +/// [`Placing::most_nodes`] and nothing in it, the symbols and patterns it uses included, draws +/// deeper than [`vectorcraft_doc::depth::MAX_DRAWN_DEPTH`]. +fn placed_fits(baked: &Node, spent: u64, dropped: u64) -> Option { + PLACING.with(|p| { + let p = p.borrow(); + let p = p.as_ref()?; + let spent = spent.saturating_add(baked.count_with_masks() as u64); + let deepest = p.heights.deepest(baked, LEVEL.with(|c| c.get())); + (spent.saturating_add(dropped) <= p.most_nodes && deepest <= vectorcraft_doc::depth::MAX_DRAWN_DEPTH).then_some(spent) + }) +} + +/// The names of the symbols of `d` whose art needs baking ([`needs_bake`]), and of those whose art +/// holds an instance of one of them at any depth, in the art of enabled opacity masks too. +fn drawn_symbols(d: &Document) -> HashSet { + fn used(n: &Node, names: &mut Vec) { + if let NodeKind::SymbolInstance { symbol, .. } = &n.kind { + names.push(symbol.clone()); + } + if let Some(m) = n.extras().mask.as_ref().filter(|m| !m.disabled) { + used(&m.art, names); + } + for c in n.children().into_iter().flatten() { + used(c, names); + } + } + let mut out: HashSet = d.symbols.iter().filter(|s| needs_bake(&s.art)).map(|s| s.name.clone()).collect(); + if out.is_empty() { + return out; + } + let uses: Vec<(&str, Vec)> = d + .symbols + .iter() + .filter(|s| !out.contains(&s.name)) + .map(|s| { + let mut names = vec![]; + used(&s.art, &mut names); + (s.name.as_str(), names) + }) + .collect(); + loop { + let before = out.len(); + for (name, names) in &uses { + if !out.contains(*name) && names.iter().any(|x| out.contains(x)) { + out.insert((*name).to_string()); + } + } + if out.len() == before { + return out; + } + } +} + +/// Does `n`'s subtree hold an instance of a symbol that [`bake_document_placing_symbols`] replaces +/// by its placed art, in the art of its enabled opacity masks too? False outside it, and for +/// objects the export does not write ([`unwritten`]). +fn holds_placed_symbol(n: &Node) -> bool { + placed_symbol_in(n, true) +} + +/// [`holds_placed_symbol`], with the art of `n`'s own opacity mask left out unless `own_mask` +/// (the art of the masks inside `n` is always looked into). +fn placed_symbol_in(n: &Node, own_mask: bool) -> bool { + fn walk(n: &Node, symbols: &HashSet, own_mask: bool) -> bool { + !unwritten(n) + && (matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if symbols.contains(symbol)) + || (own_mask && !n.is_ruler_guide() && n.extras().mask.as_ref().is_some_and(|m| !m.disabled && walk(&m.art, symbols, true))) + || n.children().is_some_and(|ch| ch.iter().any(|c| walk(c, symbols, true)))) + } + !UNWRITTEN.with(|c| c.get()) && PLACING.with(|p| p.borrow().as_ref().is_some_and(|p| walk(n, &p.symbols, own_mask))) +} + +/// Symbol instance `n`, while [`bake_document_placing_symbols`] bakes and its symbol is one it +/// places, as the art it draws: the symbol's art with the instance's own appearance changes and +/// its stain ([`vectorcraft_doc::symbol_overrides::instance_art`]), placed by the instance as the exporters +/// place it, in a group with the instance's id, name, visibility, transparency, opacity mask, +/// raster effects and attributes (its URL among them). The art is placed before its effects are baked, as the canvas draws it, so an +/// instance that scales its art does not scale what its effects do. `None` for other objects, +/// for instances the export does not write ([`unwritten`], hidden or inside such an object), for +/// instances nested [`vectorcraft_doc::depth::MAX_DEPTH`] deep in such art, and when the art +/// as placed, before its effects are baked, would already take the art placed for the export, +/// with the art baked for instances left as they are ([`DROPPED_NODES`]), past +/// [`Placing::most_nodes`]; those instances stay as they are. `Some` with the objects in the art +/// as placed, before its effects are baked. [`bake_node`] checks the baked art with +/// [`placed_fits`]. +fn placed_symbol_art(d: &Document, n: &Node) -> Option<(Node, u64)> { + let NodeKind::SymbolInstance { symbol, xf } = &n.kind else { return None }; + let (clip, most_nodes) = PLACING.with(|p| p.borrow().as_ref().filter(|p| p.symbols.contains(symbol)).map(|p| (p.clip_slices, p.most_nodes)))?; + if INSTANCE_DEPTH.with(|c| c.get()) >= vectorcraft_doc::depth::MAX_DEPTH || UNWRITTEN.with(|c| c.get()) || unwritten(n) { + return None; + } + let sym = d.symbols.iter().find(|s| s.name == *symbol)?; + let art = vectorcraft_doc::symbol_overrides::instance_art(&sym.art, n); + let most = match d.symbol_slice_map(symbol, *xf) { + Some(m) if clip => m.most_placed(&art, d), + Some(m) => m.most_placed_unclipped(&art, d), + None => art.count_with_masks() as u64, + }; + if PLACED_NODES.with(|c| c.get()).saturating_add(DROPPED_NODES.with(|c| c.get())).saturating_add(most) > most_nodes { + return None; + } + let placed = if clip { d.place_symbol_art(symbol, &art, *xf) } else { d.place_symbol_art_unclipped(symbol, &art, *xf) }?; + let mut g = dressed(Node::group(n.id, vec![Arc::new(placed)]), n); + g.extras_mut().attrs = n.extras().attrs.clone(); + Some((g, most)) +} + +/// `n` with its geometry effects evaluated (`None` = unchanged), and the art of its enabled opacity +/// mask baked one level deeper when it holds instances that [`bake_document_placing_symbols`] +/// places ([`holds_placed_symbol`]), so the mask masks with the art the instances draw. The art is +/// baked only while the object baked from `n` still carries `n`'s mask art; art already baked +/// with `n`'s recolored or placed form is not baked again. A ruler guide's mask stays as it is. fn bake_node(d: &mut Document, n: &Node) -> Option { + let out = bake_object(d, n); + let Some(mask) = n.extras().mask.as_ref().filter(|m| !m.disabled && !n.is_ruler_guide() && !unwritten(n) && holds_placed_symbol(&m.art)) else { + return out; + }; + let changed = out.is_some(); + let mut out = out.unwrap_or_else(|| n.clone()); + let Some(slot) = out.extras_if_any().and_then(|e| e.mask.as_mut()).filter(|s| Arc::ptr_eq(&s.art, &mask.art)) else { + return changed.then_some(out); + }; + let Some(art) = one_deeper(|| bake_node(d, &mask.art)) else { return changed.then_some(out) }; + slot.art = Arc::new(art); + Some(out) +} + +/// `n` with its geometry effects evaluated (`None` = unchanged); its opacity mask is left to +/// [`bake_node`]. +fn bake_object(d: &mut Document, n: &Node) -> Option { + // Inside an object the export leaves out, effects are baked but no instance is placed. + if !UNWRITTEN.with(|c| c.get()) && unwritten(n) { + UNWRITTEN.with(|c| c.set(true)); + let out = bake_node(d, n); + UNWRITTEN.with(|c| c.set(false)); + return out; + } // A cancelled export leaves the rest of the document as it is: the caller drops the result. // A ruler guide draws nothing and stays as it is, last in its layer. - if n.is_ruler_guide() || !needs_bake(n) || vectorcraft_doc::cancel::is_cancelled() { + // An object whose own mask's art alone holds placed instances stays as it is here. + if n.is_ruler_guide() || !(needs_bake(n) || placed_symbol_in(n, false)) || vectorcraft_doc::cancel::is_cancelled() { return None; } // Colour adjustments: the object recoloured (inside it too), then baked as it is. @@ -181,6 +387,26 @@ fn bake_node(d: &mut Document, n: &Node) -> Option { } return Some(baked.unwrap_or(m)); } + // Symbol instances whose art draws live effects, when the caller asks for them: the art + // placed, then baked. When the baked art passes the export's budget, or would draw too deep + // where the instance is, it is dropped with the art placed for the instances inside it, and + // the instance stays as it is. While the art bakes, its objects before baking are held in + // the budget, so the instances inside it are placed only within what is left; art baked and + // then dropped still counts against the budget for the instances after it. + if let Some((m, most)) = placed_symbol_art(d, n) { + let spent = PLACED_NODES.with(|c| c.get()); + PLACED_NODES.with(|c| c.set(spent.saturating_add(most))); + INSTANCE_DEPTH.with(|c| c.set(c.get() + 1)); + let baked = bake_node(d, &m); + INSTANCE_DEPTH.with(|c| c.set(c.get() - 1)); + let baked = baked.unwrap_or(m); + if let Some(now) = placed_fits(&baked, spent, DROPPED_NODES.with(|c| c.get())) { + PLACED_NODES.with(|c| c.set(now)); + return Some(baked); + } + PLACED_NODES.with(|c| c.set(spent)); + DROPPED_NODES.with(|c| c.set(c.get().saturating_add(baked.count_with_masks() as u64))); + } // A path whose Transform effect copies it with a gradient, or scales its strokes or moves its // patterns: each copy an object of its own, so its gradient fits it rather than spanning // every copy and its strokes and patterns can differ from the others'. @@ -201,6 +427,9 @@ fn bake_node(d: &mut Document, n: &Node) -> Option { { return bake_leaf(d, n); } + if let Some(m) = clip_group_with_type_clip(d, n) { + return Some(m); + } let mut m = n.clone(); // A clipping path takes the geometry effects in it as the canvas clips by it, those of a // compound path's paths before the compound path's own ([`crate::clip::with_clip_effects_applied`]); @@ -211,11 +440,11 @@ fn bake_node(d: &mut Document, n: &Node) -> Option { .enumerate() .map(|(i, c)| match (i < clip).then(|| crate::clip::with_clip_effects_applied(c)).flatten() { Some(a) => { - let mut a = bake_node(d, &a).unwrap_or(a); + let mut a = one_deeper(|| bake_node(d, &a)).unwrap_or(a); fresh_ids(d, &mut a, &mut std::collections::HashSet::new()); Arc::new(a) } - None => bake_node(d, c).map(Arc::new).unwrap_or_else(|| c.clone()), + None => one_deeper(|| bake_node(d, c)).map(Arc::new).unwrap_or_else(|| c.clone()), }) .collect(); if let Some(ch) = m.children_mut() { @@ -226,17 +455,77 @@ fn bake_node(d: &mut Document, n: &Node) -> Option { bake_leaf(d, n) } +/// Clip group or clipping layer `n` whose clipping path is type with geometry effects (its own, its +/// fills' or strokes', or a perspective), baked as the canvas draws it: the type becomes a +/// clipping path of the region the canvas clips to ([`crate::clip_outline`]), its fills (with their +/// effects baked) paint behind the clipped art inside the clip, and its strokes paint over it +/// outside the clip, in a group that `n` becomes with its clip group inside ([`Node::clip_paint`]). +/// The other members are baked as usual. `None` for other objects and when the type has nothing to +/// clip by. +fn clip_group_with_type_clip(d: &mut Document, n: &Node) -> Option { + let (first, rest) = n.children()?.split_first()?; + if !n.clips() + || !matches!(first.kind, NodeKind::Text(_)) + || !(has_geometry(&first.appearance.effects) || first.projection().is_some() || has_item_geometry(first)) + { + return None; + } + let (bp, rule) = crate::clip_outline(first)?; + let mut clip = Node::path(first.id, PathData::from_bezpath(&bp), Appearance::default()); + if let NodeKind::Path { rule: r, clipping, .. } = &mut clip.kind { + (*r, *clipping) = (rule, true); + } + clip.name = first.name.clone(); + clip.visible = first.visible; + let paint = first.clip_paint(); + // The type's fills and strokes as art: baked with the type's id, as the renderer draws them, + // then given ids of their own. + let mut seen = std::collections::HashSet::from([n.id, first.id]); + let mut art = |d: &mut Document, part: Option| { + part.map(|p| { + let mut a = bake_node(d, &p).unwrap_or(p); + fresh_ids(d, &mut a, &mut seen); + Arc::new(a) + }) + }; + let fill = art(d, paint.fill); + let stroke = art(d, paint.stroke); + let members: Vec> = + std::iter::once(Arc::new(clip)).chain(fill).chain(rest.iter().map(|c| bake_node(d, c).map(Arc::new).unwrap_or_else(|| c.clone()))).collect(); + let mut m = n.clone(); + let Some(stroke) = stroke else { + if let Some(ch) = m.children_mut() { + *ch = members; + } + return Some(m); + }; + // `n` keeps its id, name and transparency, and holds the clip group and the strokes over it. + let inner = Node::new(d.alloc_id(), NodeKind::Group { children: members, clip: true }); + match &mut m.kind { + NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. } => { + *children = vec![Arc::new(inner), stroke]; + *clip = false; + } + _ => return None, + } + Some(m) +} + /// `m`, art evaluated from an object, with its children baked and then given ids of their own (the /// pieces copied from the source keep the source's ids until then). The pieces are baked with the -/// ids the renderer draws them with: Random in a Transform effect takes its seed from the id. +/// ids the renderer draws them with: Random in a Transform effect takes its seed from the id. When +/// `m` clips, its clipping path, unless it is type, first takes the geometry effects in it as the +/// canvas clips by it ([`crate::clip::with_clip_effects_applied`]). fn bake_pieces(d: &mut Document, mut m: Node) -> Node { let mut seen = std::collections::HashSet::from([m.id]); + let clip = usize::from(m.clips() && !m.children().and_then(|ch| ch.first()).is_some_and(|c| matches!(c.kind, NodeKind::Text(_)))); let children = m.children().cloned().unwrap_or_default(); let children = children .into_iter() - .map(|c| { - let c = Arc::unwrap_or_clone(c); - let mut c = bake_node(d, &c).unwrap_or(c); + .enumerate() + .map(|(i, c)| { + let c = (i < clip).then(|| crate::clip::with_clip_effects_applied(&c)).flatten().unwrap_or_else(|| Arc::unwrap_or_clone(c)); + let mut c = one_deeper(|| bake_node(d, &c)).unwrap_or(c); fresh_ids(d, &mut c, &mut seen); Arc::new(c) }) @@ -713,8 +1002,60 @@ fn bake_appearance_pieces(doc: Option<&Document>, n: &mut Node, outline_strokes: /// resources of its placed documents' art added ([`Document::with_placed_art`]); `None` when /// there is nothing to do (export it as is). pub fn bake_document(doc: &Document) -> Option { + bake(doc, None) +} + +/// [`bake_document`], and every symbol instance whose symbol's art draws something baking changes +/// (live geometry effects, color adjustments and the rest [`needs_bake`] counts, in its own art or +/// in the art of the symbols it places) replaced by that art as the instance places it, baked +/// ([`placed_symbol_art`]), so the art draws as on the canvas wherever the instance is. For +/// exporters that write each instance's art in its place (PDF, print, EPS, DXF), rather than +/// writing each symbol once. `clip_slices`: whether 9-slice cells are clipped +/// ([`Document::place_symbol_art`]) or not ([`Document::place_symbol_art_unclipped`]), as the +/// exporter places other instances. `layers`: the hidden layers and layers that do not print +/// that the exporter writes. Instances the export does not write (hidden ones, those in hidden +/// objects, on template layers, and on the layers `layers` leaves out) stay as they are. The +/// symbols' own art is left as it is. +pub fn bake_document_placing_symbols(doc: &Document, clip_slices: bool, layers: WrittenLayers) -> Option { + bake(doc, Some((clip_slices, vectorcraft_doc::MAX_SYMBOL_NODES, layers))) +} + +/// Restores what [`bake`] changes in the thread's baking state when it ends. +struct Restore(Option>, u64, u64, usize, bool); + +impl Drop for Restore { + fn drop(&mut self) { + PLACING.with(|p| *p.borrow_mut() = self.0.take()); + PLACED_NODES.with(|c| c.set(self.1)); + DROPPED_NODES.with(|c| c.set(self.2)); + LEVEL.with(|c| c.set(self.3)); + UNWRITTEN.with(|c| c.set(self.4)); + } +} + +/// [`bake_document`], or with `placing` [`bake_document_placing_symbols`] with that `clip_slices`, +/// [`Placing::most_nodes`] and [`Placing::layers`]. +fn bake(doc: &Document, placing: Option<(bool, u64, WrittenLayers)>) -> Option { let placed = doc.with_placed_art(); - if !placed.layers.iter().any(|l| needs_bake(l)) { + let placing = placing + .map(|(clip_slices, most_nodes, layers)| (drawn_symbols(&placed), clip_slices, most_nodes, layers)) + .filter(|p| !p.0.is_empty()) + .map(|(symbols, clip_slices, most_nodes, layers)| Placing { + symbols, + clip_slices, + most_nodes, + heights: vectorcraft_doc::depth::DrawnHeights::of(&placed), + layers, + }); + // A bake inside another one (of art an effect makes) places symbols only when it asks to. + let _restore = Restore( + PLACING.with(|p| p.replace(placing.map(Rc::new))), + PLACED_NODES.with(|c| c.replace(0)), + DROPPED_NODES.with(|c| c.replace(0)), + LEVEL.with(|c| c.replace(1)), + UNWRITTEN.with(|c| c.replace(false)), + ); + if !placed.layers.iter().any(|l| needs_bake(l) || holds_placed_symbol(l)) { return match placed { std::borrow::Cow::Owned(d) => Some(d), std::borrow::Cow::Borrowed(_) => None, diff --git a/crates/effects/src/bake/tests.rs b/crates/effects/src/bake/tests.rs index d2ba694149..fba4f75e5f 100644 --- a/crates/effects/src/bake/tests.rs +++ b/crates/effects/src/bake/tests.rs @@ -2,7 +2,7 @@ use super::*; use serde_json::json; use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{CharStyle, Effect, NodeId, TextObject}; -use vectorcraft_geom::{Point, Rect, shapes}; +use vectorcraft_geom::{Point, Rect, Shape, shapes}; /// Type tests need glyph outlines, which only the optional craft-fonts build input provides. fn skip_without_craft_fonts() -> bool { @@ -813,6 +813,56 @@ fn type_in_a_clipping_group_with_a_fill_of_its_own_keeps_its_effect() { assert!(b.y0 > 330.0 && b.y1 < 370.0, "{b:?}"); } +#[test] +fn clipping_type_whose_fill_has_a_geometry_effect_clips_by_its_plain_outlines() { + if skip_without_craft_fonts() { + return; + } + let near = |a: Rect, b: Rect, tol: f64| [a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().all(|v| v.abs() < tol); + for stroke in [Paint::None, Paint::solid(Color::rgb(1.0, 0.0, 0.0))] { + // Type that clips a square, with a Transform effect on its own fill. + let mut t = type_node(60); + t.appearance = Appearance::basic(Paint::solid(Color::BLACK), stroke.clone(), 1.0).into(); + for item in &mut t.appearance.items { + if let AppearanceItem::Fill(f) = item { + f.effects.push(fx("distort.transform", json!({"moveH": 300}))); + } + } + let square = Node::path(NodeId(61), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default_art()); + let clip = Node::new(NodeId(62), NodeKind::Group { children: vec![Arc::new(t.clone()), Arc::new(square)], clip: true }); + let canvas = crate::clip_outline(&t).map(|(bp, _)| bp.bounding_box()).unwrap(); + assert!(canvas.x1 < 100.0, "the canvas clips by the plain outlines: {canvas:?}"); + let d = bake_document(&doc_with(clip)).unwrap(); + let baked = d.node(NodeId(62)).unwrap(); + // With a stroke, the clip group sits in a group with the stroke over it, outside the clip. + let group = match baked.kind { + NodeKind::Group { clip: true, .. } => { + assert!(stroke.is_none(), "{baked:?}"); + baked + } + _ => { + let ch = baked.children().unwrap(); + assert_eq!(ch.len(), 2, "{baked:?}"); + let strokes = ch[1].appearance.items.iter().all(|i| matches!(i, AppearanceItem::Stroke(_))); + assert!(matches!(ch[1].kind, NodeKind::Text(_)) && strokes, "the type with only its stroke: {:?}", ch[1]); + &ch[0] + } + }; + let ch = group.children().unwrap(); + assert!(matches!(group.kind, NodeKind::Group { clip: true, .. }) && ch.len() == 3, "{group:?}"); + // The export clips by the outlines the canvas clips by. + assert!(matches!(ch[0].kind, NodeKind::Path { clipping: true, .. }), "{:?}", ch[0]); + let b = crate::clip_outline(&ch[0]).map(|(bp, _)| bp.bounding_box()).unwrap(); + assert!(near(b, canvas, 1e-6), "canvas {canvas:?}, export {b:?}"); + // The fills (the characters' and the moved one) paint behind the square, inside the clip. + let fill = ch[1].geometric_bounds().unwrap(); + assert!((fill.x0 - canvas.x0).abs() < 1e-6 && fill.x1 > canvas.x1 + 250.0, "{fill:?}"); + assert_eq!(ch[2].id, NodeId(61)); + let mut ids = std::collections::HashSet::new(); + baked.walk(&mut |n| assert!(ids.insert(n.id), "duplicate id {}", n.id)); + } +} + #[test] fn type_with_its_own_transform_effect_copies_stays_type() { if skip_without_craft_fonts() { @@ -1065,3 +1115,413 @@ fn exporting_a_path_with_a_transform_gives_each_copy_its_own_gradient() { // Three squares of their own, not one path spanning all three. assert_eq!(gradient_pieces(d.node(NodeId(50)).unwrap()), vec![10.0; 3]); } + +/// A 10 × 10 square at (10, 40), with id `id`, that a Transform effect moves 100 pt right. +fn moved_square(id: u64) -> Node { + let mut n = Node::path(NodeId(id), shapes::rectangle(Rect::new(10.0, 40.0, 20.0, 50.0)), Appearance::default_art()); + n.appearance.effects.push(fx("distort.transform", json!({"moveH": 100.0}))); + n +} + +fn instance(id: u64, symbol: &str, xf: vectorcraft_geom::Affine) -> Node { + Node::new(NodeId(id), NodeKind::SymbolInstance { symbol: symbol.into(), xf }) +} + +fn add_symbol(d: &mut Document, name: &str, art: Node) { + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: name.into(), art: Arc::new(art) }); +} + +fn bounds(d: &Document, id: u64) -> Rect { + d.node(NodeId(id)).and_then(|n| n.geometric_bounds()).unwrap_or_else(|| panic!("node {id} has bounds")) +} + +fn near_rect(a: Rect, b: Rect) -> bool { + [(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(x, y)| (x - y).abs() < 1e-6) +} + +/// Each instance draws its symbol's art with the art's effects applied where the instance places +/// it: an instance that doubles the art's size moves it the effect's 100 pt, as the canvas draws +/// it, not 200 pt. Plain baking leaves the instances and the symbols' art as they are. +#[test] +fn placing_symbols_bakes_their_art_where_each_instance_places_it() { + use vectorcraft_geom::Affine; + let mut d = doc_with(instance(900, "S", Affine::IDENTITY)); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, instance(901, "S", Affine::translate((0.0, 100.0)) * Affine::scale(2.0))).unwrap(); + add_symbol(&mut d, "S", moved_square(800)); + assert!(bake_document(&d).is_none(), "nothing in the layers needs baking"); + let out = bake_document_placing_symbols(&d, true, ALL).unwrap(); + assert!(matches!(out.node(NodeId(900)).unwrap().kind, NodeKind::Group { .. })); + assert!(near_rect(bounds(&out, 900), Rect::new(110.0, 40.0, 120.0, 50.0)), "{:?}", bounds(&out, 900)); + assert!(near_rect(bounds(&out, 901), Rect::new(120.0, 180.0, 140.0, 200.0)), "{:?}", bounds(&out, 901)); + assert_eq!(out.symbols[0].art.appearance.effects.len(), 1, "the symbol's art keeps its effect"); +} + +/// An instance of a symbol whose art holds an instance of another symbol with effects draws that +/// art with its effects too. +#[test] +fn placing_symbols_reaches_the_art_of_nested_instances() { + use vectorcraft_geom::Affine; + let mut d = doc_with(instance(900, "Outer", Affine::IDENTITY)); + add_symbol(&mut d, "Inner", moved_square(800)); + add_symbol(&mut d, "Outer", Node::group(NodeId(801), vec![Arc::new(instance(802, "Inner", Affine::translate((0.0, 100.0))))])); + let out = bake_document_placing_symbols(&d, true, ALL).unwrap(); + assert!(near_rect(bounds(&out, 900), Rect::new(110.0, 140.0, 120.0, 150.0)), "{:?}", bounds(&out, 900)); +} + +/// A 10 pt square with id `id`, masked by `art` (the mask enabled unless `disabled`). +fn masked_square(id: u64, art: Node, disabled: bool) -> Node { + let mut n = Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()); + let mut mask = vectorcraft_doc::OpacityMask::new(art, false); + mask.disabled = disabled; + n.extras_mut().mask = Some(Box::new(mask)); + n +} + +/// Whether the art of `n`'s opacity mask is still a symbol instance, and its bounds when it is not. +fn mask_art(n: &Node) -> (bool, Option) { + let art = &n.extras().mask.as_ref().unwrap_or_else(|| panic!("node {:?} has a mask", n.id)).art; + (matches!(art.kind, NodeKind::SymbolInstance { .. }), art.geometric_bounds()) +} + +/// An instance in the art of an enabled opacity mask is placed and baked like any other, so the +/// mask masks with the art the instance draws, and the masked object stays as it is (a clipping +/// path stays one); one in a disabled mask, in the mask of an object the export leaves out, or in +/// a ruler guide's mask, stays as it is. +#[test] +fn placing_symbols_reaches_instances_in_opacity_masks() { + use vectorcraft_geom::Affine; + let mut d = doc_with(masked_square(700, instance(900, "S", Affine::IDENTITY), false)); + let layer = d.layers[0].id; + d.insert(Some(layer), 1, masked_square(701, instance(901, "S", Affine::IDENTITY), true)).unwrap(); + let mut hidden = masked_square(702, instance(902, "S", Affine::IDENTITY), false); + hidden.visible = false; + d.insert(Some(layer), 2, hidden).unwrap(); + let mut clipping = masked_square(703, instance(903, "S", Affine::IDENTITY), false); + if let NodeKind::Path { clipping: c, .. } = &mut clipping.kind { + *c = true; + } + d.insert(Some(layer), 3, Node::group(NodeId(704), vec![Arc::new(clipping)])).unwrap(); + let mut guide = Node::new(NodeId(705), NodeKind::RulerGuide { vertical: false, pos: 5.0, artboard: None }); + guide.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(instance(905, "S", Affine::IDENTITY), false))); + d.insert(Some(layer), 4, guide).unwrap(); + add_symbol(&mut d, "S", moved_square(800)); + let out = bake_document_placing_symbols(&d, true, ALL).unwrap(); + for id in [700, 703] { + let (still, b) = mask_art(out.node(NodeId(id)).unwrap()); + assert!(!still && b.is_some_and(|b| near_rect(b, Rect::new(110.0, 40.0, 120.0, 50.0))), "{id}: {b:?}"); + } + assert!(matches!(out.node(NodeId(703)).unwrap().kind, NodeKind::Path { clipping: true, .. }), "the clipping path stays one"); + assert!(mask_art(out.node(NodeId(701)).unwrap()).0, "a disabled mask's instance stays"); + assert!(mask_art(out.node(NodeId(702)).unwrap()).0, "a hidden object's mask's instance stays"); + assert!(mask_art(out.node(NodeId(705)).unwrap()).0, "a ruler guide's mask's instance stays"); +} + +/// A symbol whose art holds an instance only in an opacity mask's art is placed too, and the +/// instance in its mask is placed with it. +#[test] +fn placing_symbols_reaches_instances_in_the_masks_of_symbol_art() { + use vectorcraft_geom::Affine; + let mut d = doc_with(instance(900, "Outer", Affine::IDENTITY)); + add_symbol(&mut d, "Inner", moved_square(800)); + add_symbol(&mut d, "Outer", masked_square(803, instance(802, "Inner", Affine::IDENTITY), false)); + let out = bake_document_placing_symbols(&d, true, ALL).unwrap(); + assert!(!is_instance(&out, 900), "the outer instance is placed"); + let mut found = None; + out.node(NodeId(900)).unwrap().walk(&mut |n| { + if n.id == NodeId(803) { + found = Some(mask_art(n)); + } + }); + let (still, b) = found.unwrap_or_else(|| panic!("the masked square is in the placed art")); + assert!(!still && b.is_some_and(|b| near_rect(b, Rect::new(110.0, 40.0, 120.0, 50.0))), "{b:?}"); +} + +/// A symbol whose art holds an instance of itself is placed until the depth limit, and the export +/// ends. +#[test] +fn placing_a_symbol_that_holds_itself_stops() { + use vectorcraft_geom::Affine; + let mut d = doc_with(instance(900, "Loop", Affine::IDENTITY)); + add_symbol( + &mut d, + "Loop", + Node::group(NodeId(801), vec![Arc::new(moved_square(800)), Arc::new(instance(802, "Loop", Affine::translate((0.0, 1.0))))]), + ); + let out = bake_document_placing_symbols(&d, true, ALL).unwrap(); + let mut lefts = vec![]; + out.node(NodeId(900)).unwrap().walk(&mut |n| lefts.extend(n.path_data().and_then(|p| p.bounds()).map(|b| b.x0))); + assert!(lefts.len() > 1 && lefts.iter().all(|x| (x - 110.0).abs() < 1e-6), "{lefts:?}"); + let mut depth = 0; + let mut n = out.node(NodeId(900)).unwrap(); + while let Some(next) = n.children().and_then(|ch| ch.last()) { + n = next; + depth += 1; + } + assert!(depth <= 3 * (vectorcraft_doc::depth::MAX_DEPTH + 1), "{depth}"); +} + +/// A dynamic symbol instance's own paint for an object of the art applies before the object's +/// effects are baked: a fill whose own Transform effect makes the square a group of pieces still +/// paints in the instance's red, and its sibling keeps the symbol's paint. +#[test] +fn placing_symbols_keeps_dynamic_instances_changes() { + use vectorcraft_geom::Affine; + let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + let mut square = Node::path(NodeId(800), shapes::rectangle(Rect::new(10.0, 40.0, 20.0, 50.0)), Appearance::default_art()); + if let Some(AppearanceItem::Fill(f)) = square.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Fill(_))) { + f.effects.push(fx("distort.transform", json!({"moveH": 100.0}))); + } + let sibling = Node::path(NodeId(801), shapes::rectangle(Rect::new(10.0, 60.0, 20.0, 70.0)), Appearance::default_art()); + let mut inst = instance(900, "D", Affine::IDENTITY); + inst.extras_mut().symbol_overrides = vec![vectorcraft_doc::SymbolOverride { path: vec![0], fill: Some(red.clone()), ..Default::default() }]; + let mut d = doc_with(inst); + add_symbol(&mut d, "D", Node::group(NodeId(802), vec![Arc::new(square), Arc::new(sibling)])); + d.symbols[0].dynamic = true; + let out = bake_document_placing_symbols(&d, true, ALL).unwrap(); + let mut fills = vec![]; + out.node(NodeId(900)).unwrap().walk(&mut |n| { + if n.path_data().is_some() + && let Some(b) = n.geometric_bounds() + { + fills.push((b.x0.round(), b.y0.round(), n.appearance.fill_paint())); + } + }); + assert!(fills.contains(&(110.0, 40.0, red)), "{fills:?}"); + assert!(fills.contains(&(10.0, 60.0, Paint::solid(Color::WHITE))), "{fills:?}"); +} + +/// An instance whose fill stains its symbol's art places the art in its stained colors, with the +/// art's effects applied after the stain: a Transform moves the stained square and an Invert +/// inverts the stained color. +#[test] +fn placing_symbols_keeps_the_instances_stain() { + use vectorcraft_geom::Affine; + let blue = Color::rgb8(30, 90, 220); + let mut inst = instance(900, "Mark", Affine::IDENTITY); + inst.appearance = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0).into(); + inst.appearance.items.retain(|i| i.is_fill()); + if let AppearanceItem::Fill(f) = &mut inst.appearance.items[0] { + f.opacity = 0.5; + } + let square = + Node::path(NodeId(800), shapes::rectangle(Rect::new(10.0, 40.0, 20.0, 50.0)), Appearance::basic(Paint::solid(blue), Paint::None, 0.0)); + let stained = vectorcraft_doc::symbol_overrides::instance_art(&square, &inst).appearance.fill_paint().color().unwrap(); + assert_ne!(stained.to_hex(), blue.to_hex()); + let [r, g, b] = stained.to_rgb(); + let inverted = Color::rgb(1.0 - r, 1.0 - g, 1.0 - b); + for (id, params, want) in [("distort.transform", json!({"moveH": 100.0}), stained), (crate::addons::color::INVERT, json!({}), inverted)] { + let mut art = square.clone(); + art.appearance.effects.push(fx(id, params)); + let mut d = doc_with(inst.clone()); + add_symbol(&mut d, "Mark", art); + let out = bake_document_placing_symbols(&d, true, ALL).unwrap(); + assert!(!is_instance(&out, 900), "{id}: the instance is placed"); + let mut fills = vec![]; + out.node(NodeId(900)).unwrap().walk(&mut |n| { + if n.path_data().is_some() { + fills.extend(n.appearance.fill_paint().color().map(|c| c.to_hex())); + } + }); + assert_eq!(fills, [want.to_hex()], "{id}"); + } +} + +/// Every layer written, as DXF writes them (template layers are never written). +const ALL: WrittenLayers = WrittenLayers { hidden: true, non_printing: true }; + +fn is_instance(d: &Document, id: u64) -> bool { + d.node(NodeId(id)).is_some_and(|n| matches!(n.kind, NodeKind::SymbolInstance { .. })) +} + +/// The art placed for an export is counted as baked: the copies an effect makes count, so an +/// instance whose baked art passes what is left of the budget stays an instance, and the budget +/// holds the baked art of the instances placed, exactly. +#[test] +fn placing_symbols_counts_the_baked_art() { + use vectorcraft_geom::Affine; + let mut d = doc_with(instance(900, "S", Affine::IDENTITY)); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, instance(901, "S", Affine::translate((0.0, 100.0)))).unwrap(); + add_symbol(&mut d, "S", gradient_copies(800)); + let all = bake(&d, Some((true, u64::MAX, ALL))).unwrap(); + let each = all.node(NodeId(900)).map_or(0, |n| n.count_with_masks() as u64); + assert!(each > 2, "the instance's group, and the copies as objects of their own: {each}"); + assert_eq!(all.node(NodeId(901)).map(|n| n.count_with_masks() as u64), Some(each)); + let fits = bake(&d, Some((true, 2 * each, ALL))).unwrap(); + assert!(!is_instance(&fits, 900) && !is_instance(&fits, 901)); + let short = bake(&d, Some((true, 2 * each - 1, ALL))).unwrap(); + assert_eq!(usize::from(is_instance(&short, 900)) + usize::from(is_instance(&short, 901)), 1, "one instance stays as it is"); +} + +/// The baked art of an instance placed inside another's art is counted once: a budget of exactly +/// the outer instance's baked art places both. +#[test] +fn placing_symbols_counts_nested_art_once() { + use vectorcraft_geom::Affine; + let mut d = doc_with(instance(900, "Outer", Affine::IDENTITY)); + add_symbol(&mut d, "Inner", gradient_copies(800)); + add_symbol(&mut d, "Outer", Node::group(NodeId(801), vec![Arc::new(instance(802, "Inner", Affine::IDENTITY))])); + let all = bake(&d, Some((true, u64::MAX, ALL))).unwrap(); + let total = all.node(NodeId(900)).map_or(0, |n| n.count_with_masks() as u64); + let exact = bake(&d, Some((true, total, ALL))).unwrap(); + assert!(!is_instance(&exact, 900) && !is_instance(&exact, 802), "both are placed within {total}"); + let short = bake(&d, Some((true, total - 1, ALL))).unwrap(); + assert!(is_instance(&short, 900), "the outer instance stays as it is"); +} + +/// While an instance's art bakes, the art's own objects are held in the budget: an instance +/// nested in it whose art does not fit in what is left stays as it is, and the outer instance is +/// placed around it. +#[test] +fn placing_symbols_holds_the_outer_art_while_it_bakes() { + use vectorcraft_geom::Affine; + let mut d = doc_with(instance(900, "Outer", Affine::IDENTITY)); + add_symbol(&mut d, "Inner", Node::group(NodeId(803), vec![Arc::new(gradient_copies(800))])); + let mut art: Vec> = (0..5) + .map(|i| Arc::new(Node::path(NodeId(810 + i), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()))) + .collect(); + art.push(Arc::new(instance(802, "Inner", Affine::IDENTITY))); + let outer = Node::group(NodeId(801), art); + // The outer instance's group around its art, with the inner instance left as it is. + let around = 1 + outer.count_with_masks() as u64; + add_symbol(&mut d, "Outer", outer); + let all = bake(&d, Some((true, u64::MAX, ALL))).unwrap(); + let inner = all.node(NodeId(802)).map_or(0, |n| n.count_with_masks() as u64); + assert!(inner > 2 && inner <= around, "the inner art alone fits: {inner} <= {around}"); + let out = bake(&d, Some((true, around, ALL))).unwrap(); + assert!(!is_instance(&out, 900) && is_instance(&out, 802), "the outer instance is placed around the inner one"); +} + +/// Art baked for an instance and then left out, because it passes the budget, still counts: an +/// instance after it whose art would fit in the budget alone stays as it is, and a budget with +/// room for both places both. +#[test] +fn placing_symbols_counts_the_art_it_drops() { + use vectorcraft_geom::Affine; + let mut d = doc_with(instance(901, "Small", Affine::IDENTITY)); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, instance(900, "Big", Affine::IDENTITY)).unwrap(); + add_symbol(&mut d, "Big", gradient_copies(800)); + add_symbol(&mut d, "Small", moved_square(810)); + let all = bake(&d, Some((true, u64::MAX, ALL))).unwrap(); + let count = |id: u64| all.node(NodeId(id)).map_or(0, |n| n.count_with_masks() as u64); + let (big, small) = (count(900), count(901)); + assert!(small < big, "{small} < {big}"); + let short = bake(&d, Some((true, big - 1, ALL))).unwrap(); + assert!(is_instance(&short, 900), "the big art passes {}", big - 1); + assert!(is_instance(&short, 901), "the big art's {big} objects count, so the small art does not fit"); + let both = bake(&d, Some((true, big + small, ALL))).unwrap(); + assert!(!is_instance(&both, 900) && !is_instance(&both, 901)); +} + +/// Instances the export does not write are not placed and do not count against the budget: with +/// room for one instance's baked art, hidden instances, an instance in a hidden group, one on a +/// template layer, one on a layer that does not print and one on a hidden layer (when the export +/// leaves those layers out) come first and stay as they are, and the visible instance after them +/// is placed. An export that writes those layers places their instances first. +#[test] +fn placing_symbols_skips_instances_the_export_leaves_out() { + use vectorcraft_geom::Affine; + let mut d = doc_with(instance(900, "S", Affine::IDENTITY)); + add_symbol(&mut d, "S", gradient_copies(800)); + let each = bake(&d, Some((true, u64::MAX, ALL))).unwrap().node(NodeId(900)).map_or(0, |n| n.count_with_masks() as u64); + let layer = d.layers[0].id; + let mut hidden = instance(901, "S", Affine::IDENTITY); + hidden.visible = false; + let mut group = Node::group(NodeId(902), vec![Arc::new(instance(903, "S", Affine::IDENTITY))]); + group.visible = false; + for (i, n) in [hidden, group].into_iter().enumerate() { + d.insert(Some(layer), i, n).unwrap(); + } + let mut left_out = vec![]; + for (id, template, printable, visible) in [(910, true, true, true), (920, false, false, true), (930, false, true, false)] { + let mut l = Node::layer(NodeId(id), &format!("L{id}"), vectorcraft_doc::LayerColor::Preset(0)); + if let NodeKind::Layer { template: t, printable: p, .. } = &mut l.kind { + *t = template; + *p = printable; + } + l.visible = visible; + if let Some(ch) = l.children_mut() { + ch.push(Arc::new(instance(id + 1, "S", Affine::IDENTITY))); + } + left_out.push(Arc::new(l)); + } + d.layers.splice(0..0, left_out); + let out = bake(&d, Some((true, each, WrittenLayers::default()))).unwrap(); + assert!(!is_instance(&out, 900), "the visible instance is placed within {each}"); + for id in [901, 903, 911, 921, 931] { + assert!(is_instance(&out, id), "{id} stays as it is"); + } + // An export that writes the layers that do not print, or the hidden layers, places that + // layer's instance first; the template layer's instance is never placed. + for (layers, first) in [(WrittenLayers { non_printing: true, hidden: false }, 921), (WrittenLayers { non_printing: false, hidden: true }, 931)] { + let out = bake(&d, Some((true, each, layers))).unwrap(); + assert!(!is_instance(&out, first) && is_instance(&out, 900) && is_instance(&out, 911), "{layers:?}"); + } +} + +/// `leaf` in `levels` groups, with ids from `id` up. +fn in_groups(id: u64, levels: u64, leaf: Node) -> Node { + (0..levels).fold(leaf, |n, i| Node::group(NodeId(id + i), vec![Arc::new(n)])) +} + +/// Placed art is drawn no deeper than the document may draw: an instance whose art's effects add +/// a level past it stays an instance, and the instances around it are placed. +#[test] +fn placing_symbols_keeps_the_baked_art_within_the_drawn_depth() { + use vectorcraft_doc::depth::{DrawnHeights, MAX_DRAWN_DEPTH}; + use vectorcraft_geom::Affine; + // The instance on the layer is 2 deep; A to D each hold the next 31 objects down, and E's + // square is 2 deep in its art: 2 + 4 × 31 + 2 = MAX_DRAWN_DEPTH. + let mut d = doc_with(instance(900, "A", Affine::IDENTITY)); + for (i, (name, next)) in [("A", "B"), ("B", "C"), ("C", "D"), ("D", "E")].into_iter().enumerate() { + let base = 1000 * (i as u64 + 1); + add_symbol(&mut d, name, in_groups(base, 30, instance(base + 100, next, Affine::IDENTITY))); + } + add_symbol(&mut d, "E", in_groups(5000, 1, gradient_copies(5100))); + assert!(!d.too_deep(None)); + assert_eq!(DrawnHeights::of(&d).deepest(&d.layers[0], 1), MAX_DRAWN_DEPTH); + let out = bake_document_placing_symbols(&d, true, ALL).unwrap(); + // E's square becomes a group of copies, a level past the cap: E's instance stays. + assert!(is_instance(&out, 4100), "E's instance stays as it is"); + assert!(!is_instance(&out, 900) && !is_instance(&out, 3100), "A to D are placed"); + assert!(DrawnHeights::of(&out).deepest(&out.layers[0], 1) <= MAX_DRAWN_DEPTH); + // Without the chain above it, E's art is placed. + let mut shallow = doc_with(instance(900, "E", Affine::IDENTITY)); + add_symbol(&mut shallow, "E", in_groups(5000, 1, gradient_copies(5100))); + assert!(!is_instance(&bake_document_placing_symbols(&shallow, true, ALL).unwrap(), 900)); +} + +/// Art baked for an instance and then left out because it draws too deep still counts when the +/// baked art of a later instance is checked: that art fits before its effects add copies, but +/// not once they do. +#[test] +fn placing_symbols_counts_art_dropped_for_depth_against_later_baked_art() { + use vectorcraft_geom::Affine; + // The chain of placing_symbols_keeps_the_baked_art_within_the_drawn_depth, then F, whose + // square becomes a group of copies once baked. + let mut d = doc_with(instance(900, "A", Affine::IDENTITY)); + for (i, (name, next)) in [("A", "B"), ("B", "C"), ("C", "D"), ("D", "E")].into_iter().enumerate() { + let base = 1000 * (i as u64 + 1); + add_symbol(&mut d, name, in_groups(base, 30, instance(base + 100, next, Affine::IDENTITY))); + } + add_symbol(&mut d, "E", in_groups(5000, 1, gradient_copies(5100))); + add_symbol(&mut d, "F", gradient_copies(6000)); + let layer = d.layers[0].id; + d.insert(Some(layer), 1, instance(901, "F", Affine::IDENTITY)).unwrap(); + let all = bake(&d, Some((true, u64::MAX, ALL))).unwrap(); + assert!(is_instance(&all, 4100) && !is_instance(&all, 900) && !is_instance(&all, 901)); + let count = |d: &Document, id: u64| d.node(NodeId(id)).map_or(0, |n| n.count_with_masks() as u64); + let (a, f) = (count(&all, 900), count(&all, 901)); + // E's baked art, as placed where nothing above it draws deep. + let mut shallow = doc_with(instance(4100, "E", Affine::IDENTITY)); + add_symbol(&mut shallow, "E", in_groups(5000, 1, gradient_copies(5100))); + let e = count(&bake(&shallow, Some((true, u64::MAX, ALL))).unwrap(), 4100); + assert!(f > 2, "F's copies are objects of their own: {f}"); + let short = bake(&d, Some((true, a + e + f - 1, ALL))).unwrap(); + assert!(!is_instance(&short, 900) && is_instance(&short, 4100), "A to D are placed, E is not"); + assert!(is_instance(&short, 901), "E's dropped {e} objects count, so F's baked {f} do not fit"); + let room = bake(&d, Some((true, a + e + f, ALL))).unwrap(); + assert!(!is_instance(&room, 900) && !is_instance(&room, 901)); +} diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index 424beebe17..67677656e6 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -468,8 +468,8 @@ pub fn effect_catalog() -> Vec { "blur.radial", "Radial Blur…", BLUR, - "{amount: 1..100 (10; spin: an arc of `amount`°, zoom: the content scaled by up to about ±amount/2 %), method: \"spin\"|\"zoom\" (\"spin\"), quality: \"draft\"|\"good\"|\"best\" (\"good\"; 16, 64 or 256 samples)} blurs around the object's centre", - json!({"amount": 10.0, "method": "spin", "quality": "good"}), + "{amount: 1..100 (10; spin: an arc of `amount`°, zoom: the content scaled by up to about ±amount/2 %), method: \"spin\"|\"zoom\" (\"spin\"), quality: \"draft\"|\"good\"|\"best\" (\"good\"; 16, 64 or 256 samples), centerX: 0..1 (0.5; the Blur Center across the object's bounds, 0 their left edge), centerY: 0..1 (0.5; the Blur Center down the object's bounds, 0 their top edge)} blurs around the Blur Center, which moves and scales with the object. A centerX or centerY outside 0..1 is refused", + json!({"amount": 10.0, "method": "spin", "quality": "good", "centerX": 0.5, "centerY": 0.5}), ), r( "blur.smart", diff --git a/crates/effects/src/clip.rs b/crates/effects/src/clip.rs index 60cc3f2845..cd9d67fc43 100644 --- a/crates/effects/src/clip.rs +++ b/crates/effects/src/clip.rs @@ -12,10 +12,14 @@ use vectorcraft_geom::{BezPath, FillRule, PathData}; /// fills and strokes: the region is then the union of the paths they give, as an export bakes them. /// `None` when there is nothing to clip by (the clipped art is then hidden). pub fn clip_outline(clip: &Node) -> Option<(BezPath, FillRule)> { - match clip_effects_applied(clip, true) { - Some(m) => m.clip_outline(Some(&outline_text), &unite), - None => clip.clip_outline(Some(&outline_text), &unite), - } + reshaped_clip_outline(clip).unwrap_or_else(|| clip.clip_outline(Some(&outline_text), &unite)) +} + +/// [`clip_outline`] of a clipping path that a live geometry effect reshapes; `None` when nothing +/// `clip` clips by has a geometry effect of its own or on a fill or stroke. A hidden member of a +/// group or layer does not clip, so its effects are not counted. +pub fn reshaped_clip_outline(clip: &Node) -> Option> { + clip_effects_applied(clip, true, || true).map(|m| m.clip_outline(Some(&outline_text), &unite)) } /// `n`, the clipping path of a clip group, with the live geometry effects of everything it clips by @@ -31,14 +35,26 @@ pub fn clip_outline(clip: &Node) -> Option<(BezPath, FillRule)> { /// geometry effects of its own fills and strokes live instead. `None` when nothing in it has a /// geometry effect. Effects on the clip group or around it then reshape the result, after its own. pub(crate) fn with_clip_effects_applied(n: &Node) -> Option { - let paint = n.clip_paint(); - clip_effects_applied(n, paint.fill.is_none() && paint.stroke.is_none()) + with_clip_effects_applied_while(n, || true) } -/// [`with_clip_effects_applied`]; with `items` unset (a clipping path that paints, and the paths of -/// a compound path, which draw with the compound path's fills and strokes), the geometry effects of -/// `n`'s own fills and strokes are left out. -fn clip_effects_applied(n: &Node, items: bool) -> Option { +/// [`with_clip_effects_applied`] that calls `take` before it visits each member of a group, layer +/// or compound path in `n`, at every depth: once `take` returns `false`, that member and the +/// members after it are not visited. The members of a group or layer that are not visited stay as +/// they are, with their effects. A compound path with geometry effects of its own still becomes a +/// path of its reshaped geometry. In a clipping path that does not paint, one whose fills or +/// strokes have geometry effects still becomes a group of one path per fill and stroke. In both +/// cases the paths in it that are not visited go +/// into that geometry as they are, and their own effects are not applied. +pub(crate) fn with_clip_effects_applied_while(n: &Node, take: fn() -> bool) -> Option { + let paint = n.clip_paint(); + clip_effects_applied(n, paint.fill.is_none() && paint.stroke.is_none(), take) +} + +/// [`with_clip_effects_applied_while`]; with `items` unset (a clipping path that paints, and the +/// paths of a compound path, which draw with the compound path's fills and strokes), the geometry +/// effects of `n`'s own fills and strokes are left out. +fn clip_effects_applied(n: &Node, items: bool, take: fn() -> bool) -> Option { let mut m: Option = None; let members: &[std::sync::Arc] = match &n.kind { NodeKind::Group { children, clip: true } => children.get(..1).unwrap_or_default(), @@ -53,7 +69,10 @@ fn clip_effects_applied(n: &Node, items: bool) -> Option { // The paths of a compound path draw with the compound path's fills and strokes, and stay paths. let compound = matches!(n.kind, NodeKind::Compound { .. }); for (i, c) in members.iter().enumerate().skip(skip).filter(|(_, c)| all || c.visible) { - if let Some(r) = clip_effects_applied(c, items && !compound) + if !take() { + break; + } + if let Some(r) = clip_effects_applied(c, items && !compound, take) && let Some(slot) = m.get_or_insert_with(|| n.clone()).children_mut().and_then(|ch| ch.get_mut(i)) { *slot = std::sync::Arc::new(r); diff --git a/crates/effects/src/group.rs b/crates/effects/src/group.rs index 0db50ef925..1b64971a3a 100644 --- a/crates/effects/src/group.rs +++ b/crates/effects/src/group.rs @@ -741,35 +741,93 @@ fn item_art(id: NodeId, item: &AppearanceItem, shapes: &[(PathData, FillRule)], Some(g) } -/// Whether a sublayer among the members of `n`, or among its groups' members, holds a ruler guide. -fn sublayer_guides(n: &Node) -> bool { - n.children().is_some_and(|ch| ch.iter().any(|c| c.holds_ruler_guides() || (!c.is_layer() && sublayer_guides(c)))) +/// The members of a container that [`take_held_guides`] visits, by index, each with the same for +/// its own members. A ruler guide's entry is empty; a container's is not. +#[derive(Default)] +struct HeldGuides(Vec<(usize, HeldGuides)>); + +/// The members of `n` holding or leading to the ruler guides of sublayers, found by looking at each +/// member at every depth once: the ruler guides (`is_guide`) of `n` when it is a layer, each +/// sublayer holding one directly or in its sublayers, and each member of another kind with such a +/// sublayer among its members or its groups' members. With them, whether `n` is a layer holding a +/// ruler guide directly or in its sublayers. The other members of a layer holding none are not +/// looked into, unless the layer is the one whose sublayers are gathered (`top`). +fn held_guides(n: &Node, top: bool, is_guide: &impl Fn(&Node) -> bool) -> (bool, HeldGuides) { + let layer = n.is_layer(); + let (mut holds, mut held, mut other) = (false, vec![], vec![]); + for (i, c) in n.children().into_iter().flatten().enumerate() { + if is_guide(c) { + if layer { + holds = true; + held.push((i, HeldGuides::default())); + } + } else if c.is_layer() { + let (sub_holds, inner) = held_guides(c, false, is_guide); + if sub_holds { + holds = true; + held.push((i, inner)); + } + } else { + other.push((i, c)); + } + } + if !layer || holds || top { + for (i, c) in other { + let (_, inner) = held_guides(c, false, is_guide); + if !inner.0.is_empty() { + held.push((i, inner)); + } + } + held.sort_unstable_by_key(|(i, _)| *i); + } + (layer && holds, HeldGuides(held)) +} + +/// Move the ruler guides of `n` and of its members that [`held_guides`] found (`held`) to `out`: +/// those of `n` first, in order, then those of each member in turn. A guide taken from a hidden or +/// locked container, or from one inside such a container, is hidden or locked itself. Only the +/// containers in `held` are copied, and only those are visited. +fn take_held_guides(n: &mut Node, held: HeldGuides, out: &mut Vec>, hidden: bool, locked: bool) { + let Some(ch) = n.children_mut() else { return }; + let (mut own, mut deeper) = (vec![], vec![]); + for (i, inner) in held.0 { + if inner.0.is_empty() { + own.push(i); + continue; + } + let Some(c) = ch.get_mut(i) else { continue }; + let c = Arc::make_mut(c); + let (hidden, locked) = (hidden || !c.visible, locked || c.locked); + take_held_guides(c, inner, &mut deeper, hidden, locked); + } + if !own.is_empty() { + let mut own = own.into_iter().peekable(); + for (i, mut c) in std::mem::take(ch).into_iter().enumerate() { + if own.next_if_eq(&i).is_none() { + ch.push(c); + continue; + } + if hidden || locked { + let g = Arc::make_mut(&mut c); + g.visible &= !hidden; + g.locked |= locked; + } + out.push(c); + } + } + out.append(&mut deeper); } /// Move the ruler guides of the sublayers among the members of `n`, and among its groups' -/// members, to `out`, in order. A guide taken from a hidden or locked sublayer, or from one inside -/// such a sublayer or group, is hidden or locked itself. Only containers holding one are copied. -fn take_sublayer_guides(n: &mut Node, out: &mut Vec>, hidden: bool, locked: bool) { - let Some(ch) = n.children_mut() else { return }; - for c in ch.iter_mut().filter(|c| c.holds_ruler_guides() || (!c.is_layer() && sublayer_guides(c))) { - let c = Arc::make_mut(c); - let (hidden, locked) = (hidden || !c.visible, locked || c.locked); - if c.is_layer() - && let Some(lc) = c.children_mut() - { - let (taken, art): (Vec<_>, Vec<_>) = std::mem::take(lc).into_iter().partition(|g| g.is_ruler_guide()); - *lc = art; - out.extend(taken.into_iter().map(|mut g| { - if hidden || locked { - let g = Arc::make_mut(&mut g); - g.visible &= !hidden; - g.locked |= locked; - } - g - })); - } - take_sublayer_guides(c, out, hidden, locked); - } +/// members, to `out`, in order: a sublayer's own guides, then those of its members. A guide taken +/// from a hidden or locked sublayer, or from one inside such a sublayer or group, is hidden or +/// locked itself. Each member at every depth is looked at once at most (`is_guide`), and only +/// containers holding one are copied. +fn take_sublayer_guides(n: &mut Node, out: &mut Vec>, is_guide: &impl Fn(&Node) -> bool) { + let (_, mut held) = held_guides(n, true, is_guide); + // The ruler guides of `n` itself stay where they are. + held.0.retain(|(_, inner)| !inner.0.is_empty()); + take_held_guides(n, held, out, false, false); } /// `n`, a group or layer, as plain art: its Pathfinder effects evaluated, its geometry effects @@ -797,7 +855,7 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option { // So do its sublayers' guides, which would otherwise go with the art the effects replace or // copy: they stay on this layer, hidden and locked as their sublayers were. if m.is_layer() && (pathfinder || !fx.is_empty()) { - take_sublayer_guides(&mut m, &mut guides, false, false); + take_sublayer_guides(&mut m, &mut guides, &Node::is_ruler_guide); } if pathfinder { let hook = |c: &Node| crate::outline_object(doc, c); @@ -846,7 +904,10 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option { /// depth of its groups and layers, by the art it draws ([`evaluate_container`], /// [`crate::reshape::own_effects_art`]), so the geometry effects of `n` reshape what its members /// draw. A clip group's clipping path only takes the geometry effects in it into its geometry -/// ([`crate::clip::with_clip_effects_applied`]). Images, symbol instances and the other objects +/// ([`crate::clip::with_clip_effects_applied_while`]), and the members of a clipping group or +/// compound path count toward the limit below. A group or layer in a clipping path that has +/// geometry effects of its own is walked twice, once for its members' effects and once for its +/// own, and its members count each time. Images, symbol instances and the other objects /// that `own_effects_art` leaves alone stay as they are, and so does a group or layer with a 3D /// effect with everything in it. Calls nested in one another, through the /// groups and layers it walks and the art it evaluates (symbol art and Pathfinder members @@ -859,7 +920,7 @@ pub(crate) fn members_as_drawn(doc: Option<&Document>, n: &mut Node) { // The clipping path's own geometry effects shape it before the effects around it do. if clip == 1 && let Some(first) = ch.first_mut() - && let Some(applied) = crate::clip::with_clip_effects_applied(first) + && let Some(applied) = crate::clip::with_clip_effects_applied_while(first, DrawnFrame::take_member) { *first = Arc::new(applied); } diff --git a/crates/effects/src/group/tests.rs b/crates/effects/src/group/tests.rs index 947bf262f5..519323e5f0 100644 --- a/crates/effects/src/group/tests.rs +++ b/crates/effects/src/group/tests.rs @@ -849,6 +849,53 @@ fn nested_groups_with_effects_count_toward_the_depth_limit() { assert!(deepest.is_some_and(|d| crate::reshape::geometry_effects(&d).len() == 1), "the deepest member keeps its effect"); } +/// The members of a clipping path count toward the member limit: with room for two more members, +/// the third member of a clipping group keeps its own effect as it is. +#[test] +fn clipping_path_members_past_the_member_limit_stay_as_they_are() { + let member = |id: u64| { + let mut m = with_effect(square_at_100(), offset_10()); + m.id = NodeId(id); + Arc::new(m) + }; + let clipping = Node::group(NodeId(20), vec![member(2), member(3), member(4)]); + let mut clipped = Node::new(NodeId(5), NodeKind::Group { children: vec![Arc::new(clipping), Arc::new(square_at_100())], clip: true }); + // An enclosing call that has visited all the members it may but two. + let _outer = DrawnFrame::enter().unwrap(); + DRAWN.with(|d| d.set((1, crate::SYMBOL_ART_MAX_NODES - 2))); + members_as_drawn(None, &mut clipped); + let clipping = clipped.children().unwrap()[0].clone(); + let effects: Vec = clipping.children().unwrap().iter().map(|m| crate::reshape::geometry_effects(m).len()).collect(); + assert_eq!(effects, [0, 0, 1], "the first two members take their Offset Path, the third keeps it"); + let widths: Vec = clipping.children().unwrap().iter().map(|m| m.geometric_bounds().unwrap().width()).collect(); + assert!((widths[0] - 120.0).abs() < 0.5 && (widths[1] - 120.0).abs() < 0.5 && (widths[2] - 100.0).abs() < 0.5, "{widths:?}"); +} + +/// A compound clipping path with an effect of its own takes that effect when the member limit is +/// reached among its paths: with room for one more member, the first path (at 100 to 200) takes +/// its Offset Path, the second (at 300 to 400) goes in as it is, and the compound path's Offset +/// Path reshapes both, to 80 to 220 and 290 to 410. +#[test] +fn a_compound_clipping_path_takes_its_own_effect_at_the_member_limit() { + let member = |id: u64, x: f64| { + let path = Node::path(NodeId(id), shapes::rectangle(Rect::new(x, 100.0, x + 100.0, 200.0)), black()); + Arc::new(with_effect(path, offset_10())) + }; + let kind = NodeKind::Compound { children: vec![member(2, 100.0), member(3, 300.0)], rule: FillRule::NonZero }; + let clipping = with_effect(Node::new(NodeId(20), kind), offset_10()); + let mut clipped = Node::new(NodeId(5), NodeKind::Group { children: vec![Arc::new(clipping), Arc::new(square_at_100())], clip: true }); + // An enclosing call that has visited all the members it may but one. + let _outer = DrawnFrame::enter().unwrap(); + DRAWN.with(|d| d.set((1, crate::SYMBOL_ART_MAX_NODES - 1))); + members_as_drawn(None, &mut clipped); + let clipping = clipped.children().unwrap()[0].clone(); + assert!(crate::reshape::geometry_effects(&clipping).is_empty(), "the compound path's Offset Path is in its geometry"); + let subpaths = clipping.path_data().unwrap().subpaths.clone(); + let bounds: Vec<(f64, f64)> = subpaths.into_iter().map(|sp| PathData::single(sp).bounds().unwrap()).map(|b| (b.x0, b.x1)).collect(); + let near = |(a, b): (f64, f64), (x0, x1): (f64, f64)| (a - x0).abs() < 0.5 && (b - x1).abs() < 0.5; + assert!(bounds.len() == 2 && near(bounds[0], (80.0, 220.0)) && near(bounds[1], (290.0, 410.0)), "{bounds:?}"); +} + /// An image or a symbol instance that a group's Transform effect moves takes the placed gradients /// of its own fills along, as a path does, and each copy takes them as many times as it takes the /// transform. @@ -1760,6 +1807,91 @@ fn a_sublayers_ruler_guide_in_a_hidden_or_locked_group_stays_hidden_or_locked() } } +/// Gathering the ruler guides of nested sublayers, and of a sublayer inside nested groups, looks +/// at each member at every depth once at most, and takes the same guides, in the same order and +/// state, as a layer's effects keep. +#[test] +fn gathering_sublayer_ruler_guides_looks_at_each_member_once() { + use std::cell::Cell; + use vectorcraft_doc::LayerColor; + const CHAIN: u64 = 6; + let guide = |id| Arc::new(Node::new(NodeId(id), NodeKind::RulerGuide { vertical: true, pos: id as f64, artboard: None })); + let layer = |id, children: Vec>| { + let mut l = Node::layer(NodeId(id), "Sub", LayerColor::Preset(1)); + if let Some(ch) = l.children_mut() { + *ch = children; + } + l + }; + // Sublayers nested CHAIN deep, each holding the next before its own art and guide. The second + // is hidden and the fourth locked. + let first_guide = guide(201); + let mut chain = layer(100 + CHAIN, vec![sq(300 + CHAIN, 0.0, Color::BLACK), guide(200 + CHAIN)]); + for depth in (1..CHAIN).rev() { + let own = if depth == 1 { first_guide.clone() } else { guide(200 + depth) }; + chain = layer(100 + depth, vec![Arc::new(chain), sq(300 + depth, 0.0, Color::BLACK), own]); + (chain.visible, chain.locked) = (depth != 2, depth == 4); + } + let second_guide = chain.children().and_then(|c| c[0].children()).map(|c| c[2].clone()).unwrap(); + // A sublayer inside five nested groups, the third of them locked. + let mut groups = layer(450, vec![guide(250), sq(350, 0.0, Color::BLACK)]); + for depth in (1..=5).rev() { + groups = Node::group(NodeId(400 + depth), vec![Arc::new(groups)]); + groups.locked = depth == 3; + } + let free = Arc::new(Node::group(NodeId(500), vec![sq(501, 0.0, Color::BLACK), sq(502, 5.0, Color::BLACK)])); + // A sublayer with no guide: the art in its group is not looked at. + let quiet = Node::group(NodeId(601), vec![sq(602, 0.0, Color::BLACK), sq(603, 5.0, Color::BLACK)]); + let quiet = Arc::new(layer(600, vec![Arc::new(quiet)])); + let mut root = layer(10, vec![sq(1, 0.0, Color::rgb(1.0, 0.0, 0.0)), Arc::new(chain), Arc::new(groups), free.clone(), quiet.clone(), guide(20)]); + fn members(n: &Node) -> usize { + n.children().into_iter().flatten().map(|c| 1 + members(c)).sum() + } + let expected: Vec<_> = (1..=CHAIN).map(|depth| (NodeId(200 + depth), depth < 2, depth >= 4)).chain([(NodeId(250), true, true)]).collect(); + let state = |g: &[Arc]| g.iter().map(|g| (g.id, g.visible, g.locked)).collect::>(); + + let mut m = root.clone(); + let looked = Cell::new(0_usize); + let is_guide = |n: &Node| { + looked.set(looked.get() + 1); + n.is_ruler_guide() + }; + let mut taken = vec![]; + take_sublayer_guides(&mut m, &mut taken, &is_guide); + assert_eq!(looked.get(), members(&root) - 2, "each member is looked at once, none in the quiet sublayer's group"); + assert_eq!(state(&taken), expected, "a sublayer's own guides, then its sublayers', each once"); + assert!(Arc::ptr_eq(&taken[0], &first_guide), "a guide with nothing to change is not copied"); + assert!(!Arc::ptr_eq(&taken[1], &second_guide), "a guide made hidden is copied"); + assert!(second_guide.visible, "the guide as it was stays as it was"); + let ch = m.children().unwrap(); + assert!(Arc::ptr_eq(&ch[3], &free), "a member with no sublayer guide is not copied"); + assert!(Arc::ptr_eq(&ch[4], &quiet), "a sublayer with no guide is not copied"); + assert!(ch[5].is_ruler_guide(), "the layer's own guide stays where it is"); + let ids = |n: &Node| n.children().into_iter().flatten().map(|c| c.id).collect::>(); + assert_eq!(ids(&ch[1]), [NodeId(102), NodeId(301)], "the sublayer's art stays, in order"); + assert_eq!(ids(&root.children().unwrap()[1]), [NodeId(102), NodeId(301), NodeId(201)], "the source keeps its guides"); + + fn found(n: &Node, out: &mut Vec) { + for c in n.children().into_iter().flatten() { + if c.is_ruler_guide() { + out.push(c.id); + } + found(c, out); + } + } + for (effect, params) in [("pathfinder.add", serde_json::json!({})), ("distort.transform", serde_json::json!({"moveH": 30, "copies": 2}))] { + root.appearance.effects = vec![Effect { id: effect.into(), params, visible: true }]; + let art = evaluate_container(None, &root).unwrap(); + let ch = art.children().unwrap(); + let tail = &ch[ch.len() - expected.len() - 1..]; + assert_eq!(tail[0].id, NodeId(20), "{effect}: the layer's own guide comes first"); + assert_eq!(state(&tail[1..]), expected, "{effect}: then the sublayers' guides"); + let mut all = vec![]; + found(&art, &mut all); + assert_eq!(all.len(), expected.len() + 1, "{effect}: each guide once"); + } +} + /// A group's own Fill + Offset Path below its contents follows the outline of a clip group among /// its members, its clipping path, not the clipped art it hides outside that path (#7289). #[test] diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index c18a31d842..a326c85cf2 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -68,8 +68,11 @@ pub use adjust::{ ADJUSTMENTS, CHANNELS, ColorMap, ImageHook, adjust, adjust_in_document, color_map, curve_at, curve_points, has_adjustment, is_adjustment, is_channel, }; -pub use bake::{StrokeArt, bake_appearance, bake_document, bake_type_appearance, expand_art, expand_leaf, fresh_ids, needs_bake}; -pub use clip::{WarpSeams, clip_outline, knockout_silhouette, warp_pieces_translucent}; +pub use bake::{ + StrokeArt, WrittenLayers, bake_appearance, bake_document, bake_document_placing_symbols, bake_type_appearance, expand_art, expand_leaf, + fresh_ids, needs_bake, +}; +pub use clip::{WarpSeams, clip_outline, knockout_silhouette, reshaped_clip_outline, warp_pieces_translucent}; pub use group::{ OutlineHook, PATHFINDER_EFFECTS, compound_shape_area, compound_shape_art, evaluate_container, has_container_appearance, has_pathfinder, is_pathfinder, member_leaves, member_shapes, paints, pathfinder_children, shape_art, @@ -81,8 +84,8 @@ pub use pixel::{PIXEL_EFFECTS, PixelFx, PixelSpace}; pub use raster::{RASTERIZE, RasterFx, Rasterize, color_param, follow_items, item_effects_in, outset, raster_effects, without_geometry}; pub use reshape::{ SYMBOL_ART_MAX_NODES, expand_outlined, follows_image_pixels, gives_image_shape, has_gradient_copies, has_instance_row_raster, has_item_geometry, - has_painted_effects, has_transform_art, has_transform_copies, has_transform_options, image_paint, needs_outline, outline_art, outline_text, - reshape, + has_painted_effects, has_transform_art, has_transform_copies, has_transform_options, image_paint, needs_outline, outer_effects, outline_art, + outline_text, paint_type_piece, reshape, }; pub use revolve::{ CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in, diff --git a/crates/effects/src/lighting.rs b/crates/effects/src/lighting.rs index 8592776a95..257576822a 100644 --- a/crates/effects/src/lighting.rs +++ b/crates/effects/src/lighting.rs @@ -136,8 +136,86 @@ pub(crate) fn facet_art( composed_art(id, path, paint, Ramp::Rgb(light), seam) } -/// Composite smooth solid-fill facets with one clip and three channel groups per surface. -/// Black channel backdrops keep shared edges opaque before the final coverage is applied. +/// The width of the seam stroke of a facet's underlay: a round stroke that reaches 1 pt past each +/// edge, over the pixels that the antialiased edges of two neighboring facets each cover only in +/// part at 1:1. A clip to the surface's outline removes what it paints past the surface. +pub(crate) const UNDERLAY_SEAM: f64 = 2.0; + +/// The area facet `path` and its round seam stroke `seam` wide paint together: the stroke's outer +/// contours and the facet, all wound one way with a positive area. The stroke's inner contours, +/// wound the other way, are left out: the facet covers them, and contours that cancel each other +/// leave partial coverage where a union of footprints meets at a pixel. +pub(crate) fn footprint(path: &vectorcraft_geom::BezPath, seam: f64) -> vectorcraft_geom::BezPath { + use kurbo::{PathEl, Shape}; + let stroke = kurbo::stroke(path.iter(), &kurbo::Stroke::new(seam).with_join(kurbo::Join::Round), &kurbo::StrokeOpts::default(), 0.05); + let sign = if stroke.area() < 0.0 { -1.0 } else { 1.0 }; + let mut footprint = vectorcraft_geom::BezPath::new(); + let mut contour = vectorcraft_geom::BezPath::new(); + for el in stroke.elements().iter().chain(std::iter::once(&PathEl::MoveTo(kurbo::Point::ZERO))) { + if matches!(el, PathEl::MoveTo(_)) && !contour.elements().is_empty() { + if contour.area() * sign >= 0.0 { + footprint.extend(contour.iter()); + } + contour = vectorcraft_geom::BezPath::new(); + } + contour.push(*el); + } + let mut boundary = path.clone(); + if boundary.area() * sign < 0.0 { + boundary = boundary.reverse_subpaths(); + } + footprint.extend(boundary.iter()); + if sign < 0.0 { footprint.reverse_subpaths() } else { footprint } +} + +/// Colored-light facets `faces` (in drawing order) drawn over an underlay of themselves, the same +/// facets grown to seams [`UNDERLAY_SEAM`] wide, all clipped once to the union of the facets' +/// footprints. Where two facets' antialiased edges meet, the underlay fills what they leave +/// uncovered with the neighbors' own colors, so the background does not show through. `None` unless +/// every face is a facet a surface draws: a path filled and stroked by its seam, or a facet composed +/// in a clip of its footprint, neither with an opacity mask. +pub(crate) fn sealed(id: vectorcraft_doc::NodeId, faces: &[std::sync::Arc]) -> Option { + use std::sync::Arc; + use vectorcraft_doc::{Appearance, Node, NodeKind}; + let mut outline = vectorcraft_geom::BezPath::new(); + let mut underlay = Vec::with_capacity(faces.len()); + for face in faces { + if face.extras().mask.is_some() { + return None; + } + match &face.kind { + NodeKind::Path { clipping: false, .. } => { + let path = face.path_data()?.to_bezpath(); + let mut seam = None; + let mut grown = (**face).clone(); + for item in &mut grown.appearance.items { + if let AppearanceItem::Stroke(s) = item { + seam = Some(seam.map_or(s.width, |w: f64| w.max(s.width))); + s.width = UNDERLAY_SEAM; + } + } + outline.extend(footprint(&path, seam?).iter()); + underlay.push(Arc::new(grown)); + } + NodeKind::Group { children, clip: true } if children.len() == 2 => { + let clip = children.first()?.path_data()?.to_bezpath(); + let wider = Node::path(id, vectorcraft_geom::PathData::from_bezpath(&footprint(&clip, UNDERLAY_SEAM)), Appearance::default()); + let colors = children.get(1)?.clone(); + outline.extend(clip.iter()); + underlay.push(Arc::new(Node::new(id, NodeKind::Group { children: vec![Arc::new(wider), colors], clip: true }))); + } + _ => return None, + } + } + let clip = Node::path(id, vectorcraft_geom::PathData::from_bezpath(&outline), Appearance::default()); + underlay.extend(faces.iter().cloned()); + Some(Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(Node::group(id, underlay))], clip: true })) +} + +/// Composite smooth solid-fill facets with one clip and three channel groups per surface. In each +/// channel, an underlay of the facets with wide seams lies under the facets themselves, so a +/// shared edge is opaque in that channel's own light before the channels are screened together; +/// the black backdrop shows only outside the surface, which the clip removes. pub(crate) fn solid_surface(id: vectorcraft_doc::NodeId, facets: &[vectorcraft_three_d::Facet], paint: &Paint) -> vectorcraft_doc::Node { use kurbo::Shape; use std::sync::Arc; @@ -167,20 +245,36 @@ pub(crate) fn solid_surface(id: vectorcraft_doc::NodeId, facets: &[vectorcraft_t if let Some(value) = color.get_mut(channel) { *value = 1.0; } + let paints: Vec = facets + .iter() + .map(|face| { + if let Some(ramp) = face.rgb_gradient { + smooth_paint(vectorcraft_three_d::LightGradient { diffuse: ramp.channels[channel], ambient: 0.0, color }, Color::WHITE) + } else { + Paint::solid(shade(Color::WHITE, color.map(|c| c * face.illumination[channel]))) + } + }) + .collect(); + let draw = |seam: fn(&vectorcraft_three_d::Facet) -> f64| -> Vec> { + facets + .iter() + .zip(&paints) + .map(|(face, paint)| { + let edge = seam_stroke(paint.clone(), seam(face)); + Arc::new(Node::path( + id, + face.path(), + Appearance { + items: vec![AppearanceItem::Fill(FillLayer::new(paint.clone())), AppearanceItem::Stroke(edge)], + ..Default::default() + }, + )) + }) + .collect() + }; let mut children = vec![Arc::new(cover(Paint::solid(Color::BLACK)))]; - children.extend(facets.iter().map(|face| { - let paint = if let Some(ramp) = face.rgb_gradient { - smooth_paint(vectorcraft_three_d::LightGradient { diffuse: ramp.channels[channel], ambient: 0.0, color }, Color::WHITE) - } else { - Paint::solid(shade(Color::WHITE, color.map(|c| c * face.illumination[channel]))) - }; - let edge = seam_stroke(paint.clone(), (face.thickness() / 2.0).clamp(0.05, 0.75)); - Arc::new(Node::path( - id, - face.path(), - Appearance { items: vec![AppearanceItem::Fill(FillLayer::new(paint)), AppearanceItem::Stroke(edge)], ..Default::default() }, - )) - })); + children.extend(draw(|_| UNDERLAY_SEAM)); + children.extend(draw(|face| (face.thickness() / 2.0).clamp(0.05, 0.75))); let mut group = Node::group(id, children); group.isolate = true; group.blend = BlendMode::Screen; @@ -228,24 +322,25 @@ pub(crate) fn opaque_paint(paint: &Paint) -> (Paint, Option) { } fn composed_art(id: vectorcraft_doc::NodeId, path: &vectorcraft_geom::PathData, paint: &Paint, light: Ramp, seam: f64) -> vectorcraft_doc::Node { - use kurbo::Shape; use std::sync::Arc; use vectorcraft_doc::color::BlendMode; use vectorcraft_doc::{Appearance, Node, NodeKind, OpacityMask}; use vectorcraft_geom::{Rect, shapes}; - let (base, mask) = opaque_paint(paint); - // Clip once to the union of this single-contour face and its round seam stroke. - // Align their winding so the nonzero fill adds coverage instead of cancelling it. - let mut boundary = path.to_bezpath(); - let mut footprint = kurbo::stroke(boundary.iter(), &kurbo::Stroke::new(seam).with_join(kurbo::Join::Round), &kurbo::StrokeOpts::default(), 0.05); - if boundary.area() * footprint.area() < 0.0 { - boundary = boundary.reverse_subpaths(); + // An unplaced gradient (and a freeform gradient without points) stays fitted to the face's + // bounds grown by 1 pt, not to the larger cover below. + let mut paint = paint.clone(); + if let Paint::Gradient(g) = &mut paint { + g.pin(path.bounds().unwrap_or(Rect::ZERO).inflate(1.0, 1.0)); } - footprint.extend(boundary.iter()); - let clip = Node::path(id, vectorcraft_geom::PathData::from_bezpath(&footprint), Appearance::default()); + let (base, mask) = opaque_paint(&paint); + // Clip once to the union of this single-contour face and its round seam stroke. + let clip = Node::path(id, vectorcraft_geom::PathData::from_bezpath(&footprint(&path.to_bezpath(), seam)), Appearance::default()); // Opaque rectangles cover the complete seam stroke, without separately antialiasing - // either ramp. Opaque sources need only vector clipping, not full-frame opacity masks. - let bounds = path.bounds().unwrap_or(Rect::ZERO).inflate(1.0, 1.0); + // either ramp. Opaque sources need only vector clipping, not full-frame opacity masks. They + // reach at least half a point past the seam stroke grown for an underlay ([`sealed`]), so + // their own edges stay outside either clip. + let margin = seam.max(1.0) + UNDERLAY_SEAM / 2.0; + let bounds = path.bounds().unwrap_or(Rect::ZERO).inflate(margin, margin); let cover = |paint| Node::path(id, shapes::rectangle(bounds), Appearance::basic(paint, Paint::None, 0.0)); let mut illumination = match light { Ramp::Single(light) => cover(smooth_paint(light, Color::WHITE)), @@ -380,4 +475,30 @@ mod tests { assert_eq!(point.color.to_rgb(), [1.0, 0.25, 0.25]); assert_eq!(shaded.swatch, None, "a changed freeform point detaches the gradient swatch"); } + + /// Under colored light, a face's unplaced source gradient is fitted to the face's bounds grown by + /// 1 pt, whatever the size of the cover rectangle that draws it; a placed one keeps its placement. + #[test] + fn composed_faces_fit_unplaced_gradients_to_the_face_not_the_cover() { + use vectorcraft_doc::NodeKind; + use vectorcraft_geom::{Rect, shapes}; + use vectorcraft_three_d::{RgbGradient, ShadeGradient}; + let face = shapes::rectangle(Rect::new(10.0, 20.0, 50.0, 40.0)); + let ramp = |b| ShadeGradient { start: Point::new(10.0, 20.0), end: Point::new(50.0, 20.0), brightness: [b, 1.0] }; + let light = RgbGradient { channels: [ramp(0.2), ramp(0.5), ramp(0.8)] }; + let stops = vec![GradientStop::new(0.0, Color::WHITE), GradientStop::new(1.0, Color::BLACK)]; + let unplaced = GradientPaint { gradient: Gradient::new(GradientKind::Linear, stops), geom: None, angle: 0.0, swatch: None, freeform: None }; + let placed = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(80.0, 0.0), aspect: 1.0, focal: None }; + let fitted = unplaced.resolve(Rect::new(9.0, 19.0, 51.0, 41.0)); + for (geom, expected) in [(None, fitted), (Some(placed), placed)] { + let paint = Paint::Gradient(Box::new(GradientPaint { geom, ..unplaced.clone() })); + for seam in [0.05, 0.75] { + let art = facet_art(vectorcraft_doc::NodeId(1), &face, &paint, light, seam); + let NodeKind::Group { children, clip: true } = &art.kind else { panic!("a clipped composite") }; + let base = &children[1].children().unwrap()[0]; + let Paint::Gradient(g) = base.appearance.items[0].paint() else { panic!("the source gradient") }; + assert_eq!(g.geom, Some(expected), "seam {seam}"); + } + } + } } diff --git a/crates/effects/src/pixel.rs b/crates/effects/src/pixel.rs index 89eb541b19..0c159f8485 100644 --- a/crates/effects/src/pixel.rs +++ b/crates/effects/src/pixel.rs @@ -30,7 +30,7 @@ mod texture; mod video; use serde_json::Value; -use vectorcraft_geom::{Affine, Point, Rect}; +use vectorcraft_geom::{Affine, Point, Rect, Vec2}; use crate::util::{flag, num, text}; @@ -158,9 +158,10 @@ pub enum PixelFx { /// (1..20), then a [`Texture`] surface scaled by `scaling` (0.5..2), in relief as strong as /// `relief` (0..50) and lit from `light`; `invert` turns the surface's heights over. RoughPastels { length: f64, detail: f64, texture: Texture, scaling: f64, relief: f64, light: Light, invert: bool }, - /// Blur › Radial Blur around the object's centre: along arcs (spin, an arc of `amount`°) or - /// along rays (zoom, the content scaled by up to about ±`amount`/2 %), averaging 2^`passes` samples. - RadialBlur { amount: f64, zoom: bool, passes: u32 }, + /// Blur › Radial Blur around its Blur Center, `center` (0..1 across and down the object's + /// bounds; (0.5, 0.5) the object's centre): along arcs (spin, an arc of `amount`°) or along + /// rays (zoom, the content scaled by up to about ±`amount`/2 %), averaging 2^`passes` samples. + RadialBlur { amount: f64, zoom: bool, passes: u32, center: [f64; 2] }, /// Blur › Smart Blur (Normal mode): each pixel averaged with the neighbours within `radius` /// whose colour differs from its own by no more than `threshold` levels, over a grid of /// `samples` × `samples` neighbours at most. @@ -314,9 +315,12 @@ pub struct PixelSpace { pub to_doc: Affine, /// The size of a pixel in document units. pub px: f64, - /// The object's centre (document coordinates): where Radial Blur blurs around, and where the - /// Pixelate filters' patterns are anchored (so they move with the object). + /// The object's centre (document coordinates): where Radial Blur blurs around by default, and + /// where the Pixelate filters' patterns are anchored (so they move with the object). pub center: Point, + /// The width and height of the object's bounds (document units), centred on `center`: Radial + /// Blur's Blur Center lies at a share of them. + pub size: Vec2, /// What the colour channels hold. pub channels: Channels, /// The height of a line of the document's raster grid (document units: 72 / Document Raster @@ -421,6 +425,7 @@ pub(crate) fn parse(id: &str, p: &Value) -> Option { amount: num(p, "amount", 10.0).clamp(1.0, 100.0), zoom: text(p, "method", "spin").eq_ignore_ascii_case("zoom"), passes: quality([("draft", 4), ("good", 6), ("best", 8)], 6), + center: [num(p, "centerX", 0.5).clamp(0.0, 1.0), num(p, "centerY", 0.5).clamp(0.0, 1.0)], }, "blur.smart" => PixelFx::SmartBlur { radius: num(p, "radius", 3.0).clamp(0.1, 100.0), @@ -608,13 +613,13 @@ pub(crate) fn parse(id: &str, p: &Value) -> Option { impl PixelFx { /// How far beyond `bounds` (the content's, document units) the effect can paint. pub fn outset(&self, bounds: Rect) -> f64 { - // From the centre to the farthest corner, and to the nearest side. - let far = 0.5 * bounds.width().hypot(bounds.height()); - let near = 0.5 * bounds.width().min(bounds.height()); match *self { - // A rotated corner reaches the circle through the corners. - PixelFx::RadialBlur { zoom: false, .. } => (far - near).max(0.0), - PixelFx::RadialBlur { amount, zoom: true, .. } => far * (blur::zoom_extent(amount).exp() - 1.0), + // A rotated corner reaches the circle about the Blur Center through the farthest corner. + PixelFx::RadialBlur { zoom: false, center, .. } => { + let (far, near) = blur::center_reach(bounds, center); + (far - near).max(0.0) + } + PixelFx::RadialBlur { amount, zoom: true, center, .. } => blur::center_reach(bounds, center).0 * (blur::zoom_extent(amount).exp() - 1.0), PixelFx::SmartBlur { radius, .. } => radius, PixelFx::AccentedEdges { .. } => 0.0, // Strokes reach out of the object as far as they reach into it. @@ -786,7 +791,7 @@ impl PixelFx { PixelFx::RoughPastels { length, detail, ref texture, scaling, relief, light, invert } => { artistic::rough_pastels(px, w, h, space, length, detail, texture, scaling, relief, light, invert) } - PixelFx::RadialBlur { amount, zoom, passes } => blur::radial(px, w, h, space, amount, zoom, passes), + PixelFx::RadialBlur { amount, zoom, passes, center } => blur::radial(px, w, h, space, amount, zoom, passes, center), PixelFx::SmartBlur { radius, threshold, samples, mode: SmartBlurMode::Normal } => { blur::smart(px, w, h, to_px(radius), threshold, samples) } diff --git a/crates/effects/src/pixel/blur.rs b/crates/effects/src/pixel/blur.rs index 0a061571ba..877061922d 100644 --- a/crates/effects/src/pixel/blur.rs +++ b/crates/effects/src/pixel/blur.rs @@ -1,6 +1,6 @@ //! Blur › Radial Blur and Smart Blur (Normal, Edge Only and Overlay Edge). -use vectorcraft_geom::{Affine, Point, Vec2}; +use vectorcraft_geom::{Affine, Point, Rect, Vec2}; use super::{PixelSpace, Px16, box_blur, pick, to8, to16}; @@ -29,13 +29,31 @@ fn bilinear(buf: &[Px16], w: usize, h: usize, x: f64, y: f64) -> [f32; 4] { std::array::from_fn(|i| a[i] * wa + b[i] * wb + c[i] * wc + d[i] * wd) } -/// Radial Blur: the average of the content turned (spin) or scaled (zoom) about the centre over -/// evenly spaced steps spanning `amount`. Each pass averages the previous result with itself -/// turned both ways by half the last step, so `passes` passes average 2^`passes` samples at two -/// lookups a pixel each. -pub(super) fn radial(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, amount: f64, zoom: bool, passes: u32) { +/// How far Radial Blur's Blur Center `center` (0..1 across and down `bounds`) lies from the +/// farthest corner of `bounds`, and from its nearest side. +pub(super) fn center_reach(bounds: Rect, center: [f64; 2]) -> (f64, f64) { + // The share of the width (height) on the far side of the center, doubled: 1 at the middle. + let far = |f: f64| 1.0 + (2.0 * f - 1.0).abs(); + let (w, h) = (bounds.width(), bounds.height()); + let near = ((2.0 - far(center[0])) * w).min((2.0 - far(center[1])) * h); + (0.5 * (far(center[0]) * w).hypot(far(center[1]) * h), 0.5 * near) +} + +/// Where Radial Blur's Blur Center `center` (0..1 across and down the object's bounds) lies in the +/// document: the object's centre at (0.5, 0.5). +pub(super) fn blur_center(space: &PixelSpace, center: [f64; 2]) -> Point { + let shift = Vec2::new((center[0] - 0.5) * space.size.x, (center[1] - 0.5) * space.size.y); + if shift.x.is_finite() && shift.y.is_finite() { space.center + shift } else { space.center } +} + +/// Radial Blur: the average of the content turned (spin) or scaled (zoom) about the Blur Center +/// (`center`, [`blur_center`]) over evenly spaced steps spanning `amount`. Each pass averages the +/// previous result with itself turned both ways by half the last step, so `passes` passes average +/// 2^`passes` samples at two lookups a pixel each. +#[allow(clippy::too_many_arguments)] // the effect's four options +pub(super) fn radial(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, amount: f64, zoom: bool, passes: u32, center: [f64; 2]) { // The centre in pixel index coordinates (pixel centres at whole numbers). - let c = space.to_doc.inverse() * space.center - Vec2::new(0.5, 0.5); + let c = space.to_doc.inverse() * blur_center(space, center) - Vec2::new(0.5, 0.5); if !(c.x.is_finite() && c.y.is_finite()) { return; } diff --git a/crates/effects/src/pixel/tests.rs b/crates/effects/src/pixel/tests.rs index a1a083f0fe..a1e73eab33 100644 --- a/crates/effects/src/pixel/tests.rs +++ b/crates/effects/src/pixel/tests.rs @@ -12,6 +12,7 @@ fn space(w: usize, h: usize) -> PixelSpace { to_doc: Affine::IDENTITY, px: 1.0, center: Point::new(w / 2.0, h / 2.0), + size: vectorcraft_geom::Vec2::new(w, h), channels: Channels::Rgb, line: 1.0, extent: 0.5 * w.hypot(h), @@ -479,12 +480,16 @@ fn film_grain_leaves_invalid_coordinate_spaces_alone() { #[test] fn params_take_defaults_and_stay_in_range() { - assert_eq!(fx("blur.radial", json!({})), PixelFx::RadialBlur { amount: 10.0, zoom: false, passes: 6 }); + assert_eq!(fx("blur.radial", json!({})), PixelFx::RadialBlur { amount: 10.0, zoom: false, passes: 6, center: [0.5, 0.5] }); assert_eq!( - fx("blur.radial", json!({"amount": 1e308, "method": "ZOOM", "quality": "best"})), - PixelFx::RadialBlur { amount: 100.0, zoom: true, passes: 8 } + fx("blur.radial", json!({"amount": 1e308, "method": "ZOOM", "quality": "best", "centerX": 0.25, "centerY": 1})), + PixelFx::RadialBlur { amount: 100.0, zoom: true, passes: 8, center: [0.25, 1.0] } + ); + // A saved center outside the bounds (the commands refuse one) draws at the nearest edge. + assert_eq!( + fx("blur.radial", json!({"amount": -5, "quality": "nonsense", "centerX": -3, "centerY": 7})), + PixelFx::RadialBlur { amount: 1.0, zoom: false, passes: 6, center: [0.0, 1.0] } ); - assert_eq!(fx("blur.radial", json!({"amount": -5, "quality": "nonsense"})), PixelFx::RadialBlur { amount: 1.0, zoom: false, passes: 6 }); assert_eq!(fx("blur.smart", json!({})), PixelFx::SmartBlur { radius: 3.0, threshold: 25.0, samples: 7, mode: SmartBlurMode::Normal }); assert_eq!( fx("blur.smart", json!({"radius": "1e999", "threshold": -1, "quality": "low", "blurMode": "EDGEONLY"})), @@ -519,6 +524,11 @@ fn outsets_follow_the_object() { let far = 0.5 * 100f64.hypot(50.0); assert!((spin.outset(b) - (far - 25.0)).abs() < 1e-9); assert!(fx("blur.radial", json!({"method": "zoom", "amount": 100})).outset(b) > 0.4 * far); + // About a corner the spin reaches the circle through the opposite corner, the whole diagonal out. + let corner = fx("blur.radial", json!({"centerX": 0, "centerY": 0})); + assert!((corner.outset(b) - 100f64.hypot(50.0)).abs() < 1e-9, "{}", corner.outset(b)); + let zoom = |center: f64| fx("blur.radial", json!({"method": "zoom", "amount": 100, "centerX": center, "centerY": center})).outset(b); + assert!((zoom(1.0) - 2.0 * zoom(0.5)).abs() < 1e-9, "a zoom about a corner reaches twice as far"); assert_eq!(fx("blur.smart", json!({"radius": 4})).outset(b), 4.0); assert_eq!(fx("blur.smart", json!({"radius": 4})).reach(1.0), Some(4.0)); // The edge modes also read the copy blurred over a wide radius's samples. @@ -633,6 +643,40 @@ fn spin_blur_smears_along_arcs_and_keeps_the_centre() { assert_eq!(at(&z, w, 32, 16)[3], 0, "not across it"); } +/// The Blur Center moves the point the blur turns about: a dot on it stays sharp, a dot on the +/// object's centre then spreads, and the center follows the object when it moves or is scaled. +#[test] +fn radial_blur_turns_about_its_blur_center() { + let (w, h) = (41, 41); + // A dot on pixel (10, 30), whose centre (10.5, 30.5) is the Blur Center below, and one on the + // object's centre. + let src = image(w, h, |x, y| if (x == 10 && y == 30) || (x == 20 && y == 20) { grey(255) } else { [0, 0, 0, 0] }); + let blur = |p: serde_json::Value, s: &PixelSpace, src: &[u8]| { + let mut d = src.to_vec(); + fx("blur.radial", p).apply(&mut d, w, h, s); + d + }; + let off = json!({"amount": 60, "quality": "best", "centerX": 10.5 / 41.0, "centerY": 30.5 / 41.0}); + let d = blur(off.clone(), &space(w, h), &src); + assert!(at(&d, w, 10, 30)[3] > 100, "the dot on the Blur Center barely moves: {:?}", at(&d, w, 10, 30)); + assert!(at(&d, w, 20, 20)[3] < 100, "the dot on the object's centre spreads: {:?}", at(&d, w, 20, 20)); + // The default center is the object's centre, the same as no center at all. + assert_eq!(blur(json!({"amount": 60, "centerX": 0.5, "centerY": 0.5}), &space(w, h), &src), blur(json!({"amount": 60}), &space(w, h), &src)); + // Moved 7 pt right and 3 pt down, the object draws the same pixels. + let moved = + PixelSpace { to_doc: Affine::translate((7.0, 3.0)), center: space(w, h).center + vectorcraft_geom::Vec2::new(7.0, 3.0), ..space(w, h) }; + assert_eq!(blur(off.clone(), &moved, &src), d, "the center moves with the object"); + // Drawn at twice the size (two points a pixel), the center lies on the same pixels. + let big = PixelSpace { + to_doc: Affine::scale(2.0), + px: 2.0, + center: Point::new(41.0, 41.0), + size: vectorcraft_geom::Vec2::new(82.0, 82.0), + ..space(w, h) + }; + assert_eq!(blur(off, &big, &src), d, "the center scales with the object"); +} + #[test] fn smart_blur_smooths_noise_and_keeps_edges() { let (w, h) = (40, 20); @@ -862,6 +906,7 @@ fn lengths_are_document_units() { to_doc: Affine::scale(1.0 / scale as f64), px: 1.0 / scale as f64, center: Point::ZERO, + size: vectorcraft_geom::Vec2::ZERO, channels: Channels::Rgb, line: 1.0, extent: 0.0, @@ -916,7 +961,15 @@ fn linear_light_blur_mixes_light_not_values() { fn pixel_timings() { let (w, h) = (2000, 2000); let src = image(w, h, |x, y| [(x % 256) as u8, (y % 256) as u8, ((x ^ y) % 256) as u8, 255]); - let s = PixelSpace { to_doc: Affine::IDENTITY, px: 1.0, center: Point::new(1000.0, 1000.0), channels: Channels::Rgb, line: 1.0, extent: 0.0 }; + let s = PixelSpace { + to_doc: Affine::IDENTITY, + px: 1.0, + center: Point::new(1000.0, 1000.0), + size: vectorcraft_geom::Vec2::new(2000.0, 2000.0), + channels: Channels::Rgb, + line: 1.0, + extent: 0.0, + }; let cases = [ ("blur.radial", json!({"quality": "draft"})), ("blur.radial", json!({"quality": "good"})), diff --git a/crates/effects/src/pixel/tests_paint.rs b/crates/effects/src/pixel/tests_paint.rs index e84e587c9a..20fb8d10f2 100644 --- a/crates/effects/src/pixel/tests_paint.rs +++ b/crates/effects/src/pixel/tests_paint.rs @@ -14,6 +14,7 @@ fn space(w: usize, h: usize) -> PixelSpace { to_doc: Affine::IDENTITY, px: 1.0, center: Point::new(w / 2.0, h / 2.0), + size: vectorcraft_geom::Vec2::new(w, h), channels: Channels::Rgb, line: 1.0, extent: 0.5 * w.hypot(h), diff --git a/crates/effects/src/pixel/tests_sketch.rs b/crates/effects/src/pixel/tests_sketch.rs index fd467a23ca..127b79c5f0 100644 --- a/crates/effects/src/pixel/tests_sketch.rs +++ b/crates/effects/src/pixel/tests_sketch.rs @@ -14,6 +14,7 @@ fn space(w: usize, h: usize) -> PixelSpace { to_doc: Affine::IDENTITY, px: 1.0, center: Point::new(w / 2.0, h / 2.0), + size: vectorcraft_geom::Vec2::new(w, h), channels: Channels::Rgb, line: 1.0, extent: 0.5 * w.hypot(h), diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index ee7d3f8322..70e5994cb5 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -107,11 +107,44 @@ fn reaches_appearance(e: &Effect) -> bool { } /// Is `n` a path or compound path that its Transform effects make into art of separate objects -/// ([`has_gradient_copies`], [`has_layered_copies`], [`has_transform_options`]), or whose -/// live-effect plug-ins paint what they return ([`has_painted_effects`])? It is drawn, baked and -/// expanded through that art ([`reshape`]). +/// ([`has_gradient_copies`], [`has_layered_copies`], [`has_transform_options`], [`copied_raster_at`]), +/// or whose live-effect plug-ins paint what they return ([`has_painted_effects`])? It is drawn, +/// baked and expanded through that art ([`reshape`]). pub fn has_transform_art(n: &Node) -> bool { - has_gradient_copies(n) || has_layered_copies(n) || has_transform_options(n) || has_painted_effects(n) + has_gradient_copies(n) || has_layered_copies(n) || has_transform_options(n) || has_painted_effects(n) || copied_raster_at(n).is_some() +} + +/// Where the own effects of `n`, a path or compound path, split so that each copy of a Transform +/// effect carries the raster effects listed before that effect ([`copied_raster_art`]): the index +/// of the last visible Transform effect that makes copies, when a visible raster effect that +/// follows a Transform effect ([`crate::raster::follows`]) is listed before it and every other +/// visible effect before it is a geometry effect or such a raster effect. `None` otherwise, and for +/// a path with a linked opacity mask, a 3D effect, Crop Marks, Vector Halftone, a live-effect +/// plug-in that paints what it returns, or a fill or stroke that paints with geometry effects of +/// its own. +pub(crate) fn copied_raster_at(n: &Node) -> Option { + if !matches!(n.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. }) { + return None; + } + let effects = &n.appearance.effects; + // Checked first: this runs for every object drawn. + if !effects.iter().any(|e| e.visible && crate::raster::follows(&e.id)) || !effects.iter().any(|e| e.visible && e.id == "distort.transform") { + return None; + } + let t = effects.iter().rposition(|e| { + e.visible && e.id == "distort.transform" && crate::distort::transform_map(Rect::ZERO, &merged_params(&e.id, &e.params), 0).1 > 0 + })?; + let before = effects.get(..t)?; + let carried = before.iter().any(|e| e.visible && crate::raster::follows(&e.id)) + && before.iter().all(|e| !e.visible || is_geometry(&e.id) || crate::raster::follows(&e.id)); + let excluded = n.extras().mask.as_ref().is_some_and(|m| m.linked) + || crate::has_solid(n) + || crate::has_revolve(n) + || crate::has_crop_marks(n) + || crate::addons::halftone::has_halftone(n) + || has_painted_effects(n) + || n.appearance.items.iter().any(|i| crate::paints(i) && crate::has_geometry(i.effects())); + (carried && !excluded).then_some(t) } /// Is `e` a visible live-effect plug-in whose manifest declares `paintOutput`: its id's plug-in id, @@ -475,6 +508,20 @@ fn laid_out(t: &vectorcraft_doc::TextObject) -> (Vec, kurbo::Bez (runs, all, layout.bounds, colours) } +/// Paint `piece`, a piece of type's outline in text space (glyphs, ruby glyphs or an underline or +/// strikethrough bar), with `style`, the fills and strokes of its run, and place it in the document +/// by `xf`, the type's transform, as the renderer paints the run: its unplaced gradients are fixed +/// to `bounds`, the layout's bounds in text space, so every piece of the type shows the one +/// gradient fitted across the whole layout, and the transform also scales its stroke weights and +/// dashes and transforms its pattern tiles. Placed gradients keep their place in text space and +/// move with the type. +pub fn paint_type_piece(piece: &mut Node, style: &vectorcraft_doc::CharStyle, bounds: Rect, xf: Affine) { + let mut ap = style.appearance(); + ap.pin_gradients(bounds); + piece.appearance = ap.into(); + piece.transform(xf, vectorcraft_doc::Scaling { strokes: true, patterns: true, ..Default::default() }); +} + /// Type as glyph outlines in document space: one path per run with the run's fill and stroke, /// over its colour glyphs (images, art), and (when the object has its own fills/strokes) the whole /// outline with the object's items below the characters under them and the others over them, as @@ -487,7 +534,6 @@ pub fn outline_text(n: &Node) -> Option { let NodeKind::Text(t) = &n.kind else { return None }; let (runs, all, bounds, colours) = laid_out(t); let path = |bp: &kurbo::BezPath| PathData::from_bezpath(bp).transformed(t.xf); - let scaling = vectorcraft_doc::Scaling { strokes: true, patterns: true, ..Default::default() }; let mut children: Vec> = vec![]; for (i, (bp, run)) in runs.iter().zip(&t.runs).enumerate() { // Colour glyphs paint themselves, under their run's fill, as the renderer paints them. @@ -495,10 +541,8 @@ pub fn outline_text(n: &Node) -> Option { if bp.elements().is_empty() { continue; } - let mut ap = run.style.appearance(); - ap.pin_gradients(bounds); - let mut piece = Node::path(n.id, PathData::from_bezpath(bp), ap); - piece.transform(t.xf, scaling); + let mut piece = Node::path(n.id, PathData::from_bezpath(bp), Appearance::default()); + paint_type_piece(&mut piece, &run.style, bounds, t.xf); children.push(Arc::new(piece)); } if !n.appearance.items.is_empty() && !all.elements().is_empty() { @@ -797,6 +841,9 @@ fn as_art_opts( nodes: &SymbolNodes, apart: bool, ) -> Option { + if let Some(t) = copied_raster_at(n) { + return Some(dressed_keeping_effects(copied_raster_art(paint_doc, n, t, apart), n)); + } let fx = geometry_effects(n); let mut art = match &n.kind { NodeKind::Image(im) => { @@ -868,7 +915,7 @@ fn as_art_opts( /// `art`, the art made of `n`, with `n`'s name, visibility, transparency, opacity mask and /// remaining (raster) effects. -fn dressed(mut art: Node, n: &Node) -> Node { +pub(crate) fn dressed(mut art: Node, n: &Node) -> Node { art.name = n.name.clone(); art.visible = n.visible; art.opacity = n.opacity; @@ -882,6 +929,89 @@ fn dressed(mut art: Node, n: &Node) -> Node { art } +/// [`dressed`] that keeps the effects of `art`. +fn dressed_keeping_effects(mut art: Node, n: &Node) -> Node { + let effects = std::mem::take(&mut art.appearance.effects); + let mut art = dressed(art, n); + art.appearance.effects = effects; + art +} + +/// The art of path or compound path `n` whose own effects split at `t` ([`copied_raster_at`]): the +/// art the effects before the Transform effect at `t` make of `n`, with their raster effects, then +/// copied by that Transform effect, each copy an object of its own carrying those raster effects +/// moved, turned, reflected and scaled with it ([`follow_art`]), and then reshaped by the geometry +/// effects after it. The art keeps `n`'s id and carries the raster effects from `t` on, without +/// `n`'s name, visibility, transparency and opacity mask. The copies stop where [`copy_art`]'s do, +/// each with its raster effects. With `apart`, the Transform effects before `t` make each copy an +/// object of its own ([`copy_leaf`]). +fn copied_raster_art(doc: Option<&Document>, n: &Node, t: usize, apart: bool) -> Node { + let (before, rest) = n.appearance.effects.split_at(t); + let mut source = n.clone(); + source.appearance.effects = before.to_vec(); + let piece = match copied_raster_at(&source) { + Some(at) => copied_raster_art(doc, &source, at, apart), + None => { + let mut art = one_piece(&source); + let carry = reshape_leaves_apart(&mut art, &geometry_effects(&source), &source.appearance.effects, Budget::EFFECTS, apart, doc); + if apart { + hoist_copies(&mut art); + } + transform_items(&mut art, doc); + let mut ran = source.appearance.effects.clone(); + if carry.skipped() { + carry.hide_skipped(&mut ran); + } + art.appearance.effects = crate::raster::without_geometry(&ran); + art + } + }; + let mut art = Node::group(n.id, vec![Arc::new(piece)]); + if let (Some(e), Some(bounds)) = (rest.first(), art.geometric_bounds()) { + let params = merged_params(&e.id, &e.params); + let (m, copies) = crate::distort::transform_map(bounds, ¶ms, n.id.0); + let options = crate::distort::TransformOptions::of(¶ms); + // The raster effects follow the copies below; Scale Strokes & Effects scales the others. + let mut scaling = copy_scaling(options); + scaling.effects = options.strokes.then_some(scale_unfollowed as fn(&mut Effect, f64)); + let max = Budget::EFFECTS.at_least(art_cost(&art)); + copy_art(&mut art, m, copies, scaling, max); + if let Some(children) = art.children_mut() { + // The original is last, and each copy above it is mapped once more by `m`. + let step = m.with_translation(vectorcraft_geom::Vec2::ZERO); + let mut a = Affine::IDENTITY; + let none = HashSet::new(); + for (k, c) in children.iter_mut().rev().enumerate() { + if k > 0 { + a *= step; + follow_art(Arc::make_mut(c), a, &none, Some(&none), None, 0); + } + // Each copy is the piece in a group of its own: the piece takes its place. + if let Some([one]) = c.children().map(Vec::as_slice) { + *c = one.clone(); + } + } + } + } + let later: Vec<&Effect> = rest.iter().skip(1).filter(|e| e.visible && is_geometry(&e.id)).collect(); + let carry = reshape_leaves_apart(&mut art, &later, &n.appearance.effects, Budget::EFFECTS, apart, doc); + let mut ran = n.appearance.effects.clone(); + if carry.skipped() { + carry.hide_skipped(&mut ran); + } + art.appearance.effects = crate::raster::without_geometry(ran.get(t..).unwrap_or_default()); + art +} + +/// The effects of `n` that paint around its whole art: all of its own, or from the Transform effect +/// on for a path whose copies each carry the raster effects listed before it ([`copied_raster_at`]). +pub fn outer_effects(n: &Node) -> &[Effect] { + match copied_raster_at(n) { + Some(t) => n.appearance.effects.get(t..).unwrap_or_default(), + None => &n.appearance.effects, + } +} + /// A group with `n`'s id holding `n` without its transparency, opacity mask and effects: the one /// piece that `n`'s own geometry effects reshape. fn one_piece(n: &Node) -> Node { @@ -909,6 +1039,9 @@ pub(crate) fn own_effects_art(doc: Option<&Document>, n: &Node) -> Option { return None; } + if let Some(t) = copied_raster_at(n) { + return Some(dressed_keeping_effects(copied_raster_art(doc, n, t, false), n)); + } if n.appearance.items.iter().any(|i| crate::paints(i) && crate::has_geometry(i.effects())) { // One element: its pieces never knock each other out. return crate::bake_type_appearance(doc, n).map(|art| Node { knockout: vectorcraft_doc::Knockout::Off, ..art }); diff --git a/crates/effects/src/revolve.rs b/crates/effects/src/revolve.rs index 4b23c3af8c..a9c9482d1d 100644 --- a/crates/effects/src/revolve.rs +++ b/crates/effects/src/revolve.rs @@ -6,8 +6,9 @@ use serde_json::Value; use vectorcraft_doc::color::{Color, Paint}; use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, FillLayer, Node, NodeId, NodeKind}; use vectorcraft_geom::{PathData, PathEl, Point, Rect, Vec2}; -use vectorcraft_three_d::{Edge, Revolve}; +use vectorcraft_three_d::{Edge, Revolve, SolidFaces}; +use crate::solids::wireframe::WireFace; use crate::solids::{ Profile, Scope, is_container, members, object_profile, past_effect, profile, reshape_members, resolve_for, solid_paints, union_bounds, }; @@ -337,34 +338,80 @@ fn geometry(path: &PathData, fx: &[Effect], ctx: &GeomContext) -> PathData { /// `b`, revolved with `options`, as dark as `item` is opaque and in its blending mode; `None` with /// the shadow off, when `item` is fully transparent or when it casts nothing, and an error when /// the surface it is cast from is past the limits. -fn shadow_of(id: NodeId, fx: &Effect, path: &PathData, item: &AppearanceItem, b: Rect, options: Revolve) -> Result, String> { +/// +/// `kept` holds the faces the surface drawn kept for its shadow ([`surface`]); without them the +/// surface is swept again for its shadow alone. +fn shadow_of( + id: NodeId, + fx: &Effect, + path: &PathData, + item: &AppearanceItem, + b: Rect, + options: Revolve, + kept: Option, +) -> Result, String> { let Some(settings) = crate::solids::shadow::options(&merged_params(&fx.id, &fx.params)) else { return Ok(None) }; let (_, opacity, blend) = paint_of(item); if opacity <= 0.0 { return Ok(None); } let mut caster = vectorcraft_three_d::ShadowCaster::new(); - caster.revolve(path, vectorcraft_geom::FillRule::NonZero, b, options)?; + cast_surface(&mut caster, path, b, options, kept)?; Ok(crate::solids::shadow::art(id, &caster, settings, crate::solids::shadow::Ink { opacity, blend })) } +/// Does Revolve `fx` cast a shadow, so a surface in paint as opaque as `opacity` keeps the faces +/// its shadow is cast from ([`surface`])? +fn casts(fx: &Effect, opacity: f32) -> bool { + opacity > 0.0 && crate::solids::shadow::options(&merged_params(&fx.id, &fx.params)).is_some() +} + +/// Add the surface of `path` about the axis of `b` to `caster`: the faces it kept when it was +/// drawn, or without them, the surface swept for its shadow alone. +fn cast_surface( + caster: &mut vectorcraft_three_d::ShadowCaster, + path: &PathData, + b: Rect, + options: Revolve, + kept: Option, +) -> Result, String> { + match kept { + Some(kept) => caster.add_solid(kept), + None => { + #[cfg(test)] + crate::solids::SOLIDS_BUILT.with(|n| n.set(n.get() + 1)); + caster.revolve(path, vectorcraft_geom::FillRule::NonZero, b, options) + } + } +} + /// The shadow of group Revolve `fx` cast by the surfaces of the members `shapes` that have one, /// about the axis of `b`, on one plane; each member's part is as dark as its surface is opaque, /// in its paint's blending mode, and its opacity mask and blending mode apply to that part /// ([`crate::solids::shadow::scoped_art`]). An error when the surfaces it is cast from are past the -/// limits. -fn group_shadow(id: NodeId, fx: &Effect, shapes: &[Profile], b: Rect, options: Revolve) -> Result>, String> { +/// limits. `kept` holds, member by member, the faces each surface drawn kept for its shadow +/// ([`surface`]); a member without them is swept again for its shadow alone. +fn group_shadow( + id: NodeId, + fx: &Effect, + shapes: &[Profile], + b: Rect, + options: Revolve, + kept: Vec>, +) -> Result>, String> { let Some(settings) = crate::solids::shadow::options(&merged_params(&fx.id, &fx.params)) else { return Ok(vec![]) }; let mut caster = vectorcraft_three_d::ShadowCaster::new(); let mut cast = vec![]; + let mut kept = kept.into_iter(); for s in shapes { + let kept = kept.next().flatten(); let Some((_, opacity, blend)) = surface_item(&s.items).map(paint_of) else { continue }; // A member whose surface is fully transparent casts nothing. let ink = crate::solids::shadow::Ink { opacity: opacity * s.opacity, blend }; if ink.opacity <= 0.0 { continue; } - let faces = caster.revolve(&s.path, vectorcraft_geom::FillRule::NonZero, b, options)?; + let faces = cast_surface(&mut caster, &s.path, b, options, kept)?; cast.push((s.scopes.as_slice(), ink, faces)); } Ok(crate::solids::shadow::scoped_art(id, &caster, settings, cast, crate::solids::has_masks(shapes))) @@ -376,7 +423,8 @@ fn group_shadow(id: NodeId, fx: &Effect, shapes: &[Profile], b: Rect, options: R /// the bytes of the paint copies of every surface and graphic of the object. Revolve (Classic) draws every face /// with its classic surface, as Extrude & Bevel (Classic) does. Revolve's graphics, with the /// symbols of `doc`, are drawn on the faces of the side ([`crate::solids::graphics::surface_parts`]): -/// a face with a part of a graphic is a group of the face and that part. +/// a face with a part of a graphic is a group of the face and that part. With `cast`, the sweep +/// that draws the surface also keeps the faces its shadow is cast from ([`SolidFaces`]). #[allow(clippy::too_many_arguments)] fn surface( doc: Option<&Document>, @@ -390,11 +438,18 @@ fn surface( blend: vectorcraft_doc::color::BlendMode, expand: bool, copies: &mut Copies, -) -> Option<(Vec, Node)> { + cast: bool, +) -> Option<(Vec, Node, Option)> { + #[cfg(test)] + crate::solids::SOLIDS_BUILT.with(|n| n.set(n.get() + 1)); // A loaded file or a profile edited past the limits keeps drawing its source path instead // of crashing the frame. Commands validate the same evaluator and report its errors. if fx.id == CLASSIC_REVOLVE { - let facets = vectorcraft_three_d::revolve_facets(path, b, options).ok()?; + let (facets, kept) = if cast { + vectorcraft_three_d::revolve_facets_shadowed(path, b, options).ok().map(|(f, kept)| (f, Some(kept)))? + } else { + (vectorcraft_three_d::revolve_facets(path, b, options).ok()?, None) + }; copies.surfaces = copies.surfaces.saturating_add(paint_copies(facets.len(), &paint)); if copies.surfaces > MAX_PAINT_COPIES { return None; @@ -404,10 +459,14 @@ fn surface( let drawn = facets.iter().map(|f| Drawn { depth: f.depth, points: f.contours.first().cloned().unwrap_or_default(), plane: f.plane }).collect(); let p = merged_params(&fx.id, &fx.params); - return Some((drawn, crate::solids::classic::surface(n, facets, &paint, opacity, blend, &p))); + return Some((drawn, crate::solids::classic::surface(n, facets, &paint, opacity, blend, &p), kept)); } let colored = options.light_color != [1.0; 3] || options.lights.is_some(); - let faces = vectorcraft_three_d::revolve(path, b, options).ok()?; + let (faces, kept) = if cast { + vectorcraft_three_d::revolve_shadowed(path, b, options).ok().map(|(f, kept)| (f, Some(kept)))? + } else { + (vectorcraft_three_d::revolve(path, b, options).ok()?, None) + }; copies.surfaces = copies.surfaces.saturating_add(paint_copies(faces.len(), &paint)); if copies.surfaces > MAX_PAINT_COPIES { return None; @@ -531,7 +590,7 @@ fn surface( let mut group = Node::group(n.id, children); group.opacity = opacity; group.blend = blend; - Some((keys, group)) + Some((keys, group, kept)) } /// A face [`surface`] draws: its depth and, for [`crate::solids::surface_order`], its polygon on the @@ -548,8 +607,9 @@ fn in_order(items: Vec, order: &[usize]) -> Vec { order.iter().filter_map(|&k| slots.get_mut(k).and_then(Option::take)).collect() } -/// A surface of one object about the bounds of `path`, built with options derived from `fx`. -/// `copies` is the count [`surface`] adds to; its graphics take the symbols of `doc`. +/// A surface of one object about the bounds of `path`, built with options derived from `fx`, and +/// when `fx` casts a shadow from it, the faces it is cast from ([`surface`]). `copies` is the count +/// [`surface`] adds to; its graphics take the symbols of `doc`. fn object_surface( doc: Option<&Document>, n: &Node, @@ -558,10 +618,11 @@ fn object_surface( item: &AppearanceItem, expand: bool, copies: &mut Copies, -) -> Option { +) -> Option<(Node, Option)> { let b = path.bounds()?; let (paint, opacity, blend) = paint_of(item); - surface(doc, n, path, b, fx_options(fx), fx, paint, opacity, blend, expand, copies).map(|(_, art)| art) + let cast = casts(fx, opacity); + surface(doc, n, path, b, fx_options(fx), fx, paint, opacity, blend, expand, copies, cast).map(|(_, art, kept)| (art, kept)) } /// The paint of a graphic's solid color `c` on `face`, shaded as the face shades a solid fill of @@ -662,11 +723,18 @@ pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Resul /// instances, blends and clipping groups already resolved), in document coordinates: with the /// effect on the object, the surface in its top visible fill (else its stroke); with it on fills and strokes, one surface for each of /// them, reshaped by the geometry effects after each one's Revolve; on a group or layer, one for -/// each member, about one shared axis. The swatches and patterns named by a live-effect plug-in -/// after a fill's or stroke's Revolve are looked up in `doc`. -pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result, String> { - let faces = |path: &PathData, b: Rect, options: Revolve| -> Result, String> { - Ok(vectorcraft_three_d::revolve(path, b, options)?.iter().map(vectorcraft_three_d::Face::path).collect()) +/// each member, about one shared axis. With the effect on the object, group or layer, also the +/// shadow drawn behind them. The swatches and patterns named by a live-effect plug-in after a fill's +/// or stroke's Revolve are looked up in `doc`. Each face carries the width of the stroke the canvas +/// draws around it ([`surface`]). +pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result { + let faces = |path: &PathData, b: Rect, fx: &Effect, options: Revolve| -> Result, String> { + if fx.id == CLASSIC_REVOLVE { + let p = merged_params(&fx.id, &fx.params); + let facets = vectorcraft_three_d::revolve_facets(path, b, options)?; + return Ok(facets.iter().map(|f| WireFace { path: f.path(), stroke: crate::solids::classic::stroke_width(f, &p) }).collect()); + } + Ok(vectorcraft_three_d::revolve(path, b, options)?.iter().map(|f| WireFace { path: f.path(), stroke: SEAM_WIDTH }).collect()) }; if is_container(n) { let index = n @@ -675,27 +743,28 @@ pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result, n: &Node) -> Result, n: &Node, expand: bool) -> Option { let paints = solid_paints(n); let item = surface_item(&paints)?; let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id)); - let surface = object_surface(doc, n, &path, fx, item, expand, &mut copies)?; + let (surface, kept) = object_surface(doc, n, &path, fx, item, expand, &mut copies)?; if let Some(b) = path.bounds() - && let Some(shadow) = shadow_of(n.id, fx, &path, item, b, fx_options(fx)).ok()? + && let Some(shadow) = shadow_of(n.id, fx, &path, item, b, fx_options(fx), kept).ok()? { children.push(Arc::new(shadow)); } @@ -781,10 +850,10 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { let fx = item.effects().get(index)?; let p = geometry(&path, item.effects().get(..index)?, &ctx.item(original)); let expand = expand && !item.effects().iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id)); - let mut art = object_surface(doc, n, &p, fx, item, expand, &mut copies)?; + let (mut art, kept) = object_surface(doc, n, &p, fx, item, expand, &mut copies)?; art.appearance.effects = item.effects().iter().skip(index + 1).filter(|e| !is_revolve(&e.id)).cloned().collect(); if let Some(b) = p.bounds() - && let Some(mut shadow) = shadow_of(n.id, fx, &p, item, b, fx_options(fx)).ok()? + && let Some(mut shadow) = shadow_of(n.id, fx, &p, item, b, fx_options(fx), kept).ok()? { shadow.appearance.effects = art.appearance.effects.clone(); shadows.push(Arc::new(shadow)); @@ -933,21 +1002,28 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id)); let mut copies = Copies::default(); let mut surfaces = vec![]; + // The faces each member's surface kept for the shadow, member by member. + let mut kept = vec![]; let mut opaque = true; // The graphics go once, on the side of the member with the longest profile. Without graphics // no member is measured for them. let mapped = fx.id == REVOLVE && !crate::solids::mapped_graphics(&merged_params(&fx.id, &fx.params)).is_empty(); let longest = if mapped { graphics_member(&shapes, b, options) } else { None }; for (k, s) in shapes.iter().enumerate() { - let Some(item) = surface_item(&s.items) else { continue }; + let Some(item) = surface_item(&s.items) else { + kept.push(None); + continue; + }; // The opacity and blending of the member and the groups it is in apply through its scopes. let (paint, opacity, blend) = paint_of(item); opaque &= opacity >= 1.0 && blend == Default::default() && s.scopes.is_empty(); // A member with transparency of its own keeps every face, as a transparent object does. let expand = expand && s.scopes.is_empty(); let doc = doc.filter(|_| longest == Some(k)); - let (depths, art) = surface(doc, n, &s.path, b, options, fx, paint, opacity, blend, expand, &mut copies)?; + let cast = casts(fx, opacity * s.opacity); + let (depths, art, faces) = surface(doc, n, &s.path, b, options, fx, paint, opacity, blend, expand, &mut copies, cast)?; surfaces.push((depths, art, s.scopes.as_slice())); + kept.push(faces); } if surfaces.is_empty() { return None; @@ -1048,7 +1124,7 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { }; // One shadow for every member's surface, behind them all. let mut children = children; - children.splice(0..0, group_shadow(n.id, fx, &shapes, b, options).ok()?); + children.splice(0..0, group_shadow(n.id, fx, &shapes, b, options, kept).ok()?); let remaining = past_effect(&n.appearance.effects, index); let mut art = n.clone(); art.kind = NodeKind::Group { children, clip: false }; @@ -1673,6 +1749,67 @@ mod tests { } assert_eq!(expand_revolve_art(&sample), revolve_art(&sample)); } + + /// The settings the shadows are compared with: the defaults, a partial sweep turned with + /// perspective, and an open surface away from its axis under a colored light. + fn shadow_settings() -> [Value; 3] { + [ + json!({"shadow": true}), + json!({"shadow": true, "rotationX": -25, "rotationY": 35, "perspective": 50, "angle": 220, "shadowDistance": 40}), + json!({"shadow": true, "shadowDistance": 30, "lightColor": "#ff8040", "offset": 20, "cap": false}), + ] + } + + /// The shadow of the faces Revolve and Revolve (Classic) kept when they swept their surfaces, + /// to the bit: the shadow of surfaces swept for the shadow alone, for one object, for an + /// object whose fill is half transparent, and for a group of two members, one at half opacity. + #[test] + fn the_shadow_cast_from_the_surfaces_drawn_is_the_shadow_of_surfaces_swept_for_it() { + for id in [REVOLVE, CLASSIC_REVOLVE] { + for params in shadow_settings() { + // Revolve (Classic) takes no shadow settings from commands, but a file can carry them. + let mut fx = crate::new_effect(id, &json!({})).unwrap(); + fx.params = params.clone(); + let n = profile_node(); + let (path, _) = profile(&n).unwrap(); + let b = path.bounds().unwrap(); + let mut half = n.clone(); + if let AppearanceItem::Fill(f) = &mut half.appearance.items[0] { + f.opacity = 0.5; + } + for n in [n, half] { + let item = surface_item(&n.appearance.items).unwrap(); + let (_, kept) = object_surface(None, &n, &path, &fx, item, false, &mut Copies::default()).unwrap(); + let drawn = shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), kept).unwrap(); + let alone = shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), None).unwrap(); + assert!(alone.is_some() || id == CLASSIC_REVOLVE, "{id} {params}"); + assert_eq!(format!("{drawn:?}"), format!("{alone:?}"), "{id} {params}"); + } + let mut other = profile_node(); + other.id = NodeId(2); + other.transform(Affine::translate((120.0, 0.0)), false); + other.opacity = 0.5; + let mut g = Node::group(NodeId(9), vec![Arc::new(profile_node()), Arc::new(other)]); + g.appearance.effects.push(fx.clone()); + let shapes = members(&g, "").unwrap(); + let b = union_bounds(&shapes).unwrap(); + let options = shared_options(&shapes, fx_options(&fx)).unwrap(); + let kept: Vec> = shapes + .iter() + .map(|s| { + let (paint, opacity, blend) = paint_of(surface_item(&s.items).unwrap()); + let cast = casts(&fx, opacity * s.opacity); + surface(None, &g, &s.path, b, options, &fx, paint, opacity, blend, false, &mut Copies::default(), cast).unwrap().2 + }) + .collect(); + assert!(kept.iter().all(Option::is_some), "{id} {params}"); + let drawn = group_shadow(g.id, &fx, &shapes, b, options, kept).unwrap(); + let alone = group_shadow(g.id, &fx, &shapes, b, options, vec![]).unwrap(); + assert!(!alone.is_empty() || id == CLASSIC_REVOLVE, "{id} {params}"); + assert_eq!(format!("{drawn:?}"), format!("{alone:?}"), "{id} {params}"); + } + } + } } #[cfg(test)] diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index a25a36a79e..c0d44947d7 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -7,7 +7,9 @@ use vectorcraft_doc::color::{BlendMode, Paint}; use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, Node, NodeId, NodeKind, OpacityMask}; use vectorcraft_geom::{BezPath, FillRule, PathData, Point, Rect, Vec2}; use vectorcraft_pathops::BoolOp; -use vectorcraft_three_d::{Bevel, BevelShape, DepthPlane, Extrude, Facet, Inflate, MAX_OBJECT_FACES, Mesh, MeshedSolid, PlanarFace, View}; +use vectorcraft_three_d::{ + Bevel, BevelShape, DepthPlane, Extrude, Facet, Inflate, MAX_OBJECT_FACES, Mesh, MeshedSolid, PlanarFace, SolidFaces, View, +}; #[cfg(test)] use vectorcraft_doc::color::Color; @@ -236,6 +238,30 @@ fn facets(id: &str, path: &PathData, rule: FillRule, bounds: Rect, p: &Value) -> } } +/// [`facets`], and with `cast` for Extrude & Bevel or Rotate the faces the solid's shadow is cast +/// from, from the same build. Inflate's solids are built together ([`built_solids_cast`]), and the +/// classic effects cast no shadow: they keep no faces. +fn facets_and_faces( + id: &str, + path: &PathData, + rule: FillRule, + bounds: Rect, + p: &Value, + cast: bool, +) -> Result<(Vec, Option), String> { + let view = view_options(p); + #[cfg(test)] + if cast && id == EXTRUDE { + SOLID_GEOMETRY_BUILT.with(|n| n.set(n.get() + 1)); + } + let built = match id { + EXTRUDE if cast => vectorcraft_three_d::extrude_shadowed(path, rule, bounds, extrude_options(p), view), + ROTATE if cast => vectorcraft_three_d::plane_shadowed(path, rule, bounds, view), + _ => return facets(id, path, rule, bounds, p).map(|f| (f, None)), + }; + built.map(|(f, faces)| (f, Some(faces))) +} + /// Check solid `id`'s parameter values `p` alone: the part of [`validate_solid`] that does not /// need the object. fn validate_solid_params(id: &str, p: &Value) -> Result<(), String> { @@ -575,10 +601,8 @@ fn surface(n: &Node, facets: Vec, paint: &Paint, opacity: f32, blend: Ble .into_iter() .map(|face| { // Adjacent facets, antialiased on their own, would leave hairline seams: a narrow - // stroke of the same paint closes them. No wider than the facet is thick, though: seen - // at a grazing angle a facet can be thinner than the stroke, and its stroke would then - // paint over its neighbours. - let seam = (face.thickness() / 2.0).clamp(0.05, 0.75); + // stroke of the same paint closes them ([`seam_width`]). + let seam = seam_width(&face); if let Some(g) = face.rgb_gradient && (paint.color().is_some() || matches!(paint, Paint::Gradient(_))) { @@ -608,6 +632,13 @@ fn surface(n: &Node, facets: Vec, paint: &Paint, opacity: f32, blend: Ble group } +/// The width of the stroke of a facet's own paint that closes the seams between `face` and its +/// neighbors. No wider than the facet is thick: seen at a grazing angle a facet can be thinner than +/// the stroke, and its stroke would then paint over its neighbors. +pub(crate) fn seam_width(face: &Facet) -> f64 { + (face.thickness() / 2.0).clamp(0.05, 0.75) +} + /// Is a surface of `facets` in `paint` one composite of all its facets when [`surface`] draws it /// whole: a solid color under colored lights with smooth shading? fn composites_facets(facets: &[Facet], paint: &Paint, colored: bool) -> bool { @@ -630,11 +661,26 @@ fn paint_ref(item: &AppearanceItem) -> &Paint { } } -/// Paint copies `surface` makes for `facets`: two per facet (fill and seam stroke), six when colored -/// lights give each facet derived paints (`lighting::solid_surface`, or `lighting::facet_art` for -/// each face). +/// Are `facets` drawn over an underlay of themselves ([`crate::lighting::sealed`], +/// [`crate::lighting::solid_surface`])? Under colored lights, when any facet takes a smooth light +/// ramp. +fn underlaid(facets: &[Facet], colored: bool) -> bool { + colored && facets.iter().any(|f| f.rgb_gradient.is_some()) +} + +/// The most paint copies `surface` makes for one facet ([`facet_copies`]). +const MAX_FACET_COPIES: usize = 12; + +/// Paint copies `surface` makes for `facets`: two per facet (fill and seam stroke), twice that when +/// the facets lie over an underlay of themselves, and [`MAX_FACET_COPIES`] when colored lights also +/// give each facet derived paints in three channels (`lighting::solid_surface`). fn facet_copies(facets: &[Facet], paint: &Paint, colored: bool) -> usize { - facets.len().saturating_mul(if composites_facets(facets, paint, colored) { 6 } else { 2 }) + let per_facet = match (underlaid(facets, colored), paint.color().is_some()) { + (true, true) => MAX_FACET_COPIES, + (true, false) => 4, + (false, _) => 2, + }; + facets.len().saturating_mul(per_facet) } /// The area `item` paints on `path`, and the rule that fills it: the path itself for a fill, the @@ -673,7 +719,9 @@ fn solid_parts(shapes: &[Profile], fallback: Rect) -> (Vec>, Rect) { #[cfg(test)] thread_local! { /// How many solids [`built_solids`] and [`meshes_for`] have built on this thread, for the tests. - static SOLIDS_BUILT: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Rotate's planes drawn, the solids built to cast a shadow ([`cast_shadow`]) and Revolve's + /// surfaces count too. + pub(crate) static SOLIDS_BUILT: std::cell::Cell = const { std::cell::Cell::new(0) }; /// How many Extrude & Bevel (Classic included) and Inflate solids [`facets`] and /// [`built_solids`] have built on this thread, for the tests. static SOLID_GEOMETRY_BUILT: std::cell::Cell = const { std::cell::Cell::new(0) }; @@ -692,10 +740,35 @@ fn built_solids<'a>( bounds: Rect, limit: usize, ) -> impl Iterator>, String>> + 'a { + built_solids_cast(id, p, parts, bounds, limit, false).map(|r| r.map(|s| s.map(|(f, _)| f))) +} + +/// One solid's facets and, when its shadow is cast, the faces it is cast from. +type CastingSolid = (Vec, Option); + +/// The surfaces of an object's solids, and the faces each solid kept for its shadow +/// ([`surfaces_for`]). +type SurfacesAndFaces = (Vec>, Vec>); + +/// [`built_solids`], and with `cast` for Extrude & Bevel or Inflate each solid's faces its shadow +/// is cast from, from the same build ([`SolidFaces`]). +fn built_solids_cast<'a>( + id: &'a str, + p: &'a Value, + parts: &'a [Part<'a>], + bounds: Rect, + limit: usize, + cast: bool, +) -> impl Iterator, String>> + 'a { // Inflate's eye is placed for every puff together, as far away as the highest needs. - let mut inflated = (id == INFLATE).then(|| { + let mut inflated = (id == INFLATE).then(|| -> Box>> { let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, _, area, rule, _, _)| (area, *rule)).collect(); - vectorcraft_three_d::inflate_each(&shapes, bounds, inflate_options(p), view_options(p)) + let (o, view) = (inflate_options(p), view_options(p)); + if cast { + Box::new(vectorcraft_three_d::inflate_shadowed(&shapes, bounds, o, view).map(|r| r.map(|(f, faces)| (f, Some(faces))))) + } else { + Box::new(vectorcraft_three_d::inflate_each(&shapes, bounds, o, view).map(|r| r.map(|f| (f, None)))) + } }); let mut kept = 0usize; let mut ended = false; @@ -709,13 +782,13 @@ fn built_solids<'a>( Some(each) => { #[cfg(test)] SOLID_GEOMETRY_BUILT.with(|n| n.set(n.get() + 1)); - each.next().unwrap_or_else(|| Ok(vec![])) + each.next().unwrap_or_else(|| Ok((vec![], None))) } - None => facets(id, area, *rule, bounds, p), + None => facets_and_faces(id, area, *rule, bounds, p, cast), }; let result = match built { Ok(f) => { - kept = kept.saturating_add(f.len()); + kept = kept.saturating_add(f.0.len()); if kept > limit { Err(vectorcraft_three_d::TOO_COMPLEX_SOLID.to_string()) } else { Ok(Some(f)) } } Err(_) if matches!(item, AppearanceItem::Stroke(_)) => Ok(None), @@ -827,14 +900,14 @@ fn rects_overlap(a: Rect, b: Rect) -> bool { /// How many faces [`cut_stroke_faces`] may add to solids painted by `items` that hold `faces` faces /// and whose paint copies take `paint_bytes` so far: as many as keep the faces within -/// [`MAX_OBJECT_FACES`] and the copies within the allowance, each added face counted as six copies -/// of the costliest stroke's paint. +/// [`MAX_OBJECT_FACES`] and the copies within the allowance, each added face counted as +/// [`MAX_FACET_COPIES`] copies of the costliest stroke's paint. fn cut_room<'a>(items: impl Iterator, faces: usize, paint_bytes: usize) -> usize { let per_face = items .filter(|item| matches!(item, AppearanceItem::Stroke(_))) .map(|item| { let mut copies = 0usize; - crate::revolve::paint_copies_add(&mut copies, 6, paint_ref(item)); + crate::revolve::paint_copies_add(&mut copies, MAX_FACET_COPIES, paint_ref(item)); copies }) .max() @@ -1344,18 +1417,31 @@ type ShadowAndSurfaces = (Vec>, Vec>); /// otherwise each solid is a surface of its own, in that order. A member's opacity mask and /// blending mode, and those of a group it is in, apply to the surfaces of the members it holds /// ([`masked`]). The art comes in two parts: the effect's shadow ([`cast_shadow`], none with it -/// off), to be drawn behind every surface of the object, and the surfaces. +/// off), cast from the faces the solids drawn kept ([`cast_built`]), to be drawn behind every +/// surface of the object, and the surfaces. fn art_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile]) -> Option { - let art = surfaces_for(doc, n, fx, shapes)?; + let p = crate::merged_params(&fx.id, &fx.params); + let cast = !is_classic_three_d(&fx.id) && shadow::options(&p).is_some(); + let (art, built) = surfaces_for(doc, n, fx, shapes, cast)?; // A shadow past the limits draws the source path, as a solid past them does; commands report // the error ([`validate_solid_in`]). - let shadow = match cast_shadow(&fx.id, &crate::merged_params(&fx.id, &fx.params), shapes).ok()? { + let shadow = if cast { cast_built(&fx.id, &p, shapes, built) } else { Ok(None) }; + let shadow = match shadow.ok()? { Some((caster, settings, cast)) => shadow::scoped_art(n.id, &caster, settings, cast, has_masks(shapes)), None => vec![], }; Some((shadow, art)) } +/// The shadow [`art_for`] draws for effect `fx` on `shapes` behind the surfaces of object `id`: +/// none with the shadow off, and an error when it is past the limits. +pub(crate) fn shadow_for(id: NodeId, fx: &Effect, shapes: &[Profile]) -> Result>, String> { + Ok(match cast_shadow(&fx.id, &crate::merged_params(&fx.id, &fx.params), shapes)? { + Some((caster, settings, cast)) => shadow::scoped_art(id, &caster, settings, cast, has_masks(shapes)), + None => vec![], + }) +} + /// What the shadow of the solids [`surfaces_for`] builds for effect `id` with parameters `p` on /// `shapes` is cast from, on one plane: the faces of every solid, the shadow's settings and the /// faces of each solid of visible art with its member's scopes and ink. `None` with the shadow @@ -1382,6 +1468,8 @@ fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result 0.0) { let (area, rule) = region(&s.path, s.rule, item); + #[cfg(test)] + SOLIDS_BUILT.with(|n| n.set(n.get() + 1)); let faces = caster.plane(&area, rule, b, view)?; cast.push((s.scopes.as_slice(), ink(item, s.opacity), faces)); } @@ -1393,10 +1481,14 @@ fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result, String>> = if id == INFLATE { let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, _, area, rule, _, _)| (area, *rule)).collect(); let casts: Vec = inks.iter().map(|i| i.opacity > 0.0).collect(); + #[cfg(test)] + SOLIDS_BUILT.with(|n| n.set(n.get() + shapes.len())); caster.inflate(&shapes, &casts, bounds, inflate_options(p), view) } else { let mut added = vec![]; for ((_, _, area, rule, _, _), ink) in parts.iter().zip(&inks) { + #[cfg(test)] + SOLIDS_BUILT.with(|n| n.set(n.get() + usize::from(ink.opacity > 0.0))); added.push(if ink.opacity > 0.0 { caster.extrude(area, *rule, bounds, extrude_options(p), view) } else { Ok(0..0) }); } added @@ -1418,6 +1510,76 @@ fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result(id: &str, p: &Value, shapes: &'a [Profile], built: Vec>) -> Result>, String> { + if id == CLASSIC_EXTRUDE || id == CLASSIC_ROTATE { + return Ok(None); + } + let (Some(settings), Some(b)) = (shadow::options(p), union_bounds(shapes)) else { return Ok(None) }; + let view = view_options(p); + let mut caster = vectorcraft_three_d::ShadowCaster::new(); + let mut cast: Vec = vec![]; + let ink = |item: &AppearanceItem, member: f32| { + let (_, opacity, blend) = paint_of(item, member); + shadow::Ink { opacity, blend } + }; + if id == ROTATE { + let items: Vec<(&Profile, &AppearanceItem)> = shapes.iter().flat_map(|s| s.items.iter().map(move |item| (s, item))).collect(); + if items.len() != built.len() { + return cast_shadow(id, p, shapes); + } + for ((s, item), kept) in items.into_iter().zip(built) { + let ink = ink(item, s.opacity); + if ink.opacity <= 0.0 { + continue; + } + let faces = match kept { + Some(kept) => caster.add_solid(kept)?, + None => { + let (area, rule) = region(&s.path, s.rule, item); + #[cfg(test)] + SOLIDS_BUILT.with(|n| n.set(n.get() + 1)); + caster.plane(&area, rule, b, view)? + } + }; + cast.push((s.scopes.as_slice(), ink, faces)); + } + return Ok(Some((caster, settings, cast))); + } + let (parts, bounds) = solid_parts(shapes, b); + let inks: Vec = parts.iter().map(|(item, member, ..)| ink(item, *member)).collect(); + if parts.len() != built.len() || (id == INFLATE && inks.iter().zip(&built).any(|(ink, kept)| ink.opacity > 0.0 && kept.is_none())) { + return cast_shadow(id, p, shapes); + } + for (((item, _, area, rule, scopes, _), ink), kept) in parts.iter().zip(inks).zip(built) { + if ink.opacity <= 0.0 { + continue; + } + let faces = match kept { + Some(kept) => caster.add_solid(kept), + None => { + #[cfg(test)] + SOLIDS_BUILT.with(|n| n.set(n.get() + 1)); + caster.extrude(area, *rule, bounds, extrude_options(p), view) + } + }; + // A stroke whose own solid is past the limits is left out; past the shadow's limit for all + // the solids together, the shadow is refused. + let faces = match faces { + Ok(faces) => faces, + Err(e) if matches!(item, AppearanceItem::Stroke(_)) && e != vectorcraft_three_d::TOO_COMPLEX_SHADOW => continue, + Err(e) => return Err(e), + }; + cast.push((*scopes, ink, faces)); + } + Ok(Some((caster, settings, cast))) +} + /// The faces a shadow is cast from, its settings, and the faces of each solid of visible art with /// its member's scopes and ink ([`cast_shadow`]). type Cast<'a> = (vectorcraft_three_d::ShadowCaster, vectorcraft_three_d::Shadow, Vec>); @@ -1476,31 +1638,31 @@ fn masks_surface(paint: &Paint, colored: bool) -> bool { colored && crate::lighting::opaque_paint(paint).1.is_some() } +/// A graphic of [`placed_graphics`]: the index of the first surface of the solids that share it, +/// the index of the surface it is drawn right after, its face and its art. +type Placement = (usize, usize, PlanarFace, Arc); + /// The graphics of the solids `filled` ([`graphic_art`]), each with the index of the surface it is /// drawn right after (the last of those solids holding its face) and its face. Solids in a run -/// with the same opacity and blending mode share their graphics. With `per_member` -/// (a member's opacity mask or blending mode applies to its surfaces) each member's solids get -/// graphics of their own, clipped to that member's caps, so they stay in that member's scopes. -/// All the groups share one limit on the path elements drawn: once it is reached, later groups -/// draw no graphics. -fn placed_graphics( - doc: Option<&Document>, - id: NodeId, - effect: (&str, &Value), - bounds: Rect, - filled: &[Filled], - per_member: bool, -) -> Vec<(usize, PlanarFace, Arc)> { +/// with the same opacity and blending mode share their graphics, one on each face. With +/// `per_member` (a member's opacity mask or blending mode applies to its surfaces) each member's +/// solids get graphics of their own, clipped to that member's caps, so they stay in that member's +/// scopes. All the groups share one limit on the path elements drawn: once it is reached, later +/// groups draw no graphics. +fn placed_graphics(doc: Option<&Document>, id: NodeId, effect: (&str, &Value), bounds: Rect, filled: &[Filled], per_member: bool) -> Vec { let mut groups: Vec> = vec![]; for f in filled { // Solids whose fills or strokes differ in opacity or blending mode get graphics of their - // own, each drawn as its fill or stroke is. A solid whose surface carries an opacity mask - // gets its own too, which takes that mask ([`with_graphics`]). A solid joins only the - // group of the solid before it, so a graphic is never drawn past a solid painted between. - let joins = |first: &Filled| { - (!per_member || first.member == f.member) && first.opacity == f.opacity && first.blend == f.blend && !first.masked && !f.masked + // own, each drawn as its fill or stroke is. One member's solids share their graphics + // whether or not their surfaces carry an opacity mask, and each graphic takes the mask of + // the surface it is drawn after ([`with_graphics`]). Solids of different members share + // them only when neither surface carries a mask. A solid joins only the group of the solid + // before it, so a graphic is never drawn past a solid painted between. + let joins = |g: &&Filled| { + let member = g.member == f.member; + (member || !per_member && !g.masked && !f.masked) && g.opacity == f.opacity && g.blend == f.blend }; - match groups.last_mut().filter(|g| g.first().is_some_and(|first| joins(first))) { + match groups.last_mut().filter(|g| g.iter().all(joins)) { Some(g) => g.push(f), None => groups.push(vec![f]), } @@ -1509,12 +1671,13 @@ fn placed_graphics( let mut elements = 0usize; for group in groups { let caps: Vec<&Facet> = group.iter().flat_map(|f| &f.caps).collect(); + let first = group.first().map_or(0, |f| f.at); let opacity = group.first().map_or(1.0, |f| f.opacity); let blend = group.first().map_or(BlendMode::Normal, |f| f.blend); for (face, mut art) in graphic_art(doc, id, effect, bounds, &caps, opacity, &mut elements) { if let Some(f) = group.iter().rev().find(|f| f.caps.iter().any(|c| c.end == Some(face))) { Arc::make_mut(&mut art).blend = blend; - out.push((f.at, face, art)); + out.push((first, f.at, face, art)); } } } @@ -1526,23 +1689,19 @@ fn placed_graphics( type BuiltSurface<'s> = (Vec, Node, &'s [Scope], Vec>); /// [`with_graphics`] of built surfaces, each drawn whole. -fn whole_surfaces<'s>(surfaces: Vec>, arts: &[(usize, PlanarFace, Arc)]) -> Vec<(&'s [Scope], Arc)> { +fn whole_surfaces<'s>(surfaces: Vec>, arts: &[Placement]) -> Vec<(&'s [Scope], Arc)> { with_graphics(surfaces.into_iter().map(|(_, s, scopes, _)| (scopes, Arc::new(s))).collect(), 0, arts) } /// `surfaces` (those from index `first`) drawn whole, each with its scopes, and the graphics `arts` /// ([`placed_graphics`]) of those surfaces each right after its surface, with that surface's scopes /// and its opacity mask (a gradient's transparency), so a graphic is hidden where its cap is. -fn with_graphics<'s>( - surfaces: Vec<(&'s [Scope], Arc)>, - first: usize, - arts: &[(usize, PlanarFace, Arc)], -) -> Vec<(&'s [Scope], Arc)> { +fn with_graphics<'s>(surfaces: Vec<(&'s [Scope], Arc)>, first: usize, arts: &[Placement]) -> Vec<(&'s [Scope], Arc)> { let mut out = Vec::with_capacity(surfaces.len() + arts.len()); for (k, (scopes, s)) in surfaces.into_iter().enumerate() { let mask = s.extras().mask.clone(); out.push((scopes, s)); - out.extend(arts.iter().filter(|(at, ..)| *at == first + k).map(|(.., art)| { + out.extend(arts.iter().filter(|(_, at, ..)| *at == first + k).map(|(.., art)| { let mut art = art.clone(); if let Some(mask) = &mask { Arc::make_mut(&mut art).extras_mut().mask = Some(mask.clone()); @@ -1559,8 +1718,10 @@ fn seen_ends(f: &[Facet]) -> impl Iterator { } /// [`art_for`] without the shadow: the solids' surfaces, with the graphics mapped onto their planar -/// faces drawn right after the last of the solids' surfaces that holds that face. -fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile]) -> Option>> { +/// faces drawn right after the last of the solids' surfaces that holds that face. With `cast`, each +/// solid built also keeps the faces its shadow is cast from, from the same build, in the order the +/// solids are built ([`cast_built`]); `None` for a stroke's solid left out of the art. +fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile], cast: bool) -> Option { let b = union_bounds(shapes)?; let p = crate::merged_params(&fx.id, &fx.params); let classic = fx.id == CLASSIC_EXTRUDE || fx.id == CLASSIC_ROTATE; @@ -1575,11 +1736,15 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile // the centre of theirs), so they stay together. let mut out = vec![]; let mut filled = vec![]; + let mut built = vec![]; for (member, s) in shapes.iter().enumerate() { for item in &s.items { let (paint, opacity, blend) = paint_of(item, s.opacity); let (area, rule) = region(&s.path, s.rule, item); - let f = facets(ROTATE, &area, rule, b, &p).ok()?; + #[cfg(test)] + SOLIDS_BUILT.with(|n| n.set(n.get() + 1)); + let (f, faces) = facets_and_faces(ROTATE, &area, rule, b, &p, cast).ok()?; + built.push(faces); if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(&f, &paint, colored), &paint) { return None; } @@ -1596,19 +1761,23 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile } let arts = placed_graphics(doc, n.id, (ROTATE, &p), b, &filled, masks); let out = with_graphics(out, 0, &arts); - return Some(if masks { masked(n.id, out) } else { out.into_iter().map(|(_, s)| s).collect() }); + return Some((if masks { masked(n.id, out) } else { out.into_iter().map(|(_, s)| s).collect() }, built)); } let (parts, bounds) = solid_parts(shapes, b); let mut solids = vec![]; - for ((item, opacity, _, _, scopes, member), f) in parts.iter().zip(built_solids(&fx.id, &p, &parts, bounds, MAX_OBJECT_FACES)) { + let mut built = vec![]; + for ((item, opacity, _, _, scopes, member), f) in parts.iter().zip(built_solids_cast(&fx.id, &p, &parts, bounds, MAX_OBJECT_FACES, cast)) { let item: &AppearanceItem = item; match f { - Ok(Some(f)) if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(&f, paint_ref(item), colored), paint_ref(item)) => { + Ok(Some((f, _))) if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(&f, paint_ref(item), colored), paint_ref(item)) => { return None; } - Ok(Some(f)) => solids.push((item, *opacity, *scopes, f, *member)), + Ok(Some((f, faces))) => { + solids.push((item, *opacity, *scopes, f, *member)); + built.push(faces); + } // A stroke's outline past the limits is left out; the fill's solid still draws. - Ok(None) => {} + Ok(None) => built.push(None), // A loaded file or a shape edited past the limits (its own, or those of the object's // solids together) keeps drawing its source path instead of failing the frame; // commands validate the same evaluator and report its errors. @@ -1688,6 +1857,10 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile let split = split && solids.iter().filter(|(item, _, _, f, _)| composite(item, f)).map(|(.., f, _)| f.len()).sum::() <= MAX_FACE_COMPOSITES; let members: Vec = solids.iter().map(|s| s.4).collect(); + // Which surfaces lie over an underlay of their facets, in one order or whole + // ([`in_one_order`], [`underlaid_surface`]). + let seals: Vec = solids.iter().map(|(.., f, _)| underlaid(f, colored)).collect(); + let seal = |range: std::ops::Range| seals.get(range).is_some_and(|s| s.iter().any(|s| *s)); let surfaces: Vec = solids .into_iter() .map(|(item, member, scopes, f, shape)| { @@ -1723,19 +1896,37 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile run.push(s); } let flat = run.iter().all(|s| plain(s) && s.1.opacity >= 1.0 && s.1.blend == BlendMode::Normal && s.1.extras().mask.is_none()); + let range = first..first + run.len(); if ordered(member) && flat { let scopes = run.first().map_or(&[][..], |s| s.2); - out.push((scopes, Arc::new(Node::group(n.id, in_one_order(n.id, run, first, &arts, sealed))))); + let seals = seals.get(range).unwrap_or_default(); + out.push((scopes, Arc::new(Node::group(n.id, in_one_order(n.id, run, first, &arts, sealed, seals))))); } else { - out.extend(with_graphics(run.into_iter().map(|(_, s, scopes, _)| (scopes, Arc::new(s))).collect(), first, &arts)); + let run = run.into_iter().zip(range).map(|((_, s, scopes, _), k)| (scopes, Arc::new(underlaid_surface(n.id, s, seal(k..k + 1))))); + out.extend(with_graphics(run.collect(), first, &arts)); } } - return Some(masked(n.id, out)); + return Some((masked(n.id, out), built)); } if !opaque || !surfaces.iter().all(plain) { - return Some(whole_surfaces(surfaces, &arts).into_iter().map(|(_, s)| s).collect()); + let surfaces = + surfaces.into_iter().enumerate().map(|(k, (d, s, scopes, e))| (d, underlaid_surface(n.id, s, seal(k..k + 1)), scopes, e)).collect(); + return Some((whole_surfaces(surfaces, &arts).into_iter().map(|(_, s)| s).collect(), built)); } - Some(vec![Arc::new(Node::group(n.id, in_one_order(n.id, surfaces, 0, &arts, sealed)))]) + Some((vec![Arc::new(Node::group(n.id, in_one_order(n.id, surfaces, 0, &arts, sealed, &seals)))], built)) +} + +/// A plain `surface` ([`surface`]: a group of its facets) over an underlay of its facets when +/// `seal`, keeping the surface's opacity, blend mode and opacity mask. +fn underlaid_surface(id: NodeId, surface: Node, seal: bool) -> Node { + let NodeKind::Group { children, clip: false } = &surface.kind else { return surface }; + let Some(mut out) = seal.then(|| crate::lighting::sealed(id, children)).flatten() else { return surface }; + out.opacity = surface.opacity; + out.blend = surface.blend; + if let Some(mask) = surface.extras().mask.clone() { + out.extras_mut().mask = Some(mask); + } + out } /// The faces of `surfaces` (plain groups of their faces, [`surfaces_for`]'s from index `first`) in @@ -1743,9 +1934,11 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile /// surfaces right after the last face it is drawn on, of the surfaces that share it. A surface in a gradient with transparent stops /// carries an opacity mask: its faces go in runs ([`in_runs`]), each carrying the mask, and each of /// its graphics carries the mask too ([`with_graphics`]), so a graphic is hidden where its cap is. -fn in_one_order(id: NodeId, surfaces: Vec>, first: usize, arts: &[(usize, PlanarFace, Arc)], sealed: bool) -> Vec> { +/// The faces of the surfaces that `seals` marks lie over underlays of themselves +/// ([`underlaid_runs`], [`underlaid_surface`]). +fn in_one_order(id: NodeId, surfaces: Vec>, first: usize, arts: &[Placement], sealed: bool, seals: &[bool]) -> Vec> { let masks: Vec>> = surfaces.iter().map(|(_, s, _, _)| s.extras().mask.clone()).collect(); - let arts: Vec<&(usize, PlanarFace, Arc)> = arts.iter().filter(|(at, ..)| (first..first + surfaces.len()).contains(at)).collect(); + let arts: Vec<&Placement> = arts.iter().filter(|(_, at, ..)| (first..first + surfaces.len()).contains(at)).collect(); let (mut placed, mut faces, mut ends) = (vec![], vec![], vec![]); for (surface, (depths, s, _, e)) in surfaces.into_iter().enumerate() { if let NodeKind::Group { children, .. } = s.kind { @@ -1756,24 +1949,18 @@ fn in_one_order(id: NodeId, surfaces: Vec>, first: usize, arts: } let order = draw_order(&placed, sealed); // Each graphic goes right after the last of the faces it is drawn on, among the surfaces that - // share it ([`placed_graphics`]): a masked surface's own, or else the run of surfaces without a - // mask that ends at its surface. + // share it ([`placed_graphics`]): those from the first of them to its own. let last: Vec> = arts .iter() - .map(|(at, face, _)| { - let at = at - first; - let from = if masks.get(at).is_some_and(Option::is_some) { - at - } else { - masks.get(..at).and_then(|before| before.iter().rposition(Option::is_some)).map_or(0, |k| k + 1) - }; + .map(|(from, at, face, _)| { + let (from, at) = (from.saturating_sub(first), at - first); order.iter().rposition(|k| ends.get(*k).copied().flatten().is_some_and(|(surface, end)| end == *face && (from..=at).contains(&surface))) }) .collect(); let mut drawn: Vec<(usize, Arc)> = Vec::with_capacity(order.len() + arts.len()); for (at, k) in order.into_iter().enumerate() { drawn.extend(faces.get_mut(k).and_then(Option::take)); - drawn.extend(last.iter().zip(&arts).filter(|(l, _)| **l == Some(at)).map(|(_, (surface, .., art))| { + drawn.extend(last.iter().zip(&arts).filter(|(l, _)| **l == Some(at)).map(|(_, (_, surface, _, art))| { let mut art = art.clone(); if let Some(mask) = masks.get(surface - first).cloned().flatten() { Arc::make_mut(&mut art).extras_mut().mask = Some(mask); @@ -1782,7 +1969,46 @@ fn in_one_order(id: NodeId, surfaces: Vec>, first: usize, arts: (masks.len(), art) })); } - if masks.iter().any(Option::is_some) { in_runs(id, drawn, &masks) } else { drawn.into_iter().map(|(_, face)| face).collect() } + let takes_underlay = |surface: usize| seals.get(surface) == Some(&true); + if masks.iter().any(Option::is_some) { + // The faces of a surface without a mask are sealed run by run before the masked surfaces' + // faces go in runs of their own, each holding one surface's faces, sealed with its mask. + let unmasked = underlaid_runs(id, drawn, |s| takes_underlay(s) && masks.get(s).is_some_and(Option::is_none)); + return in_runs(id, unmasked, &masks) + .into_iter() + .map(|run| match &run.kind { + NodeKind::Group { clip: false, .. } if seals.iter().any(|s| *s) && run.extras().mask.is_some() => { + Arc::new(underlaid_surface(id, (*run).clone(), true)) + } + _ => run, + }) + .collect(); + } + underlaid_runs(id, drawn, takes_underlay).into_iter().map(|(_, face)| face).collect() +} + +/// `faces` in their drawing order, each with the index of its surface. Each run of consecutive +/// faces of one surface that `seal` takes lies over an underlay of its own faces, clipped to their +/// outline ([`crate::lighting::sealed`]), so no underlay reaches under another surface's faces or a +/// graphic drawn between them. A sealed run keeps its surface's index. +fn underlaid_runs(id: NodeId, faces: Vec<(usize, Arc)>, seal: impl Fn(usize) -> bool) -> Vec<(usize, Arc)> { + let mut out = Vec::with_capacity(faces.len()); + let mut run: Vec> = vec![]; + let mut faces = faces.into_iter().peekable(); + while let Some((surface, face)) = faces.next() { + run.push(face); + if faces.peek().is_some_and(|(next, _)| *next == surface) { + continue; + } + match seal(surface).then(|| crate::lighting::sealed(id, &run)).flatten() { + Some(sealed) => { + out.push((surface, Arc::new(sealed))); + run.clear(); + } + None => out.extend(run.drain(..).map(|face| (surface, face))), + } + } + out } /// `faces` in their back-to-front order, each with the index of its surface, where some surfaces diff --git a/crates/effects/src/solids/classic.rs b/crates/effects/src/solids/classic.rs index 23d8d0ffad..29c05406a2 100644 --- a/crates/effects/src/solids/classic.rs +++ b/crates/effects/src/solids/classic.rs @@ -192,6 +192,12 @@ fn shaded(c: Color, tone: f64, spec: f64, shade: Option) -> Color { Color::rgb(r, g, b) } +/// The width of the stroke [`surface`] draws around `face` with parameters `p`: a wire edge on +/// Wireframe, else the seam between faces. +pub(crate) fn stroke_width(face: &Facet, p: &Value) -> f64 { + if classic_shading(p).surface == ClassicSurface::Wireframe { WIRE } else { super::seam_width(face) } +} + /// One solid's faces in paint `paint`, as a group with the paint's opacity and blend mode, one child /// for each facet: the edges of the faces on Wireframe, else each face filled in its paint shaded by /// its tone and highlight. A gradient with transparent stops is shaded opaque and then masked by @@ -213,7 +219,7 @@ pub(crate) fn surface(n: &Node, facets: Vec, source: &Paint, opacity: f32 } let (tone, spec) = shading.tone(face.normal, &lights); // A narrow stroke of the face's own paint closes the hairline seams between faces. - let seam = (face.thickness() / 2.0).clamp(0.05, 0.75); + let seam = super::seam_width(&face); let items = match paint.color() { // Unshaded (No Shading, no shading color, or a face in full light) with no // highlight: the paint itself, its color space and swatch kept. diff --git a/crates/effects/src/solids/tests.rs b/crates/effects/src/solids/tests.rs index 8222484c20..945eb639aa 100644 --- a/crates/effects/src/solids/tests.rs +++ b/crates/effects/src/solids/tests.rs @@ -535,14 +535,53 @@ fn a_colored_inflate_in_gradients_draws_its_faces_in_one_order() { assert_eq!(drawn(&solid, Some(colored)).0, 1); } +/// The faces `run` stands for: a run of faces over an underlay of themselves ([`crate::lighting::sealed`]: +/// a clip and a group of the underlay's copies followed by the faces) gives its faces, any other +/// node gives itself. +fn unsealed(run: &Arc) -> Vec> { + if let NodeKind::Group { clip: true, children } = &run.kind + && let [clip, inner] = children.as_slice() + && matches!(clip.kind, NodeKind::Path { .. }) + && let NodeKind::Group { clip: false, children: kids } = &inner.kind + && !kids.is_empty() + && kids.len() % 2 == 0 + { + let (under, faces) = kids.split_at(kids.len() / 2); + let underlay = |k: &Arc| match &k.kind { + NodeKind::Group { clip, .. } => *clip, + _ => k.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(s) if s.width == crate::lighting::UNDERLAY_SEAM)), + }; + if under.first().is_some_and(underlay) { + return faces.to_vec(); + } + } + vec![run.clone()] +} + +/// The bounds of every face under `n`, a sealed run's faces one by one ([`unsealed`]). +fn face_bounds_under(n: &Arc, out: &mut Vec) { + let faces = unsealed(n); + if faces.len() != 1 || !Arc::ptr_eq(&faces[0], n) { + out.extend(faces.iter().map(|f| drawn_face_bounds(f))); + return; + } + if let NodeKind::Group { clip: true, .. } = &n.kind { + out.push(drawn_face_bounds(n)); + } + for child in n.children().into_iter().flatten() { + face_bounds_under(child, out); + } +} + /// The bounds of face `f` of 3D art: its path's, or for a clipped colored composite -/// ([`crate::lighting::facet_art`]) its color cover's, which is the face's bounds grown by 1 pt. +/// ([`crate::lighting::facet_art`]) its color cover's, which is the face's bounds grown by 2 pt (a +/// point past the seam and half the underlay's seam). fn drawn_face_bounds(f: &Node) -> Rect { match &f.kind { NodeKind::Path { .. } => f.path_data().and_then(PathData::bounds).unwrap(), NodeKind::Group { clip: true, children } => { let cover = &children[1].children().unwrap()[0]; - cover.path_data().and_then(PathData::bounds).unwrap().inflate(-1.0, -1.0) + cover.path_data().and_then(PathData::bounds).unwrap().inflate(-2.0, -2.0) } _ => panic!("a face is a path or a clipped composite"), } @@ -587,7 +626,7 @@ fn colored_solid_fills_and_strokes_share_face_depth_order() { let art = solid_art(&with).unwrap(); let surfaces = art.children().unwrap(); assert_eq!(surfaces.len(), 1, "{what}: one order"); - let faces = surfaces[0].children().unwrap(); + let faces: Vec> = surfaces[0].children().unwrap().iter().flat_map(unsealed).collect(); assert_eq!(faces.len(), parts.len(), "{what}: one face per facet"); for (k, (face, (facet, ..))) in faces.iter().zip(&parts).enumerate() { let (a, b) = (drawn_face_bounds(face), facet.path().bounds().unwrap()); @@ -616,11 +655,9 @@ fn colored_solid_fills_and_strokes_share_face_depth_order() { g.appearance.effects.push(fx(id, params.clone())); let bounds = |art: &Node| { let mut out = vec![]; - art.walk(&mut |n| { - if let NodeKind::Group { clip: true, .. } = &n.kind { - out.push(drawn_face_bounds(n)); - } - }); + for child in art.children().into_iter().flatten() { + face_bounds_under(child, &mut out); + } out }; let (plain, scoped) = (solid_art(&plain).unwrap(), solid_art(&g).unwrap()); @@ -637,6 +674,89 @@ fn colored_solid_fills_and_strokes_share_face_depth_order() { assert!(whole_misdrawn > 0, "whole surfaces show farther faces"); } +/// Under a colored light, the faces of an Inflate in gradients, in one order, lie over underlays +/// run by run: each run of consecutive faces of one surface (the fill's or the dashed stroke's) +/// over an underlay of its own faces, so no underlay reaches under the other surface's faces. +#[test] +fn a_colored_inflate_in_gradients_lies_over_underlays_of_each_surfaces_runs() { + use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let gradient = |c: Color| { + Paint::Gradient(Box::new(GradientPaint::new(Gradient::new( + GradientKind::Linear, + vec![GradientStop::new(0.0, c), GradientStop::new(1.0, Color::WHITE)], + )))) + }; + let mut n = stroked(&letter_c()); + for item in &mut n.appearance.items { + match item { + AppearanceItem::Fill(f) => f.paint = gradient(RED), + AppearanceItem::Stroke(s) => { + s.paint = gradient(BLUE); + s.dash = Some(vectorcraft_doc::Dash { pattern: vec![12.0, 12.0], offset: 0.0, align_corners: false }); + } + } + } + let p = json!({"rotationX": -20, "rotationY": -40, "rotationZ": 0, "depth": 60}); + let cut = drawn_parts(&n, INFLATE, &p).len(); + let mut lit = p.clone(); + lit["lights"] = json!([{"color": "#ff8080"}]); + n.appearance.effects.push(fx(INFLATE, lit)); + // Which surface a face belongs to, by the first stop of its paint (a composed face's own paint, + // or a path face's shaded one): red for the fill's, blue for the stroke's. + fn surface_of(face: &Node) -> Option { + let item = match &face.kind { + NodeKind::Path { .. } => face.appearance.items.first()?, + _ => face.children()?.get(1)?.children()?.first()?.appearance.items.first()?, + }; + let Paint::Gradient(g) = item.paint() else { return None }; + let [r, _, b] = g.gradient.stops.first()?.color.to_rgb(); + Some(if r > b { RED } else { BLUE }) + } + // The faces in `order`, and the surface of each run over an underlay, looking into the groups + // that carry a surface's opacity mask. + fn runs(order: &[Arc], faces: &mut usize, surfaces: &mut Vec) { + for child in order { + let NodeKind::Group { children, clip } = &child.kind else { + assert!(surface_of(child).is_some(), "a face"); + *faces += 1; + continue; + }; + if !clip { + assert!(child.extras().mask.is_some(), "a masked run"); + runs(children, faces, surfaces); + continue; + } + // A composed face isolates its colors; a run's faces are not isolated together. + if children[1].isolate { + assert!(surface_of(child).is_some(), "a composed face"); + *faces += 1; + continue; + } + let stack = children[1].children().unwrap(); + let (under, own) = stack.split_at(stack.len() / 2); + assert_eq!(under.len(), own.len(), "one underlay face for each face"); + let colors: Vec<_> = own.iter().map(|f| surface_of(f).unwrap()).collect(); + assert!(colors.iter().all(|c| *c == colors[0]), "a run holds one surface's faces"); + surfaces.push(colors[0]); + *faces += own.len(); + } + } + let (mut faces, mut surfaces) = (0, vec![]); + runs(solid_art(&n).unwrap().children().unwrap()[0].children().unwrap(), &mut faces, &mut surfaces); + assert!(faces >= cut, "{faces} faces, {cut} under a white light, whose cells are not triangulated"); + assert!(surfaces.contains(&RED) && surfaces.contains(&BLUE), "{surfaces:?}"); + // With transparent stops in the fill's gradient, the fill's faces go in masked runs; the + // stroke's faces, without a mask, still lie over underlays of their own runs. + if let Some(AppearanceItem::Fill(f)) = n.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Fill(_))) + && let Paint::Gradient(g) = &mut f.paint + { + g.gradient.stops.iter_mut().for_each(|s| s.opacity = 0.5); + } + let (mut faces, mut surfaces) = (0, vec![]); + runs(solid_art(&n).unwrap().children().unwrap()[0].children().unwrap(), &mut faces, &mut surfaces); + assert!(faces >= cut && surfaces.contains(&RED) && surfaces.contains(&BLUE), "{faces} faces, {surfaces:?}"); +} + /// A face of a stroke that leaves gaps passing through the plane of its fill's wall where they /// overlap is cut along the line where their depths meet, into the piece in front of the wall and /// the piece behind it; a face on one side of the wall, another shape's stroke, a covering stroke @@ -724,7 +844,7 @@ fn cutting_stays_within_the_face_limit_and_the_paint_allowance() { let items = stroked(&letter_c()).appearance.items.clone(); let stroke = items.iter().find(|i| matches!(i, AppearanceItem::Stroke(_))).unwrap(); let mut one = 0usize; - crate::revolve::paint_copies_add(&mut one, 6, paint_ref(stroke)); + crate::revolve::paint_copies_add(&mut one, MAX_FACET_COPIES, paint_ref(stroke)); let max = crate::revolve::MAX_PAINT_COPIES; assert_eq!(cut_room(items.iter(), 10, 0), (MAX_OBJECT_FACES - 10).min(max / one)); assert_eq!(cut_room(items.iter(), MAX_OBJECT_FACES + 5, 0), 0); @@ -995,6 +1115,44 @@ fn the_check_builds_the_profile_of_a_shape_with_no_fill() { } } +/// A filled shape is checked about the bounds the effect draws its solid about, which take in the +/// strokes beside it. A shape of many small curves is too complex for Extrude & Bevel about the +/// shapes' own bounds, where its curves are sampled more finely, and passes about the bounds of a +/// wide stroke in its group, as its solid draws there. +#[test] +fn the_check_builds_a_filled_shape_about_the_bounds_its_solid_draws_about() { + // 900 curves about (100, 100), each bulging 1 pt out from a side of a polygon 80 pt across. + let corners = 900; + let center = Point::new(100.0, 100.0); + let corner = |k: usize| { + let (s, c) = (k as f64 * std::f64::consts::TAU / corners as f64).sin_cos(); + Point::new(center.x + 40.0 * c, center.y + 40.0 * s) + }; + let mut b = BezPath::new(); + b.move_to(corner(0)); + for k in 0..corners { + let (p0, p3) = (corner(k), corner(k + 1)); + let out = p0.midpoint(p3) - center; + let out = out / out.hypot(); + b.curve_to(p0 + (p3 - p0) / 3.0 + out, p0 + (p3 - p0) * (2.0 / 3.0) + out, p3); + } + b.close_path(); + let filled = Node::path(NodeId(1), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(RED), Paint::None, 0.0)); + let mut line = BezPath::new(); + line.move_to((80.0, 100.0)); + line.line_to((120.0, 100.0)); + let mut wide = Node::path(NodeId(2), PathData::from_bezpath(&line), Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 2000.0)); + wide.appearance.items.retain(|i| matches!(i, AppearanceItem::Stroke(_))); + let p = json!({"bevel": "rounded", "bevelRepeat": 6}); + let (path, rule) = profile(&filled).unwrap(); + let own = path.bounds().unwrap().union(wide.path_data().unwrap().bounds().unwrap()); + assert_eq!(facets(EXTRUDE, &path, rule, own, &p).map(|_| ()), Err(vectorcraft_three_d::TOO_COMPLEX_SOLID.to_string()), "about its own bounds"); + let mut g = Node::group(NodeId(9999), vec![Arc::new(filled), Arc::new(wide)]); + assert_eq!(validate_solid(&g, EXTRUDE, &p), Ok(())); + g.appearance.effects.push(fx(EXTRUDE, p)); + assert!(solid_art(&g).is_some(), "the solid draws"); +} + /// A convex polygon of `corners` corners about (20,000, 20,000), filled red, with no stroke. fn polygon_node(id: u64, corners: usize) -> Node { let points: Vec = (0..corners) @@ -1595,12 +1753,14 @@ fn a_colored_solid_face_on_its_own_keeps_the_composites_colors() { assert_eq!(one[0], paint, "the paint"); // The composite: its paint cover, then each channel's black backdrop and the face's ramp. let all_fills = fills(&batch); - let ramps: Vec<&Paint> = all_fills.iter().filter(|p| **p != Paint::solid(Color::BLACK)).skip(1).collect(); + let mut ramps: Vec<&Paint> = all_fills.iter().filter(|p| **p != Paint::solid(Color::BLACK)).skip(1).collect(); + // Each channel's ramp is drawn twice, in the underlay and in the facet itself. + ramps.dedup(); assert_eq!(all_fills.first(), Some(&paint)); assert_eq!(ramps, one.iter().skip(1).collect::>(), "the same light ramps"); // The single face's clip holds its seam: the clip reaches past the facet by half the seam. let seam = (face.thickness() / 2.0).clamp(0.05, 0.75); - let widths: Vec = paints(&batch).into_iter().filter_map(|(_, w)| w).filter(|w| *w > 0.0).collect(); + let widths: Vec = paints(&batch).into_iter().filter_map(|(_, w)| w).filter(|w| *w > 0.0 && *w != crate::lighting::UNDERLAY_SEAM).collect(); assert!(widths.len() == 3 && widths.iter().all(|w| (w - seam).abs() < 1e-12), "{widths:?}"); let NodeKind::Group { children, .. } = &single.kind else { panic!("a clip group") }; let (clip, facet) = (children[0].path_data().and_then(PathData::bounds).unwrap(), face.path().bounds().unwrap()); diff --git a/crates/effects/src/solids/tests_graphics.rs b/crates/effects/src/solids/tests_graphics.rs index e0935a43e7..f0da6b992b 100644 --- a/crates/effects/src/solids/tests_graphics.rs +++ b/crates/effects/src/solids/tests_graphics.rs @@ -617,10 +617,11 @@ fn a_solid_in_a_transparent_gradient_keeps_its_graphic() { }; // The graphic carries the cap's mask, so it is hidden where the gradient is transparent. assert_eq!(masks(&art), vec![true]); - // With an opaque stroke drawn after the fill, the fill's cap keeps a masked graphic of its own - // and the stroke's outline gets an unmasked one. + // With an opaque stroke drawn after the fill, the fill and the stroke share one graphic, drawn + // after the stroke's cap as for a fill without a mask, and it takes the stroke's surface, + // which carries no mask. n.appearance.items.push(AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 4.0))); - assert_eq!(masks(&solid_art_in(Some(&d), &n).unwrap()), vec![true, false]); + assert_eq!(masks(&solid_art_in(Some(&d), &n).unwrap()), vec![false]); } /// The paths of `art`'s faces in drawing order (a face lit by a colored light is a clip group: its @@ -649,23 +650,56 @@ fn face_paths(art: &Node) -> Vec { out } +/// The graphics in `art` (clip groups of solid-color paths), in drawing order: for each, how many +/// faces ([`face_paths`]) are drawn before it, whether it carries an opacity mask, its opacity and +/// its blending mode. +fn graphic_places(art: &Node) -> Vec<(usize, bool, f32, BlendMode)> { + fn walk(n: &Node, faces: &mut usize, out: &mut Vec<(usize, bool, f32, BlendMode)>) { + match &n.kind { + NodeKind::Group { children, clip: true } => { + let graphic = children.get(1).is_some_and(|inner| match &inner.kind { + NodeKind::Group { children: paths, clip: false } => paths.iter().all(|p| { + p.path_data().is_some() + && p.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(f) if f.paint.color().is_some())) + }), + _ => false, + }); + if graphic { + out.push((*faces, n.extras().mask.is_some(), n.opacity, n.blend)); + } else if children.first().and_then(|c| c.path_data()).is_some() { + *faces += 1; + } + } + NodeKind::Group { children, .. } => children.iter().for_each(|c| walk(c, faces, out)), + _ => *faces += usize::from(n.path_data().is_some()), + } + } + let mut out = vec![]; + walk(art, &mut 0, &mut out); + out +} + /// A turned solid in a gradient with transparent stops under a colored light, with a dashed stroke /// and a graphic, draws its fill's and its stroke's faces in the one order it draws them in without -/// the graphic, and the graphic keeps the cap's mask and goes after the fill's cap, not the stroke's. +/// the graphic, and draws the graphic once, where it goes in a gradient without transparent stops: +/// after the stroke's cap, without a mask. #[test] fn a_transparent_gradient_with_a_graphic_keeps_the_shared_face_order() { use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; let d = document(); - let mut stop = GradientStop::new(1.0, red()); - stop.opacity = 0.25; - let gradient = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, red()), stop])); - let solid = |graphics: Value| { + // A red gradient whose last stop has opacity `last`. + let gradient = |last: f32| { + let mut stop = GradientStop::new(1.0, red()); + stop.opacity = last; + GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, red()), stop])) + }; + let solid = |fill: &GradientPaint, graphics: Value| { let mut n = object( EXTRUDE, json!({"rotationX": -20.0, "rotationY": -40.0, "depth": 60.0, "shade": true, "lights": [{"color": "#ff8080"}], "graphics": graphics}), ); if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() { - f.paint = Paint::Gradient(Box::new(gradient.clone())); + f.paint = Paint::Gradient(Box::new(fill.clone())); } // A gradient stroke: a solid color under the colored light would be one composite. let blues = Gradient::new( @@ -677,54 +711,76 @@ fn a_transparent_gradient_with_a_graphic_keeps_the_shared_face_order() { n.appearance.items.push(AppearanceItem::Stroke(stroke)); solid_art_in(Some(&d), &n).unwrap() }; - let with = solid(json!([{"symbol": "Mark"}])); - let without = solid(json!([])); + let masked = gradient(0.25); + let with = solid(&masked, json!([{"symbol": "Mark"}])); + let without = solid(&masked, json!([])); assert!(face_paths(&without).len() > 20, "the faces are found"); assert_eq!(face_paths(&with), face_paths(&without), "the faces in one order"); - // The graphic is drawn on the fill's cap and on the stroke's (the clip groups holding the - // symbol's red square); the fill's, whose surface carries the mask, carries it too. - let mut masked = vec![]; - with.walk(&mut |c| { - if let NodeKind::Group { children, clip: true } = &c.kind - && let [_, inner] = children.as_slice() - && let NodeKind::Group { children: paths, clip: false } = &inner.kind - && paths.iter().any(|p| { - p.appearance.items.iter().any(|i| match i { - AppearanceItem::Fill(f) => f.paint.color().is_some_and(|c| c.to_rgb()[1] < 0.1 && c.to_rgb()[0] > 0.3), - AppearanceItem::Stroke(_) => false, - }) - }) - { - masked.push(c.extras().mask.is_some()); - } - }); - masked.sort_unstable(); - assert_eq!(masked, [false, true], "the fill's graphic carries the cap's mask"); - // The fill's graphic goes right after the fill's cap, so the dashes on the cap's edge, drawn - // after it, cover it. Drawn in order: the fill's graphic (the masked clip group), and each face, - // the fill's or the stroke's by its gradient's first stop (red or blue), with its bounds. - let mut drawn: Vec<(&str, Rect)> = vec![]; - with.walk(&mut |c| { - if let NodeKind::Group { children, clip: true } = &c.kind - && c.extras().mask.is_some() - && let Some(bounds) = children.first().and_then(|clip| clip.path_data()).and_then(PathData::bounds) - { - drawn.push(("graphic", bounds)); - } - let first_stop = c.appearance.items.iter().find_map(|i| match i { - AppearanceItem::Fill(f) => match &f.paint { - Paint::Gradient(g) => g.gradient.stops.first().map(|s| s.color.to_rgb()), - _ => None, - }, - AppearanceItem::Stroke(_) => None, - }); - if let (Some(rgb), Some(bounds)) = (first_stop, c.path_data().and_then(PathData::bounds)) { - drawn.push((if rgb[0] > rgb[2] { "fill" } else { "stroke" }, bounds)); - } - }); - let graphic = drawn.iter().position(|(kind, _)| *kind == "graphic").unwrap(); - let covering = |(kind, b): &(&str, Rect)| *kind == "stroke" && b.intersect(drawn[graphic].1).area() > 0.0; - assert!(drawn[graphic..].iter().any(covering), "a dash on the cap's edge is drawn over the fill's graphic"); + let mut mask = false; + with.walk(&mut |c| mask |= c.extras().mask.is_some()); + assert!(mask, "the fill's faces carry the gradient's mask"); + let opaque = solid(&gradient(1.0), json!([{"symbol": "Mark"}])); + assert_eq!(face_paths(&opaque), face_paths(&with)); + let places = graphic_places(&with); + assert_eq!(places.iter().map(|(_, mask, opacity, blend)| (*mask, *opacity, *blend)).collect::>(), [(false, 1.0, BlendMode::Normal)]); + assert_eq!(places, graphic_places(&opaque), "drawn where a fill without a mask draws it"); +} + +/// A plane in a gradient with transparent stops under a colored light draws its graphic with the +/// fill's mask, and with a dashed stroke draws it once, after the stroke, without a mask. +#[test] +fn a_plane_in_a_transparent_gradient_with_a_stroke_draws_its_graphic_once() { + use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let d = document(); + let mut stop = GradientStop::new(1.0, red()); + stop.opacity = 0.25; + let gradient = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, red()), stop])); + let mut n = object(ROTATE, json!({"shade": true, "lights": [{"color": "#ff8080"}], "graphics": [{"symbol": "Mark"}]})); + if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() { + f.paint = Paint::Gradient(Box::new(gradient)); + } + let places = graphic_places(&solid_art_in(Some(&d), &n).unwrap()); + assert_eq!(places.iter().map(|(_, mask, ..)| *mask).collect::>(), [true]); + let mut stroke = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 6.0); + stroke.dash = Some(vectorcraft_doc::Dash { pattern: vec![12.0, 12.0], offset: 0.0, align_corners: false }); + n.appearance.items.push(AppearanceItem::Stroke(stroke)); + let art = solid_art_in(Some(&d), &n).unwrap(); + let places = graphic_places(&art); + assert_eq!(places, [(face_paths(&art).len(), false, 1.0, BlendMode::Normal)], "one graphic, drawn after every face"); +} + +/// Members of a group share a graphic only when neither surface carries an opacity mask, while +/// one member's fill and stroke share theirs. +#[test] +fn members_in_transparent_gradients_keep_graphics_of_their_own() { + use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let d = document(); + let mut stop = GradientStop::new(1.0, red()); + stop.opacity = 0.25; + let gradient = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, red()), stop])))); + let gray = Paint::solid(Color::rgb(0.5, 0.5, 0.5)); + let (left, right) = (Rect::new(0.0, 0.0, 50.0, 100.0), Rect::new(50.0, 0.0, 100.0, 100.0)); + // Whether each graphic drawn on the group of `members` carries an opacity mask, in order. + let masks = |members: Vec| { + let mut group = Node::group(NodeId(3), members.into_iter().map(Arc::new).collect()); + let p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": true, "lights": [{"color": "#ff8080"}], "graphics": [{"symbol": "Mark", "scale": 1000.0}]}); + group.appearance.effects.push(crate::new_effect(EXTRUDE, &p).unwrap()); + let mut masks: Vec = graphic_places(&solid_art_in(Some(&d), &group).unwrap()).iter().map(|(_, mask, ..)| *mask).collect(); + masks.sort_unstable(); + masks + }; + assert_eq!(masks(vec![square(1, left, gradient.clone()), square(2, right, gradient.clone())]), [true, true]); + // With a dashed stroke, the first member's fill and stroke share one graphic, without a mask. + let mut stroked = square(1, left, gradient.clone()); + let mut stroke = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 6.0); + stroke.dash = Some(vectorcraft_doc::Dash { pattern: vec![12.0, 12.0], offset: 0.0, align_corners: false }); + stroked.appearance.items.push(AppearanceItem::Stroke(stroke)); + assert_eq!(masks(vec![stroked, square(2, right, gradient.clone())]), [false, true]); + // A member with a gray stroke listed before its fill in the gradient does not share its + // graphic with the gray member after it. + let mut layered = square(1, left, gradient); + layered.appearance.items.insert(0, AppearanceItem::Stroke(StrokeLayer::new(gray.clone(), 6.0))); + assert_eq!(masks(vec![layered, square(2, right, gray)]), [false, true]); } #[test] diff --git a/crates/effects/src/solids/tests_shadow.rs b/crates/effects/src/solids/tests_shadow.rs index 7e7d2e1595..4d62961612 100644 --- a/crates/effects/src/solids/tests_shadow.rs +++ b/crates/effects/src/solids/tests_shadow.rs @@ -223,3 +223,92 @@ fn expand_appearance_keeps_the_shadow_as_a_path() { assert!((after.x0 - before.x0 - 40.0).abs() < 1e-6, "{id}: {before:?} {after:?}"); } } + +/// A square filled red and stroked blue, its stroke as opaque as `stroke`. +fn stroked_square(id: u64, dx: f64, stroke: f32) -> Node { + let mut n = square_node(id, dx); + n.appearance = Appearance::basic(Paint::solid(RED), Paint::solid(Color::rgb(0.1, 0.2, 0.9)), 6.0).into(); + for item in &mut n.appearance.items { + if let AppearanceItem::Stroke(s) = item { + s.opacity = stroke; + } + } + n +} + +/// Objects with 3D effect `id` and its shadow on (`params`): a filled and stroked square, one whose +/// stroke is half transparent, one whose stroke is fully transparent, and a group of two members, +/// one of them at half opacity. +fn shadowed(id: &str, params: &Value) -> Vec { + let with = |mut n: Node| { + n.appearance.effects.push(crate::new_effect(id, params).unwrap()); + n + }; + let mut half = stroked_square(2, 200.0, 1.0); + half.opacity = 0.5; + let group = Node::group(NodeId(9), vec![Arc::new(stroked_square(1, 0.0, 1.0)), Arc::new(half)]); + vec![with(stroked_square(1, 0.0, 1.0)), with(stroked_square(1, 0.0, 0.5)), with(stroked_square(1, 0.0, 0.0)), with(group)] +} + +/// The settings the shadows of effect `id` are compared with: the defaults, turned with +/// perspective, and under a colored light, below the object for Extrude & Bevel, Inflate and +/// Rotate and behind it for Revolve. +fn shadow_settings(id: &str) -> [Value; 3] { + let position = if id == crate::REVOLVE { "behind" } else { "below" }; + [ + json!({"shadow": true}), + json!({"shadow": true, "rotationX": -25, "rotationY": 35, "perspective": 50, "shadowDistance": 40}), + json!({"shadow": true, "shadowPosition": position, "shadowDistance": 30, "lightColor": "#ff8040", "twist": 30}), + ] +} + +/// How many solids drawing the art of `n` with effect `id` builds. +fn solids_built(n: &Node, id: &str) -> usize { + let start = SOLIDS_BUILT.with(std::cell::Cell::get); + assert!(art(n, id).is_some(), "{id}"); + SOLIDS_BUILT.with(std::cell::Cell::get) - start +} + +/// Drawing a 3D object with its shadow on builds each of its solids once: the shadow is cast from +/// the faces the solids drawn kept, so it builds no more solids than the art without a shadow. +#[test] +fn a_shadowed_3d_object_builds_each_solid_once() { + for id in CASTING { + for params in shadow_settings(id) { + for (lit, mut plain) in shadowed(id, ¶ms).into_iter().zip(shadowed(id, ¶ms)) { + plain.appearance.effects.iter_mut().for_each(|e| e.params["shadow"] = json!(false)); + let mut cast = 0; + art(&lit, id).unwrap().walk(&mut |c| cast += usize::from(shadow_opacity(c).is_some())); + assert!(cast > 0, "{id} {params}"); + let built = solids_built(&plain, id); + assert!(built > 0, "{id}"); + assert_eq!(solids_built(&lit, id), built, "{id} {params}: the shadow builds no solid of its own"); + } + } + } +} + +/// The shadow of the faces Extrude & Bevel, Inflate and Rotate kept when they drew their solids, +/// to the bit: the shadow [`cast_shadow`] casts from solids built for the shadow alone. +#[test] +fn the_shadow_cast_from_the_solids_drawn_is_the_shadow_of_solids_built_for_it() { + for id in [EXTRUDE, INFLATE, ROTATE] { + for params in shadow_settings(id) { + for n in shadowed(id, ¶ms) { + let (_, fx) = solid(&n.appearance.effects).unwrap(); + let shapes = if is_container(&n) { + members(&n, "").unwrap() + } else { + let (path, rule) = profile(&n).unwrap(); + vec![Profile { path, rule, items: solid_paint_sources(&n).1, opacity: 1.0, scopes: vec![] }] + }; + let (drawn, _) = art_for(None, &n, fx, &shapes).unwrap(); + let p = crate::merged_params(&fx.id, &fx.params); + let (caster, settings, cast) = cast_shadow(&fx.id, &p, &shapes).unwrap().unwrap(); + let alone = shadow::scoped_art(n.id, &caster, settings, cast, has_masks(&shapes)); + assert!(!alone.is_empty(), "{id} {params}"); + assert_eq!(format!("{drawn:?}"), format!("{alone:?}"), "{id} {params}"); + } + } + } +} diff --git a/crates/effects/src/solids/wireframe.rs b/crates/effects/src/solids/wireframe.rs index e6e7d89ab5..410d51443f 100644 --- a/crates/effects/src/solids/wireframe.rs +++ b/crates/effects/src/solids/wireframe.rs @@ -4,13 +4,13 @@ use std::collections::{HashMap, HashSet, VecDeque}; use std::sync::Arc; use vectorcraft_doc::color::{Color, Paint}; -use vectorcraft_doc::{Appearance, Document, Effect, Node, NodeId}; +use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, FillLayer, Node, NodeId}; use vectorcraft_geom::{Anchor, CubicBez, PathData, Point, SubPath}; use vectorcraft_three_d::Facet; use super::{ - Profile, ROTATE, built_solids, facets, geometry, has_solid, is_container, is_plane, is_three_d, label_of, members, object_profile, region, - reshape_members, resolve, resolve_for, solid, solid_paint_sources, solid_parts, union_bounds, + CLASSIC_EXTRUDE, CLASSIC_ROTATE, Profile, ROTATE, built_solids, facets, geometry, has_solid, is_container, is_plane, is_three_d, label_of, + members, object_profile, region, reshape_members, resolve, resolve_for, solid, solid_paint_sources, solid_parts, union_bounds, }; use crate::{GeomContext, is_geometry}; @@ -53,8 +53,8 @@ pub fn three_d_wireframe_in(doc: Option<&Document>, n: &Node) -> Result = after_geometry(doc, n, faces, shadow, revolve).into_iter().map(|f| f.path).collect(); let wire = edges(&faces)?; if wire.is_empty() { return Err(format!("{label} draws no faces for this object")); @@ -63,44 +63,86 @@ pub fn three_d_wireframe_in(doc: Option<&Document>, n: &Node) -> Result, n: &Node, faces: Vec, revolve: bool) -> Vec { +/// ([`reshaped_beside`]): its first visible Revolve when `revolve` is set, else its first visible +/// Extrude & Bevel, Inflate or Rotate. The effects measure the faces together with `shadow`, the +/// shadow the canvas draws behind them, as they measure the drawn art. +fn after_geometry(doc: Option<&Document>, n: &Node, faces: Vec, shadow: Vec>, revolve: bool) -> Vec { let fx = &n.appearance.effects; let drawn = if revolve { fx.iter().position(|e| e.visible && crate::revolve::is_revolve(&e.id)) } else { solid(fx).map(|(i, _)| i) }; let Some(index) = drawn else { return faces }; - reshaped(faces, fx.get(index + 1..).unwrap_or_default(), &GeomContext { doc, ..GeomContext::of(n) }) + reshaped_beside(faces, shadow, fx.get(index + 1..).unwrap_or_default(), &GeomContext { doc, ..GeomContext::of(n) }) +} + +/// One face of a drawn 3D surface: its outline and the width of the stroke the canvas draws around +/// it (the seam between faces, or a wire edge), which a later Outline Stroke outlines. +pub(crate) struct WireFace { + pub(crate) path: PathData, + pub(crate) stroke: f64, } /// `faces` reshaped by the visible geometry effects in `later` (the effects after a 3D effect), as /// they reshape the faces of the drawn surface ([`crate::reshape::reshape_leaves`]): each effect /// reshapes each face on its own, about the bounds all the faces have before it, and the faces keep -/// to one budget of anchors together. `ctx` gives the object's id, the seed of a random Transform, -/// and the document. -pub(crate) fn reshaped(faces: Vec, later: &[Effect], ctx: &GeomContext) -> Vec { +/// to one budget of anchors together. Each face is filled and carries its round-joined stroke, as on +/// the canvas, so an Outline Stroke outlines that stroke. `ctx` gives the object's id, the seed of a +/// random Transform, and the document. +pub(crate) fn reshaped(faces: Vec, later: &[Effect], ctx: &GeomContext) -> Vec { + reshaped_beside(faces, vec![], later, ctx) +} + +/// The name the faces carry through [`reshaped_beside`], which tells them from the shadow. +const FACE: &str = "face"; + +/// [`reshaped`] with `shadow`, the shadow drawn behind the faces, in the art the effects reshape: +/// each effect measures the faces and the shadow together, and only the faces are returned. +fn reshaped_beside(faces: Vec, shadow: Vec>, later: &[Effect], ctx: &GeomContext) -> Vec { let after: Vec<&Effect> = later.iter().filter(|e| e.visible && is_geometry(&e.id)).collect(); if after.is_empty() { return faces; } let id = NodeId(ctx.seed); - let fill = Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0); - let mut art = Node::group(id, faces.into_iter().map(|f| Arc::new(Node::path(id, f, fill.clone()))).collect()); + let paint = Paint::solid(Color::BLACK); + let face = |f: WireFace| { + let items = + vec![AppearanceItem::Fill(FillLayer::new(paint.clone())), AppearanceItem::Stroke(crate::lighting::seam_stroke(paint.clone(), f.stroke))]; + let mut face = Node::path(id, f.path, Appearance { items, ..Default::default() }); + face.name = Some(FACE.into()); + Arc::new(face) + }; + let mut art = Node::group(id, shadow.into_iter().chain(faces.into_iter().map(face)).collect()); crate::reshape::reshape_leaves(&mut art, &after, later, ctx.doc); let mut out = vec![]; - art.walk(&mut |c| out.extend(c.path_data().cloned())); + face_paths(&art, false, &mut out); out } +/// The faces in `n` ([`FACE`]), `inside` one or not, each with the width of its stroke: a face that +/// a Transform effect copies or a live-effect plug-in cuts into pieces becomes a group with its name. +fn face_paths(n: &Node, inside: bool, out: &mut Vec) { + let inside = inside || n.name.as_deref() == Some(FACE); + if inside && let Some(path) = n.path_data() { + out.push(WireFace { path: path.clone(), stroke: n.appearance.stroke().map_or(0.0, |s| s.width) }); + } + for c in n.children().into_iter().flatten() { + face_paths(c, inside, out); + } +} + +/// The faces of a 3D effect on an object, group or layer itself, and the shadow the canvas draws +/// behind them (none with the shadow off, or with the effect on fills and strokes). +pub(crate) type FacesAndShadow = (Vec, Vec>); + /// The outline of every face [`super::solid_art`] draws for `n` (already resolved): with the effect /// on the object, its solids; with it on fills and strokes, the solid of each; on a group or layer, -/// the solids of its members, about one shared axis. The swatches and patterns named by a live-effect -/// plug-in after a fill's or stroke's 3D effect are looked up in `doc`. -fn solid_face_paths(doc: Option<&Document>, n: &Node) -> Result, String> { +/// the solids of its members, about one shared axis. With the effect on the object, group or layer, +/// also the shadow drawn behind them. The swatches and patterns named by a live-effect plug-in after +/// a fill's or stroke's 3D effect are looked up in `doc`. +fn solid_face_paths(doc: Option<&Document>, n: &Node) -> Result { if is_container(n) { let (index, fx) = solid(&n.appearance.effects).ok_or("a 3D effect on a group's fill or stroke draws nothing")?; let mut shapes = members(n, label_of(&fx.id))?; reshape_members(n, n.appearance.effects.get(..index).unwrap_or_default(), &mut shapes); - return facet_paths(fx, &shapes); + return Ok((facet_paths(fx, &shapes)?, super::shadow_for(n.id, fx, &shapes)?)); } let label = n.appearance.effects.iter().find(|e| e.visible && is_three_d(&e.id)).map_or("This effect", |e| label_of(&e.id)); let (path, rule) = object_profile(n, label)?; @@ -108,7 +150,8 @@ fn solid_face_paths(doc: Option<&Document>, n: &Node) -> Result, S let (sources, paints) = solid_paint_sources(n); if let Some((index, fx)) = solid(&n.appearance.effects) { let path = geometry(&path, n.appearance.effects.get(..index).unwrap_or_default(), &ctx); - return facet_paths(fx, &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }]); + let shapes = [Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }]; + return Ok((facet_paths(fx, &shapes)?, super::shadow_for(n.id, fx, &shapes)?)); } let path = geometry(&path, &n.appearance.effects, &ctx); let mut out = vec![]; @@ -119,24 +162,27 @@ fn solid_face_paths(doc: Option<&Document>, n: &Node) -> Result, S out.extend(reshaped(faces, item.effects().get(index + 1..).unwrap_or_default(), &GeomContext { doc, ..ctx })); } } - Ok(out) + Ok((out, vec![])) } /// The outlines of the facets effect `fx` builds from `shapes`, as `art_for` builds them: Rotate and /// Rotate (Classic) turn every fill and stroke; Extrude & Bevel and Inflate build a solid from each shape's /// top fill and from the outline of each stroke. A stroke whose solid is past the limits is left out, /// as it is left out of the drawn art; past the limits of the object's solids together, the result -/// is an error, as the canvas draws the source art. -fn facet_paths(fx: &Effect, shapes: &[Profile]) -> Result, String> { +/// is an error, as the canvas draws the source art. Each facet carries the width of the stroke the +/// canvas draws around it. +fn facet_paths(fx: &Effect, shapes: &[Profile]) -> Result, String> { let label = label_of(&fx.id); let b = union_bounds(shapes).ok_or_else(|| format!("{label} requires a shape with at least two anchors"))?; let p = crate::merged_params(&fx.id, &fx.params); + let classic = fx.id == CLASSIC_EXTRUDE || fx.id == CLASSIC_ROTATE; + let face = |f: &Facet| WireFace { path: f.path(), stroke: if classic { super::classic::stroke_width(f, &p) } else { super::seam_width(f) } }; let mut out = vec![]; if is_plane(&fx.id) { for s in shapes { for item in &s.items { let (area, rule) = region(&s.path, s.rule, item); - out.extend(facets(ROTATE, &area, rule, b, &p)?.iter().map(Facet::path)); + out.extend(facets(ROTATE, &area, rule, b, &p)?.iter().map(face)); } } return Ok(out); @@ -144,7 +190,7 @@ fn facet_paths(fx: &Effect, shapes: &[Profile]) -> Result, String> let (parts, bounds) = solid_parts(shapes, b); // The solids the art draws, each past the limits of the object's solids together as it is. for f in built_solids(&fx.id, &p, &parts, bounds, vectorcraft_three_d::MAX_OBJECT_FACES) { - out.extend(f?.iter().flatten().map(Facet::path)); + out.extend(f?.iter().flatten().map(face)); } Ok(out) } diff --git a/crates/effects/src/solids/wireframe/tests.rs b/crates/effects/src/solids/wireframe/tests.rs index 792fbdb28a..735be60d6b 100644 --- a/crates/effects/src/solids/wireframe/tests.rs +++ b/crates/effects/src/solids/wireframe/tests.rs @@ -163,13 +163,43 @@ fn revolve_classic_and_rotate_classic_expand_too() { fn later_geometry_effects_reshape_each_face_on_its_own() { let n = solid_square(super::super::EXTRUDE, json!({})); let fx = [crate::new_effect("path.offsetPath", &json!({"offset": 1.0})).unwrap()]; - let out = reshaped(vec![square(0.0, 0.0, 10.0), square(10.0, 0.0, 10.0)], &fx, &GeomContext::of(&n)); - assert_eq!(out.len(), 2, "{out:?}"); - let (a, b) = (out[0].bounds().unwrap(), out[1].bounds().unwrap()); + let faces = [square(0.0, 0.0, 10.0), square(10.0, 0.0, 10.0)].map(|path| WireFace { path, stroke: 0.75 }); + let out = reshaped(faces.into(), &fx, &GeomContext::of(&n)); + assert_eq!(out.len(), 2); + let (a, b) = (out[0].path.bounds().unwrap(), out[1].path.bounds().unwrap()); assert!((a.x0 + 1.0).abs() < 1e-3 && (a.x1 - 11.0).abs() < 1e-3, "{a:?}"); assert!((b.x0 - 9.0).abs() < 1e-3 && (b.x1 - 21.0).abs() < 1e-3, "{b:?}"); } +/// An Outline Stroke after a 3D effect outlines the stroke each face is drawn with (the seam between +/// faces, or a Classic wire edge), not a plain 1 pt stroke: the wireframe covers the outlined faces +/// the canvas draws, in the same place. +#[test] +fn a_later_outline_stroke_outlines_the_stroke_each_face_is_drawn_with() { + let outline = || crate::new_effect("path.outlineStroke", &json!({})).unwrap(); + let cases = [ + (super::super::EXTRUDE, json!({})), + (super::super::CLASSIC_EXTRUDE, json!({})), + (super::super::CLASSIC_EXTRUDE, json!({"surface": "wireframe"})), + (super::super::INFLATE, json!({})), + (ROTATE, json!({})), + (crate::REVOLVE, json!({})), + (crate::CLASSIC_REVOLVE, json!({})), + (crate::CLASSIC_REVOLVE, json!({"surface": "wireframe"})), + ]; + for (id, params) in cases { + let mut n = solid_square(id, params.clone()); + n.appearance.effects.push(outline()); + let wire = three_d_wireframe_in(None, &n).unwrap_or_else(|e| panic!("{id} {params}: {e}")); + let art = if crate::revolve::is_revolve(id) { crate::revolve_art(&n) } else { super::super::solid_art(&n) }.unwrap(); + let drawn = crate::group::shape_art(None, &art, None).unwrap(); + let (w, a) = (bounds(&wire), bounds(&face_paths(&drawn))); + for (x, y) in [(w.x0, a.x0), (w.y0, a.y0), (w.x1, a.x1), (w.y1, a.y1)] { + assert!((x - y).abs() < 1e-6, "{id} {params}: {w:?} {a:?}"); + } + } +} + /// A geometry effect after a fill's 3D effect moves that fill's edges, as it moves its drawn surface. #[test] fn a_geometry_effect_after_a_fill_s_3d_effect_reshapes_its_edges() { @@ -192,6 +222,32 @@ fn a_geometry_effect_after_a_fill_s_3d_effect_reshapes_its_edges() { } } +/// A Transform effect after the 3D effect scales the faces about the center of the drawn art with +/// its shadow, as it scales the surfaces on the canvas. +#[test] +fn a_later_transform_measures_the_faces_with_their_shadow() { + for id in [super::super::EXTRUDE, crate::REVOLVE] { + let scale = crate::new_effect("distort.transform", &json!({"scaleH": 50.0, "scaleV": 50.0})).unwrap(); + let mut n = solid_square(id, json!({"shadow": true, "shadowDistance": 100})); + n.appearance.effects.push(scale.clone()); + let wire = bounds(&three_d_wireframe_in(None, &n).unwrap_or_else(|e| panic!("{id}: {e}"))); + let art = if id == crate::REVOLVE { crate::revolve_art(&n) } else { super::super::solid_art(&n) }.unwrap(); + let mut drawn = art.clone(); + let fx: Vec<&Effect> = art.appearance.effects.iter().collect(); + crate::reshape::reshape_leaves(&mut drawn, &fx, &art.appearance.effects, None); + // The shadow is the art's first member; the surfaces follow it. + let surfaces: Vec = drawn.children().unwrap().iter().skip(1).flat_map(|c| face_paths(c)).collect(); + let a = bounds(&surfaces); + for (x, y) in [(wire.x0, a.x0), (wire.y0, a.y0), (wire.x1, a.x1), (wire.y1, a.y1)] { + assert!((x - y).abs() < 1e-6, "{id}: {wire:?} {a:?}"); + } + // Without the shadow, the faces are scaled about their own center. + let mut alone = solid_square(id, json!({})); + alone.appearance.effects.push(scale); + assert!((bounds(&three_d_wireframe_in(None, &alone).unwrap()).x0 - wire.x0).abs() > 1.0, "{id}"); + } +} + /// With two 3D effects, a geometry effect between them reshapes the faces of the one drawn only /// once: Revolve is drawn, so a Transform before it moves its profile and not its faces again. #[test] diff --git a/crates/effects/src/svg_filter.rs b/crates/effects/src/svg_filter.rs index 3877a60ae9..0c4bff0f1d 100644 --- a/crates/effects/src/svg_filter.rs +++ b/crates/effects/src/svg_filter.rs @@ -16,6 +16,7 @@ use vectorcraft_geom::{Affine, Rect, Vec2}; use crate::pixel::PixelSpace; use crate::util::{num, text}; +pub mod defaults; #[cfg(test)] mod tests; diff --git a/crates/effects/src/svg_filter/defaults.rs b/crates/effects/src/svg_filter/defaults.rs new file mode 100644 index 0000000000..5ce67fac6b --- /dev/null +++ b/crates/effects/src/svg_filter/defaults.rs @@ -0,0 +1,248 @@ +//! The default SVG filters: the filters Effect › SVG Filters and Apply SVG Filter list in every +//! document. The set, the names and the values are VectorCraft's own, written with the filter +//! primitives of SVG 1.1 (). A default is not part of a +//! document until it is applied or edited there: the document then holds a copy under the +//! default's name, and that copy stands in the default's place in the lists. Every default computes +//! in sRGB (`color-interpolation-filters="sRGB"`), so art a filter passes through keeps its colors. + +use vectorcraft_doc::SvgFilter; + +/// A default SVG filter: its name (the `` element's `id`) and the element's XML. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct DefaultFilter { + pub name: &'static str, + pub xml: &'static str, +} + +/// The default filters, in the order the lists show them. +pub const DEFAULT_FILTERS: [DefaultFilter; 14] = [ + DefaultFilter { + name: "Soft Blur", + xml: r#""#, + }, + DefaultFilter { + name: "Heavy Blur", + xml: r#""#, + }, + DefaultFilter { + name: "Soft Shadow", + xml: r#""#, + }, + DefaultFilter { + name: "Hard Shadow", + xml: r#""#, + }, + DefaultFilter { + name: "Glow", + xml: r##""##, + }, + DefaultFilter { + name: "Bevel", + xml: r##""##, + }, + DefaultFilter { + name: "Emboss", + xml: r#""#, + }, + DefaultFilter { + name: "Thicken", + xml: r#""#, + }, + DefaultFilter { + name: "Thin", + xml: r#""#, + }, + DefaultFilter { + name: "Rough Edges", + xml: r#""#, + }, + DefaultFilter { + name: "Grain", + xml: r#""#, + }, + DefaultFilter { + name: "Grayscale", + xml: r#""#, + }, + DefaultFilter { + name: "Invert", + xml: r#""#, + }, + DefaultFilter { + name: "Hue Shift", + xml: r#""#, + }, +]; + +/// The default filter named `name`. +pub fn default_filter(name: &str) -> Option { + DEFAULT_FILTERS.iter().copied().find(|f| f.name == name) +} + +impl DefaultFilter { + /// The filter as a document holds it once it is applied or edited there. + pub fn to_filter(self) -> SvgFilter { + SvgFilter { name: self.name.to_string(), xml: self.xml.to_string() } + } +} + +/// A filter of the lists ([`listed`]), and whether it is a default the document does not hold. +#[derive(Clone, Debug, PartialEq)] +pub struct Listed { + pub filter: SvgFilter, + /// A default the document has no filter named for: applying or editing it adds a copy. + pub default: bool, +} + +/// The filters Effect › SVG Filters and Apply SVG Filter list for a document that holds `held`, +/// and how many of them come first as the defaults: each default in [`DEFAULT_FILTERS`]' order (the +/// document's filter of that name in its place), then the document's other filters in their order. +pub fn listed(held: &[SvgFilter]) -> (Vec, usize) { + let mut out: Vec = DEFAULT_FILTERS + .iter() + .map(|d| match held.iter().find(|f| f.name == d.name) { + Some(f) => Listed { filter: f.clone(), default: false }, + None => Listed { filter: d.to_filter(), default: true }, + }) + .collect(); + let defaults = out.len(); + out.extend(held.iter().filter(|f| default_filter(&f.name).is_none()).map(|f| Listed { filter: f.clone(), default: false })); + (out, defaults) +} + +#[cfg(test)] +mod tests { + use serde_json::json; + use vectorcraft_doc::Effect; + use vectorcraft_geom::{Affine, Point}; + + use super::*; + use crate::pixel::{Channels, PixelSpace}; + use crate::svg_filter::{SVG_FILTER, SvgFilterFx, check, with_id}; + use crate::{PixelFx, RasterFx, raster_effects}; + + /// A `w` × `w` raster whose pixels are one point wide. + fn space(w: usize) -> PixelSpace { + let wd = w as f64; + PixelSpace { + to_doc: Affine::scale(1.0), + px: 1.0, + center: Point::new(wd / 2.0, wd / 2.0), + channels: Channels::Rgb, + line: 1.0, + extent: 0.5 * wd.hypot(wd), + } + } + + /// The default named `name` as the renderer reads it. + fn fx(name: &str) -> SvgFilterFx { + let d = default_filter(name).unwrap_or_else(|| panic!("no default {name}")); + let e = Effect { id: SVG_FILTER.into(), params: json!({"name": d.name, "xml": d.xml}), visible: true }; + match raster_effects(&[e]).first() { + Some(RasterFx::Pixel(PixelFx::Svg(f))) => f.clone(), + other => panic!("{name}: {other:?}"), + } + } + + /// A 40 × 40 raster with an opaque square of `rgb` from 10 to 30, run through default `name`. + fn run(name: &str, rgb: [u8; 3]) -> Vec { + let mut data: Vec = (0..40usize) + .flat_map(|y| (0..40usize).map(move |x| (x, y))) + .flat_map(|(x, y)| if (10..30).contains(&x) && (10..30).contains(&y) { [rgb[0], rgb[1], rgb[2], 255] } else { [0; 4] }) + .collect(); + fx(name).apply(&mut data, 40, 40, &space(40)); + data + } + + fn at(d: &[u8], x: usize, y: usize) -> [u8; 4] { + let i = (y * 40 + x) * 4; + [d[i], d[i + 1], d[i + 2], d[i + 3]] + } + + #[test] + fn every_default_is_a_filter_the_check_takes_under_its_own_name() { + let mut seen = std::collections::BTreeSet::new(); + for d in DEFAULT_FILTERS { + assert_eq!(check(d.xml), Ok(d.name.to_string()), "{}", d.name); + assert!(seen.insert(d.name), "{} is listed twice", d.name); + assert_eq!(d.name, d.name.trim()); + // Edit SVG Filter keeps the name by writing it as the id: a default's code comes back as it is. + assert_eq!(with_id(d.xml, d.name).as_deref(), Some(d.xml), "{}", d.name); + assert_eq!(default_filter(d.name), Some(d)); + assert!(d.xml.contains(r#" color-interpolation-filters="sRGB""#), "{} computes in sRGB", d.name); + } + assert!(DEFAULT_FILTERS.len() <= SvgFilter::MAX); + assert_eq!(default_filter("soft blur"), None, "names match exactly"); + } + + #[test] + fn every_default_draws_and_is_written_to_svg_as_a_filter() { + let plain = { + let mut d = vec![0u8; 40 * 40 * 4]; + for y in 10..30 { + for x in 10..30 { + d[(y * 40 + x) * 4..(y * 40 + x) * 4 + 4].copy_from_slice(&[200, 60, 20, 255]); + } + } + d + }; + for d in DEFAULT_FILTERS { + assert_ne!(run(d.name, [200, 60, 20]), plain, "{} changes what is drawn", d.name); + assert!(fx(d.name).writes_as_svg11(), "{} is written as SVG 1.1", d.name); + } + } + + /// The color defaults against SVG 1.1's own arithmetic, in sRGB as each filter asks. + #[test] + fn the_color_defaults_compute_what_svg_1_1_defines() { + let near = |got: [u8; 4], want: [u8; 4]| got.iter().zip(want).all(|(g, w)| g.abs_diff(w) <= 1); + // feComponentTransfer, type="table" with values 1 0: C' = 1 - C (§15.11). + let inv = at(&run("Invert", [200, 60, 20]), 20, 20); + assert!(near(inv, [55, 195, 235, 255]), "{inv:?}"); + // feColorMatrix type="saturate" values="0": every channel is 0.213 R + 0.715 G + 0.072 B (§15.10). + let grey = at(&run("Grayscale", [200, 60, 20]), 20, 20); + let l = (0.213 * 200.0 + 0.715 * 60.0 + 0.072 * 20.0f64).round() as u8; + assert!(near(grey, [l, l, l, 255]), "{grey:?} for {l}"); + // feColorMatrix type="hueRotate" values="180" (§15.10): cos = -1 and sin = 0 leave + // R' = (2·0.213 - 1) R + 2·0.715 G + 2·0.072 B, and likewise for G' and B'. + let hue = at(&run("Hue Shift", [200, 60, 20]), 20, 20); + let lum2 = 2.0 * (0.213 * 200.0 + 0.715 * 60.0 + 0.072 * 20.0f64); + let turned = [lum2 - 200.0, lum2 - 60.0, lum2 - 20.0].map(|v| v.round().clamp(0.0, 255.0) as u8); + assert!(near(hue, [turned[0], turned[1], turned[2], 255]), "{hue:?} for {turned:?}"); + } + + /// The shape defaults against what their primitives define: an offset copy of the alpha behind + /// the art (feOffset, §15.21), and a shape grown or shrunk by its radius (feMorphology, §15.20). + #[test] + fn the_shape_defaults_move_and_resize_the_alpha() { + let shadow = run("Hard Shadow", [200, 60, 20]); + assert_eq!(at(&shadow, 20, 20), [200, 60, 20, 255], "the art is on top"); + // Right of and below the art by up to 3: black at 60% alpha (premultiplied 153). + assert_eq!(at(&shadow, 31, 31), [0, 0, 0, 153]); + assert_eq!(at(&shadow, 34, 34)[3], 0, "past the offset"); + assert_eq!(at(&shadow, 8, 8)[3], 0, "nothing up and left"); + let thick = run("Thicken", [200, 60, 20]); + assert_eq!((at(&thick, 9, 20)[3], at(&thick, 7, 20)[3]), (255, 0), "grown by its radius"); + let thin = run("Thin", [200, 60, 20]); + assert_eq!((at(&thin, 10, 20)[3], at(&thin, 13, 20)[3]), (0, 255), "shrunk by its radius"); + let soft = run("Soft Shadow", [200, 60, 20]); + assert_eq!(at(&soft, 20, 20), [200, 60, 20, 255]); + let below = at(&soft, 33, 33); + assert!(below[3] > 0 && below[3] < 128 && below[0] == 0, "a blurred, half-strength shadow: {below:?}"); + } + + #[test] + fn the_lists_show_the_defaults_first_with_the_documents_copy_in_place() { + let (all, defaults) = listed(&[]); + assert_eq!((all.len(), defaults), (DEFAULT_FILTERS.len(), DEFAULT_FILTERS.len())); + assert!(all.iter().all(|l| l.default)); + let mine = SvgFilter { name: "Mine".into(), xml: "".into() }; + let glow = SvgFilter { name: "Glow".into(), xml: "".into() }; + let (all, defaults) = listed(&[mine.clone(), glow.clone()]); + assert_eq!((all.len(), defaults), (DEFAULT_FILTERS.len() + 1, DEFAULT_FILTERS.len())); + let at = DEFAULT_FILTERS.iter().position(|d| d.name == "Glow").unwrap(); + assert_eq!(all[at], Listed { filter: glow, default: false }, "the document's Glow where the default was"); + assert_eq!(all.last(), Some(&Listed { filter: mine, default: false })); + assert_eq!(all.iter().filter(|l| l.default).count(), DEFAULT_FILTERS.len() - 1); + } +} diff --git a/crates/effects/src/svg_filter/tests.rs b/crates/effects/src/svg_filter/tests.rs index df1956f3f0..f93cb53124 100644 --- a/crates/effects/src/svg_filter/tests.rs +++ b/crates/effects/src/svg_filter/tests.rs @@ -10,7 +10,15 @@ use crate::{PixelFx, RasterFx, raster_effects}; /// resolution whose pixels are `line` points wide. fn space(w: usize, h: usize, px: f64, line: f64) -> PixelSpace { let (wd, hd) = (w as f64 * px, h as f64 * px); - PixelSpace { to_doc: Affine::scale(px), px, center: Point::new(wd / 2.0, hd / 2.0), channels: Channels::Rgb, line, extent: 0.5 * wd.hypot(hd) } + PixelSpace { + to_doc: Affine::scale(px), + px, + center: Point::new(wd / 2.0, hd / 2.0), + size: vectorcraft_geom::Vec2::new(wd, hd), + channels: Channels::Rgb, + line, + extent: 0.5 * wd.hypot(hd), + } } /// `w` × `h` premultiplied pixels: `f(x, y)` each. diff --git a/crates/effects/src/tests.rs b/crates/effects/src/tests.rs index c43d383c19..c605b6461f 100644 --- a/crates/effects/src/tests.rs +++ b/crates/effects/src/tests.rs @@ -1850,6 +1850,7 @@ fn rasterize_compose_leaves_the_raster_alone_when_the_sizes_do_not_fit() { to_doc: Affine::IDENTITY, px: 1.0, center: Point::new(1.0, 1.0), + size: vectorcraft_geom::Vec2::new(2.0, 2.0), channels: pixel::Channels::Rgb, line: 1.0, extent: std::f64::consts::SQRT_2, diff --git a/crates/effects/src/tests/clipfx.rs b/crates/effects/src/tests/clipfx.rs index 370f32fa81..bf63df61ab 100644 --- a/crates/effects/src/tests/clipfx.rs +++ b/crates/effects/src/tests/clipfx.rs @@ -172,6 +172,48 @@ fn the_clipping_paths_effects_apply_before_the_clip_groups() { assert!((b.x0 - want.x0).abs() < 0.5 && (b.x1 - want.x1).abs() < 0.5, "exported: {b:?} against {want:?}"); } +#[test] +fn a_clip_group_with_a_fill_or_stroke_of_its_own_clips_as_the_canvas_does() { + // A clip group with a fill or a stroke of its own and no effects: the export turns its paint + // into art and still clips by the outline the canvas clips by, Transform copies included. + let items = [ + vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::solid(Color::BLACK))), + vectorcraft_doc::AppearanceItem::Stroke(vectorcraft_doc::StrokeLayer::new(Paint::solid(Color::BLACK), 2.0)), + ]; + let copies = || fx("distort.transform", json!({"moveH": 60, "copies": 1})); + let roughen = fx("distort.roughen", json!({"size": 10, "detail": 10, "relative": false})); + // A ring: a compound path of two squares with effects `own`, its hole with effects `hole_fx`. + let ring = |hole_fx: Vec, own: Vec| { + let outer = Node::path(NodeId(3), shapes::rectangle(Rect::new(50.0, 50.0, 150.0, 150.0)), Appearance::default()); + let mut hole = Node::path(NodeId(4), shapes::rectangle(Rect::new(75.0, 75.0, 125.0, 125.0)), Appearance::default()); + hole.appearance.effects = hole_fx; + let mut c = + Node::new(NodeId(2), NodeKind::Compound { children: vec![Arc::new(outer), Arc::new(hole)], rule: vectorcraft_geom::FillRule::EvenOdd }); + c.appearance.effects = own; + c + }; + let clips = [ + ("copies", clipping_path(2, vec![copies()])), + ("roughen", clipping_path(2, vec![roughen])), + ("a compound path's copies", ring(vec![], vec![copies()])), + ("a compound path member's copies", ring(vec![copies()], vec![])), + ]; + for item in &items { + for (what, clip) in &clips { + let mut d = Document::new(400.0, 400.0); + let layer = d.layers[0].id; + let live = clip_outline(clip).unwrap(); + let mut group = clip_group(1, clip.clone()); + group.appearance.items.push(item.clone()); + d.insert(Some(layer), 0, group).unwrap(); + let exported = clip_outline(&baked_clip(&d)).unwrap(); + assert_eq!(live, exported, "{what} with {item:?}: the canvas clips by the outline the export writes"); + } + } + let b = bounds(&clips[0].1); + assert!((b.x0 - 50.0).abs() < 1e-6 && (b.x1 - 210.0).abs() < 1e-6, "the clip covers both copies: {b:?}"); +} + #[test] fn nested_effects_apply_before_the_clip_groups() { // The clip group grows its clipping path by 10 (Offset Path). Inside the clipping path a diff --git a/crates/effects/src/tests/rasterfollow.rs b/crates/effects/src/tests/rasterfollow.rs index a610ae7c71..1ebcab785a 100644 --- a/crates/effects/src/tests/rasterfollow.rs +++ b/crates/effects/src/tests/rasterfollow.rs @@ -584,8 +584,9 @@ fn image(id: u64, effects: Vec) -> Node { /// A group's Transform effect transforms, with Scale Strokes & Effects off or on, the raster /// effects that a member's own Transform effect with copies holds back: they keep their value /// through the member's effect and transform with the group's. That holds for a shadow listed -/// before the member's copying effect, one listed after it, a fill's shadow under it, the shadow -/// of a member of a nested group with such an effect, and an image's shadow. +/// before the member's copying effect (which each copy carries), one listed after it, a fill's +/// shadow under it, the shadow of a member of a nested group with such an effect, and an image's +/// shadow. #[test] fn a_groups_transform_moves_the_shadows_its_members_copies_hold_back() { let copies = || transform(json!({"moveH": 60, "copies": 1})); @@ -605,7 +606,8 @@ fn a_groups_transform_moves_the_shadows_its_members_copies_hold_back() { let art = crate::evaluate_container(None, &g).unwrap(); for id in [71, 72, 73, 75, 76] { let drawn = shadows_in(&node_in(&art, id)); - assert!(near(&drawn, &[want]), "Scale Strokes & Effects {strokes}: {id} {drawn:?}"); + let wanted = if id == 71 { vec![want, want] } else { vec![want] }; + assert!(near(&drawn, &wanted), "Scale Strokes & Effects {strokes}: {id} {drawn:?}"); } } } @@ -841,3 +843,93 @@ fn copying_and_object_disabled_transforms_keep_their_existing_shadow_rules() { assert!(close(drawn_shadow(&effects), (10.0, 5.0, 4.0)), "{t:?}: {:?}", drawn_shadow(&effects)); } } + +/// The blur of every Drop Shadow drawn on `n` and the nodes under it, in the order of +/// [`shadows_in`]. +fn shadow_blurs_in(n: &Node) -> Vec { + let mut out = vec![]; + n.walk(&mut |m| { + let lists = std::iter::once(&m.appearance.effects).chain(m.appearance.items.iter().map(|i| i.effects())); + for list in lists { + for r in raster_effects(list) { + if let RasterFx::DropShadow { blur, .. } = r { + out.push(blur); + } + } + } + }); + out +} + +/// How many paths `n` holds. +fn paths_in(n: &Node) -> usize { + let mut count = 0; + n.walk(&mut |m| count += usize::from(matches!(m.kind, vectorcraft_doc::NodeKind::Path { .. }))); + count +} + +/// A Transform effect that makes copies gives each copy the shadow listed before it, moved, turned, +/// reflected and scaled with that copy, the last copy lowest: drawn, expanded and baked. The object +/// itself keeps the shadow as it is, and paints none around all of them. With Scale Strokes & +/// Effects on, the shadow is not scaled a second time. +#[test] +fn each_copy_of_a_transform_effect_carries_the_shadow_listed_before_it() { + let cases = [ + (json!({"moveH": 100, "copies": 2}), vec![(10.0, 0.0), (10.0, 0.0), (10.0, 0.0)], vec![4.0, 4.0, 4.0]), + // A turn of 90° counterclockwise on screen takes an offset to the right to one upward. + (json!({"rotate": 90, "copies": 2}), vec![(-10.0, 0.0), (0.0, -10.0), (10.0, 0.0)], vec![4.0, 4.0, 4.0]), + (json!({"reflectX": true, "moveH": 100, "copies": 1}), vec![(-10.0, 0.0), (10.0, 0.0)], vec![4.0, 4.0]), + (json!({"scaleH": 200, "scaleV": 200, "moveH": 100, "copies": 1}), vec![(20.0, 0.0), (10.0, 0.0)], vec![8.0, 4.0]), + (json!({"scaleH": 200, "scaleV": 200, "moveH": 100, "copies": 1, "strokes": true}), vec![(20.0, 0.0), (10.0, 0.0)], vec![8.0, 4.0]), + (json!({"scaleH": 200, "scaleV": 200, "moveH": 100, "copies": 1, "random": true}), vec![(10.0, 0.0), (10.0, 0.0)], vec![4.0, 4.0]), + ]; + for (params, want, blurs) in cases { + let n = square(91, vec![shadow(10.0, 0.0, 4.0), transform(params.clone())]); + assert!(crate::has_transform_art(&n), "{params}"); + assert!(crate::outer_effects(&n).iter().all(|e| e.id != "stylize.dropShadow"), "{params}"); + let random = params["random"].as_bool().unwrap_or(false); + for (how, art) in + [("drawn", crate::reshape(None, &n, None).unwrap()), ("expanded", expand_outlined(None, &n, None).unwrap()), ("baked", baked(n.clone()))] + { + let drawn = shadows_in(&art); + assert_eq!(paths_in(&art), want.len(), "{params}: {how} {art:?}"); + if random { + // Random scales the copy by a share of the 200 %, and its shadow with it; the object + // keeps its own. + assert_eq!(drawn.len(), want.len(), "{params}: {how} {drawn:?}"); + assert!(near(&drawn[1..], &want[1..]), "{params}: {how} {drawn:?}"); + continue; + } + assert!(near(&drawn, &want), "{params}: {how} {drawn:?}"); + let b = shadow_blurs_in(&art); + assert!(b.len() == blurs.len() && b.iter().zip(&blurs).all(|(x, y)| (x - y).abs() < 1e-9), "{params}: {how} blurs {b:?}"); + } + } +} + +/// A shadow listed after a Transform effect that makes copies paints once around all of them, and +/// one listed before it on each copy. A Transform effect that makes no copies, or has Transform +/// Objects off, leaves the object's shadows on the object. +#[test] +fn a_shadow_after_a_copying_transform_paints_once_around_the_copies() { + let n = square(92, vec![shadow(10.0, 0.0, 0.0), transform(json!({"rotate": 90, "copies": 1})), shadow(0.0, 5.0, 0.0)]); + let art = crate::reshape(None, &n, None).unwrap(); + assert!(near(&shadows_in(&art), &[(0.0, 5.0), (0.0, -10.0), (10.0, 0.0)]), "{:?}", shadows_in(&art)); + assert_eq!(crate::outer_effects(&n).len(), 2); + for params in [json!({"rotate": 90}), json!({"rotate": 90, "copies": 1, "objects": false})] { + let n = square(93, vec![shadow(10.0, 0.0, 0.0), transform(params.clone())]); + assert!(!crate::has_transform_art(&n), "{params}"); + assert_eq!(crate::outer_effects(&n).len(), 2, "{params}"); + } +} + +/// Copies that stop at the effect budget each keep their shadow: no copy goes without one, and no +/// shadow is left without its copy. +#[test] +fn copies_past_the_budget_each_keep_their_shadow() { + let n = path_node(94, wavy(30_000), vec![shadow(1.0, 0.5, 0.0), transform(json!({"moveV": 50, "copies": 1000}))]); + let art = crate::reshape(None, &n, None).unwrap(); + let paths = paths_in(&art); + assert!(paths > 1 && paths < 1001, "{paths}"); + assert_eq!(shadows_in(&art).len(), paths); +} diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 19695fd4ff..99b8e1ecdd 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -827,7 +827,7 @@ pub use docmenu::guide_indexes; pub(crate) use edit::{settle_interaction, typing_in_progress}; pub(crate) use object::bounds_rewrite; pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned}; -pub use plugin_call::{Location, key_location, location_in, location_keys}; +pub use plugin_call::{Location, ParamsPlace, key_location, location_in, location_keys}; pub(crate) use vectorcraft_doc::range::parse_range; /// A date param in Unix seconds that defaults to the clock: `None` when absent (now, see @@ -892,6 +892,10 @@ pub use buildcmds::live_paint_gaps; /// Control bar enable it when it changes one). pub use brushsym::reset_transformation_changes; +/// The byte order of UTF-16 text without a byte-order mark, by Import Data Sets' rule (the Graph +/// Data window reads files by it too). +pub use variablecmds::utf16_order_without_mark; + /// Command ids kept only so older scripts keep working: `(alias, the command it duplicates)`. /// They run as before but the command palette leaves them out (it lists the command once). pub const ALIASES: &[(&str, &str)] = &[("object.convertDocumentColorMode", "file.documentColorMode")]; diff --git a/crates/engine/src/cmd/addons/arrange.rs b/crates/engine/src/cmd/addons/arrange.rs index d7cae868ed..f81d7a599a 100644 --- a/crates/engine/src/cmd/addons/arrange.rs +++ b/crates/engine/src/cmd/addons/arrange.rs @@ -21,8 +21,9 @@ use vectorcraft_geom::{Affine, Point, Rect}; use vectorcraft_render::effects; use super::super::appearance::series_children_in_paint_order; +use super::super::colorcmds::edit_if_changed; use super::super::edit::selected_roots; -use super::super::graph::capture_series_object_opacity; +use super::super::graph::{capture_series_object_opacity, series_groups_among}; use super::super::menucmds::whole_or; use super::super::object::{choice, object_bounds_transform, scaling, transform_node, transform_patterns}; use super::super::typecmd::refresh_bounds_of; @@ -92,7 +93,7 @@ pub fn specs() -> Vec { "Randomize Opacity", ["Object", "Plug-ins", "Arrange Tools"], None, - "{min?: % 0..100 (30), max?: % 0..100 (100; not less than min), seed?: whole number (0; the same seed, objects and range give the same opacities), ids?: [id…] (default: the selection)} give each selected object (the top-level ones) its own opacity, picked at random and evenly from min to max, as one undo step; it is the object's opacity, as the Transparency panel sets it. On paths directly in a graph series whose opacity changes, the graph stores the opacity and blend mode of the frontmost of them for its next redraw (docs/mcp.md) → {count}", + "{min?: % 0..100 (30), max?: % 0..100 (100; not less than min), seed?: whole number (0; the same seed, objects and range give the same opacities), ids?: [id…] (default: the selection)} give each selected object (the top-level ones) its own opacity, picked at random and evenly from min to max, as one undo step (none when no opacity changes); it is the object's opacity, as the Transparency panel sets it. On paths directly in a graph series whose opacity changes, the graph stores the opacity and blend mode of the frontmost of them for its next redraw, and on a series group, the group's own (docs/mcp.md) → {count}", has_selection, randomize_opacity ), @@ -101,7 +102,7 @@ pub fn specs() -> Vec { "Sort Objects", ["Object", "Plug-ins", "Arrange Tools"], None, - "{by?: \"width\" | \"height\" | \"area\" (width × height) | \"x\" (left edge) | \"y\" (top edge) | \"opacity\" (%) | \"stacking\" (stacking order, from the back) (\"area\"), apply?: one of the same (\"stacking\"), order?: \"ascending\" (small to large) | \"descending\" (large to small) | \"random\" (\"ascending\"), distribute?: false (true: the values step evenly from the smallest to the largest; false: the objects trade the values they have), seed?: whole number (0; the order \"random\" picks), scaleStrokes?: the Scale Strokes & Effects preference (width, height and area), ids?: [id…] (default: the selection)} sort the selected objects (the top-level ones, at most 20000) by the attribute `by` and give them the values of `apply` in that order, as one undo step: the first in order gets the smallest value. Sizes and places are measured and set as object.setBounds measures them (Use Preview Bounds), a width, height or area about each object's centre (an area in proportion); stacking order always trades places, and only among the objects in the same layer or group. With apply \"opacity\", on paths directly in a graph series whose opacity changes, the graph stores the opacity and blend mode of the frontmost of them for its next redraw (docs/mcp.md). A run that changes nothing makes no step → {count}", + "{by?: \"width\" | \"height\" | \"area\" (width × height) | \"x\" (left edge) | \"y\" (top edge) | \"opacity\" (%) | \"stacking\" (stacking order, from the back) (\"area\"), apply?: one of the same (\"stacking\"), order?: \"ascending\" (small to large) | \"descending\" (large to small) | \"random\" (\"ascending\"), distribute?: false (true: the values step evenly from the smallest to the largest; false: the objects trade the values they have), seed?: whole number (0; the order \"random\" picks), scaleStrokes?: the Scale Strokes & Effects preference (width, height and area), ids?: [id…] (default: the selection)} sort the selected objects (the top-level ones, at most 20000) by the attribute `by` and give them the values of `apply` in that order, as one undo step: the first in order gets the smallest value. Sizes and places are measured and set as object.setBounds measures them (Use Preview Bounds), a width, height or area about each object's centre (an area in proportion); stacking order always trades places, and only among the objects in the same layer or group. With apply \"opacity\", on paths directly in a graph series whose opacity changes, the graph stores the opacity and blend mode of the frontmost of them for its next redraw, and on a series group, the group's own (docs/mcp.md). A run that changes nothing makes no step → {count}", has_multi, sort ), @@ -397,7 +398,8 @@ fn randomize_opacity(s: &mut Session, p: &Value) -> Result { return Ok(json!({ "count": 0 })); } let (lo, hi) = ((min / 100.0) as f32, (max / 100.0) as f32); - s.edit("Randomize Opacity", |d, _| { + // A run that gives every object the opacity it has records no undo step. + edit_if_changed(s, "Randomize Opacity", |_, d| { let mut changed = vec![]; for id in &ids { let o = rng.range(lo, hi); @@ -409,16 +411,18 @@ fn randomize_opacity(s: &mut Session, p: &Value) -> Result { } } keep_series_opacity(d, &changed); - Ok(()) + Ok(((), !changed.is_empty())) })?; Ok(json!({ "count": ids.len() })) } /// Store on their graphs the opacity just given to the paths among `changed` (objects whose opacity changed) that are /// directly in a graph series, with their blend mode, so that every path of the series has them when the graph is drawn -/// again; the frontmost of them in a series sets them. +/// again; the frontmost of them in a series sets them. A series group among `changed` has its own opacity stored for the +/// group. fn keep_series_opacity(d: &mut vectorcraft_doc::Document, changed: &[NodeId]) { - let marks = series_children_in_paint_order(d, changed); + let mut marks = series_children_in_paint_order(d, changed); + marks.extend(series_groups_among(d, changed)); capture_series_object_opacity(d, &marks); } @@ -516,16 +520,18 @@ fn sort(s: &mut Session, p: &Value) -> Result { } let wanted: Vec<(&Sorted, f64)> = rank.iter().filter_map(|i| items.get(*i)).zip(values).collect(); if apply == "opacity" { - if wanted.iter().all(|(o, v)| (o.opacity - v).abs() < 1e-6) { + // The opacity each object is given, as stored; an object whose stored opacity it already is has not changed. + let given: Vec<(NodeId, f32)> = wanted.iter().map(|(o, v)| (o.id, (v / 100.0) as f32)).collect(); + let changed: Vec = given.iter().filter(|(id, a)| d.node(*id).is_some_and(|n| n.opacity != *a)).map(|(id, _)| *id).collect(); + if changed.is_empty() { return Ok(count); } s.edit("Sort Objects", |d, _| { - for (o, v) in &wanted { - if let Some(n) = d.node_mut(o.id) { - n.opacity = (v / 100.0) as f32; + for (id, a) in &given { + if let Some(n) = d.node_mut(*id) { + n.opacity = *a; } } - let changed: Vec = wanted.iter().filter(|(o, v)| (o.opacity - v).abs() >= 1e-6).map(|(o, _)| o.id).collect(); keep_series_opacity(d, &changed); Ok(()) })?; diff --git a/crates/engine/src/cmd/addons/arrange/tests.rs b/crates/engine/src/cmd/addons/arrange/tests.rs index 85191935b2..759f6f321e 100644 --- a/crates/engine/src/cmd/addons/arrange/tests.rs +++ b/crates/engine/src/cmd/addons/arrange/tests.rs @@ -393,6 +393,25 @@ fn randomize_opacity_takes_ids_and_leaves_the_rest() { assert_eq!((opacity(&s, g), opacity(&s, a), opacity(&s, b)), (0.2, 1.0, 1.0)); } +#[test] +fn randomize_opacity_records_no_undo_step_when_no_opacity_changes() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 5.0, 5.0); + let b = rect(&mut s, 10.0, 0.0, 5.0, 5.0); + select(&mut s, &[a, b]); + let n = steps(&s); + // Every object already has the one opacity the range allows. + let r = s.execute("addon.arrange.randomizeOpacity", &json!({"min": 100, "max": 100})).unwrap(); + assert_eq!(r["count"], json!(2)); + assert_eq!(steps(&s), n); + assert_eq!((opacity(&s, a), opacity(&s, b)), (1.0, 1.0)); + s.execute("addon.arrange.randomizeOpacity", &json!({"min": 40, "max": 40})).unwrap(); + assert_eq!(steps(&s), n + 1); + s.execute("addon.arrange.randomizeOpacity", &json!({"min": 40, "max": 40})).unwrap(); + assert_eq!(steps(&s), n + 1, "the same opacities again"); + assert_eq!((opacity(&s, a), opacity(&s, b)), (0.4, 0.4)); +} + #[test] fn randomize_opacity_refuses_bad_params() { let mut s = session(); diff --git a/crates/engine/src/cmd/addons/cleanup/text.rs b/crates/engine/src/cmd/addons/cleanup/text.rs index 052ba901ed..ea7e3314bb 100644 --- a/crates/engine/src/cmd/addons/cleanup/text.rs +++ b/crates/engine/src/cmd/addons/cleanup/text.rs @@ -45,7 +45,7 @@ pub fn specs() -> Vec { "Break Text", ["Object", "Plug-ins", "Artwork Cleanup"], None, - "{by?: \"lines\"|\"paragraphs\"|\"words\"|\"glyphs\" (lines), ids?: [id…] (default: the selection)} each horizontal point or area type object becomes point type objects, one per line, paragraph, word or glyph, each where its characters were and with their character styles, as one undo step; spaces between pieces go, a paragraph's lines stay lines (a wrapped line ends in a line break), justified lines close up, and a paragraph broken out whole keeps its bullet (not its number; other pieces have no list markers). Type on a path, vertical type, threaded type and area type whose text doesn't fit stay as they are → {ids (the pieces, selected), skipped}", + "{by?: \"lines\"|\"paragraphs\"|\"words\"|\"glyphs\" (lines), ids?: [id…] (default: the selection; the type they name is taken locked or hidden too)} each horizontal point or area type object becomes point type objects, one per line, paragraph, word or glyph, each where its characters were and with their character styles, as one undo step; spaces between pieces go, a paragraph's lines stay lines (a wrapped line ends in a line break), justified lines close up, and a paragraph broken out whole keeps its bullet (not its number; other pieces have no list markers). Type on a path, vertical type, threaded type and area type whose text doesn't fit stay as they are → {ids (the pieces, selected), skipped}", has_selection, break_text ), @@ -54,7 +54,7 @@ pub fn specs() -> Vec { "Combine Point Text", ["Object", "Plug-ins", "Artwork Cleanup"], None, - "{ids?: [id…] (default: the selection)} merge one-line horizontal point type into as few objects as it can, every glyph staying where it was: pieces turned and sheared alike whose baselines line up (within 0.4 em; the difference becomes baseline shift) join left to right, a space goes between pieces at least half a space apart, and tracking on the character before each piece keeps the spacing; each object keeps its character styles, and the leftmost piece of each run its place and paint, as one undo step → {ids (the objects made, selected), combined (pieces merged into them)}", + "{ids?: [id…] (default: the selection; the type they name is taken locked or hidden too)} merge one-line horizontal point type into as few objects as it can, every glyph staying where it was: pieces turned and sheared alike, as visible and as locked (their groups and layers included), whose baselines line up (within 0.4 em; the difference becomes baseline shift) join left to right, a space goes between pieces at least half a space apart, and tracking on the character before each piece keeps the spacing; each object keeps its character styles, and the leftmost piece of each run its place and paint, as one undo step → {ids (the objects made, selected), combined (pieces merged into them)}", has_selection, combine_text ), @@ -63,7 +63,7 @@ pub fn specs() -> Vec { "Join Point Text", ["Object", "Plug-ins", "Artwork Cleanup"], None, - "{ids?: [id…] (default: the selection)} join one-line horizontal point type into one point type object, as one undo step: pieces turned and sheared like the top-left one are read as lines (baselines within 0.4 em of each other), top to bottom, each line's pieces left to right with a space between them; each line becomes a paragraph, left aligned, and keeps the distance between baselines as its leading. The text keeps its character styles; the object takes the top-left piece's place and paint, and the other pieces go → {id (selected), joined (pieces merged into it), lines}", + "{ids?: [id…] (default: the selection; the type they name is taken locked or hidden too)} join one-line horizontal point type into one point type object, as one undo step: pieces turned and sheared like the top-left one, and as visible and as locked (their groups and layers included), are read as lines (baselines within 0.4 em of each other), top to bottom, each line's pieces left to right with a space between them; each line becomes a paragraph, left aligned, and keeps the distance between baselines as its leading. The text keeps its character styles; the object takes the top-left piece's place and paint, and the other pieces go → {id (selected), joined (pieces merged into it), lines}", has_selection, join_text ), @@ -72,7 +72,7 @@ pub fn specs() -> Vec { "Remove Breaks", ["Object", "Plug-ins", "Artwork Cleanup"], None, - "{kind: \"line\"|\"paragraph\", ids?: [id…]} remove the forced line breaks (line) or paragraph returns (paragraph) in the characters selected with a Type tool (after Select All in a frame of threaded text, in the text of every frame of the story), else in all the text of the selected type, as one undo step; a break between two words becomes a space, the frames of a threaded story selected all together being read as one text → {ids, removed}", + "{kind: \"line\"|\"paragraph\", ids?: [id…] (the type they name is taken locked or hidden too)} remove the forced line breaks (line) or paragraph returns (paragraph) in the characters selected with a Type tool (after Select All in a frame of threaded text, in the text of every frame of the story, locked and hidden frames included), else in all the text of the selected type, as one undo step; a break between two words becomes a space, the frames of a threaded story selected all together being read as one text → {ids, removed}", has_selection, remove_breaks ), @@ -90,7 +90,7 @@ pub fn specs() -> Vec { "Set Alignment, Keep Position", ["Object", "Plug-ins", "Artwork Cleanup"], None, - "{align: \"left\"|\"center\"|\"right\", ids?: [id…] (default: the selection)} align every paragraph of each horizontal point type object so, moving the object so its longest line stays where it is (one line: the text doesn't move), as one undo step → {ids (the objects changed)}", + "{align: \"left\"|\"center\"|\"right\", ids?: [id…] (default: the selection; the type they name is taken locked or hidden too)} align every paragraph of each horizontal point type object so, moving the object so its longest line stays where it is (one line: the text doesn't move), as one undo step → {ids (the objects changed)}", has_selection, align_in_place ), @@ -99,7 +99,7 @@ pub fn specs() -> Vec { "Reset Text Transform", ["Object", "Plug-ins", "Artwork Cleanup"], None, - "{scale?: bool (false: the horizontal scale stays; true: it goes too, the object's and every character's), ids?: [id…] (default: the selection)} take the rotation, shear and reflection off each point type object, its size and the centre of its text staying, as one undo step → {ids (the objects changed)}", + "{scale?: bool (false: the horizontal scale stays; true: it goes too, the object's and every character's), ids?: [id…] (default: the selection; the type they name is taken locked or hidden too)} take the rotation, shear and reflection off each point type object, its size and the centre of its text staying, as one undo step → {ids (the objects changed)}", has_selection, reset_transform ), @@ -123,8 +123,17 @@ fn editing_text(s: &Session) -> std::result::Result<(), String> { } } -/// The type objects under `roots` (inside groups and layers, not live art) that can be edited. -fn texts_under(d: &Document, roots: &[NodeId]) -> Result> { +/// The type objects a command acts on: those under the objects `ids` names, locked and hidden ones +/// included, else those under the selection that can be edited ([`texts_under`]). +fn target_texts(s: &Session, p: &Value, command: &str) -> Result> { + let named = p.get("ids").is_some_and(|v| !v.is_null()); + texts_under(&s.doc()?.doc, &checked_ids_or_selection(s, p, command)?, named) +} + +/// The type objects under `roots` (inside groups and layers, not live art). When `named`, every one +/// not on a locked artboard, locked and hidden ones (and ones in a locked or hidden group or layer) +/// included; else only those that can be edited. +fn texts_under(d: &Document, roots: &[NodeId], named: bool) -> Result> { fn visit(n: &Node, out: &mut Vec) { match &n.kind { NodeKind::Text(_) => out.push(n.id), @@ -134,8 +143,13 @@ fn texts_under(d: &Document, roots: &[NodeId]) -> Result> { } let mut out = vec![]; roots.iter().filter_map(|id| d.node(*id)).for_each(|n| visit(n, &mut out)); - let editable = d.editable(); - out.retain(|id| editable(*id)); + if named { + let locks = d.locked_artboards(); + out.retain(|id| !locks.holds_id(*id)); + } else { + let editable = d.editable(); + out.retain(|id| editable(*id)); + } out.dedup(); if out.len() > MAX_TEXTS { return Err(EngineError::Other("Too many type objects to change at once".into())); @@ -376,7 +390,9 @@ fn replace_with_pieces(s: &mut Session, label: &str, items: Vec<(NodeId, Node, V places.push((id, nodes)); } d.insert_beside(places, true)?; - sel.set(made.iter().copied()); + // Pieces of locked or hidden type stay unselected. + let editable = d.editable(); + sel.set(made.iter().copied().filter(|id| editable(*id))); Ok(made.iter().map(|i| i.0).collect()) }) } @@ -396,7 +412,7 @@ fn break_text(s: &mut Session, p: &Value) -> Result { }; let d = &s.doc()?.doc; let (mut items, mut skipped, mut count) = (vec![], vec![], 0); - let ids = texts_under(d, &checked_ids_or_selection(s, p, C)?)?; + let ids = target_texts(s, p, C)?; let threads = thread_index(d); for id in ids { let (Some(src), Some(node)) = (Source::of(d, id, threads.contains_key(&id)), d.node(id)) else { @@ -450,6 +466,9 @@ fn split_text(s: &mut Session, _: &Value) -> Result { struct Piece { id: NodeId, t: TextObject, + /// Whether the object and every group and layer above it are visible, and whether they are all + /// unlocked. + state: (bool, bool), /// The object's turn and shear (`xf` without its move). turn: [f64; 4], /// Where its first character's glyph starts on its baseline, in that frame. @@ -487,13 +506,19 @@ impl Piece { if !(at.x.is_finite() && at.y.is_finite() && size > 0.0) { return None; } - Some((Self { id, t, turn: [a, b, c, dd], at, end: at.x + end, size, pens }, node)) + let state = d.ancestry(id)?.iter().filter_map(|i| d.node(*i)).fold((true, true), |(v, u), n| (v && n.visible, u && !n.locked)); + Some((Self { id, t, state, turn: [a, b, c, dd], at, end: at.x + end, size, pens }, node)) } /// Whether `o` is turned and sheared alike. fn turned_like(&self, o: &Piece) -> bool { self.turn.iter().zip(&o.turn).all(|(x, y)| (x - y).abs() <= 1e-6 * x.abs().max(y.abs()).max(1.0)) } + + /// Whether `o` is turned and sheared alike and has the same `state`. + fn joins(&self, o: &Piece) -> bool { + self.turned_like(o) && self.state == o.state + } } /// Whether two objects look alike apart from their text (paint, opacity, blending, effects). @@ -595,15 +620,14 @@ fn merge(chain: &[&Piece]) -> std::result::Result { fn combine_text(s: &mut Session, p: &Value) -> Result { const C: &str = "addon.cleanup.combineText"; let d = &s.doc()?.doc; - let mut pieces: Vec<(Piece, &Node)> = - texts_under(d, &checked_ids_or_selection(s, p, C)?)?.into_iter().filter_map(|id| Piece::of(d, id)).collect(); - // Lines: pieces turned alike and looking alike, by baseline, then left to right. + let mut pieces: Vec<(Piece, &Node)> = target_texts(s, p, C)?.into_iter().filter_map(|id| Piece::of(d, id)).collect(); + // Lines: pieces turned alike, as visible and as locked and looking alike, by baseline, then left + // to right. pieces.sort_by(|x, y| x.0.at.y.total_cmp(&y.0.at.y).then(x.0.at.x.total_cmp(&y.0.at.x))); let mut lines: Vec> = vec![]; for (piece, node) in &pieces { let fits = |l: &Vec<(&Piece, &Node)>| { - l.first() - .is_some_and(|(f, n)| f.turned_like(piece) && same_look(n, node) && (f.at.y - piece.at.y).abs() <= SAME_LINE * f.size.min(piece.size)) + l.first().is_some_and(|(f, n)| f.joins(piece) && same_look(n, node) && (f.at.y - piece.at.y).abs() <= SAME_LINE * f.size.min(piece.size)) }; match lines.iter_mut().find(|l| fits(l)) { Some(l) => l.push((piece, node)), @@ -672,7 +696,8 @@ fn combine_text(s: &mut Session, p: &Value) -> Result { gone.extend(others); } d.remove_many(&gone)?; - sel.set(ids.iter().map(|i| NodeId(*i))); + let editable = d.editable(); + sel.set(ids.iter().map(|i| NodeId(*i)).filter(|id| editable(*id))); Ok(()) })?; Ok(json!({ "ids": ids, "combined": combined })) @@ -681,15 +706,15 @@ fn combine_text(s: &mut Session, p: &Value) -> Result { fn join_text(s: &mut Session, p: &Value) -> Result { const C: &str = "addon.cleanup.joinText"; let d = &s.doc()?.doc; - let pieces: Vec = - texts_under(d, &checked_ids_or_selection(s, p, C)?)?.into_iter().filter_map(|id| Piece::of(d, id).map(|p| p.0)).collect(); - // The piece top-left on the page sets the turn; the others turned like it are read in that frame. + let pieces: Vec = target_texts(s, p, C)?.into_iter().filter_map(|id| Piece::of(d, id).map(|p| p.0)).collect(); + // The piece top-left on the page sets the turn; the others turned like it, and as visible and as + // locked, are read in that frame. let on_page = |p: &Piece| Affine::new([p.turn[0], p.turn[1], p.turn[2], p.turn[3], 0.0, 0.0]) * p.at; let first = pieces.iter().min_by(|x, y| { let (a, b) = (on_page(x), on_page(y)); a.y.total_cmp(&b.y).then(a.x.total_cmp(&b.x)) }); - let mut kept: Vec<&Piece> = first.map(|f| pieces.iter().filter(|p| p.turned_like(f)).collect()).unwrap_or_default(); + let mut kept: Vec<&Piece> = first.map(|f| pieces.iter().filter(|p| f.joins(p)).collect()).unwrap_or_default(); kept.sort_by(|x, y| x.at.y.total_cmp(&y.at.y).then(x.at.x.total_cmp(&y.at.x))); // Lines, top to bottom, by baseline; each line's pieces left to right. let mut lines: Vec> = vec![]; @@ -751,7 +776,7 @@ fn join_text(s: &mut Session, p: &Value) -> Result { n.kind = NodeKind::Text(Box::new(m)); } d.remove_many(&gone)?; - sel.set([id]); + sel.set([id].into_iter().filter(|id| d.is_editable(*id))); Ok(()) })?; Ok(json!({ "id": id.0, "joined": joined, "lines": count })) @@ -796,8 +821,8 @@ fn apply_cuts(t: &mut TextObject, cuts: &[(usize, bool)], brk: char) -> usize { } /// The breaks `brk` in the text of the frames of `story`, read as one text: a break at the end or -/// start of a frame between words of the frames on either side becomes a space. Each editable frame -/// comes with its own breaks, at its own bytes. +/// start of a frame between words of the frames on either side becomes a space. Each frame comes +/// with its own breaks, at its own bytes, its locked and hidden frames included. fn story_cuts(d: &Document, story: &[NodeId], brk: char) -> Vec<(NodeId, Vec<(usize, bool)>)> { let texts: Vec<(NodeId, String)> = story.iter().filter_map(|id| Some((*id, text_of(d, *id)?.plain_text()))).collect(); let joined: String = texts.iter().map(|(_, t)| t.as_str()).collect(); @@ -811,9 +836,7 @@ fn story_cuts(d: &Document, story: &[NodeId], brk: char) -> Vec<(NodeId, Vec<(us while let Some((at, space)) = cuts.next_if(|(at, _)| *at < end) { own.push((at - start, space)); } - if d.is_editable(id) { - out.push((id, own)); - } + out.push((id, own)); start = end; } out @@ -841,24 +864,30 @@ fn remove_breaks(s: &mut Session, p: &Value) -> Result { .filter_map(|(id, a, b)| Some((id, break_cuts(&text_of(d, id)?.plain_text(), a, b, brk)))) .collect(), None => { - let ids = texts_under(d, &checked_ids_or_selection(s, p, C)?)?; + let ids = target_texts(s, p, C)?; // A threaded story whose frames are all among them is read as one text, once. let named: std::collections::HashSet = ids.iter().copied().collect(); let threads = thread_index(d); let mut done = std::collections::HashSet::new(); + // The threads already found not to be a story whose frames are all among them: their + // other frames are read one at a time without going through the thread again. + let mut partial = std::collections::HashSet::new(); let mut out: Vec<(NodeId, Vec<(usize, bool)>)> = vec![]; for &id in &ids { if !done.insert(id) { continue; } - let story = match threads.get(&id).and_then(|&i| d.text_threads.get(i)) { - Some(thread) => crate::cmd::threads::story_in(d, thread, id), + let thread = threads.get(&id).copied(); + let story = match thread.filter(|i| !partial.contains(i)).and_then(|i| d.text_threads.get(i)) { + Some(frames) => crate::cmd::threads::story_in(d, frames, id), None => vec![], }; if !story.is_empty() && story.iter().all(|f| named.contains(f)) { done.extend(story.iter().copied()); out.extend(story_cuts(d, &story, brk)); } else if let Some(t) = text_of(d, id) { + // `id` is type, so the story of its thread is the same for each of its frames. + partial.extend(thread); out.push((id, break_cuts(&t.plain_text(), 0, usize::MAX, brk))); } } @@ -891,10 +920,8 @@ fn remove_breaks(s: &mut Session, p: &Value) -> Result { /// Horizontal point type among the objects `p` names. fn point_texts(s: &Session, p: &Value, cmd: &str) -> Result> { let d = &s.doc()?.doc; - let ids: Vec = texts_under(d, &checked_ids_or_selection(s, p, cmd)?)? - .into_iter() - .filter(|id| text_of(d, *id).is_some_and(|t| matches!(t.kind, TextKind::Point))) - .collect(); + let ids: Vec = + target_texts(s, p, cmd)?.into_iter().filter(|id| text_of(d, *id).is_some_and(|t| matches!(t.kind, TextKind::Point))).collect(); if ids.is_empty() { return Err(EngineError::Other("Select point type".into())); } diff --git a/crates/engine/src/cmd/addons/cleanup/text/tests.rs b/crates/engine/src/cmd/addons/cleanup/text/tests.rs index cfa78a5ce5..9671bb3306 100644 --- a/crates/engine/src/cmd/addons/cleanup/text/tests.rs +++ b/crates/engine/src/cmd/addons/cleanup/text/tests.rs @@ -379,6 +379,228 @@ fn remove_breaks_reads_the_threads_once() { } } +/// Remove Breaks reads each named frame of a story that is not all named on its own, in the order +/// named and each once, as one undo step, and goes through that story's frames once for all of them. +#[test] +fn remove_breaks_goes_through_a_partly_named_story_once() { + for (kind, brk) in [("line", '\u{2028}'), ("paragraph", '\n')] { + let mut s = session(); + let a = text(&mut s, json!({"x": 10, "y": 20, "text": "a\u{2028}b\n".repeat(40), "size": 12, "area": {"width": 150, "height": 60}})); + let mut roots = vec![a]; + for i in 0..4 { + let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 100 + 70 * i, "width": 150, "height": 60})).unwrap(); + roots.push(NodeId(r["id"].as_u64().unwrap())); + } + select(&mut s, &roots); + s.execute("text.thread.create", &json!({})).unwrap(); + let f = s.doc().unwrap().doc.text_threads[0].clone(); + assert_eq!(f.len(), 5); + let named = [f[4], f[1], f[3]]; + let breaks: Vec = named.iter().map(|id| obj(&s, *id).plain_text().matches(brk).count()).collect(); + assert!(breaks.iter().all(|n| *n > 0), "{kind}: each named frame holds breaks: {breaks:?}"); + let before = doc_json(&s); + let steps = undo_steps(&s); + let builds = crate::cmd::threads::story_builds(); + let r = s.execute("addon.cleanup.removeBreaks", &json!({"kind": kind, "ids": [f[4].0, f[1].0, f[4].0, f[3].0]})).unwrap(); + assert_eq!(crate::cmd::threads::story_builds() - builds, 1, "{kind}: the story's frames are gone through once"); + assert_eq!(r["removed"].as_u64(), Some(breaks.iter().sum::() as u64), "{kind}"); + assert_eq!(ids(&r), named, "{kind}"); + assert_eq!(undo_steps(&s), steps + 1, "{kind}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(doc_json(&s), before, "{kind}"); + } +} + +/// Lock `id` (`locked`), else hide it, as an undo step of its own. +fn lock_or_hide(s: &mut Session, id: NodeId, locked: bool) { + s.edit("Lock or Hide", |d, _| { + let n = d.node_mut(id).unwrap(); + if locked { + n.locked = true; + } else { + n.visible = false; + } + Ok(()) + }) + .unwrap(); +} + +/// Remove Breaks takes the locked and hidden type that `ids` names, and the locked member of a +/// group it names, as one undo step; from the selection it takes only type that can be edited, and +/// nothing changed makes no undo step. +#[test] +fn remove_breaks_named_locked_and_hidden_type() { + let mut s = session(); + let locked = text(&mut s, json!({"x": 40, "y": 60, "text": "a\nb", "size": 12})); + let hidden = text(&mut s, json!({"x": 40, "y": 120, "text": "c\nd", "size": 12})); + let grouped = text(&mut s, json!({"x": 40, "y": 180, "text": "e\nf", "size": 12})); + let free = text(&mut s, json!({"x": 40, "y": 240, "text": "g\nh", "size": 12})); + select(&mut s, &[grouped, free]); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + lock_or_hide(&mut s, locked, true); + lock_or_hide(&mut s, hidden, false); + lock_or_hide(&mut s, grouped, true); + select(&mut s, &[locked, hidden]); + let steps = undo_steps(&s); + assert_eq!(other(s.execute("addon.cleanup.removeBreaks", &json!({"kind": "paragraph"}))), "No paragraph breaks to remove"); + assert_eq!(undo_steps(&s), steps, "the selected locked and hidden type stays as it is"); + let r = s.execute("addon.cleanup.removeBreaks", &json!({"kind": "paragraph", "ids": [locked.0, hidden.0, group.0]})).unwrap(); + assert_eq!(undo_steps(&s), steps + 1); + assert_eq!(r["removed"], 4); + for (id, now) in [(locked, "a b"), (hidden, "c d"), (grouped, "e f"), (free, "g h")] { + assert_eq!(obj(&s, id).plain_text(), now); + } + assert_eq!(other(s.execute("addon.cleanup.removeBreaks", &json!({"kind": "paragraph", "ids": [locked.0]}))), "No paragraph breaks to remove"); + assert_eq!(undo_steps(&s), steps + 1, "nothing changed, no undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(obj(&s, locked).plain_text(), "a\nb"); +} + +/// A threaded story whose frames `ids` all names is read as one text even when a frame is locked. +#[test] +fn remove_breaks_named_story_with_a_locked_frame() { + let mut s = session(); + let (a, b) = threaded(&mut s, "one\ntwo"); + lock_or_hide(&mut s, a, true); + let r = s.execute("addon.cleanup.removeBreaks", &json!({"kind": "paragraph", "ids": [a.0, b.0]})).unwrap(); + assert_eq!(r["removed"], 1); + assert_eq!(obj(&s, a).plain_text(), "one two"); +} + +/// Type on a locked artboard stays as it is even when `ids` names it, with no undo step. +#[test] +fn remove_breaks_named_type_on_a_locked_artboard() { + let mut s = session(); + let on_board = text(&mut s, json!({"x": 40, "y": 60, "text": "a\nb", "size": 12})); + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + let steps = undo_steps(&s); + let r = s.execute("addon.cleanup.removeBreaks", &json!({"kind": "paragraph", "ids": [on_board.0]})); + assert_eq!(other(r), "No paragraph breaks to remove"); + assert_eq!(undo_steps(&s), steps); + assert_eq!(obj(&s, on_board).plain_text(), "a\nb"); +} + +/// Break Text, Combine and Join Point Text, Set Alignment, Keep Position and Reset Text Transform +/// act on the locked and hidden type that `ids` names (type in a locked layer included), each as +/// one undo step, and leave it as it is when it is only selected. +#[test] +fn named_locked_and_hidden_type() { + let mut s = session(); + let words = text(&mut s, json!({"x": 40, "y": 100, "text": "Two words", "size": 14})); + lock_or_hide(&mut s, words, true); + select(&mut s, &[words]); + assert!(s.execute("addon.cleanup.breakText", &json!({"by": "words"})).is_err()); + let steps = undo_steps(&s); + let r = s.execute("addon.cleanup.breakText", &json!({"by": "words", "ids": [words.0]})).unwrap(); + assert_eq!((ids(&r).len(), undo_steps(&s)), (2, steps + 1)); + assert!(s.doc().unwrap().selection.objects.is_empty(), "the locked pieces stay unselected"); + + let mut s = session(); + let a = text(&mut s, json!({"x": 50, "y": 100, "text": "Left", "size": 20})); + let b = text(&mut s, json!({"x": 110, "y": 100, "text": "Right", "size": 20})); + lock_or_hide(&mut s, a, false); + lock_or_hide(&mut s, b, false); + select(&mut s, &[a, b]); + assert!(s.execute("addon.cleanup.combineText", &json!({})).is_err()); + let r = s.execute("addon.cleanup.combineText", &json!({"ids": [a.0, b.0]})).unwrap(); + assert_eq!(ids(&r), [a]); + assert_eq!(obj(&s, a).plain_text(), "Left Right"); + assert!(s.doc().unwrap().selection.objects.is_empty(), "the hidden object stays unselected"); + + let mut s = session(); + let first = text(&mut s, json!({"x": 50, "y": 100, "text": "First", "size": 20})); + let second = text(&mut s, json!({"x": 50, "y": 130, "text": "Second", "size": 20})); + let layer = s.doc().unwrap().doc.layers[0].id; + lock_or_hide(&mut s, layer, true); + select(&mut s, &[first, second]); + assert!(s.execute("addon.cleanup.joinText", &json!({})).is_err()); + let r = s.execute("addon.cleanup.joinText", &json!({"ids": [first.0, second.0]})).unwrap(); + assert_eq!(r["id"].as_u64(), Some(first.0)); + assert_eq!(obj(&s, first).plain_text(), "First\nSecond"); + assert!(s.doc().unwrap().selection.objects.is_empty(), "the object in the locked layer stays unselected"); + + let mut s = session(); + let lines = text(&mut s, json!({"x": 50, "y": 100, "text": "a\nlonger line", "size": 20})); + lock_or_hide(&mut s, lines, false); + select(&mut s, &[lines]); + assert!(s.execute("addon.cleanup.alignInPlace", &json!({"align": "center"})).is_err()); + s.execute("addon.cleanup.alignInPlace", &json!({"align": "center", "ids": [lines.0]})).unwrap(); + assert!(obj(&s, lines).para_styles().all(|p| p.justify == Justify::Center)); + + let mut s = session(); + let turned = text(&mut s, json!({"x": 300, "y": 200, "text": "Turned", "size": 18, "rotation": 30})); + lock_or_hide(&mut s, turned, true); + select(&mut s, &[turned]); + assert!(s.execute("addon.cleanup.resetTextTransform", &json!({})).is_err()); + let steps = undo_steps(&s); + s.execute("addon.cleanup.resetTextTransform", &json!({"ids": [turned.0]})).unwrap(); + assert_eq!(undo_steps(&s), steps + 1); + let [_, b, c, _, _, _] = obj(&s, turned).xf.as_coeffs(); + assert!(b.abs() < 1e-9 && c.abs() < 1e-9, "the rotation is gone"); +} + +/// Combine Point Text joins named pieces only with pieces as visible and as locked, a group's lock +/// included: a visible piece and a hidden one beside it, or a free piece and one in a locked group, +/// stay as they are, with no undo step. +#[test] +fn combine_keeps_hidden_and_locked_pieces_apart() { + let mut s = session(); + let a = text(&mut s, json!({"x": 50, "y": 100, "text": "Left", "size": 20})); + let b = text(&mut s, json!({"x": 110, "y": 100, "text": "Right", "size": 20})); + lock_or_hide(&mut s, b, false); + let steps = undo_steps(&s); + assert!(s.execute("addon.cleanup.combineText", &json!({"ids": [a.0, b.0]})).is_err()); + assert_eq!(undo_steps(&s), steps); + assert_eq!((obj(&s, a).plain_text(), obj(&s, b).plain_text()), ("Left".into(), "Right".into())); + let d = &s.doc().unwrap().doc; + assert!(d.is_visible(a) && !d.is_visible(b), "the visible text stays shown and the hidden text stays hidden"); + + let mut s = session(); + let a = text(&mut s, json!({"x": 50, "y": 100, "text": "Left", "size": 20})); + let b = text(&mut s, json!({"x": 110, "y": 100, "text": "Right", "size": 20})); + select(&mut s, &[b]); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + lock_or_hide(&mut s, group, true); + let steps = undo_steps(&s); + assert!(s.execute("addon.cleanup.combineText", &json!({"ids": [a.0, group.0]})).is_err()); + assert_eq!(undo_steps(&s), steps); + assert_eq!((obj(&s, a).plain_text(), obj(&s, b).plain_text()), ("Left".into(), "Right".into())); +} + +/// Join Point Text joins only the named pieces as visible and as locked as the top-left one: a +/// hidden piece between two visible lines stays as it is, hidden, and a hidden top-left piece +/// with only a visible one below it joins nothing, with no undo step. +#[test] +fn join_keeps_a_hidden_piece_apart() { + let mut s = session(); + let first = text(&mut s, json!({"x": 50, "y": 100, "text": "First", "size": 20})); + let hidden = text(&mut s, json!({"x": 50, "y": 130, "text": "Hidden", "size": 20})); + let third = text(&mut s, json!({"x": 50, "y": 160, "text": "Third", "size": 20})); + lock_or_hide(&mut s, hidden, false); + let steps = undo_steps(&s); + let r = s.execute("addon.cleanup.joinText", &json!({"ids": [first.0, hidden.0, third.0]})).unwrap(); + assert_eq!((r["id"].as_u64(), r["joined"].as_u64(), undo_steps(&s)), (Some(first.0), Some(2), steps + 1)); + assert_eq!(obj(&s, first).plain_text(), "First\nThird"); + assert_eq!(obj(&s, hidden).plain_text(), "Hidden"); + let d = &s.doc().unwrap().doc; + assert!(d.is_visible(first) && !d.is_visible(hidden), "the visible text stays shown and the hidden text stays hidden"); + assert!(d.node(third).is_none()); + + let mut s = session(); + let top = text(&mut s, json!({"x": 50, "y": 100, "text": "Top", "size": 20})); + let below = text(&mut s, json!({"x": 50, "y": 130, "text": "Below", "size": 20})); + lock_or_hide(&mut s, top, false); + let steps = undo_steps(&s); + assert!(s.execute("addon.cleanup.joinText", &json!({"ids": [top.0, below.0]})).is_err()); + assert_eq!(undo_steps(&s), steps); + assert_eq!((obj(&s, top).plain_text(), obj(&s, below).plain_text()), ("Top".into(), "Below".into())); + assert!(s.doc().unwrap().doc.is_visible(below)); +} + #[test] fn split_at_the_cursor_and_around_a_selection() { for (anchor, caret, want) in [(6, 6, &["Split", "here please"][..]), (6, 10, &["Split", "here", "please"][..])] { diff --git a/crates/engine/src/cmd/addons/cutting.rs b/crates/engine/src/cmd/addons/cutting.rs index 37e9f2fa79..6ad2af043b 100644 --- a/crates/engine/src/cmd/addons/cutting.rs +++ b/crates/engine/src/cmd/addons/cutting.rs @@ -2,9 +2,11 @@ //! Bridges cuts bridges out of the selected art so that a stencil cut from it holds together //! ([`stencil`]), and Weed Box and Lines adds a weed box and weeding lines around the selected art //! for vinyl cutting ([`weed`]). Banner Hems and Grommets marks the hems and grommets of a banner -//! ([`banner`]). Its submenu (Object › Plug-ins › Cutting Tools) and dialogs are the UI's. +//! ([`banner`]). Nest Shapes packs the selected art onto a sheet or a roll of material ([`nest`]). +//! Its submenu (Object › Plug-ins › Cutting Tools) and dialogs are the UI's. mod banner; +mod nest; mod stencil; mod weed; @@ -14,5 +16,6 @@ pub fn specs() -> Vec { let mut v = stencil::specs(); v.extend(weed::specs()); v.extend(banner::specs()); + v.extend(nest::specs()); v } diff --git a/crates/engine/src/cmd/addons/cutting/nest.rs b/crates/engine/src/cmd/addons/cutting/nest.rs new file mode 100644 index 0000000000..18d4dd70f2 --- /dev/null +++ b/crates/engine/src/cmd/addons/cutting/nest.rs @@ -0,0 +1,403 @@ +//! Nest Shapes (`addon.cutting.nest`), a command of the built-in Cutting Tools add-on that packs +//! the selected objects onto a sheet or a roll of material by their bounding boxes +//! (). The sheet is an +//! artboard, or a set size from the artboard's top-left corner; a roll is as wide as the sheet +//! and has no end. The objects are moved, and with `rotate` turned a quarter turn when that places +//! them better; they are never scaled or changed otherwise. + +#[cfg(test)] +mod tests; + +use std::collections::VecDeque; + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind, Scaling}; +use vectorcraft_geom::{Affine, Point, Rect, Vec2}; +use vectorcraft_render::effects; + +use super::super::super::edit::selected_roots_to_transform; +use super::super::super::object::{keep_compound_aligned, transform_node, transform_patterns}; +use super::super::super::pathops::length_given; +use super::super::super::{CommandSpec, bad, check_switches, cmd, has_selection, switch_or}; +use crate::{Result, Session}; + +/// Nest Shapes' command. +pub const NEST: &str = "addon.cutting.nest"; +/// The largest sheet width or height, in points. +const MAX_SIZE: f64 = 1_000_000.0; +/// The largest margin or spacing, in points. +const MAX_GAP: f64 = 100_000.0; +/// The most objects one run nests. +const MAX_SHAPES: usize = 10_000; +/// How far a box may reach past the sheet's edge and still fit (rounding). +const EPS: f64 = 1e-9; + +pub fn specs() -> Vec { + vec![cmd!( + "addon.cutting.nest", + "Nest Shapes…", + ["Object", "Plug-ins", "Cutting Tools"], + None, + "{roll?: bool (false: a sheet `width` × `height`; true: a roll `width` wide with no end), width?: pt 0..1000000 (0: the artboard's width), height?: pt 0..1000000 (0: the artboard's height; not used with roll), margin?: pt 0..100000 (18: kept clear inside each edge of the sheet; on a roll, the sides and the start), spacing?: pt 0..100000 (9: kept between two objects), rotate?: bool (false: objects keep their orientation; true: an object may turn 90° clockwise where that puts its bottom edge higher, or where only the turned object fits), usePreviewBounds?: bool (true: objects are measured with their strokes and effects, the reach of shadows, glows and blurs included; false: by their geometry), artboard?: index (0-based; the sheet's artboard; default: the artboard under the center of the selection, else the first), patterns?: bool (Transform Patterns: pattern fills and strokes move with the art; default: prefs transformPatternTiles)} move the selected objects onto the sheet or roll, which starts at the artboard's top-left corner, packed by their bounding boxes: the tallest first (with rotate, the longest side first), each where its bottom edge is highest and then furthest left, without resizing them. An object on the pixel grid moves by whole points and takes 1 pt more room across and down; a path of a pixel-aligned compound path is not turned. Objects that do not fit on the sheet go in a column to the right of it, `spacing` from its edge and from each other, from its top, in stacking order (back to front). Objects without bounds (an empty group) are not moved. One undo step; nothing changes when no object moves → {placed: count, unplaced: [ids of the objects put beside the sheet], rotated: [ids], skipped: [ids of the objects without bounds], length: pt (from the sheet's top edge to the bottom margin below the lowest object placed)}", + has_selection, + nest + )] +} + +/// The length `p` gives for `key`, from 0 to `max`, or `default`. +fn length(p: &Value, key: &str, default: f64, max: f64) -> Result { + match length_given(p, key, NEST)? { + None => Ok(default), + Some(v) if (0.0..=max).contains(&v) => Ok(v), + Some(_) => Err(bad(NEST, format!("`{key}` must be from 0 to {max} pt"))), + } +} + +/// One stretch of a skyline: from `x`, `w` wide, filled down to `y`. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Span { + x: f64, + w: f64, + y: f64, +} + +/// Bottom-left packing of boxes on a skyline: a strip `width` wide and `height` deep +/// (`f64::INFINITY` for a roll), whose filled part is the spans' outline along its top. +struct Skyline { + spans: Vec, + width: f64, + height: f64, +} + +impl Skyline { + fn new(width: f64, height: f64) -> Self { + Skyline { spans: vec![Span { x: 0.0, w: width, y: 0.0 }], width, height } + } + + /// Where a box `w` × `h` goes: at the left edge of a span, as high as the spans under it + /// allow, choosing the place where its bottom edge is highest and then furthest left. `None` + /// when it fits nowhere. The spans under the box at each span are a window whose two ends only + /// move right, and `window` holds the indices in it whose depth no later span in it reaches, so + /// its front is the deepest: one call takes time in proportion to the number of spans. + fn find(&self, w: f64, h: f64) -> Option<(f64, f64)> { + let mut best: Option<(f64, f64)> = None; + let mut window: VecDeque = VecDeque::new(); + let mut end = 0; + for (i, s) in self.spans.iter().enumerate() { + if s.x + w > self.width + EPS { + break; + } + while window.front().is_some_and(|&j| j < i) { + window.pop_front(); + } + end = end.max(i); + while let Some(t) = self.spans.get(end) + && (end == i || t.x < s.x + w - EPS) + { + while window.back().and_then(|&j| self.spans.get(j)).is_some_and(|b| b.y <= t.y) { + window.pop_back(); + } + window.push_back(end); + end += 1; + } + let y = window.front().and_then(|&j| self.spans.get(j)).map_or(0.0, |t| t.y.max(0.0)); + if y + h > self.height + EPS { + continue; + } + // The box is `h` tall at every place, so the place with the highest bottom edge is the + // place with the highest top edge. + if best.is_none_or(|(bx, by)| y < by - EPS || ((y - by).abs() <= EPS && s.x < bx)) { + best = Some((s.x, y)); + } + } + best + } + + /// Fills the skyline down to `y + h` from `x` across `w`. + fn place(&mut self, x: f64, y: f64, w: f64, h: f64) { + if w <= 0.0 { + return; + } + let end = x + w; + let mut out = Vec::with_capacity(self.spans.len() + 2); + let mut added = false; + for s in &self.spans { + let s_end = s.x + s.w; + if s_end <= x || s.x >= end { + out.push(*s); + continue; + } + if s.x < x { + out.push(Span { x: s.x, w: x - s.x, y: s.y }); + } + if !added { + out.push(Span { x, w, y: y + h }); + added = true; + } + if s_end > end { + out.push(Span { x: end, w: s_end - end, y: s.y }); + } + } + // Neighbors filled to the same depth are one span. + let mut merged: Vec = Vec::with_capacity(out.len()); + for s in out { + match merged.last_mut() { + Some(l) if l.y == s.y => l.w = s.x + s.w - l.x, + _ => merged.push(s), + } + } + self.spans = merged; + } +} + +/// One box to pack: its width and height as it stands, and when it may turn, as it is turned. +type Sizes = ((f64, f64), Option<(f64, f64)>); + +/// The side a box is ordered by: its height, or its longest side when it may turn. +fn lead(b: &Sizes) -> (f64, f64) { + let ((w, h), turned) = *b; + if turned.is_some() { (w.max(h), w.min(h)) } else { (h, w) } +} + +/// Packs `boxes` onto a strip `width` wide and `height` deep, the tallest first (a box that may +/// turn by its longest side; then the widest, then in their order), each where [`Skyline::find`] +/// puts it, turned when that puts its bottom edge higher (then further left), or when only the +/// turned box fits. Gives each box's top-left corner and whether it is turned, or `None` for a box +/// that does not fit. +fn pack(boxes: &[Sizes], width: f64, height: f64) -> Vec> { + let mut order: Vec = (0..boxes.len()).collect(); + order.sort_by(|&a, &b| { + let (la, lb) = (lead(&boxes[a]), lead(&boxes[b])); + lb.0.total_cmp(&la.0).then(lb.1.total_cmp(&la.1)) + }); + let mut sky = Skyline::new(width, height); + let mut at = vec![None; boxes.len()]; + for i in order { + let Some(&((w, h), turned)) = boxes.get(i) else { continue }; + let mut best = sky.find(w, h).map(|(x, y)| (x, y, false, w, h)); + if let Some((tw, th)) = turned + && let Some((x, y)) = sky.find(tw, th) + { + let better = best.is_none_or(|(bx, by, _, _, bh)| { + let (was, now) = (by + bh, y + th); + now < was - EPS || ((now - was).abs() <= EPS && x < bx - EPS) + }); + if better { + best = Some((x, y, true, tw, th)); + } + } + if let Some((x, y, t, bw, bh)) = best { + sky.place(x, y, bw, bh); + if let Some(slot) = at.get_mut(i) { + *slot = Some((x, y, t)); + } + } + } + at +} + +/// A quarter turn clockwise on the page about `c`. +fn quarter_turn(c: Point) -> Affine { + Affine::translate(c.to_vec2()) * vectorcraft_geom::rotate_deg(90.0) * Affine::translate(-c.to_vec2()) +} + +fn finite(r: &Rect) -> bool { + [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) +} + +/// The box `id` is packed by: with `preview`, its visual bounds with geometry effects +/// ([`effects::preview::bounds_of`]) and the reach of its raster effects, such as shadows, glows +/// and blurs ([`vectorcraft_render::drawn_bounds`]); else its geometric bounds. +fn measure(d: &vectorcraft_doc::Document, id: NodeId, preview: bool) -> Option { + let b = effects::preview::bounds_of(d, &[id], preview).filter(finite)?; + if !preview { + return Some(b); + } + match d.node(id).and_then(|n| vectorcraft_render::drawn_bounds(d, n)).filter(finite) { + Some(r) => Some(b.union(r)), + None => Some(b), + } +} + +/// Whether `id` is a path of a pixel-aligned compound path. +fn in_aligned_compound(d: &Document, id: NodeId) -> bool { + d.parent_of(id).and_then(|p| d.node(p)).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }) && n.extras().pixel_aligned) +} + +/// Whether moving `id` snaps it, or an object in it, to the pixel grid: it, an object it holds or +/// the art of a linked opacity mask in it is pixel-aligned, or it is a path of a pixel-aligned +/// compound path. +fn snaps(d: &Document, id: NodeId) -> bool { + if in_aligned_compound(d, id) { + return true; + } + let mut stack: Vec<&Node> = d.node(id).into_iter().collect(); + while let Some(n) = stack.pop() { + if n.extras().pixel_aligned { + return true; + } + stack.extend(n.children().map_or(&[][..], Vec::as_slice).iter().map(|c| &**c)); + if let Some(m) = n.extras().mask.as_ref() + && m.linked + { + stack.push(&*m.art); + } + } + false +} + +fn nest(s: &mut Session, p: &Value) -> Result { + check_switches(p, &["patterns"], NEST)?; + let roll = switch_or(p, "roll", false, NEST)?; + let width = length(p, "width", 0.0, MAX_SIZE)?; + let height = length(p, "height", 0.0, MAX_SIZE)?; + let margin = length(p, "margin", 18.0, MAX_GAP)?; + let spacing = length(p, "spacing", 9.0, MAX_GAP)?; + let turn = switch_or(p, "rotate", false, NEST)?; + let preview = switch_or(p, "usePreviewBounds", true, NEST)?; + let named = match p.get("artboard") { + None | Some(Value::Null) => None, + Some(v) => Some(v.as_u64().and_then(|i| usize::try_from(i).ok()).ok_or_else(|| bad(NEST, "`artboard` must be an artboard's index"))?), + }; + // A path of a compound path selected on its own moves without the rest of the compound path. + let ids = selected_roots_to_transform(s)?; + if ids.len() > MAX_SHAPES { + return Err(bad(NEST, format!("select at most {MAX_SHAPES} objects to nest"))); + } + // Objects without a finite box (an empty group, empty type) are left where they are and + // listed as `skipped`. + let mut skipped = vec![]; + let (items, board): (Vec<(NodeId, Rect)>, Rect) = { + let d = &s.doc()?.doc; + let mut items: Vec<(NodeId, Rect)> = Vec::with_capacity(ids.len()); + for id in &ids { + match measure(d, *id, preview) { + Some(r) => items.push((*id, r)), + None => skipped.push(id.0), + } + } + let board = match named { + Some(i) => d.artboards.get(i).ok_or_else(|| bad(NEST, format!("there is no artboard {i}")))?.rect, + None => { + let all = items.iter().map(|(_, r)| *r).reduce(|a, b| a.union(b)); + let i = all.and_then(|r| d.artboard_at(r.center())).unwrap_or(0); + d.artboards.get(i).ok_or_else(|| bad(NEST, "there is no artboard for the sheet"))?.rect + } + }; + (items, board) + }; + if items.is_empty() { + return Err(bad(NEST, "the selection has nothing to nest")); + } + let sheet_w = if width > 0.0 { width } else { board.width() }; + let sheet_h = if roll { + f64::INFINITY + } else if height > 0.0 { + height + } else { + board.height() + }; + // Every box is `spacing` wider and taller, and the strip is `spacing` wider and deeper than + // the room inside the margins, so the spacing falls between boxes and not at the far edges. + let room_w = sheet_w - 2.0 * margin; + let room_h = if roll { f64::INFINITY } else { sheet_h - 2.0 * margin }; + if room_w <= 0.0 || room_h <= 0.0 { + return Err(bad(NEST, "the margin leaves no room on the sheet")); + } + let all: Vec = items.iter().map(|(id, _)| *id).collect(); + let grid: Vec = { + let d = &s.doc()?.doc; + all.iter().map(|id| snaps(d, *id)).collect() + }; + let sc = Scaling { patterns: transform_patterns(s, p, &all)?, ..Scaling::default() }; + // With `rotate`, each object is turned in a copy of the document and measured there, so the + // box packed for a turned object is the box its turned strokes and effects take. A path of a + // pixel-aligned compound path keeps its orientation: turning it snaps the whole compound path + // again, which would move the compound's other paths away from where they were measured. + let turned: Vec> = if turn { + let mut t = vectorcraft_doc::Document::clone(&s.doc()?.doc); + let xfs: Vec> = items.iter().map(|(id, r)| (!in_aligned_compound(&t, *id)).then(|| quarter_turn(r.center()))).collect(); + for ((id, _), xf) in items.iter().zip(&xfs) { + if let (Some(xf), Some(n)) = (xf, t.node_mut(*id)) { + transform_node(n, *xf, sc, true); + } + } + items.iter().zip(xfs).map(|((id, _), xf)| xf.and_then(|xf| measure(&t, *id, preview).map(|r| (xf, r)))).collect() + } else { + vec![None; items.len()] + }; + // An object that snaps to the pixel grid moves by whole points, so it stays on the grid and the + // snap after the move does not shift it; its box is 1 pt wider and taller to hold the rounding. + let slack = |g: bool| if g { 1.0 } else { 0.0 }; + let boxes: Vec = items + .iter() + .zip(&turned) + .zip(&grid) + .map(|(((_, r), t), g)| { + let pad = spacing + slack(*g); + ((r.width() + pad, r.height() + pad), t.map(|(_, q)| (q.width() + pad, q.height() + pad))) + }) + .collect(); + let at = pack(&boxes, room_w + spacing, room_h + spacing); + let origin = Vec2::new(board.x0 + margin, board.y0 + margin); + // The move that puts the top-left corner of box `b` at `to`: rounded up to whole points for an + // object on the pixel grid, so it moves at most 1 pt further right and down, into its slack. + let shift = |b: &Rect, to: Vec2, g: bool| { + let v = Vec2::new(to.x - b.x0, to.y - b.y0); + if g { Vec2::new(v.x.ceil(), v.y.ceil()) } else { v } + }; + // Each move: the quarter turn first, when the object turns, then the shift. + let mut moves: Vec<(NodeId, Option, Vec2)> = vec![]; + let mut aside: Vec<(NodeId, Option, Vec2)> = vec![]; + let mut unplaced = vec![]; + let mut rotated = vec![]; + let mut bottom = 0.0_f64; + // Objects that do not fit go in a column to the right of the sheet, `spacing` from its edge + // and from each other, so that no object placed on the sheet covers them. + let aside_x = board.x0 + sheet_w + spacing; + let mut aside_y = board.y0; + for ((((id, r), spot), t), g) in items.iter().zip(&at).zip(&turned).zip(&grid) { + match (spot, t) { + (Some((x, y, true)), Some((xf, q))) => { + let dv = shift(q, Vec2::new(origin.x + x, origin.y + y), *g); + moves.push((*id, Some(*xf), dv)); + rotated.push(id.0); + bottom = bottom.max(q.y1 + dv.y - origin.y); + } + (Some((x, y, _)), _) => { + let dv = shift(r, Vec2::new(origin.x + x, origin.y + y), *g); + moves.push((*id, None, dv)); + bottom = bottom.max(r.y1 + dv.y - origin.y); + } + (None, _) => { + aside.push((*id, None, shift(r, Vec2::new(aside_x, aside_y), *g))); + aside_y += r.height() + spacing + slack(*g); + unplaced.push(id.0); + } + } + } + if moves.is_empty() { + return Err(bad(NEST, "no selected object fits on the sheet")); + } + moves.extend(aside); + let length = 2.0 * margin + bottom; + let placed = moves.len() - unplaced.len(); + let result = json!({ "placed": placed, "unplaced": unplaced, "rotated": rotated, "skipped": skipped, "length": length }); + if moves.iter().all(|(_, xf, dv)| xf.is_none() && dv.x.abs() <= EPS && dv.y.abs() <= EPS) { + return Ok(result); + } + s.edit("Nest Shapes", |d, _| { + for (id, xf, dv) in &moves { + // The turn is the one the object was measured with in the copy, and the shift after it + // is whole points for an object on the pixel grid. + for step in xf.iter().copied().chain([Affine::translate(*dv)]) { + if let Some(n) = d.node_mut(*id) { + transform_node(n, step, sc, true); + } + keep_compound_aligned(d, *id, sc); + } + } + Ok(()) + })?; + Ok(result) +} diff --git a/crates/engine/src/cmd/addons/cutting/nest/tests.rs b/crates/engine/src/cmd/addons/cutting/nest/tests.rs new file mode 100644 index 0000000000..6ca6548a19 --- /dev/null +++ b/crates/engine/src/cmd/addons/cutting/nest/tests.rs @@ -0,0 +1,433 @@ +//! Tests for `addon.cutting.nest`: packing the selected objects onto a sheet or a roll. + +use serde_json::{Value, json}; +use vectorcraft_geom::Rect; + +use super::{Skyline, pack}; +use crate::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + s +} + +fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { + NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap()) +} + +fn bounds(s: &Session, id: NodeId) -> Rect { + s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap() +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); +} + +fn steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn overlap(a: Rect, b: Rect) -> bool { + a.x0 < b.x1 - 1e-9 && b.x0 < a.x1 - 1e-9 && a.y0 < b.y1 - 1e-9 && b.y0 < a.y1 - 1e-9 +} + +#[test] +fn boxes_pack_tallest_first_from_the_top_left() { + // 100 wide: the 60 × 50 box goes first at the left and the 40 × 30 one beside it. The 50 × 20 + // one is too wide for the 40 pt beside the first box, so it goes below the first box. + let at = pack(&fixed(&[(40.0, 30.0), (60.0, 50.0), (50.0, 20.0)]), 100.0, f64::INFINITY); + assert_eq!(at, vec![Some((60.0, 0.0, false)), Some((0.0, 0.0, false)), Some((0.0, 50.0, false))]); +} + +#[test] +fn a_box_that_does_not_fit_is_left_out() { + let at = pack(&fixed(&[(80.0, 80.0), (80.0, 80.0), (120.0, 10.0)]), 100.0, 100.0); + assert_eq!(at, vec![Some((0.0, 0.0, false)), None, None]); +} + +/// Boxes that keep their orientation. +fn fixed(b: &[(f64, f64)]) -> Vec { + b.iter().map(|&s| (s, None)).collect() +} + +/// Boxes that may turn a quarter. +fn turning(b: &[(f64, f64)]) -> Vec { + b.iter().map(|&(w, h)| ((w, h), Some((h, w)))).collect() +} + +#[test] +fn a_box_turns_where_its_bottom_edge_ends_higher_or_only_turned_it_fits() { + // A 20 × 90 box lies down as 90 × 20 at the top; a 120 × 10 box only fits the 100 pt strip + // turned, as 10 × 120. + let at = pack(&turning(&[(20.0, 90.0), (120.0, 10.0)]), 100.0, f64::INFINITY); + assert_eq!(at, vec![Some((10.0, 0.0, true)), Some((0.0, 0.0, true))]); + // Without turning, the 120 pt wide box is left out and the other stands up. + let at = pack(&fixed(&[(20.0, 90.0), (120.0, 10.0)]), 100.0, f64::INFINITY); + assert_eq!(at, vec![Some((0.0, 0.0, false)), None]); + // A square box is never turned: turned, it is no better. + let at = pack(&turning(&[(30.0, 30.0)]), 100.0, 100.0); + assert_eq!(at, vec![Some((0.0, 0.0, false))]); +} + +#[test] +fn the_skyline_fills_and_merges_spans() { + let mut sky = Skyline::new(100.0, f64::INFINITY); + sky.place(0.0, 0.0, 30.0, 10.0); + sky.place(30.0, 0.0, 30.0, 10.0); + assert_eq!(sky.spans.len(), 2, "two spans at the same depth are one: {:?}", sky.spans); + assert_eq!(sky.find(50.0, 5.0), Some((0.0, 10.0)), "50 wide does not fit in the 40 left at the top"); + assert_eq!(sky.find(40.0, 5.0), Some((60.0, 0.0))); +} + +#[test] +fn selected_objects_are_nested_on_the_artboard_as_one_undo_step() { + let mut s = session(); + let ids: Vec = (0..6).map(|i| rect(&mut s, 900.0 + 300.0 * i as f64, 700.0, 150.0, 100.0 + 10.0 * i as f64)).collect(); + select(&mut s, &ids); + let n = steps(&s); + let r = s.execute("addon.cutting.nest", &json!({"margin": 10, "spacing": 5, "usePreviewBounds": false})).unwrap(); + assert_eq!(steps(&s), n + 1, "one undo step"); + assert_eq!(r["placed"], json!(6)); + assert_eq!(r["unplaced"], json!([])); + let boxes: Vec = ids.iter().map(|id| bounds(&s, *id)).collect(); + for (i, a) in boxes.iter().enumerate() { + assert!(a.x0 >= 10.0 - 1e-9 && a.y0 >= 10.0 - 1e-9 && a.x1 <= 790.0 + 1e-9 && a.y1 <= 590.0 + 1e-9, "{a:?} inside the margins"); + assert!((a.width(), a.height()) == (150.0, 100.0 + 10.0 * i as f64), "moved, not resized"); + for b in &boxes[i + 1..] { + assert!(!overlap(a.inflate(2.5, 2.5), b.inflate(2.5, 2.5)), "{a:?} and {b:?} are 5 pt apart"); + } + } + // The tallest (150 pt) is at the top-left corner inside the margin, and five 150 pt wide + // boxes with 5 pt between them fill the 780 pt inside the margins. The shortest goes 5 pt below + // the 110 pt tall box at the right, where its bottom edge is highest. + assert_eq!((boxes[5].x0, boxes[5].y0), (10.0, 10.0)); + assert_eq!(boxes.iter().filter(|b| b.y0 == 10.0).count(), 5); + assert_eq!((boxes[0].x0, boxes[0].y0), (630.0, 125.0)); + assert_eq!(r["length"], json!(10.0 + 115.0 + 100.0 + 10.0)); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(bounds(&s, ids[0]), Rect::new(900.0, 700.0, 1050.0, 800.0)); +} + +#[test] +fn objects_that_do_not_fit_go_beside_the_sheet() { + let mut s = session(); + let a = rect(&mut s, 900.0, 0.0, 500.0, 400.0); + let b = rect(&mut s, 1500.0, 0.0, 500.0, 400.0); + let big = rect(&mut s, 2100.0, 0.0, 900.0, 100.0); + select(&mut s, &[a, b, big]); + let r = s.execute("addon.cutting.nest", &json!({"margin": 0, "spacing": 5, "usePreviewBounds": false})).unwrap(); + assert_eq!(r["placed"], json!(1)); + assert_eq!(r["unplaced"], json!([b.0, big.0])); + assert_eq!(bounds(&s, a), Rect::new(0.0, 0.0, 500.0, 400.0)); + // A column 5 pt to the right of the 800 pt sheet, in stacking order, 5 pt apart. + assert_eq!(bounds(&s, b), Rect::new(805.0, 0.0, 1305.0, 400.0)); + assert_eq!(bounds(&s, big), Rect::new(805.0, 405.0, 1705.0, 505.0)); +} + +#[test] +fn the_column_beside_the_sheet_is_in_stacking_order() { + let mut s = session(); + let back = rect(&mut s, 900.0, 0.0, 900.0, 100.0); + let front = rect(&mut s, 900.0, 200.0, 900.0, 50.0); + let small = rect(&mut s, 900.0, 400.0, 50.0, 50.0); + // Selected front first: the column still starts with the object at the back. + select(&mut s, &[front, small, back]); + let r = s.execute("addon.cutting.nest", &json!({"margin": 0, "spacing": 5, "usePreviewBounds": false})).unwrap(); + assert_eq!(r["unplaced"], json!([back.0, front.0])); + assert_eq!(bounds(&s, back), Rect::new(805.0, 0.0, 1705.0, 100.0)); + assert_eq!(bounds(&s, front), Rect::new(805.0, 105.0, 1705.0, 155.0)); +} + +#[test] +fn objects_without_bounds_are_skipped_and_listed() { + let mut s = session(); + let a = rect(&mut s, 900.0, 0.0, 50.0, 50.0); + let layer = s.doc().unwrap().doc.parent_of(a); + let empty = s + .edit("empty group", |d, _| { + let g = vectorcraft_doc::Node::new(d.alloc_id(), vectorcraft_doc::NodeKind::Group { children: vec![], clip: false }); + Ok(d.insert(layer, usize::MAX, g).unwrap()) + }) + .unwrap(); + select(&mut s, &[a, empty]); + let r = s.execute("addon.cutting.nest", &json!({"margin": 0, "usePreviewBounds": false})).unwrap(); + assert_eq!((r["placed"].clone(), r["unplaced"].clone(), r["skipped"].clone()), (json!(1), json!([]), json!([empty.0]))); + assert_eq!(bounds(&s, a), Rect::new(0.0, 0.0, 50.0, 50.0)); +} + +#[test] +fn the_sheet_is_the_artboard_under_the_center_of_the_selection() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 1000, "y": 0, "width": 300, "height": 300})).unwrap(); + let a = rect(&mut s, 1100.0, 100.0, 50.0, 50.0); + let b = rect(&mut s, 1200.0, 200.0, 40.0, 40.0); + select(&mut s, &[a, b]); + s.execute("addon.cutting.nest", &json!({"margin": 0, "spacing": 0, "usePreviewBounds": false})).unwrap(); + assert_eq!(bounds(&s, a), Rect::new(1000.0, 0.0, 1050.0, 50.0), "on the second artboard, not the first"); + assert_eq!(bounds(&s, b), Rect::new(1050.0, 0.0, 1090.0, 40.0)); +} + +#[test] +fn rotate_turns_clockwise() { + let mut s = session(); + // A 400 × 100 group with a 20 pt mark at its top-left corner. Turned clockwise on the page, the + // top-left corner goes to the top-right. + let long = rect(&mut s, 900.0, 0.0, 400.0, 100.0); + let mark = rect(&mut s, 900.0, 0.0, 20.0, 20.0); + select(&mut s, &[long, mark]); + s.execute("object.group", &json!({})).unwrap(); + let r = s + .execute("addon.cutting.nest", &json!({"width": 300, "height": 500, "margin": 0, "spacing": 0, "rotate": true, "usePreviewBounds": false})) + .unwrap(); + assert_eq!(r["rotated"].as_array().map(Vec::len), Some(1)); + assert_eq!(bounds(&s, long), Rect::new(0.0, 0.0, 100.0, 400.0)); + assert_eq!(bounds(&s, mark), Rect::new(80.0, 0.0, 100.0, 20.0), "the mark is at the top-right"); +} + +#[test] +fn a_path_of_a_pixel_aligned_compound_path_is_not_turned() { + let mut s = session(); + let outer = rect(&mut s, 900.0, 100.0, 500.0, 200.0); + let hole = rect(&mut s, 950.0, 150.0, 400.0, 100.0); + select(&mut s, &[outer, hole]); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + s.execute("object.setPixelAligned", &json!({})).unwrap(); + select(&mut s, &[hole]); + // The 400 pt wide path fits the 300 pt sheet only turned, and it keeps its orientation. + let r = + s.execute("addon.cutting.nest", &json!({"width": 300, "height": 500, "margin": 0, "spacing": 0, "rotate": true, "usePreviewBounds": false})); + let e = r.unwrap_err().to_string(); + assert!(e.contains("no selected object fits"), "{e}"); +} + +/// [`Skyline::find`] as a search of every span and every span under the box. +fn find_by_search(sky: &Skyline, w: f64, h: f64) -> Option<(f64, f64)> { + let mut best: Option<(f64, f64)> = None; + for (i, s) in sky.spans.iter().enumerate() { + if s.x + w > sky.width + 1e-9 { + break; + } + let y = sky.spans[i..].iter().take_while(|t| t.x == s.x || t.x < s.x + w - 1e-9).fold(0.0_f64, |m, t| m.max(t.y)); + if y + h > sky.height + 1e-9 { + continue; + } + if best.is_none_or(|(bx, by)| y < by - 1e-9 || ((y - by).abs() <= 1e-9 && s.x < bx)) { + best = Some((s.x, y)); + } + } + best +} + +#[test] +fn find_matches_a_search_of_every_span() { + // A fixed pseudo-random sequence of boxes, each placed where `find` puts it. + let mut seed: u64 = 0x2545_f491_4f6c_dd1d; + let mut next = |n: u64| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed % n) as f64 + 1.0 + }; + let mut sky = Skyline::new(200.0, 400.0); + for _ in 0..400 { + let (w, h) = (next(60), next(30)); + let got = sky.find(w, h); + assert_eq!(got, find_by_search(&sky, w, h), "{w} × {h} on {:?}", sky.spans); + if let Some((x, y)) = got { + sky.place(x, y, w, h); + } + } +} + +#[test] +fn an_object_that_does_not_fit_is_not_covered_by_the_others() { + let mut s = session(); + // The wide object sits on the sheet and does not fit; the small one must not land on it. + let wide = rect(&mut s, 0.0, 0.0, 900.0, 100.0); + let small = rect(&mut s, 300.0, 300.0, 50.0, 50.0); + select(&mut s, &[wide, small]); + s.execute("addon.cutting.nest", &json!({"margin": 0, "spacing": 0, "usePreviewBounds": false})).unwrap(); + assert!(!overlap(bounds(&s, wide), bounds(&s, small)), "{:?} {:?}", bounds(&s, wide), bounds(&s, small)); +} + +#[test] +fn objects_on_the_pixel_grid_keep_the_margin_and_spacing() { + let mut s = session(); + let a = rect(&mut s, 900.0, 0.0, 100.0, 100.0); + let b = rect(&mut s, 1100.0, 0.0, 100.0, 90.0); + select(&mut s, &[a, b]); + s.execute("object.setPixelAligned", &json!({})).unwrap(); + let on_grid = |r: Rect| [r.x0, r.y0, r.x1, r.y1].iter().all(|v| (v * 2.0).fract() == 0.0); + assert!(on_grid(bounds(&s, a)) && on_grid(bounds(&s, b))); + s.execute("addon.cutting.nest", &json!({"margin": 0.6, "spacing": 0.6, "usePreviewBounds": false})).unwrap(); + let (ba, bb) = (bounds(&s, a), bounds(&s, b)); + assert!(on_grid(ba) && on_grid(bb), "still on the grid: {ba:?} {bb:?}"); + assert!(ba.x0 >= 0.6 && ba.y0 >= 0.6 && bb.y0 >= 0.6, "inside the margin: {ba:?} {bb:?}"); + assert!(bb.x0 >= ba.x1 + 0.6, "0.6 pt apart: {ba:?} {bb:?}"); + assert!(ba.x1.max(bb.x1) <= 800.0 - 0.6, "inside the margin: {ba:?} {bb:?}"); +} + +#[test] +fn preview_bounds_take_in_a_drop_shadow() { + let mut s = session(); + let a = rect(&mut s, 900.0, 0.0, 100.0, 100.0); + let b = rect(&mut s, 1100.0, 0.0, 100.0, 100.0); + s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "ids": [a.0], "params": {"x": 20, "y": 0, "blur": 0}})).unwrap(); + select(&mut s, &[a, b]); + s.execute("addon.cutting.nest", &json!({"margin": 0, "spacing": 0})).unwrap(); + let (ba, bb) = (bounds(&s, a), bounds(&s, b)); + let shadow = vectorcraft_render::drawn_bounds(&s.doc().unwrap().doc, s.doc().unwrap().doc.node(a).unwrap()).unwrap(); + assert!(shadow.x1 >= ba.x1 + 20.0 - 1e-9, "the shadow reaches 20 pt right: {shadow:?}"); + let shadow_b = vectorcraft_render::drawn_bounds(&s.doc().unwrap().doc, s.doc().unwrap().doc.node(b).unwrap()).unwrap_or(bb); + assert!(!overlap(shadow, shadow_b.union(bb)), "the shadow {shadow:?} does not reach {bb:?}"); +} + +#[test] +fn a_roll_has_no_end() { + let mut s = session(); + let ids: Vec = (0..5).map(|i| rect(&mut s, 900.0, 300.0 * i as f64, 500.0, 400.0)).collect(); + select(&mut s, &ids); + let r = s.execute("addon.cutting.nest", &json!({"roll": true, "margin": 0, "spacing": 10, "usePreviewBounds": false})).unwrap(); + assert_eq!((r["placed"].clone(), r["unplaced"].clone()), (json!(5), json!([]))); + let mut tops: Vec = ids.iter().map(|id| bounds(&s, *id).y0).collect(); + tops.sort_by(f64::total_cmp); + assert_eq!(tops, vec![0.0, 410.0, 820.0, 1230.0, 1640.0], "one 500 pt wide shape per row on the 800 pt roll"); + assert_eq!(r["length"], json!(2040.0)); +} + +#[test] +fn width_and_height_set_the_sheet_from_the_artboard_corner() { + let mut s = session(); + let ids: Vec = (0..3).map(|i| rect(&mut s, 50.0 * i as f64, 300.0, 40.0, 40.0)).collect(); + select(&mut s, &ids); + let r = s.execute("addon.cutting.nest", &json!({"width": "1 in", "height": 200, "margin": 0, "spacing": 0, "usePreviewBounds": false})).unwrap(); + assert_eq!(r["placed"], json!(3)); + for id in &ids { + let b = bounds(&s, *id); + assert!(b.x0 == 0.0 && b.x1 <= 72.0, "one 40 pt shape per row on a 72 pt sheet: {b:?}"); + } +} + +#[test] +fn preview_bounds_keep_strokes_apart() { + let mut s = session(); + let a = rect(&mut s, 900.0, 0.0, 100.0, 100.0); + let b = rect(&mut s, 1100.0, 0.0, 100.0, 100.0); + select(&mut s, &[a, b]); + s.execute("stroke.set", &json!({"weight": 10})).unwrap(); + s.execute("addon.cutting.nest", &json!({"margin": 0, "spacing": 0})).unwrap(); + let (ba, bb) = (bounds(&s, a), bounds(&s, b)); + assert_eq!((ba.x0, ba.y0), (5.0, 5.0), "the stroke's outer half is inside the sheet"); + assert_eq!((bb.x0 - ba.x1), 10.0, "the strokes touch and do not overlap"); +} + +#[test] +fn a_selection_already_nested_adds_no_undo_step() { + let mut s = session(); + let a = rect(&mut s, 18.0, 18.0, 100.0, 100.0); + select(&mut s, &[a]); + let n = steps(&s); + let r = s.execute("addon.cutting.nest", &json!({"usePreviewBounds": false})).unwrap(); + assert_eq!(r["placed"], json!(1)); + assert_eq!(steps(&s), n, "nothing moved"); +} + +#[test] +fn bad_params_are_refused_and_change_nothing() { + let mut s = session(); + let a = rect(&mut s, 900.0, 0.0, 100.0, 100.0); + select(&mut s, &[a]); + let n = steps(&s); + let bad: [(Value, &str); 10] = [ + (json!({"rotate": 1}), "`rotate` must be true or false"), + (json!({"width": -1}), "`width` must be from 0"), + (json!({"height": 2e6}), "`height` must be from 0"), + (json!({"margin": "x"}), "`margin` must be a number"), + (json!({"spacing": 1e6}), "`spacing` must be from 0"), + (json!({"roll": "yes"}), "`roll` must be true or false"), + (json!({"usePreviewBounds": 1}), "`usePreviewBounds` must be true or false"), + (json!({"artboard": 3}), "there is no artboard 3"), + (json!({"artboard": -1}), "`artboard` must be"), + (json!({"margin": 400}), "the margin leaves no room"), + ]; + for (p, want) in bad { + let e = s.execute("addon.cutting.nest", &p).expect_err(&p.to_string()).to_string(); + assert!(e.contains(want), "{p}: {e}"); + } + let e = s.execute("addon.cutting.nest", &json!({"width": 50, "margin": 0})).unwrap_err().to_string(); + assert!(e.contains("no selected object fits"), "{e}"); + let e = s.execute("addon.cutting.nest", &json!({"patterns": "no"})).unwrap_err().to_string(); + assert!(e.contains("`patterns` must be true or false"), "{e}"); + assert_eq!(steps(&s), n, "a refused run changes nothing"); + assert_eq!(bounds(&s, a), Rect::new(900.0, 0.0, 1000.0, 100.0)); +} + +#[test] +fn the_named_artboard_is_the_sheet() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 1000, "y": 0, "width": 300, "height": 300})).unwrap(); + let a = rect(&mut s, 100.0, 100.0, 50.0, 50.0); + select(&mut s, &[a]); + s.execute("addon.cutting.nest", &json!({"artboard": 1, "margin": 0, "usePreviewBounds": false})).unwrap(); + assert_eq!(bounds(&s, a), Rect::new(1000.0, 0.0, 1050.0, 50.0)); +} + +#[test] +fn rotate_turns_objects_a_quarter_to_fit_the_sheet() { + let mut s = session(); + // On a 300 × 500 sheet with no margin, a 400 × 100 object only fits standing up. + let long = rect(&mut s, 900.0, 0.0, 400.0, 100.0); + let small = rect(&mut s, 900.0, 300.0, 50.0, 40.0); + select(&mut s, &[long, small]); + let p = json!({"width": 300, "height": 500, "margin": 0, "spacing": 0, "usePreviewBounds": false}); + let r = s.execute("addon.cutting.nest", &p).unwrap(); + assert_eq!((r["unplaced"].clone(), r["rotated"].clone()), (json!([long.0]), json!([])), "without rotate it does not fit"); + s.execute("edit.undo", &json!({})).unwrap(); + let mut p = p; + p["rotate"] = json!(true); + let n = steps(&s); + let r = s.execute("addon.cutting.nest", &p).unwrap(); + assert_eq!(steps(&s), n + 1, "one undo step"); + assert_eq!((r["placed"].clone(), r["unplaced"].clone(), r["rotated"].clone()), (json!(2), json!([]), json!([long.0]))); + assert_eq!(bounds(&s, long), Rect::new(0.0, 0.0, 100.0, 400.0), "turned and at the corner"); + // The 50 × 40 object stays as it is: turned, its bottom edge would be lower. + assert_eq!(bounds(&s, small), Rect::new(100.0, 0.0, 150.0, 40.0)); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(bounds(&s, long), Rect::new(900.0, 0.0, 1300.0, 100.0), "undo turns it back"); +} + +#[test] +fn rotate_measures_the_turned_preview_bounds() { + let mut s = session(); + let a = rect(&mut s, 900.0, 0.0, 400.0, 100.0); + select(&mut s, &[a]); + s.execute("stroke.set", &json!({"weight": 10})).unwrap(); + let r = s.execute("addon.cutting.nest", &json!({"width": 300, "height": 500, "margin": 0, "spacing": 0, "rotate": true})).unwrap(); + assert_eq!(r["rotated"], json!([a.0])); + assert_eq!(bounds(&s, a), Rect::new(5.0, 5.0, 105.0, 405.0), "the turned stroke's outer half is inside the sheet"); +} + +#[test] +fn a_compound_paths_path_selected_alone_moves_alone() { + let mut s = session(); + let outer = rect(&mut s, 900.0, 100.0, 40.0, 40.0); + let hole = rect(&mut s, 910.0, 110.0, 10.0, 10.0); + select(&mut s, &[outer, hole]); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + select(&mut s, &[hole]); + s.execute("addon.cutting.nest", &json!({"margin": 0, "usePreviewBounds": false})).unwrap(); + assert_eq!(bounds(&s, hole), Rect::new(0.0, 0.0, 10.0, 10.0), "the path moved"); + assert_eq!(bounds(&s, outer), Rect::new(900.0, 100.0, 940.0, 140.0), "the rest of the compound path stayed"); +} + +#[test] +fn a_group_is_nested_as_one_object() { + let mut s = session(); + let a = rect(&mut s, 900.0, 0.0, 50.0, 50.0); + let b = rect(&mut s, 1000.0, 100.0, 50.0, 50.0); + select(&mut s, &[a, b]); + s.execute("object.group", &json!({})).unwrap(); + s.execute("addon.cutting.nest", &json!({"margin": 0, "usePreviewBounds": false})).unwrap(); + assert_eq!((bounds(&s, a), bounds(&s, b)), (Rect::new(0.0, 0.0, 50.0, 50.0), Rect::new(100.0, 100.0, 150.0, 150.0))); +} diff --git a/crates/engine/src/cmd/addons/image/mask.rs b/crates/engine/src/cmd/addons/image/mask.rs index 786effbd2e..0dd8fabe3c 100644 --- a/crates/engine/src/cmd/addons/image/mask.rs +++ b/crates/engine/src/cmd/addons/image/mask.rs @@ -320,7 +320,8 @@ fn fresh(doc: &Document, n: &Node, cmd: &str) -> Option, doc: &mut Document) { diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index 97230cec0e..b9b517ae85 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -498,8 +498,9 @@ pub(crate) fn stood_for(own: &[NodeId], ids: &[NodeId]) -> Vec { } /// Clear Appearance on each series group a command gave a whole new appearance through its paths, so the group's own -/// opacity, blend mode, isolation, knockout, effects and style link do not stay on top of it. -pub(crate) fn clear_stood_for(d: &mut Document, groups: &[NodeId]) { +/// opacity, blend mode, isolation, knockout, effects and style link do not stay on top of it. The graph stops keeping the +/// groups' opacity, blend mode, isolation and knockout. Returns whether what a graph keeps changed. +pub(crate) fn clear_stood_for(d: &mut Document, groups: &[NodeId]) -> bool { for id in groups { if let Some(n) = d.node_mut(*id) { clear(n); @@ -507,6 +508,7 @@ pub(crate) fn clear_stood_for(d: &mut Document, groups: &[NodeId]) { n.extras_mut().graphic_style = None; } } + super::graph::capture_series_object_opacity(d, groups) } /// [`whole_targets`] of `cmd`, which needs at least one. @@ -943,7 +945,7 @@ fn transfer(s: &mut Session, p: &Value) -> Result { (src.opacity, src.blend, src.isolate, src.knockout, src.knockout_shape); super::object::snap_if_aligned(to); } - clear_stood_for(d, &group); + let forgot = clear_stood_for(d, &group); for id in &cleared { if let Some(n) = d.node_mut(*id) { clear(n); @@ -961,7 +963,7 @@ fn transfer(s: &mut Session, p: &Value) -> Result { // The targets last: on two labels of one kind, the target's rows are the ones the kind keeps. let labels = super::graph::capture_label_rows(d, &changed); let all: Vec = from.iter().chain(&targets).chain(&group).copied().collect(); - Ok(count_changed(d, &before, &all) + usize::from(kept || painted || object || labels)) + Ok(count_changed(d, &before, &all) + usize::from(kept || painted || object || labels || forgot)) })?; s.active_appearance_item = None; Ok(json!({ "source": source.0, "target": target.0 })) diff --git a/crates/engine/src/cmd/artboardalign.rs b/crates/engine/src/cmd/artboardalign.rs index 541ec94a4e..a3e585a8a0 100644 --- a/crates/engine/src/cmd/artboardalign.rs +++ b/crates/engine/src/cmd/artboardalign.rs @@ -6,8 +6,8 @@ use vectorcraft_doc::Scaling; use vectorcraft_geom::{Rect, Vec2}; use super::object::choice; -use super::panelcmds::{artboard_index, artboards_art, locked_and_hidden, named_or_selected, note_artboards}; -use super::{Affine, CommandSpec, NodeId, Result, Session, bad, check_switches, cmd, has_doc, switch_or}; +use super::panelcmds::{artboard_at, artboards_art, locked_and_hidden, named_or_selected, note_artboards, on_board}; +use super::{Affine, CommandSpec, NodeId, Result, Session, bad, check_switches, cmd, has_doc, index, switch_or}; use crate::EngineError; pub fn specs() -> Vec { @@ -63,13 +63,7 @@ fn boards(s: &mut Session, p: &Value, cmd: &str) -> Result { check_switches(p, &["patterns"], cmd)?; let to_artboard = choice(p, cmd, "to", &["selection", "artboard"])? == Some("artboard"); let indices = named_or_selected(s, p, cmd)?; - let given = |key: &str| -> Result> { - match p.get(key).filter(|v| !v.is_null()) { - Some(v) => artboard_index(&s.doc()?.doc, &json!({ "index": v }), cmd).map(Some), - None => Ok(None), - } - }; - let (named, recorded) = (given("artboard")?, given("activeArtboard")?); + let (named, recorded) = (artboard_at(&s.doc()?.doc, p, "artboard", cmd)?, artboard_at(&s.doc()?.doc, p, "activeArtboard", cmd)?); let move_art = switch_or(p, "moveArt", s.tool_options_of("artboard")["moveArt"].as_bool().unwrap_or(true), cmd)?; let locked_art = locked_and_hidden(s, p, move_art, cmd)?; note_artboards(s, p, &indices); @@ -78,8 +72,8 @@ fn boards(s: &mut Session, p: &Value, cmd: &str) -> Result { (false, _) => None, (true, Some(i)) => Some(i), (true, None) => { - let active = s.tool_options_of("artboard")["active"].clone(); - Some(artboard_index(&s.doc()?.doc, &json!({ "index": active }), cmd)?) + let active = s.tool_options_of("artboard")["active"].as_u64().map(index); + Some(active.map_or_else(|| Err(EngineError::Other("no such artboard".into())), |i| on_board(&s.doc()?.doc, i))?) } }; if let Some(i) = reference.filter(|_| named.is_none()) { diff --git a/crates/engine/src/cmd/assets.rs b/crates/engine/src/cmd/assets.rs index e30e6efcdc..cb990e4857 100644 --- a/crates/engine/src/cmd/assets.rs +++ b/crates/engine/src/cmd/assets.rs @@ -89,7 +89,7 @@ pub fn specs() -> Vec { "Asset Export Settings", [], None, - "{exportPreset?: (a preset of document.exportPresets.list: its formats or preset, its format settings over the saved ones, its prefix (none when it has none), its folders (or subfolders: rows or none) with subfolders on for rows, and antiAlias; the other keys go over it), formats?, preset?: mobile|density|\"\" (none), settings?, prefix?, subfolders?, antiAlias?} change the export settings the Asset Export panel and Export for Screens share (document.exportSettings; the values of document.exportForScreens; null removes one): formats replace a preset, a preset replaces the formats → {settings}. Not an undo step", + "{exportPreset?: (a preset of document.exportPresets.list: its formats or preset, its format settings over the saved ones, its prefix (none when it has none), its folders (or subfolders: rows or none) with subfolders on for rows, and antiAlias; the other keys go over it), formats?, preset?: mobile|density|\"\" (none), settings?, prefix?, subfolders?: true|false (Create Sub-folders: true sorts the files into a folder per row; false puts assets.export's files in the folder itself and, given without exportPreset, sets a remembered folder per format or item to none as well), antiAlias?, openLocation?: true|false (Open Location after Export: remembered in document.exportSettings, not in presets or the reply; given alone to a document without settings, Create Sub-folders stays on)} change the export settings the Asset Export panel and Export for Screens share (document.exportSettings; the values of document.exportForScreens; null removes one): formats replace a preset, a preset replaces the formats → {settings}. Not an undo step", has_doc, settings_set ), @@ -435,19 +435,35 @@ fn export(s: &mut Session, p: &Value) -> Result { fn settings_set(s: &mut Session, p: &Value) -> Result { const C: &str = "assets.settings.set"; let o = p.as_object().ok_or_else(|| bad(C, "give the settings to change, e.g. {\"formats\": [{\"format\": \"png\", \"scale\": \"2x\"}]}"))?; - if let Some(k) = o.keys().find(|k| !SCREEN_SETTINGS_KEYS.contains(&k.as_str()) && k.as_str() != "exportPreset") { - return Err(bad(C, format!("`{k}` isn't an export setting: {}", SCREEN_SETTINGS_KEYS.join(", ")))); + if let Some(k) = o.keys().find(|k| !SCREEN_SETTINGS_KEYS.contains(&k.as_str()) && !matches!(k.as_str(), "exportPreset" | "openLocation")) { + return Err(bad(C, format!("`{k}` isn't an export setting: {}, openLocation", SCREEN_SETTINGS_KEYS.join(", ")))); + } + for k in ["subfolders", "openLocation"] { + if o.get(k).is_some_and(|v| !v.is_boolean() && !v.is_null()) { + return Err(bad(C, format!("`{k}` is true or false"))); + } } let mut settings = s.doc()?.doc.export_settings.clone(); let mut given = o.clone(); + // Create Sub-folders is on for a document without settings (Export for Screens opens so), and + // Open Location after Export set on its own leaves it on. + if settings.is_empty() && o.len() == 1 && o.get("openLocation").is_some_and(Value::is_boolean) { + given.insert("subfolders".into(), json!(true)); + } if let Some(name) = given.remove("exportPreset") { let name = name.as_str().ok_or_else(|| bad(C, "`exportPreset` is the name of a preset of document.exportPresets.list"))?; with_screen_export_preset(s, C, &mut settings, name)?; } // Create Sub-folders is Export for Screens' folder per row: the dialog opens on the choice. + // Turned off on its own (the panel menu), it also ends a remembered folder per format or item; + // with an export preset, that preset's folder per format or item stays. + let folders = settings.get("folders").and_then(Value::as_str).map(str::to_string); + let sorted = folders.as_deref().is_some_and(|f| f != "none"); match given.get("subfolders").and_then(Value::as_bool) { Some(true) => _ = settings.insert("folders".into(), json!("rows")), - Some(false) if settings.get("folders").and_then(Value::as_str) == Some("rows") => _ = settings.insert("folders".into(), json!("none")), + Some(false) if folders.as_deref() == Some("rows") || (sorted && !o.contains_key("exportPreset")) => { + _ = settings.insert("folders".into(), json!("none")) + } _ => {} } overlay(&mut settings, &given); diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index 32b0f9fcd0..1046cada1c 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -180,7 +180,7 @@ pub fn specs() -> Vec { "Paintbrush", [], None, - "{…params as path.freehand, brush} paint a freehand stroke with a brush → {id}", + "{…params as path.freehand, brush?: name} paint a freehand stroke with a brush; without `brush` (or with null) the plain path is drawn; a `brush` that names no brush in the document, or a `style` other than \"pencil\" or \"brush\", is an error and nothing is drawn → {id}", has_doc, brush_freehand ), diff --git a/crates/engine/src/cmd/brushsym/brushes.rs b/crates/engine/src/cmd/brushsym/brushes.rs index 1f63076cfd..7fd8c9aa9a 100644 --- a/crates/engine/src/cmd/brushsym/brushes.rs +++ b/crates/engine/src/cmd/brushsym/brushes.rs @@ -729,8 +729,21 @@ pub(super) fn expand_brush(s: &mut Session, p: &Value) -> Result { Ok(json!({ "ids": ids_json(&out) })) } +/// Paints a `path.freehand` stroke with the brush `brush` names. A `brush` left out or null draws +/// the plain path; a `brush` that is not a string or names no brush in the document, and a `style` +/// other than "pencil" or "brush", is an error before anything is drawn. pub(super) fn brush_freehand(s: &mut Session, p: &Value) -> Result { - let name = str_param(p, "brush").map(str::to_string).filter(|n| s.doc().is_ok_and(|st| brush::find(&st.doc, n).is_some())); + const C: &str = "brush.freehand"; + let name = match crate::cmd::text_param(p, "brush", C)? { + None => None, + Some(n) if brush::find(&s.doc()?.doc, n).is_some() => Some(n.to_string()), + Some(n) => return Err(bad(C, format!("no brush named `{n}`"))), + }; + match p.get("style") { + None | Some(Value::Null) => {} + Some(v) if matches!(v.as_str(), Some("pencil" | "brush")) => {} + Some(v) => return Err(bad(C, format!("`style` must be \"pencil\" or \"brush\", not {v}"))), + } let spec = find_command("path.freehand").ok_or_else(|| EngineError::UnknownCommand("path.freehand".into()))?; let r = crate::cmd::run_checked(s, spec, p)?; let (Some(name), Some(id)) = (name, id_param(&r, "id")) else { return Ok(r) }; diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index 06ec06e348..07eb025798 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -54,7 +54,7 @@ pub fn specs() -> Vec { "Shape Builder", [], None, - "{ids?|id?: [id…] (default: selection), points: [[x,y]…] (drag path; one point = click; may be left out with rect), rect?: [x, y, width, height] (Shift-drag marquee from where the drag started, x and y, to x+width and y+height; width and height may be negative: touches every region whose outline crosses the rectangle or has an anchor inside it and the region holding the whole rectangle, the region under x, y comes first and the one under the opposite corner comes next; with points, it also touches the regions along them; for pickColorFrom, x, y is the drag's first point and the opposite corner is its last), erase?: bool (erase mode, Alt: deletes the regions touched, and the pieces of open paths that cut regions and the edges (outline pieces between the points where paths meet; see shapeBuilder.regions) within tolerance, except that a point in a region no more than twice the tolerance across there touches the region; a deleted edge opens its path there, and edges bounding a deleted region go with it; what is left of each path keeps its look, with gradients fitted to its bounds kept where they were on it, its name, opacity mask and attributes, and its fill rule unless merged regions shaped it), splitStroke?: false (In Merge Mode, Clicking Stroke Splits the Path; not with erase or rect: when the one point of a click is within tolerance of a stroke, the path that stroke is on splits in two instead of a merge: the path keeps the rest of it, and a copy of the path holding the run of it from the anchor or crossing point before the click to the one after it, in the path's direction, goes directly above it; both keep the path's gradients where they were on it; the other objects stay as they are; with pickColorFrom \"swatches\" or fill, the run's stroke takes that paint; a path in a Live Paint group or a Shaper Group does not split, and nor does a path the run is all of, such as a lone line, or all but 0.05 pt or less of (a ten-thousandth of the larger side of a path over 500 pt)), tolerance?: pt (2, erase or splitStroke), gap?: pt (0–72; 0: Gap Detection off), openFilledAsClosed?: true (Consider Open Filled Paths as Closed: a filled open path bounds a region as if an invisible edge closed it; false: it cuts the regions it crosses like an unfilled one), pickColorFrom?: \"artwork\" (default: the merged shape takes the look of the front-most object under the first point, else under the last point, else of the front-most object) | \"swatches\" (the current fill, with the rest of the look of the front-most object over the first region the drag touches that an object covers, else of the front-most object), fill?: \"#rrggbb\" | {color|swatch|gradient|none} (overrides pickColorFrom)} replaces the paths it uses where they are; other selected objects (type, hidden or locked objects, clipping paths) stay, and a group goes only when it is left empty → {ids (selected after: each selected object still there, or what took its place), merged, regions, lines, edges (counts deleted, merged or split), split?: id (the run split off, after a split)}; after a split, ids are the roots, with the rest and the run in place of the path when it was one", + "{ids?|id?: [id…] (default: selection), points: [[x,y]…] (drag path; one point = click; may be left out with rect), rect?: [x, y, width, height] (Shift-drag marquee from where the drag started, x and y, to x+width and y+height; width and height may be negative: touches every region whose outline crosses the rectangle or has an anchor inside it and the region holding the whole rectangle, the region under x, y comes first and the one under the opposite corner comes next; with points, it also touches the regions along them; for pickColorFrom, x, y is the drag's first point and the opposite corner is its last), erase?: bool (erase mode, Alt: deletes the regions touched, and the pieces of open paths that cut regions and the edges (outline pieces between the points where paths meet; see shapeBuilder.regions) within tolerance, except that a point in a region no more than twice the tolerance across there touches the region; a deleted edge opens its path there, and edges bounding a deleted region go with it; what is left of each path keeps its look, with gradients fitted to its bounds kept where they were on it, its name, opacity mask and attributes, and its fill rule unless merged regions shaped it), splitStroke?: false (In Merge Mode, Clicking Stroke Splits the Path; not with erase or rect: when the one point of a click is within tolerance of a stroke, the path that stroke is on splits in two instead of a merge: the path keeps the rest of it, and a copy of the path holding the run of it from the anchor or crossing point before the click to the one after it, in the path's direction, goes directly above it; both keep the path's gradients where they were on it; the other objects stay as they are; with pickColorFrom \"swatches\" or fill, the run's stroke takes that paint; a path in a Live Paint group or a Shaper Group does not split, and nor does a path the run is all of, such as a lone line, or all but 0.05 pt or less of (a ten-thousandth of the larger side of a path over 500 pt)), tolerance?: pt (2, erase or splitStroke), gap?: pt (0–72; 0: Gap Detection off), openFilledAsClosed?: true (Consider Open Filled Paths as Closed: a filled open path bounds a region as if an invisible edge closed it, where filled means any fill row is shown, painted and above 0% opacity, whichever row is on top; false: it cuts the regions it crosses like an unfilled one), pickColorFrom?: \"artwork\" (default: the merged shape takes the look of the front-most object under the first point, else under the last point, else of the front-most object) | \"swatches\" (the current fill, with the rest of the look of the front-most object over the first region the drag touches that an object covers, else of the front-most object), fill?: \"#rrggbb\" | {color|swatch|gradient|none} (overrides pickColorFrom)} replaces the paths it uses where they are; other selected objects (type, hidden or locked objects, clipping paths) stay, and a group goes only when it is left empty → {ids (selected after: each selected object still there, or what took its place), merged, regions, lines, edges (counts deleted, merged or split), split?: id (the run split off, after a split)}; after a split, ids are the roots, with the rest and the run in place of the path when it was one", has_selection_or_ids, sb_merge ), @@ -117,7 +117,7 @@ pub fn specs() -> Vec { "Live Paint Bucket", [], None, - "{group?: id | ids?|id?: [id…] (paths to make live first, as livePaint.make does), point: [x,y], points?: [[x,y]…] (a drag polyline starting at point; 1 to 4096 finite canvas points; fills every crossed face of the same group), continuation?: [[[x,y]…]…] (further path chunks of 1 to 4096 finite canvas points each; each starts at the preceding chunk's last point; requires points), color?|swatch?|gradient?|none? (default: current fill; a color in #rrggbbaa or #rgba is refused), tint?: 0..100, keepModel?: bool (both as paint.setFill)} fill the face containing point, skipping hidden faces; when every face it reaches already has the paint, nothing changes (no undo step, and the recent colors stay as they are) → {group, face}", + "{group?: id | ids?|id?: [id…] (paths to make live first, as livePaint.make does), point: [x,y], points?: [[x,y]…] (a drag polyline starting at point; 1 to 4096 finite canvas points; fills every crossed face of the same group), continuation?: [[[x,y]…]…] (further path chunks of 1 to 4096 finite canvas points each; each starts at the preceding chunk's last point; requires points), scope?: \"one\" (default: the face alone) | \"connected\" (a double-click: also each face reached across edges that are hidden or draw no stroke, as a flood from the face; a stroked edge, a hidden face or a Gap Detection gap stops it) | \"samePaint\" (a triple-click: also every face of the group whose fill is match; \"connected\" and \"samePaint\" are refused with points), match?: paint (as the document stores it, the `fill` of a face's appearance; scope samePaint only; default: the face's fill), color?|swatch?|gradient?|none? (default: current fill; a color in #rrggbbaa or #rgba is refused), tint?: 0..100, keepModel?: bool (both as paint.setFill)} fill the face containing point, skipping hidden faces; when every face it reaches already has the paint, nothing changes (no undo step, and the recent colors stay as they are) → {group, face, count (faces reached)}", has_doc, lp_fill ), @@ -126,7 +126,7 @@ pub fn specs() -> Vec { "Live Paint Bucket (Stroke)", [], None, - "{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point; when it already has the paint and the width, nothing changes (no undo step, and the recent colors stay as they are) → {group, edge}", + "{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), scope?: \"one\" (default: the edge alone) | \"connected\" (a double-click: also each edge joined to it, end to end, through edges that draw with stroke paint match) | \"samePaint\" (a triple-click: also every edge of the group that draws with stroke paint match), match?: paint (as the document stores it; scope connected or samePaint only; default: the stroke paint the edge draws with; an edge draws with the paint of its topmost stroke that is shown, with paint, above 0 pt and not fully transparent, and with none when the edge is fully transparent or has no such stroke), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point, skipping hidden edges: each edge reached takes the paint and width in its topmost stroke that is shown, or in a new stroke above the others when it has none; when every edge it reaches already has the paint and the width there, nothing changes (no undo step, and the recent colors stay as they are) → {group, edge, count (edges reached)}", has_doc, lp_stroke_edge ), @@ -135,7 +135,7 @@ pub fn specs() -> Vec { "Live Paint Info", [], None, - "{group, id?: object id (default: the selection)} → {faces: [{id, fill, bounds}], edges: [{id, stroke, width}], sources, gapOptions: {detect, size: \"small\"|\"medium\"|\"large\"|pt, points, color: #rrggbb} (as livePaint.gapOptions sets them), gaps: [[x0,y0,x1,y1]…] (as livePaint.gapOptions returns them)}", + "{group?|id?: Live Paint group id (one required; id is read when group is left out)} → {faces: [{id, fill (top fill), bounds, appearance: [row…]}], edges: [{id, stroke (top stroke), width (top stroke's), appearance: [row…]}], where a row is {index (in the part's fill and stroke stack, bottom first), kind: \"fill\"|\"stroke\", paint, opacity: 0..1, visible, width?: pt (strokes only), drawn (the part is shown with opacity above 0, and the row is shown, has paint and opacity above 0, a stroke also width above 0)}, sources, gapOptions: {detect, size: \"small\"|\"medium\"|\"large\"|pt, points, color: #rrggbb} (as livePaint.gapOptions sets them), gaps: [[x0,y0,x1,y1]…] (as livePaint.gapOptions returns them)}", has_doc, lp_info ), diff --git a/crates/engine/src/cmd/buildcmds/live_paint.rs b/crates/engine/src/cmd/buildcmds/live_paint.rs index 9c3c750996..20e22d261e 100644 --- a/crates/engine/src/cmd/buildcmds/live_paint.rs +++ b/crates/engine/src/cmd/buildcmds/live_paint.rs @@ -1,7 +1,8 @@ use super::{ - Appearance, Arc, Beside, Document, EDGE_NAME, EngineError, FACE_NAME, GapOptions, GapSize, LIVE_PAINT_NAME, Node, NodeId, PathData, Point, Rect, - Result, SOURCES_NAME, Selection, Session, SubPath, Value, b, bad, build_children, edge_near, face_at, finite, ids_json, is_live_paint, json, - number_or, object_param, paint_from, po, point_param, repaint_from, replace_roots, root_ids, source_nodes, source_shapes, switch_or, + Appearance, AppearanceItem, Arc, Beside, Document, EDGE_NAME, EngineError, FACE_NAME, GapOptions, GapSize, LIVE_PAINT_NAME, Node, NodeId, + PathData, Point, Rect, Result, SOURCES_NAME, Selection, Session, SubPath, Value, b, bad, build_children, edge_near, face_at, finite, ids_json, + is_live_paint, json, number_or, object_param, paint_from, po, point_param, repaint_from, replace_roots, root_ids, source_nodes, source_shapes, + switch_or, }; /// `options` as stored on a Live Paint group: none for the defaults. @@ -362,9 +363,52 @@ pub(super) fn lp_gap_options(s: &mut Session, p: &Value) -> Result { Ok(json!({ "ids": ids_json(&targets), "faces": faces, "gaps": gaps_json(&gaps), "closed": closed })) } +/// Which parts a Live Paint Bucket click paints besides the one under the pointer. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum LpScope { + /// The part under the pointer alone (a click). + One, + /// A face and the faces reached from it across edges that draw no stroke ([`b::flood_faces`]), + /// or an edge and the edges joined to it end to end that draw with the same stroke paint + /// ([`b::connected_edges`], [`b::lp_stroke_paint`]) (a double-click). + Connected, + /// Every face with the same fill, or every edge that draws with the same stroke paint, in the + /// group (a triple-click). + SamePaint, +} + +/// The `scope` of `livePaint.fill` and `livePaint.strokeEdge`: `one` when left out or null. +fn scope_param(p: &Value, c: &str) -> Result { + match p.get("scope").filter(|v| !v.is_null()) { + None => Ok(LpScope::One), + Some(v) => match v.as_str() { + Some("one") => Ok(LpScope::One), + Some("connected") => Ok(LpScope::Connected), + Some("samePaint") => Ok(LpScope::SamePaint), + _ => Err(bad(c, "scope must be \"one\", \"connected\" or \"samePaint\"")), + }, + } +} + +/// The `match` of `livePaint.fill` and `livePaint.strokeEdge`: a paint as the document stores it, +/// None when left out or null. With `allowed` false (a scope that compares no paints) a `match` is +/// an error naming `scopes`, the scopes it applies to. +fn match_param(p: &Value, c: &str, allowed: bool, scopes: &str) -> Result> { + let Some(v) = p.get("match").filter(|v| !v.is_null()) else { return Ok(None) }; + if !allowed { + return Err(bad(c, format!("match applies only with scope {scopes}"))); + } + serde_json::from_value::(v.clone()).map(Some).map_err(|_| bad(c, "match must be a paint as the document stores it")) +} + pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result { const C: &str = "livePaint.fill"; let pt = point_param(p, "point").filter(|q| finite(*q)).ok_or_else(|| bad(C, "missing point [x,y]"))?; + let scope = scope_param(p, C)?; + let like = match_param(p, C, scope == LpScope::SamePaint, "\"samePaint\"")?; + if scope != LpScope::One && p.get("points").is_some() { + return Err(bad(C, "scope applies to a click: leave out points")); + } let parse_chunk = |input: &Value, start: Point| -> Result> { let values = input .as_array() @@ -399,7 +443,8 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result { let group = object_param(p, "group", C)?; let roots = if group.is_none() { root_ids(s, p)? } else { vec![] }; // The faces the click or drag paints in Live Paint group `gid`: the visible face at the point, - // and every visible face the drag crosses; → (the face at the point, the faces). + // the faces its scope adds, and every visible face the drag crosses; → (the face at the point, + // the faces). let targets_in = |d: &Document, gid: NodeId| -> Result<(NodeId, std::collections::BTreeSet)> { let fid = d .node(gid) @@ -407,6 +452,18 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result { .map(|f| f.id) .ok_or_else(|| EngineError::Other("no Live Paint face at that point".into()))?; let mut targets = std::collections::BTreeSet::from([fid]); + if scope != LpScope::One { + let n = d.node(gid).ok_or(EngineError::NoNode(gid))?; + if scope == LpScope::Connected { + targets.extend(b::flood_faces(n, fid)); + } else { + let like = match &like { + Some(m) => m.clone(), + None => d.node(fid).ok_or(EngineError::NoNode(fid))?.appearance.fill_paint(), + }; + targets.extend(b::faces(n).into_iter().filter(|f| f.visible && f.appearance.fill_paint() == like).map(|f| f.id)); + } + } if let Some(points) = points { let n = d.node(gid).ok_or(EngineError::NoNode(gid))?; // Use the existing region-crossing probes, so even a face narrower than the distance @@ -456,34 +513,36 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result { } } }; - let (g, face) = match live { + let (g, face, count) = match live { Some(gid) => { let (fid, targets) = targets_in(&s.doc()?.doc, gid)?; + let count = targets.len(); // Faces that already have the paint stay as they are: when every face has it, nothing // changes and no undo step is recorded. let d = &s.doc()?.doc; let unpainted: Vec = targets.into_iter().filter(|t| d.node(*t).is_none_or(|f| f.appearance.fill_paint() != paint)).collect(); if unpainted.is_empty() { - return Ok(json!({ "group": gid.0, "face": fid.0 })); + return Ok(json!({ "group": gid.0, "face": fid.0, "count": count })); } s.edit("Live Paint Bucket", |d, _| { for target in unpainted { d.node_mut(target).ok_or(EngineError::NoNode(target))?.appearance.set_fill(paint.clone()); } - Ok((gid, fid)) + Ok((gid, fid, count)) })? } None => s.edit("Live Paint Bucket", |d, sel| { let gid = make_live(d, sel, &roots)?.0; let (fid, targets) = targets_in(d, gid)?; + let count = targets.len(); for target in targets { d.node_mut(target).ok_or(EngineError::NoNode(target))?.appearance.set_fill(paint.clone()); } - Ok((gid, fid)) + Ok((gid, fid, count)) })?, }; s.remember_paint(&paint); - Ok(json!({ "group": g.0, "face": face.0 })) + Ok(json!({ "group": g.0, "face": face.0, "count": count })) } pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result { @@ -497,31 +556,103 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "width out of range")); } let tol = number_or(p, "tolerance", 4.0, C)?.clamp(0.0, 1000.0); - let (eid, unchanged) = { + let scope = scope_param(p, C)?; + let like = match_param(p, C, scope != LpScope::One, "\"connected\" or \"samePaint\"")?; + let (eid, count, changed) = { let d = &s.doc()?.doc; let n = d.node(g).filter(|n| is_live_paint(n)).ok_or_else(|| bad(C, format!("{g} is not a Live Paint group")))?; - let e = b::visible_edge_near(n, pt, tol).ok_or_else(|| EngineError::Other("no Live Paint edge near that point".into()))?; - // An edge that already has the paint and the width (or has no stroke and gets none) stays as - // it is, and no undo step is recorded. - let unchanged = match e.appearance.stroke() { - Some(st) => st.paint == paint && st.width == width, - None => paint.is_none(), + let start = b::visible_edge_near(n, pt, tol).ok_or_else(|| EngineError::Other("no Live Paint edge near that point".into()))?; + let eid = start.id; + let like = like.unwrap_or_else(|| b::lp_stroke_paint(start)); + let targets = match scope { + LpScope::One => vec![eid], + LpScope::Connected => b::connected_edges(n, eid, &like), + LpScope::SamePaint => std::iter::once(eid) + .chain(b::edges(n).into_iter().filter(|e| e.visible && e.id != eid && b::lp_stroke_paint(e) == like).map(|e| e.id)) + .collect(), }; - (e.id, unchanged) + let count = targets.len(); + // An edge whose shown stroke already has the paint and the width (or that has no shown stroke + // and gets none) stays as it is; when every edge does, nothing changes and no undo step is + // recorded. + let changed: Vec = targets + .into_iter() + .filter(|t| { + d.node(*t).is_none_or(|e| match shown_stroke(e) { + Some(st) => !(st.paint == paint && st.width == width), + None => !paint.is_none(), + }) + }) + .collect(); + (eid, count, changed) }; - if unchanged { - return Ok(json!({ "group": g.0, "edge": eid.0 })); + if changed.is_empty() { + return Ok(json!({ "group": g.0, "edge": eid.0, "count": count })); } - let edge = s.edit("Live Paint Bucket", |d, _| { - let e = d.node_mut(eid).ok_or(EngineError::NoNode(eid))?; - e.appearance.set_stroke(paint.clone()); - if let Some(st) = e.appearance.stroke_mut() { - st.width = width; + s.edit("Live Paint Bucket", |d, _| { + for target in &changed { + let e = d.node_mut(*target).ok_or(EngineError::NoNode(*target))?; + match shown_stroke_mut(e) { + Some(st) => { + st.paint = paint.clone(); + st.width = width; + } + None => e.appearance.items.push(super::AppearanceItem::Stroke(super::StrokeLayer::new(paint.clone(), width))), + } } - Ok(eid) + Ok(()) })?; s.remember_paint(&paint); - Ok(json!({ "group": g.0, "edge": edge.0 })) + Ok(json!({ "group": g.0, "edge": eid.0, "count": count })) +} + +/// The stroke `livePaint.strokeEdge` paints on Live Paint edge `e`: its topmost stroke that is +/// shown. None when it has no stroke or every stroke is hidden; the command then adds a stroke +/// above the others. +fn shown_stroke(e: &Node) -> Option<&super::StrokeLayer> { + e.appearance.items.iter().rev().find_map(|i| match i { + super::AppearanceItem::Stroke(s) if s.visible => Some(s), + _ => None, + }) +} + +/// [`shown_stroke`], to change. +fn shown_stroke_mut(e: &mut Node) -> Option<&mut super::StrokeLayer> { + e.appearance.items.iter_mut().rev().find_map(|i| match i { + super::AppearanceItem::Stroke(s) if s.visible => Some(s), + _ => None, + }) +} + +/// Every fill and stroke row of face or edge `n`, bottom first, as `livePaint.info` lists them. A +/// row is `drawn` when the part is shown with an opacity above 0 and the row is shown, has paint +/// and has an opacity above 0 (a stroke also a weight above 0): the rule of [`draws`], row by row. +fn appearance_rows(n: &Node) -> Vec { + let part_shown = n.visible && n.opacity > 0.0; + n.appearance + .items + .iter() + .enumerate() + .map(|(i, item)| { + let shown = part_shown && item.visible() && !item.paint().is_none() && item.opacity() > 0.0; + let mut row = json!({ + "index": i, + "kind": item.kind_name(), + "paint": item.paint().label(), + "opacity": item.opacity(), + "visible": item.visible(), + }); + let drawn = match item { + AppearanceItem::Fill(_) => shown, + AppearanceItem::Stroke(st) => { + row["width"] = json!(st.width); + shown && st.width > 0.0 + } + }; + row["drawn"] = json!(drawn); + row + }) + .collect() } pub(super) fn lp_info(s: &mut Session, p: &Value) -> Result { @@ -535,12 +666,24 @@ pub(super) fn lp_info(s: &mut Session, p: &Value) -> Result { .iter() .map(|f| { let bb = f.geometric_bounds().unwrap_or(Rect::ZERO); - json!({ "id": f.id.0, "fill": f.appearance.fill_paint().label(), "bounds": [bb.x0, bb.y0, bb.x1, bb.y1] }) + json!({ + "id": f.id.0, + "fill": f.appearance.fill_paint().label(), + "bounds": [bb.x0, bb.y0, bb.x1, bb.y1], + "appearance": appearance_rows(f), + }) }) .collect(); let edges: Vec = b::edges(n) .iter() - .map(|e| json!({ "id": e.id.0, "stroke": e.appearance.stroke_paint().label(), "width": e.appearance.stroke_width() })) + .map(|e| { + json!({ + "id": e.id.0, + "stroke": e.appearance.stroke_paint().label(), + "width": e.appearance.stroke_width(), + "appearance": appearance_rows(e), + }) + }) .collect(); let sources = b::sources(n).and_then(|g| g.children()).map(|c| c.len()).unwrap_or(0); let options = n.gap_options(); diff --git a/crates/engine/src/cmd/buildcmds/shape_builder.rs b/crates/engine/src/cmd/buildcmds/shape_builder.rs index fea79a0e6a..472ba2208b 100644 --- a/crates/engine/src/cmd/buildcmds/shape_builder.rs +++ b/crates/engine/src/cmd/buildcmds/shape_builder.rs @@ -63,7 +63,7 @@ pub(super) fn sb_merge(s: &mut Session, p: &Value) -> Result { && let Some(&q) = pts.first() && let Some((i, run)) = map.stroke_at(&outlines, q, tol) && let (Some(leaf), Some(drawn)) = (leaves.get(i), outlines.get(i)) - && let Some(rest) = po::cut_out(drawn, &run, open_filled_as_closed && !leaf.appearance.fill_paint().is_none(), b::outline_snap(drawn)) + && let Some(rest) = po::cut_out(drawn, &run, open_filled_as_closed && leaf.appearance.has_drawn_fill(), b::outline_snap(drawn)) && rest.length() > b::outline_snap(drawn) { // The path keeps the rest of it, and a copy of it with the run under the click goes diff --git a/crates/engine/src/cmd/buildcmds/trace.rs b/crates/engine/src/cmd/buildcmds/trace.rs index 11519b84be..a117bd453e 100644 --- a/crates/engine/src/cmd/buildcmds/trace.rs +++ b/crates/engine/src/cmd/buildcmds/trace.rs @@ -288,9 +288,10 @@ fn trace_library(c: &str, s: &Session, params: &mut tr::TraceParams) -> Result>) -> Result, /// The settings traced with, as JSON. @@ -600,7 +604,7 @@ fn prepare(s: &Session, c: &str, p: &Value) -> Result { let bytes = Arc::clone(&blob.bytes); let library = trace_library(c, s, &mut params)?; let traced_with = serde_json::to_value(¶ms).map_err(|e| EngineError::Other(e.to_string()))?; - let inputs = TraceInputs { target, image, params: traced_with, swatches: params.swatches.clone(), bytes }; + let inputs = TraceInputs { doc: s.doc()?.uid, target, image, params: traced_with, swatches: params.swatches.clone(), bytes }; Ok(Prepared { inputs, trace: params, view, params_json, preset_label, library }) } @@ -612,8 +616,9 @@ pub struct Traced { } impl Traced { - /// Hand it to the next run of its command with the same inputs ([`TraceRun::params`]), which - /// applies it as one undo step instead of tracing again. Any other trace drops it. + /// Hand it to the next run of its command with the same inputs ([`TraceRun::params`]) in the + /// document it was made in, which applies it as one undo step instead of tracing again. Any + /// other trace drops it, a trace in another document included. pub fn hand_in(self, s: &mut Session) { s.trace_hand_off = Some(self); } @@ -686,7 +691,7 @@ impl TraceRun { } /// Does it still apply: would the command trace the same object, image, pixels and settings - /// now? + /// now, in the document it was prepared in? pub fn current(&self, s: &Session) -> bool { prepare(s, self.command, &self.params).is_ok_and(|now| now.inputs == self.prepared.inputs) } @@ -1135,7 +1140,7 @@ mod trace_limit_tests { assert_eq!(w, ["Flat Logo traced the image at 946 × 710 pixels, averaged down from 16000 × 12000."]); } - // A 4000 × 3000 photo at High Fidelity Photo makes about 1.9 million anchors, which must fit; - // the limit still guards memory (about 90 bytes an anchor). Checked when the tests build. + // A 4000 × 3000 photo at Limited 64 colors, Paths 90, Corners 25 and Noise 4 makes about + // 1.9 million anchors, which must fit; the limit still guards memory (about 90 bytes an anchor). Checked when the tests build. const _: () = assert!(MAX_TRACE_ANCHORS >= 2_000_000 && MAX_TRACE_ANCHORS <= 16_000_000); } diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index 66295f50f2..8bf6841e17 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -9,7 +9,8 @@ //! ([`use_front_profiles`]): when they are assigned, when the working settings change, and when the //! document comes to the front or its assignment comes back (an open, a switch, a close, a revert, //! an undo or a rollback, [`Session::sync_front_profiles`]); the working spaces stay as Edit → Color -//! Settings set them. +//! Settings set them. A document drawn while another is in front draws through its own profiles +//! ([`doc_cms`]). use std::collections::BTreeMap; use std::sync::Arc; @@ -236,6 +237,9 @@ fn load_profile(s: &mut Session, p: &Value) -> Result { } else if proof_targets(&info.name) { // A new file of the CMYK profile View → Proof Setup targets: redraw. touch_all(s); + } else { + // Documents behind the front one draw through their own profiles: those assigned it redraw. + touch_assigned(s, &info.name); } Ok(json!({"name": info.name, "kind": info.kind, "remembered": remembered})) } @@ -266,9 +270,21 @@ fn remove_profile(s: &mut Session, p: &Value) -> Result { if proof_targets(&info.name) { touch_all(s); } + // Documents behind the front one draw through their own profiles: those assigned it redraw. + touch_assigned(s, &info.name); Ok(json!({"removed": info.name})) } +/// Redraw the open documents assigned the profile `name`. +fn touch_assigned(s: &mut Session, name: &str) { + for d in &mut s.docs { + let (rgb, cmyk) = doc_profiles(&d.doc); + if [rgb, cmyk].iter().any(|n| n.as_deref() == Some(name)) { + d.revision += 1; + } + } +} + /// Whether View → Proof Setup targets the CMYK profile `name`. fn proof_targets(name: &str) -> bool { matches!(proof::view().setup.target, ProofTarget::Cmyk(t) if t == name) @@ -285,6 +301,14 @@ pub fn doc_profiles(d: &vectorcraft_doc::Document) -> (Option, Option Arc { + let (rgb, cmyk) = doc_profiles(d); + cms::for_document(rgb.as_deref(), cmyk.as_deref()) +} + fn assign_profile(s: &mut Session, p: &Value) -> Result { const C: &str = "edit.assignProfile"; let (mut rgb, mut cmyk) = doc_profiles(&s.doc()?.doc); @@ -662,8 +686,15 @@ fn map_graph_colors(g: &mut vectorcraft_doc::GraphSpec, f: &mut dyn FnMut(&Color } } let styles = &mut g.label_styles; - for st in [&mut styles.values, &mut styles.categories, &mut styles.legend].into_iter().flatten() { - map_paint_colors(&mut st.fill, f); + // A legend fill of the labels' own stays theirs when `f` makes it black. The default black legend fill stays black, + // so the labels on dark pie wedges are still drawn white. + styles.mark_own_legend_fill(); + let own = styles.legend_fill_is_own(); + for (st, fill) in [(&mut styles.values, true), (&mut styles.categories, true), (&mut styles.legend, own)] { + let Some(st) = st else { continue }; + if fill { + map_paint_colors(&mut st.fill, f); + } map_paint_colors(&mut st.stroke, f); } for r in [&mut styles.values_rows, &mut styles.categories_rows, &mut styles.legend_rows].into_iter().flatten() { diff --git a/crates/engine/src/cmd/compositefonts/tests.rs b/crates/engine/src/cmd/compositefonts/tests.rs index cac6f4bdcb..da310a89b9 100644 --- a/crates/engine/src/cmd/compositefonts/tests.rs +++ b/crates/engine/src/cmd/compositefonts/tests.rs @@ -671,10 +671,11 @@ fn a_document_replaced_in_the_back_is_measured_before_it_comes_to_the_front() { } /// Type a document replaced in the back sets in a composite font that only the front document -/// defines is measured in that font while the front one is registered, and again, as missing, when -/// the replaced document comes to the front. +/// defines is measured as missing, though the front one is registered, also when the replaced +/// document defines no composite font, and still as missing when it comes to the front. #[test] -fn a_document_replaced_in_the_back_measures_a_font_it_lacks_again_in_front() { +fn a_document_replaced_in_the_back_measures_a_font_it_lacks_as_missing() { + let db = vectorcraft_text::FontDb::global(); let mut s = session(); let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Ab12", "size": 20, "font": "CF Lacked"})).unwrap()["id"].as_u64().unwrap(); let bytes = vectorcraft_format::save_file(&s.doc().unwrap().doc); @@ -682,8 +683,16 @@ fn a_document_replaced_in_the_back_measures_a_font_it_lacks_again_in_front() { s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Lacked")]})).unwrap(); assert!(s.replace_document(0, vectorcraft_format::load(&bytes).unwrap())); let back = text_in(&s, 0, id); - let expected = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &back).bounds; - assert_eq!(back.cached_bounds, Some(expected)); + assert!(s.documents()[0].doc.composite_fonts.is_empty()); + let in_front = vectorcraft_text::layout(db, &back).bounds; + // The same type set in a family nothing defines. + let mut nowhere = back.clone(); + for r in &mut nowhere.runs { + r.style.font_family = "No Such Family CF Lacked".into(); + } + let missing = vectorcraft_text::layout(db, &nowhere).bounds; + assert!((in_front.width() - missing.width()).abs() > 1e-6, "the front document's font draws otherwise"); + assert_eq!(back.cached_bounds, Some(missing)); assert!(s.set_active(0)); assert!(vectorcraft_text::FontDb::global().composite_font("CF Lacked").is_none()); let actual = text(&s, id); diff --git a/crates/engine/src/cmd/distortcmds.rs b/crates/engine/src/cmd/distortcmds.rs index 2dbb7a9a18..8f1b5b97e6 100644 --- a/crates/engine/src/cmd/distortcmds.rs +++ b/crates/engine/src/cmd/distortcmds.rs @@ -26,7 +26,7 @@ pub use perspective::perspective_click; use perspective::{ attach, edit_text, grid_set, grid_show, persp_draw, persp_move, persp_nudge, persp_transform, plane_match, plane_move, plane_set, release, }; -pub(crate) use perspective::{finish_edit_text, grid_of, perspective_rewrite, silent, store_grid, transform_again}; +pub(crate) use perspective::{finish_edit_text, grid_kept, grid_of, perspective_rewrite, silent, store_grid, transform_again}; pub fn specs() -> Vec { vec![ @@ -107,7 +107,7 @@ pub fn specs() -> Vec { "Perspective Grid Preset", [], None, - "{kind: 1|2|3 (its normal view) | name: a preset (see perspective.presets.list)} reset the grid to the preset fitted to the first artboard (and show it; attached objects stay attached)", + "{kind: 1|2|3 (its normal view) | name: a preset (see perspective.presets.list)} reset the grid to the preset fitted to the first artboard (and show it; attached objects stay attached). No undo step when the document already holds that grid; when only whether it shows or its active plane differs, those are set without one", has_doc, super::perspgrid::grid_preset ), diff --git a/crates/engine/src/cmd/distortcmds/perspective.rs b/crates/engine/src/cmd/distortcmds/perspective.rs index 62b72a8e0f..90d58541a6 100644 --- a/crates/engine/src/cmd/distortcmds/perspective.rs +++ b/crates/engine/src/cmd/distortcmds/perspective.rs @@ -18,7 +18,7 @@ pub(crate) fn store_grid(d: &mut Document, g: &PerspectiveGrid) { /// Whether `d` holds `g` as [`store_grid`] writes it (with `attached` cleared): then storing `g` /// leaves `d` as it is. -fn grid_kept(d: &Document, g: &PerspectiveGrid) -> bool { +pub(crate) fn grid_kept(d: &Document, g: &PerspectiveGrid) -> bool { let mut g = g.clone(); g.attached.clear(); serde_json::to_value(&g).is_ok_and(|v| d.unknown.get(persp::DOC_KEY) == Some(&v)) @@ -70,13 +70,26 @@ pub(super) fn grid_show(s: &mut Session, p: &Value) -> Result { None | Some(Value::Null) => None, Some(_) => Some(switch_or(p, "visible", false, C)?), }; - let g = silent(s, |g| g.visible = want.unwrap_or(!g.visible))?; + // A hidden grid holds no plane for Automatic Plane Positioning. + let g = silent(s, |g| { + g.visible = want.unwrap_or(!g.visible); + if !g.visible { + g.inferred = None; + } + })?; Ok(json!({ "visible": g.visible })) } pub(super) fn plane_set(s: &mut Session, p: &Value) -> Result { let plane = str_param(p, "plane").and_then(Plane::parse).ok_or_else(|| bad("perspective.plane.set", "plane must be left|right|ground|none"))?; - silent(s, |g| g.plane = plane)?; + // The new active plane passes through the point Automatic Plane Positioning holds, unless no + // plane is active or that would put the plane behind the viewer. + silent(s, |g| { + g.plane = plane; + if g.inferred.is_some() && (plane == Plane::None || g.validate().is_err()) { + g.inferred = None; + } + })?; Ok(json!({ "plane": plane.id() })) } @@ -91,9 +104,14 @@ fn plane_param(g: &PerspectiveGrid, p: &Value, cmd: &str) -> Result { Ok(plane) } +/// The objects a perspective command acts on: the outermost of `ids` (each once, in the order first +/// given), else the selection's roots. pub(super) fn roots(s: &Session, p: &Value) -> Result> { match named_ids(p)? { - Some(v) => Ok(outermost(&s.doc()?.doc, v)), + Some(v) => { + let mut seen = std::collections::HashSet::new(); + Ok(outermost(&s.doc()?.doc, v.into_iter().filter(|id| seen.insert(*id)).collect())) + } None => selected_roots(s), } } @@ -138,6 +156,9 @@ pub(super) fn attach(s: &mut Session, p: &Value) -> Result { store_grid(d, &g); Ok(()) })?; + if !ids.is_empty() { + crate::cmd::perspgrid::plane_positioning_used(s, plane)?; + } Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>(), "plane": plane.id() })) } @@ -205,8 +226,13 @@ fn persp_edit( return Err(EngineError::Other("select the objects to transform in perspective".into())); } let mut g = grid_of(&s.doc()?.doc); + // An object not in perspective yet attaches to `fallback` where that plane is now. + let attaches = { + let d = &s.doc()?.doc; + fallback.filter(|_| ids.iter().any(|id| g.attachment_of(d, *id).is_none())) + }; let kept = if copy && !stores_attachments(&s.doc()?.doc) { crate::cmd::object::preview_copies(s, ids, false)? } else { None }; - s.edit(label, |d, sel| { + let edited = s.edit(label, |d, sel| { g.adopt_stored_attachments(d); let targets = match &kept { // The document becomes the snapshot with the kept copies, not yet mapped, and the loop @@ -236,7 +262,11 @@ fn persp_edit( } store_grid(d, &g); Ok((targets, first)) - }) + })?; + if let Some(plane) = attaches { + crate::cmd::perspgrid::plane_positioning_used(s, plane)?; + } + Ok(edited) } /// Where the first of `ids` is in perspective (its plane and depth) when `ids` is not empty, every one @@ -430,6 +460,9 @@ pub(super) fn plane_move(s: &mut Session, p: &Value) -> Result { check_numbers(p, &["offset", "by"], C)?; let old = grid_of(&s.doc()?.doc); let plane = plane_param(&old, p, C)?; + // A plane that Automatic Plane Positioning holds moves from where it is held, and the move + // places it there for good: the moved grid holds no plane (undoing the move holds it again). + let held = old.inferred; let from = old.offset(plane); let to = match (p.get("offset").and_then(Value::as_f64), p.get("by").and_then(Value::as_f64)) { (Some(o), _) => o, @@ -440,7 +473,7 @@ pub(super) fn plane_move(s: &mut Session, p: &Value) -> Result { if !matches!(objects, "none" | "move" | "copy") { return Err(bad(C, "objects must be none, move or copy")); } - let mut g = old.clone(); + let mut g = PerspectiveGrid { inferred: None, ..old.clone() }; g.set_offset(plane, to); g.validate().map_err(|e| bad(C, e))?; let label = match objects { @@ -458,8 +491,9 @@ pub(super) fn plane_move(s: &mut Session, p: &Value) -> Result { .collect() }; // A plane moved to where it is, with its objects or without them, moves nothing: when the - // document holds the grid already, the document and its undo history stay as they are. - if to == from && objects != "copy" && grid_kept(&s.doc()?.doc, &g) { + // document holds the grid already, the document and its undo history stay as they are (a + // plane held where it was placed stays held). + if to == from && objects != "copy" && grid_kept(&s.doc()?.doc, &PerspectiveGrid { inferred: held, ..g.clone() }) { let ids = if objects == "move" { on_plane(&s.doc()?.doc) } else { vec![] }; return Ok(json!({ "plane": plane.id(), "offset": to, "ids": ids.iter().map(|i| i.0).collect::>() })); } @@ -507,12 +541,19 @@ pub(super) fn plane_match(s: &mut Session, p: &Value) -> Result { named_id(p)?.or_else(|| st.selection.objects.first().copied()).ok_or_else(|| EngineError::Other("select an object in perspective".into()))?; let mut g = grid_of(&st.doc); let (plane, depth) = g.attachment_of(&st.doc, id).ok_or_else(|| EngineError::Other("the object isn't in perspective".into()))?; + // The moved grid holds no plane for Automatic Plane Positioning (undoing the move holds it + // again). + let held = g.inferred.take(); g.set_offset(plane, depth); g.plane = plane; g.validate().map_err(|e| bad("perspective.plane.matchObject", e))?; // When the plane is at the object and active already, and the document holds that grid, the - // document and its undo history stay as they are. - if grid_kept(&st.doc, &g) { + // document and its undo history stay as they are; a plane held elsewhere goes back to that + // place as view state. + if grid_kept(&st.doc, &PerspectiveGrid { inferred: held, ..g.clone() }) { + if held.is_some() { + silent(s, |g| g.inferred = None)?; + } return Ok(json!({ "plane": plane.id(), "offset": depth })); } s.edit("Move Plane to Match Object", |d, _| { @@ -573,6 +614,7 @@ pub(super) fn persp_draw(s: &mut Session, p: &Value) -> Result { st.history.recost_last(&st.doc); } res?; + crate::cmd::perspgrid::plane_positioning_used(s, plane)?; Ok(json!({ "id": id.0, "plane": plane.id() })) } diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index 53949fdaf0..ffa11e362c 100644 --- a/crates/engine/src/cmd/draw2/commands.rs +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -11,7 +11,7 @@ pub fn specs() -> Vec { "Pencil", [], None, - "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\"|\"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end: \"start\"|\"end\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end; with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it", + "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\"|\"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end: \"start\"|\"end\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it", has_doc, freehand ), @@ -110,7 +110,7 @@ pub fn specs() -> Vec { "Smooth", [], None, - "{points: [[x,y]…], radius?: pt (12), fidelity?: pt (2.5; kept within 0.000078125 and about 3195, the Smooth tool's 0.05 to 100 px at the highest and the lowest zoom: the tool sends its Fidelity in screen pixels divided by the zoom)} smooth selected paths near the drag → {ids, before, after}", + "{points: [[x,y]…], radius?: pt (12), fidelity?: pt (2.5; kept within 0.000078125 and about 3195, the Smooth tool's 0.05 to 100 px at the highest and the lowest zoom: the tool sends its Fidelity in screen pixels divided by the zoom)} smooth selected paths near the drag, keeping a corner where the path turns by more than 57.5° at the anchor and over radius and twice radius on either side → {ids, before, after}", has_selection, smooth_region ), diff --git a/crates/engine/src/cmd/draw2/freehand.rs b/crates/engine/src/cmd/draw2/freehand.rs index 0439aaa081..401bdd2977 100644 --- a/crates/engine/src/cmd/draw2/freehand.rs +++ b/crates/engine/src/cmd/draw2/freehand.rs @@ -217,11 +217,18 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result { } None => None, }; - // An extending stroke that ends within four Fidelities of the path's other end closes it: - // at least 6 pt and at most 400 pt, whatever the Fidelity it is fitted at. + // `closed`, when given, says whether the stroke closes the path: the Pencil and the + // Paintbrush send it, by their Close Paths When Ends Are Within and Alt at the release. + // Left out, an extending stroke that ends within four Fidelities of the path's other end + // closes it: at least 6 pt and at most 400 pt, whatever the Fidelity it is fitted at. let close_tol = (tol * 4.0).clamp(6.0, 400.0); - let closing = connect.is_none() && sp.anchors.len() >= 2 && pts.last().is_some_and(|p| p.distance(first) <= close_tol); - if closing && let Some(l) = pts.last_mut() { + let near_first = pts.last().is_some_and(|p| p.distance(first) <= close_tol); + let wants_close = if p.get("closed").is_some_and(|v| !v.is_null()) { closed } else { near_first }; + let closing = connect.is_none() && sp.anchors.len() >= 2 && wants_close; + // A stroke ending near the other end ends on it; one ending farther away closes with a + // straight segment back to it. + let ends_on_first = closing && near_first; + if ends_on_first && let Some(l) = pts.last_mut() { *l = first; } if let Some((_, _, y, _)) = &connect @@ -238,13 +245,23 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result { add.remove(0); } sp.anchors.extend(add); - if closing + if ends_on_first && sp.anchors.len() > 2 && let Some(l) = sp.anchors.pop() && let Some(a0) = sp.anchors.first_mut() { a0.h_in = l.h_in; sp.closed = true; + } else if closing && !ends_on_first && sp.anchors.len() > 2 { + // Closed from away from the other end: a straight segment back to it, whatever + // handles the open ends carried. + sp.closed = true; + if let Some(l) = sp.anchors.last_mut() { + l.h_out = l.p; + } + if let Some(f) = sp.anchors.first_mut() { + f.h_in = f.p; + } } for a in &mut sp.anchors { *a = Anchor::with_handles(a.p, a.h_in, a.h_out); diff --git a/crates/engine/src/cmd/draw2/smooth.rs b/crates/engine/src/cmd/draw2/smooth.rs index 560990cec1..be7db9a1ae 100644 --- a/crates/engine/src/cmd/draw2/smooth.rs +++ b/crates/engine/src/cmd/draw2/smooth.rs @@ -13,9 +13,237 @@ use super::{ /// of path within the reach on either side of it. VectorCraft's own value. const SMOOTH_SPREAD: f64 = 1.0 / 3.0; +/// The degrees by which a path must turn at an anchor, and over the tool's reach and twice its reach +/// on either side of it, for the Smooth tool to keep the anchor as a corner ([`smooth_corners`]): a +/// turn of more than 57.5°, an angle inside the corner of less than 122.5°. VectorCraft's own value, +/// the same on every drag and at any Fidelity. +const SMOOTH_CORNER_DEG: f64 = 57.5; + +/// Most pieces a curved segment is cut into evenly, and most more pieces near each of its ends, to +/// measure lengths along it in [`smooth_corners`]. +const CORNER_PIECES: usize = 64; + +/// The control polygon's length of `c`, which is at least its length. +fn polygon_len(c: CubicBez) -> f64 { + c.p0.distance(c.p1) + c.p1.distance(c.p2) + c.p2.distance(c.p3) +} + +/// The places (0 to 1, in order, without 0 and with 1) on the curved segment `c` that +/// [`smooth_corners`] measures it at: up to [`CORNER_PIECES`] evenly spaced, and near each end, over +/// a stretch at least three times `reach` long where the segment is that long, up to as many more +/// that are no more than `reach` / 8 apart along the control polygon, and as many again in each +/// stretch twice as long after it until the pieces reach three times `reach`. The turns over `reach` and +/// twice `reach` from an anchor are then measured along the curve however long the segment is. +fn corner_places(c: CubicBez, reach: f64) -> Vec { + let piece = reach / 8.0; + let pieces = |len: f64| if piece > 0.0 { (len / piece).ceil().clamp(1.0, CORNER_PIECES as f64) as usize } else { 1 }; + let k = pieces(polygon_len(c)).max(4); + let mut places: Vec = (1..=k).map(|j| j as f64 / k as f64).collect(); + if piece > 0.0 { + for from_start in [true, false] { + // The stretch from the end: halved until its control polygon is at most six reaches long. + let first = 1.0 / k as f64; + let mut t = first; + let part = |t: f64| if from_start { c.subsegment(0.0..t) } else { c.subsegment(1.0 - t..1.0) }; + for _ in 0..60 { + if polygon_len(part(t)) <= 6.0 * reach { + break; + } + t /= 2.0; + } + let side = |u: f64| if from_start { u } else { 1.0 - u }; + let m = pieces(polygon_len(part(t))); + let mut fine: Vec = (1..=m).map(|j| t * j as f64 / m as f64).collect(); + // Then the stretches twice as long in turn, cut as finely, up to the first even place, until + // the pieces reach three reaches from the end, so twice the reach is measured along the curve + // where a handle that does not reach out makes the curve start more slowly than its polygon. + let mut covered = 0.0; + let mut at = c.eval(side(0.0)); + for u in &fine { + let q = c.eval(side(*u)); + covered += at.distance(q); + at = q; + } + let (mut from, mut levels) = (t, 0); + while covered < 3.0 * reach && from < first && levels < 60 { + let to = (2.0 * from).min(first); + let piece_len = polygon_len(if from_start { c.subsegment(from..to) } else { c.subsegment(1.0 - to..1.0 - from) }); + let m = pieces(piece_len); + for j in 1..=m { + let u = from + (to - from) * j as f64 / m as f64; + let q = c.eval(side(u)); + covered += at.distance(q); + at = q; + fine.push(u); + } + (from, levels) = (to, levels + 1); + } + places.extend(fine.into_iter().map(side)); + } + } + places.retain(|u| *u > 0.0 && *u <= 1.0); + places.sort_by(f64::total_cmp); + places.dedup(); + places +} + +/// The degrees between the directions `u` and `v`, `None` when either has no length or is not a +/// number. +fn turn_between(u: kurbo::Vec2, v: kurbo::Vec2) -> Option { + let (lu, lv) = (u.hypot(), v.hypot()); + if !(lu.is_finite() && lv.is_finite() && lu > 1e-12 && lv > 1e-12) { + return None; + } + let deg = u.cross(v).atan2(u.dot(v)).abs().to_degrees(); + deg.is_finite().then_some(deg) +} + +/// Which anchors of `anchors` (a closed path when `closed`) the Smooth tool keeps as corners: those +/// where the path turns by more than [`SMOOTH_CORNER_DEG`] at the anchor itself, between the +/// direction it arrives along and the one it leaves along, and also over `reach` and over twice +/// `reach` on either side of it, between the direction from the point that far back along the path +/// to the anchor and the direction from the anchor to the point that far ahead. The points are taken +/// no farther than the ends of an open path, and no more than an eighth of the way round a closed +/// one. A jag or a bump smaller than the reach turns sharply at its anchor but not over twice the +/// reach, and an anchor in the middle of a tight curve turns over the reach but not at the anchor, so +/// neither is kept. An open path's first and last anchors are never corners. +fn smooth_corners(anchors: &[Anchor], closed: bool, reach: f64) -> Vec { + let n = anchors.len(); + let mut corners = vec![false; n]; + if n < 2 || (n < 3 && !closed) { + return corners; + } + // The distances on either side the turn is measured over: one reach and two, no more than an + // eighth of the way round a closed path. Over that much of a circle the path turns by 45°, so a + // loop shorter than the reach is not all corners, while a square's or a triangle's corners still are. + let mut spans = [reach, 2.0 * reach]; + if closed { + let mut total = 0.0; + for i in 0..n { + total += walk(anchors, closed, (i, true), [f64::INFINITY; 2], reach, 1).1; + } + if !(total.is_finite() && total > 0.0) { + return corners; + } + spans = spans.map(|r| r.min(total / 8.0)); + } + for (i, flag) in corners.iter_mut().enumerate() { + if !closed && (i == 0 || i == n - 1) { + continue; + } + let (prev, a, next) = (anchors[(i + n - 1) % n], anchors[i], anchors[(i + 1) % n]); + let arrive = [a.p - a.h_in, a.p - prev.h_out, a.p - prev.p].into_iter().find(|d| d.hypot() > 1e-12).unwrap_or_default(); + let leave = [a.h_out - a.p, next.h_in - a.p, next.p - a.p].into_iter().find(|d| d.hypot() > 1e-12).unwrap_or_default(); + if !turn_between(arrive, leave).is_some_and(|t| t > SMOOTH_CORNER_DEG) { + continue; + } + let [Some(back_near), Some(back_far)] = walk(anchors, closed, (i, false), spans, reach, MAX_CORNER_WALK).0 else { continue }; + let [Some(ahead_near), Some(ahead_far)] = walk(anchors, closed, (i, true), spans, reach, MAX_CORNER_WALK).0 else { continue }; + *flag = [(back_near, ahead_near, spans[0]), (back_far, ahead_far, spans[1])] + .into_iter() + .all(|(back, ahead, r)| r <= 0.0 || turn_between(a.p - back, ahead - a.p).is_some_and(|t| t > SMOOTH_CORNER_DEG)); + } + corners +} + +/// Most segments [`walk`] passes from an anchor before it stops, which bounds the work for each +/// anchor on a path of very many very short segments. +const MAX_CORNER_WALK: usize = 256; + +/// A walk along the path `anchors` from anchor `from.0`, ahead when `from.1` and back otherwise, +/// past no more than `segments` segments, measured along the lines between each curved segment's +/// points at [`corner_places`]. It gives the points at the distances `to` (in order, the nearer +/// first), an open path's end for one beyond the end, and `None` for one it did not reach within +/// `segments` segments, and the length it walked. Both points are `None` when it meets a length that +/// is not a number or is too large to add, and the length is then infinite. +fn walk(anchors: &[Anchor], closed: bool, from: (usize, bool), to: [f64; 2], reach: f64, segments: usize) -> ([Option; 2], f64) { + let (n, forward) = (anchors.len(), from.1); + let Some(mut here) = anchors.get(from.0).map(|a| a.p) else { return ([None; 2], 0.0) }; + let (mut at, mut gone) = (from.0, 0.0); + let mut found: [Option; 2] = [None; 2]; + let mut at_end = false; + 'segments: for _ in 0..segments { + let next = match (forward, closed) { + (true, _) if at + 1 < n => at + 1, + (true, true) => 0, + (false, _) if at > 0 => at - 1, + (false, true) => n - 1, + _ => { + at_end = true; + break; + } + }; + let (a, b) = (anchors[at], anchors[next]); + let c = if forward { CubicBez::new(a.p, a.h_out, b.h_in, b.p) } else { CubicBez::new(a.p, a.h_in, b.h_out, b.p) }; + let places = if c.p1 == c.p0 && c.p2 == c.p3 { vec![1.0] } else { corner_places(c, reach) }; + for u in places { + let q = if u >= 1.0 { c.p3 } else { c.eval(u) }; + let d = here.distance(q); + if !(d.is_finite() && (gone + d).is_finite()) { + return ([None; 2], f64::INFINITY); + } + for (slot, &dist) in found.iter_mut().zip(&to) { + if slot.is_none() && gone + d >= dist { + let t = if d > 0.0 { ((dist - gone) / d).clamp(0.0, 1.0) } else { 1.0 }; + *slot = Some(here.lerp(q, t)); + } + } + gone += d; + here = q; + if found.iter().all(Option::is_some) { + break 'segments; + } + } + at = next; + } + // An open path that ends after the last segment walked ends there too. + if !closed && at == if forward { n - 1 } else { 0 } { + at_end = true; + } + (found.map(|p| p.or(at_end.then_some(here))), gone) +} + +/// Whether `a` and `b` are the same anchors, to within a rounding error. +fn same_anchors(a: &[Anchor], b: &[Anchor]) -> bool { + let near = |p: Point, q: Point| p.distance(q) <= 1e-9; + a.len() == b.len() && a.iter().zip(b).all(|(x, y)| near(x.p, y.p) && near(x.h_in, y.h_in) && near(x.h_out, y.h_out)) +} + +/// [`refit_run`] of the open run `anchors` cut at its anchors marked in `corners`: each part between +/// two corners is smoothed and refitted on its own, so each corner keeps its place and the direction +/// the path arrives and leaves along. `free` applies to the run's first and last anchors only. +fn refit_split(anchors: &[Anchor], corners: &[bool], tol: f64, sigma: f64, free: [bool; 2]) -> Vec { + let last = anchors.len().saturating_sub(1); + let mut cuts: Vec = (1..last).filter(|&i| corners.get(i).copied().unwrap_or(false)).collect(); + if cuts.is_empty() { + return refit_run(anchors, tol, sigma, free); + } + cuts.insert(0, 0); + cuts.push(last); + let mut out: Vec = Vec::with_capacity(anchors.len()); + for w in cuts.windows(2) { + let (a, b) = (w[0], w[1]); + let part = refit_run(&anchors[a..=b], tol, sigma, [free[0] && a == 0, free[1] && b == last]); + match out.pop() { + // The corner ends one part and starts the next: it keeps its place, and takes the handle + // in from the part before and the handle out from the part after. + Some(end) => { + let mut rest = part.into_iter(); + if let Some(start) = rest.next() { + out.push(Anchor::with_handles(anchors[a].p, end.h_in, start.h_out)); + } + out.extend(rest); + } + None => out.extend(part), + } + } + out +} + /// The options the Smooth tool refits with: the path smoothed along its length by a Gaussian of /// spread `sigma` (none at 0), then refitted within `tol` of that and within twice the distance the -/// smoothing moved it, keeping a corner only where the path turns back on itself. `free` says whether +/// smoothing moved it. The tool cuts the path at its corners first ([`smooth_corners`]), so within a +/// part the refit keeps a corner only where the path turns back on itself. `free` says whether /// the start and the end of the stretch refitted are ends of an open path, whose direction then /// follows the smoothed path within the reach rather than the first or last segment. fn refit_options(tol: f64, sigma: f64, free: [bool; 2]) -> SimplifyOptions { @@ -49,6 +277,84 @@ fn refit_run(anchors: &[Anchor], tol: f64, sigma: f64, free: [bool; 2]) -> Vec (usize, f64) { + let mut best: Option<(f64, usize, f64)> = None; + for j in 0..orig.anchors.len() { + let hit = orig.segment(j).nearest(p, 1e-9); + if hit.distance_sq.is_finite() && hit.t.is_finite() && best.is_none_or(|(d, ..)| hit.distance_sq < d) { + best = Some((hit.distance_sq, j, hit.t)); + } + } + best.map_or((usize::MAX, f64::INFINITY), |(_, j, t)| (j, t)) +} + +/// The closed `sp` started at the point on it nearest `start`: at the anchor there, or at a new +/// anchor split into the segment there, which leaves the outline as it is. Of points equally near +/// `start`, the one earliest along `orig` (the path before smoothing) from its first anchor is used, +/// then the first in `sp`'s order. An open `sp`, or one with no segment or no finite nearest point, +/// is returned as it is. +fn start_nearest(mut sp: SubPath, start: Point, orig: &SubPath) -> SubPath { + let n = sp.anchors.len(); + if !sp.closed || n < 2 { + return sp; + } + // (distance, place along `orig` once a tie needs it, segment of `sp`, parameter) + type Best = (f64, Option<(usize, f64)>, usize, f64); + let mut best: Option = None; + for i in 0..n { + let c = sp.segment(i); + let hit = c.nearest(start, 1e-9); + if !hit.distance_sq.is_finite() || !hit.t.is_finite() { + continue; + } + let d = hit.distance_sq.sqrt(); + match &mut best { + None => best = Some((d, None, i, hit.t)), + Some((bd, bplace, bi, bt)) if (d - *bd).abs() <= START_TIE => { + let held = *bplace.get_or_insert_with(|| place_along(orig, sp.segment(*bi).eval(*bt))); + let place = place_along(orig, c.eval(hit.t)); + if place.0 < held.0 || (place.0 == held.0 && place.1 < held.1) { + best = Some((d, Some(place), i, hit.t)); + } + } + Some((bd, ..)) if d < *bd => best = Some((d, None, i, hit.t)), + Some(_) => {} + } + } + let Some((_, _, i, t)) = best else { return sp }; + let c = sp.segment(i); + let at = c.eval(t); + let first = if at.distance(c.p0) <= START_SNAP { + i + } else if at.distance(c.p3) <= START_SNAP { + (i + 1) % n + } else { + let mid = if sp.segment_is_line(i) { + Anchor::corner(at) + } else { + let (l, r) = (c.subsegment(0.0..t), c.subsegment(t..1.0)); + sp.anchors[i].h_out = l.p1; + sp.anchors[(i + 1) % n].h_in = r.p2; + Anchor::with_handles(at, l.p2, r.p1) + }; + sp.anchors.insert(i + 1, mid); + i + 1 + }; + sp.anchors.rotate_left(first); + sp +} + /// Pieces of curve that one Smooth drag measures against the drag while it searches the segments /// under it ([`reach_samples`]), shared equally by the curved segments that come within its reach, /// each of which gets at least one: enough to search 300,000 pt of curve within the default reach @@ -226,6 +532,9 @@ fn mark_reached(sp: &SubPath, pts: &[Point], radius: f64, share: usize) -> (SubP (out, marked) } +/// `sp` with the anchors in the drag's reach smoothed and refitted, `None` when none are in reach. +/// A closed path whose first anchor is in reach starts at the point of the refitted path nearest +/// that anchor's place (VectorCraft's own rule). fn smooth_subpath(sp: &SubPath, pts: &[Point], radius: f64, share: usize, tol: f64, sigma: f64) -> Option { if sp.anchors.len() < 2 { return None; @@ -238,10 +547,33 @@ fn smooth_subpath(sp: &SubPath, pts: &[Point], radius: f64, share: usize, tol: f return None; } if sp.closed { + let start = sp.anchors[0].p; let Some(k) = marked.iter().position(|m| !m) else { - // Everything is in range: smooth the whole closed path, across its start too. - let f = po::simplify_with(&PathData::single(sp.clone()), &refit_options(tol, sigma, [false; 2])); - return f.subpaths.into_iter().next(); + let corners = smooth_corners(&sp.anchors, true, radius); + let Some(c) = corners.iter().position(|c| *c) else { + // Everything is in range and nothing is a corner: smooth the whole closed path, + // across its start too. + let f = po::simplify_with(&PathData::single(sp.clone()), &refit_options(tol, sigma, [false; 2])); + return f.subpaths.into_iter().next().map(|r| start_nearest(r, start, sp)); + }; + // Cut the path open at a corner, which then ends the last part as well as starting the first. + let mut open = sp.anchors.clone(); + open.rotate_left(c); + let mut cut = corners; + cut.rotate_left(c); + open.push(open[0]); + cut.push(true); + let mut res = refit_split(&open, &cut, tol, sigma, [false; 2]); + if same_anchors(&res, &open) { + return None; + } + let l = res.pop()?; + if let Some(r0) = res.first_mut() { + *r0 = Anchor::with_handles(r0.p, l.h_in, r0.h_out); + } + // The path starts where it did when the refit keeps an anchor there, and otherwise at its + // point nearest there. + return Some(start_nearest(SubPath::new(res, true), start, sp)); }; // Rotate so an untouched anchor comes first, duplicate it at the end and treat as open. let mut open = sp.clone(); @@ -251,14 +583,20 @@ fn smooth_subpath(sp: &SubPath, pts: &[Point], radius: f64, share: usize, tol: f open.anchors.push(open.anchors[0]); m.push(false); open.closed = false; - let mut res = smooth_open(&open.anchors, &m, near, tol, sigma, false); + let mut res = smooth_open(&open.anchors, &m, near, tol, sigma, radius, false); + if same_anchors(&res, &open.anchors) { + return None; + } let l = res.pop()?; if let Some(r0) = res.first_mut() { r0.h_in = l.h_in; } - return Some(SubPath::new(res, true)); + // With k = 0 the first anchor is out of reach and still starts the result. + let res = SubPath::new(res, true); + return Some(if k == 0 { res } else { start_nearest(res, start, sp) }); } - Some(SubPath::new(smooth_open(&sp.anchors, &marked, near, tol, sigma, true), false)) + let res = smooth_open(&sp.anchors, &marked, near, tol, sigma, radius, true); + (!same_anchors(&res, &sp.anchors)).then(|| SubPath::new(res, false)) } /// The segment `c`, which ends in the drag's reach (`near`) and starts outside it, split where it @@ -292,8 +630,10 @@ fn split_at_reach(c: CubicBez, near: &dyn Fn(Point) -> bool) -> Option<(CubicBez /// drag's reach (`near`): a short drag smooths what is under it, and the rest of a long segment next /// to it stays as it was (#1512). With `open`, `anchors` are an open path, and the curve at its first /// or last anchor turns with the smoothing when a run's refit reaches that anchor; a run's other ends, -/// and those of the open run a closed path is cut into, keep their direction. -fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool, tol: f64, sigma: f64, open: bool) -> Vec { +/// and those of the open run a closed path is cut into, keep their direction. Each run keeps its +/// corners ([`smooth_corners`] within `radius`, the tool's reach, measured within the run), and a run +/// whose refit changes nothing stays as it was. +fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool, tol: f64, sigma: f64, radius: f64, open: bool) -> Vec { let n = anchors.len(); let mut runs = vec![]; let mut i = 0; @@ -334,7 +674,11 @@ fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool *outer = Anchor::with_handles(far.p3, far.p2, reach.p1); } let free = [open && lo == 0 && head.is_none(), open && hi == n - 1 && tail.is_none()]; - let new = refit_run(&piece, tol, sigma, free); + let corners = smooth_corners(&piece, false, radius); + let new = refit_split(&piece, &corners, tol, sigma, free); + if same_anchors(&new, &piece) { + continue; + } out.splice(lo..=hi, head.into_iter().chain(new).chain(tail)); } out @@ -621,6 +965,89 @@ pub(super) fn join_scrub(s: &mut Session, p: &Value) -> Result { mod tests { use super::*; + /// A closed ring of four smooth anchors round (100, 100) with radius 50. + fn ring() -> SubPath { + let k = 0.5523 * 50.0; + let a = |x: f64, y: f64, dx: f64, dy: f64| Anchor::with_handles(Point::new(x, y), Point::new(x - dx, y - dy), Point::new(x + dx, y + dy)); + SubPath::new(vec![a(150.0, 100.0, 0.0, k), a(100.0, 150.0, -k, 0.0), a(50.0, 100.0, 0.0, -k), a(100.0, 50.0, k, 0.0)], true) + } + + /// A start between two anchors of a curve splits that curve there into two that trace it, and the + /// new anchor comes first. + #[test] + fn start_nearest_splits_a_curve_where_it_passes_the_start() { + let sp = ring(); + let old = sp.segment(0); + let start = old.eval(0.3) + (old.eval(0.3) - Point::new(100.0, 100.0)) * 0.1; + let out = start_nearest(sp.clone(), start, &sp); + assert!(out.closed && out.anchors.len() == 5, "{out:?}"); + let t = old.nearest(start, 1e-9).t; + assert!(out.anchors[0].p.distance(old.eval(t)) < 1e-9, "{out:?}"); + let (head, rest) = (out.segment(4), out.segment(0)); + for k in 0..=8 { + let u = f64::from(k) / 8.0; + assert!(head.eval(u).distance(old.eval(t * u)) < 1e-9); + assert!(rest.eval(u).distance(old.eval(t + (1.0 - t) * u)) < 1e-9); + } + for i in 1..4 { + assert_eq!(out.segment(i), sp.segment(i), "segment {i} stays"); + } + } + + /// A start within [`START_SNAP`] of an anchor starts the ring at that anchor, with no anchor added. + #[test] + fn start_nearest_starts_at_an_anchor_near_the_start() { + let sp = ring(); + let out = start_nearest(sp.clone(), Point::new(50.0, 100.0 + START_SNAP / 2.0), &sp); + let mut want = sp.anchors.clone(); + want.rotate_left(2); + assert_eq!(out.anchors, want); + } + + /// A start on a straight side of a triangle adds a corner point there without handles, and the + /// sides stay straight. + #[test] + fn start_nearest_splits_a_line_with_a_corner_point() { + let sp = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(50.0, 80.0)], true); + let out = start_nearest(sp.clone(), Point::new(40.0, -5.0), &sp); + let want: Vec = [(40.0, 0.0), (100.0, 0.0), (50.0, 80.0), (0.0, 0.0)].map(|(x, y)| Point::new(x, y)).to_vec(); + assert!(out.anchors.len() == 4 && out.anchors.iter().zip(&want).all(|(a, w)| a.p.distance(*w) < 1e-9), "{out:?}"); + assert!((0..4).all(|i| out.segment_is_line(i)), "{out:?}"); + } + + /// A ring whose last anchor lies on its first keeps its first anchor first, and gets no third + /// anchor at that place. + #[test] + fn start_nearest_keeps_the_first_of_two_anchors_on_one_place() { + let p = [(0.0, 0.0), (100.0, 0.0), (50.0, 80.0), (0.0, 0.0)].map(|(x, y)| Point::new(x, y)); + let sp = SubPath::polyline(&p, true); + assert_eq!(start_nearest(sp.clone(), p[0], &sp), sp); + } + + /// Of points equally near the start, the one earliest along the path before smoothing from its + /// first anchor comes first, whatever the smoothed path's order. The center of a square is equally + /// near the middle of each side. The square before smoothing starts at (-50, -50), so the middle + /// of its first side, (0, -50), comes first, though the smoothed copy starts at (50, 50). + #[test] + fn start_nearest_breaks_a_tie_by_the_order_before_smoothing() { + let p = [(-50.0, -50.0), (50.0, -50.0), (50.0, 50.0), (-50.0, 50.0)].map(|(x, y)| Point::new(x, y)); + let orig = SubPath::polyline(&p, true); + let mut sp = orig.clone(); + sp.anchors.rotate_left(2); + let out = start_nearest(sp, Point::new(0.0, 0.0), &orig); + assert!(out.closed && out.anchors.len() == 5, "{out:?}"); + assert!(out.anchors[0].p.distance(Point::new(0.0, -50.0)) < 1e-9, "{out:?}"); + assert!(out.anchors[1].p.distance(p[1]) < 1e-9, "{out:?}"); + } + + /// An open path, and a start that is not a number, leave the path as it is. + #[test] + fn start_nearest_leaves_an_open_path_or_a_start_without_a_place() { + let open = SubPath { closed: false, ..ring() }; + assert_eq!(start_nearest(open.clone(), Point::new(100.0, 50.0), &ring()), open); + assert_eq!(start_nearest(ring(), Point::new(f64::NAN, 0.0), &ring()), ring()); + } + /// Searching a curve 1,000,000 pt long under a drag of 1,000 points along it measures no more /// pieces than the budget it is given, and a search with none left gives one sample. #[test] @@ -649,4 +1076,123 @@ mod tests { assert_eq!(drag_stretches(&one), vec![0]); assert!((dist_to_stretches(&one, &[0], Point::new(13.0, 14.0)) - 5.0).abs() < 1e-12); } + + fn polyline(pts: &[(f64, f64)]) -> Vec { + pts.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect() + } + + /// Anchors on one point, anchors that are not numbers or are too far out to measure, and a + /// zigzag of 100,001 anchors 1 pt high give no corner and do not fail; a square's four anchors + /// are its corners, and an open path's ends never are. + #[test] + fn corners_are_found_only_where_the_path_turns_at_and_around_an_anchor() { + assert_eq!(smooth_corners(&polyline(&[(5.0, 5.0); 4]), false, 12.0), vec![false; 4]); + assert_eq!(smooth_corners(&polyline(&[(0.0, 0.0), (f64::NAN, 1.0), (10.0, 0.0)]), false, 12.0), vec![false; 3]); + assert_eq!(smooth_corners(&polyline(&[(0.0, 0.0), (1e308, 0.0), (1e308, 1e308), (-1e308, 0.0)]), true, 12.0), vec![false; 4]); + let zigzag: Vec<(f64, f64)> = (0..=100_000).map(|i| (f64::from(i), f64::from(i % 2))).collect(); + assert!(!smooth_corners(&polyline(&zigzag), false, 12.0).contains(&true)); + let square = polyline(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]); + assert_eq!(smooth_corners(&square, true, 12.0), vec![true; 4]); + assert_eq!(smooth_corners(&square, false, 12.0), vec![false, true, true, false]); + assert_eq!(smooth_corners(&square, false, 0.0), vec![false, true, true, false], "with no reach the turn at the anchor decides"); + assert_eq!(smooth_corners(&square[..2], false, 12.0), vec![false; 2]); + } + + /// A 90° bump 400 pt high cut into 1 pt segments, between two long straight segments: with a reach + /// of 10 pt its top is a corner, and with a reach of 1,000 pt, where the walk passes more segments + /// than it measures before it gets that far, its top is not one, as the path turns by about 51° + /// over that reach. + #[test] + fn a_corner_is_not_kept_where_the_reach_is_not_measured() { + let side = 400.0 * std::f64::consts::SQRT_2; + let steps = side.ceil() as usize; + let mut pts = vec![(-3000.0, 0.0)]; + pts.extend((0..steps).map(|j| { + let f = j as f64 / steps as f64; + (-400.0 + 400.0 * f, 400.0 * f) + })); + pts.extend((0..=steps).map(|j| { + let f = j as f64 / steps as f64; + (400.0 * f, 400.0 - 400.0 * f) + })); + pts.push((3000.0, 0.0)); + let anchors = polyline(&pts); + let top = steps + 1; + assert_eq!(anchors[top].p, Point::new(0.0, 400.0)); + assert!(smooth_corners(&anchors, false, 10.0)[top]); + assert!(!smooth_corners(&anchors, false, 1000.0)[top]); + } + + /// A 60° corner between two curved segments 1,000 pt long is found at a reach of 2 pt as it is + /// when each segment is cut into a thousand pieces: the turns over the reach are measured along the + /// curve near the anchor, not along a chord much longer than the reach. + #[test] + fn a_corner_between_long_curves_is_measured_along_them() { + // The curves arrive along x and leave at 60° to it, each bending away from the other. + let d = kurbo::Vec2::from_angle(-60f64.to_radians()); + let side = kurbo::Vec2::new(-d.y, d.x) * 1000.0; + let v = Point::new(0.0, 0.0); + let a = Anchor::with_handles(Point::new(-1000.0, 1000.0), Point::new(-1000.0, 1000.0), Point::new(-300.0, 1000.0)); + let b = Anchor::with_handles(v, Point::new(-300.0, 0.0), v + d * 300.0); + let end = v + d * 1000.0 + side; + let c = Anchor::with_handles(end, v + d * 300.0 + side, end); + let long = [a, b, c]; + let fine: Vec = { + let sp = SubPath::new(long.to_vec(), false); + let mut pts = vec![]; + for i in 0..2 { + let s = sp.segment(i); + for j in 0..1000 { + let p = s.subsegment(f64::from(j) / 1000.0..f64::from(j + 1) / 1000.0); + if j == 0 && i == 0 { + pts.push(Anchor::with_handles(p.p0, p.p0, p.p1)); + } else if let Some(last) = pts.last_mut() { + *last = Anchor::with_handles(last.p, last.h_in, p.p1); + } + pts.push(Anchor::with_handles(p.p3, p.p2, p.p3)); + } + } + pts + }; + let at_v = |anchors: &[Anchor]| { + let corners = smooth_corners(anchors, false, 2.0); + anchors.iter().zip(corners).find(|(x, _)| x.p == v).map(|(_, c)| c) + }; + assert_eq!(at_v(&fine), Some(true), "cut finely, the anchor is a corner"); + assert_eq!(at_v(&long), Some(true)); + } + + /// A line that meets a curve leaving with no handle, turning by 58° at the anchor and by about + /// 57.53° over twice a reach of 0.02 pt: the anchor is a corner, measured either way along the path, + /// as the stretch measured finely near the anchor covers twice the reach along the curve. + #[test] + fn a_corner_next_to_a_curve_without_a_handle_is_kept() { + let at = 58f64.to_radians(); + let prev = Anchor::corner(Point::new(-100.0 * at.cos(), -100.0 * at.sin())); + let v = Point::new(0.0, 0.0); + let a = Anchor::with_handles(v, v, v); + let end = Point::new(600.0, 600.0); + let next = Anchor::with_handles(end, Point::new(200.0, 0.0), end); + assert_eq!(smooth_corners(&[prev, a, next], false, 0.02), vec![false, true, false]); + let back = |x: Anchor| Anchor::with_handles(x.p, x.h_out, x.h_in); + assert_eq!(smooth_corners(&[back(next), back(a), back(prev)], false, 0.02), vec![false, true, false]); + } + + /// A jagged closed path whose length is less than twice the reach: its jags are not corners, + /// while a triangle that small keeps its three. + #[test] + fn a_small_jagged_loop_has_no_corners() { + let ring: Vec<(f64, f64)> = (0..16) + .map(|i| { + let (a, r) = (f64::from(i) / 16.0 * std::f64::consts::TAU, if i % 2 == 0 { 3.0 } else { 2.0 }); + (r * a.cos(), r * a.sin()) + }) + .collect(); + let jags = polyline(&ring); + let sp = SubPath::new(jags.clone(), true); + assert!(subpath_len(&sp) < 24.0); + assert!(smooth_corners(&jags, true, 1e-6).iter().all(|c| *c), "each jag turns sharply at its anchor"); + assert_eq!(smooth_corners(&jags, true, 12.0), vec![false; 16]); + assert_eq!(smooth_corners(&polyline(&[(0.0, 0.0), (6.0, 0.0), (3.0, 5.196)]), true, 12.0), vec![true; 3]); + } } diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 9ecb5c3984..00b6a338f2 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -808,11 +808,11 @@ fn new_document_from_state(s: &mut Session, p: &Value) -> Result { let created = date_param(p, "created", C)?; let st = s.doc()?; // The row as the panel lists it now: keeping an edit in progress below changes the rows. - let chosen = match p.get("index") { - None | Some(Value::Null) => None, - Some(v) => { - let state = v.as_u64().and_then(|row| st.history.state(&st.doc, index(row))); - Some(state.ok_or_else(|| bad(C, format!("no history state {v}")))?.clone()) + let chosen = match super::index_opt(p, "index", C)? { + None => None, + Some(row) => { + let v = &p["index"]; + Some(st.history.state(&st.doc, row).ok_or_else(|| bad(C, format!("no history state {v}")))?.clone()) } }; settle_interaction(s)?; @@ -1276,23 +1276,28 @@ pub(crate) fn place_clip(s: &mut Session, clip: &Clipboard, center: vectorcraft_ /// The artboards Paste in Place, in Front or in Back puts a copy on, in artboard order: `artboard` /// (the active one, #693), else `artboards`, else, while the Artboard tool is chosen with several /// artboards selected, those (noted in the journal as `artboards`, so a replay pastes on the same -/// ones); `None` when none is named. A named index that is not an artboard of the document, a -/// repeated one or an empty list is an error. +/// ones); `None` when none is named. A named value that is not a whole number (null included), a +/// named index that is not an artboard of the document, a repeated one or an empty list is an +/// error; every value is checked for its form before any is checked against the artboards. fn paste_targets(s: &mut Session, p: &Value, cmd: &str) -> Result>> { let n = s.doc()?.doc.artboards.len(); - let one = |v: &Value| v.as_u64().and_then(|i| usize::try_from(i).ok()).filter(|i| *i < n); - let single = match p.get("artboard") { - Some(v) => Some(one(v).ok_or_else(|| bad(cmd, "`artboard` must be the index of an artboard of the document"))?), - None => None, - }; - let listed = match p.get("artboards") { + let single = p.get("artboard").map(|v| v.as_u64().map(index).ok_or_else(|| bad(cmd, "`artboard` must be a whole number"))).transpose()?; + let entries = match p.get("artboards") { Some(v) => { let list = v.as_array().filter(|a| !a.is_empty()).ok_or_else(|| bad(cmd, "`artboards` must be a list of artboard indices"))?; - let mut all = list - .iter() - .map(one) - .collect::>>() - .ok_or_else(|| bad(cmd, "`artboards` names an artboard the document does not have"))?; + let all = list.iter().map(|i| i.as_u64().map(index)).collect::>>(); + Some(all.ok_or_else(|| bad(cmd, "`artboards` must contain whole numbers"))?) + } + None => None, + }; + if single.is_some_and(|i| i >= n) { + return Err(bad(cmd, "`artboard` must be the index of an artboard of the document")); + } + let listed = match entries { + Some(mut all) => { + if all.iter().any(|i| *i >= n) { + return Err(bad(cmd, "`artboards` names an artboard the document does not have")); + } all.sort_unstable(); if all.windows(2).any(|w| w[0] == w[1]) { return Err(bad(cmd, "`artboards` names an artboard twice")); diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index 65672f8b6b..041476a2ed 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -427,6 +427,7 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result { } super::params::check_effect_color(C, id, ¶ms)?; super::params::check_effect_channel(C, id, ¶ms)?; + super::params::check_effect_center(C, id, ¶ms)?; // Crop Marks take their style from the preferences when applied. if id == effects::CROP_MARKS && params.get("style").is_none() { params["style"] = json!(s.crop_mark_style().id()); @@ -718,7 +719,7 @@ fn lighting_preset(s: &mut Session, p: &Value) -> Result { /// sets its Warp style (`warpStyle`), its 3D type (`threeDType`) or visibility (`visible`), as one /// undo step. They are checked as `effect.apply` checks them, and a visible 3D effect must still /// fit; a hidden one has its given values checked. → `{ids}`. -fn set_params(s: &mut Session, p: &Value) -> Result { +pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result { const C: &str = "effect.setParams"; let index = index_param(p, "index", C)?; let mut params = p.get("params").cloned().unwrap_or(Value::Null); @@ -740,6 +741,7 @@ fn set_params(s: &mut Session, p: &Value) -> Result { for effect in &edited { super::params::check_effect_color(C, effect, ¶ms)?; super::params::check_effect_channel(C, effect, ¶ms)?; + super::params::check_effect_center(C, effect, ¶ms)?; } if edited.iter().any(|e| texture_load_effect(e)) { load_texture(&mut params, C)?; diff --git a/crates/engine/src/cmd/effectcmd/tests.rs b/crates/engine/src/cmd/effectcmd/tests.rs index 306aaa4797..b3389e190d 100644 --- a/crates/engine/src/cmd/effectcmd/tests.rs +++ b/crates/engine/src/cmd/effectcmd/tests.rs @@ -1016,3 +1016,69 @@ fn a_3d_shadow_is_one_undo_step_saved_exported_and_expanded() { }); assert_eq!(shadows, 1); } + +/// Radial Blur's Blur Center: stored as given, drawn about that point of the object's bounds, and +/// a value outside 0 to 1 (or not a number) is refused with nothing changed and no undo step. +#[test] +fn radial_blur_center_is_stored_drawn_and_checked() { + let (mut s, id) = session_with_rect(); + let draw = |s: &Session| { + vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 300, 300, vectorcraft_geom::Affine::IDENTITY, &Default::default()).pixels + }; + s.execute("effect.apply", &json!({"effect": "blur.radial", "params": {"amount": 40}})).unwrap(); + assert_eq!(node(&s, id).appearance.effects[0].params["centerX"], json!(0.5), "the default center is stored"); + let middle = draw(&s); + s.execute("effect.setParams", &json!({"index": 0, "params": {"centerX": 0.5, "centerY": 0.5}})).unwrap(); + assert_eq!(draw(&s), middle, "the default center draws as before"); + s.execute("effect.setParams", &json!({"index": 0, "params": {"centerX": 0, "centerY": 1}})).unwrap(); + let params = node(&s, id).appearance.effects[0].params.clone(); + assert_eq!((params["centerX"].clone(), params["centerY"].clone()), (json!(0), json!(1))); + let corner = draw(&s); + assert_ne!(corner, middle, "the blur turns about the bottom-left corner"); + let undo = s.doc().unwrap().history.undo.len(); + for (cmd, params) in [ + ("effect.setParams", json!({"index": 0, "params": {"centerX": 1.5}})), + ("effect.setParams", json!({"index": 0, "params": {"centerY": -0.01}})), + ("effect.setParams", json!({"index": 0, "params": {"centerX": "0.5"}})), + ("effect.apply", json!({"effect": "blur.radial", "params": {"centerY": 2}})), + ] { + let e = s.execute(cmd, ¶ms).unwrap_err().to_string(); + assert!(e.contains("must be a number"), "{cmd} {params}: {e}"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{cmd} {params}"); + assert_eq!(node(&s, id).appearance.effects.len(), 1, "{cmd} {params}"); + assert_eq!(draw(&s), corner, "{cmd} {params}"); + } + // A replayed journal is checked too: the refusal is the command's own. + let e = s.replay("effect.setParams", &json!({"index": 0, "params": {"centerX": 7}})).unwrap_err().to_string(); + assert!(e.contains("`centerX` must be a number from 0 to 1"), "{e}"); + // Moving the object moves the blur with it. + s.execute("object.move", &json!({"ids": [id.0], "dx": 40, "dy": 20})).unwrap(); + let moved = draw(&s); + let at = |px: &[u8], x: usize, y: usize| px[(y * 300 + x) * 4..][..4].to_vec(); + for (x, y) in [(95, 150), (150, 205), (205, 95), (120, 120)] { + assert_eq!(at(&moved, x + 40, y + 20), at(&corner, x, y), "({x}, {y})"); + } +} + +/// A Rasterize with transparent room around the art, before another Rasterize, splits the stack, +/// and the part after the split paints around content the room spreads. The Blur Center still +/// lies in the object's own bounds, so the blur draws as it does without the room. +#[test] +fn radial_blur_center_stays_in_the_object_when_the_stack_splits() { + let draw = |room: bool| { + let (mut s, _) = session_with_rect(); + let mut stack = vec![("rasterize", json!({})), ("blur.radial", json!({"amount": 60, "centerX": 0, "centerY": 0}))]; + if room { + stack.insert(0, ("rasterize", json!({"addAround": 40}))); + } + for (effect, params) in stack { + s.execute("effect.apply", &json!({"effect": effect, "params": params})).unwrap(); + } + vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 300, 300, vectorcraft_geom::Affine::IDENTITY, &Default::default()).pixels + }; + let (plain, split) = (draw(false), draw(true)); + let alpha = |px: &[u8]| px.iter().skip(3).step_by(4).map(|a| u64::from(*a)).sum::(); + assert!(alpha(&plain) > 0, "the blurred art draws"); + let differ = (0..300 * 300).filter(|i| plain[i * 4 + 3].abs_diff(split[i * 4 + 3]) > 8).count(); + assert!(differ < 50, "{differ} pixels' coverage moved with the room around the art"); +} diff --git a/crates/engine/src/cmd/expand.rs b/crates/engine/src/cmd/expand.rs index 02dbad5d23..43975fe4e4 100644 --- a/crates/engine/src/cmd/expand.rs +++ b/crates/engine/src/cmd/expand.rs @@ -265,25 +265,27 @@ fn gradient_expands(d: &Document, l: &Node) -> bool { /// Whether type `t` has a gradient fill that Fill expands once Object has outlined it: one of the /// paths `type.createOutlines` makes of its glyphs, ruby glyphs and underline and strikethrough -/// bars, each painted as its run, has one ([`gradient_expands`] on that path's own box). Inline -/// graphics and color glyphs become other art. Leaves the document as it is and stops at the -/// first such path. +/// bars, each painted as its run with its unplaced gradients fitted to the layout's bounds, has one +/// ([`gradient_expands`] on that path). Inline graphics and color glyphs become other art. Leaves +/// the document as it is and stops at the first such path. fn text_gradient_expands(d: &Document, t: &TextObject) -> bool { if !t.runs.iter().any(|r| matches!(r.style.fill, Paint::Gradient(_))) { return false; } let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + let first = t.first_style(); let expands = |run: usize, outline: &BezPath| { - let style = t.runs.get(run).map(|r| &r.style); - if !matches!(style.map_or_else(|| t.first_style().fill, |s| s.fill.clone()), Paint::Gradient(_)) { + let style = t.runs.get(run).map_or(&first, |r| &r.style); + if !matches!(style.fill, Paint::Gradient(_)) { return false; } - let path = PathData::from_bezpath(outline).transformed(t.xf); + let path = PathData::from_bezpath(outline); if path.is_empty() { return false; } - let appearance = style.map_or_else(|| t.first_style().appearance(), |s| s.appearance()); - gradient_expands(d, &Node::path(NodeId(u64::MAX), path, appearance)) + let mut piece = Node::path(NodeId(u64::MAX), path, Appearance::default()); + vectorcraft_render::effects::paint_type_piece(&mut piece, style, lay.bounds, t.xf); + gradient_expands(d, &piece) }; let inline = |gi: usize| lay.inlines.iter().find(|i| i.glyph == gi).is_some_and(|i| t.runs.get(i.run).is_some_and(|r| r.inline.is_some())); lay.glyphs.iter().enumerate().any(|(gi, g)| !inline(gi) && g.image.is_none() && g.colour.is_none() && expands(g.run, &g.outline)) diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 84fb121d0c..6995075d2f 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -66,7 +66,10 @@ use serde_json::{Value, json}; pub use action_batch::batch_overwrites_one_file; 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 use encode::{ + ARTBOARD_PARAMS, ArtboardPick, Encoded, Note, NoteKind, encode, encode_all, encode_with_notes, encode_with_warnings, export_art_bounds, + note_texts, +}; pub(crate) use encode::{anti_alias, background, with_single_artboard}; pub(crate) use export::with_artboard_fills; pub(crate) use export::{EXPORT_PARAMS, export_crop, isolated}; diff --git a/crates/engine/src/cmd/fileio/action_batch.rs b/crates/engine/src/cmd/fileio/action_batch.rs index 232d5ba1f4..4e99f4ee3e 100644 --- a/crates/engine/src/cmd/fileio/action_batch.rs +++ b/crates/engine/src/cmd/fileio/action_batch.rs @@ -12,6 +12,8 @@ use serde_json::json; use super::super::{Result, Session, bad}; #[cfg(not(target_arch = "wasm32"))] use super::super::{check_switches, find_command, switch_or, text_param}; +#[cfg(not(target_arch = "wasm32"))] +use crate::EngineError; #[cfg(target_arch = "wasm32")] pub(super) fn action_batch(_: &mut Session, _: &Value) -> Result { @@ -58,6 +60,10 @@ pub(super) fn action_batch(s: &mut Session, p: &Value) -> Result { if id == "command.batch" || id == "action.batch" { return Err(bad(C, "batches cannot nest")); } + // `command.batch` refuses the batch when it reaches this step, which would fail every file or data set it plays. + if id == "prefs.import" { + return Err(bad(C, format!("commands[{i}]: `prefs.import` runs on its own, not as a batch step"))); + } if find_command(id).is_none() { return Err(bad( C, @@ -213,7 +219,7 @@ fn batch_folder(s: &mut Session, cmd: &str, p: &Value, override_open: bool, run: // open, so its artboard files count ([`dataset_output_paths`]). No output takes the name of a // source file in the destination folder, other than that file's own output, or of a subfolder // of the destination folder that holds source files. - let steps = filter_steps(run.steps, override_open, false); + let (steps, places) = filter_steps(run.steps, override_open, false); let run = Run { steps: &steps, ..*run }; let in_dest: Vec> = files.iter().map(|path| name_in_folder(path, run.dest_folder)).collect(); let mut picker = @@ -228,7 +234,7 @@ fn batch_folder(s: &mut Session, cmd: &str, p: &Value, override_open: bool, run: let outputs = dataset_output_extensions(&run, doc, &ext); picker.pick(&base, |stem| output_names(run.dest_folder, stem, &outputs, doc), own.as_deref()) }; - match process_one_file(s, &run, path, &ext, pick) { + match process_one_file(s, &run, &places, path, &ext, pick) { Ok(row) => processed.push(row), Err(e) => { failed += 1; @@ -266,12 +272,12 @@ fn batch_datasets(s: &mut Session, cmd: &str, run: &Run<'_>) -> Result { } let doc_stem = st.path.as_deref().and_then(|p| std::path::Path::new(p).file_stem().and_then(|s| s.to_str())).unwrap_or("Untitled").to_string(); let stems = dataset_stems(&names, &doc_stem, run.dataset_file_naming, run, &st.doc)?; - let steps = filter_steps(run.steps, true, false); + let (steps, places) = filter_steps(run.steps, true, false); let run = Run { steps: &steps, ..*run }; let mut processed = Vec::new(); let mut failed = 0usize; for (name, stem) in names.iter().zip(&stems) { - match process_one_dataset(s, &run, name, stem) { + match process_one_dataset(s, &run, &places, name, stem) { Ok(row) => processed.push(row), Err(e) => { failed += 1; @@ -347,11 +353,13 @@ impl StemPicker { } } -/// Drop Open (and optionally Close) steps when the batch supplies the file itself. +/// Drop Open (and optionally Close) steps when the batch supplies the file itself → the steps that +/// stay, and the index of each in `cmds`. #[cfg(not(target_arch = "wasm32"))] -fn filter_steps(cmds: &[Value], drop_open: bool, drop_close: bool) -> Vec { +fn filter_steps(cmds: &[Value], drop_open: bool, drop_close: bool) -> (Vec, Vec) { cmds.iter() - .filter(|c| { + .enumerate() + .filter(|(_, c)| { let id = c.get("command").and_then(Value::as_str).unwrap_or(""); if drop_open && matches!(id, "document.open" | "file.open") { return false; @@ -361,14 +369,44 @@ fn filter_steps(cmds: &[Value], drop_open: bool, drop_close: bool) -> Vec } true }) - .cloned() - .collect() + .map(|(i, c)| (c.clone(), i)) + .unzip() +} + +/// Plays `commands`, the steps of `run` with their paths rewritten, as one `command.batch`. When a +/// step fails, the error names it by its place in the caller's `commands`, from 1, counting the Open +/// steps the batch skipped (`places` gives the index there of each step of `run`): +/// ``action step 3 (`object.move`) failed: …``. Any other error, such as one about the whole batch, +/// stays as it is. +#[cfg(not(target_arch = "wasm32"))] +fn play_steps(s: &mut Session, run: &Run<'_>, places: &[usize], commands: Vec) -> Result { + s.execute("command.batch", &json!({"label": run.label, "commands": commands})).map_err(|e| { + let text = e.to_string(); + let Some((n, id, reason)) = batch_step_failure(&text) else { return e }; + let same = run.steps.get(n).and_then(|c| c.get("command")).and_then(Value::as_str) == Some(id); + match places.get(n) { + Some(place) if same => EngineError::Other(format!("action step {} (`{id}`) failed: {reason}", place + 1)), + _ => e, + } + }) +} + +/// The step number, command id and reason in the error `command.batch` gives when one of its steps +/// fails (``batch step 2 (`object.move`) failed: …``); none for any other error. +#[cfg(not(target_arch = "wasm32"))] +fn batch_step_failure(e: &str) -> Option<(usize, &str, &str)> { + let rest = e.strip_prefix("batch step ")?; + let digits = rest.find(|c: char| !c.is_ascii_digit())?; + let n = rest[..digits].parse().ok()?; + let (id, reason) = rest[digits..].strip_prefix(" (`")?.split_once("`) failed: ")?; + Some((n, id, reason)) } #[cfg(not(target_arch = "wasm32"))] fn process_one_file( s: &mut Session, run: &Run<'_>, + places: &[usize], path: &str, ext: &str, stem_for: impl FnOnce(&vectorcraft_doc::Document) -> String, @@ -376,17 +414,17 @@ fn process_one_file( s.execute("document.open", &json!({"path": path}))?; let stem = stem_for(&s.doc()?.doc); let rewritten = rewrite_paths(run.steps, run.override_save, run.override_export, run.dest_folder, &stem, ext); - let batch = s.execute("command.batch", &json!({"label": run.label, "commands": rewritten}))?; + let batch = play_steps(s, run, places, rewritten)?; // Folder sources open a file per pass: close after Save and Close / Folder. finish_destination(s, run, &stem, ext, path, true)?; Ok(json!({"path": path, "result": batch})) } #[cfg(not(target_arch = "wasm32"))] -fn process_one_dataset(s: &mut Session, run: &Run<'_>, name: &str, stem: &str) -> Result { +fn process_one_dataset(s: &mut Session, run: &Run<'_>, places: &[usize], name: &str, stem: &str) -> Result { s.execute("dataset.select", &json!({"name": name}))?; let rewritten = rewrite_paths(run.steps, run.override_save, run.override_export, run.dest_folder, stem, "vectorcraft"); - let batch = s.execute("command.batch", &json!({"label": run.label, "commands": rewritten}))?; + let batch = play_steps(s, run, places, rewritten)?; // Data sets share one open document: write each row out but leave it open for the next. finish_destination(s, run, stem, "vectorcraft", "", false)?; Ok(json!({"dataset": name, "result": batch})) @@ -1454,7 +1492,8 @@ mod tests { assert_eq!((r["failed"].as_u64(), r["processed"].as_array().map(Vec::len)), (Some(rows), Some(rows as usize)), "{r}"); for row in r["processed"].as_array().unwrap() { let e = row["error"].as_str().unwrap_or_default(); - let want = format!("batch step 0 (`document.save`) failed: automation path rejected: outside the write root {root}: doc.vectorcraft"); + let want = + format!("action step 1 (`document.save`) failed: automation path rejected: outside the write root {root}: doc.vectorcraft"); assert_eq!(e, want, "{r}"); } assert!(!r.to_string().contains(&hidden), "{r}"); @@ -2224,4 +2263,144 @@ mod tests { .is_err() ); } + + /// The steps of the step-number tests: an Open the batch skips, a step that works, and one that + /// fails (an Align with nothing selected). + fn open_then_failing_align() -> Value { + json!([ + {"command": "document.open", "params": {"path": "/no/such/file.svg"}}, + {"command": "object.unlockAll", "params": {}}, + {"command": "object.align", "params": {}} + ]) + } + + /// The step a source's error names, after `action step ` and before ` failed: `. + fn named_step(r: &Value, row: usize) -> String { + let e = r["processed"][row]["error"].as_str().unwrap_or_default(); + assert!(!e.contains("batch step"), "{r}"); + e.strip_prefix("action step ").and_then(|e| e.split_once(" failed: ")).map(|(step, _)| step.to_string()).unwrap_or_else(|| e.to_string()) + } + + /// A failed step of a folder batch is named by its place in the `commands` sent, from 1, with the + /// Open step that Override Open skips counted; the reason follows unchanged. + #[test] + fn a_folder_batch_error_names_the_step_in_the_commands_sent() { + let src = tmp("step-number-src"); + write_svg(&src, "a.svg", "#f00"); + write_svg(&src, "b.svg", "#0f0"); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 80})).unwrap(); + // `command.batch` itself still numbers its steps from 0. + let reason = s + .execute( + "command.batch", + &json!({"commands": [{"command": "object.unlockAll", "params": {}}, {"command": "object.align", "params": {}}]}), + ) + .unwrap_err() + .to_string(); + let reason = reason.strip_prefix("batch step 1 (`object.align`) failed: ").unwrap_or_else(|| panic!("{reason}")).to_string(); + for (stop, rows) in [(true, 1), (false, 2)] { + let r = s + .execute("action.batch", &json!({"folder": src.to_string_lossy(), "stopOnError": stop, "commands": open_then_failing_align()})) + .unwrap(); + assert_eq!(r["failed"], rows, "{r}"); + for row in 0..rows { + assert_eq!(r["processed"][row]["error"], format!("action step 3 (`object.align`) failed: {reason}"), "{r}"); + } + } + } + + /// With Override Open off, a recorded Open step runs, and its failure is named as the first step. + #[test] + fn a_recorded_open_that_fails_is_the_first_step() { + let src = tmp("step-number-open-src"); + write_svg(&src, "a.svg", "#f00"); + let mut s = Session::new(); + let r = s + .execute("action.batch", &json!({"folder": src.to_string_lossy(), "overrideOpen": false, "commands": open_then_failing_align()})) + .unwrap(); + assert_eq!(named_step(&r, 0), "1 (`document.open`)", "{r}"); + } + + /// A data set batch, which always skips Open steps, names a failed step by its place in the + /// `commands` sent for every data set it fails on. + #[test] + fn a_data_set_batch_error_names_the_step_in_the_commands_sent() { + let mut s = with_data_sets(&["Alpha", "Beta"]); + for (stop, rows) in [(true, 1), (false, 2)] { + let r = s.execute("action.batch", &json!({"source": "datasets", "stopOnError": stop, "commands": open_then_failing_align()})).unwrap(); + assert_eq!(r["failed"], rows, "{r}"); + for row in 0..rows { + assert_eq!(named_step(&r, row), "3 (`object.align`)", "{r}"); + } + } + } + + /// A recorded export that Override Export points into the destination folder keeps its place in + /// the `commands` sent when it fails. + #[test] + fn a_redirected_export_that_fails_keeps_its_place() { + let src = tmp("step-number-export-src"); + write_svg(&src, "a.svg", "#f00"); + let dest = tmp("step-number-export-out"); + // A file where the export's folder goes, so the export cannot write its files. + std::fs::write(dest.join("a"), "taken").unwrap(); + let mut s = Session::new(); + let r = s + .execute( + "action.batch", + &json!({ + "folder": src.to_string_lossy(), + "destinationFolder": dest.to_string_lossy(), + "commands": [ + {"command": "document.open", "params": {"path": "/no/such/file.svg"}}, + {"command": "object.unlockAll", "params": {}}, + {"command": "document.exportForScreens", "params": {"formats": [{"format": "svg"}]}} + ] + }), + ) + .unwrap(); + assert_eq!(r["failed"], 1, "{r}"); + assert_eq!(named_step(&r, 0), "3 (`document.exportForScreens`)", "{r}"); + } + + /// A source file that does not open, which the batch opens itself, gives the open's own error + /// with no step number. + #[test] + fn a_source_that_does_not_open_names_no_step() { + let src = tmp("step-number-bad-src"); + std::fs::write(src.join("a.svg"), "not an svg").unwrap(); + let mut s = Session::new(); + let r = s.execute("action.batch", &json!({"folder": src.to_string_lossy(), "commands": open_then_failing_align()})).unwrap(); + assert_eq!(r["failed"], 1, "{r}"); + let e = r["processed"][0]["error"].as_str().unwrap_or_default(); + assert!(!e.is_empty() && !e.contains("action step") && !e.contains("batch step"), "{r}"); + } + + /// A `prefs.import` step, which `command.batch` does not run, is refused before any file opens. + #[test] + fn a_prefs_import_step_is_refused_before_any_file_opens() { + let src = tmp("step-number-prefs-src"); + write_svg(&src, "a.svg", "#f00"); + let mut s = Session::new(); + let p = json!({"folder": src.to_string_lossy(), "commands": [{"command": "object.unlockAll"}, {"command": "prefs.import", "params": {}}]}); + let e = s.execute("action.batch", &p).unwrap_err().to_string(); + assert!(e.contains("commands[1]: `prefs.import` runs on its own, not as a batch step"), "{e}"); + assert!(s.active().is_none(), "no file was opened"); + } + + /// Only the error `command.batch` gives for a failed step is read as one. + #[test] + fn batch_step_failure_reads_only_a_step_error() { + assert_eq!(batch_step_failure("batch step 12 (`object.move`) failed: no selection"), Some((12, "object.move", "no selection"))); + for e in [ + "batch step (`object.move`) failed: no selection", + "batch step 99999999999999999999999 (`object.move`) failed: x", + "batch step 1 `object.move` failed: x", + "invalid parameters for `command.batch`: batches cannot nest", + "batch step 1", + ] { + assert_eq!(batch_step_failure(e), None, "{e}"); + } + } } diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index a225bfcad9..a46f46492a 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -9,7 +9,7 @@ pub fn specs() -> Vec { "Open Document", [], None, - "{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), importer?: \"plugin.\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning), PICT .pct/.pic/.pict (QuickDraw versions 1 and 2, with or without the file's 512-byte header: one artboard, the picture's frame; shapes, lines and regions as paths, text as point type, bitmaps, pixel maps and QuickTime JPEG images as images; what isn't read is listed in warnings), HP-GL plot files .plt/.hpgl/.hgl/.hpg (one artboard round the art; what isn't drawn is listed in warnings), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts first, when several do): it is given the file, at most 128 MiB, and its objects become a new document whose artboard is their bounds; Save then asks for a name, and the warnings are the importer's. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks). An SVG's variable data (SVG Options › Include Variable Data, a variableSets element) gives the document its text variables and data sets, each text variable bound to the type object its docRef names, unless the SVG restores the native document; variable data variable.loadLibrary would refuse is left out with a warning", + "{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds), in a row, and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), importer?: \"plugin.\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning), PICT .pct/.pic/.pict (QuickDraw versions 1 and 2, with or without the file's 512-byte header: one artboard, the picture's frame; shapes, lines and regions as paths, text as point type, bitmaps, pixel maps and QuickTime JPEG images as images; what isn't read is listed in warnings), HP-GL plot files .plt/.hpgl/.hgl/.hpg (one artboard round the art; what isn't drawn is listed in warnings), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts first, when several do): it is given the file, at most 128 MiB, and its objects become a new document whose artboard is their bounds; Save then asks for a name, and the warnings are the importer's. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks). An SVG's variable data (SVG Options › Include Variable Data, a variableSets element) gives the document its text variables and data sets, each text variable bound to the type object its docRef names, unless the SVG restores the native document; variable data variable.loadLibrary would refuse is left out with a warning", always, load::open ), @@ -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 not used, and warnings name it. Under automation read roots, svg and svgz are refused while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked). 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: of the layers the file draws, 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 art it plots, without placed images, unpainted paths and art at 0% opacity), 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. Under automation read roots, svg and svgz are refused while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked). Never changes the document's path", has_doc, export::export ), @@ -117,7 +117,7 @@ pub fn specs() -> Vec { "Batch…", [], None, - "{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close; for source datasets, save the open document over its own file after each data set, and refuse a document that was never saved, was converted from an older version or was restored by Data Recovery, unless a recorded Save or Save As step writes a file first; a Save or Save As step that overrideSave points into destinationFolder makes each data set's file the document's own) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open / file.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportSelection the same way, and give document.exportForScreens / assets.export the folder destinationFolder/{stem}, one for each source file or data set, in which the export names its files as it does outside Batch), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs; {stem} is the file's name without its extension and without trailing periods and spaces, with `-2`, `-3`… added to a name an earlier file used or whose file or folder has the name of one an earlier file wrote or of another source file or a folder of source files in destinationFolder), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-` and trailing periods and spaces are dropped; a name already used in the batch or whose output file or folder already exists in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. Batches cannot nest. A switch (includeSubdirs, overrideOpen, overrideSave, overrideExport, stopOnError) that is not true or false, or a source, folder, destination, destinationFolder, datasetFileNaming or label that is not a string, is an error before any folder is made or file opened; null reads as left out. → {processed: [{path|dataset, result|error}…], count, failed, stopped, warning?} (warning: for source datasets, when Save and Close without such a step, or a Save, Save a Copy, Save as Template or export step (document.export, exportSelection, exportForScreens, exportPdf, exportEps, exportDxf, exportForWeb, exportForOffice) that writes a file and is not pointed into destinationFolder, saves every data set over the same file)", + "{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close; for source datasets, save the open document over its own file after each data set, and refuse a document that was never saved, was converted from an older version or was restored by Data Recovery, unless a recorded Save or Save As step writes a file first; a Save or Save As step that overrideSave points into destinationFolder makes each data set's file the document's own) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open / file.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportSelection the same way, and give document.exportForScreens / assets.export the folder destinationFolder/{stem}, one for each source file or data set, in which the export names its files as it does outside Batch), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs; {stem} is the file's name without its extension and without trailing periods and spaces, with `-2`, `-3`… added to a name an earlier file used or whose file or folder has the name of one an earlier file wrote or of another source file or a folder of source files in destinationFolder), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-` and trailing periods and spaces are dropped; a name already used in the batch or whose output file or folder already exists in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. Batches cannot nest, and a prefs.import step is refused (commands[i], from 0) before any file is opened. A switch (includeSubdirs, overrideOpen, overrideSave, overrideExport, stopOnError) that is not true or false, or a source, folder, destination, destinationFolder, datasetFileNaming or label that is not a string, is an error before any folder is made or file opened; null reads as left out. A step that fails is named in the error by its place in commands, from 1, counting the Open steps the batch skips (action step 3 (`object.align`) failed: …); the batch's own opening of a file, choosing of a data set and destination save, export or close give their errors without a step number. → {processed: [{path|dataset, result|error}…], count, failed, stopped, warning?} (warning: for source datasets, when Save and Close without such a step, or a Save, Save a Copy, Save as Template or export step (document.export, exportSelection, exportForScreens, exportPdf, exportEps, exportDxf, exportForWeb, exportForOffice) that writes a file and is not pointed into destinationFolder, saves every data set over the same file)", always, action_batch::action_batch ), diff --git a/crates/engine/src/cmd/fileio/encode.rs b/crates/engine/src/cmd/fileio/encode.rs index 0fbffcea82..c823b8866f 100644 --- a/crates/engine/src/cmd/fileio/encode.rs +++ b/crates/engine/src/cmd/fileio/encode.rs @@ -2,11 +2,13 @@ //! (unknown keys are ignored, so one params object can carry the options of several formats). use std::borrow::Cow; +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; use serde::Deserialize; use serde::de::DeserializeOwned; use serde_json::Value; -use vectorcraft_doc::{Artboard, Document}; +use vectorcraft_doc::{Artboard, Document, Node, NodeKind, SymbolOverride}; use vectorcraft_geom::Rect; use vectorcraft_render::AntiAlias; use vectorcraft_render::encode::jpeg::{self, JpegOptions}; @@ -419,13 +421,15 @@ pub(super) fn use_artboards(cmd: &str, p: &Value) -> Result> { /// With `useArtboards: false` in `p`: `doc` without its opacity-mask or symbol editing layer and /// with one artboard, the bounds of its visible art, and `p` without the artboard choice. `None` -/// when `useArtboards` is absent, null or true. A document with no visible art is refused. -pub(super) fn art_page(cmd: &str, doc: &Document, p: &Value) -> Result> { +/// when `useArtboards` is absent, null or true. The objects that `left_out` picks (layers or +/// objects the format leaves out, see [`hidden_nodes`]) are not measured, and a document with no +/// other visible art is refused. +pub(super) fn art_page(cmd: &str, doc: &Document, p: &Value, left_out: impl Fn(&Node) -> bool) -> Result> { if use_artboards(cmd, p)? != Some(false) { return Ok(None); } let doc = &*doc.without_edit_modes(); - let bounds = vectorcraft_render::encode::art_bounds(doc).ok_or_else(|| bad(cmd, "nothing to export: the document has no visible art"))?; + let bounds = bounds_without(doc, &left_out).ok_or_else(|| bad(cmd, "nothing to export: the document has no visible art"))?; let mut q = super::export::without_artboards(p); if let Some(o) = q.as_object_mut() { o.remove("useArtboards"); @@ -433,6 +437,272 @@ pub(super) fn art_page(cmd: &str, doc: &Document, p: &Value) -> Result Option { + let doc = &*doc.without_edit_modes(); + bounds_without(doc, &|n| format == "hpgl" && vectorcraft_cad::hpgl::write::plots_nothing(doc, n)) +} + +/// The bounds of the visible art of `doc` with the objects that `left_out` picks hidden +/// ([`hidden_nodes`]) and the ones in the art of the symbols that instances show taken out +/// ([`without_nodes`]: symbol art is measured with its hidden objects). An instance of a symbol +/// whose art is all picked or hidden is hidden too. The drawn instances of a dynamic symbol that +/// make the same appearance changes to its art are measured on a copy of the symbol of their own, +/// in which each object is judged with those changes ([`as_drawn`]); the objects taken out of +/// a dynamic symbol's art leave empty groups in their places, by which instances find the objects +/// they change. +fn bounds_without(doc: &Document, left_out: &dyn Fn(&Node) -> bool) -> Option { + // The symbols instances show (the first of each name). + let mut names = HashSet::new(); + let shown: Vec = doc.symbols.iter().enumerate().filter(|(_, s)| names.insert(s.name.as_str())).map(|(i, _)| i).collect(); + // The sets of appearance changes the drawn instances of each dynamic symbol make to its art; + // `None` for a symbol with more than `MAX_ART_COPIES`, which is measured whole. + let mut sets: HashMap<&str, Option>>> = + shown.iter().filter_map(|i| doc.symbols.get(*i)).filter(|s| s.dynamic).map(|s| (s.name.as_str(), Some(Vec::new()))).collect(); + if !sets.is_empty() { + let mut walked = HashSet::new(); + for l in &doc.layers { + drawn_changes(doc, l, left_out, true, &mut walked, &mut sets); + } + } + // Each set of changes gets a copy of its symbol, appended after the symbols, which the instances + // that make those changes show instead. + let variant = |symbol: &str, n: &Node| -> Option { + let k = sets.get(symbol)?.as_ref()?.iter().position(|c| *c == own_changes(n))?; + Some(format!("{symbol}\u{0}{k}")) + }; + let mut copies: Vec<(usize, &[&SymbolOverride])> = Vec::new(); + let remapped_doc = sets.values().flatten().any(|v| !v.is_empty()).then(|| { + let mut d = doc.clone(); + for l in &mut d.layers { + if let Some(n) = remapped(l, &variant) { + *l = n; + } + } + for s in &mut d.symbols { + if let Some(n) = remapped(&s.art, &variant) { + s.art = n; + } + } + for i in &shown { + let Some(s) = d.symbols.get(*i).cloned() else { continue }; + for (k, c) in sets.get(s.name.as_str()).into_iter().flatten().flatten().enumerate() { + copies.push((d.symbols.len(), c.as_slice())); + d.symbols.push(vectorcraft_doc::Symbol { name: format!("{}\u{0}{k}", s.name), ..s.clone() }); + } + } + d + }); + let src = remapped_doc.as_ref().unwrap_or(doc); + // The symbols to measure with the changes their instances make (`None` for a static symbol), + // without the dynamic symbols measured whole. + let entries: Vec<(usize, Option<&[&SymbolOverride]>)> = shown + .iter() + .filter_map(|i| src.symbols.get(*i).map(|s| (*i, s))) + .filter(|(_, s)| !s.dynamic || sets.get(s.name.as_str()).is_some_and(Option::is_some)) + .map(|(i, s)| (i, s.dynamic.then_some(&[][..]))) + .chain(copies.iter().map(|(i, c)| (*i, Some(*c)))) + .collect(); + // The symbols whose art `left_out` leaves nothing of, those that only hold instances of such + // symbols included. + let mut empty: HashSet<&str> = HashSet::new(); + while let Some(s) = entries.iter().find_map(|(i, c)| { + src.symbols.get(*i).filter(|s| !empty.contains(s.name.as_str()) && all_left_out(&s.art, left_out, &empty, *c, &mut Vec::new())) + }) { + empty.insert(&s.name); + } + let left_out = + &|n: &Node| left_out(n) || matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if empty.contains(symbol.as_str()) && !has_effects(n)); + let layers = hidden_nodes(&src.layers, left_out); + let symbols: Vec<(usize, Arc)> = entries + .iter() + .filter_map(|(i, c)| { + let s = src.symbols.get(*i).filter(|s| !empty.contains(s.name.as_str()))?; + without_nodes(&s.art, left_out, *c, &mut Vec::new()).map(|art| (*i, art)) + }) + .collect(); + if layers.is_none() && symbols.is_empty() { + return vectorcraft_render::encode::art_bounds(src); + } + let mut d = remapped_doc.unwrap_or_else(|| doc.clone()); + if let Some(layers) = layers { + d.layers = layers; + } + for (i, art) in symbols { + if let Some(s) = d.symbols.get_mut(i) { + s.art = art; + } + } + vectorcraft_render::encode::art_bounds(&d) +} + +/// The appearance changes instance `n` makes to its symbol's art, without those that change nothing. +fn own_changes(n: &Node) -> Vec<&SymbolOverride> { + n.extras().symbol_overrides.iter().filter(|o| !o.is_empty()).collect() +} + +/// `n` with each instance at any depth that `variant` gives another symbol (from the instance's +/// symbol and the instance) made an instance of that symbol; `None` when none is. +fn remapped(n: &Arc, variant: &dyn Fn(&str, &Node) -> Option) -> Option> { + if let NodeKind::SymbolInstance { symbol, .. } = &n.kind { + let name = variant(symbol, n)?; + let mut m = (**n).clone(); + if let NodeKind::SymbolInstance { symbol, .. } = &mut m.kind { + *symbol = name; + } + return Some(Arc::new(m)); + } + let children = n.children()?; + let mut out: Option>> = None; + for (i, c) in children.iter().enumerate() { + if let Some(new) = remapped(c, variant) + && let Some(slot) = out.get_or_insert_with(|| children.clone()).get_mut(i) + { + *slot = new; + } + } + out.map(|c| { + let mut m = (**n).clone(); + if let Some(children) = m.children_mut() { + *children = c; + } + Arc::new(m) + }) +} + +/// Whether `n` is hidden, picked by `left_out`, an instance of one of the `empty` symbols, or a +/// layer or a group holding only such objects (its clipping path among them when it clips). A +/// Shaper group, or a layer, group or instance with effects, fills or strokes of its own, is none +/// of these unless it is hidden or picked. In the art of a dynamic symbol (`changed`, the changes +/// an instance makes to it; `n` is at place `at`), each object is judged with those changes +/// ([`as_drawn`]). +fn all_left_out(n: &Node, left_out: &dyn Fn(&Node) -> bool, empty: &HashSet<&str>, changed: Option<&[&SymbolOverride]>, at: &mut Vec) -> bool { + let m = as_drawn(n, changed, at); + !n.visible + || left_out(&m) + || !has_effects(&m) + && n.extras().shaper.is_none() + && match &n.kind { + NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().enumerate().all(|(i, c)| { + at.push(i as u32); + let out = all_left_out(c, left_out, empty, changed, at); + at.pop(); + out + }), + NodeKind::SymbolInstance { symbol, .. } => empty.contains(symbol.as_str()), + _ => false, + } +} + +/// Add the sets of appearance changes that the instances in `n` and its subtree make to the art of +/// the symbols `sets` names, each set once, and those of the instances in the art of the symbols the +/// instances show (`walked`, the symbols already looked in). The instances that `left_out` picks or +/// that are in an object it picks are left out, and with `hidden` (in a layer) the hidden ones and +/// those in a hidden object. A symbol with more than [`MAX_ART_COPIES`] sets gets `None`. +fn drawn_changes<'a>( + doc: &'a Document, + n: &'a Node, + left_out: &dyn Fn(&Node) -> bool, + hidden: bool, + walked: &mut HashSet<&'a str>, + sets: &mut HashMap<&'a str, Option>>>, +) { + if hidden && !n.visible || left_out(n) { + return; + } + if let NodeKind::SymbolInstance { symbol, .. } = &n.kind { + let changes = own_changes(n); + if let Some(entry) = sets.get_mut(symbol.as_str()) + && !changes.is_empty() + { + let full = match entry { + Some(list) if !list.contains(&changes) && list.len() < MAX_ART_COPIES => { + list.push(changes); + false + } + Some(list) => !list.contains(&changes), + None => false, + }; + if full { + *entry = None; + } + } + if walked.insert(symbol.as_str()) + && let Some(s) = doc.symbols.iter().find(|s| s.name == *symbol) + { + drawn_changes(doc, &s.art, left_out, false, walked, sets); + } + } + for c in n.children().into_iter().flatten() { + drawn_changes(doc, c, left_out, hidden, walked, sets); + } +} + +/// The most copies of one dynamic symbol's art [`bounds_without`] measures, one for each set of +/// appearance changes its instances make; a symbol whose instances make more sets is measured whole. +const MAX_ART_COPIES: usize = 64; + +/// `n`, the object at place `at` of a symbol's art, with the appearance changes `changed` that an +/// instance makes to it applied in their order; `n` itself for the art of a symbol that is not +/// dynamic (`changed` is `None`) and when no change names `at`. +fn as_drawn<'a>(n: &'a Node, changed: Option<&[&SymbolOverride]>, at: &[u32]) -> Cow<'a, Node> { + let here: Vec = + changed.into_iter().flatten().filter(|o| o.path == at).map(|o| SymbolOverride { path: Vec::new(), ..(*o).clone() }).collect(); + if here.is_empty() { + return Cow::Borrowed(n); + } + let mut m = n.clone(); + vectorcraft_doc::symbol_overrides::apply(&mut m, &here); + Cow::Owned(m) +} + +/// Whether `n` has a visible effect, fill or stroke of its own, which the objects it holds can +/// take part in. +fn has_effects(n: &Node) -> bool { + n.appearance.effects.iter().any(|e| e.visible) || n.appearance.items.iter().any(|i| i.visible()) +} + +/// `n` without the objects that `left_out` picks in it, when it is a layer or a group, and in the +/// layers and groups in it at any depth; `None` when it picks none of them. A clipping layer or +/// group keeps its clipping path, its first object, and a Shaper group and a layer or group with +/// effects, fills or strokes of its own keep all they hold. In the art of a dynamic symbol +/// (`changed`, the changes an instance makes to it, as for [`all_left_out`]; `n` is at place +/// `at`), each object is judged with those changes ([`as_drawn`]), and an object taken out leaves +/// an empty group in its place. +fn without_nodes(n: &Arc, left_out: &dyn Fn(&Node) -> bool, changed: Option<&[&SymbolOverride]>, at: &mut Vec) -> Option> { + let (NodeKind::Layer { children, clip, .. } | NodeKind::Group { children, clip }) = &n.kind else { return None }; + if has_effects(&as_drawn(n, changed, at)) || n.extras().shaper.is_some() { + return None; + } + let mut taken = false; + let kept: Vec> = children + .iter() + .enumerate() + .filter_map(|(i, c)| { + at.push(i as u32); + let out = if left_out(&as_drawn(c, changed, at)) && !(*clip && i == 0) { + taken = true; + changed.map(|_| Arc::new(Node::group(c.id, Vec::new()))) + } else { + Some(without_nodes(c, left_out, changed, at).inspect(|_| taken = true).unwrap_or_else(|| c.clone())) + }; + at.pop(); + out + }) + .collect(); + taken.then(|| { + let mut new = (**n).clone(); + if let NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } = &mut new.kind { + *children = kept; + } + Arc::new(new) + }) +} + /// The `rect` param of a raster export: `[x, y, width, height]` in points, y down. `None` when /// absent; an error when it is not four finite numbers with a positive size, when the format isn't /// a raster one, or when it comes with an artboard choice (`rect` is the area, so those would @@ -481,6 +751,35 @@ pub(crate) fn with_single_artboard(mut d: Document, rect: Rect, name: &str) -> D d } +/// `nodes` with the visible objects that `left_out` picks hidden, in layers, sublayers and groups +/// that don't clip, at any depth (what an object it picks holds is not looked at); `None` when it +/// picks none of them. Clipping layers are looked in too, as their sublayers can be picked. +pub(super) fn hidden_nodes(nodes: &[Arc], left_out: &dyn Fn(&Node) -> bool) -> Option>> { + let mut out: Option>> = None; + for (i, l) in nodes.iter().enumerate() { + let new = if left_out(l) { + l.visible.then(|| { + let mut n = (**l).clone(); + n.visible = false; + Arc::new(n) + }) + } else { + let (NodeKind::Layer { children, .. } | NodeKind::Group { children, clip: false }) = &l.kind else { continue }; + hidden_nodes(children, left_out).map(|c| { + let mut n = (**l).clone(); + if let NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } = &mut n.kind { + *children = c; + } + Arc::new(n) + }) + }; + if let Some(slot) = new.and_then(|new| Some((out.get_or_insert_with(|| nodes.to_vec()).get_mut(i)?, new))) { + *slot.0 = slot.1; + } + } + out +} + fn boards(r: std::result::Result) -> Result { r.map_err(|e| bad(C, e)) } @@ -636,8 +935,9 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result { { return Ok(enc); } + let left_out = |n: &Node| f.id == "hpgl" && vectorcraft_cad::hpgl::write::plots_nothing(doc, n); if use_artboards == Some(false) - && let Some((art, q)) = art_page(C, doc, p)? + && let Some((art, q)) = art_page(C, doc, p, left_out)? { return encode_files(&art, f, &q); } diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index bb9dc3711a..7ed3fb723d 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -550,9 +550,10 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result // Optical Margin Alignment setting and writing direction. When that changes the direction of a // frame of a restored document, the story flows through that frame's thread again. Threaded // frames keep their size: Auto Size is off for them. The story is laid out in the document's - // own composite fonts. + // own composite fonts, and type naming one the document does not define flows as in a missing + // font, also when the document defines none. let fonts = if doc.text_threads.is_empty() { Default::default() } else { doc.composite_fonts.clone() }; - let lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&fonts); + let lent = vectorcraft_text::FontDb::global().lend_document_composite_fonts(&fonts); if !doc.text_threads.is_empty() && !restored { crate::cmd::threads::reflow(&Document::new(1.0, 1.0), &mut doc); } else if !doc.text_threads.is_empty() { @@ -677,15 +678,28 @@ impl ReadFile { /// ([`super::importer`]). pub fn read_for_open(name: &str, bytes: &[u8], path: Option, p: &Value, update_links: bool, low_res_proxy_eps: bool) -> Result { let opts = LoadOptions::from_params("document.open", p)?; - let mut loaded = match super::importer::pick(name, bytes, p)? { - Some(plugin) => super::importer::load(name, bytes, &plugin, p)?, - None => load_with(name, bytes, &opts)?, + let mut loaded = if opts.link_pages { + linked_pages(name, bytes, path.as_deref(), &opts)? + } else { + match super::importer::pick(name, bytes, p)? { + Some(plugin) => super::importer::load(name, bytes, &plugin, p)?, + None => load_with(name, bytes, &opts)?, + } }; let links = crate::cmd::links::resolve(&mut loaded.doc, crate::cmd::links::LinkBase::file(path.as_deref()), update_links, low_res_proxy_eps); Session::refresh_text_bounds(&mut loaded.doc); Ok(ReadFile { loaded, opts, path, links }) } +/// The PDF `name` (`bytes`, read from `path`) opened with `linkPages`: its pages as placed documents +/// linked to them ([`super::pdfimport::linked_pages`]), named after the file. +fn linked_pages(name: &str, bytes: &[u8], path: Option<&str>, opts: &LoadOptions) -> Result { + let (mut doc, warnings) = super::pdfimport::linked_pages(name, bytes, path, opts)?; + doc.title = file_name(name); + let format = detect(name, bytes).ok_or_else(|| err(format!("can't open `{}`: not a PDF", file_name(name))))?; + Ok(Loaded { doc, format, warnings, restored: false, converted: false, preview_only: false, editing_data: false, native_pdf_compatible: None }) +} + /// The second half of [`open_bytes_with`]: open a file [`read_for_open`] read as the new active /// document → `document.open`'s result. pub fn open_read(s: &mut Session, file: ReadFile) -> Result { @@ -850,7 +864,9 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option { /// they are, with their ink amounts ([`ImageBlob::cmyk`]), except that ones storing one plane per /// ink are written again with their inks together ([`vectorcraft_doc::cmyk::stored_cmyk_tiff`]); /// CMYK TIFFs with an alpha channel, which the decoder can't read, become RGBA in the active color -/// settings' CMYK, as do CMYK Photoshop documents, whose merged image is read ([`psdread`]). +/// settings' CMYK, whichever of their extra channels is the alpha +/// ([`vectorcraft_doc::cmyk::extra_samples_tiff_rgba`]), as do CMYK Photoshop documents, whose +/// merged image is read ([`psdread`]). /// 1-bit TIFFs compressed with CCITT Group 3, which the decoder can't read either, become RGBA /// too ([`vectorcraft_doc::cmyk::group3_tiff_rgba`]). /// Grayscale TIFFs with an alpha channel or other extra channels, which the decoder can't read diff --git a/crates/engine/src/cmd/fileio/pdf.rs b/crates/engine/src/cmd/fileio/pdf.rs index c834e653e4..da6da069e9 100644 --- a/crates/engine/src/cmd/fileio/pdf.rs +++ b/crates/engine/src/cmd/fileio/pdf.rs @@ -128,7 +128,7 @@ pub fn specs() -> Vec { "Export PDF", [], None, - "{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art, as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused", + "{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says; a CMYK image that keeps its numbers carries the CMYK profile it embeds with all and taggedSource, and in PDF/A, pdfX3 and pdfX4 unless destination, never in pdfX1a), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused", has_doc, export_pdf ), @@ -289,7 +289,7 @@ pub const EDITING_NEEDS_THE_ARTBOARDS: &str = /// Editing on, the notes end with [`EDITING_NEEDS_THE_ARTBOARDS`]. `None` when `p` asks for the /// artboards. pub(super) fn encode_art_page(cmd: &str, doc: &Document, p: &Value) -> Result, Vec)>> { - let Some((art, mut q)) = super::encode::art_page(cmd, doc, p)? else { return Ok(None) }; + let Some((art, mut q)) = art_page(cmd, doc, p)? else { return Ok(None) }; let left_out = settings(cmd, &q)?.preserve_editing; if left_out && let Some(o) = q.as_object_mut() { o.insert("preserveEditing".into(), json!(false)); @@ -301,6 +301,18 @@ pub(super) fn encode_art_page(cmd: &str, doc: &Document, p: &Value) -> Result Result> { + if super::encode::use_artboards(cmd, p)? != Some(false) { + return Ok(None); + } + let set = settings(cmd, p)?; + let keeps = set.include_non_printing || set.create_layers; + super::encode::art_page(cmd, doc, p, |l| !keeps && matches!(l.kind, NodeKind::Layer { printable: false, .. })) +} + /// The warning for a PDF/X file that leaves out the document's bleed /// ([`vectorcraft_pdf::PdfSettings::leaves_out_bleed`]). pub const BLEED_LEFT_OUT: &str = "the document sets a bleed that this PDF/X file leaves out: turn on Use document bleed settings"; @@ -477,29 +489,7 @@ fn thumbnails(doc: &Document, opts: &PdfOptions) -> std::result::Result]) -> Option>> { - let mut out: Option>> = None; - for (i, l) in layers.iter().enumerate() { - let NodeKind::Layer { printable, children, .. } = &l.kind else { continue }; - let new = if !printable { - l.visible.then(|| { - let mut n = (**l).clone(); - n.visible = false; - Arc::new(n) - }) - } else { - without_non_printing(children).map(|c| { - let mut n = (**l).clone(); - if let NodeKind::Layer { children, .. } = &mut n.kind { - *children = c; - } - Arc::new(n) - }) - }; - if let Some(slot) = new.and_then(|new| Some((out.get_or_insert_with(|| layers.to_vec()).get_mut(i)?, new))) { - *slot.0 = slot.1; - } - } - out + super::encode::hidden_nodes(layers, &|l| matches!(l.kind, NodeKind::Layer { printable: false, .. })) } fn export_pdf(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/fileio/pdfimport.rs b/crates/engine/src/cmd/fileio/pdfimport.rs index 2a0dede17f..b0f08ca4c5 100644 --- a/crates/engine/src/cmd/fileio/pdfimport.rs +++ b/crates/engine/src/cmd/fileio/pdfimport.rs @@ -2,11 +2,15 @@ //! and `file.place` read ([`LoadOptions`]), the pages they import and `document.pdfInfo` (pages, //! boxes, a thumbnail; one page for a PostScript file) for the Import PDF dialog. +use std::sync::Arc; + use serde_json::{Value, json}; -use vectorcraft_doc::{ColorMode, Document}; +use vectorcraft_doc::{Artboard, ColorMode, Document, LayerColor, LinkInfo, Node, NodeKind}; +use vectorcraft_geom::{Affine, Rect}; use vectorcraft_pdf::{Choice, CropTo, ImportOptions, PdfError, TextAs}; use super::super::colormgmt::Grays; +use super::super::place::document; use super::super::{Result, Session, bad, check_numbers, number_or, parse_range, text_param}; use super::{err, source}; @@ -47,6 +51,9 @@ pub struct LoadOptions { /// A PDF or `.ai` saved with Preserve Editing opens from the VectorCraft document it carries; /// off, it opens as another app would open it, from the editing copy of its art or its pages. pub native: bool, + /// Each page of a PDF opens as a placed document linked to that page of its file, on an + /// artboard of its own, instead of as editable art (`linkPages`; see [`linked_pages`]). + pub link_pages: bool, } impl Default for LoadOptions { @@ -65,6 +72,7 @@ impl Default for LoadOptions { trust_editing_data: false, legacy_names: vectorcraft_eps::NameEncoding::default(), native: true, + link_pages: false, } } } @@ -74,8 +82,8 @@ impl LoadOptions { /// `pages` isn't given), `cropTo` (or `crop`), `password`, `colorMode` (`rgb` | `cmyk`) with `grays`, /// `textAs` (`text` | `outlines`), `layers` (true | false), `hiddenLayers` (true | false), /// `editingData` (true | false | `always`), - /// `legacyNameEncoding` (one of [`vectorcraft_eps::NameEncoding::LABELS`]) and `dxf` (the DXF - /// import options). + /// `legacyNameEncoding` (one of [`vectorcraft_eps::NameEncoding::LABELS`]), `linkPages` (true | + /// false) and `dxf` (the DXF import options). pub fn from_params(cmd: &str, p: &Value) -> Result { let pages = match p.get("pages").filter(|v| !v.is_null()).or_else(|| p.get("page").filter(|v| !v.is_null())) { None => None, @@ -115,6 +123,10 @@ impl LoadOptions { .and_then(vectorcraft_eps::NameEncoding::from_label) .ok_or_else(|| bad(cmd, format!("legacyNameEncoding must be one of {}", vectorcraft_eps::NameEncoding::LABELS.join(", "))))?, }; + let link_pages = match p.get("linkPages").filter(|v| !v.is_null()) { + None => false, + Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "linkPages must be true or false"))?, + }; let dxf = super::dxfimport::options(cmd, p.get("dxf"))?; Ok(Self { pages, @@ -130,14 +142,15 @@ impl LoadOptions { trust_editing_data, legacy_names, native: true, + link_pages, }) } /// Does the document read only part of the file, or read it differently (a page range, another - /// box, a password, without its hidden layers, without the VectorCraft document it carries)? - /// Writing it back would lose the rest, so Save doesn't (it asks for a name). + /// box, a password, without its hidden layers, without the VectorCraft document it carries, its + /// pages linked)? Writing it back would lose the rest, so Save doesn't (it asks for a name). pub fn is_partial(&self) -> bool { - self.pages.is_some() || self.crop != CropTo::default() || self.password.is_some() || !self.layers || !self.native + self.pages.is_some() || self.crop != CropTo::default() || self.password.is_some() || !self.layers || !self.native || self.link_pages } /// The PDF import options: `pages` resolved against the file's page count. A PDF-compatible @@ -201,6 +214,82 @@ fn page_options(page: usize, o: &LoadOptions) -> ImportOptions { ImportOptions { pages: Some(vec![page]), crop: o.crop, password: o.password.clone(), text_as: o.text_as, layers: false, ..Default::default() } } +/// `document.open` with `linkPages`: the pages `o` picks of the PDF (or PDF-compatible `.ai` or +/// `.ait`) `name`, read from `path`, as a document holding one placed document per page, linked to +/// that page of the file as File › Place with Link places one ([`document::source`]). Each page +/// gets an artboard of its `o.crop` box (its art's bounds for `bounding`), in a row from the left +/// with the gap a PDF's artboards open with, and a layer named after the page. The document opens +/// in CMYK when most of the pages read in CMYK, unless `o.color_mode` names a mode. Refused without a +/// path, for any other file, with a password (a linked page is read again without one), with +/// `textAs: outlines` (a linked page shows the file's own type) and for a file over +/// [`document::MAX_FILE`] → the document and the notes of reading its pages. +pub(super) fn linked_pages(name: &str, bytes: &[u8], path: Option<&str>, o: &LoadOptions) -> Result<(Document, Vec)> { + const C: &str = "document.open"; + let file = super::file_name(name); + if !document::is_pdf(name, bytes) { + return Err(bad(C, format!("linkPages: `{file}` isn't a PDF or a PDF-compatible .ai file"))); + } + let path = path.ok_or_else(|| bad(C, "linkPages needs the file's path: linked pages are read from it"))?; + if o.password.is_some() { + return Err(bad(C, "linkPages can't open a file with a password: linked pages are read again without it")); + } + if o.text_as != TextAs::Text { + return Err(bad(C, "linkPages can't be used with textAs: outlines: linked pages show the file's own type")); + } + if bytes.len() > document::MAX_FILE { + return Err(bad(C, format!("linkPages: `{file}` is over {} MB", document::MAX_FILE >> 20))); + } + let count = vectorcraft_pdf::open_pdf(bytes, None).map_err(err)?.page_count(); + let picked = match &o.pages { + None => (0..count).collect(), + Some(range) => parse_range(range, count).map_err(|e| err(format!("pages: {e}")))?, + }; + let bounding = o.crop == CropTo::Bounding; + let mut doc = Document::new(1.0, 1.0); + let board = doc.artboards.first().cloned().ok_or_else(|| err("a new document has no artboard"))?; + doc.artboards.clear(); + doc.layers.clear(); + let link = crate::cmd::links::link_info(path, bytes); + let gap = ImportOptions::default().artboard_gap; + // Every page's object keeps the same one copy of the file. + let shared = Arc::new(bytes.to_vec()); + let (mut x, mut warnings, mut cmyk_pages) = (0.0, Vec::::new(), 0); + for (i, &index) in picked.iter().enumerate() { + let page = index as u32 + 1; + let s = document::shared_source(name, &shared, Some(path), page, bounding, document::page_box(o.crop), C)?; + cmyk_pages += usize::from(s.color_mode == ColorMode::Cmyk); + let mut node = document::node(&mut doc, &s, LinkInfo { page: Some(page), ..link.clone() }, bounding); + if let NodeKind::PlacedDocument(p) = &mut node.kind { + p.xf = Affine::translate((x, 0.0)); + } + node.name = Some(file.clone()); + let mut layer = Node::layer(doc.alloc_id(), &format!("Page {page}"), LayerColor::Preset((i % 27) as u8)); + if let NodeKind::Layer { children, .. } = &mut layer.kind { + children.push(Arc::new(node)); + } + doc.layers.push(Arc::new(layer)); + let rect = Rect::new(x, 0.0, x + s.frame.width(), s.frame.height()); + doc.artboards.push(Artboard { id: i as u32 + 1, name: format!("Artboard {}", i + 1), rect, ..board.clone() }); + x = rect.x1 + gap; + for w in s.warnings { + if !warnings.contains(&w) { + warnings.push(w); + } + } + } + // Pages painted mostly in CMYK read as CMYK documents, as opening them as art does: the + // document opens in CMYK (with the CMYK default swatches) when most of its pages do. + if cmyk_pages * 2 > picked.len() { + doc.color_mode = ColorMode::Cmyk; + let (swatches, groups) = vectorcraft_color::default_swatches(ColorMode::Cmyk.model()); + (doc.swatches, doc.swatch_groups) = (swatches.into(), groups.into()); + } + if let Some(mode) = o.color_mode.filter(|m| *m != doc.color_mode) { + super::super::colormgmt::set_color_mode(&mut doc, mode, true, None, o.grays); + } + Ok((doc, warnings)) +} + const INFO: &str = "document.pdfInfo"; /// `document.pdfInfo`. diff --git a/crates/engine/src/cmd/fileio/ppi.rs b/crates/engine/src/cmd/fileio/ppi.rs index 6998d86b28..119201bb87 100644 --- a/crates/engine/src/cmd/fileio/ppi.rs +++ b/crates/engine/src/cmd/fileio/ppi.rs @@ -3,26 +3,22 @@ //! header's HDpi and VDpi, JP2 capture and display resolution boxes, or a HEIF image's EXIF //! resolution tags. Place //! sizes an image by it (72 ppi when the file has none); images converted to PNG on import keep it -//! as a `pHYs` chunk. +//! as a `pHYs` chunk. The formats the image decoder reads are read by [`vectorcraft_doc::ppi`]. + +pub(super) use vectorcraft_doc::ppi::png_chunks; +use vectorcraft_doc::ppi::tiff; +pub use vectorcraft_doc::ppi::with_png_resolution; const INCH_M: f64 = 0.0254; -const INCH_CM: f64 = 2.54; /// The resolution a file declares as (horizontal, vertical) ppi; `None` when it declares none (or /// only an aspect ratio). pub fn resolution(bytes: &[u8]) -> Option<(f64, f64)> { - let r = if bytes.starts_with(b"\x89PNG\r\n\x1a\n") { - png(bytes) - } else if bytes.starts_with(&[0xff, 0xd8]) { - jpeg(bytes) - } else if bytes.starts_with(b"II*\0") || bytes.starts_with(b"MM\0*") { - tiff(bytes) - } else if super::jxlread::is_jxl(bytes) { + if vectorcraft_doc::ppi::reads(bytes) { + return vectorcraft_doc::ppi::resolution(bytes); + } + let r = if super::jxlread::is_jxl(bytes) { jxl(bytes) - } else if bytes.len() >= 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" { - webp(bytes) - } else if bytes.starts_with(b"BM") { - bmp(bytes) } else if super::psdread::is_psd(bytes) { super::psdread::resolution(bytes) } else if super::pcxread::is_pcx(bytes) { @@ -82,121 +78,9 @@ fn slice(b: &[u8], at: usize, n: usize) -> Option<&[u8]> { fn bytes(b: &[u8], at: usize) -> Option<[u8; N]> { slice(b, at, N)?.try_into().ok() } -fn be16(b: &[u8], at: usize) -> Option { - bytes(b, at).map(u16::from_be_bytes) -} fn be32(b: &[u8], at: usize) -> Option { bytes(b, at).map(u32::from_be_bytes) } -fn le32(b: &[u8], at: usize) -> Option { - bytes(b, at).map(u32::from_le_bytes) -} - -/// Pixels per inch from the whole pixels per metre PNG and BMP store: a whole number of ppi when -/// the metre value is that rounded (300 ppi is stored as 11811 per metre, 299.9994 ppi). -fn per_metre(ppm: u32) -> f64 { - let v = ppm as f64 * INCH_M; - let whole = v.round(); - if (v - whole).abs() <= INCH_M / 2.0 + 1e-9 { whole } else { v } -} - -/// PNG chunks after the signature: (type, data). -pub(super) fn png_chunks(b: &[u8]) -> impl Iterator { - let mut at = 8; - std::iter::from_fn(move || { - let len = be32(b, at)? as usize; - let ty = slice(b, at + 4, 4)?; - let data = slice(b, at + 8, len)?; - at = at.checked_add(12 + len)?; - Some((ty, data)) - }) -} - -fn png(b: &[u8]) -> Option<(f64, f64)> { - let (_, d) = png_chunks(b).take_while(|(ty, _)| *ty != b"IDAT").find(|(ty, _)| *ty == b"pHYs")?; - // Unit 1 = metre; 0 only gives the pixel aspect ratio. - (d.get(8) == Some(&1)).then(|| (per_metre(be32(d, 0).unwrap_or(0)), per_metre(be32(d, 4).unwrap_or(0)))) -} - -fn jpeg(b: &[u8]) -> Option<(f64, f64)> { - let (mut jfif, mut exif) = (None, None); - let mut at = 2; - while at + 4 <= b.len() && b[at] == 0xff { - let marker = b[at + 1]; - // 0xff fill bytes pad between segments. - if marker == 0xff { - at += 1; - continue; - } - if marker == 0xd8 || marker == 0x01 || (0xd0..=0xd7).contains(&marker) { - at += 2; - continue; - } - // Start of scan or end of image: no more metadata. - if marker == 0xda || marker == 0xd9 { - break; - } - let len = be16(b, at + 2)? as usize; - let seg = slice(b, at + 4, len.checked_sub(2)?)?; - match marker { - 0xe0 if seg.starts_with(b"JFIF\0") && seg.len() >= 12 => { - let (x, y) = (be16(seg, 8)? as f64, be16(seg, 10)? as f64); - jfif = match seg[7] { - 1 => Some((x, y)), - 2 => Some((x * INCH_CM, y * INCH_CM)), - _ => None, - }; - } - 0xe1 if seg.starts_with(b"Exif\0\0") => exif = tiff(&seg[6..]), - _ => {} - } - at += 2 + len; - } - jfif.or(exif) -} - -/// TIFF (or EXIF) IFD0 XResolution / YResolution / ResolutionUnit. -fn tiff(b: &[u8]) -> Option<(f64, f64)> { - let le = b.starts_with(b"II"); - let u16_at = |at: usize| bytes(b, at).map(if le { u16::from_le_bytes } else { u16::from_be_bytes }); - let u32_at = |at: usize| bytes(b, at).map(if le { u32::from_le_bytes } else { u32::from_be_bytes }); - let ifd = u32_at(4)? as usize; - let (mut x, mut y, mut unit) = (None, None, 2); - for i in 0..u16_at(ifd)? as usize { - let e = ifd.checked_add(2 + i * 12)?; - let rational = || -> Option { - let at = u32_at(e + 8)? as usize; - let (n, d) = (u32_at(at)?, u32_at(at.checked_add(4)?)?); - (d != 0).then(|| n as f64 / d as f64) - }; - match u16_at(e)? { - 282 => x = rational(), - 283 => y = rational(), - 296 => unit = u16_at(e + 8)?, - _ => {} - } - } - let k = match unit { - 2 => 1.0, - 3 => INCH_CM, - _ => return None, - }; - let x = x?; - Some((x * k, y.unwrap_or(x) * k)) -} - -fn webp(b: &[u8]) -> Option<(f64, f64)> { - let mut at = 12; - while at + 8 <= b.len() { - let len = le32(b, at + 4)? as usize; - let data = b.get(at + 8..at + 8 + len)?; - if &b[at..at + 4] == b"EXIF" { - return tiff(data.strip_prefix(b"Exif\0\0").unwrap_or(data)); - } - at += 8 + len + (len & 1); - } - None -} fn jxl(b: &[u8]) -> Option<(f64, f64)> { if !b.starts_with(&[0, 0, 0, 12, b'J', b'X', b'L', b' ', 13, 10, 135, 10]) { @@ -224,33 +108,6 @@ fn jxl(b: &[u8]) -> Option<(f64, f64)> { None } -fn bmp(b: &[u8]) -> Option<(f64, f64)> { - // BITMAPINFOHEADER (40 bytes or longer) at 14: pixels per metre at +24 and +28. - if le32(b, 14)? < 40 { - return None; - } - let ppm = |at| le32(b, at).filter(|v| (1..=i32::MAX as u32).contains(v)).map(per_metre); - Some((ppm(38)?, ppm(42)?)) -} - -/// `png` with a `pHYs` chunk declaring `ppi` right after the header (any existing one is replaced). -pub fn with_png_resolution(png: &[u8], (x, y): (f64, f64)) -> Vec { - let Some(head) = be32(png, 8).and_then(|len| slice(png, 0, 20usize.checked_add(len as usize)?)) else { return png.to_vec() }; - let chunk = vectorcraft_render::encode::png::phys_chunk(x, y); - let mut out = Vec::with_capacity(png.len() + chunk.len()); - out.extend_from_slice(head); - out.extend_from_slice(&chunk); - let mut at = head.len(); - while let Some(chunk) = be32(png, at).and_then(|len| slice(png, at, 12usize.checked_add(len as usize)?)) { - if chunk.get(4..8) != Some(b"pHYs") { - out.extend_from_slice(chunk); - } - at += chunk.len(); - } - out.extend_from_slice(png.get(at..).unwrap_or_default()); - out -} - #[cfg(test)] mod tests { use super::*; diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index af9ed8e58a..e4a72ffc35 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -757,8 +757,9 @@ pub const AI_EDITING_NEEDS_THE_ARTBOARDS: &str = pub const ART_PAGE_NEEDS_PDF: &str = "pdfCompatible: false needs the artboards to keep the editable artwork when useArtboards is false"; /// With `useArtboards: false` in `p`: the PDF-compatible `.ai` file of one page, the bounds of -/// `doc`'s visible art ([`super::encode::art_page`]). It carries neither the native document nor -/// the editing copy for other apps, and its notes end with [`AI_EDITING_NEEDS_THE_ARTBOARDS`]. +/// `doc`'s visible art on the layers its pages draw ([`super::pdf::art_page`]). It carries neither +/// the native document nor the editing copy for other apps, and its notes end with +/// [`AI_EDITING_NEEDS_THE_ARTBOARDS`]. /// `pdfCompatible: false` is refused. `None` when `p` asks for the artboards or for a legacy /// version 7 `.ai` file. pub(super) fn encode_ai_art_page(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result> { @@ -768,7 +769,7 @@ pub(super) fn encode_ai_art_page(cmd: &str, f: &Format, doc: &Document, p: &Valu if !bool_or(p, "pdfCompatible", true) { return Err(bad(cmd, ART_PAGE_NEEDS_PDF)); } - let Some((art, q)) = super::encode::art_page(cmd, doc, p)? else { return Ok(None) }; + let Some((art, q)) = super::pdf::art_page(cmd, doc, &ai_pdf_params(p, false))? else { return Ok(None) }; let mut enc = encode_ai_pages(cmd, f, &art, &q, false)?; enc.setting_notes.push(AI_EDITING_NEEDS_THE_ARTBOARDS.to_string()); Ok(Some(enc)) @@ -784,9 +785,10 @@ pub(super) fn encode_ai(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Res encode_ai_pages(cmd, f, doc, p, true) } -/// [`encode_ai`] of a `.ai` file with or without PDF content, carrying the native document and -/// the editing copy for other apps when `editing` is true, and neither otherwise. -fn encode_ai_pages(cmd: &str, f: &Format, doc: &Document, p: &Value, editing: bool) -> Result { +/// `p` with the PDF options a `.ai` file is written with: Preserve Editing when `editing` is true, +/// layers unless a standard decides, long pages with a `UserUnit`, and `compress` as +/// `compression.compressText`. +fn ai_pdf_params(p: &Value, editing: bool) -> Value { let mut params = if p.is_object() { p.clone() } else { json!({}) }; if let Some(o) = params.as_object_mut() { o.insert("preserveEditing".into(), json!(editing)); @@ -805,6 +807,13 @@ fn encode_ai_pages(cmd: &str, f: &Format, doc: &Document, p: &Value, editing: bo } } } + params +} + +/// [`encode_ai`] of a `.ai` file with or without PDF content, carrying the native document and +/// the editing copy for other apps when `editing` is true, and neither otherwise. +fn encode_ai_pages(cmd: &str, f: &Format, doc: &Document, p: &Value, editing: bool) -> Result { + let params = ai_pdf_params(p, editing); let pdf_compatible = bool_or(¶ms, "pdfCompatible", true); let f = &if pdf_compatible { *f } else { without_pdf(f) }; let native_options = super::native::ai_options(cmd, f, doc, ¶ms)?; diff --git a/crates/engine/src/cmd/fileio/tests.rs b/crates/engine/src/cmd/fileio/tests.rs index 7374e26e2b..b66b22d1a8 100644 --- a/crates/engine/src/cmd/fileio/tests.rs +++ b/crates/engine/src/cmd/fileio/tests.rs @@ -202,6 +202,41 @@ fn a_16_bit_cmyk_tiff_with_alpha_places_at_16_bits() { } } +/// A CMYK or grayscale TIFF whose alpha follows another extra sample opens and places with that +/// alpha, at 8 and 16 bits, chunky and planar; a CMYK one is not kept as inks. A CMYK one with two +/// more samples than its ExtraSamples values count does too. +#[test] +fn a_tiff_with_alpha_after_another_extra_sample_places_with_its_alpha() { + let none = vec![0u16; 6]; + let full = vec![255u16; 6]; + let other = vec![9u16, 8, 7, 6, 5, 4]; + let alpha = vec![255u16, 128, 0, 255, 64, 1]; + let inks = [full.clone(), none.clone(), none.clone(), none.clone()]; + let cases = [ + ("CMYK", 5, vec![full.clone(), none.clone(), none.clone(), none.clone(), other.clone(), alpha.clone()]), + ("CMYK, two more samples", 5, [&inks[..], &[other.clone(), alpha.clone(), other.clone(), full.clone()]].concat()), + ("gray", 1, vec![full.clone(), other.clone(), alpha.clone()]), + ]; + for (what, photometric, channels) in cases { + for bits in [8, 16] { + let wide: Vec> = channels.iter().map(|ch| ch.iter().map(|v| if bits == 16 { v * 257 } else { *v }).collect()).collect(); + for planar in [false, true] { + let what = format!("{what}, {bits} bits, planar {planar}"); + let file = hand_tiff(photometric, bits, &[0, 2], planar, &wide); + let (inks, rgba) = kept(&what, &file); + assert_eq!(inks, None, "{what}: shown as RGB with its alpha"); + let alphas: Vec = rgba.iter().skip(3).step_by(4).copied().collect(); + assert_eq!(alphas, [255, 128, 0, 255, 64, 1], "{what}: the alpha is the second extra sample"); + let mut s = session(100.0, 100.0, 1); + s.execute("file.place", &json!({"name": "a.tif", "dataBase64": vectorcraft_format::base64_encode(&file)})).unwrap(); + let blob = &s.doc().unwrap().doc.images[&image_of(&s).key]; + let placed = image::load_from_memory(&blob.bytes).unwrap().to_rgba8().into_raw(); + assert_eq!(placed, rgba, "{what}: Place reads it as Open does"); + } + } + } +} + /// A planar TIFF whose header claims more strips than the decoder can count (here 2^31 + 1 rows /// a strip each, times 5 planes) is refused as too large to draw, without a panic. #[test] diff --git a/crates/engine/src/cmd/fileio/tests_aiimport.rs b/crates/engine/src/cmd/fileio/tests_aiimport.rs index fafcc12215..c48b437b76 100644 --- a/crates/engine/src/cmd/fileio/tests_aiimport.rs +++ b/crates/engine/src/cmd/fileio/tests_aiimport.rs @@ -424,8 +424,8 @@ fn a_graphic_style_library_in_a_ai_file_without_layers_loads_its_styles() { /BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n{xa}0 1 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n;\n" ) }; - // Styles of one paint (`/SimpleStyle`): a red 2 pt stroke and no fill, and a gradient fill, - // which isn't read, so it is left out rather than listed with no paint. + // Styles of one paint (`/SimpleStyle`): a red 2 pt stroke and no fill, and a fill with a gradient + // the file doesn't define, which is left out rather than listed with no paint. let one_paint = |name: &str, paint: &str| format!("/KnownStyle :\n({name}) /Name ,\n/SimpleStyle :\n{paint}/Paint ;\n/Def ;\n"); let styles = format!( "%AI9_BeginArtStyles\n{}{}{}{}{}%AI9_EndArtStyles\n\ @@ -465,6 +465,64 @@ fn a_graphic_style_library_in_a_ai_file_without_layers_loads_its_styles() { assert_eq!(styles, [("Red", 1), ("Green", 2), ("Blue", 3), ("Red outline", 4)], "{r}"); } +/// A `.ai` graphic style library's styles that paint with one of the file's gradients by name (a +/// fill style's, and the fill or stroke of a style of one paint) load with that gradient at the +/// style's angle, fitted to the bounds of each object the style is applied to; one naming a gradient +/// the file doesn't define is left out. +#[test] +fn graphic_styles_in_a_ai_library_that_paint_with_a_named_gradient_load_with_it() { + let gradient = + "%AI5_BeginGradient: (Sky)\n(Sky) 0 2 Bd\n[\n%_0 0 0 0 0 1 0 2 1 6 50 0 Bs\n%_0 0 0 0 1 1 1 2 1 6 50 100 Bs\nBD\n%AI5_EndGradient\n"; + let band = "/KnownStyle :\n(Sky band) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n\ + 0 Bb\n2 (Sky) 0 0 45 100 1 0 0 1 0 0 Bg\n0 BB\n0 1 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n;\n"; + let one_paint = |name: &str, paint: &str| format!("/KnownStyle :\n({name}) /Name ,\n/SimpleStyle :\n{paint}/Paint ;\n/Def ;\n"); + let styles = format!( + "%AI9_BeginArtStyles\n{band}{}{}{}%AI9_EndArtStyles\n\ + %AI9_BeginArtStyleList\n(Sky band)\n(Sky fill)\n(Sky outline)\n(Dusk fill)\n%AI9_EndArtStyleList\n", + one_paint("Sky fill", "0 O\n0 Bb\n2 (Sky) 0 0 0 100 1 0 0 1 0 0 Bg\n0 BB\n0 1 Xd\n"), + one_paint("Sky outline", "0 R\n0 J 0 j 2 w 10 M []0 d\n1 Bb\n2 (Sky) 0 0 90 100 1 0 0 1 0 0 1 Bg\n0 BB\n1 0 Xd\n"), + one_paint("Dusk fill", "0 O\n0 Bb\n2 (Dusk) 0 0 0 100 1 0 0 1 0 0 Bg\n0 BB\n0 1 Xd\n") + ); + // A palette with the gradient's swatch, so the document opened from the file shows its gradient. + let palette = INKS_PALETTE.replace("0 0 Pb\n", "0 0 Pb\nBb\n2 (Sky) 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB\n(Sky)\nPc\n"); + let data = ai::editing_data(200.0, 100.0, &format!("{gradient}{palette}{styles}")); + let file = ai::ai(&compressed(data.as_bytes()), "1 0 0 rg 10 50 30 40 re f"); + let mut s = Session::new(); + let p = json!({"dataBase64": vectorcraft_format::base64_encode(&file), "name": "skies.ai"}); + let r = s.execute("graphicStyle.loadLibrary", &p).unwrap(); + let library = r["library"].clone(); + let lib = s.execute("graphicStyle.library", &json!({"library": library})).unwrap(); + let names: Vec<&str> = lib["styles"].as_array().unwrap().iter().map(|g| g["name"].as_str().unwrap()).collect(); + assert_eq!(names, ["Sky band", "Sky fill", "Sky outline"], "{lib}"); + // The file's gradient, as the document opened from it has its swatch. + open(&mut s, "skies.ai", &file, json!({})).unwrap(); + let sky = match s.doc().unwrap().doc.swatch("Sky").map(|w| w.paint.clone()) { + Some(vectorcraft_color::Paint::Gradient(g)) => g.gradient, + other => panic!("{other:?}"), + }; + // Applied to a small and a large rectangle, each gradient is fitted to the rectangle it paints. + s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap(); + for (style, (x, size)) in [("Sky band", (10, 20)), ("Sky fill", (40, 200)), ("Sky outline", (10, 120))] { + let rect = json!({"x": x, "y": x, "width": size, "height": size / 2}); + let id = NodeId(s.execute("shape.rectangle", &rect).unwrap()["id"].as_u64().unwrap()); + let r = s.execute("graphicStyle.addFromLibrary", &json!({"library": library, "names": [style], "apply": true, "ids": [id.0]})).unwrap(); + assert_eq!(r["added"], json!([style]), "{r}"); + let look = &s.doc().unwrap().doc.node(id).unwrap().appearance; + let (paint, angle, stroked) = match style { + "Sky outline" => (look.stroke().map(|st| &st.paint), 90.0, true), + "Sky band" => (look.fill().map(|f| &f.paint), 45.0, false), + _ => (look.fill().map(|f| &f.paint), 0.0, false), + }; + let Some(vectorcraft_color::Paint::Gradient(g)) = paint else { panic!("{style}: {look:?}") }; + assert_eq!((&g.gradient, g.geom, g.angle), (&sky, None, angle), "{style}"); + assert_eq!(look.stroke().is_some(), stroked, "{style}: {look:?}"); + if stroked { + assert!(look.fill().is_none() && look.stroke().is_some_and(|st| st.width == 2.0), "{look:?}"); + } + } +} + /// A `.ai` symbol library (symbols and their list, no layers) opens with its symbols, and Other /// Library… in the Symbols panel lists them in the list's order. #[test] diff --git a/crates/engine/src/cmd/fileio/tests_hpgl.rs b/crates/engine/src/cmd/fileio/tests_hpgl.rs index f4767fd81d..82957468d8 100644 --- a/crates/engine/src/cmd/fileio/tests_hpgl.rs +++ b/crates/engine/src/cmd/fileio/tests_hpgl.rs @@ -170,6 +170,197 @@ fn a_plot_reads_back_as_its_art() { assert!((board.height() - (30.0 + pen)).abs() < 0.1, "{board:?}"); } +/// A plot of the art's bounds is measured on the art it plots: art on a non-printing layer, on a +/// layer at 0% opacity or at 0% opacity in a group, a placed image and a path that paints nothing +/// don't move its origin, a clipping layer is measured as clipped, and a document whose only +/// visible art is such art is refused. +#[test] +fn a_plot_of_the_arts_bounds_leaves_out_the_layers_it_does_not_plot() { + let mut s = two_boards(); + let plot = |s: &mut Session| s.execute("document.export", &json!({"format": "hpgl", "useArtboards": false})).map(|v| bytes(&v)); + let alone = plot(&mut s).unwrap(); + let printing = s.doc().unwrap().doc.layers[0].id; + for props in [json!({"printable": false}), json!({})] { + let layer = s.execute("layer.new", &json!({})).unwrap()["id"].clone(); + if props.as_object().unwrap().is_empty() { + s.execute("transparency.set", &json!({"ids": [layer], "opacity": 0})).unwrap(); + } else { + let mut p = props.clone(); + p["id"] = layer.clone(); + s.execute("layer.setProps", &p).unwrap(); + } + s.execute("shape.rectangle", &json!({"x": -300, "y": 500, "width": 20, "height": 20})).unwrap(); + assert_eq!(plot(&mut s).unwrap(), alone, "{props}"); + } + // An object at 0% opacity in a group, on a layer that plots. + s.execute("layer.new", &json!({})).unwrap(); + let far = s.execute("shape.rectangle", &json!({"x": -500, "y": 700, "width": 20, "height": 20})).unwrap()["id"].clone(); + s.execute("object.group", &json!({"ids": [far]})).unwrap(); + s.execute("transparency.set", &json!({"ids": [far], "opacity": 0})).unwrap(); + assert_eq!(plot(&mut s).unwrap(), alone, "0% opacity in a group"); + // A placed image and a path whose fill and stroke paint nothing. + let mut png = vec![]; + image::DynamicImage::new_rgb8(4, 4).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + s.execute("file.place", &json!({"name": "far.png", "dataBase64": b64(&png), "at": [-600, 800]})).unwrap(); + assert_eq!(plot(&mut s).unwrap(), alone, "a placed image"); + let bare = s.execute("shape.rectangle", &json!({"x": 500, "y": -400, "width": 20, "height": 20})).unwrap()["id"].clone(); + s.execute("paint.setStroke", &json!({"ids": [bare], "none": true})).unwrap(); + assert_eq!(plot(&mut s).unwrap(), alone, "a path that paints nothing"); + + // A clipping layer's clipping path, which loses its paint, still clips the art measured: a + // large square clipped to the first square draws nothing more. + let clipping = s.execute("layer.new", &json!({})).unwrap()["id"].clone(); + s.execute("shape.rectangle", &json!({"x": -300, "y": -300, "width": 800, "height": 800})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap(); + s.execute("layer.clippingMask.toggle", &json!({"id": clipping})).unwrap(); + assert_eq!(plot(&mut s).unwrap(), alone, "a clipping layer"); + + s.execute("layer.setProps", &json!({"id": clipping, "visible": false})).unwrap(); + s.execute("layer.setProps", &json!({"id": printing, "visible": false})).unwrap(); + let e = plot(&mut s).unwrap_err().to_string(); + assert!(e.contains("no visible art"), "{e}"); +} + +/// A placed image in a symbol's art doesn't move a plot of the art's bounds either, and a +/// document whose only other visible art is an instance of that symbol is refused. +#[test] +fn a_plot_of_the_arts_bounds_leaves_out_images_in_symbol_art() { + let mut s = two_boards(); + let plot = |s: &mut Session| s.execute("document.export", &json!({"format": "hpgl", "useArtboards": false})).map(|v| bytes(&v)); + let alone = plot(&mut s).unwrap(); + let printing = s.doc().unwrap().doc.layers[0].id; + s.execute("layer.new", &json!({})).unwrap(); + let mut png = vec![]; + image::DynamicImage::new_rgb8(4, 4).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + s.execute("file.place", &json!({"name": "far.png", "dataBase64": b64(&png), "at": [-600, 800]})).unwrap(); + s.execute("symbol.new", &json!({"name": "Far"})).unwrap(); + assert!(s.doc().unwrap().doc.symbols.iter().any(|sym| sym.name == "Far")); + assert_eq!(plot(&mut s).unwrap(), alone, "an image in symbol art"); + + s.execute("layer.setProps", &json!({"id": printing, "visible": false})).unwrap(); + let e = plot(&mut s).unwrap_err().to_string(); + assert!(e.contains("no visible art"), "{e}"); + + // A symbol of a square and an image is measured by its square. + let bounds = |s: &Session| super::export_art_bounds(&s.doc().unwrap().doc, "hpgl").unwrap(); + let square = s.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": 20, "height": 20})).unwrap()["id"].clone(); + let before = bounds(&s); + let image = s.execute("file.place", &json!({"name": "near.png", "dataBase64": b64(&png), "at": [400, 600]})).unwrap()["ids"][0].clone(); + s.execute("symbol.new", &json!({"name": "Both", "ids": [square, image]})).unwrap(); + assert_eq!(s.doc().unwrap().doc.symbols.len(), 2); + let after = bounds(&s); + for (a, b) in [(before.x0, after.x0), (before.y0, after.y0), (before.x1, after.x1), (before.y1, after.y1)] { + assert!((a - b).abs() < 1e-6, "{before:?} {after:?}"); + } +} + +/// In the art of a dynamic symbol a placed image and a path that paints nothing are left out as +/// well, until an instance paints the path, and a document whose only other visible art is an +/// instance of a dynamic symbol of an image is refused. +#[test] +fn a_plot_of_the_arts_bounds_leaves_out_images_in_dynamic_symbol_art() { + let mut s = two_boards(); + let plot = |s: &mut Session| s.execute("document.export", &json!({"format": "hpgl", "useArtboards": false})).map(|v| bytes(&v)); + let bounds = |s: &Session| super::export_art_bounds(&s.doc().unwrap().doc, "hpgl").unwrap(); + let same = |a: vectorcraft_geom::Rect, b: vectorcraft_geom::Rect| { + [(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(a, b)| (a - b).abs() < 1e-6) + }; + let printing = s.doc().unwrap().doc.layers[0].id; + s.execute("layer.new", &json!({})).unwrap(); + let mut png = vec![]; + image::DynamicImage::new_rgb8(4, 4).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let image = s.execute("file.place", &json!({"name": "far.png", "dataBase64": b64(&png), "at": [-600, 800]})).unwrap()["ids"][0].clone(); + let square = s.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": 20, "height": 20})).unwrap()["id"].clone(); + let bare = s.execute("shape.rectangle", &json!({"x": 500, "y": -400, "width": 20, "height": 20})).unwrap()["id"].clone(); + s.execute("paint.setStroke", &json!({"ids": [bare], "none": true})).unwrap(); + let before = bounds(&s); + let inst = s.execute("symbol.new", &json!({"name": "Mixed", "ids": [image, square, bare], "type": "dynamic"})).unwrap()["id"].clone(); + let after = bounds(&s); + assert!(same(before, after), "{before:?} {after:?}"); + + // A change of the path's blending mode leaves it painting nothing; once the instance paints the + // path, the path is measured. + let art = s.doc().unwrap().doc.symbols[0].art.clone(); + let x0 = |c: &std::sync::Arc| c.visual_bounds().map_or(f64::MIN, |b| b.x0); + let at = (0..art.children().unwrap().len()).max_by(|a, b| x0(&art.children().unwrap()[*a]).total_cmp(&x0(&art.children().unwrap()[*b]))).unwrap(); + s.execute("symbol.instance.setAppearance", &json!({"id": inst, "path": [at], "blend": "multiply"})).unwrap(); + let blended = bounds(&s); + assert!(same(before, blended), "{before:?} {blended:?}"); + s.execute("symbol.instance.setAppearance", &json!({"id": inst, "path": [at], "stroke": "#000000"})).unwrap(); + let painted = bounds(&s); + assert!(painted.x1 > 500.0 && painted.y0 < -390.0, "{painted:?}"); + // A later change to the same object, as a file can hold, takes the paint off again. + { + let id = vectorcraft_doc::NodeId(inst.as_u64().unwrap()); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let n = d.node_mut(id).unwrap(); + let mut overrides = n.extras().symbol_overrides.clone(); + overrides.push(vectorcraft_doc::SymbolOverride { path: vec![at as u32], opacity: Some(0.0), ..Default::default() }); + n.extras_mut().symbol_overrides = overrides.clone(); + let taken_off = bounds(&s); + assert!(same(before, taken_off), "{before:?} {taken_off:?}"); + overrides.pop(); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + d.node_mut(id).unwrap().extras_mut().symbol_overrides = overrides; + } + // Another instance, far above, that doesn't paint the path is measured without it, whether or + // not the first one paints it. + let other = s.execute("symbol.place", &json!({"name": "Mixed", "x": 0, "y": -5000})).unwrap()["id"].clone(); + let with_paint = bounds(&s); + s.execute("symbol.instance.reset", &json!({"ids": [inst]})).unwrap(); + let without_paint = bounds(&s); + assert!((with_paint.y0 - without_paint.y0).abs() < 1e-6, "{with_paint:?} {without_paint:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + let undone = bounds(&s); + assert!(same(undone, with_paint), "{undone:?} {with_paint:?}"); + s.execute("select.set", &json!({"ids": [other]})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + + s.execute("select.set", &json!({"ids": [inst]})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + s.execute("layer.setProps", &json!({"id": printing, "visible": false})).unwrap(); + let image = s.execute("file.place", &json!({"name": "far.png", "dataBase64": b64(&png), "at": [-600, 800]})).unwrap()["ids"][0].clone(); + s.execute("symbol.new", &json!({"name": "Image", "ids": [image], "type": "dynamic"})).unwrap(); + let e = plot(&mut s).unwrap_err().to_string(); + assert!(e.contains("no visible art"), "{e}"); + + // An instance that brings a group at 0% opacity back to full opacity still draws nothing when + // the group holds only an image. + let image = s.execute("file.place", &json!({"name": "far.png", "dataBase64": b64(&png), "at": [-600, 800]})).unwrap()["ids"][0].clone(); + let group = s.execute("object.group", &json!({"ids": [image]})).unwrap()["id"].clone(); + s.execute("transparency.set", &json!({"ids": [group], "opacity": 0})).unwrap(); + let inst = s.execute("symbol.new", &json!({"name": "Clear", "ids": [group], "type": "dynamic"})).unwrap()["id"].clone(); + let id = vectorcraft_doc::NodeId(inst.as_u64().unwrap()); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + d.node_mut(id).unwrap().extras_mut().symbol_overrides = + [vec![], vec![0]].into_iter().map(|path| vectorcraft_doc::SymbolOverride { path, opacity: Some(1.0), ..Default::default() }).collect(); + let e = plot(&mut s).unwrap_err().to_string(); + assert!(e.contains("no visible art"), "{e}"); +} + +/// A placed image with a Vector Halftone effect is measured when the effect makes dots, and left +/// out when it would take more cells than the effect makes. +#[test] +fn a_plot_of_the_arts_bounds_measures_images_by_their_halftone_dots() { + let mut s = two_boards(); + let plot = |s: &mut Session| s.execute("document.export", &json!({"format": "hpgl", "useArtboards": false})).map(|v| bytes(&v)); + let printing = s.doc().unwrap().doc.layers[0].id; + s.execute("layer.new", &json!({})).unwrap(); + let mut png = vec![]; + image::DynamicImage::new_rgb8(100, 100).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + s.execute("file.place", &json!({"name": "dots.png", "dataBase64": b64(&png), "at": [300, 300]})).unwrap(); + s.execute("layer.setProps", &json!({"id": printing, "visible": false})).unwrap(); + + // At 300 lines per inch a 100 pt image takes more cells than the effect makes. + s.execute("effect.apply", &json!({"effect": "addon.color.halftone", "params": {"frequency": 300}})).unwrap(); + let e = plot(&mut s).unwrap_err().to_string(); + assert!(e.contains("no visible art"), "{e}"); + + s.execute("effect.apply", &json!({"effect": "addon.color.halftone", "params": {"frequency": 20}})).unwrap(); + let out = String::from_utf8(plot(&mut s).unwrap()).unwrap(); + assert!(out.contains("PD"), "{out}"); +} + #[test] fn export_options_are_checked() { let mut s = two_boards(); diff --git a/crates/engine/src/cmd/fileio/tests_pdf.rs b/crates/engine/src/cmd/fileio/tests_pdf.rs index f57e02fc2d..f5b1b8e34d 100644 --- a/crates/engine/src/cmd/fileio/tests_pdf.rs +++ b/crates/engine/src/cmd/fileio/tests_pdf.rs @@ -103,6 +103,48 @@ fn use_artboards_false_writes_one_page_of_the_arts_bounds() { } } +/// A page of the art's bounds is measured on the layers the PDF draws: a non-printing layer that +/// the PDF leaves out doesn't make it larger, unless `includeNonPrinting` or `createLayers` keeps +/// the layer. A `.ai` file of the art's bounds, which keeps layers by default, measures it unless +/// `createLayers` is off. A document whose only visible art doesn't print is refused. +#[test] +fn a_page_of_the_arts_bounds_leaves_out_non_printing_layers() { + let mut s = session(1); + let printing = s.doc().unwrap().doc.layers[0].id; + let notes = s.execute("layer.new", &json!({})).unwrap()["id"].clone(); + s.execute("layer.setProps", &json!({"id": notes, "printable": false})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": 20, "height": 20})).unwrap(); + let size = |bytes: &[u8]| vectorcraft_pdf::import(bytes).unwrap().artboards[0].rect.size(); + let printed = size(&b64(&export(&mut s, json!({"useArtboards": false})))); + assert!(printed.width < 50.0 && printed.height < 40.0, "{printed:?}"); + let through_export = s.execute("document.export", &as_export(&json!({"useArtboards": false}))).unwrap(); + assert_eq!(size(&b64(&through_export)), printed); + let ai = |s: &mut Session, extra: Value| { + let mut p = json!({"format": "ai", "useArtboards": false}); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + size(&b64(&s.execute("document.export", &p).unwrap_or_else(|e| panic!("{p}: {e}")))) + }; + assert_eq!(ai(&mut s, json!({"createLayers": false})), printed); + let kept = [ + size(&b64(&export(&mut s, json!({"useArtboards": false, "includeNonPrinting": true})))), + size(&b64(&export(&mut s, json!({"useArtboards": false, "createLayers": true})))), + ai(&mut s, json!({})), + ]; + for all in kept { + assert!(all.width > 200.0 && all.height > 200.0, "{all:?}"); + } + + // Only the non-printing layer shows: the PDF would draw nothing. + s.execute("layer.setProps", &json!({"id": printing, "visible": false})).unwrap(); + for p in [json!({"useArtboards": false}), json!({"useArtboards": false, "includeNonPrinting": false})] { + let e = s.execute("document.exportPdf", &p).unwrap_err().to_string(); + assert!(e.contains("no visible art"), "{p}: {e}"); + } + let e = s.execute("document.export", &json!({"format": "ai", "useArtboards": false, "createLayers": false})).unwrap_err().to_string(); + assert!(e.contains("no visible art"), "{e}"); + assert!(size(&b64(&export(&mut s, json!({"useArtboards": false, "includeNonPrinting": true})))).width < 25.0); +} + /// In a PDF without a standard, the warning for a page longer than 14,400 pt written with a /// `UserUnit` above 1 names "Write pages longer than 200 in at full size in points": at PDF 1.5 /// (written as 1.6) and later, through `document.exportPdf`, `document.export`, a page of the diff --git a/crates/engine/src/cmd/fileio/tests_svg.rs b/crates/engine/src/cmd/fileio/tests_svg.rs index eb3989597f..121cc0b279 100644 --- a/crates/engine/src/cmd/fileio/tests_svg.rs +++ b/crates/engine/src/cmd/fileio/tests_svg.rs @@ -352,20 +352,8 @@ fn svg_darkness_preserves_source_model_and_gradient_appearance() { #[test] fn svg_darkness_uses_rendered_shadow_in_non_srgb_working_space() { - const CHILD: &str = "VECTORCRAFT_TEST_SHADOW_RGB_PROFILE"; - if std::env::var_os(CHILD).is_none() { - // Color settings are process-wide: exercise this profile in a separate test process. - let output = std::process::Command::new(std::env::current_exe().unwrap()) - .args(["--exact", "cmd::fileio::tests_svg::svg_darkness_uses_rendered_shadow_in_non_srgb_working_space", "--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 color profile test failed:\n{stdout}\n{}", - String::from_utf8_lossy(&output.stderr), - ); + // Color settings are process-wide: exercise this profile in a separate test process. + if !crate::tests::in_own_process("cmd::fileio::tests_svg::svg_darkness_uses_rendered_shadow_in_non_srgb_working_space") { return; } use vectorcraft_color::{Color, Paint, cms}; diff --git a/crates/engine/src/cmd/flatten/analysis.rs b/crates/engine/src/cmd/flatten/analysis.rs index 0adb06132a..37adcf438d 100644 --- a/crates/engine/src/cmd/flatten/analysis.rs +++ b/crates/engine/src/cmd/flatten/analysis.rs @@ -184,15 +184,17 @@ impl Sets { /// boxes it overlaps, not every open one (many objects stacked in a column, sharing their /// horizontal extent, would otherwise compare every pair). An open box inside a later box of /// its group, ending no further right, is closed early, and a box inside an open box of its group, -/// ending no further right, isn't opened: whatever overlaps it overlaps that box. Fails only when -/// cancelled ([`vectorcraft_doc::cancel`]). +/// ending no further right, isn't opened: whatever overlaps it overlaps that box. An open box that +/// a later box of its group overlaps, starting lower and ending no further right or lower, keeps +/// only its part above the later box's top, so boxes staggered right and down each meet only the +/// one before. Fails only when cancelled ([`vectorcraft_doc::cancel`]). pub(super) fn overlapping(bounds: &[Option]) -> Result>, Cancelled> { Ok(sweep(bounds, None)?.groups()) } /// [`overlapping`]'s sweep. With `see_through`, two boxes are joined only when one of them is -/// see-through, and an open box is closed early, or a box isn't opened, only inside a see-through -/// box. The open +/// see-through, an open box is closed early, or a box isn't opened, only inside a see-through box, +/// and an open box is cut short only by a see-through box that is opened. The open /// see-through boxes and the open boxes without transparency are then in trees of their own, and /// a box without transparency meets only the see-through ones. fn sweep(bounds: &[Option], see_through: Option<&[bool]>) -> Result { @@ -285,12 +287,20 @@ fn sweep(bounds: &[Option], see_through: Option<&[bool]>) -> Result], joins: impl Fn(usize, usize) -> bool) -> Vec> { + let bounds: Vec> = bounds.iter().map(|b| b.filter(finite)).collect(); let n = bounds.len(); let mut group: Vec = (0..n).collect(); let hit = |a: &Rect, b: &Rect| a.x0 <= b.x1 && b.x0 <= a.x1 && a.y0 <= b.y1 && b.y0 <= a.y1; @@ -731,9 +743,9 @@ mod tests { ]; let see = [false, true, true, false]; let mut sets = sweep(&bounds, Some(&see)).unwrap(); - // The second box meets the first; the third meets the second; the fourth meets the second - // and the third. - assert_eq!(sets.meets, 4); + // The second box meets the first; the third meets the second, which keeps only its part + // above the third's top; the fourth meets the third. + assert_eq!(sets.meets, 3); assert_eq!(sets.groups(), vec![vec![0, 1, 2, 3]]); // Opaque boxes alone meet nothing. let mut sets = sweep(&bounds, Some(&[false; 4])).unwrap(); @@ -741,6 +753,86 @@ mod tests { assert_eq!(sets.groups().len(), 4); } + /// `n` boxes of one size, each a little right of and below the one before, all overlapping and + /// none inside another. + fn staggered(n: usize) -> Vec> { + let w = 2.0 * n as f64; + (0..n).map(|i| Some(Rect::new(i as f64, i as f64, w + i as f64, w + i as f64))).collect() + } + + /// Each box of a stagger right and down meets only the box before it, which keeps only its + /// part above the new box's top, not every box still open. + #[test] + fn staggered_boxes_meet_only_the_box_before() { + let n = 512; + let bounds = staggered(n); + let mut sets = sweep(&bounds, None).unwrap(); + assert_eq!(sets.meets, n - 1); + assert_eq!(sets.groups(), vec![(0..n).collect::>()]); + // See-through boxes do the same with transparency. + let mut sets = sweep(&bounds, Some(&vec![true; n])).unwrap(); + assert_eq!(sets.meets, n - 1); + assert_eq!(sets.groups(), vec![(0..n).collect::>()]); + } + + /// An open box keeps the part a later box would meet without meeting the box that cut it short: + /// a part lower than that box, a part further right, or any part when that box is opaque. + #[test] + fn a_box_is_cut_short_only_where_the_later_box_covers_it() { + let k = Rect::new(5.0, 5.0, 15.0, 15.0); + // Lower than `k`: the last box overlaps only the bottom of the first. + let lower = [Some(Rect::new(0.0, 0.0, 10.0, 20.0)), Some(k), Some(Rect::new(8.0, 17.0, 9.0, 25.0))]; + assert_eq!(overlapping(&lower).unwrap(), vec![vec![0, 1, 2]]); + // Further right than `k`: the last box starts right of it and overlaps the first. + let right = [Some(Rect::new(0.0, 0.0, 20.0, 10.0)), Some(k), Some(Rect::new(17.0, 7.0, 25.0, 9.0))]; + assert_eq!(overlapping(&right).unwrap(), vec![vec![0, 1, 2]]); + // An opaque `k` doesn't join the opaque last box, which joins the see-through first one. + let opaque = [Some(Rect::new(0.0, 0.0, 10.0, 10.0)), Some(k), Some(Rect::new(6.0, 8.0, 7.0, 20.0))]; + let mut sets = sweep(&opaque, Some(&[true, false, false])).unwrap(); + assert_eq!(sets.groups(), vec![vec![0, 1, 2]]); + // A see-through `k` held by a see-through box around it isn't opened and cuts nothing short. + let held = [Some(Rect::new(0.0, 2.0, 30.0, 30.0)), Some(Rect::new(1.0, 0.0, 10.0, 10.0)), Some(k), Some(Rect::new(6.0, 8.0, 7.0, 20.0))]; + let see = [true, false, true, false]; + let mut sets = sweep(&held, Some(&see)).unwrap(); + assert_eq!(sets.groups(), vec![vec![0, 1, 2, 3]]); + assert_eq!(sets.groups(), every_pair_joining(&held, |i, j| see[i] || see[j])); + } + + /// Staggers in all four directions, of mixed sizes (empty ones included) with gaps and shared + /// edges, in either order, with signed zeros and boxes that aren't finite, some see-through, + /// group as comparing every pair groups them. + #[test] + fn staggered_boxes_group_as_comparing_every_pair() { + let mut seed = 0x3c6e_f372_fe94_f82bu64; + let mut next = |m: f64| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed % 1000) as f64 / 1000.0 * m + }; + for round in 0..48 { + let n = 8 + round * 2; + let (sx, sy) = (if round % 2 == 0 { 1.0 } else { -1.0 }, if round / 2 % 2 == 0 { 1.0 } else { -1.0 }); + let mut bounds: Vec> = (0..n) + .map(|i| { + let step = next(4.0).floor(); + let (x, y) = (sx * (i as f64 * 2.0 + step), sy * (i as f64 * 2.0 + next(4.0).floor())); + let (w, h) = (next(8.0).floor() * 2.0, next(8.0).floor() * 2.0); + Some(Rect::new(x, y, x + w, y + h)) + }) + .collect(); + bounds[0] = Some(Rect::new(-0.0, -0.0, 0.0, 6.0)); + bounds[n / 2] = Some(Rect::new(0.0, sy * 6.0, f64::INFINITY, sy * 6.0 + 4.0)); + if round / 4 % 2 == 1 { + bounds.reverse(); + } + assert_eq!(overlapping(&bounds).unwrap(), every_pair(&bounds), "round {round}"); + let see: Vec = (0..n).map(|_| next(1.0) < 0.5).collect(); + let mut sets = sweep(&bounds, Some(&see)).unwrap(); + assert_eq!(sets.groups(), every_pair_joining(&bounds, |i, j| see[i] || see[j]), "round {round}, with transparency"); + } + } + /// An opaque box between a member and its group's top that paints over the member joins, and /// so on along a chain; one under the member stays, but for one within the fringe. #[test] diff --git a/crates/engine/src/cmd/flatten/apply.rs b/crates/engine/src/cmd/flatten/apply.rs index ef8425b362..b159fa7361 100644 --- a/crates/engine/src/cmd/flatten/apply.rs +++ b/crates/engine/src/cmd/flatten/apply.rs @@ -797,22 +797,47 @@ fn place_of(d: &Document, roots: &[NodeId]) -> Option { } /// The ruler guides of each of `roots` that is a sublayer (in its sublayers too), with the layer -/// that holds it, in order. Other objects hold none. +/// that holds it, in order. Other objects hold none. Each root, and each child of it and of its +/// sublayers, is looked at once. fn held_guides(d: &Document, roots: impl IntoIterator) -> Vec<(NodeId, Node)> { let mut out = vec![]; for id in roots { let (Some(n), Some(parent)) = (d.node(id), d.parent_of(id)) else { continue }; - if n.holds_ruler_guides() { - n.walk(&mut |c| { - if c.is_ruler_guide() { - out.push((parent, c.clone())); - } - }); + guide_seen(n); + if n.is_layer() { + guides_of(n, parent, &mut out); } } out } +/// Push each ruler guide of `layer` and of its sublayers onto `out` in paint order, with `parent`. +fn guides_of(layer: &Node, parent: NodeId, out: &mut Vec<(NodeId, Node)>) { + for c in layer.children().into_iter().flatten() { + guide_seen(c); + if c.is_ruler_guide() { + out.push((parent, Node::clone(c))); + } else if c.is_layer() { + guides_of(c, parent, out); + } + } +} + +#[cfg(test)] +thread_local! { + /// The nodes that [`held_guides`] has looked at on this thread, in order. + static GUIDES_SEEN: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; +} + +/// Note that [`held_guides`] looked at `n`. +#[cfg(test)] +fn guide_seen(n: &Node) { + GUIDES_SEEN.with(|s| s.borrow_mut().push(n.id)); +} + +#[cfg(not(test))] +fn guide_seen(_: &Node) {} + /// An image of `r` (in a clip group when it is clipped). fn raster_node(d: &mut Document, r: Raster) -> Node { let key = unique_key(d, "flattened"); @@ -922,6 +947,53 @@ mod tests { assert_eq!(flat.children(Some(layer)).and_then(|c| c.last()).map(|c| c.id), Some(g)); } + /// The guides of a sublayer and of its sublayers are gathered in paint order with the layer + /// that holds it, looking at the sublayer and each child of it and of its sublayers once. + /// Other roots give none. + #[test] + fn held_guides_look_at_each_node_once() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let layer = s.doc().unwrap().doc.layers[0].id; + let sublayer = + |s: &mut Session, parent: NodeId| NodeId(s.execute("layer.newSublayer", &json!({"parent": parent.0})).unwrap()["id"].as_u64().unwrap()); + let rect = |s: &mut Session, on: NodeId| { + s.execute("layer.setCurrent", &json!({"id": on.0})).unwrap(); + NodeId(s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap()) + }; + let sub = sublayer(&mut s, layer); + let deep = sublayer(&mut s, sub); + let empty = sublayer(&mut s, layer); + let (a, b, c) = (rect(&mut s, sub), rect(&mut s, deep), rect(&mut s, empty)); + let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let mut guide = |on: NodeId, pos: f64| { + let g = Node::new(d.alloc_id(), NodeKind::RulerGuide { vertical: true, pos, artboard: None }); + d.insert(Some(on), usize::MAX, g).unwrap() + }; + let (g1, g2, g3) = (guide(sub, 1.0), guide(deep, 2.0), guide(sub, 3.0)); + let doc = &s.doc().unwrap().doc; + let ids = |n: &Node| { + let mut v = vec![]; + n.walk(&mut |c| v.push(c.id)); + v + }; + assert_eq!(ids(doc.node(sub).unwrap()), vec![sub, deep, b, g2, a, g1, g3]); + let run = |roots: &[NodeId]| { + GUIDES_SEEN.with(|v| v.borrow_mut().clear()); + let got: Vec<_> = held_guides(doc, roots.iter().copied()).into_iter().map(|(p, g)| (p, g.id)).collect(); + (got, GUIDES_SEEN.with(|v| v.take())) + }; + // Every node of the sublayer is looked at once, and the guides keep their paint order. + assert_eq!(run(&[sub]), (vec![(layer, g2), (layer, g1), (layer, g3)], vec![sub, deep, b, g2, a, g1, g3])); + // A sublayer that holds none gives none; a path holds none; a missing root and a top-level + // layer, which has no parent, are skipped. + assert_eq!(run(&[empty]), (vec![], vec![empty, c])); + assert_eq!(run(&[a]), (vec![], vec![a])); + assert_eq!(run(&[NodeId(u64::MAX), layer]), (vec![], vec![])); + // A deeper sublayer gives its guides to the sublayer that holds it. + assert_eq!(run(&[deep, deep]).0, vec![(sub, g2), (sub, g2)]); + } + /// In a file without transparency with Clip Complex Regions on, art under a group's opaque /// image within one of its pixels joins the group, also where a long image is made at a lower /// resolution and its pixels are wider than at the preset's. diff --git a/crates/engine/src/cmd/globaledit.rs b/crates/engine/src/cmd/globaledit.rs index f454d7133b..879767d8be 100644 --- a/crates/engine/src/cmd/globaledit.rs +++ b/crates/engine/src/cmd/globaledit.rs @@ -6,20 +6,34 @@ //! (), in our words: //! //! - With one object selected, Start Global Edit finds the objects that repeat its shape: the -//! same outline, wherever it lies and at whatever size. Two options narrow the match: Appearance -//! (the same fill and stroke too) and Size (the same width and height too). The search covers -//! every artboard and the canvas around them by default; it can be limited to a range of -//! artboards (`1, 3-5`) and can leave out the objects that lie on no artboard. Images, type, -//! masks, linked files and selections of more than one object are not supported. +//! same outline, wherever it lies, at whatever size and at whatever angle. Two options narrow +//! the match: Appearance (the same fill and stroke too) and Size (the same width and height +//! too). The search covers every artboard and the canvas around them by default; it can be +//! limited to a range of artboards (`1, 3-5`) and can leave out the objects that lie on no +//! artboard. Images, type, masks, linked files and selections of more than one object are not +//! supported. //! - The help page "Edit groups with similar objects" //! (): //! with a group selected, Start Global Edit finds the groups like it, and an edit made to an //! object inside one of them is made to the matching object in each of the others. Here a group //! is like another when it holds as many objects, in the same order, each like the one at its //! place (paths, compound paths, symbol instances and groups of them, clipping paths included), -//! and they lie the same way relative to each other: the group as a whole is moved or scaled. -//! With Appearance on, each of those objects must have the same fill and stroke too; with Size, -//! the groups the same width and height. +//! and they lie the same way relative to each other: the group as a whole is moved, scaled or +//! rotated. With Appearance on, each of those objects must have the same fill and stroke too; +//! with Size, the groups the same width and height. +//! - The how-to "Design a modern geometric logo" +//! () makes rotated +//! copies of a group of shapes around a point, then starts Global Edit on one object and edits +//! every copy of it at once. Here a rotated copy is found as a moved or scaled one is, and an +//! edit reaches it turned by its own angle: an anchor moved to the right on the selected object +//! moves downward on a copy turned a quarter turn clockwise. The rules below for rotated copies +//! are VectorCraft's own. The angle is the one that lays each anchor and handle of the selected +//! object on the copy's of the same order, so a square whose anchors were turned a quarter turn +//! is a copy turned a quarter turn. A copy is the same shape when, laid so, every anchor and +//! handle lies within a millionth of the larger side of the copy's box of its own ([`SAME`]). +//! A reflected copy is another shape. With Size, a rotated copy has the same size when it is the +//! selected object rotated without scaling: its width and height are compared as they were +//! before the rotation. //! - Selecting one of the repeated objects with the Selection tool highlights the similar objects //! at once, before Global Edit starts. Here they are the objects Start Global Edit would take //! with the current Global Edit Options ([`similar`]). @@ -29,15 +43,16 @@ //! //! Here the found objects ([`GlobalEdit::members`]) stay highlighted while the selection keeps the //! object that was selected, so that the Transform panel and the bounding box measure that object -//! and not the whole set. Each member keeps the transform (a move and a uniform scale) that maps -//! the first object's outline onto its own. After every edit ([`propagate`], run inside -//! [`Session::edit`], so the whole change is one undo step), the first selected member the edit -//! changed is the model: what changed about it is given to every other member, and nothing else, -//! so members found by shape alone keep their own fills and strokes where the edit didn't touch -//! them: +//! and not the whole set. Each member keeps the transform (a move, a uniform scale and, for a +//! rotated copy, a turn) that maps the first object's outline onto its own. After every edit +//! ([`propagate`], run inside [`Session::edit`], so the whole change is one undo step), the first +//! selected member the edit changed is the model: what changed about it is given to every other +//! member, and nothing else, so members found by shape alone keep their own fills and strokes +//! where the edit didn't touch them: //! //! - its outline (and anchors), placed through that transform, so in proportion to each member's -//! size. Only geometry is placed so: no stroke weight is scaled to a member's size; +//! size and turned by its angle. Only geometry is placed so: no stroke weight is scaled to a +//! member's size; //! - its opacity, blending, knockout and the object's effects, each when it changed; //! - of its fills and strokes, each setting that changed (paint, weight, opacity, blending, //! effects, caps, dashes, arrowheads …), as it is: it goes to the member's fill or stroke of the @@ -74,12 +89,12 @@ //! and later edits leave it as it is. //! The object the edit started from can't be left out (a Shift-click on it selects it or //! deselects it as before), Global Edit ends when fewer than two members are left, and leaving -//! one out is not an undo step. Rotated copies are not covered. +//! one out is not an undo step. use serde::Serialize; use serde_json::{Value, json}; use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeId, NodeKind, Scaling, Shared, StrokeLayer}; -use vectorcraft_geom::{Affine, BezPath, PathData, Point, Rect, Shape}; +use vectorcraft_geom::{Affine, BezPath, PathData, Point, Rect, Shape, Vec2}; use super::wand::{fill_of, stroke_of}; use super::{CommandSpec, Result, Session, bad, bool_or, checked_id, cmd, has_doc}; @@ -98,7 +113,7 @@ pub fn specs() -> Vec { "Start Global Edit", ["Select"], None, - "{appearance?: bool, size?: bool, artboards?: \"all\" | range such as \"1, 3-5\", includeCanvas?: bool} (each defaults to the Global Edit Options) while Global Edit is off: start it on the one selected object (a path, compound path, symbol instance or group of them), with the objects of the same shape (for a group: the groups holding objects like its own, at the same places) (and, with `appearance`, the same fill and stroke; with `size`, the same width and height) on the artboards given (and, with `includeCanvas`, off every artboard), at most 10000 → {active: true, count, ids}; while on: stop it (Escape does the same) → {active: false}", + "{appearance?: bool, size?: bool, artboards?: \"all\" | range such as \"1, 3-5\", includeCanvas?: bool} (each defaults to the Global Edit Options) while Global Edit is off: start it on the one selected object (a path, compound path, symbol instance or group of them), with the objects of the same shape, moved, scaled or rotated copies of it and not reflected ones (for a group: the groups holding objects like its own, at the same places) (and, with `appearance`, the same fill and stroke; with `size`, the same width and height, for a rotated copy before its rotation) on the artboards given (and, with `includeCanvas`, off every artboard), at most 10000 → {active: true, count, ids}; while on: stop it (Escape does the same) → {active: false}", can_toggle, toggle ), @@ -181,7 +196,8 @@ pub type Outlines = Vec<(BezPath, [u8; 3])>; #[derive(Clone, Debug, PartialEq)] pub struct GlobalEdit { /// The objects edited together, the one selected at the start first, each with the transform - /// (a move and a uniform scale) that maps that first object's outline onto its own. + /// (a move, a uniform scale and, for a turned copy, a turn) that maps that first object's + /// outline onto its own. pub members: Vec<(NodeId, Affine)>, /// [`highlights`] as of a document revision: the canvas asks every frame. outlines: std::cell::RefCell>, @@ -257,14 +273,60 @@ impl Form { } } - fn same(&self, o: &Form) -> bool { - self.tag == o.tag - && self.symbols == o.symbols - && self.points.len() == o.points.len() - && self.points.iter().zip(&o.points).all(|(a, b)| a.distance(*b) < 1e-6) + /// The transform that lays this form's object on `o`'s, point for point in order, and whether + /// it turns the object: a move and a uniform scale when the two lie the same way, otherwise a + /// turn too. `None` when `o` is another shape, a reflected copy included. + fn onto(&self, o: &Form) -> Option<(Affine, bool)> { + if self.tag != o.tag || self.symbols != o.symbols || self.points.len() != o.points.len() { + return None; + } + let near = |xf: Affine| self.points.iter().zip(&o.points).all(|(a, b)| (xf * *a).distance(*b) < SAME); + let back = self.frame.inverse(); + if near(Affine::IDENTITY) { + return Some((o.frame * back, false)); + } + let turn = self.turn_onto(o)?; + near(turn).then(|| (o.frame * turn * back, true)) + } + + /// The turn, uniform scale and move (both forms in their unit boxes) that best lays this + /// form's points on `o`'s in order, by least squares. A turn within [`SQUARE`] of a quarter + /// turn is that quarter turn exactly. + fn turn_onto(&self, o: &Form) -> Option { + let n = self.points.len() as f64; + let middle = |f: &Form| f.points.iter().fold(Vec2::ZERO, |s, p| s + p.to_vec2()) / n; + let (from, to) = (middle(self), middle(o)); + // With the points as complex numbers about their middles, the fit is `Σ conj(p) q / Σ |p|²`. + let (mut re, mut im, mut spread) = (0.0, 0.0, 0.0); + for (a, b) in self.points.iter().zip(&o.points) { + let (p, q) = (a.to_vec2() - from, b.to_vec2() - to); + re += p.dot(q); + im += p.cross(q); + spread += p.hypot2(); + } + let len = re.hypot(im); + let scale = len / spread; + if !(scale.is_finite() && scale > 0.0) { + return None; + } + let (mut cos, mut sin) = (re / len, im / len); + if cos.abs() < SQUARE { + (cos, sin) = (0.0, sin.signum()); + } else if sin.abs() < SQUARE { + (cos, sin) = (cos.signum(), 0.0); + } + let (a, b) = (scale * cos, scale * sin); + Some(Affine::translate(to) * Affine::new([a, b, -b, a, 0.0, 0.0]) * Affine::translate(-from)) } } +/// How far apart two forms' points may lie, each form in its unit box, for the forms to be the +/// same. For a turned copy this bounds the angle too: a copy turned and then changed by more than +/// a millionth of its larger side is another shape. +const SAME: f64 = 1e-6; +/// A turn whose sine or cosine is below this is taken as a whole number of quarter turns. +const SQUARE: f64 = 1e-9; + /// Global Edit supports paths, compound paths, symbol instances and groups of them; not images, /// type, linked files, objects with an opacity mask, clipping paths or guides (the help page lists /// images, text, masks and links as unsupported). @@ -395,8 +457,16 @@ fn matches(s: &Session, o: &Options) -> Result> { } boards.as_ref().is_none_or(|rs| rs.iter().any(|r| on(*r, b))) }; + // A copy that lies the same way has the size of the selected object when their boxes are as + // wide and as high; a turned copy, when the transform that lays the object on it doesn't scale. + let same_size = |n: &Node, xf: Affine, turned: bool| { + if turned { + close(xf.determinant().abs().sqrt(), 1.0) + } else { + matches!((key_size, size(n)), (Some((w, h)), Some((w2, h2))) if close(w, w2) && close(h, h2)) + } + }; let mut out = vec![(*id, Affine::IDENTITY)]; - let back = form.frame.inverse(); super::select::walk_selectable(d, st.isolation, |n| { if n.id == *id || out.len() >= MAX_MEMBERS { return false; @@ -413,12 +483,12 @@ fn matches(s: &Session, o: &Options) -> Result> { }; // The object count first: it turns most objects down before their form is made. if n.children().map(Vec::len) == count - && let Some(f) = Form::of(n).filter(|f| f.same(&form) && supported(n)) - && (!o.size || matches!((key_size, size(n)), (Some((w, h)), Some((w2, h2))) if close(w, w2) && close(h, h2))) + && let Some((xf, turned)) = Form::of(n).and_then(|f| form.onto(&f)).filter(|_| supported(n)) + && (!o.size || same_size(n, xf, turned)) && (!o.appearance || same_look(key, n)) && in_scope(n) { - out.push((n.id, f.frame * back)); + out.push((n.id, xf)); // A group taken is taken whole, as compound paths, symbol instances and the others are. return false; } @@ -464,7 +534,7 @@ fn toggle(s: &mut Session, p: &Value) -> Result { let o = s.global_edit_options.with(p, &s.doc()?.doc, C)?; let members = matches(s, &o)?; if members.len() < 2 { - return Err(bad(C, "no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again")); + return Err(bad(C, "no similar objects found (reflected copies are not matched); change the Global Edit Options and try again")); } let ids: Vec = members.iter().map(|(id, _)| id.0).collect(); let st = s.doc_mut()?; @@ -795,7 +865,8 @@ pub(crate) fn propagate(before: &Document, d: &mut Document, ge: &GlobalEdit, se } /// Store on their graphs what the members `edited`, and the objects in them, took on the paths directly in a graph -/// series, for the graph's next redraw. The edited member is left to the edit's own command. +/// series, and the transparency a series group among them took, for the graph's next redraw. The edited member is left to +/// the edit's own command. fn keep_series_changes(before: &Document, d: &mut Document, edited: &[NodeId]) { let mut taken = vec![]; for id in edited { @@ -804,6 +875,8 @@ fn keep_series_changes(before: &Document, d: &mut Document, edited: &[NodeId]) { } } super::appearance::capture_series_changes(before, d, &taken); + let groups = super::graph::series_groups_among(d, &taken); + super::graph::capture_series_object_opacity(d, &groups); } /// The outlines of the members of the active document's Global Edit that are not selected, hold @@ -1027,6 +1100,38 @@ mod tests { assert!(taken > 100 && checked - taken > 100 && asked > 200, "{taken} of {checked}, {asked} selected"); } + #[test] + fn a_form_is_laid_on_a_turned_copy_and_on_no_reflected_or_unmeasurable_one() { + let mut d = Document::new(800.0, 600.0); + let mut path = |points: &[(f64, f64)]| { + let anchors = points.iter().map(|(x, y)| Anchor::corner(Point::new(*x, *y))).collect(); + Node::path(d.alloc_id(), PathData::new(vec![SubPath::new(anchors, true)]), Appearance::default()) + }; + let form = Form::of(&path(&[(0.0, 0.0), (30.0, 0.0), (30.0, 70.0)])).unwrap(); + let mut onto = |points: &[(f64, f64)]| Form::of(&path(points)).and_then(|f| form.onto(&f)); + let near = |xf: Affine, want: [f64; 6]| xf.as_coeffs().iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-9); + // The same way at twice the size: a move and a scale, no turn. + let (xf, turned) = onto(&[(100.0, 0.0), (160.0, 0.0), (160.0, 140.0)]).unwrap(); + assert!(!turned && near(xf, [2.0, 0.0, 0.0, 2.0, 100.0, 0.0]), "{xf:?}"); + // A quarter turn, (x, y) → (−y, x), moved by (100, 0); and a turn by 30° at half the size. + let (xf, turned) = onto(&[(100.0, 0.0), (100.0, 30.0), (30.0, 30.0)]).unwrap(); + assert!(turned && near(xf, [0.0, 1.0, -1.0, 0.0, 100.0, 0.0]), "{xf:?}"); + let by = Affine::rotate(30f64.to_radians()) * Affine::scale(0.5); + let at = |x: f64, y: f64| { + let p = by * Point::new(x, y); + (p.x, p.y) + }; + let (xf, turned) = onto(&[at(0.0, 0.0), at(30.0, 0.0), at(30.0, 70.0)]).unwrap(); + assert!(turned && near(xf, by.as_coeffs()), "{xf:?}"); + // A reflected copy, a copy with an anchor a thousandth of its size away, and points that + // are not numbers or not finite. + assert!(onto(&[(0.0, 0.0), (-30.0, 0.0), (-30.0, 70.0)]).is_none()); + assert!(onto(&[at(0.0, 0.0), at(30.0, 0.0), at(30.0, 70.07)]).is_none()); + assert!(onto(&[(f64::NAN, 0.0), (30.0, 0.0), (30.0, 70.0)]).is_none()); + assert!(onto(&[(0.0, 0.0), (f64::INFINITY, 0.0), (30.0, 70.0)]).is_none()); + assert!(onto(&[(0.0, 0.0), (30.0, 0.0)]).is_none(), "another count of anchors"); + } + #[test] fn support_of_empty_degenerate_and_deep_objects_is_decided_as_building_the_form_decides() { let mut d = Document::new(800.0, 600.0); diff --git a/crates/engine/src/cmd/graph.rs b/crates/engine/src/cmd/graph.rs index da23bd4f04..06557e6f59 100644 --- a/crates/engine/src/cmd/graph.rs +++ b/crates/engine/src/cmd/graph.rs @@ -37,9 +37,10 @@ use axis::{nice_axis, tick_values}; #[cfg(test)] use columns::{fill_totals, total_text}; pub use commands::specs; -pub(crate) use data::apply_csv; +pub(crate) use data::{apply_csv, parse_csv}; #[cfg(test)] -use data::{fmt_value, parse_csv, to_csv}; +use data::{fmt_value, to_csv}; +pub(crate) use edit::{graphs_holding, keep_placed}; #[cfg(test)] use generate::generate; #[cfg(test)] @@ -47,7 +48,7 @@ use series::default_series_color; pub(crate) use series::{ LabelTextChange, capture_label_anti_alias, capture_label_changes, capture_label_object_opacity, capture_label_paragraphs, capture_label_rows, capture_label_styles, capture_label_text, capture_series_object_opacity, capture_series_opacity, capture_series_top_paints, is_design_art, - label_object_opacity_differs, labels_in, paint_targets, series_group_marks, series_group_marks_where, series_marks_in, + label_object_opacity_differs, labels_in, paint_targets, series_group_marks, series_group_marks_where, series_groups_among, series_marks_in, series_object_opacity_differs, shown_paint, }; diff --git a/crates/engine/src/cmd/graph/data.rs b/crates/engine/src/cmd/graph/data.rs index f7f672325e..68a83fd80a 100644 --- a/crates/engine/src/cmd/graph/data.rs +++ b/crates/engine/src/cmd/graph/data.rs @@ -42,7 +42,7 @@ fn cell(c: &str) -> Cell { } } -pub(super) fn parse_csv(csv: &str) -> (Vec, Vec, Vec>>) { +pub(crate) fn parse_csv(csv: &str) -> (Vec, Vec, Vec>>) { let csv = csv.strip_prefix('\u{feff}').unwrap_or(csv); // Records end at line breaks outside quotes; a record is tab-separated if it has a tab outside quotes. let rows: Vec> = split_unquoted(csv, '\n') diff --git a/crates/engine/src/cmd/graph/edit.rs b/crates/engine/src/cmd/graph/edit.rs index c7f6d52ea8..77ce7a7b2a 100644 --- a/crates/engine/src/cmd/graph/edit.rs +++ b/crates/engine/src/cmd/graph/edit.rs @@ -1,3 +1,5 @@ +use vectorcraft_doc::graph::graph_art_without_type as art_bounds; + use super::axis::{MAX_TICK_MARKS, count_given, one_line}; use super::data::apply_data; use super::generate::{children_bounds, generate}; @@ -17,11 +19,80 @@ fn bound_param(p: &Value, key: &str, cmd: &str) -> Result>> { } } +/// The bounds a redraw of graph `n` measures a move or scale on, as kept at the last generation and as they are now: +/// those of its art without type ([`GraphSpec::placed_art`]), or those of all its art when the graph keeps no such +/// bounds with a width and a height. `None` when the art measured has no width or no height now, or the graph keeps +/// bounds of its art without type and has no such art now. +fn measured(n: &Node) -> Option<(Rect, Rect)> { + let kept = n.extras().graph.as_deref()?; + let c = n.children()?; + let solid = |r: &Rect| r.width() > 1e-9 && r.height() > 1e-9; + match kept.placed_art.filter(solid) { + Some(placed) => art_bounds(c).filter(solid).map(|now| (placed, now)), + None => kept.placed.zip(children_bounds(c).filter(solid)), + } +} + +/// `r` carried by the change from bounds `from` to bounds `to`: each edge stays at the same place relative to them. +/// `None` when `from` has no width or no height. +fn carried(r: Rect, from: Rect, to: Rect) -> Option { + if from.width() <= 1e-9 || from.height() <= 1e-9 { + return None; + } + let (sx, sy) = (to.width() / from.width(), to.height() / from.height()); + Some(Rect::new(to.x0 + (r.x0 - from.x0) * sx, to.y0 + (r.y0 - from.y0) * sy, to.x0 + (r.x1 - from.x0) * sx, to.y0 + (r.y1 - from.y0) * sy)) +} + +/// The graphs holding objects `ids`, that are among them or that are inside them, each with the bounds of its art +/// without type and of all its art. Give them to [`keep_placed`] after an edit that changes a graph's art without +/// moving the graph. +pub(crate) fn graphs_holding(d: &Document, ids: &[NodeId]) -> Vec<(NodeId, Option, Option)> { + let is_graph = |n: &Node| n.extras().graph.is_some(); + let mut found: Vec = vec![]; + for id in ids { + let Some(chain) = d.ancestry(*id) else { continue }; + found.extend(chain.iter().rev().copied().find(|a| d.node(*a).is_some_and(is_graph))); + if let Some(n) = d.node(*id) { + n.walk(&mut |c| { + if is_graph(c) { + found.push(c.id); + } + }); + } + } + let mut out: Vec<(NodeId, Option, Option)> = vec![]; + for gid in found { + if out.iter().any(|(o, ..)| *o == gid) { + continue; + } + let children = d.node(gid).and_then(Node::children); + out.push((gid, children.and_then(|c| art_bounds(c)), children.and_then(|c| children_bounds(c)))); + } + out +} + +/// After an edit that changed the art of `graphs` (from [`graphs_holding`]) without moving them, set the bounds each +/// keeps so that its next redraw measures the same move or scale as it would have before the edit. +pub(crate) fn keep_placed(d: &mut Document, graphs: &[(NodeId, Option, Option)]) { + for &(gid, art_was, whole_was) in graphs { + let Some(n) = d.node(gid) else { continue }; + let children = n.children(); + let (art_now, whole_now) = (children.and_then(|c| art_bounds(c)), children.and_then(|c| children_bounds(c))); + let Some(spec) = d.node_mut(gid).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue }; + if let (Some(placed), Some(was), Some(now)) = (spec.placed_art, art_was, art_now) { + spec.placed_art = carried(now, was, placed).or(spec.placed_art); + } + if let (Some(placed), Some(was), Some(now)) = (spec.placed, whole_was, whole_now) { + spec.placed = carried(now, was, placed).or(spec.placed); + } + } +} + /// Regenerate graph `id` from `spec` (adjusting the plot rect for any move/scale since the last -/// generation, which is recorded in the spec's `placed` bounds). +/// generation, which is recorded in the spec's `placed_art` bounds, or `placed` in graphs saved without them). pub(super) fn regenerate(d: &mut Document, id: NodeId, mut spec: GraphSpec) -> Result<()> { let n = d.node(id).ok_or(EngineError::NoNode(id))?; - if let (Some(placed), Some(now)) = (n.extras().graph.as_ref().and_then(|g| g.placed), n.children().and_then(|c| children_bounds(c))) + if let Some((placed, now)) = measured(n) && placed.width() > 1e-9 && placed.height() > 1e-9 && (placed.x0 - now.x0).abs() + (placed.y0 - now.y0).abs() + (placed.x1 - now.x1).abs() + (placed.y1 - now.y1).abs() > 1e-6 @@ -33,6 +104,7 @@ pub(super) fn regenerate(d: &mut Document, id: NodeId, mut spec: GraphSpec) -> R } let children = generate(d, &spec); spec.placed = children_bounds(&children); + spec.placed_art = art_bounds(&children); let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?; if let Some(ch) = n.children_mut() { *ch = children; diff --git a/crates/engine/src/cmd/graph/generate.rs b/crates/engine/src/cmd/graph/generate.rs index fe8ffb98f8..5fadcb8768 100644 --- a/crates/engine/src/cmd/graph/generate.rs +++ b/crates/engine/src/cmd/graph/generate.rs @@ -6,7 +6,7 @@ use super::labels::{ recolour_text, runs, shadow_of, }; use super::markers::{MARKER_BUDGET, marker_cost, marker_designs}; -use super::series::{picks_legend_fill, series_marks, with_series_gradients, with_series_opacity}; +use super::series::{picks_legend_fill, series_marks, with_series_gradients, with_series_group_opacity, with_series_opacity}; use super::{ Arc, BezPath, Color, Document, GraphKind, GraphSpec, Justify, Node, NodeKind, Paint, PathData, Point, Rect, TickLength, ValueAxisSide, shapes, }; @@ -1005,7 +1005,7 @@ impl<'a> Plot<'a> { } } let name = g.series.get(s).cloned().filter(|n| !n.is_empty()).unwrap_or_else(|| format!("Series {}", s + 1)); - let grp = self.b.series(&name, s, with_series_opacity(g, s, with_series_gradients(g, s, items))); + let grp = with_series_group_opacity(g, s, self.b.series(&name, s, with_series_opacity(g, s, with_series_gradients(g, s, items)))); self.b.out.push(grp); } self.b.out.append(&mut self.on_top); diff --git a/crates/engine/src/cmd/graph/labels.rs b/crates/engine/src/cmd/graph/labels.rs index 290e099500..8e56ad8ae6 100644 --- a/crates/engine/src/cmd/graph/labels.rs +++ b/crates/engine/src/cmd/graph/labels.rs @@ -149,20 +149,22 @@ impl Gen<'_> { refresh_bounds(&mut t); t } - /// A category or series label: a `|` in it starts a new line (Add graph labels). `middle`: the lines are centred - /// on `at` (labels beside an axis or in a wedge) instead of running down from it. + /// A category or series label: a `|` in it starts a new line (Add graph labels), as does a line break a quoted CSV + /// cell keeps. `middle`: the lines are centred on `at` (labels beside an axis or in a wedge) instead of running down + /// from it. pub(super) fn label(&mut self, role: Role, at: Point, s: &str, justify: Justify, middle: bool) -> Arc { - let lines = s.split('|').count(); + let text = s.replace('|', "\n"); + let lines = text.split('\n').count(); // Default leading puts the first and last baselines this far above and below `at`. let half = (lines - 1) as f64 * label_size(self.styles, role) * 1.2 / 2.0; let start = if middle { Point::new(at.x, at.y - half) } else { at }; - let mut t = self.text_object(role, start, &s.replace('|', "\n"), justify); + let mut t = self.text_object(role, start, &text, justify); // Kept leading or paragraph spacing moves the lines: put the middle of the first and last baselines on `at`. An // empty line has no baseline: an empty first or last line leaves the label where the default leading puts it. if middle && kept_para(self.styles, role).is_some() { let ys: Vec = t.baselines().map(|(a, _)| a.y).collect(); - let ends_set = s.split('|').next().is_some_and(|l| !l.is_empty()) && s.split('|').next_back().is_some_and(|l| !l.is_empty()); - let set = s.split('|').filter(|l| !l.is_empty()).count(); + let ends_set = text.split('\n').next().is_some_and(|l| !l.is_empty()) && text.split('\n').next_back().is_some_and(|l| !l.is_empty()); + let set = text.split('\n').filter(|l| !l.is_empty()).count(); if let (Some(first), Some(last), true) = (ys.first(), ys.last(), ends_set && ys.len() == set) { t.xf = Affine::translate((0.0, half - (first + last) / 2.0)) * t.xf; } diff --git a/crates/engine/src/cmd/graph/series.rs b/crates/engine/src/cmd/graph/series.rs index b5acb1ba66..681c1a6a4a 100644 --- a/crates/engine/src/cmd/graph/series.rs +++ b/crates/engine/src/cmd/graph/series.rs @@ -475,15 +475,16 @@ pub(crate) fn capture_series_opacity(doc: &mut Document, edited: &[(NodeId, bool settle_series_paints(doc, before) } -/// Copy the object opacity and blend mode of generated series art just edited (`edited`) into that series' object opacity -/// and blend mode. Called inside the same document edit, so both undo together. Returns whether a series' kept object -/// opacity or blend mode changed. +/// Copy the object transparency of generated series art just edited (`edited`) into what that series keeps: a path +/// directly in a series group sets the paths' object opacity and blend mode, and the series group itself sets the +/// group's opacity, blend mode, isolation, knockout and knockout shape. Called inside the same document edit, so both undo +/// together. Returns whether what a series keeps changed. pub(crate) fn capture_series_object_opacity(doc: &mut Document, edited: &[NodeId]) -> bool { let mut before = SeriesPaintsBefore::new(); - for (graph, index, opacity, blend) in object_opacity_captures(doc, edited) { + for (graph, index, group, look) in object_opacity_captures(doc, edited) { let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue }; // A fully opaque Normal object on a series the graph keeps nothing for leaves the graph as it is. - if opacity.is_none() && blend.is_none() && spec.series_paints.len() <= index { + if look == ObjectOpacity::default() && spec.series_paints.len() <= index { continue; } before.entry(graph).or_insert_with(|| spec.series_paints.clone()); @@ -492,7 +493,12 @@ pub(crate) fn capture_series_object_opacity(doc: &mut Document, edited: &[NodeId spec.series_paints.resize(index + 1, vectorcraft_doc::SeriesPaint::default()); } let Some(slot) = spec.series_paints.get_mut(index) else { continue }; - (slot.opacity, slot.blend) = (opacity, blend); + if group { + (slot.group_opacity, slot.group_blend) = (look.opacity, look.blend); + (slot.group_isolate, slot.group_knockout, slot.group_knockout_shape) = (look.isolate, look.knockout, look.knockout_shape); + } else { + (slot.opacity, slot.blend) = (look.opacity, look.blend); + } } settle_series_paints(doc, before) } @@ -500,20 +506,50 @@ pub(crate) fn capture_series_object_opacity(doc: &mut Document, edited: &[NodeId /// Would [`capture_series_object_opacity`] change what the graph stores for `edited`? Reads the document without copying /// it. pub(crate) fn series_object_opacity_differs(doc: &Document, edited: &[NodeId]) -> bool { - let mut after: HashMap<(NodeId, usize), (Option, Option)> = HashMap::new(); - let stored = |graph: NodeId, index: usize| { + let mut after: HashMap<(NodeId, usize, bool), ObjectOpacity> = HashMap::new(); + let stored = |graph: NodeId, index: usize, group: bool| { let spec = doc.node(graph).and_then(|n| n.extras().graph.as_deref()); - spec.and_then(|g| g.series_paints.get(index)).map_or((None, None), |slot| (slot.opacity, slot.blend)) + let slot = spec.and_then(|g| g.series_paints.get(index)); + slot.map_or_else(ObjectOpacity::default, |slot| { + if group { + ObjectOpacity { + opacity: slot.group_opacity, + blend: slot.group_blend, + isolate: slot.group_isolate, + knockout: slot.group_knockout, + knockout_shape: slot.group_knockout_shape, + } + } else { + ObjectOpacity { opacity: slot.opacity, blend: slot.blend, ..ObjectOpacity::default() } + } + }) }; - for (graph, index, opacity, blend) in object_opacity_captures(doc, edited) { - after.insert((graph, index), (opacity, blend)); + for (graph, index, group, look) in object_opacity_captures(doc, edited) { + after.insert((graph, index, group), look); } - after.into_iter().any(|((graph, index), pair)| stored(graph, index) != pair) + after.into_iter().any(|((graph, index, group), look)| stored(graph, index, group) != look) } -/// The series and object opacity and blend mode (None for 100% and Normal) of each of `edited` that is a path directly in a -/// series group, in order. -fn object_opacity_captures(doc: &Document, edited: &[NodeId]) -> Vec<(NodeId, usize, Option, Option)> { +/// The series groups among `ids`, for an edit that changes only what a group's transparency has beyond its opacity and +/// blend mode (isolation, knockout and knockout shape), which the graph keeps for series groups alone. +pub(crate) fn series_groups_among(doc: &Document, ids: &[NodeId]) -> Vec { + ids.iter().copied().filter(|id| doc.node(*id).is_some_and(|n| n.extras().series_index.is_some())).collect() +} + +/// An object's transparency as a graph keeps it: the object opacity and blend mode (None for 100% and Normal), and for a +/// series group its isolation, knockout (None for neutral) and knockout shape. Paths keep the first two only. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +struct ObjectOpacity { + opacity: Option, + blend: Option, + isolate: bool, + knockout: Option, + knockout_shape: bool, +} + +/// The graph, series, whether it is the series group itself (`true`) or a path directly in it, and the object +/// transparency of each of `edited` that is one of those, in order. +fn object_opacity_captures(doc: &Document, edited: &[NodeId]) -> Vec<(NodeId, usize, bool, ObjectOpacity)> { if edited.is_empty() { return Vec::new(); } @@ -524,14 +560,48 @@ fn object_opacity_captures(doc: &Document, edited: &[NodeId]) -> Vec<(NodeId, us edited .iter() .filter_map(|id| { - // Only the paths the graph draws again, not the copy of a graph design. - let r = members.get(id).filter(|r| doc.parent_of(*id) == Some(r.group))?; - let node = doc.node(*id).filter(|n| matches!(n.kind, NodeKind::Path { .. }))?; - Some((r.graph, r.index, (node.opacity < 1.0).then_some(node.opacity), (node.blend != BlendMode::Normal).then_some(node.blend))) + let r = members.get(id)?; + let group = r.group == *id; + // Only the series group and the paths the graph draws again, not the copy of a graph design. + let node = doc.node(*id).filter(|n| group || (doc.parent_of(*id) == Some(r.group) && matches!(n.kind, NodeKind::Path { .. })))?; + let mut look = ObjectOpacity { + opacity: (node.opacity < 1.0).then_some(node.opacity), + blend: (node.blend != BlendMode::Normal).then_some(node.blend), + ..ObjectOpacity::default() + }; + if group { + look.isolate = node.isolate; + look.knockout = (node.knockout != vectorcraft_doc::Knockout::Neutral).then_some(node.knockout); + look.knockout_shape = node.knockout_shape; + } + Some((r.graph, r.index, group, look)) }) .collect() } +/// Series `i`'s group (`group`) with the object opacity, blend mode, isolation, knockout and knockout shape the graph +/// keeps for it. An opacity read from a file is held to 0..1, and one that is not a number is left out. +pub(super) fn with_series_group_opacity(g: &GraphSpec, i: usize, mut group: Arc) -> Arc { + let Some(slot) = g.series_paints.get(i) else { return group }; + let opacity = slot.group_opacity.filter(|o| o.is_finite()).map(|o| o.clamp(0.0, 1.0)); + if opacity.is_none() && slot.group_blend.is_none() && !slot.group_isolate && slot.group_knockout.is_none() && !slot.group_knockout_shape { + return group; + } + let n = Arc::make_mut(&mut group); + if let Some(o) = opacity { + n.opacity = o; + } + if let Some(b) = slot.group_blend { + n.blend = b; + } + if let Some(k) = slot.group_knockout { + n.knockout = k; + } + n.isolate |= slot.group_isolate; + n.knockout_shape |= slot.group_knockout_shape; + group +} + /// Graph Data › Transpose row/column: categories become series and series categories. pub(super) fn transpose(g: &mut GraphSpec) { let cells = g.cells(); @@ -631,19 +701,33 @@ pub(crate) fn capture_label_styles(doc: &mut Document, ids: &[NodeId], change: & changed } -/// Apply `change` to the style graph `graph` keeps for its labels of kind `role` (or the default one). Returns whether -/// the kept style changed. +/// Apply `change` to the style graph `graph` keeps for its labels of kind `role` (or the default one). A `change` that +/// sets the fill of legend labels marks it as set on them, so a black one stays black on dark pie wedges. Returns whether +/// the kept style or that mark changed. fn store_label_style(doc: &mut Document, graph: NodeId, role: Role, change: &dyn Fn(&mut CharStyle)) -> bool { let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { return false }; let mut style = label_style(&spec.label_styles, role); + // The kept fill can already be the one `change` sets (black, the default): `change` sets the fill when it gives one + // of two different fills something else. + let sets_fill = role == Role::Legend + && [Paint::None, Paint::solid(Color::BLACK)].into_iter().any(|fill| { + let mut probe = CharStyle { fill: fill.clone(), ..style.clone() }; + change(&mut probe); + probe.fill != fill + }); change(&mut style); + let styles = &mut spec.label_styles; let slot = match role { - Role::Value => &mut spec.label_styles.values, - Role::Category => &mut spec.label_styles.categories, - Role::Legend => &mut spec.label_styles.legend, + Role::Value => &mut styles.values, + Role::Category => &mut styles.categories, + Role::Legend => &mut styles.legend, }; - let changed = slot.as_ref() != Some(&style); + let mut changed = slot.as_ref() != Some(&style); *slot = Some(style); + if sets_fill && !styles.legend_fill_set { + styles.legend_fill_set = true; + changed = true; + } changed } @@ -872,12 +956,9 @@ fn run_paint_change(was: &Node, now: &Node, fill: bool) -> Option<(CharStyle, Ve } /// Does graph `g` pick the fill of its legend labels itself, white on a dark wedge and black on the others: a pie with -/// Legends in Wedges whose legend labels keep no fill of their own? +/// Legends in Wedges whose legend labels keep no fill of their own ([`GraphSpec::picks_legend_fill`])? pub(super) fn picks_legend_fill(g: &GraphSpec) -> bool { - g.kind == GraphKind::Pie - && g.legend - && g.pie_legend_in_wedges - && !g.label_styles.legend.as_ref().is_some_and(|st| st.fill != Paint::solid(Color::BLACK)) + g.picks_legend_fill() } /// The graph labels among `roots` and inside them, for an edit that reaches graph labels without naming them. diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index 0a788c4330..f167a124d6 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -840,6 +840,24 @@ fn an_opacity_sort_objects_stores_the_frontmost_mark_it_changes() { assert_eq!(spec(&s, id).series_paints[0].opacity, Some(0.6)); } +/// A Sort Objects that gives series marks the opacities they already have changes nothing: the value the graph stores +/// stays and no undo step is made, even when the evenly stepped percentage differs from a mark's in the last digits. +#[test] +fn an_opacity_sort_objects_that_changes_no_mark_keeps_the_stored_opacity() { + let (mut s, id, _, marks) = column_marks(); + s.execute("object.setProps", &json!({"id": marks[1].0, "opacity": 65})).unwrap(); + s.execute("object.setProps", &json!({"id": marks[0].0, "opacity": 30})).unwrap(); + assert_eq!(spec(&s, id).series_paints[0].opacity, Some(0.3)); + // From left to right the columns have 30%, 65% and 100%, the values an even step from 30% to 100% gives them. + let undo = s.doc().unwrap().history.undo.len(); + let ids = [marks[0].0, marks[1].0, marks[2].0]; + s.execute("addon.arrange.sort", &json!({"ids": ids, "by": "x", "apply": "opacity", "distribute": true})).unwrap(); + let opacities: Vec = marks[..3].iter().map(|m| s.doc().unwrap().doc.node(*m).unwrap().opacity).collect(); + assert_eq!(opacities, [0.3, 0.65, 1.0]); + assert_eq!(spec(&s, id).series_paints[0].opacity, Some(0.3)); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step"); +} + /// An object opacity, blend mode, fill, stroke and weight that Global Edit gives a mark of another series from the mark /// that was edited are stored on the graph for that series in the same undo step, and every mark of the series has them /// when the graph is drawn again. @@ -905,6 +923,32 @@ fn what_global_edit_gives_the_marks_of_another_series_group_survives_regeneratio assert!(series(&n, 1).children().unwrap().iter().all(|m| m.appearance.fill_paint() == given)); } +/// With a whole series group picked and Global Edit on, the opacity and blend mode set on that group reach the other +/// series groups of the same form, and the graph stores them for those groups too. +#[test] +fn the_transparency_global_edit_gives_another_series_group_survives_regeneration() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + // Series without names draw no legend, so each series group holds only its columns, laid out like the other's. + let csv = ",,\nQ1,3,3\nQ2,5,5"; + let made = s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap(); + let id = NodeId(made["id"].as_u64().unwrap()); + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + let (first, other) = (series(&n, 0).id, series(&n, 1).id); + s.execute("object.isolate", &json!({"id": id.0})).unwrap(); + s.execute("select.set", &json!({"ids": [first.0]})).unwrap(); + let r = s.execute("select.globalEdit", &json!({})).unwrap(); + assert!(r["ids"].as_array().unwrap().contains(&json!(other.0)), "{r}"); + s.execute("transparency.set", &json!({"ids": [first.0], "opacity": 40, "blend": "multiply"})).unwrap(); + let g = s.doc().unwrap().doc.node(other).unwrap().clone(); + assert_eq!((g.opacity, g.blend), (0.4, BlendMode::Multiply), "Global Edit reaches the other group"); + let kept = spec(&s, id).series_paints[1].clone(); + assert_eq!((kept.group_opacity, kept.group_blend), (Some(0.4), Some(BlendMode::Multiply))); + s.execute("object.exitIsolation", &json!({})).unwrap(); + s.execute("graph.setData", &json!({"rows": [[1, 2], [3, 4]]})).unwrap(); + assert_eq!(group_transparency(&s, id, 1).0, (0.4, BlendMode::Multiply)); +} + /// A blend mode set on the top fill or stroke row of one series mark is kept by the graph and drawn on every mark of /// the series again; Normal forgets it. #[test] @@ -2192,8 +2236,8 @@ fn appearance_commands_given_a_series_group_edit_its_marks() { s.execute("edit.undo", &json!({})).unwrap(); let (rect, blue) = blue_style(&mut s, "Blue", false); - let was = spec(&s, id).series_paints; s.execute("object.setProps", &json!({"ids": [group.0], "opacity": 50})).unwrap(); + let was = spec(&s, id).series_paints; s.execute("appearance.transfer", &json!({"source": rect.0, "target": group.0, "copy": true})).unwrap(); assert!(series_0_group(&s, id).1); assert_eq!(s.doc().unwrap().doc.node(group).unwrap().opacity, 1.0, "the appearance replaces the group's own opacity"); @@ -2415,10 +2459,10 @@ fn a_graphic_style_applied_to_a_series_group_styles_its_marks() { let (mut s, id, marks) = stored_red_stroke(); let (group, _) = series_0_group(&s, id); let (_, blue) = blue_style(&mut s, "Blue", false); - let was = spec(&s, id).series_paints; let own = json!({"ids": [group.0], "opacity": 50, "blend": "multiply", "isolate": true, "knockout": "on", "item": null}); s.execute("transparency.set", &own).unwrap(); s.execute("effect.apply", &json!({"ids": [group.0], "effect": "distort.twist"})).unwrap(); + let was = spec(&s, id).series_paints; let g = s.doc().unwrap().doc.node(group).unwrap().clone(); assert!(g.isolate && g.knockout != Default::default() && g.blend != vectorcraft_color::BlendMode::Normal); s.execute("graphicStyle.apply", &json!({"name": "Blue", "ids": [group.0]})).unwrap(); @@ -2495,6 +2539,161 @@ fn redefining_a_graphic_style_keeps_an_edited_mark_of_a_linked_series_group() { assert!(marks[1..].iter().all(|m| d.node(*m).unwrap().extras().graphic_style == Some(style.id))); } +/// Series `index`'s group: its object opacity and blend mode, and those of each path directly inside it. +fn group_transparency(s: &Session, id: NodeId, index: u32) -> ((f32, BlendMode), Vec<(f32, BlendMode)>) { + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + let g = series(&n, index); + ((g.opacity, g.blend), g.children().unwrap().iter().map(|m| (m.opacity, m.blend)).collect()) +} + +/// An object opacity and blend mode set on a selected series group are kept by the graph for the group: the series group +/// has them after the graph is drawn again, the graph's data reads them back unchanged after it is written to JSON, its +/// paths and the other series stay opaque and Normal, setting them again records no step, 100% and Normal forget them, +/// and undo takes them back. +#[test] +fn an_opacity_and_blend_mode_on_a_series_group_survive_regeneration() { + let (mut s, id, _, _) = column_marks(); + let (group, _) = series_0_group(&s, id); + s.execute("select.set", &json!({"ids": [group.0]})).unwrap(); + s.execute("transparency.set", &json!({"opacity": 40, "blend": "multiply"})).unwrap(); + let kept = spec(&s, id).series_paints[0].clone(); + assert_eq!((kept.group_opacity, kept.group_blend), (Some(0.4), Some(BlendMode::Multiply))); + assert_eq!((kept.opacity, kept.blend), (None, None), "the paths keep their own"); + let restored: GraphSpec = serde_json::from_value(serde_json::to_value(spec(&s, id)).unwrap()).unwrap(); + assert_eq!(restored, spec(&s, id)); + s.execute("graph.setData", &json!({"id": id.0, "rows": [[1, 2], [3, 4]]})).unwrap(); + let normal = (1.0, BlendMode::Normal); + let (own, paths) = group_transparency(&s, id, 0); + assert_eq!(own, (0.4, BlendMode::Multiply)); + assert!(!paths.is_empty() && paths.iter().all(|t| *t == normal), "{paths:?}"); + let (own, paths) = group_transparency(&s, id, 1); + assert_eq!(own, normal); + assert!(paths.iter().all(|t| *t == normal), "{paths:?}"); + + let (group, _) = series_0_group(&s, id); + let undo = s.doc().unwrap().history.undo.len(); + s.execute("object.setProps", &json!({"id": group.0, "opacity": 40, "blend": "multiply"})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "the values the group and the graph have already"); + s.execute("object.setProps", &json!({"id": group.0, "opacity": 100, "blend": "normal"})).unwrap(); + let kept = spec(&s, id).series_paints[0].clone(); + assert_eq!((kept.group_opacity, kept.group_blend), (None, None)); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.setData", &json!({"rows": [[2, 2], [3, 4]]})).unwrap(); + assert_eq!(group_transparency(&s, id, 0).0, normal); + for _ in 0..4 { + s.execute("edit.undo", &json!({})).unwrap(); + } + assert!(spec(&s, id).series_paints.is_empty(), "undo takes back the edit and what the graph stored"); +} + +/// Commands that clear a series group's own opacity and blend mode also remove what the graph keeps for it: Clear +/// Appearance on the group, a graphic style applied to it and Move Appearance onto it. +#[test] +fn clearing_a_series_groups_opacity_forgets_what_the_graph_keeps() { + let kept = |s: &Session, id: NodeId| { + let slot = spec(s, id).series_paints[0].clone(); + (slot.group_opacity, slot.group_blend) + }; + let faded = (Some(0.5), Some(BlendMode::Screen)); + let (mut s, id, _, _) = column_marks(); + let (rect, _) = blue_style(&mut s, "Blue", false); + let (group, _) = series_0_group(&s, id); + s.execute("object.setProps", &json!({"id": group.0, "opacity": 50, "blend": "screen"})).unwrap(); + assert_eq!(kept(&s, id), faded); + let commands = [ + ("appearance.clear", json!({"ids": [group.0]})), + ("graphicStyle.apply", json!({"name": "Blue", "ids": [group.0]})), + ("appearance.transfer", json!({"source": rect.0, "target": group.0, "copy": true})), + ]; + for (cmd, params) in commands { + s.execute(cmd, ¶ms).unwrap(); + assert_eq!(kept(&s, id), (None, None), "{cmd}"); + s.execute("graph.setData", &json!({"id": id.0, "rows": [[1, 2], [3, 4]]})).unwrap(); + assert_eq!(group_transparency(&s, id, 0).0, (1.0, BlendMode::Normal), "{cmd}"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(kept(&s, id), faded, "{cmd}"); + } +} + +/// Redefining a graphic style a series group is linked to clears the group's own opacity and blend mode, and removes +/// what the graph keeps for them. +#[test] +fn redefining_a_style_linked_to_a_series_group_forgets_its_kept_opacity() { + let (mut s, id, _, _) = column_marks(); + let (group, _) = series_0_group(&s, id); + let (rect, _) = blue_style(&mut s, "Blue", false); + let style = s.doc().unwrap().doc.graphic_style("Blue").unwrap().clone(); + s.edit("Link", |d, _| { + let i = d.graphic_style_index("Blue").unwrap(); + (d.graphic_styles[i].opacity, d.graphic_styles[i].blend) = (0.5, BlendMode::Screen); + let g = d.node_mut(group).unwrap(); + g.appearance = style.appearance.clone().into(); + (g.opacity, g.blend) = (0.5, BlendMode::Screen); + g.extras_mut().graphic_style = Some(style.id); + Ok(()) + }) + .unwrap(); + s.execute("object.setProps", &json!({"id": group.0, "opacity": 50, "blend": "screen"})).unwrap(); + let slot = spec(&s, id).series_paints[0].clone(); + assert_eq!((slot.group_opacity, slot.group_blend), (Some(0.5), Some(BlendMode::Screen))); + assert_eq!(s.doc().unwrap().doc.node(group).unwrap().extras().graphic_style, Some(style.id), "still linked"); + s.execute("appearance.setItem", &json!({"ids": [rect.0], "index": top_row(&s, rect, true), "color": "#00ff00"})).unwrap(); + s.execute("graphicStyle.redefine", &json!({"name": "Blue", "id": rect.0})).unwrap(); + let slot = spec(&s, id).series_paints.first().cloned().unwrap_or_default(); + assert_eq!((slot.group_opacity, slot.group_blend), (None, None)); + s.execute("graph.setData", &json!({"id": id.0, "rows": [[1, 2], [3, 4]]})).unwrap(); + assert_eq!(group_transparency(&s, id, 0).0, (1.0, BlendMode::Normal)); +} + +/// Isolate Blending, a knockout state and Knockout Shape set on a selected series group are kept by the graph for the +/// group, through the graph being drawn again; the other series' group stays as the graph draws it, and turning them off +/// forgets them. +#[test] +fn isolation_and_knockout_on_a_series_group_survive_regeneration() { + let (mut s, id, _, _) = column_marks(); + let (group, _) = series_0_group(&s, id); + s.execute("select.set", &json!({"ids": [group.0]})).unwrap(); + s.execute("transparency.set", &json!({"isolate": true, "knockout": "off", "knockoutShape": true})).unwrap(); + let slot = spec(&s, id).series_paints[0].clone(); + assert_eq!((slot.group_isolate, slot.group_knockout, slot.group_knockout_shape), (true, Some(vectorcraft_doc::Knockout::Off), true)); + assert_eq!((slot.group_opacity, slot.group_blend, slot.opacity, slot.blend), (None, None, None, None)); + let undo = s.doc().unwrap().history.undo.len(); + s.execute("object.setProps", &json!({"id": group.0, "isolate": true})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "the values the group and the graph have already"); + s.execute("graph.setData", &json!({"id": id.0, "rows": [[1, 2], [3, 4]]})).unwrap(); + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + let (g, other) = (series(&n, 0), series(&n, 1)); + assert_eq!((g.isolate, g.knockout, g.knockout_shape), (true, vectorcraft_doc::Knockout::Off, true)); + assert_eq!((other.isolate, other.knockout, other.knockout_shape), (false, vectorcraft_doc::Knockout::Neutral, false)); + let (group, _) = series_0_group(&s, id); + s.execute("object.setProps", &json!({"id": group.0, "isolate": false, "knockout": "neutral", "knockoutShape": false})).unwrap(); + assert!(spec(&s, id).series_paints.iter().all(|p| *p == vectorcraft_doc::SeriesPaint::default()), "nothing is kept"); +} + +/// Randomize Opacity and Sort Objects given a series group keep the opacity they give it for the group. +#[test] +fn randomize_and_sort_opacity_on_a_series_group_are_kept() { + let (mut s, id, _, _) = column_marks(); + let (group, _) = series_0_group(&s, id); + s.execute("addon.arrange.randomizeOpacity", &json!({"ids": [group.0], "min": 30, "max": 60, "seed": 7})).unwrap(); + let given = s.doc().unwrap().doc.node(group).unwrap().opacity; + assert!(given < 1.0); + assert_eq!(spec(&s, id).series_paints[0].group_opacity, Some(given)); + s.execute("graph.setData", &json!({"id": id.0, "rows": [[1, 2], [3, 4]]})).unwrap(); + assert_eq!(group_transparency(&s, id, 0).0, (given, BlendMode::Normal)); + + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + let (first, second) = (series(&n, 0).id, series(&n, 1).id); + s.execute("object.setProps", &json!({"id": second.0, "opacity": 80})).unwrap(); + s.execute("addon.arrange.sort", &json!({"ids": [first.0, second.0], "by": "x", "apply": "opacity", "order": "descending"})).unwrap(); + let d = &s.doc().unwrap().doc; + let (a, b) = (d.node(first).unwrap().opacity, d.node(second).unwrap().opacity); + assert_eq!((a, b), (0.8, given), "the opacities trade places"); + let kept = &spec(&s, id).series_paints; + assert_eq!((kept[0].group_opacity, kept.get(1).and_then(|k| k.group_opacity)), ((a < 1.0).then_some(a), (b < 1.0).then_some(b))); +} + /// Default Fill and Stroke on a series mark stores a white fill and a 1 pt black stroke, both opaque, on the graph. #[test] fn default_fill_and_stroke_on_a_series_mark_is_kept() { @@ -5673,6 +5872,286 @@ fn formatting_one_label_keeps_that_kind_of_label() { assert!(serde_json::to_value(GraphSpec::default()).unwrap().get("labelStyles").is_none()); } +/// Character and paragraph edits that resize a graph's labels leave the plot where it is when the graph is drawn +/// again, and a move or scale of the graph made after them is still followed. +#[test] +fn restyling_a_graphs_labels_leaves_the_plot_in_place() { + let csv = ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"; + let redraw = |s: &mut Session, id: NodeId| s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let rect = spec(&s, id).rect; + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("text.setStyle", &json!({"size": 14})).unwrap(); + redraw(&mut s, id); + assert_eq!(spec(&s, id).rect, rect, "after a size change to every label"); + let c = text_id(&s, id, "Axes", "Q2"); + s.execute("text.setFormat", &json!({"ids": [c.0], "leftIndent": 20})).unwrap(); + redraw(&mut s, id); + assert_eq!(spec(&s, id).rect, rect, "after an indent on the category labels"); + let l = text_id(&s, id, "Legend", "2025"); + s.execute("text.setStyle", &json!({"ids": [l.0], "size": 4})).unwrap(); + redraw(&mut s, id); + assert_eq!(spec(&s, id).rect, rect, "after a smaller size on the legend labels"); + // A move and a scale of the whole graph still carry the plot with them. + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("object.move", &json!({"dx": 40, "dy": -10})).unwrap(); + redraw(&mut s, id); + let moved = spec(&s, id).rect; + assert!((moved.x0 - (rect.x0 + 40.0)).abs() < 1e-6 && (moved.y0 - (rect.y0 - 10.0)).abs() < 1e-6, "{moved:?}"); + assert!((moved.width() - rect.width()).abs() < 1e-6 && (moved.height() - rect.height()).abs() < 1e-6, "{moved:?}"); + s.execute("object.scale", &json!({"sx": 200, "sy": 100, "origin": [moved.x0, moved.y0]})).unwrap(); + redraw(&mut s, id); + let scaled = spec(&s, id).rect; + assert!((scaled.width() - 2.0 * rect.width()).abs() < 1e-6 && (scaled.height() - rect.height()).abs() < 1e-6, "{scaled:?}"); + assert!((scaled.x0 - moved.x0).abs() < 1e-6 && (scaled.y0 - moved.y0).abs() < 1e-6, "{scaled:?}"); +} + +/// Moving one label of a graph on its own leaves the plot where it is when the graph is drawn again. +#[test] +fn moving_one_label_leaves_the_plot_in_place() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let rect = spec(&s, id).rect; + for (grp, text) in [("Legend", "2025"), ("Axes", "Q2")] { + let l = text_id(&s, id, grp, text); + s.execute("select.set", &json!({"ids": [l.0]})).unwrap(); + s.execute("object.move", &json!({"dx": 120, "dy": 60})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap(); + assert_eq!(spec(&s, id).rect, rect, "after moving {text}"); + } +} + +/// Label edits leave the plot in place in graphs whose legend swatches follow the size of the labels at the next +/// drawing: a legend across the top, a legend after a right value axis, and legend labels of several lines. A move of +/// the graph made after them is still followed. +#[test] +fn restyling_the_labels_of_a_graph_whose_legend_follows_them_leaves_the_plot_in_place() { + let csv = ",North|East|Coast,South|West,Inland|Hills|Lakes|Plains\nQ1,3,2,4\nQ2,5,4,1\nQ3,-1,6,2"; + for options in [json!({"legendAcrossTop": true}), json!({"valueAxis": "right"}), json!({"valueAxis": "both"}), json!({})] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.setType", &options).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap(); + let rect = spec(&s, id).rect; + for size in [16, 5] { + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("text.setStyle", &json!({"size": size})).unwrap(); + for _ in 0..2 { + s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap(); + assert_eq!(spec(&s, id).rect, rect, "{options}: labels at {size} pt"); + } + } + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("object.move", &json!({"dx": 30, "dy": 20})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap(); + let moved = spec(&s, id).rect; + assert!((moved.x0 - (rect.x0 + 30.0)).abs() < 1e-6 && (moved.y0 - (rect.y0 + 20.0)).abs() < 1e-6, "{options}: {moved:?}"); + assert!((moved.width() - rect.width()).abs() < 1e-6 && (moved.height() - rect.height()).abs() < 1e-6, "{options}: {moved:?}"); + } +} + +/// Outlining a graph's labels leaves the plot where it is when the graph is drawn again, and a move of the graph made +/// before them is still followed. +#[test] +fn outlining_a_graphs_labels_leaves_the_plot_in_place() { + let csv = ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"; + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let rect = spec(&s, id).rect; + s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap(); + s.execute("select.set", &json!({"ids": [text_id(&s, id, "Axes", "Q2").0, text_id(&s, id, "Legend", "2025").0]})).unwrap(); + s.execute("type.createOutlines", &json!({})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap(); + assert_eq!(spec(&s, id).rect, rect, "after outlining labels"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("object.move", &json!({"dx": 30, "dy": 15})).unwrap(); + s.execute("select.set", &json!({"ids": [text_id(&s, id, "Axes", "Q1").0, text_id(&s, id, "Legend", "2024").0]})).unwrap(); + s.execute("type.createOutlines", &json!({})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap(); + let moved = spec(&s, id).rect; + assert!((moved.x0 - (rect.x0 + 30.0)).abs() < 1e-6 && (moved.y0 - (rect.y0 + 15.0)).abs() < 1e-6, "{moved:?}"); + assert!((moved.width() - rect.width()).abs() < 1e-6 && (moved.height() - rect.height()).abs() < 1e-6, "{moved:?}"); + // A scale of the graph made before outlining is still followed. + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("object.scale", &json!({"sx": 150, "sy": 50, "origin": [moved.x0, moved.y0]})).unwrap(); + s.execute("select.set", &json!({"ids": [text_id(&s, id, "Axes", "Q3").0]})).unwrap(); + s.execute("type.createOutlines", &json!({})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap(); + let scaled = spec(&s, id).rect; + assert!((scaled.x0 - moved.x0).abs() < 1e-6 && (scaled.y0 - moved.y0).abs() < 1e-6, "{scaled:?}"); + assert!((scaled.width() - 1.5 * rect.width()).abs() < 1e-6 && (scaled.height() - 0.5 * rect.height()).abs() < 1e-6, "{scaled:?}"); +} + +/// Outline Stroke on a graph's strokes leaves the plot where it is when the graph is drawn again, and a move of the +/// graph made before it is still followed. +#[test] +fn outlining_a_graphs_strokes_leaves_the_plot_in_place() { + let csv = ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"; + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let rect = spec(&s, id).rect; + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("object.move", &json!({"dx": 20, "dy": 10})).unwrap(); + s.execute("object.path.outlineStroke", &json!({})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap(); + let moved = spec(&s, id).rect; + assert!((moved.x0 - (rect.x0 + 20.0)).abs() < 1e-6 && (moved.y0 - (rect.y0 + 10.0)).abs() < 1e-6, "{moved:?}"); + assert!((moved.width() - rect.width()).abs() < 1e-6 && (moved.height() - rect.height()).abs() < 1e-6, "{moved:?}"); +} + +/// A graph left with only its labels, or with its labels and one vertical line, leaves the plot where it is when it is +/// drawn again after a label edit. +#[test] +fn a_graph_left_with_only_its_labels_leaves_the_plot_in_place() { + for keep_a_line in [false, true] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let rect = spec(&s, id).rect; + let (mut art, mut line) = (vec![], None); + s.doc().unwrap().doc.node(id).unwrap().walk(&mut |n| { + if n.children().is_none() && !matches!(n.kind, NodeKind::Text(_)) { + let vertical = n.geometric_bounds().is_some_and(|b| b.width() < 1e-9 && b.height() > 1.0); + if keep_a_line && vertical && line.is_none() { + line = n.geometric_bounds(); + } else { + art.push(n.id.0); + } + } + }); + assert!(!art.is_empty() && line.is_some() == keep_a_line); + s.execute("select.set", &json!({"ids": art})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + let left = s.doc().unwrap().doc.node(id).unwrap().clone(); + assert_eq!(vectorcraft_doc::graph::graph_art_without_type(left.children().unwrap()), line, "{:#?}", left.children()); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("text.setStyle", &json!({"size": 20})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap(); + assert_eq!(spec(&s, id).rect, rect, "keeping a line: {keep_a_line}"); + } +} + +/// A graph saved without the bounds of its art without type, left with one vertical line, keeps its plot's size when +/// it is drawn again. +#[test] +fn a_graph_saved_with_only_its_whole_bounds_and_left_with_a_line_keeps_its_plot() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let rect = spec(&s, id).rect; + let mut old = spec(&s, id); + old.placed_art = None; + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().extras_mut().graph = Some(Box::new(old)); + let (mut art, mut line) = (vec![], None); + s.doc().unwrap().doc.node(id).unwrap().walk(&mut |n| { + if n.children().is_none() { + let vertical = !matches!(n.kind, NodeKind::Text(_)) && n.geometric_bounds().is_some_and(|b| b.width() < 1e-9 && b.height() > 1.0); + if vertical && line.is_none() { + line = Some(n.id); + } else { + art.push(n.id.0); + } + } + }); + assert!(line.is_some()); + s.execute("select.set", &json!({"ids": art})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap(); + assert_eq!(spec(&s, id).rect, rect); +} + +/// The bounds a graph measures moves on take a clipping group holding type at the bounds of its clip, so art outside the +/// clip does not change them; a clipping group whose clip is type is measured on its other art. +#[test] +fn a_clipping_group_holding_type_is_measured_on_its_clip() { + use std::sync::Arc; + use vectorcraft_doc::graph::graph_art_without_type as measure; + use vectorcraft_geom::Affine; + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + let label: Arc = + group(&n, "Legend").children().unwrap().iter().find(|c| matches!(c.kind, NodeKind::Text(_))).unwrap().clone(); + let mut paths = vec![]; + n.walk(&mut |c| { + if matches!(c.kind, NodeKind::Path { .. }) { + paths.push(c.clone()); + } + }); + let (clip, art) = (Arc::new(paths[0].clone()), paths[1].clone()); + let clipped = |dx: f64, first: Arc, second: Arc| { + let mut far = art.clone(); + far.transform(Affine::translate((dx, 0.0)), false); + let mut g = vectorcraft_doc::Node::group(NodeId(999_999), vec![first, second, Arc::new(far)]); + if let NodeKind::Group { clip, .. } = &mut g.kind { + *clip = true; + } + measure(&[Arc::new(g)]) + }; + assert_eq!(clipped(500.0, clip.clone(), label.clone()), clip.geometric_bounds()); + assert_eq!(clipped(500.0, clip.clone(), label.clone()), clipped(900.0, clip.clone(), label.clone())); + // A clip that is type leaves the other art to measure. + assert_ne!(clipped(500.0, label.clone(), clip.clone()), clipped(900.0, label.clone(), clip.clone())); + // A clip that is a clipping group holding type in its clipped art is measured on its own clip. + let mut inner = vectorcraft_doc::Node::group(NodeId(999_998), vec![clip.clone(), label.clone()]); + if let NodeKind::Group { clip, .. } = &mut inner.kind { + *clip = true; + } + let inner = Arc::new(inner); + assert_eq!(clipped(500.0, inner.clone(), label.clone()), clip.geometric_bounds()); + assert_eq!(clipped(500.0, inner.clone(), label.clone()), clipped(900.0, inner.clone(), label.clone())); + // A blend holding type is measured whole, as it is drawn. + let blend = vectorcraft_doc::Node::new(NodeId(999_997), NodeKind::Blend { children: vec![clip.clone(), label.clone()], spec: Box::default() }); + assert_eq!(measure(&[Arc::new(blend.clone())]), blend.geometric_bounds()); +} + +/// A graph whose kept bounds of its art without type have no width follows a move with the bounds of all of its art. +#[test] +fn a_graph_whose_art_without_type_kept_no_width_still_follows_a_move() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let rect = spec(&s, id).rect; + let mut flat = spec(&s, id); + let art = flat.placed_art.unwrap(); + flat.placed_art = Some(vectorcraft_geom::Rect::new(art.x0, art.y0, art.x0, art.y1)); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().extras_mut().graph = Some(Box::new(flat)); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("object.move", &json!({"dx": 25, "dy": 5})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap(); + let moved = spec(&s, id).rect; + assert!((moved.x0 - (rect.x0 + 25.0)).abs() < 1e-6 && (moved.y0 - (rect.y0 + 5.0)).abs() < 1e-6, "{moved:?}"); +} + +/// A graph saved before it kept the bounds of its art without type follows a move made since with its old bounds. +#[test] +fn a_graph_saved_with_only_its_whole_bounds_still_follows_a_move() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let rect = spec(&s, id).rect; + let mut old = serde_json::to_value(spec(&s, id)).unwrap(); + old.as_object_mut().unwrap().remove("placedArt"); + let old: GraphSpec = serde_json::from_value(old).unwrap(); + assert_eq!(old.placed_art, None); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().extras_mut().graph = Some(Box::new(old)); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("object.move", &json!({"dx": 25, "dy": 5})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap(); + let moved = spec(&s, id).rect; + assert!((moved.x0 - (rect.x0 + 25.0)).abs() < 1e-6 && (moved.y0 - (rect.y0 + 5.0)).abs() < 1e-6, "{moved:?}"); + assert!(spec(&s, id).placed_art.is_some(), "the next drawing keeps the bounds of the art without type"); +} + /// Each Axes and Legend text after the graph is drawn again, with its object rows (fill or stroke, color, opacity, and /// for a stroke its weight) and its object opacity. type RowLooks = Vec<(bool, String, f32, f64)>; @@ -6343,6 +6822,93 @@ fn pie_names_and_wedge_labels_keep_their_style() { assert_eq!(fills, ["#00ff00", "#00ff00"], "the kept fill, also on the dark wedge"); } +/// On a pie with Legends in Wedges, a black fill given to the white legend label on the dark wedge is kept for every +/// legend label: the graph draws it black on the dark wedge again, also after a native save and open. +#[test] +fn a_black_fill_set_on_a_wedge_legend_label_stays_black_on_dark_wedges() { + let cases = [("paint.setFill", json!({"color": "#000000"})), ("text.setStyle", json!({"fill": "#000000"})), ("edit.colors.invert", json!({}))]; + every_case(cases, |(cmd, params)| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = make(&mut s, "pie", ",a,b\nP1,1,2"); + s.execute("graph.setType", &json!({"id": id.0, "pieLegend": "wedges"})).unwrap(); + let legend_fill = |s: &Session, text: &str| { + let NodeKind::Text(t) = label_node(s, id, "Legend", text).kind else { panic!("{text} is not type") }; + t.runs[0].style.fill.color().map(|c| c.to_hex()).unwrap_or_default() + }; + assert_eq!(legend_fill(&s, "a"), "#ffffff", "white on the black wedge"); + let mut p = params.clone(); + p["ids"] = json!([text_id(&s, id, "Legend", "a").0]); + s.execute(cmd, &p).unwrap(); + assert!(spec(&s, id).label_styles.legend_fill_set, "{cmd}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(!spec(&s, id).label_styles.legend_fill_set, "{cmd}: undone"); + assert_eq!(legend_fill(&s, "a"), "#ffffff", "{cmd}: white again after the undo"); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(spec(&s, id).label_styles.legend_fill_set, "{cmd}: redone"); + s.execute("graph.setData", &json!({"id": id.0, "rows": [[1, 2]]})).unwrap(); + assert_eq!((legend_fill(&s, "a"), legend_fill(&s, "b")), ("#000000".into(), "#000000".into()), "{cmd}: black on both wedges"); + let dir = vectorcraft_testkit::TempDir::new("graph-wedge-legend"); + let path = dir.join("pie.vectorcraft"); + s.execute("document.save", &json!({"path": path})).unwrap(); + s.execute("document.open", &json!({"path": path})).unwrap(); + assert!(spec(&s, id).label_styles.legend_fill_set, "{cmd}: kept through save and open"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "rows": [[2, 1]]})).unwrap(); + assert_eq!(legend_fill(&s, "a"), "#000000", "{cmd}: still black after open"); + }); +} + +/// A size given to the legend labels of a pie with Legends in Wedges keeps the default black fill with it. A color mode +/// change leaves that fill black, so the legend label on the dark wedge is still drawn white. A legend fill that is not +/// black, in a file saved without the mark, is marked as set by the change. +#[test] +fn a_color_mode_change_keeps_the_default_wedge_legend_fill() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = make(&mut s, "pie", ",a,b\nP1,1,2"); + s.execute("graph.setType", &json!({"id": id.0, "pieLegend": "wedges"})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("text.setStyle", &json!({"size": 11})).unwrap(); + s.execute("file.documentColorMode", &json!({"mode": "cmyk"})).unwrap(); + let styles = spec(&s, id).label_styles; + assert!(!styles.legend_fill_set && !styles.legend_fill_is_own(), "{styles:?}"); + s.execute("graph.setData", &json!({"id": id.0, "rows": [[1, 2]]})).unwrap(); + let NodeKind::Text(t) = label_node(&s, id, "Legend", "a").kind else { panic!("a is not type") }; + assert_eq!(t.runs[0].style.fill.color().map(|c| c.to_hex()), Some("#ffffff".into()), "white on the black wedge"); + let red = Paint::solid(vectorcraft_color::Color::from_hex("#ff0000").unwrap()); + let styles = vectorcraft_doc::LabelStyles { legend: Some(vectorcraft_doc::CharStyle { fill: red, ..Default::default() }), ..Default::default() }; + assert!(!styles.legend_fill_set && styles.legend_fill_is_own(), "{styles:?}"); + s.edit("legacy", |d, _| { + d.node_mut(id).unwrap().extras_mut().graph.as_deref_mut().unwrap().label_styles = styles; + Ok(()) + }) + .unwrap(); + s.execute("file.documentColorMode", &json!({"mode": "rgb"})).unwrap(); + assert!(spec(&s, id).label_styles.legend_fill_set, "the converted red is still the labels' own"); +} + +/// The default black legend fill of a graph that keeps its legend beside the marks stays the default through a color +/// mode change, so turning on Legends in Wedges later still draws the labels on dark wedges white. +#[test] +fn a_color_mode_change_keeps_the_default_legend_fill_of_other_graphs() { + // A pie made here keeps its legend beside the pies. + for kind in ["column", "pie"] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = make(&mut s, kind, ",a,b\nP1,1,2"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("text.setStyle", &json!({"size": 11})).unwrap(); + let black = Paint::solid(vectorcraft_color::Color::BLACK); + let before = spec(&s, id).label_styles; + assert_eq!(before.legend.as_ref().map(|st| st.fill.clone()), Some(black.clone()), "{kind}: {before:?}"); + s.execute("file.documentColorMode", &json!({"mode": "cmyk"})).unwrap(); + let after = spec(&s, id).label_styles; + assert_eq!(after.legend.as_ref().map(|st| st.fill.clone()), Some(black), "{kind}: {after:?}"); + assert!(!after.legend_fill_set && !after.legend_fill_is_own(), "{kind}: still the default: {after:?}"); + } +} + #[test] fn labels_are_told_apart_by_where_they_come_not_by_their_text() { let mut s = Session::new(); @@ -6576,6 +7142,43 @@ fn a_centered_label_with_an_empty_middle_line_and_kept_leading_stays_centered() assert!((after - before).abs() < 0.01, "the three-line category label keeps its middle: {before} {after}"); } +#[test] +fn a_centered_label_with_a_line_break_in_its_text_is_set_as_with_a_bar() { + // A quoted CSV cell keeps its line breaks, so they reach the label as well as the `|` it is written with. + for (bar, quoted, text) in [("Q|1", "\"Q\n1\"", "Q\n1"), ("Q|||1", "\"Q\n||1\"", "Q\n\n\n1")] { + let label_middle = |s: &Session, id: NodeId| { + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + let label = + group(&n, "Axes").children().unwrap().iter().find(|c| matches!(&c.kind, NodeKind::Text(t) if t.plain_text() == text)).unwrap(); + let b = label.geometric_bounds().unwrap(); + (b.y0 + b.y1) / 2.0 + }; + let drawn = |cat: &str, leading: bool| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let csv = format!(",2024,2025\n{cat},3,2\nQ2,5,4\nQ3,-1,6"); + let id = NodeId( + s.execute("graph.create", &json!({"type": "bar", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap()["id"] + .as_u64() + .unwrap(), + ); + if leading { + let l = text_id(&s, id, "Axes", text); + s.execute("select.set", &json!({"ids": [l.0]})).unwrap(); + s.execute("text.setFormat", &json!({"autoLeading": 400})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap(); + } + label_middle(&s, id) + }; + for leading in [false, true] { + let (by_bar, by_break) = (drawn(bar, leading), drawn(quoted, leading)); + assert!((by_bar - by_break).abs() < 0.01, "{text:?} sits where {bar:?} does (kept leading: {leading}): {by_bar} {by_break}"); + } + assert!((drawn(quoted, true) - drawn(quoted, false)).abs() < 0.01, "{text:?} keeps its middle with kept leading"); + } +} + #[test] fn a_legend_across_top_measures_its_labels_with_system_layout() { let mut s = Session::new(); @@ -6830,3 +7433,50 @@ fn a_graph_opened_from_ai_keeps_its_data_for_editing() { assert!(notes.iter().any(|w| w.as_str().is_some_and(|w| w.starts_with("graphs are written as their art"))), "{name}: {r}"); } } + +/// A graph opened from a `.ai` keeps the bounds of its art without type, so moving one of its labels on its own +/// leaves the plot where it is at the first redraw. +#[test] +fn a_graph_opened_from_ai_measures_moves_without_its_labels() { + let graph = "%_Gs\n%_100 200 300 100 Gb\n%_5 0 0 14 0 1 0 0 6 44 Gy\n%_10 2 0 0 90 80 0 Gd\n\ + %_1 () Ga\n%_0 13 0 0 0 0 0 () GA\n%_2 () Ga\n%_0 14 0 0 0 0 0 () GA\n%_4 () Ga\n%_0 14 0 0 0 0 0 () GA\n\ + %_2 2 1 1 Gz\n%_() Gc (East) Gc (Q1) Gc 5 Gc GC\n\ + u\nu\n0.6 0 1 0 k\n110 100 m\n110 150 L\n130 150 L\n130 100 L\nf\nU\n%_2 1 0 0 Go\n\ + u\n0 0 0 1 K\n100 200 m\n100 100 L\n300 100 L\nS\nU\n\ + 0 To\n1 0 0 1 100 220 0 Tp\nTP\n0 Tr\n0 0 0 1 k\n/_Helvetica 12 Tf\n(Sales) Tx\nTO\nU\n%_GS\n"; + let text = format!( + "%!PS-Adobe-3.0\n%%Creator: a script\n%%BoundingBox: 0 0 400 400\n%AI5_FileFormat 3\n%AI3_Cropmarks: 0 0 400 400\n%%EndComments\n\ + %%BeginProlog\n%%EndProlog\n%%BeginSetup\n%%EndSetup\n%AI5_BeginLayer\n1 1 1 1 0 0 0 79 128 255 Lb\n(Graph) Ln\n0 A\n{graph}LB\n\ + %AI5_EndLayer--\n%%PageTrailer\n%%Trailer\n%%EOF\n" + ); + let dir = vectorcraft_testkit::temp_dir("graph-ai-label"); + let path = dir.join("graph.ai"); + std::fs::write(&path, text).unwrap(); + let mut s = Session::new(); + s.execute("document.open", &json!({"path": path})).unwrap(); + let (mut graphs, mut labels) = (vec![], vec![]); + s.doc().unwrap().doc.walk(|n| { + if n.extras().graph.is_some() { + graphs.push(n.id); + } + if matches!(&n.kind, NodeKind::Text(t) if t.plain_text() == "Sales") { + labels.push(n.id); + } + }); + assert_eq!((graphs.len(), labels.len()), (1, 1)); + let (id, label) = (graphs[0], labels[0]); + let before = spec(&s, id); + s.execute("select.set", &json!({"ids": [label.0]})).unwrap(); + s.execute("text.setStyle", &json!({"size": 30})).unwrap(); + s.execute("object.move", &json!({"dx": 80, "dy": -40})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "csv": ",East\nQ1,8\nQ2,2"})).unwrap(); + let rect = spec(&s, id).rect; + assert_eq!(rect, before.rect, "after restyling and moving a label"); + // A move of the whole opened graph is still followed. + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("object.move", &json!({"dx": 15, "dy": 25})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "csv": ",East\nQ1,8\nQ2,2"})).unwrap(); + let moved = spec(&s, id).rect; + assert!((moved.x0 - (rect.x0 + 15.0)).abs() < 1e-6 && (moved.y0 - (rect.y0 + 25.0)).abs() < 1e-6, "{moved:?}"); + assert!((moved.width() - rect.width()).abs() < 1e-6 && (moved.height() - rect.height()).abs() < 1e-6, "{moved:?}"); +} diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rs index ced9347bc1..4d562a76e7 100644 --- a/crates/engine/src/cmd/library.rs +++ b/crates/engine/src/cmd/library.rs @@ -470,8 +470,8 @@ impl Library { } } -/// Make `g` a library gradient: no placement, freeform points or swatch links (a linked stop keeps -/// the color it shows), the angle its placement showed (a finite one), and stops in order with +/// Make `g` a library gradient: no placement, freeform points, swatch links or process plates (a +/// linked stop keeps the color it shows), the angle its placement showed (a finite one), and stops in order with /// offsets, opacities and midpoints in range. False when it has fewer than 2 or more than /// [`MAX_STOPS`] stops. fn clean_gradient(g: &mut GradientPaint) -> bool { @@ -490,8 +490,8 @@ fn clean_gradient(g: &mut GradientPaint) -> bool { st.offset = within(st.offset, 0.0, 1.0, 0.0); st.opacity = within(st.opacity, 0.0, 1.0, 1.0); st.midpoint = within(st.midpoint, 0.13, 0.87, 0.5); - st.swatch = None; - st.tint = 1.0; + let color = st.color; + st.set_color(color, None); } g.gradient.stops.sort_by(|a, b| a.offset.total_cmp(&b.offset)); true @@ -1488,29 +1488,15 @@ fn add_to_char_styles(s: &mut Session, p: &Value) -> Result { /// Unlink a library character style's `fill` and `stroke` colors (solid, and each gradient stop) /// from swatches that are not global or spot swatches of `doc`: an unlinked color keeps the color -/// it shows at full tint, as [`clean_gradient`] keeps a library gradient's stops. A link to a +/// it shows at full tint, and an unlinked stop has no process plates, as [`clean_gradient`] keeps +/// a library gradient's stops. A link to a /// global or spot swatch `doc` has stays, and takes that swatch's color. fn unlink_missing_swatches(doc: &vectorcraft_doc::Document, attrs: &mut Map) { let keep = |name: &str| doc.global_color(name).is_some(); for key in ["fill", "stroke"] { let Some(mut paint) = attrs.get(key).and_then(|v| serde_json::from_value::(v.clone()).ok()) else { continue }; - let mut changed = false; - let mut unlink = |swatch: &mut Option, tint: &mut f32| { - if swatch.as_deref().is_some_and(|n| !keep(n)) { - *swatch = None; - *tint = 1.0; - changed = true; - } - }; - match &mut paint { - Paint::Solid { swatch, tint, .. } => unlink(swatch, tint), - Paint::Gradient(g) => { - for st in &mut g.gradient.stops { - unlink(&mut st.swatch, &mut st.tint); - } - } - _ => {} - } + // `map_links` gives an unlinked color full tint, and an unlinked stop no process plates. + let changed = paint.map_links(&mut |_, swatch, _| swatch.take_if(|n| !keep(n.as_str())).is_some()); if changed && let Ok(v) = serde_json::to_value(&paint) { attrs.insert(key.to_string(), v); } diff --git a/crates/engine/src/cmd/linkfiles.rs b/crates/engine/src/cmd/linkfiles.rs index 99295e5c79..fa8ef06856 100644 --- a/crates/engine/src/cmd/linkfiles.rs +++ b/crates/engine/src/cmd/linkfiles.rs @@ -144,9 +144,10 @@ fn find(s: &mut Session, p: &Value) -> Result { None | Some(Value::Null) => None, Some(_) => { // Images and placed documents in opacity-mask art and in the art of symbols, graph - // designs and patterns are named by their ids too (`links.list`). + // designs, patterns and stored brushes are named by their ids too (`links.list`). let ids = ids_param(p, "ids", C)?.unwrap_or_default(); - let kind = |id: &NodeId| st.doc.stored_node(*id).map(|(n, _)| &n.kind); + let doc = super::links::with_brush_art(&st.doc); + let kind = |id: &NodeId| doc.stored_node(*id).map(|(n, _)| &n.kind); if let Some(value) = ids.iter().find(|id| kind(id).is_none()).map(|id| id.0) { return Err(bad(C, format!("no such object id {value}"))); } diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index d37abc85c7..ecc4a12bff 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -27,6 +27,7 @@ use std::path::{Component, Path, PathBuf}; use std::sync::Arc; use serde_json::{Value, json}; +use vectorcraft_brush::stored_art::StoredArt; use vectorcraft_doc::links::{Align, Preserve, hash_bytes}; use vectorcraft_doc::{ Appearance, DataValue, Document, ImageBlob, ImageObject, LinkInfo, Node, NodeId, NodeKind, PageBox, PlacedDocument, PlacementOptions, @@ -44,7 +45,7 @@ pub fn specs() -> Vec { "Check Links", [], None, - "{ids?: [image or placed document ids] (default: every linked image and placed document, in the layers and in opacity-mask art, symbols, graph designs and patterns)} where each linked file is and whether it changed since it was read → {links: [{name, path?, status: ok|modified|missing, ids, found?: path (found away from its path: relative to the document, or by name in its folder), preview: true (showing the low-resolution preview, not the file), refused?: why the path is not followed (another computer, a device or a URL: it counts as missing)}], missing, modified}; under automation read roots, path and found are left out when the file they name is outside the roots", + "{ids?: [image or placed document ids] (default: every linked image and placed document, in the layers and in opacity-mask art, symbols, graph designs, patterns and the art of stored brushes)} where each linked file is and whether it changed since it was read → {links: [{name, path?, status: ok|modified|missing, ids, found?: path (found away from its path: relative to the document, or by name in its folder), preview: true (showing the low-resolution preview, not the file), refused?: why the path is not followed (another computer, a device or a URL: it counts as missing)}], missing, modified}; under automation read roots, path and found are left out when the file they name is outside the roots", has_doc, check ), @@ -53,7 +54,7 @@ pub fn specs() -> Vec { "Update Links", [], None, - "{ids?: [image or placed document ids] (default: the linked images whose file was modified or is showing its preview, and placed documents whose file was modified)} read their linked files again; each keeps its bounds. Images and placed documents inside symbols, graph designs, patterns and opacity masks have ids of their own, as links.list gives them; those that show the same content as one read again are read again too. One undo step → {updated: [ids], missing: [ids], warnings?: [a DCS file's spot plate whose ink a swatch of the document already names, as file.place warns]}", + "{ids?: [image or placed document ids] (default: the linked images whose file was modified or is showing its preview, and placed documents whose file was modified)} read their linked files again; each keeps its bounds. Images and placed documents inside symbols, graph designs, patterns, opacity masks and the art of stored brushes have ids of their own, as links.list gives them; those that show the same content as one read again are read again too. One undo step → {updated: [ids], missing: [ids], warnings?: [a DCS file's spot plate whose ink a swatch of the document already names, as file.place warns]}", has_doc, update ), @@ -71,7 +72,7 @@ pub fn specs() -> Vec { "Relink", [], None, - "{ids?: [image or placed document ids] (default: the selected ones; with folder and nothing selected, every missing link), path | folder, scope?: selected (default: ids) | all (ids and every other object linked to the same file as one of them, in the layers, opacity-mask art, symbols, graph designs and patterns) | missingInFolder (with path: ids, then every other missing link whose file name is in path's folder, each to the file of its name there; names not there are in notFound; with copy, only images are looked for) | each (with paths), paths?: [{ids, path}] (with scope each, in place of ids, path and folder: each link to its own file; an id in two entries is an error), copy?: false (with path or paths, for images of a saved document: copy the file into the document's folder and link to the copy; the names Name.png, Name 2.png … Name 99.png are tried in turn until one is free, which gets the copy, or is a file with the same contents, which is used; an error for a DCS file that reads plate files of its own), preserve?: transforms|bounds|fileDimensions|fit|fill (how the new file takes each image's place this time, as links.placementOptions describes; default: each image's Placement Options; fit keeps the new file's aspect ratio inside the old bounds: Replace)} link images (or placed documents, each showing the same artboard or page of the new file) to the file at path, or each to the file of its link's name in folder; embedded images become linked; each keeps its bounds. One undo step → {relinked: [ids], notFound: [file names], copied?: [{from, to}], kept?: [{from, to}] (with copy; to is the file name alone when the document's folder is outside the automation read roots), warnings?: (as links.update's)}", + "{ids?: [image or placed document ids] (default: the selected ones; with folder and nothing selected, every missing link), path | folder, scope?: selected (default: ids) | all (ids and every other object linked to the same file as one of them, in the layers, opacity-mask art, symbols, graph designs, patterns and the art of stored brushes) | missingInFolder (with path: ids, then every other missing link whose file name is in path's folder, each to the file of its name there; names not there are in notFound; with copy, only images are looked for) | each (with paths), paths?: [{ids, path}] (with scope each, in place of ids, path and folder: each link to its own file; an id in two entries is an error), copy?: false (with path or paths, for images of a saved document: copy the file into the document's folder and link to the copy; the names Name.png, Name 2.png … Name 99.png are tried in turn until one is free, which gets the copy, or is a file with the same contents, which is used; an error for a DCS file that reads plate files of its own), preserve?: transforms|bounds|fileDimensions|fit|fill (how the new file takes each image's place this time, as links.placementOptions describes; default: each image's Placement Options; fit keeps the new file's aspect ratio inside the old bounds: Replace)} link images (or placed documents, each showing the same artboard or page of the new file) to the file at path, or each to the file of its link's name in folder; embedded images become linked; each keeps its bounds. One undo step → {relinked: [ids], notFound: [file names], copied?: [{from, to}], kept?: [{from, to}] (with copy; to is the file name alone when the document's folder is outside the automation read roots), warnings?: (as links.update's)}", has_doc, relink ), @@ -80,7 +81,7 @@ pub fn specs() -> Vec { "Links", [], None, - "{show?: all (default)|missing|modified|embedded, sort?: name|kind (file format)|status (missing, modified, ok, embedded); default: stacking order; top first, dcsTransparency?: false (Show DCS Transparency Interactions: mark the images placed from DCS files that are transparent, themselves or a group or layer holding them, or that overlap a visible object with its own transparency; it looks at every object, so it takes longer)} every image object and placed document the document stores, as the Links panel lists them: those in the layers, then those in opacity-mask art and in the art of symbols, graph designs and patterns (one row per stored object, never one per symbol instance or pattern tile) → {links: [{id, name, linked, status: ok|modified|missing|embedded, format (DCS for an image placed from a DCS file), pixelWidth, pixelHeight, path?, found?: path (found away from its path), page?, preview?: true (showing the saved preview), note?: said of an image past the decode allowance (shown at reduced size, or too large to draw), document?: true (a placed document: pageWidth and pageHeight in pt instead of pixels), dcsTransparency?: true (with dcsTransparency), owner?: {kind: layers|symbol|graphDesign|pattern, name? (of the symbol, graph design or pattern), maskOf?: id (in the opacity-mask art of that object)} (an object outside the layer tree)}], missing, modified, embedded}; under automation read roots, path and found are left out when the file they name is outside the roots", + "{show?: all (default)|missing|modified|embedded, sort?: name|kind (file format)|status (missing, modified, ok, embedded)|size (the linked file's size in bytes as Link Info shows it, smallest first; rows without one, embedded images and missing files whose size is not kept, last; equal sizes by name); default: stacking order; top first, dcsTransparency?: false (Show DCS Transparency Interactions: mark the images placed from DCS files that are transparent, themselves or a group or layer holding them, or that overlap a visible object with its own transparency; it looks at every object, so it takes longer)} every image object and placed document the document stores, as the Links panel lists them: those in the layers, then those in opacity-mask art and in the art of symbols, graph designs, patterns and stored brushes (one row per stored object, never one per symbol instance, pattern tile or brushed stroke) → {links: [{id, name, linked, status: ok|modified|missing|embedded, format (DCS for an image placed from a DCS file), pixelWidth, pixelHeight, path?, found?: path (found away from its path), page?, preview?: true (showing the saved preview), note?: said of an image past the decode allowance (shown at reduced size, or too large to draw), document?: true (a placed document: pageWidth and pageHeight in pt instead of pixels), dcsTransparency?: true (with dcsTransparency), owner?: {kind: layers|symbol|graphDesign|pattern|brush, name? (of the symbol, graph design, pattern or brush), index? (a brush's place in the Brushes panel, from 0), tile?: side|outerCorner|innerCorner|start|end (a pattern brush's tile), maskOf?: id (in the opacity-mask art of that object)} (an object outside the layer tree)}], missing, modified, embedded}; under automation read roots, path and found are left out when the file they name is outside the roots", has_doc, list ), @@ -89,7 +90,7 @@ pub fn specs() -> Vec { "Go To Link", [], None, - "{id?} select image or placed document `id` (default: the first selected one); the Links panel scrolls it into view → {id, bounds: [x0, y0, x1, y1], onCanvas: true}; one in opacity-mask art or in the art of a symbol, graph design or pattern has no place of its own on the canvas: the selection is cleared → {id, onCanvas: false, owner} (owner as links.list gives it)", + "{id?} select image or placed document `id` (default: the first selected one); the Links panel scrolls it into view → {id, bounds: [x0, y0, x1, y1], onCanvas: true}; one in opacity-mask art or in the art of a symbol, graph design, pattern or stored brush has no place of its own on the canvas: the selection is cleared → {id, onCanvas: false, owner} (owner as links.list gives it)", has_doc, go_to ), @@ -198,6 +199,8 @@ pub(crate) fn linked_groups(d: &Document) -> Vec<(String, Vec)> { /// visited before it has (art being edited on a layer and its definition) counts once, by its /// first place; without `ids` its content is still grouped. fn groups(d: &Document, ids: Option<&[NodeId]>) -> Vec { + let view = with_brush_art(d); + let d = &*view; let mut out: Vec = vec![]; let mut index: BTreeMap<(String, String, bool), usize> = BTreeMap::new(); // Looked up for every linked node: a set, not the list (which may repeat an id many times). @@ -234,13 +237,52 @@ fn stored(d: &Document, id: NodeId) -> Option<&Node> { d.stored_node(id).map(|(n, _)| &**n) } +/// `d` with the art of its stored brushes set on it ([`vectorcraft_brush::stored_art`]), so that +/// the images and placed documents in that art are visited and found by their ids as stored art; +/// `d` itself when no stored brush's art holds one or the art is set on it already. +pub(crate) fn with_brush_art(d: &Document) -> Cow<'_, Document> { + if !d.mounted_art.is_empty() { + return Cow::Borrowed(d); + } + let art = StoredArt::read(d); + if art.is_empty() { + return Cow::Borrowed(d); + } + let mut d = d.clone(); + art.mount(&mut d); + Cow::Owned(d) +} + +/// `f` run on `d` with the art of its stored brushes set on it as [`with_brush_art`] sets it; the +/// brushes whose art `f` changed are then written back into the library, the color masks of its +/// images made for their pixels first. The ids it gives that art are the ones [`with_brush_art`] +/// gives it in the same document. +pub(crate) fn editing_brush_art(d: &mut Document, f: impl FnOnce(&mut Document) -> T) -> T { + if !d.mounted_art.is_empty() { + return f(d); + } + let art = StoredArt::read(d); + if art.is_empty() { + return f(d); + } + art.mount(d); + let before: Vec> = d.mounted_art.iter().map(|(n, _)| n.clone()).collect(); + let out = f(d); + if d.mounted_art.len() != before.len() || d.mounted_art.iter().zip(&before).any(|((n, _), b)| !Arc::ptr_eq(n, b)) { + super::refresh_color_masks(None, d); + } + art.write_back(d); + out +} + /// Of `ids`, the objects of `d` outside the layer tree (where [`Document::node`] finds none). fn nested_ids(d: &Document, ids: &[NodeId]) -> std::collections::HashSet { ids.iter().copied().filter(|id| d.node(*id).is_none()).collect() } /// `links.list`'s `owner` of an object stored at `place` of `d`, when it is not in the layer tree -/// itself: `{kind: layers|symbol|graphDesign|pattern, name?, maskOf?}`. +/// itself: `{kind: layers|symbol|graphDesign|pattern, name?, maskOf?}`, or for one in the art of a +/// stored brush, `{kind: brush, name, index, tile?, maskOf?}`. fn owner_json(d: &Document, place: StoredPlace) -> Option { if place.in_layers() { return None; @@ -250,6 +292,7 @@ fn owner_json(d: &Document, place: StoredPlace) -> Option { StoredRoot::Symbol(i) => json!({ "kind": "symbol", "name": d.symbols.get(i).map(|s| s.name.as_str()) }), StoredRoot::GraphDesign(i) => json!({ "kind": "graphDesign", "name": d.graph_designs.get(i).map(|g| g.name.as_str()) }), StoredRoot::Pattern { pattern, .. } => json!({ "kind": "pattern", "name": d.patterns.get(pattern).map(|p| p.name.as_str()) }), + StoredRoot::Mounted(i) => d.mounted_art.get(i).map_or_else(|| json!({}), |(_, owner)| owner.clone()), }; if let Some(m) = place.mask_of { owner["maskOf"] = json!(m.0); @@ -479,7 +522,8 @@ pub(crate) fn linked_files(d: &Document, base: LinkBase) -> Vec { /// again (Preferences › Use Low Resolution Proxy for Linked EPS keeps the preview on screen only). pub(crate) fn full_linked_images<'a>(d: &'a Document, base: LinkBase) -> (Cow<'a, Document>, Vec) { let mut keys = BTreeSet::new(); - d.visit_images(|_, im| { + // The art of the stored brushes draws its images too. + with_brush_art(d).visit_images(|_, im| { if im.link.is_some() && d.images.get(&im.key).is_some_and(ImageBlob::is_proxy) { keys.insert(im.key.clone()); } @@ -763,7 +807,7 @@ struct Nested<'a> { impl Nested<'_> { /// Every root of `d`: the layers (whose own objects are left alone), then the art of symbols, - /// graph designs and patterns. + /// graph designs and patterns, then [`Document::mounted_art`]. fn run(mut self, d: &mut Document) { let first = d.peek_next_id(); self.next = first; @@ -774,7 +818,7 @@ impl Nested<'_> { for root in d.symbols.iter_mut().map(|s| &mut s.art).chain(d.graph_designs.iter_mut().map(|g| &mut g.art)) { self.root(root); } - for root in d.patterns.iter_mut().flat_map(|p| &mut p.art) { + for root in d.patterns.iter_mut().flat_map(|p| &mut p.art).chain(d.mounted_art.iter_mut().map(|(n, _)| n)) { self.root(root); } for _ in first..self.next { @@ -1306,8 +1350,14 @@ impl Resolved { /// found away from their path take the new path. A link nothing is known of whose image, or placed /// document, shows a preview (a file another app wrote kept only that) was never read: its file is /// read now, into the object's bounds, which isn't a change to report. A placed document whose -/// file's bytes are gone isn't showing a preview. Nothing here is an undo step. +/// file's bytes are gone isn't showing a preview. Links in the art of the stored brushes count too, +/// and that art keeps the ids they are listed by. Nothing here is an undo step. pub fn resolve(d: &mut Document, base: LinkBase, update: bool, low_res_proxy_eps: bool) -> Resolved { + editing_brush_art(d, |d| resolve_links(d, base, update, low_res_proxy_eps)) +} + +/// [`resolve`] in the art `d` stores. +fn resolve_links(d: &mut Document, base: LinkBase, update: bool, low_res_proxy_eps: bool) -> Resolved { let mut out = Resolved::default(); // The image (with its preview) and hash of each file read for a preview here, by path: images // of other keys linking to the same file share them, rather than each reading, decoding and @@ -1458,8 +1508,8 @@ fn set_links(d: &mut Document, ids: &[NodeId], link: &LinkInfo) { } /// Placed documents of the document saved at `path` (document `saved` of `s`) in the other open -/// documents, in the layers, symbols, graph designs, patterns and opacity masks: read again from -/// the new file, each as one Update Links step of its document. +/// documents, in the layers, symbols, graph designs, patterns, opacity masks and the art of the +/// stored brushes: read again from the new file, each as one Update Links step of its document. pub(crate) fn refresh_placed(s: &mut Session, saved: u64, path: &str) { let path = absolute_path(path); let targets: Vec = s @@ -1469,7 +1519,7 @@ pub(crate) fn refresh_placed(s: &mut Session, saved: u64, path: &str) { .filter(|(_, st)| st.uid != saved) .filter(|(_, st)| { let mut placed = false; - st.doc.visit_placed(|_, p| placed |= p.link.path == path); + with_brush_art(&st.doc).visit_placed(|_, p| placed |= p.link.path == path); placed }) .map(|(i, _)| i) @@ -1526,7 +1576,7 @@ fn link_target(link: &LinkInfo, base: LinkBase) -> PathBuf { /// `d` (looking from `base`) as saved to `dest`: the links' paths relative to its folder written /// in; `None` when they are already. A link whose file is not at its path is written relative to /// where its file is found, else to the place its relative path names. Links in the layers, -/// symbols, graph designs, patterns and opacity masks are all set. +/// symbols, graph designs, patterns, opacity masks and the art of the stored brushes are all set. pub fn with_relative_paths(d: &Document, base: LinkBase, dest: &str) -> Option { let dest = absolute_path(dest); let dir = Path::new(&dest).parent()?; @@ -1535,23 +1585,29 @@ pub fn with_relative_paths(d: &Document, base: LinkBase, dest: &str) -> Option); @@ -1706,7 +1762,9 @@ fn update_where(s: &mut Session, ids: Option>, path: Option<&str>) - let updated: Vec = reads.iter().flat_map(|(g, _)| ids_json(&g.ids)).collect(); let warnings = spot_swatch_notes(&st.doc, reads.iter().map(|(_, read)| read)); if !reads.is_empty() { - s.edit("Update Links", |d, _| reads.into_iter().try_for_each(|(g, read)| install_read(d, &g.ids, read, None, Some(&g))))?; + s.edit("Update Links", |d, _| { + editing_brush_art(d, |d| reads.into_iter().try_for_each(|(g, read)| install_read(d, &g.ids, read, None, Some(&g)))) + })?; } let mut out = json!({ "updated": updated, "missing": missing }); if !warnings.is_empty() { @@ -1833,9 +1891,10 @@ fn relink(s: &mut Session, p: &Value) -> Result { Some(Path::new(&doc).parent().map(Path::to_path_buf).ok_or_else(no_folder)?) } }; + let doc = with_brush_art(&st.doc); // An image or a placed document, with its link. let image = |id: &NodeId| { - stored(&st.doc, *id).and_then(|n| match &n.kind { + stored(&doc, *id).and_then(|n| match &n.kind { NodeKind::Image(im) => Some(im.link.as_ref()), NodeKind::PlacedDocument(p) => Some(Some(&p.link)), _ => None, @@ -1865,7 +1924,7 @@ fn relink(s: &mut Session, p: &Value) -> Result { let paths: BTreeSet<&str> = ids.iter().filter_map(|id| image(id).flatten()).map(|l| l.path.as_str()).collect(); let mut given: BTreeSet = ids.iter().copied().collect(); let mut more = vec![]; - st.doc.visit_stored(|n, _| { + doc.visit_stored(|n, _| { if let Some((l, _, _)) = linked(n) && paths.contains(l.path.as_str()) && n.id.0 != 0 @@ -1876,7 +1935,7 @@ fn relink(s: &mut Session, p: &Value) -> Result { }); ids.extend(more); } - if copy_to.is_some() && ids.iter().any(|id| matches!(stored(&st.doc, *id).map(|n| &n.kind), Some(NodeKind::PlacedDocument(_)))) { + if copy_to.is_some() && ids.iter().any(|id| matches!(stored(&doc, *id).map(|n| &n.kind), Some(NodeKind::PlacedDocument(_)))) { return Err(bad(C, "copy takes images only: relink placed documents where their files are")); } // (ids, the file) per file to read. @@ -1912,7 +1971,7 @@ fn relink(s: &mut Session, p: &Value) -> Result { let mut images = vec![]; let mut documents: Vec<((u32, bool, PageBox), Vec)> = vec![]; for id in ids { - match stored(&st.doc, id).map(|n| &n.kind) { + match stored(&doc, id).map(|n| &n.kind) { Some(NodeKind::PlacedDocument(pl)) => { let k = (pl.page(), pl.bounding, pl.page_box); match documents.iter_mut().find(|(e, _)| *e == k) { @@ -1963,9 +2022,10 @@ fn relink(s: &mut Session, p: &Value) -> Result { } } let relinked: Vec = reads.iter().flat_map(|(ids, _)| ids_json(ids)).collect(); + drop(doc); let warnings = spot_swatch_notes(&s.doc()?.doc, reads.iter().map(|(_, read)| read)); if !reads.is_empty() { - s.edit("Relink", |d, _| reads.into_iter().try_for_each(|(ids, read)| install_read(d, &ids, read, preserve, None)))?; + s.edit("Relink", |d, _| editing_brush_art(d, |d| reads.into_iter().try_for_each(|(ids, read)| install_read(d, &ids, read, preserve, None))))?; } not_found.sort(); not_found.dedup(); @@ -2075,14 +2135,15 @@ fn selected_images(st: &crate::DocState, keep: impl Fn(&ImageObject) -> bool) -> st.selection.objects.iter().copied().filter(|id| image_of(&st.doc, *id).is_some_and(&keep)).collect() } -/// `id`, else the first selected image. -fn image_param(st: &crate::DocState, p: &Value, cmd: &str) -> Result { +/// `id` (looked up in `doc`, the document of `st` as [`with_brush_art`] gives it), else the first +/// selected image. +fn image_param(st: &crate::DocState, doc: &Document, p: &Value, cmd: &str) -> Result { let id = object_param(p, "id", cmd)? .or_else(|| selected_images(st, |_| true).first().copied()) .ok_or_else(|| bad(cmd, "select an image, or pass id"))?; - match image_of(&st.doc, id) { + match image_of(doc, id) { Some(_) => Ok(id), - None if stored(&st.doc, id).is_none() => Err(crate::EngineError::NoNode(id)), + None if stored(doc, id).is_none() => Err(crate::EngineError::NoNode(id)), None => Err(bad(cmd, format!("object {} is not an image", id.0))), } } @@ -2105,13 +2166,14 @@ fn placement_of(d: &Document, id: NodeId) -> Option { } } -/// `id`, else the first selected image or placed document. -fn linked_param(st: &crate::DocState, p: &Value, cmd: &str) -> Result { - let first = || st.selection.objects.iter().copied().find(|id| placement_of(&st.doc, *id).is_some()); +/// `id` (looked up in `doc`, the document of `st` as [`with_brush_art`] gives it), else the first +/// selected image or placed document. +fn linked_param(st: &crate::DocState, doc: &Document, p: &Value, cmd: &str) -> Result { + let first = || st.selection.objects.iter().copied().find(|id| placement_of(doc, *id).is_some()); let id = object_param(p, "id", cmd)?.or_else(first).ok_or_else(|| bad(cmd, "select an image, or pass id"))?; - match placement_of(&st.doc, id) { + match placement_of(doc, id) { Some(_) => Ok(id), - None if stored(&st.doc, id).is_none() => Err(crate::EngineError::NoNode(id)), + None if stored(doc, id).is_none() => Err(crate::EngineError::NoNode(id)), None => Err(bad(cmd, format!("object {} is not an image or a linked file", id.0))), } } @@ -2149,6 +2211,16 @@ fn document_row(p: &PlacedDocument) -> Value { json!({ "format": pdf.map_or("VectorCraft", |f| f.label), "document": true, "pageWidth": p.width, "pageHeight": p.height }) } +/// The size in bytes of the file that link `l` (of `st`) names, as Link Info shows it: the file's +/// size now, else the size the document keeps of it when the caller may see its path. +fn link_file_size(st: &crate::DocState, l: &LinkInfo) -> Option { + let doc_path = LinkBase::of(st).doc; + let kept = l.size.filter(|_| path_shown(&l.path, doc_path)); + let roots = crate::file_access::current().or_else(|| st.opened_by.clone()); + let now = crate::file_access::confine(roots.as_ref(), || fileio::document_path(&l.path, doc_path).ok().as_deref().and_then(file_stamp)); + now.map(|s| s.0).or(kept) +} + /// Sort rank of a `links.list` status: missing, modified, ok, embedded. fn status_rank(status: &str) -> usize { ["missing", "modified", "ok", "embedded"].iter().position(|s| *s == status).unwrap_or(4) @@ -2215,13 +2287,21 @@ fn list(s: &mut Session, p: &Value) -> Result { if !matches!(show, "all" | "missing" | "modified" | "embedded") { return Err(bad(C, format!("show `{show}`: all, missing, modified or embedded"))); } + let sort = str_param(p, "sort"); + if let Some(x) = sort.filter(|x| !matches!(*x, "name" | "kind" | "status" | "size")) { + return Err(bad(C, format!("sort `{x}`: name, kind, status or size"))); + } let interactions = if switch_or(p, "dcsTransparency", false, C)? { dcs_transparency(&st.doc) } else { BTreeSet::new() }; let statuses = statuses(st); + // The file size of each listed row's link, read only to sort by size. + let mut sizes: BTreeMap = BTreeMap::new(); // The layer tree's objects, top first as the Layers panel lists them, then the others in the - // order they are stored (opacity-mask art, symbols, graph designs, patterns), each once. + // order they are stored (opacity-mask art, symbols, graph designs, patterns, the art of the + // stored brushes), each once. + let doc = with_brush_art(&st.doc); let (mut objects, mut nested) = (vec![], vec![]); let mut seen = std::collections::HashSet::new(); - st.doc.visit_stored(|n, place| { + doc.visit_stored(|n, place| { if matches!(n.kind, NodeKind::Image(_) | NodeKind::PlacedDocument(_)) && n.id.0 != 0 && seen.insert(n.id) { if place.in_layers() { objects.push((n, place)) } else { nested.push((n, place)) } } @@ -2262,6 +2342,11 @@ fn list(s: &mut Session, p: &Value) -> Result { } let doc_path = LinkBase::of(st).doc; if let Some(l) = link { + if sort == Some("size") + && let Some(size) = link_file_size(st, l) + { + sizes.insert(n.id.0, size); + } note_path(&mut row, "path", &l.path, doc_path); if let Some(page) = l.page { row["page"] = json!(page); @@ -2273,7 +2358,7 @@ fn list(s: &mut Session, p: &Value) -> Result { if preview { row["preview"] = json!(true); } - if let Some(owner) = owner_json(&st.doc, place) { + if let Some(owner) = owner_json(&doc, place) { row["owner"] = owner; } if interactions.contains(&n.id) { @@ -2282,12 +2367,17 @@ fn list(s: &mut Session, p: &Value) -> Result { rows.push(row); } let text = |r: &Value, k: &str| r[k].as_str().unwrap_or_default().to_lowercase(); - match str_param(p, "sort") { - None => {} + match sort { Some("name") => rows.sort_by_cached_key(|r| text(r, "name")), Some("kind") => rows.sort_by_cached_key(|r| (text(r, "format"), text(r, "name"))), Some("status") => rows.sort_by_cached_key(|r| (status_rank(r["status"].as_str().unwrap_or_default()), text(r, "name"))), - Some(x) => return Err(bad(C, format!("sort `{x}`: name, kind or status"))), + // Smallest file first; rows without a file size (embedded images, a missing file whose + // size the document does not keep) come last; equal sizes by name. + Some("size") => rows.sort_by_cached_key(|r| { + let size = r["id"].as_u64().and_then(|id| sizes.get(&id).copied()); + (size.is_none(), size.unwrap_or(0), text(r, "name")) + }), + _ => {} } let count = |k: &str| counts.get(k).copied().unwrap_or(0); Ok(json!({ "links": rows, "missing": count("missing"), "modified": count("modified"), "embedded": count("embedded") })) @@ -2295,10 +2385,13 @@ fn list(s: &mut Session, p: &Value) -> Result { fn go_to(s: &mut Session, p: &Value) -> Result { let st = s.doc()?; - let id = linked_param(st, p, "links.goTo")?; - // An object in mask art or a definition has no place of its own on the canvas: the selection - // is cleared, and the reply names what holds it. - if let Some(owner) = st.doc.stored_node(id).and_then(|(_, place)| owner_json(&st.doc, place)) { + let doc = with_brush_art(&st.doc); + let id = linked_param(st, &doc, p, "links.goTo")?; + // An object in mask art, a definition or a stored brush's art has no place of its own on the + // canvas: the selection is cleared, and the reply names what holds it. + let owner = doc.stored_node(id).and_then(|(_, place)| owner_json(&doc, place)); + drop(doc); + if let Some(owner) = owner { s.select(|_, sel| sel.set([]))?; return Ok(json!({ "id": id.0, "onCanvas": false, "owner": owner })); } @@ -2310,7 +2403,8 @@ fn go_to(s: &mut Session, p: &Value) -> Result { fn embed(s: &mut Session, p: &Value) -> Result { const C: &str = "links.embed"; let st = s.doc()?; - let kind = |id: &NodeId| stored(&st.doc, *id).map(|n| &n.kind); + let doc = with_brush_art(&st.doc); + let kind = |id: &NodeId| stored(&doc, *id).map(|n| &n.kind); let linked = |id: &NodeId| match kind(id) { Some(NodeKind::Image(im)) => im.link.is_some(), Some(NodeKind::PlacedDocument(_)) => true, @@ -2362,17 +2456,20 @@ fn embed(s: &mut Session, p: &Value) -> Result { _ => missing.extend(g.ids), } } + drop(doc); if !done.is_empty() || !documents.is_empty() { s.edit("Embed", |d, _| { - for (ids, read) in reads { - install(d, &ids, read, Some(Preserve::Bounds), None)?; - } - for id in &done { - if let Some(Node { kind: NodeKind::Image(im), .. }) = d.stored_node_mut(*id) { - im.link = None; + editing_brush_art(d, |d| { + for (ids, read) in reads { + install(d, &ids, read, Some(Preserve::Bounds), None)?; } - } - documents.iter().try_for_each(|id| super::place::document::expand(d, *id, C)) + for id in &done { + if let Some(Node { kind: NodeKind::Image(im), .. }) = d.stored_node_mut(*id) { + im.link = None; + } + } + documents.iter().try_for_each(|id| super::place::document::expand(d, *id, C)) + }) })?; } done.extend(documents); @@ -2395,9 +2492,10 @@ fn convert_image(bytes: &[u8], ext: &str) -> std::result::Result, String fn unembed(s: &mut Session, p: &Value) -> Result { const C: &str = "links.unembed"; let st = s.doc()?; - let id = image_param(st, p, C)?; - let n = stored(&st.doc, id).ok_or(crate::EngineError::NoNode(id))?; - let im = image_of(&st.doc, id).ok_or_else(|| bad(C, format!("object {} is not an image", id.0)))?; + let doc = with_brush_art(&st.doc); + let id = image_param(st, &doc, p, C)?; + let n = stored(&doc, id).ok_or(crate::EngineError::NoNode(id))?; + let im = image_of(&doc, id).ok_or_else(|| bad(C, format!("object {} is not an image", id.0)))?; if im.link.is_some() { return Err(bad(C, format!("image {} is linked already", id.0))); } @@ -2422,7 +2520,8 @@ fn unembed(s: &mut Session, p: &Value) -> Result { let img = linked_image(&bytes, Some(&path))?; write_file(&path, &bytes)?; let read = (link_info(&path, &bytes), img); - s.edit("Unembed", |d, _| install(d, &[id], read, Some(Preserve::Bounds), None))?; + drop(doc); + s.edit("Unembed", |d, _| editing_brush_art(d, |d| install(d, &[id], read, Some(Preserve::Bounds), None)))?; Ok(json!({ "id": id.0, "path": path })) } @@ -2480,9 +2579,10 @@ fn scale_rotation(xf: Affine, (px, py): (f64, f64)) -> (Value, Value) { (json!([a.hypot(b) / px * 100.0, c.hypot(d) / py * 100.0]), json!((-b).atan2(a).to_degrees() + 0.0)) } -/// Link Info of placed document `id`. -fn placed_info(st: &crate::DocState, id: NodeId) -> Result { - let n = stored(&st.doc, id).ok_or(crate::EngineError::NoNode(id))?; +/// Link Info of placed document `id` (looked up in `doc`, the document of `st` as +/// [`with_brush_art`] gives it). +fn placed_info(st: &crate::DocState, doc: &Document, id: NodeId) -> Result { + let n = stored(doc, id).ok_or(crate::EngineError::NoNode(id))?; let NodeKind::PlacedDocument(pl) = &n.kind else { return Err(bad("links.info", format!("object {} is not a placed document", id.0))) }; let size = n.geometric_bounds().unwrap_or_default(); let (scale, rotation) = scale_rotation(pl.xf, (1.0, 1.0)); @@ -2507,13 +2607,19 @@ fn placed_info(st: &crate::DocState, id: NodeId) -> Result { fn info(s: &mut Session, p: &Value) -> Result { const C: &str = "links.info"; - let id = linked_param(s.doc()?, p, C)?; - if image_of(&s.doc()?.doc, id).is_none() { - return placed_info(s.doc()?, id); - } + let id = { + let st = s.doc()?; + let doc = with_brush_art(&st.doc); + let id = linked_param(st, &doc, p, C)?; + if image_of(&doc, id).is_none() { + return placed_info(st, &doc, id); + } + id + }; let mut out = super::place::image_info(s, &json!({ "id": id.0 }))?; let st = s.doc()?; - let im = image_of(&st.doc, id).ok_or_else(|| bad(C, format!("object {} is not an image", id.0)))?; + let doc = with_brush_art(&st.doc); + let im = image_of(&doc, id).ok_or_else(|| bad(C, format!("object {} is not an image", id.0)))?; let (px, py) = file_pt(&st.doc, &im.key); out["effectivePpi"] = out["ppi"].take(); out["ppi"] = json!([72.0 / px, 72.0 / py]); @@ -2530,9 +2636,10 @@ fn info(s: &mut Session, p: &Value) -> Result { fn placement_options(s: &mut Session, p: &Value) -> Result { const C: &str = "links.placementOptions"; let st = s.doc()?; + let doc = with_brush_art(&st.doc); let ids = - ids_param(p, "ids", C)?.unwrap_or_else(|| st.selection.objects.iter().copied().filter(|id| placement_of(&st.doc, *id).is_some()).collect()); - if let Some(id) = ids.iter().find(|id| placement_of(&st.doc, **id).is_none()) { + ids_param(p, "ids", C)?.unwrap_or_else(|| st.selection.objects.iter().copied().filter(|id| placement_of(&doc, *id).is_some()).collect()); + if let Some(id) = ids.iter().find(|id| placement_of(&doc, **id).is_none()) { return Err(bad(C, format!("object {} is not an image or a linked file", id.0))); } if ids.is_empty() { @@ -2551,7 +2658,8 @@ fn placement_options(s: &mut Session, p: &Value) -> Result { None | Some(Value::Null) => None, Some(v) => Some(v.as_bool().ok_or_else(|| bad(C, "clip must be true or false"))?), }; - let first = ids.first().and_then(|id| placement_of(&st.doc, *id)).unwrap_or_default(); + let first = ids.first().and_then(|id| placement_of(&doc, *id)).unwrap_or_default(); + drop(doc); if preserve.is_none() && align.is_none() && clip.is_none() { return Ok(json!({ "placement": placement_json(first) })); } @@ -2561,11 +2669,13 @@ fn placement_options(s: &mut Session, p: &Value) -> Result { o.clip = clip.unwrap_or(o.clip); }; s.edit("Placement Options", |d, _| { - for id in &ids { - if let Some(o) = d.stored_node_mut(*id).and_then(placement_mut) { - set(o); + editing_brush_art(d, |d| { + for id in &ids { + if let Some(o) = d.stored_node_mut(*id).and_then(placement_mut) { + set(o); + } } - } + }); Ok(()) })?; let mut shown = first; diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index 6ffdb04a5c..b86f260cd8 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -251,7 +251,7 @@ pub fn specs() -> Vec { "Object Properties", [], None, - "{ids?|id?, name?, visible?, locked? (visible: false or locked: true deselects every selected object hidden or locked after the call, the key object included), opacity?: 0..100, blend?: \"Multiply\"…, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, data?: {key: \"value\" | null (removes it)} (the object's own data, SVG data-* attributes: {pivot: \"100,180\"} is data-pivot; document.node → attrs.data)}. On a path directly in a graph series, the graph also stores the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, the graph stores the label's opacity and blend mode for every label of its kind", + "{ids?|id?, name?, visible?, locked? (visible: false or locked: true deselects every selected object hidden or locked after the call, the key object included), opacity?: 0..100, blend?: \"Multiply\"…, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, data?: {key: \"value\" | null (removes it)} (the object's own data, SVG data-* attributes: {pivot: \"100,180\"} is data-pivot; document.node → attrs.data)}. On a path directly in a graph series, the graph also stores the object's opacity and blend mode, and on a series group the group's opacity, blend mode, isolate, knockout and knockoutShape (exceptions: docs/mcp.md); on a graph label, the graph stores the label's opacity and blend mode for every label of its kind", has_doc, set_props ), diff --git a/crates/engine/src/cmd/object/props.rs b/crates/engine/src/cmd/object/props.rs index bd00b6b323..54ad23eb2f 100644 --- a/crates/engine/src/cmd/object/props.rs +++ b/crates/engine/src/cmd/object/props.rs @@ -68,8 +68,14 @@ pub(super) fn set_props(s: &mut Session, p: &Value) -> Result { // A graph keeps the object opacity and blend mode set on a mark of a series for the whole series, and set on a label // for its kind of label, so a value a mark or label already has still replaces the one another left on the graph. let transparency = opacity.is_some() || blend.is_some(); - let stores = - || transparency && (crate::cmd::graph::series_object_opacity_differs(d, &ids) || crate::cmd::graph::label_object_opacity_differs(d, &ids)); + // A series group's isolation, knockout and knockout shape are kept for the group alone. + let group_only = !transparency && ["isolate", "knockout", "knockoutShape"].iter().any(|k| p.get(*k).is_some()); + let kept = if group_only { crate::cmd::graph::series_groups_among(d, &ids) } else { ids.clone() }; + let stores = || { + (transparency || group_only) + && (crate::cmd::graph::series_object_opacity_differs(d, &kept) + || transparency && crate::cmd::graph::label_object_opacity_differs(d, &ids)) + }; if ids.iter().all(|id| d.node(*id).is_some_and(has_values)) && !stores() { // Hidden or locked objects can't stay selected. if hides { @@ -123,8 +129,10 @@ pub(super) fn set_props(s: &mut Session, p: &Value) -> Result { }); } } + if transparency || group_only { + crate::cmd::graph::capture_series_object_opacity(d, &kept); + } if transparency { - crate::cmd::graph::capture_series_object_opacity(d, &ids); crate::cmd::graph::capture_label_object_opacity(d, &ids); } // Hidden or locked objects can't stay selected. diff --git a/crates/engine/src/cmd/opacitymask.rs b/crates/engine/src/cmd/opacitymask.rs index 75d5852ea2..ac3c780c11 100644 --- a/crates/engine/src/cmd/opacitymask.rs +++ b/crates/engine/src/cmd/opacitymask.rs @@ -472,7 +472,7 @@ impl Session { pub fn transparency_info(&self) -> TransparencyInfo { match (self.active(), transparency_targets(self, &Value::Null)) { (Some(st), Ok(ids)) => { - let points = super::paint::picked_mesh_points_of(self, &ids); + let points = self.mesh_points_picked(); TransparencyInfo::of(&st.doc, ids).with_mesh_points(&st.doc, points) } _ => TransparencyInfo::default(), @@ -483,7 +483,8 @@ impl Session { fn info(s: &mut Session, p: &Value) -> Result { let st = s.doc()?; let ids = transparency_targets(s, p)?; - let points = super::paint::picked_mesh_points_of(s, &ids); + // The points `transparency.set` with the same `ids` (or none) fades. + let points = if p.get("ids").is_none() && p.get("id").is_none() { s.mesh_points_picked() } else { super::paint::picked_mesh_points_of(s, &ids) }; let i = TransparencyInfo::of(&st.doc, ids).with_mesh_points(&st.doc, points); Ok(json!({ "ids": i.ids.iter().map(|id| id.0).collect::>(), diff --git a/crates/engine/src/cmd/package.rs b/crates/engine/src/cmd/package.rs index 8d6f53d55b..315a737c59 100644 --- a/crates/engine/src/cmd/package.rs +++ b/crates/engine/src/cmd/package.rs @@ -229,7 +229,7 @@ impl<'a> Collector<'a> { Some((d, base)) => super::links::linked_files(d, base), None => super::links::linked_files(doc, LinkBase::file(Some(source))), }; - doc.visit_placed(|_, p| { + super::links::with_brush_art(doc).visit_placed(|_, p| { let page = (p.link.page.unwrap_or(1), p.bounding, p.page_box); let pages = placed.entry(p.link.path.clone()).or_default(); if !pages.contains(&page) { @@ -389,16 +389,20 @@ impl<'a> Collector<'a> { } if self.opts.relink { // The child files have already been rewritten; the hash and size of each - // target must reflect the *packaged* bytes rather than the original. - doc.update_links(|link: &mut LinkInfo| { - if let Some(copy) = local.get(&link.path) { - let relative = relative_in_package(destination, ©.name); - link.path = self.root.as_ref().map_or_else(|| copy.name.clone(), |r| r.join(©.name).to_string_lossy().into_owned()); - link.relative = Some(relative); - link.size = copy.size; - link.hash = copy.hash.clone(); - link.modified = None; - } + // target must reflect the *packaged* bytes rather than the original. The links in the + // art of the stored brushes are written back into the brush library. + let root = &self.root; + super::links::editing_brush_art(doc, |doc| { + doc.update_links(|link: &mut LinkInfo| { + if let Some(copy) = local.get(&link.path) { + let relative = relative_in_package(destination, ©.name); + link.path = root.as_ref().map_or_else(|| copy.name.clone(), |r| r.join(©.name).to_string_lossy().into_owned()); + link.relative = Some(relative); + link.size = copy.size; + link.hash = copy.hash.clone(); + link.modified = None; + } + }) }); } if let Some(s) = self.sections.get_mut(section) { diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index e7b89ade16..ccdb86197b 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|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). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did → {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 color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids 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). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did → {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) ), @@ -81,7 +81,7 @@ pub fn specs() -> Vec { "Transparency", ["Window", "Transparency"], None, - "{ids?|id?, opacity?: 0..100, blend?: name, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, item?: appearance item index|null, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} for `ids`, the selection, or the object whose opacity mask is being edited; opacity and blend go to the targeted fill/stroke item (omitted: the Appearance panel's active item, else the objects; a gradient mesh point last clicked with the Mesh tool or Direct Selection takes the opacity itself). With an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, opacity and blend change that object for this instance only (isolate, knockout, knockoutShape, aligned and target are refused). On a path directly in a graph series (for a fill or stroke item, a series group's id stands for those paths), the graph also stores the opacity and blend mode of the object and of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, the graph stores the label's object opacity and blend mode for every label of its kind, and with `item` its topmost visible fill and stroke rows too", + "{ids?|id?, opacity?: 0..100, blend?: name, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, item?: appearance item index|null, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} for `ids`, the selection, or the object whose opacity mask is being edited; opacity and blend go to the targeted fill/stroke item (omitted: the Appearance panel's active item, else the objects; when every target is a gradient mesh with points picked by the Mesh tool, Direct Selection or the Lasso, those points take the opacity themselves). With an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, opacity and blend change that object for this instance only (isolate, knockout, knockoutShape, aligned and target are refused). On a path directly in a graph series (for a fill or stroke item, a series group's id stands for those paths), the graph also stores the opacity and blend mode of the object and of the topmost visible fill and stroke, and on a series group without an item, the group's own opacity, blend mode, isolate, knockout and knockoutShape (exceptions: docs/mcp.md); on a graph label, the graph stores the label's object opacity and blend mode for every label of its kind, and with `item` its topmost visible fill and stroke rows too", has_doc, transparency ), @@ -154,7 +154,7 @@ pub fn proxy_specs() -> Vec { "Fill and Stroke", [], None, - "{} → {fill, stroke: the paints the Fill/Stroke proxies show (the Appearance panel's active item for the proxy of its kind, else the first selected object's, a group's first painted object's, type: its first run's; else the defaults for new art), fillActive, fillMixed, strokeMixed: the selected objects' (or a selected group's contents') fills (strokes) differ, shown as a \"?\" proxy}", + "{} → {fill, stroke: the paints the Fill/Stroke proxies show (the Appearance panel's active item for the proxy of its kind, else the first selected object's, a group's first painted object's, type: its first run's; else the defaults for new art; when that object is a gradient mesh with points picked by the Mesh tool, Direct Selection or the Lasso and no fill item is active, the fill is its first picked point's color), fillActive, fillMixed, strokeMixed: the selected objects' (or a selected group's contents') fills (strokes) differ, shown as a \"?\" proxy (a gradient mesh with points picked counts with their colors)}", always, proxies ), @@ -179,9 +179,13 @@ impl Session { /// The fill and stroke the Fill/Stroke proxies show: the Appearance panel's active item (in the /// first selected object's own stack) for the proxy of its kind, else the first selected /// object's (a group's first painted object's; type: its first run's), else the defaults for - /// new art. + /// new art. When the object whose fill the proxy shows is a gradient mesh with points picked + /// ([`Session::fill_mesh_points`]), the fill is its first picked point's color, which a solid + /// fill color changes. pub fn proxy_paints(&self) -> (Paint, Paint) { + let points = self.fill_mesh_points(); let show = |stroke: bool| match self.proxy_source(stroke) { + Some((n, None)) if !stroke && let Some(c) = picked_colors(&n, &points).first() => Paint::solid(*c), Some((n, item)) => proxy_paint(&n, stroke, item), None if stroke => self.paint.stroke.clone(), None => self.paint.fill.clone(), @@ -273,6 +277,13 @@ impl DocState { /// each selected object's own stack is compared. One walk of the document, so callers that ask /// every frame cache it by revision. pub fn proxy_mixed(&self, item: Option) -> (bool, bool) { + self.proxy_mixed_with(item, &[]) + } + + /// [`DocState::proxy_mixed`] with the gradient mesh points a solid fill color recolors + /// (`points`, see [`Session::fill_mesh_points`]): a mesh among them counts with the colors of + /// its picked points instead of its fill. + fn proxy_mixed_with(&self, item: Option, points: &[(NodeId, Vec)]) -> (bool, bool) { if self.selection.is_empty() { return (false, false); } @@ -291,7 +302,10 @@ impl DocState { let differ = |stroke: bool| { let item = first.and_then(|f| f.appearance.item_of_kind(item, !stroke)); let set = if item.is_some() { &selected } else { &nodes }; - let mut paints = set.iter().map(|n| proxy_paint(n, stroke, item)); + let mut paints = set.iter().flat_map(|n| match picked_colors(n, if stroke || item.is_some() { &[] } else { points }) { + c if c.is_empty() => vec![proxy_paint(n, stroke, item)], + c => c.into_iter().map(Paint::solid).collect(), + }); let Some(p0) = paints.next() else { return false }; paints.any(|p| !same_in_proxy(&p0, &p)) }; @@ -313,8 +327,9 @@ impl DocState { impl Session { /// [`DocState::proxy_mixed`] of the active document for the Appearance panel's active item. + /// A gradient mesh with points picked ([`Session::fill_mesh_points`]) counts with their colors. pub fn proxy_mixed(&self) -> (bool, bool) { - self.active().map_or((false, false), |st| st.proxy_mixed(self.appearance_item())) + self.active().map_or((false, false), |st| st.proxy_mixed_with(self.appearance_item(), &self.fill_mesh_points())) } } @@ -539,8 +554,8 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool) let selected = item.targets(s, p)?; let ids = super::graph::paint_targets(&s.doc()?.doc, &selected); let paint = if span { placed_across(&s.doc()?.doc, &ids, paint, p, fill) } else { paint }; - // The gradient mesh points picked with the Mesh tool or Direct Selection: a solid fill - // recolours just those points of their meshes. + // The gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso: a solid + // fill recolors just those points of their meshes (the proxies show them: `fill_mesh_points`). let mesh_points = if fill && matches!(paint, Paint::Solid { .. }) { picked_mesh_points(s, &ids) } else { vec![] }; // Without `item`, unless the Appearance panel's active fill item takes the paint. let colorized = if fill && p.get("item").is_none() && item == ItemTarget::Top { @@ -871,6 +886,55 @@ pub(crate) fn picked_mesh_points_of(s: &Session, ids: &[NodeId]) -> Option)]) -> Vec { + match (&n.kind, points.iter().find(|(id, _)| *id == n.id)) { + (NodeKind::Mesh(m), Some((_, v))) => v.iter().filter_map(|i| m.points.get(*i)).map(|q| q.color).collect(), + _ => vec![], + } +} + +impl Session { + /// The picked gradient mesh points that a solid fill color (`paint.setFill` without `ids` or + /// `item`) recolors instead of their meshes' fills, each mesh with its points: the targets are + /// resolved as [`set_paint`] resolves them, so this is empty while the Appearance panel's + /// active item is a fill row or an object of a symbol instance is selected, and a mesh with + /// points picked counts even when other objects are selected with it. + pub fn fill_mesh_points(&self) -> Vec<(NodeId, Vec)> { + let Some(st) = self.active() else { return vec![] }; + // Only gradient meshes have points to pick: a selection with no mesh and no container that + // could hold one skips reading the tool's options. + let may_hold_mesh = |id: &NodeId| st.doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Mesh(_)) || n.is_container()); + if st.selection.symbol_part.is_some() || !st.selection.subjects().iter().any(may_hold_mesh) { + return vec![]; + } + let Ok(item) = item_target(self, &Value::Null, "paint.setFill").map(|t| t.of_kind(self, true)) else { return vec![] }; + if item != ItemTarget::Top { + return vec![]; + } + let Ok(selected) = item.targets(self, &Value::Null) else { return vec![] }; + picked_mesh_points(self, &super::graph::paint_targets(&st.doc, &selected)) + } + + /// The picked gradient mesh points that the Transparency panel's opacity (`transparency.set` + /// without `ids` or `item`) fades instead of their objects: `None` unless every target is a + /// gradient mesh with points picked, and while the Appearance panel's active item takes the + /// opacity (outside opacity mask editing). + pub fn mesh_points_picked(&self) -> Option)>> { + let st = self.active()?; + let ids = super::opacitymask::transparency_targets(self, &Value::Null).ok()?; + // Only gradient meshes have points to pick: other targets skip reading the tool's options. + if ids.is_empty() || !ids.iter().all(|id| matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Mesh(_)))) { + return None; + } + if st.doc.mask_edit.is_none() && self.appearance_item().is_some() { + return None; + } + picked_mesh_points_of(self, &ids) + } +} + /// A type run's stroke; a painted stroke on a run without one gets 1 pt. pub(super) fn set_run_stroke(style: &mut CharStyle, paint: Paint) { if !paint.is_none() { @@ -1086,8 +1150,8 @@ fn transparency(s: &mut Session, p: &Value) -> Result { q.remove("item"); q.remove("id"); q.insert("ids".into(), json!(ids.iter().map(|id| id.0).collect::>())); - // The gradient mesh points picked with the Mesh tool or Direct Selection take the opacity - // themselves, so only the mesh around them fades (#4206, #4170, #4208). + // The gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso take the + // opacity themselves, so only the mesh around them fades (#4206, #4170, #4208). if matches!(item, ItemTarget::Top) && let Some(o) = q.get("opacity").and_then(Value::as_f64) && let Some(points) = picked_mesh_points_of(s, &ids) diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index 2383d05a3a..fa0492c2db 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -5,7 +5,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::{Composer, JustificationOptions, NodeKind, Scaling, SingleWordJustify, TextRun}; use vectorcraft_geom::{Rect, Vec2}; -use super::{Affine, CommandSpec, NodeId, Result, Session, bad, bool_or, check_switches, cmd, has_doc, index, ok, point_indices, switch_or}; +use super::{Affine, CommandSpec, NodeId, Result, Session, bad, bool_or, check_switches, cmd, has_doc, index, ok, switch_or}; use crate::{Clipboard, EngineError}; pub fn specs() -> Vec { @@ -67,7 +67,7 @@ pub fn specs() -> Vec { "Character / Paragraph", [], None, - "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"yakumonoHankaku\"|\"gyomatsuYakumonoHankaku\"|\"gyomatsuYakumonoZenkaku\"|\"yakumonoZenkaku\"|\"lineEndHalf\" (Mojikumi Set: Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tenth of an em each, pushOutFirst does so only when moving the character before them to the next line would leave the line more than an em short, and pushOutOnly, the default, moves it unless Burasagari hangs an overflowing comma or full stop; no effect with kinsoku \"none\"), bunriKinshi?: bool (Paragraph panel menu › Bunri-Kinshi: a line never breaks inside an inseparable pair, two em dashes, two horizontal ellipses, two two-dot leaders or the two halves of a vertical kana repeat mark, and justification adds no space inside one; kept but without effect with kinsoku \"none\"; off by default), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings, as text.setRangeStyle: a tate-chu-yoko block moves up or down, right or left, and on a vertical path toward or away from the path's start, to its left or right), warichu?: bool, warichuLines?: 1..6, warichuGap?: pt 0..100, warichuScale?: % 10..100, warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Character panel menu › Warichu and Warichu Settings, as text.setRangeStyle: the characters set smaller and stacked on lines inside their line), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options, as text.setRangeStyle: space before and after each character in reading order), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options, as text.setRangeStyle: the share of the blank space beside each character's ink taken away in horizontal type), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, as text.setRangeStyle), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference, as text.setRangeStyle: the height of the font that the size measures), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), koreanLineBreakAnywhere?: bool (Paragraph panel menu › Korean Line Break Anywhere: a line may break between any two Hangul syllables; off, a word with Hangul in it breaks only at its spaces and punctuation, or where it is wider than the line; new type: false, paragraphs saved before the option: true), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\" (line breaking, Every-line by default), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text, and graph labels keep the character and paragraph attributes for every label of their kind when the graph is drawn again, the graph still setting each label's alignment; a number or switch given as another type fails the call, and a null value leaves its attribute as it is, so a call with only null values fails with nothing to change; a call that gives the values the text already has records no undo step). Or {paragraphIndents: [{id, start: byte where the paragraph starts, leftIndent?, firstLineIndent?: pt -1296..1296}…]} alone (Tabs panel indent markers over paragraphs with indents of their own): each entry sets one paragraph of a type object, at least one indent each, at most 100000 entries; every entry is checked before anything changes, and an unknown key, a value out of range, an object that is not type, a byte where no paragraph starts or two entries for one paragraph with other values fail the call; all of it is one edit, a threaded story flowing again once, and when no paragraph's indents change nothing is recorded → {ids}", + "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"yakumonoHankaku\"|\"gyomatsuYakumonoHankaku\"|\"gyomatsuYakumonoZenkaku\"|\"yakumonoZenkaku\"|\"lineEndHalf\" (Mojikumi Set: Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tenth of an em each, pushOutFirst does so only when moving the character before them to the next line would leave the line more than an em short, and pushOutOnly, the default, moves it unless Burasagari hangs an overflowing comma or full stop; no effect with kinsoku \"none\"), bunriKinshi?: bool (Paragraph panel menu › Bunri-Kinshi: a line never breaks inside an inseparable pair, two em dashes, two horizontal ellipses, two two-dot leaders or the two halves of a vertical kana repeat mark, and justification adds no space inside one; kept but without effect with kinsoku \"none\"; off by default), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings, as text.setRangeStyle: a tate-chu-yoko block moves up or down, right or left, and on a vertical path toward or away from the path's start, to its left or right), warichu?: bool, warichuLines?: 1..6, warichuGap?: pt 0..100, warichuScale?: % 10..100, warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Character panel menu › Warichu and Warichu Settings, as text.setRangeStyle: the characters set smaller and stacked on lines inside their line), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options, as text.setRangeStyle: space before and after each character in reading order), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options, as text.setRangeStyle: the share of the blank space beside each character's ink taken away in horizontal type), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, as text.setRangeStyle), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), glyphForm?: \"traditional\"|\"expert\"|\"jis04\"|\"jis90\"|\"jis78\"|\"jis83\"|\"fullWidth\"|\"halfWidth\"|\"thirdWidth\"|\"quarterWidth\"|\"default\" (Glyphs panel menu, with Show East Asian Options, as text.setRangeStyle: the characters drawn in one OpenType form of the font, or its default glyphs), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference, as text.setRangeStyle: the height of the font that the size measures), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), koreanLineBreakAnywhere?: bool (Paragraph panel menu › Korean Line Break Anywhere: a line may break between any two Hangul syllables; off, a word with Hangul in it breaks only at its spaces and punctuation, or where it is wider than the line; new type: false, paragraphs saved before the option: true), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\" (line breaking, Every-line by default), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text, and graph labels keep the character and paragraph attributes for every label of their kind when the graph is drawn again, the graph still setting each label's alignment; a number or switch given as another type fails the call, and a null value leaves its attribute as it is, so a call with only null values fails with nothing to change; a call that gives the values the text already has records no undo step). Or {paragraphIndents: [{id, start: byte where the paragraph starts, leftIndent?, firstLineIndent?: pt -1296..1296}…]} alone (Tabs panel indent markers over paragraphs with indents of their own): each entry sets one paragraph of a type object, at least one indent each, at most 100000 entries; every entry is checked before anything changes, and an unknown key, a value out of range, an object that is not type, a byte where no paragraph starts or two entries for one paragraph with other values fail the call; all of it is one edit, a threaded story flowing again once, and when no paragraph's indents change nothing is recorded → {ids}", has_doc, set_format ), @@ -76,7 +76,7 @@ pub fn specs() -> Vec { "Convert to Text", [], None, - "{ids?|id?, start?: byte, end?: byte} (Type › Bullets and Numbering › Convert to Text: the paragraphs of the selected type, or of `ids`, or those a start/end range touches; after Select All in a frame of threaded text, without `ids`, `id` or a range, every paragraph of the story's frames that are neither locked nor hidden; while the story is selected, its locked and hidden frames are not converted even when named, nor a paragraph whose text starts in one) the marker of each list paragraph becomes characters of its text: the bullet, or the number and its period as the paragraph showed it, then a tab, at the start of the paragraph in the marker's font, size and color; the list is turned off. When the marker's tab went to the left indent, the paragraph gets a left-aligned tab stop without a leader there, in place of any stop there, which keeps the text after the tab where it started; when it went to a tab stop and a stop there or past it has a leader or is not left-aligned, or a right, center or decimal stop lies between the marker and that place, the paragraph gets a left-aligned stop without a leader where the marker's tab ended, in place of any stop there and of those right, center and decimal stops before it (past the left indent only in a paragraph with no tab of its own). In threaded type the numbers are those counted through the story's frames, and a paragraph that continues into a later frame is converted where its text starts. An empty list paragraph has no marker and only leaves the list. A paragraph with no direction set gets the direction it ran in when the characters would change it (a letter or roman numeral before right-to-left text). With the Every-line Composer, a paragraph with a tab is broken line by line, so a converted paragraph can break its lines at other places. While the Type tool edits, its typing ends first and its anchor and caret move past the characters inserted at or before them (a whole story that Select All selected stays selected when the call converts all of it); in threaded type, when the caret's character moved to another frame, the tool edits that frame, which becomes the selection when it was not selected. One undo step → {ids, converted: paragraphs, inserted: [{id, at: byte before the change, length: bytes}]}", + "{ids?|id?, start?: byte, end?: byte} (Type › Bullets and Numbering › Convert to Text: the paragraphs of the selected type, or of `ids`, or those a start/end range touches; after Select All in a frame of threaded text, without `ids`, `id` or a range, every paragraph of every frame of the story, locked and hidden frames included) the marker of each list paragraph becomes characters of its text: the bullet, or the number and its period as the paragraph showed it, then a tab, at the start of the paragraph in the marker's font, size and color; the list is turned off. When the marker's tab went to the left indent, the paragraph gets a left-aligned tab stop without a leader there, in place of any stop there, which keeps the text after the tab where it started; when it went to a tab stop and a stop there or past it has a leader or is not left-aligned, or a right, center or decimal stop lies between the marker and that place, the paragraph gets a left-aligned stop without a leader where the marker's tab ended, in place of any stop there and of those right, center and decimal stops before it (past the left indent only in a paragraph with no tab of its own). In threaded type the numbers are those counted through the story's frames, and a paragraph that continues into a later frame is converted where its text starts. An empty list paragraph has no marker and only leaves the list. A paragraph with no direction set gets the direction it ran in when the characters would change it (a letter or roman numeral before right-to-left text). With the Every-line Composer, a paragraph with a tab is broken line by line, so a converted paragraph can break its lines at other places. While the Type tool edits, its typing ends first and its anchor and caret move past the characters inserted at or before them (a whole story that Select All selected stays selected when the call converts all of it); in threaded type, when the caret's character moved to another frame, the tool edits that frame, which becomes the selection when it was not selected. One undo step → {ids, converted: paragraphs, inserted: [{id, at: byte before the change, length: bytes}]}", has_doc, convert_list_to_text ), @@ -137,19 +137,16 @@ pub(crate) fn named_or_selected(s: &Session, p: &Value, cmd: &str) -> Result = t["selected"] - .as_array() - .into_iter() - .flatten() - .filter_map(Value::as_u64) - .filter(|i| usize::try_from(*i).is_ok_and(|i| i < d.artboards.len())) - .collect(); + let mut picked: Vec = + t["selected"].as_array().into_iter().flatten().filter_map(Value::as_u64).map(index).filter(|i| *i < d.artboards.len()).collect(); if picked.is_empty() { - picked.push(t["active"].as_u64().unwrap_or(0)); + picked.push(on_board(d, t["active"].as_u64().map_or(0, index))?); } - artboard_indices(d, &json!({ "indices": picked }), cmd) + picked.sort_unstable(); + picked.dedup(); + Ok(picked) } /// Rename Artboards: one artboard takes the name, and several take it numbered in artboard order, in @@ -221,23 +218,51 @@ fn artboard_switch_orientation(s: &mut Session, p: &Value) -> Result { Ok(json!({ "switched": switched })) } -/// The one artboard `cmd` acts on: `index`, an artboard of `d`, with the errors of -/// [`artboard_indices`] (`missing index`, `no such artboard`). +/// The one artboard `cmd` acts on: `index`, an artboard of `d`. Left out or null, it is +/// `missing index`; a value that is not a whole number is "`index` must be a whole number"; a +/// whole number past the last artboard is `no such artboard`. pub(crate) fn artboard_index(d: &vectorcraft_doc::Document, p: &Value, cmd: &str) -> Result { - let i = p.get("index").ok_or_else(|| bad(cmd, "missing index"))?; - artboard_indices(d, &json!({ "index": i }), cmd)?.into_iter().next().ok_or_else(|| EngineError::Other("no such artboard".into())) + artboard_at(d, p, "index", cmd)?.ok_or_else(|| bad(cmd, "missing index")) +} + +/// The artboard of `d` that `key` of `p` names, or `None` when `p` leaves it out or gives null. A +/// value that is not a whole number is "`{key}` must be a whole number", and a whole number past the +/// last artboard is `no such artboard`. +pub(crate) fn artboard_at(d: &vectorcraft_doc::Document, p: &Value, key: &str, cmd: &str) -> Result> { + super::index_opt(p, key, cmd)?.map(|i| on_board(d, i)).transpose() +} + +/// `i` when it is an artboard of `d`, else `no such artboard`. +pub(crate) fn on_board(d: &vectorcraft_doc::Document, i: usize) -> Result { + match i < d.artboards.len() { + true => Ok(i), + false => Err(EngineError::Other("no such artboard".into())), + } } /// The artboards `cmd` acts on: `indices` (several), else `index` (one), each an artboard of `d`, -/// in order and once each. +/// in order and once each. `indices` is read as [`listed_artboards`] reads it, and `index` as +/// [`artboard_index`] reads it. pub(crate) fn artboard_indices(d: &vectorcraft_doc::Document, p: &Value, cmd: &str) -> Result> { - let listed = match (p.get("indices"), p.get("index")) { - (Some(v), _) => point_indices(v), - (None, Some(i)) => point_indices(&json!([i])), - (None, None) => return Err(bad(cmd, "missing index")), - }; - let mut indices = - listed.filter(|v| !v.is_empty() && v.iter().all(|i| *i < d.artboards.len())).ok_or_else(|| EngineError::Other("no such artboard".into()))?; + match p.get("indices") { + Some(v) => listed_artboards(d, v, "indices", cmd), + None => Ok(vec![artboard_index(d, p, cmd)?]), + } +} + +/// `v`, the value of `key`, as artboards of `d`, in order and once each. A value that is not a list +/// is "`{key}` must be a list of artboard indices", an empty list is "`{key}` must be a non-empty +/// list of artboard indices", and a list with an entry that is not a whole number is "`{key}` must +/// contain whole numbers"; a whole number past the last artboard is `no such artboard`. Every entry +/// is checked for its form before any is checked against the artboards. +fn listed_artboards(d: &vectorcraft_doc::Document, v: &Value, key: &str, cmd: &str) -> Result> { + let entries = v.as_array().ok_or_else(|| bad(cmd, format!("`{key}` must be a list of artboard indices")))?; + if entries.is_empty() { + return Err(bad(cmd, format!("`{key}` must be a non-empty list of artboard indices"))); + } + let listed = entries.iter().map(Value::as_u64).collect::>>(); + let listed = listed.ok_or_else(|| bad(cmd, format!("`{key}` must contain whole numbers")))?; + let mut indices = listed.into_iter().map(|i| on_board(d, index(i))).collect::>>()?; indices.sort_unstable(); indices.dedup(); Ok(indices) @@ -592,6 +617,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result { "standardVerticalRoman", "noBreak", "digits", + "glyphForm", "fontHeightReference", "language", "fontAxes", @@ -626,6 +652,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result { let char_align = super::textedit::char_align_param(p, C)?; let char_direction = super::textedit::char_direction_param(p, C)?; let digits = super::textedit::digits_param(p, C)?; + let glyph_form = super::textedit::glyph_form_param(p, C)?; let language = super::textedit::language_param(p, C)?; let font_axes = super::textedit::font_axes_param(p, C)?; let font_height_reference = super::textedit::font_height_reference_param(p, C)?; @@ -796,6 +823,9 @@ fn set_format(s: &mut Session, p: &Value) -> Result { if let Some(v) = digits { st.digits = v; } + if let Some(v) = glyph_form { + st.glyph_form = v; + } if let Some(v) = &language { st.language.clone_from(v); } @@ -1310,19 +1340,11 @@ fn convert_list_to_text(s: &mut Session, p: &Value) -> Result { use vectorcraft_doc::text::ParaList; let range = super::typecmd::TextRange::parse(p, C)?; // After Select All in a frame of threaded text, a call that names no type and no range takes - // every paragraph of the story's editable frames; its locked and hidden frames stay as they are - // whichever way they are named. - let full = super::textedit::editing_story(s); - let story: Vec = full.iter().copied().filter(|f| s.doc().is_ok_and(|st| st.doc.is_editable(*f))).collect(); + // every paragraph of every frame of the story, its locked and hidden frames included: the story + // is one text. + let story = super::textedit::editing_story(s); let named = ["ids", "id"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())); - let ids = if !story.is_empty() && !named && range.is_none() { - story.clone() - } else { - super::typecmd::text_targets(s, p, C)?.into_iter().filter(|id| !full.contains(id) || story.contains(id)).collect() - }; - // The selected story's locked and hidden frames: no paragraph whose text starts in one is - // converted, and none of their paragraphs is restyled. - let held: Vec = full.iter().copied().filter(|f| !story.contains(f)).collect(); + let ids = if !story.is_empty() && !named && range.is_none() { story.clone() } else { super::typecmd::text_targets(s, p, C)? }; // Converting the whole story leaves it selected. let whole_story = !story.is_empty() && range.is_none() && story.iter().all(|f| ids.contains(f)); let editing = match super::textedit::editing_range(s)? { @@ -1356,7 +1378,6 @@ fn convert_list_to_text(s: &mut Session, p: &Value) -> Result { let mut converted = 0; for story in &stories { let frames: Vec<&vectorcraft_doc::TextObject> = story.iter().filter_map(|id| text(*id)).collect(); - let is_held = |f: usize| story.get(f).is_some_and(|id| held.contains(id)); let mut paras: Vec = vec![]; let mut named_parts = vec![]; let plains: Vec = frames.iter().map(|t| t.plain_text()).collect(); @@ -1382,7 +1403,7 @@ fn convert_list_to_text(s: &mut Session, p: &Value) -> Result { } for (i, named) in named_parts { if let Some(para) = paras.get_mut(i) { - let listed = para.main_part().is_some_and(|p| p.list.is_some() && !is_held(p.frame)); + let listed = para.main_part().is_some_and(|p| p.list.is_some()); para.converts |= named && listed; } } @@ -1472,7 +1493,7 @@ fn convert_list_to_text(s: &mut Session, p: &Value) -> Result { let tab = vectorcraft_doc::TabStop { position: x, align: vectorcraft_doc::TabAlign::Left, leader: String::new(), align_on: '.' }; style.tabs.insert(i, tab); } - for part in story_para.parts.iter().filter(|q| (std::ptr::eq(*q, para) || q.bytes.is_empty()) && !is_held(q.frame)) { + for part in story_para.parts.iter().filter(|q| std::ptr::eq(*q, para) || q.bytes.is_empty()) { if let Some((stops, _)) = frame_edits.get_mut(part.frame) { stops.push((part.index, style.clone())); } diff --git a/crates/engine/src/cmd/params.rs b/crates/engine/src/cmd/params.rs index fe8431a6c6..736358ff9b 100644 --- a/crates/engine/src/cmd/params.rs +++ b/crates/engine/src/cmd/params.rs @@ -183,7 +183,7 @@ pub(crate) fn accepted_keys(doc: &'static str) -> Option> { /// Does the description `doc` name `key` as a parameter (its own keys, and those of the commands /// its `…` entries name)? -pub(crate) fn takes_key(doc: &'static str, key: &str) -> bool { +pub fn takes_key(doc: &'static str, key: &str) -> bool { doc_keys(doc).is_ok_and(|parsed| parsed.keys.contains(&key)) || accepted(doc, 0).is_some_and(|keys| keys.contains(&key)) } @@ -382,7 +382,8 @@ pub fn check_effect_params(id: &str, effect: &str, params: &Value) -> Result<()> return Err(bad(id, format!("`version` must be 0 or {newest}"))); } check_effect_color(id, effect, params)?; - check_effect_channel(id, effect, params) + check_effect_channel(id, effect, params)?; + check_effect_center(id, effect, params) } /// The type of the values in `params` of effect `effect`, as command `id` was given them: a key @@ -500,6 +501,22 @@ pub(crate) fn check_effect_channel(id: &str, effect: &str, params: &Value) -> Re Err(bad(id, format!("`{key}` must be one of {}", vectorcraft_render::effects::CHANNELS.join(", ")))) } +/// The Blur Center (`centerX`, `centerY`) in `params` of Radial Blur (`effect`), as command `id` +/// was given it: a parameter error unless each is a number from 0 to 1 (a share of the object's +/// bounds). `effect.apply` and `effect.setParams` run this themselves before they edit, as they +/// run [`check_effect_channel`]. +pub(crate) fn check_effect_center(id: &str, effect: &str, params: &Value) -> Result<()> { + if effect != "blur.radial" { + return Ok(()); + } + for key in ["centerX", "centerY"] { + if params.get(key).is_some_and(|v| !v.as_f64().is_some_and(|x| (0.0..=1.0).contains(&x))) { + return Err(bad(id, format!("`{key}` must be a number from 0 to 1"))); + } + } + Ok(()) +} + /// Commands whose params aren't checked yet (#1442): they read keys in ways the audit of the /// descriptions couldn't follow (a list of keys in a loop, a whole object read as settings), so /// their descriptions aren't proven to name every key they take. Sorted; take a command out once diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index 9d7b42cca2..0fb450fa43 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -77,7 +77,7 @@ pub fn specs() -> Vec { "Reverse Path Direction", ["Object", "Path"], None, - "{ids?|id?, subpath?: usize (reverse only this subpath of each path, 0 included; default: every subpath), reversed?: bool (true: every subpath runs counter-clockwise on screen, false: clockwise, the Attributes panel's Reverse Path Direction On / Off; omitted: flip each path; with subpath, the direction is not read: that subpath is flipped)} the paths in ids or the selection (groups and compound paths: the paths inside), as one undo step → {changed: paths}", + "{ids?|id?, subpath?: usize (reverse only this subpath of each path, 0 included; default: every subpath), reversed?: bool (true: every subpath runs counter-clockwise on screen, false: clockwise, the Attributes panel's Reverse Path Direction On / Off; omitted: flip each path; with subpath, the direction is not read: that subpath is flipped)} the paths in ids or the selection (groups and compound paths: the paths inside), as one undo step; when every subpath of a path or compound path turns alike, its strokes' width profiles (sides swapped) and pen pressure, tilt, bearing and rotation turn with it, so they draw as before → {changed: paths}", has_selected_path, reverse ), @@ -315,13 +315,13 @@ fn set_handle(s: &mut Session, p: &Value) -> Result { let pos = Point::new(f64_req(p, "x", "path.setHandle")?, f64_req(p, "y", "path.setHandle")?); let independent = switch_or(p, "independent", false, "path.setHandle")?; // A handle already there, on an anchor already of the kind it would get, changes nothing and - // records no undo step. - if let Some(a) = anchor_of(s, id, si, ai)? { - let mut b = a; - b.set_handle(out, pos, independent); - if b == a { - return ok(); - } + // records no undo step. The handle is compared directly: `set_handle` would recompute the + // other handle of a smooth anchor, which need not give back the same value. + if let Some(a) = anchor_of(s, id, si, ai)? + && (if out { a.h_out } else { a.h_in }) == pos + && !(independent && a.kind != AnchorKind::Corner) + { + return ok(); } s.edit("Reshape", |d, _| { let path = path_mut(d, id)?; @@ -458,26 +458,47 @@ fn reverse(s: &mut Session, p: &Value) -> Result { if ids.is_empty() { return Err(bad(C, "select paths")); } + let flip_of = |path: &PathData| -> Vec { + match subpath { + Some(si) => (0..path.subpaths.len()).map(|i| i == si).collect(), + None => path.subpaths.iter().map(|sp| want.is_none_or(|ccw| (sp.signed_area() < 0.0) != ccw)).collect(), + } + }; let changed = super::overprint::edit_counted(s, "Reverse Path Direction", |d| { + // A compound path's own strokes run along its members' subpaths in order, so they turn + // with them, read before any member turns. + let compounds: BTreeSet = ids.iter().map(|id| compound_or_self(d, *id)).filter(|c| ids.binary_search(c).is_err()).collect(); + for c in compounds { + let Some(NodeKind::Compound { children, .. }) = d.node(c).map(|n| &n.kind) else { continue }; + let flip: Vec = children + .iter() + .filter_map(|m| m.path_data().map(|pd| if ids.binary_search(&m.id).is_ok() { flip_of(pd) } else { vec![false; pd.subpaths.len()] })) + .flatten() + .collect(); + if flip.contains(&true) + && let Some(n) = d.node_mut(c) + { + vectorcraft_doc::blend::reverse_stroke_records(n, &flip); + } + } let mut changed = 0; for id in &ids { let path = path_mut(d, *id)?; - if let Some(si) = subpath { - if let Some(sp) = path.subpaths.get_mut(si) { + let flip = flip_of(path); + if !flip.contains(&true) { + continue; + } + // The stroke's width profile and pen recordings turn with the path, read before it turns. + if let Some(n) = d.node_mut(*id) { + vectorcraft_doc::blend::reverse_stroke_records(n, &flip); + } + let path = path_mut(d, *id)?; + for (sp, f) in path.subpaths.iter_mut().zip(flip) { + if f { sp.reverse(); - changed += 1; - } - } else { - let flip: Vec = path.subpaths.iter().map(|sp| want.is_none_or(|ccw| (sp.signed_area() < 0.0) != ccw)).collect(); - if flip.contains(&true) { - for (sp, f) in path.subpaths.iter_mut().zip(flip) { - if f { - sp.reverse(); - } - } - changed += 1; } } + changed += 1; } Ok(changed) })?; diff --git a/crates/engine/src/cmd/pathops.rs b/crates/engine/src/cmd/pathops.rs index 878b3743cf..b5267fa990 100644 --- a/crates/engine/src/cmd/pathops.rs +++ b/crates/engine/src/cmd/pathops.rs @@ -1188,6 +1188,8 @@ fn outline_stroke(s: &mut Session, _: &Value) -> Result { let roots = selected_roots(s)?; let ids = s.edit("Outline Stroke", |d, sel| { let before = d.clone(); + // Outlining the strokes in a graph does not move or scale its plot at the next redraw. + let graphs = super::graph::graphs_holding(d, &roots); // A dimension selected with the art it measures keeps its own lines: it is out of the // document while the art is outlined. let lifted = super::dimension::lift(d, &roots); @@ -1207,6 +1209,7 @@ fn outline_stroke(s: &mut Session, _: &Value) -> Result { if changed == 0 || (kept && d.layers == before.layers) { return Err(EngineError::Other("Outline Stroke: no stroked paths selected".into())); } + super::graph::keep_placed(d, &graphs); sel.set(new_sel.iter().copied()); Ok(new_sel) })?; diff --git a/crates/engine/src/cmd/perspgrid.rs b/crates/engine/src/cmd/perspgrid.rs index d13e7d8c52..150d716421 100644 --- a/crates/engine/src/cmd/perspgrid.rs +++ b/crates/engine/src/cmd/perspgrid.rs @@ -7,7 +7,8 @@ //! fields; `perspective.grid.preset` applies one, `perspective.presets.*` manage them. //! //! View options (Lock Grid, Lock Station Point, Snap to Grid, Show Rulers) are view state on -//! the grid: they toggle without an undo step, as Show Grid does. +//! the grid: they toggle without an undo step, as Show Grid does. So is the point Automatic Plane +//! Positioning holds the active plane through (`perspective.plane.infer`). use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; @@ -15,12 +16,15 @@ use vectorcraft_doc::{Document, NodeId}; use vectorcraft_geom::{Point, Rect, Vec2}; use vectorcraft_tools::distort::perspective::Plane; use vectorcraft_tools::distort::perspective::define::{BUILTINS, LETTER, first_artboard, is_builtin}; +use vectorcraft_tools::distort::perspective::infer::{HIT_PX, InferSource}; use vectorcraft_tools::distort::perspective::widget::{WidgetCorner, WidgetPlace}; -use vectorcraft_tools::distort::perspective::{GridDefinition, PerspectiveGrid}; +use vectorcraft_tools::distort::perspective::{GridDefinition, MAX_DEPTH, PerspectiveGrid}; use vectorcraft_tools::{PointerEvent, PointerKind, ToolKey}; -use super::distortcmds::{grid_of, silent, store_grid}; -use super::{CommandSpec, EngineError, Result, Session, always, bad, bool_or, cmd, has_doc, str_param, switch_or, unique_name}; +use super::distortcmds::{grid_kept, grid_of, silent, store_grid}; +use super::{ + CommandSpec, EngineError, Result, Session, always, bad, bool_or, cmd, finite_numbers, has_doc, number_or, str_param, switch_or, unique_name, +}; pub fn specs() -> Vec { vec![ @@ -92,10 +96,19 @@ pub fn specs() -> Vec { "Perspective Grid Options", [], None, - "{show?: bool, position?: topLeft|topRight|bottomLeft|bottomRight} the Plane Switching Widget: shown or not, and the corner of the document window it stays in (kept with the preferences; no params reads them) → {show, position}", + "{show?: bool, position?: topLeft|topRight|bottomLeft|bottomRight, anchorPoint?: bool, gridlineIntersection?: bool} the Plane Switching Widget: shown or not, and the corner of the document window it stays in; Automatic Plane Positioning: whether it takes a point from an anchor point of art in perspective and from a gridline intersection (both on by default; see perspective.plane.infer). Kept with the preferences; no params reads them → {show, position, anchorPoint, gridlineIntersection}", always, widget_options ), + cmd!( + "perspective.plane.infer", + "Automatic Plane Positioning", + [], + None, + "{at?: [x, y], tolerance?: pt around `at` (default 6), clear?: bool} with `at` on an anchor point of shown art in perspective, or on a gridline intersection of a plane that shows, the active plane moves through that point for now and the other planes hide (the Perspective Selection tool: Shift held over one with no button down). An anchor point within reach wins over an intersection, and perspective.widget.options turns either off. Making another plane active (perspective.plane.set) brings that plane through the same point. The plane goes back to its place when an object is drawn on it or attached to it (perspective.draw, perspective.attach, an object brought into perspective by perspective.move or perspective.transform), when a plane is moved (perspective.plane.move, perspective.plane.matchObject), when the grid hides or no plane is active, when the file is opened again, and with `clear` (Escape with the Perspective Selection tool). View state: not an undo step; no params reads it → {active, plane, offset: where the active plane is, point?: [x, y, z] in the grid's frame, source?: anchor|gridline (what `at` found; absent when nothing was within reach)}", + has_doc, + plane_infer + ), cmd!( "perspective.grid.lock", "Lock Grid", @@ -259,12 +272,34 @@ pub(crate) fn grid_preset(s: &mut Session, p: &Value) -> Result { let old = grid_of(&s.doc()?.doc); let ab = s.doc()?.doc.artboards.first().map(|a| a.rect).ok_or_else(|| EngineError::Other("no artboard".into()))?; let g = s.perspective_preset_grid(&name, ab).ok_or_else(|| bad(C, format!("no perspective grid preset named `{name}`")))?; - // The objects stay attached and the view options stay as they were. - let g = PerspectiveGrid { attached: old.attached, locked: old.locked, lock_station: old.lock_station, snap: old.snap, rulers: old.rulers, ..g }; - s.edit("Perspective Grid Preset", |d, _| { - store_grid(d, &g); - Ok(()) - })?; + // The objects stay attached and the view options stay as they were, and so does a plane held + // by Automatic Plane Positioning while the new grid can hold it. + let mut g = PerspectiveGrid { + attached: old.attached, + locked: old.locked, + lock_station: old.lock_station, + snap: old.snap, + rulers: old.rulers, + inferred: old.inferred, + ..g + }; + g.keep_positioning_valid(); + // When the document holds this grid already, apart from whether it shows and its active plane, + // the preset only sets those two, without an undo step (as perspective.grid.show and + // perspective.plane.set do). + let view = PerspectiveGrid { visible: old.visible, plane: old.plane, inferred: old.inferred, ..g.clone() }; + if !grid_kept(&s.doc()?.doc, &view) { + s.edit("Perspective Grid Preset", |d, _| { + store_grid(d, &g); + Ok(()) + })?; + } else if (old.visible, old.plane, old.inferred) != (g.visible, g.plane, g.inferred) { + silent(s, |cur| { + cur.visible = g.visible; + cur.plane = g.plane; + cur.inferred = g.inferred; + })?; + } Ok(g.definition_json()) } @@ -449,10 +484,100 @@ fn widget_options(s: &mut Session, p: &Value) -> Result { o.position = v.as_str().and_then(WidgetCorner::parse).ok_or_else(|| bad(C, "position must be topLeft, topRight, bottomLeft or bottomRight"))?; } + if let Some(v) = p.get("anchorPoint") { + o.anchor_point = v.as_bool().ok_or_else(|| bad(C, "anchorPoint must be true or false"))?; + } + if let Some(v) = p.get("gridlineIntersection") { + o.gridline_intersection = v.as_bool().ok_or_else(|| bad(C, "gridlineIntersection must be true or false"))?; + } s.prefs.perspective_widget = o; Ok(json!(o)) } +/// What `perspective.plane.infer` reports for `g`. +fn infer_info(g: &PerspectiveGrid, source: Option) -> Value { + let active = g.inferred.is_some() && g.plane != Plane::None; + let mut v = json!({ "active": active, "plane": g.plane.id(), "offset": g.offset(g.plane) }); + if let Some(at) = g.inferred.filter(|_| active) { + v["point"] = json!(at); + } + if let Some(source) = source { + v["source"] = json!(source.id()); + } + v +} + +fn plane_infer(s: &mut Session, p: &Value) -> Result { + const C: &str = "perspective.plane.infer"; + let clear = switch_or(p, "clear", false, C)?; + let at = match p.get("at") { + None | Some(Value::Null) => None, + Some(v) => Some(finite_numbers(v).map(|[x, y]| Point::new(x, y)).ok_or_else(|| bad(C, "`at` must be [x, y]"))?), + }; + let tol = number_or(p, "tolerance", HIT_PX, C)?; + if !(tol.is_finite() && (0.0..=MAX_DEPTH).contains(&tol)) { + return Err(bad(C, "tolerance must be 0 or more")); + } + if clear && at.is_some() { + return Err(bad(C, "give `at` or `clear`, not both")); + } + let doc = &s.doc()?.doc; + let g = PerspectiveGrid::current(doc); + let mut source = None; + let next = match at { + _ if clear => None, + None => g.inferred, + Some(at) => { + if !g.visible { + return Err(EngineError::Other("the perspective grid is hidden".into())); + } + if g.plane == Plane::None { + return Err(EngineError::Other("no active perspective plane".into())); + } + let targets = s.prefs.perspective_widget.targets(); + if !targets.any() { + return Err(EngineError::Other( + "Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options)".into(), + )); + } + match g.infer_at(doc, at, tol, targets) { + Some((found, point)) => { + source = Some(found); + Some(point) + } + None => g.inferred, + } + } + }; + if next == g.inferred { + return Ok(infer_info(&g, source)); + } + // A plane through the point stays in front of the viewer. + if next.is_some() { + PerspectiveGrid { inferred: next, ..g }.validate().map_err(|e| bad(C, e))?; + } + let g = silent(s, |g| g.inferred = next)?; + Ok(infer_info(&g, source)) +} + +/// An object was drawn on, or attached to, `plane`: when Automatic Plane Positioning holds that +/// plane, it goes back to its place as view state, not an undo step (a plane it doesn't hold +/// leaves it as it is). In a drag that happens once the drag is committed +/// ([`Session::commit_interaction`]), so the plane stays put while the object is drawn. +pub(crate) fn plane_positioning_used(s: &mut Session, plane: Plane) -> Result<()> { + let st = s.doc_mut()?; + let g = grid_of(&st.doc); + if g.inferred.is_none() || g.plane != plane { + return Ok(()); + } + if let Some(it) = &mut st.interaction { + it.plane_placed = true; + return Ok(()); + } + silent(s, |g| g.inferred = None)?; + Ok(()) +} + impl Session { /// The Plane Switching Widget's part of a pointer event: a press on it picks the plane (its /// drag and release go nowhere); None when the event isn't the widget's. diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index 20f19ef803..dc95f925b6 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -75,7 +75,7 @@ pub fn specs() -> Vec { "Place…", ["File"], Some("Cmd+Shift+P"), - "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set), platform?: \"windows\" (Windows-1252) | \"mac\" (Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file placed in a clip group, which the Links commands take}. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", + "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set), platform?: \"windows\" (Windows-1252) | \"mac\" (Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file placed in a clip group, which the Links commands take}. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", has_doc, place ), @@ -962,8 +962,10 @@ pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result { (None, [id]) => *id, _ => return Err(bad(C, "select one image or pass id")), }; - // An image in opacity-mask art or a definition's art is found by its id too (`links.list`). - let n = st.doc.stored_node(id).map(|(n, _)| &**n).ok_or(EngineError::NoNode(id))?; + // An image in opacity-mask art, a definition's art or a stored brush's art is found by its id + // too (`links.list`). + let doc = super::links::with_brush_art(&st.doc); + let n = doc.stored_node(id).map(|(n, _)| &**n).ok_or(EngineError::NoNode(id))?; let NodeKind::Image(im) = &n.kind else { return Err(bad(C, format!("object {} is not an image", id.0))) }; // Effective resolution: 72 pt per inch over the points one pixel spans along each axis. let [a, b, c, d, ..] = im.xf.as_coeffs(); diff --git a/crates/engine/src/cmd/place/document.rs b/crates/engine/src/cmd/place/document.rs index 8e4afaa295..5809990e0f 100644 --- a/crates/engine/src/cmd/place/document.rs +++ b/crates/engine/src/cmd/place/document.rs @@ -20,7 +20,7 @@ use std::sync::Arc; use vectorcraft_doc::links::hash_bytes; use vectorcraft_doc::placed_document::{PREVIEW_MAX, PREVIEW_PX_PER_PT, key_for}; -use vectorcraft_doc::{Document, ImageBlob, LinkInfo, Node, NodeKind, PageBox, PlacedDocument, PlacementOptions}; +use vectorcraft_doc::{ColorMode, Document, ImageBlob, LinkInfo, Node, NodeKind, PageBox, PlacedDocument, PlacementOptions}; use vectorcraft_geom::{Affine, Rect}; use vectorcraft_pdf::CropTo; @@ -221,22 +221,57 @@ pub(crate) struct Source { /// What is shown, in the file's coordinates: the artboard, the page's box or the art's bounds. pub frame: Rect, pub warnings: Vec, + /// The colour mode the file's art was read in (a PDF page painted mostly in CMYK reads in CMYK). + pub color_mode: ColorMode, } /// The VectorCraft document `name` (`bytes`, from `path` when there is one) read for showing /// artboard `page`, or the PDF or `.ai` file for showing page `page` clipped to its box /// `page_box` (its art's bounds when `bounding`). pub(crate) fn source(name: &str, bytes: &[u8], path: Option<&str>, page: u32, bounding: bool, page_box: PageBox, cmd: &str) -> Result { + read_source(name, bytes, None, path, (page, bounding, page_box), cmd) +} + +/// [`source`] of the file whose bytes `bytes` holds, kept by the blob without a copy of its own: +/// several pages of one file read this way share one copy of it. +pub(crate) fn shared_source( + name: &str, + bytes: &Arc>, + path: Option<&str>, + page: u32, + bounding: bool, + page_box: PageBox, + cmd: &str, +) -> Result { + read_source(name, bytes, Some(bytes), path, (page, bounding, page_box), cmd) +} + +/// [`source`], the blob keeping `shared` when given (else a copy of `bytes`); `shown` is the page +/// (or artboard), whether the art's bounds are shown, and the page's box. +fn read_source( + name: &str, + bytes: &[u8], + shared: Option<&Arc>>, + path: Option<&str>, + shown: (u32, bool, PageBox), + cmd: &str, +) -> Result { + let (page, bounding, page_box) = shown; // The same document placed the same way is read once (placing it again is free). let key = key_for(&hash_bytes(bytes), page, bounding, page_box); // Resolving its links depends on where the file is and on what the caller may read, so a hit // needs the same path, and nothing is shared with or from a confined (automation) caller. let confined = crate::file_access::current().is_some(); - if !confined && let Some((_, s)) = lock_memo().iter().find(|(at, s)| s.key == key && at.as_deref() == path).cloned() { + if !confined && let Some((_, mut s)) = lock_memo().iter().find(|(at, s)| s.key == key && at.as_deref() == path).cloned() { + // The same bytes: the copy given is kept instead, so the pages that share it go on sharing. + if let Some(b) = shared { + s.blob.bytes = b.clone(); + } return Ok(s); } let a = document_art(name, bytes, path, page, bounding, page_box, cmd)?; - let mut blob = ImageBlob::new(mime(name, bytes), bytes.to_vec()); + let bytes = shared.cloned().unwrap_or_else(|| Arc::new(bytes.to_vec())); + let mut blob = ImageBlob { mime: mime(name, &bytes).into(), bytes, proxy: None }; let shown = PlacedDocument { link: LinkInfo { page: Some(page), ..LinkInfo::new(path.unwrap_or(name)) }, key: key.clone(), @@ -249,9 +284,10 @@ pub(crate) fn source(name: &str, bytes: &[u8], path: Option<&str>, page: u32, bo }; let art = group(a.nodes, a.clip); blob.proxy = preview(&a.doc, &art, a.frame).map(Arc::new); + let color_mode = a.doc.color_mode; // Drawing it needn't read it again. vectorcraft_doc::placed_document::prime(&shown, blob.bytes.clone(), (a.doc, art, a.frame)); - let s = Source { blob, key, page_box, frame: a.frame, warnings: a.warnings }; + let s = Source { blob, key, page_box, frame: a.frame, warnings: a.warnings, color_mode }; if !confined { let mut m = lock_memo(); if m.len() >= MEMO_SIZE { @@ -330,7 +366,8 @@ pub(crate) fn node(d: &mut Document, s: &Source, link: LinkInfo, bounding: bool) } /// `d` for output: linked images and placed documents that keep only their previews get their -/// files back, else output as their previews, with a warning. +/// files back, else output as their previews, with a warning. The art of the stored brushes counts +/// too. pub(crate) fn full_documents(d: &Document) -> (Cow<'_, Document>, Vec) { let (d, mut warnings) = super::super::links::full_linked_images(d, Default::default()); let doc = match &d { @@ -339,7 +376,7 @@ pub(crate) fn full_documents(d: &Document) -> (Cow<'_, Document>, Vec) { }; let mut need: Vec = vec![]; let mut seen = std::collections::HashSet::new(); - doc.visit_placed(|_, p| { + super::super::links::with_brush_art(doc).visit_placed(|_, p| { if doc.images.get(&p.key).is_some_and(ImageBlob::is_proxy) && seen.insert(p.key.clone()) { need.push(p.clone()); } @@ -370,7 +407,7 @@ pub(crate) fn full_documents(d: &Document) -> (Cow<'_, Document>, Vec) { "{n} placed documents output as their previews: their files can't be found, or changed since they were read (relink or update them)" ), }); - out.placed_as_previews(&previews); + super::super::links::editing_brush_art(&mut out, |out| out.placed_as_previews(&previews)); } (Cow::Owned(out), warnings) } diff --git a/crates/engine/src/cmd/place/text.rs b/crates/engine/src/cmd/place/text.rs index 25f5f36dbd..7d8afc92d4 100644 --- a/crates/engine/src/cmd/place/text.rs +++ b/crates/engine/src/cmd/place/text.rs @@ -3,6 +3,7 @@ use serde_json::Value; +use super::super::utf16_order_without_mark; use super::{Point, Rect, Result, bad, bool_or, fileio, shapes, str_param}; /// Text files as `file.place` reports them (not a format `document.open` reads). @@ -76,8 +77,10 @@ pub(super) fn import(bytes: &[u8], o: TextOptions, cmd: &str) -> Result Ok(clean(&decode(bytes, o), o)) } -/// `bytes` as text: Unicode (UTF-8, or UTF-16 with a byte-order mark; bytes that aren't UTF-8 are -/// read as the platform's 8-bit set), or the platform's 8-bit character set. +/// `bytes` as text: Unicode (UTF-8, or UTF-16 with a byte-order mark, or without one when the +/// file has an even length, reads as valid UTF-16 with no NUL character in the byte order +/// [`utf16_order_without_mark`] gives; bytes that aren't UTF-8 are read as the platform's 8-bit +/// set), or the platform's 8-bit character set. fn decode(bytes: &[u8], o: TextOptions) -> String { let eight_bit = |b: &[u8]| -> String { b.iter().map(|&c| if o.mac { mac_roman(c) } else { windows_1252(c) }).collect() }; if o.ansi { @@ -91,7 +94,17 @@ fn decode(bytes: &[u8], o: TextOptions) -> String { [0xEF, 0xBB, 0xBF, rest @ ..] => String::from_utf8_lossy(rest).into_owned(), [0xFF, 0xFE, rest @ ..] => utf16(rest, true), [0xFE, 0xFF, rest @ ..] => utf16(rest, false), - _ => std::str::from_utf8(bytes).map_or_else(|_| eight_bit(bytes), str::to_string), + _ => { + let without_mark = (bytes.len().is_multiple_of(2) && bytes.contains(&0)) + .then(|| utf16_order_without_mark(bytes)) + .flatten() + .and_then(|le| { + let units = bytes.as_chunks::<2>().0.iter().map(|&c| if le { u16::from_le_bytes(c) } else { u16::from_be_bytes(c) }); + char::decode_utf16(units).collect::>().ok() + }) + .filter(|text| !text.contains('\0')); + without_mark.unwrap_or_else(|| std::str::from_utf8(bytes).map_or_else(|_| eight_bit(bytes), str::to_string)) + } } } diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 3fa082bdb0..867f256b4c 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -51,6 +51,7 @@ use vectorcraft_doc::{Effect, Node}; use vectorcraft_plugins::{Budget, Command, Kind, Plugin, effect, export, objects, registry, safe_mode}; use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, cmd, has_doc, ids_param, str_param, switch_or}; +use crate::store::StoreTurn; use vectorcraft_plugins::permissions::{self, Grant, GrantToken, Permission}; @@ -683,6 +684,9 @@ thread_local! { /// Tests: runs once in the next `plugin.install` on this thread after it installs and before it /// writes the store. pub(crate) static BEFORE_STORE: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; + /// Tests: runs once on this thread when [`keep_installed`] has written the module to the store + /// and before it writes the grant. + pub(crate) static BEFORE_GRANT_STORED: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; /// Tests: runs once on this thread when [`hold_plugin_changes`] finds the lock held and waits. pub(crate) static WHILE_WAITING: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; } @@ -718,7 +722,9 @@ pub(crate) fn hold_plugin_changes() -> std::sync::MutexGuard<'static, ()> { /// the next start → its `plugin.list` entry. A refused install changes neither the plug-in store /// nor the plug-ins and grants of the process. A module that lists no permissions ends any grant /// held for its id. A `plugin.remove` in another session waits until the install has written the -/// store. +/// store. With a plug-in store, all of it happens in a turn on the store ([`StoreTurn`]), so another +/// process using the same folder changes it before or after; when the store can't be locked, nothing +/// is installed. fn install(s: &mut Session, p: &Value) -> Result { const C: &str = "plugin.install"; // One use: spent whatever this install does. @@ -736,8 +742,11 @@ fn install(s: &mut Session, p: &Value) -> Result { { return Err(bad(C, "the module doesn't have the SHA-256 `hash` gives: nothing was installed")); } - // A removal in another session waits until the store holds what this install wrote. + // A removal in another session waits until the store holds what this install wrote, and so + // does a change of the store by another process. let _held = hold_plugin_changes(); + let turn = + s.plugin_store_turn().map_err(|e| EngineError::Other(format!("{C}: {}: {e}: nothing was installed", crate::store::STORE_NOT_LOCKED)))?; // The grant the checks below count on, the approval included. The install checks it again, // with the plug-in installed under the id, before anything is stored: another session may // change either in between. @@ -844,41 +853,12 @@ fn install(s: &mut Session, p: &Value) -> Result { } // The plug-in gets the settings and cache kept for its id. A module without permissions takes // the id over, so nothing the user approved for the id applies any more. - let installed = registry::install_checked(plugin, update, check, || s.attach_plugin_storage(&id), err)?; + let installed = registry::install_checked(plugin, update, check, || s.attach_plugin_storage(&turn, &id), err)?; #[cfg(test)] if let Some(between) = BEFORE_STORE.take() { between(); } - // Installed plug-ins stay installed after a restart (#2541). The module is written first and its - // grant only once it is there; when the grant can't be written, the store gets the module it - // held back. A failed write of that module is only logged: the store then holds the new module, - // which the grant doesn't cover. A write that reports a failure may still have put the old - // module back, so the store is read again to tell which module it holds. A stored module that - // can't be read back isn't replaced by one that needs a grant. - let previous = s.stored_plugin_bytes(&id); - let mut stored = (previous.is_ok() || !asks) && s.store_plugin(&id, &bytes); - let holds_new = |s: &Session| s.stored_plugin_bytes(&id).is_ok_and(|held| held.as_deref() == Some(&bytes[..])); - if asks { - if stored && !s.store_grant(&id, Some(g)) { - stored = !s.put_back_plugin(&id, previous.ok().flatten().as_deref()) && holds_new(s); - } - } else { - // When the write failed, the old stored module stays in the folder and needs its grant at - // the next launch. A grant that can't be removed still approves the old bytes, so the store - // gets the module it held back. When that module can't be read or written back, or there - // was none, no module goes with the grant, and the grant stops counting for every session in - // the process attached to the folder. A grants file that is too large or doesn't hold a list - // approves nothing, and the new module stays; one that can't be opened or read may approve - // the old bytes once it reads again. - let writes = s.grant_writes(); - if stored && !s.store_grant(&id, None) && s.holds_plugin_grant(&id) { - let back = previous.as_ref().is_ok_and(|held| s.put_back_plugin(&id, held.as_deref())); - stored = !back && holds_new(s); - if !back || matches!(previous, Ok(None)) { - s.ignore_stored_grant(&id, writes); - } - } - } + let stored = keep_installed(s, &turn, &id, &bytes, asks.then_some(g)); // Installing a disabled plug-in again (an updated version) turns it on for the next launch too, // also when it is disabled by its stored file alone (it stopped a launch while loading). When // the new version could not replace the stored file, the old one stays disabled. @@ -891,8 +871,9 @@ fn install(s: &mut Session, p: &Value) -> Result { } } if changed { - s.store_disabled_plugins(); + s.store_disabled_plugins_in(&turn); } + drop(turn); let mut v = describe_installed(&installed); if !unknown.is_empty() { v["unknownCommands"] = json!(unknown); @@ -900,6 +881,53 @@ fn install(s: &mut Session, p: &Value) -> Result { Ok(v) } +/// Keeps the plug-in `id` that `plugin.install` installed, its module `bytes`, in the plug-in store, +/// in `turn`, with `grant` when its module lists permissions (`None`: it lists none, and the grant +/// held for the id is removed) → whether the store now holds the new module (`false` without a +/// store). +/// +/// Installed plug-ins stay installed after a restart (#2541). The module is written first and its +/// grant only once it is there; when the grant can't be written, the store gets the module it held +/// back. A failed write of that module is only logged: the store then holds the new module, which +/// the grant doesn't cover. A write that reports a failure may still have put the old module back, +/// so the store is read again to tell which module it holds. A stored module that can't be read back +/// isn't replaced by one that needs a grant. +pub(crate) fn keep_installed(s: &Session, turn: &StoreTurn, id: &str, bytes: &[u8], grant: Option) -> bool { + let asks = grant.is_some(); + let previous = s.stored_plugin_bytes(id); + let mut stored = (previous.is_ok() || !asks) && s.store_plugin(turn, id, bytes); + #[cfg(test)] + if let Some(between) = BEFORE_GRANT_STORED.take() { + between(); + } + let holds_new = |s: &Session| s.stored_plugin_bytes(id).is_ok_and(|held| held.as_deref() == Some(bytes)); + match grant { + Some(g) => { + if stored && !s.store_grant_in(turn, id, Some(g)) { + stored = !s.put_back_plugin(turn, id, previous.ok().flatten().as_deref()) && holds_new(s); + } + } + None => { + // When the write failed, the old stored module stays in the folder and needs its grant + // at the next launch. A grant that can't be removed still approves the old bytes, so the + // store gets the module it held back. When that module can't be read or written back, or + // there was none, no module goes with the grant, and the grant stops counting for every + // session in the process attached to the folder. A grants file that is too large or + // doesn't hold a list approves nothing, and the new module stays; one that can't be + // opened or read may approve the old bytes once it reads again. + let writes = s.grant_writes(); + if stored && !s.store_grant_in(turn, id, None) && s.holds_plugin_grant(id) { + let back = previous.as_ref().is_ok_and(|held| s.put_back_plugin(turn, id, held.as_deref())); + stored = !back && holds_new(s); + if !back || matches!(previous, Ok(None)) { + s.ignore_stored_grant(id, writes); + } + } + } + } + stored +} + /// `plugin.inspect`: what installing the module would install, without installing it, whether that /// needs the user to grant its permissions first (`needsApproval`) and whether it would take /// another module's place (`needsReplace`). @@ -992,15 +1020,17 @@ fn load_folder(s: &Session, folder: &str) -> Value { None if crate::file_access::current().is_none() => Ok(()), None => Err(format!("automation path rejected: {} isn't valid text", f.display())), }; - // A `plugin.install` in another session finishes writing the store first. + // A `plugin.install` in another session or process finishes writing the store first. When the + // store can't be locked, the folder still loads, and the store isn't written. let _held = hold_plugin_changes(); + let turn = s.plugin_store_turn().unwrap_or_else(|_| StoreTurn::unheld()); match registry::load_folder_where(std::path::Path::new(folder), allow, s.plugin_folder_approver()) { Ok(r) => { for id in &r.loaded { - s.attach_plugin_storage(id); + s.attach_plugin_storage(&turn, id); } if r.disabled_changed { - s.store_disabled_plugins(); + s.store_disabled_plugins_in(&turn); } json!({"folder": folder, "loaded": r.loaded, "failed": r.failed.iter().map(|(f, e)| json!({"file": f, "error": e})).collect::>()}) } @@ -1140,6 +1170,9 @@ fn set_enabled(s: &mut Session, p: &Value) -> Result { (None, None) => return Err(bad(C, "give `id` or `file` (see plugin.safeMode)")), }; let items: Vec<&safe_mode::Item> = std::iter::once(&item).chain(stored.as_ref()).collect(); + // The list is changed and saved in one turn on the plug-in store, so that an install in another + // process doesn't change the store in between. + let turn = s.plugin_store_turn().ok(); if enabled && !safe_mode::disabled().iter().any(|i| items.iter().any(|item| i.same(item))) { return Err(bad(C, "that plug-in isn't disabled (see plugin.safeMode)")); } @@ -1149,7 +1182,7 @@ fn set_enabled(s: &mut Session, p: &Value) -> Result { } // Without a plug-in folder (a session confined to automation roots), or when the list there // can't take the change, the change stays in this process and goes with the next change that saves. - let saved = !changed || s.store_disabled_plugins(); + let saved = !changed || turn.as_ref().is_some_and(|turn| s.store_disabled_plugins_in(turn)); Ok(json!({"changed": changed, "saved": saved, "disabled": safe_mode::disabled().iter().map(shown_item).collect::>()})) } @@ -1164,31 +1197,35 @@ fn info(_: &mut Session, p: &Value) -> Result { fn remove(s: &mut Session, p: &Value) -> Result { let id = str_param(p, "id").ok_or_else(|| bad("plugin.remove", "missing `id`"))?; - // An install in another session finishes its store writes first. + // An install in another session or process finishes its store writes first. When the store + // can't be locked, nothing is removed. let _held = hold_plugin_changes(); + let turn = s + .plugin_store_turn() + .map_err(|e| EngineError::Other(format!("plugin.remove: {}: {e}: nothing was removed", crate::store::STORE_NOT_LOCKED)))?; let installed = registry::get(id).is_some(); // Settings and cache the store keeps for an id that isn't installed are deleted too. let stored = !installed && vectorcraft_plugins::manifest::valid_id(id) && s.has_plugin_storage(id); // Installed again, it asks again. A grant that can't be removed still approves the module, and // so may a grants file that can't be opened or read. One that is too large or doesn't hold a // list approves nothing and doesn't stop the removal. - let forget = || s.store_grant(id, None) || !s.holds_plugin_grant(id); + let forget = || s.store_grant_in(&turn, id, None) || !s.holds_plugin_grant(id); // Its settings and cache are moved aside and its grant removed before anything is deleted: when // either can't be done, the plug-in stays installed, as it was, and a second `plugin.remove` // tries again. let failed = if installed || stored { - s.remove_plugin_storage(id, forget).err().map(|e| e.to_string()) + s.remove_plugin_storage(&turn, id, forget).err().map(|e| e.to_string()) } else { (!forget()).then(|| crate::store::GRANT_NOT_REMOVED.to_string()) }; if let Some(e) = failed { if installed { - s.attach_plugin_storage(id); + s.attach_plugin_storage(&turn, id); } return Err(EngineError::Other(e)); } registry::revoke(id); - s.unstore_plugin(id); + s.unstore_plugin(&turn, id); if !stored && (!installed || !registry::remove(id)) { return Err(err(vectorcraft_plugins::Error::NotFound(id.into()))); } @@ -1248,7 +1285,7 @@ pub fn specs() -> Vec { "Install Plug-in", [], None, - "{path: a .wasm file (desktop) | dataBase64: the module (+ name?: shown as its source), replace?: bool (true once the user agreed: a module with other bytes than the plug-in installed with its id, or with none installed, one whose id has settings or a cache in the plug-in store, installs only with it, takes that plug-in's place and gets its settings and cache; false: one whose id is installed is refused; left out, the same module installs again), name?: file name (with dataBase64), allowHeavy?: bool (a filter whose manifest asks for a heavy budget, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (a plug-in whose manifest lists permissions, needsApproval in plugin.inspect, installs only when grant holds every one of them; the grant is recorded with the module's hash and covers only that module, so a module with other bytes needs a new grant even when it lists the same permissions; installing a module that lists no permissions forgets the grant held for its id; a refused install keeps the grant, a failed write of the module to the plug-in store leaves the grant in the store, and a stored module that is disabled or not read in Safe Mode keeps the grant for its id; with a plug-in store attached, only the grants kept there count; a request's allowHeavy and grant are refused unless the session was started with vectorcraft-cli --allow-plugin-grants: in the desktop app a person approves the install, see ui.installPlugin, and a module whose hash is already recorded, by a person's approval or by a grant accepted under that flag, needs no grant), hash?: string (the module's SHA-256 as plugin.inspect gave it: a module with other bytes is refused)} validate and install a WebAssembly plug-in for this session (a module whose commandAllowlist names a command no plug-in may call, such as one that reads or writes files, is refused) → its plugin.list entry, plus unknownCommands?: [id] (commandAllowlist ids no command has; a call of one fails)", + "{path: a .wasm file (desktop) | dataBase64: the module (+ name?: shown as its source), replace?: bool (true once the user agreed: a module with other bytes than the plug-in installed with its id, or with none installed, one whose id has settings or a cache in the plug-in store, installs only with it, takes that plug-in's place and gets its settings and cache; false: one whose id is installed is refused; left out, the same module installs again), name?: file name (with dataBase64), allowHeavy?: bool (a filter whose manifest asks for a heavy budget, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (a plug-in whose manifest lists permissions, needsApproval in plugin.inspect, installs only when grant holds every one of them; the grant is recorded with the module's hash and covers only that module, so a module with other bytes needs a new grant even when it lists the same permissions; installing a module that lists no permissions forgets the grant held for its id; a refused install keeps the grant, a failed write of the module to the plug-in store leaves the grant in the store, and a stored module that is disabled or not read in Safe Mode keeps the grant for its id; with a plug-in store attached, only the grants kept there count; a request's allowHeavy and grant are refused unless the session was started with vectorcraft-cli --allow-plugin-grants: in the desktop app a person approves the install, see ui.installPlugin, and a module whose hash is already recorded, by a person's approval or by a grant accepted under that flag, needs no grant), hash?: string (the module's SHA-256 as plugin.inspect gave it: a module with other bytes is refused)} validate and install a WebAssembly plug-in for this session (with a plug-in store, the install waits while another window or process changes the store and writes the module and its grant before that window or process changes it again; when the store's disabled.lock can't be locked, nothing is installed) (a module whose commandAllowlist names a command no plug-in may call, such as one that reads or writes files, is refused) → its plugin.list entry, plus unknownCommands?: [id] (commandAllowlist ids no command has; a call of one fails)", always, install ), @@ -1266,7 +1303,7 @@ pub fn specs() -> Vec { "Remove Plug-in", [], None, - "{id} uninstall a plug-in (its live effects then leave the geometry as it is) and delete the settings and cache it kept (when their folder can't be moved aside, or its grant can't be removed from the plug-in store, the command fails and the plug-in stays installed; when the settings can't be moved back either, the error names the folder they stay in, and the next load, install or removal of the plug-in moves them back); for an id that isn't installed, deletes the settings and cache the plug-in store still keeps for it → {removed}", + "{id} uninstall a plug-in (its live effects then leave the geometry as it is) and delete the settings and cache it kept (when their folder can't be moved aside, or its grant can't be removed from the plug-in store, the command fails and the plug-in stays installed; when the settings can't be moved back either, the error names the folder they stay in, and the next load, install or removal of the plug-in moves them back); for an id that isn't installed, deletes the settings and cache the plug-in store still keeps for it; it waits while another window or process changes the plug-in store, and when the store's disabled.lock can't be locked, the command fails and nothing is removed → {removed}", always, remove ), diff --git a/crates/engine/src/cmd/plugin_call.rs b/crates/engine/src/cmd/plugin_call.rs index d42cc5b82c..6d1ddbee43 100644 --- a/crates/engine/src/cmd/plugin_call.rs +++ b/crates/engine/src/cmd/plugin_call.rs @@ -101,12 +101,30 @@ const FILE_WORDS: &[&str] = &[ "clipboard", ]; -/// Param keys that name a file or a folder. -const FILE_KEYS: &[&str] = - &["path", "paths", "file", "files", "folder", "folders", "dir", "directory", "destinationFolder", "sourceFolder", "url", "diffPath"]; +/// Param keys that name a file or a folder, each by its whole name, the folder preferences +/// `prefs.set {values}` takes included: a command that adds a key naming one adds it here. A key +/// that only ends like one (`alignToPath`, `linksFolder`, `sortPaths`) names none, nor do `folders` +/// (how an export groups its files) and `url` (a web link). +const FILE_KEYS: &[&str] = &[ + "path", + "paths", + "file", + "files", + "folder", + "dir", + "directory", + "destinationFolder", + "sourceFolder", + "diffPath", + "fontsFolder", + "pluginsFolder", + "recoveryFolder", + "templatesFolder", +]; /// The keys in [`FILE_KEYS`] that name a folder. -const FOLDER_KEYS: &[&str] = &["folder", "folders", "dir", "directory", "destinationFolder", "sourceFolder"]; +const FOLDER_KEYS: &[&str] = + &["folder", "dir", "directory", "destinationFolder", "sourceFolder", "fontsFolder", "pluginsFolder", "recoveryFolder", "templatesFolder"]; /// What a param key that names a place on disk names there. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -132,7 +150,83 @@ pub fn key_location(key: &str) -> Option { /// What `key` names on disk in command `spec`: [`key_location`], or `None` when [`NOT_FILES`] /// names it for `spec` (it names part of the document there). pub fn location_in(spec: &CommandSpec, key: &str) -> Option { - if NOT_FILES.contains(&(spec.id, key)) { None } else { key_location(key) } + ParamsPlace::top(Some(spec)).member(key, None).1 +} + +/// A place in the params of a command. What a key names on disk depends on the command and on the +/// keys above it: [`key_location`], less a key [`NOT_FILES`] names for the command at the top of its +/// params and one at the end of a [`NESTED_NOT_FILES`] key list. A walk of params starts at +/// [`ParamsPlace::top`] and goes down with [`ParamsPlace::member`] and [`ParamsPlace::item`]. +#[derive(Clone, Copy, Debug)] +pub struct ParamsPlace { + /// The command whose params these are; `None` for a command that isn't known. + command: Option<&'static str>, + /// Whether this is the top of the params. + top: bool, + /// The keys of a [`NESTED_NOT_FILES`] list still to follow below this place. + trail: Option<&'static [&'static str]>, +} + +impl ParamsPlace { + /// The top of the params of `spec`, or of a command that isn't known (`None`), where every key in + /// [`FILE_KEYS`] names a file or a folder. + pub fn top(spec: Option<&CommandSpec>) -> ParamsPlace { + ParamsPlace { command: spec.map(|s| s.id), top: true, trail: None } + } + + /// The top of the params of the command with id `id` ([`ParamsPlace::top`]). + pub fn of(id: &str) -> ParamsPlace { + ParamsPlace::top(super::find_command(id)) + } + + /// The top of the params of the command that object `fields` calls, when it is a call + /// (`{command | id: , params}`, as a `command.batch` step or a control request is): + /// the place of its `params` member ([`ParamsPlace::member`]). + pub fn carried(fields: &serde_json::Map) -> Option { + if !fields.contains_key("params") { + return None; + } + let id = fields.get("command").or_else(|| fields.get("id")).and_then(Value::as_str)?; + super::find_command(id).map(|spec| ParamsPlace::top(Some(spec))) + } + + /// The top of the params of the command that array `items` records, when it is a recorded step + /// (`[command id, params]`): the place of its item 1 ([`ParamsPlace::item`]). + pub fn step(items: &[Value]) -> Option { + match items { + [Value::String(id), Value::Object(_)] => super::find_command(id).map(|spec| ParamsPlace::top(Some(spec))), + _ => None, + } + } + + /// The place of member `key` of an object here, with what `key` names on disk there. `carried` is + /// [`ParamsPlace::carried`] of that object: its `params` member is then the top of that command's + /// params, and names no file. + pub fn member(self, key: &str, carried: Option) -> (ParamsPlace, Option) { + if key == "params" + && let Some(inner) = carried + { + return (inner, None); + } + let rest = if self.top { + let id = self.command; + NESTED_NOT_FILES.iter().find(|(c, keys)| Some(*c) == id && keys.first() == Some(&key)).map(|(_, keys)| keys.get(1..).unwrap_or_default()) + } else { + self.trail.filter(|keys| keys.first() == Some(&key)).map(|keys| keys.get(1..).unwrap_or_default()) + }; + let document = (self.top && self.command.is_some_and(|id| NOT_FILES.contains(&(id, key)))) || rest.is_some_and(<[&str]>::is_empty); + let place = ParamsPlace { command: self.command, top: false, trail: rest.filter(|keys| !keys.is_empty()) }; + (place, if document { None } else { key_location(key) }) + } + + /// The place of item `index` of an array here. `step` is [`ParamsPlace::step`] of that array: its + /// item 1 is then the top of that command's params. + pub fn item(self, index: usize, step: Option) -> ParamsPlace { + match step { + Some(inner) if index == 1 => inner, + _ => ParamsPlace { command: self.command, top: false, trail: None }, + } + } } /// The param keys of `spec` that name a file or a folder, with what they name: the keys in @@ -158,9 +252,6 @@ pub(crate) const NOT_FILES: &[(&str, &str)] = &[ ("symbol.instance.setAppearance", "path"), ("symbol.instance.selectPart", "path"), ("object.objectsOnPath.attach", "path"), - ("attributes.set", "url"), - ("object.slice.options", "url"), - ("document.exportForScreens", "folders"), ]; /// Commands and the keys from the top of their params down to a key in [`FILE_KEYS`] that, there, @@ -251,34 +342,24 @@ pub(crate) fn names_key(text: &str, key: &str) -> bool { }) } -/// Does `args`, the arguments of a call of command `id`, carry a key in [`FILE_KEYS`] at any depth -/// (in objects and in arrays), such as an effect's `textureImage.path`? Only a key [`NOT_FILES`] -/// names for `id`, at the top level, and one at the end of a [`NESTED_NOT_FILES`] key list for -/// `id`, aren't counted. The walk keeps its own stack, so deep arguments can't overflow the -/// thread's. +/// Does `args`, the arguments of a call of command `id`, carry a key that names a file or a folder at +/// any depth (in objects and in arrays, [`ParamsPlace`]), such as an effect's `textureImage.path`? +/// Only a key [`NOT_FILES`] names for `id`, at the top level, and one at the end of a +/// [`NESTED_NOT_FILES`] key list for `id`, aren't counted. A call or a recorded step inside `args` +/// is read as part of `id`'s arguments, not as the command it names. The walk keeps its own stack, +/// so deep arguments can't overflow the thread's. fn names_file(id: &str, args: &Value) -> bool { - // Each value, whether it is the params themselves, and the keys of a NESTED_NOT_FILES list - // still to follow below it. - let mut stack: Vec<(&Value, bool, Option<&[&str]>)> = vec![(args, true, None)]; - while let Some((v, top, trail)) = stack.pop() { + let mut stack: Vec<(&Value, ParamsPlace)> = vec![(args, ParamsPlace::of(id))]; + while let Some((v, place)) = stack.pop() { match v { - Value::Array(a) => stack.extend(a.iter().map(|x| (x, false, None))), + Value::Array(a) => stack.extend(a.iter().enumerate().map(|(i, x)| (x, place.item(i, None)))), Value::Object(o) => { for (k, x) in o { - let k = k.as_str(); - let rest = if top { - NESTED_NOT_FILES - .iter() - .find(|(c, keys)| *c == id && keys.first() == Some(&k)) - .map(|(_, keys)| keys.get(1..).unwrap_or_default()) - } else { - trail.filter(|keys| keys.first() == Some(&k)).map(|keys| keys.get(1..).unwrap_or_default()) - }; - let document = (top && NOT_FILES.contains(&(id, k))) || rest.is_some_and(<[&str]>::is_empty); - if FILE_KEYS.contains(&k) && !document { + let (below, location) = place.member(k, None); + if location.is_some() { return true; } - stack.push((x, false, rest.filter(|keys| !keys.is_empty()))); + stack.push((x, below)); } } _ => {} @@ -638,7 +719,13 @@ mod tests { assert!(names_file("effect.apply", &texture)); assert!(names_file("effect.setParams", &texture)); assert!(names_file("effect.apply", &json!({"params": {"layers": [{"name": "a"}, {"folder": "/tmp"}]}}))); - assert!(names_file("select.all", &json!([[[{"url": "file:///etc/hosts"}]]]))); + assert!(names_file("select.all", &json!([[[{"file": "file:///etc/hosts"}]]]))); + // A web link and an export's grouping name no file. + assert!(!names_file("attributes.set", &json!({"url": "https://example.com/a"}))); + assert!(!names_file("object.move", &json!({"opts": {"folders": "rows", "alignToPath": "baseline"}}))); + // A call nested in the arguments doesn't vouch for its own keys. + assert!(names_file("object.move", &json!({"opts": {"command": "object.setLiveShape", "params": {"path": "/tmp/x"}}}))); + assert!(names_file("object.move", &json!({"opts": ["object.setLiveShape", {"path": "/tmp/x"}]}))); assert!(!names_file("effect.apply", &json!({"effect": "distort.glass", "params": {"distortion": 5, "textureImage": "frosted"}}))); assert!(!names_file("object.move", &json!({"dx": 5, "dy": 0, "ids": [1, 2], "opts": {"copy": false}}))); // `path` is the path text is set on in text.createInPath, but only as its own param. @@ -647,7 +734,13 @@ mod tests { assert!(names_file("object.move", &json!({"path": [[0, 0]]}))); // object.setLiveShape takes no `path`; its description says "on any path:" in its prose. assert!(names_file("object.setLiveShape", &json!({"path": "/tmp/x"}))); - // Image Trace's path fidelity setting, only inside its tracing settings. + } + + /// Image Trace's path fidelity setting `paths` names no file, but only inside its tracing + /// settings. + #[test] + fn image_trace_paths_name_no_file_only_in_its_settings() { + use serde_json::json; for id in ["imageTrace.make", "imageTrace.makeAndExpand"] { assert!(!names_file(id, &json!({"preset": "Default", "params": {"mode": "color", "paths": 50}}))); assert!(!names_file(id, &json!({"savedPreset": {"paths": 50, "corners": 75}}))); @@ -658,7 +751,12 @@ mod tests { assert!(names_file(id, &json!({"options": {"paths": 50}}))); } assert!(names_file("object.move", &json!({"params": {"paths": 50}}))); - // A custom arrowhead's outline in stroke.set, only where stroke.set takes one. + } + + /// A custom arrowhead's outline `path` names no file, but only where stroke.set takes one. + #[test] + fn a_custom_arrowhead_outline_names_no_file_only_in_stroke_set() { + use serde_json::json; let outline = json!({"subpaths": []}); assert!(!names_file("stroke.set", &json!({"endArrow": {"Custom": {"name": "A", "path": outline}}}))); assert!(!names_file("stroke.set", &json!({"startArrow": {"Custom": {"name": "A", "path": outline}}, "endArrow": "Triangle"}))); @@ -668,7 +766,12 @@ mod tests { assert!(names_file("stroke.set", &json!({"options": {"endArrow": {"Custom": {"path": "/tmp/x"}}}}))); assert!(names_file("stroke.set", &json!({"endArrow": [{"Custom": {"path": "/tmp/x"}}]}))); assert!(names_file("object.move", &json!({"endArrow": {"Custom": {"path": "/tmp/x"}}}))); - // Deep nesting is walked without recursion. + } + + /// A file key under deep nesting is found, and the walk doesn't recurse. + #[test] + fn a_file_key_is_found_under_deep_nesting() { + use serde_json::json; let mut deep = json!({"file": "/tmp/x"}); for _ in 0..10_000 { deep = Value::Array(vec![deep]); @@ -726,11 +829,48 @@ mod tests { assert!(found.iter().all(|(k, l)| (*l == Location::Folder) == FOLDER_KEYS.contains(k)), "{}: {found:?}", spec.id); assert!(denied(spec).is_some() || found.is_empty(), "{} names {found:?} but a plug-in may call it", spec.id); } - assert_eq!(key_location("url"), Some(Location::File)); + assert_eq!(key_location("url"), None); + assert_eq!(key_location("folders"), None); + assert_eq!(key_location("linksFolder"), None); assert_eq!(key_location("sourceFolder"), Some(Location::Folder)); assert_eq!(key_location("pathData"), None); } + /// A key keeps the meaning its command gives it at every depth: a call (`{command, params}`) and a + /// recorded step (`[command id, params]`) carry their command's exceptions down, and a custom + /// arrowhead's outline is part of the document only at its own place in `stroke.set`. + #[test] + fn a_params_place_follows_its_command() { + use serde_json::json; + let at = |place: ParamsPlace, keys: &[&str]| { + let mut place = place; + let mut location = None; + for k in keys { + (place, location) = place.member(k, None); + } + location + }; + assert_eq!(at(ParamsPlace::of("text.createInPath"), &["path"]), None); + assert_eq!(at(ParamsPlace::of("text.createInPath"), &["options", "path"]), Some(Location::File)); + assert_eq!(at(ParamsPlace::of("stroke.set"), &["endArrow", "Custom", "path"]), None); + assert_eq!(at(ParamsPlace::of("stroke.set"), &["endArrow", "Custom", "file"]), Some(Location::File)); + assert_eq!(at(ParamsPlace::of("no.such.command"), &["path"]), Some(Location::File)); + assert_eq!(at(ParamsPlace::top(None), &["destinationFolder"]), Some(Location::Folder)); + let call = json!({"command": "text.createInPath", "params": {"path": [[0, 0]]}}); + let carried = call.as_object().and_then(ParamsPlace::carried); + let (inner, location) = ParamsPlace::of("command.batch").member("params", carried); + assert_eq!(location, None); + assert_eq!(inner.member("path", None).1, None); + assert_eq!(ParamsPlace::carried(&serde_json::Map::new()).map(|_| ()), None); + let unknown = json!({"command": "no.such.command", "params": {}}); + assert!(unknown.as_object().and_then(ParamsPlace::carried).is_none()); + let step = [json!("text.createInPath"), json!({"path": [[0, 0]]})]; + let place = ParamsPlace::top(None).item(1, ParamsPlace::step(&step)); + assert_eq!(place.member("path", None).1, None); + assert_eq!(ParamsPlace::top(None).item(0, ParamsPlace::step(&step)).member("path", None).1, Some(Location::File)); + assert!(ParamsPlace::step(&[json!("text.createInPath")]).is_none()); + } + /// A file key counts as a command's param only where its description takes it: not a word in /// the prose after the params, in a nested object or in the result. A description that doesn't /// say which keys it takes counts any `key:` in its text. diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 5329f23331..03a931ba5d 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -34,6 +34,7 @@ pub(super) const ALLOWED: &[&str] = &[ "addon.contour.set", "addon.cutting.banner", "addon.cutting.bridges", + "addon.cutting.nest", "addon.cutting.weed", "addon.image.applyColorMask", "addon.image.colorMask", @@ -473,6 +474,7 @@ pub(super) const ALLOWED: &[&str] = &[ "perspective.grid.snap", "perspective.move", "perspective.nudge", + "perspective.plane.infer", "perspective.plane.matchObject", "perspective.plane.move", "perspective.plane.set", diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index 7a948bfc87..b6c500749f 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -217,6 +217,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[ p!("recentFontsCount", "Type", "Options", "Number of Recent Fonts", int(1, 15)), p!("missingGlyphProtection", "Type", "Options", "Enable Missing Glyph Protection", bool), p!("highlightAlternateGlyphs", "Type", "Options", "Highlight Alternate Glyphs", bool), + p!("showCharacterAlternates", "Type", "Options", "Show Character Alternates", bool), p!("highlightSubstitutedFonts", "Type", "Options", "Highlight Substituted Fonts", bool), p!("placeholderText", "Type", "Options", "Fill New Type Objects With Placeholder Text", bool), p!("typedLists", "Type", "Options", "Start Lists From Typed Markers", bool), diff --git a/crates/engine/src/cmd/stylelib.rs b/crates/engine/src/cmd/stylelib.rs index 09b478e8c7..bc06f197e5 100644 --- a/crates/engine/src/cmd/stylelib.rs +++ b/crates/engine/src/cmd/stylelib.rs @@ -62,7 +62,7 @@ pub fn specs() -> Vec { "Other Library…", ["Window", "Graphic Style Libraries"], None, - "{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} load a .vcstyles library, or the graphic styles of any document VectorCraft opens (see document.formats), for the library panel (Window → Graphic Style Libraries lists it until the app quits; a file of the user library folder, or a file with the same extension and bytes as one there, opens as that User Defined library) → {library: id, name, count}", + "{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} load a .vcstyles library, or the graphic styles of any document VectorCraft opens (see document.formats), for the library panel (Window → Graphic Style Libraries lists it until the app quits; a file of the user library folder, or a file with the same extension and bytes as one there, opens as that User Defined library; a .ai or EPS style painting with one of the file's gradients by name takes it at the style's angle, fitted to each object it is applied to, VectorCraft's own placement) → {library: id, name, count}", always, load ), diff --git a/crates/engine/src/cmd/svgfilter.rs b/crates/engine/src/cmd/svgfilter.rs index 98b29a6e27..43af8bce35 100644 --- a/crates/engine/src/cmd/svgfilter.rs +++ b/crates/engine/src/cmd/svgfilter.rs @@ -3,9 +3,14 @@ //! applied effect names the document's filter: editing the filter changes what every object that //! uses it draws, and deleting it leaves their effects in place, drawing nothing, until a filter of //! that name exists again. Each effect holds the definition it draws with, kept in step here. +//! +//! The default filters ([`svg_filter::defaults`]) are listed for every document. Applying or +//! editing one adds a copy to the document under the default's name, and from then on that copy is +//! the filter of that name. Deleting the copy lists the default again. use serde_json::{Value, json}; use vectorcraft_doc::{Appearance, Document, SvgFilter}; +use vectorcraft_render::effects::svg_filter::defaults::{DEFAULT_FILTERS, default_filter}; use vectorcraft_render::effects::{self, svg_filter}; use super::fileio::{absolute_path, read_file_head}; @@ -21,7 +26,7 @@ pub fn specs() -> Vec { "SVG Filters", [], None, - "{} → {filters: [{name, xml}…]} the SVG filters the document holds, in the SVG Filters submenu's order", + "{} → {filters: [{name, xml}…], defaults: [{name, xml, inDocument}…]} filters: the SVG filters the document holds, in the order they were added; defaults: the default filters every document lists (VectorCraft's own set), with inDocument true when the document holds a filter of that name, which then stands in the default's place. The SVG Filters submenu and Apply SVG Filter list the defaults first, then the document's other filters", has_doc, list ), @@ -30,7 +35,7 @@ pub fn specs() -> Vec { "New SVG Filter", [], None, - "{xml: one SVG element (its id is its name; 1..64 primitives; at most 64 KB), replace?: the name of the filter it replaces and keeps (Edit SVG Filter)} add an SVG filter to the document, after the others, or replace one, as one undo step; every object whose svg.filter effect names it draws with the new definition; a name another filter has is refused and a document holds at most 64 filters → {name, filters}", + "{xml: one SVG element (its id is its name; 1..64 primitives; at most 64 KB), replace?: the name of the filter it replaces and keeps (Edit SVG Filter)} add an SVG filter to the document, after the others, or replace one, as one undo step; every object whose svg.filter effect names it draws with the new definition; a name another filter of the document has is refused and a document holds at most 64 filters; replace with the name of a default filter the document does not hold adds the edited copy to the document under that name, and code equal to the default's adds nothing; a new filter may take a default's name, and then stands in its place → {name, filters}", has_doc, define ), @@ -39,7 +44,7 @@ pub fn specs() -> Vec { "Delete SVG Filter", [], None, - "{name} remove an SVG filter from the document, as one undo step; objects whose svg.filter effect names it keep the effect, which draws nothing until a filter of that name is defined or imported again → {filters}", + "{name} remove an SVG filter from the document, as one undo step; objects whose svg.filter effect names it keep the effect, which draws nothing until a filter of that name is defined or imported again, or the default of that name is applied; a default filter the document holds no copy of is refused (the defaults are not deleted), and deleting the document's copy of one lists the default again → {filters}", has_doc, delete ), @@ -57,7 +62,7 @@ pub fn specs() -> Vec { "Apply SVG Filter", [], None, - "{name, ids?|id?, item?} apply the document's SVG filter `name` (svgFilter.list) to ids or the selection as a live svg.filter effect, as one undo step, like effect.apply → {ids, index, item}", + "{name, ids?|id?, item?, index?} apply the document's SVG filter `name`, or the default filter of that name when the document holds none (svgFilter.list), to ids or the selection as a live svg.filter effect, as one undo step, like effect.apply → {ids, index, item}; with index, the filter takes the place of the applied svg.filter effect at index of item, like effect.setParams → {ids}; a default is copied into the document in the same undo step, which is refused when the document already holds 64 filters", has_doc, apply ), @@ -69,7 +74,10 @@ fn filters_json(d: &Document) -> Value { } fn list(s: &mut Session, _: &Value) -> Result { - Ok(json!({ "filters": filters_json(&s.doc()?.doc) })) + let d = &s.doc()?.doc; + let held = |name: &str| d.svg_filters.iter().any(|f| f.name == name); + let defaults: Vec = DEFAULT_FILTERS.iter().map(|f| json!({ "name": f.name, "xml": f.xml, "inDocument": held(f.name) })).collect(); + Ok(json!({ "filters": filters_json(d), "defaults": defaults })) } /// `p`'s `name`, trimmed and not empty. @@ -132,10 +140,12 @@ fn define(s: &mut Session, p: &Value) -> Result { }; svg_filter::check(&xml).map_err(|e| bad(C, e))?; let filters = &s.doc()?.doc.svg_filters; - let at = match &replace { - Some(r) => Some(filters.iter().position(|f| f.name == *r).ok_or_else(|| bad(C, format!("the document has no SVG filter named {r:?}")))?), - None => None, - }; + let at = replace.as_ref().and_then(|r| filters.iter().position(|f| f.name == *r)); + // A default the document does not hold: its edited copy is added under the default's name. + let default = replace.as_ref().filter(|_| at.is_none()).and_then(|r| default_filter(r)); + if let Some(r) = replace.as_ref().filter(|_| at.is_none() && default.is_none()) { + return Err(bad(C, format!("the document has no SVG filter named {r:?}"))); + } // An edited filter keeps its name, whatever id its new code gives it. let xml = match &replace { Some(r) => svg_filter::with_id(&xml, r).ok_or_else(|| bad(C, "give one element"))?, @@ -145,22 +155,28 @@ fn define(s: &mut Session, p: &Value) -> Result { if filters.iter().enumerate().any(|(i, f)| f.name == name && Some(i) != at) { return Err(bad(C, format!("the document already has an SVG filter named {name:?}"))); } + let new = SvgFilter { name: name.clone(), xml }; + // Nothing to record when the filter, and every object that uses it, is already as given: a + // default saved with its own code stays out of the document. + let as_given = match default { + Some(d) => d.to_filter() == new, + None => at.and_then(|i| filters.get(i)) == Some(&new), + }; + if as_given && !out_of_step(&s.doc()?.doc, &new.name, &new.xml) { + return Ok(json!({ "name": name, "filters": filters_json(&s.doc()?.doc) })); + } if at.is_none() && filters.len() >= SvgFilter::MAX { return Err(bad(C, format!("a document holds at most {} SVG filters", SvgFilter::MAX))); } - let new = SvgFilter { name: name.clone(), xml }; - // Nothing to record when the filter, and every object that uses it, is already as given. - if at.and_then(|i| filters.get(i)) != Some(&new) || out_of_step(&s.doc()?.doc, &new.name, &new.xml) { - let label = if at.is_some() { "Edit SVG Filter" } else { "New SVG Filter" }; - s.edit(label, |d, _| { - update_users(d, &new.name, &new.xml); - match at.and_then(|i| d.svg_filters.get_mut(i)) { - Some(f) => *f = new, - None => d.svg_filters.push(new), - } - Ok(()) - })?; - } + let label = if replace.is_some() { "Edit SVG Filter" } else { "New SVG Filter" }; + s.edit(label, |d, _| { + update_users(d, &new.name, &new.xml); + match at.and_then(|i| d.svg_filters.get_mut(i)) { + Some(f) => *f = new, + None => d.svg_filters.push(new), + } + Ok(()) + })?; Ok(json!({ "name": name, "filters": filters_json(&s.doc()?.doc) })) } @@ -168,6 +184,9 @@ fn delete(s: &mut Session, p: &Value) -> Result { const C: &str = "svgFilter.delete"; let name = name_param(p, C)?; if !s.doc()?.doc.svg_filters.iter().any(|f| f.name == name) { + if default_filter(&name).is_some() { + return Err(bad(C, format!("{name:?} is a default SVG filter, and the document holds no copy of it to delete"))); + } return Err(bad(C, format!("the document has no SVG filter named {name:?}"))); } s.edit("Delete SVG Filter", |d, _| { @@ -222,13 +241,79 @@ fn import(s: &mut Session, p: &Value) -> Result { fn apply(s: &mut Session, p: &Value) -> Result { const C: &str = "svgFilter.apply"; let name = name_param(p, C)?; - let f = s.doc()?.doc.svg_filters.iter().find(|f| f.name == name).cloned(); - let f = f.ok_or_else(|| bad(C, format!("the document has no SVG filter named {name:?}")))?; - let mut q = json!({ "effect": effects::SVG_FILTER, "params": { "name": f.name, "xml": f.xml } }); + let filters = &s.doc()?.doc.svg_filters; + // The document's filter of that name, or the default of that name, which the document then takes. + let (f, copied) = match (filters.iter().find(|f| f.name == name), default_filter(&name)) { + (Some(f), _) => (f.clone(), false), + (None, Some(_)) if filters.len() >= SvgFilter::MAX => { + return Err(bad(C, format!("a document holds at most {} SVG filters, and applying a default filter adds it", SvgFilter::MAX))); + } + (None, Some(d)) => (d.to_filter(), true), + (None, None) => return Err(bad(C, format!("the document has no SVG filter named {name:?}"))), + }; + // A given `index`, null included, is checked as an index: only a missing one adds an effect. + let replaces = p.get("index").is_some(); + let mut q = match replaces { + true => json!({ "index": p["index"], "params": { "name": f.name, "xml": f.xml } }), + false => json!({ "effect": effects::SVG_FILTER, "params": { "name": f.name, "xml": f.xml } }), + }; for key in ["ids", "id", "item"] { if let Some(v) = p.get(key) { q[key] = v.clone(); } } - super::effectcmd::apply(s, &q) + if !copied { + return apply_as_given(s, p, &q, replaces, None); + } + // The effect and the copy are two edits joined into one step. The history keeps room for both + // until they are joined, so the application lets one old step go at most, as any edit does. + let limit = s.doc()?.history.limit; + if let Some(st) = s.active_mut() { + st.history.limit = limit.saturating_add(2); + } + let out = apply_as_given(s, p, &q, replaces, Some(f)); + if let Some(st) = s.active_mut() { + st.history.limit = limit; + st.history.trim(); + } + out +} + +/// [`apply`] once the filter is known: the effect added (`q`) or put in the applied filter's place +/// (`replaces`), and `copy`, a default's copy, added to the document in the same undo step. +fn apply_as_given(s: &mut Session, p: &Value, q: &Value, replaces: bool, copy: Option) -> Result { + const C: &str = "svgFilter.apply"; + let newest = s.doc()?.history.step().0; + let out = if replaces { + super::appearance::index_param(p, "index", C)?; + // Only an applied SVG filter gives its place: another effect would take the filter's + // parameters as its own. + let edited = super::effectcmd::set_params_effects(s, q); + if edited.is_empty() || edited.iter().any(|e| e != effects::SVG_FILTER) { + return Err(bad(C, "`index` must be the index of an applied SVG filter")); + } + super::effectcmd::set_params(s, q)? + } else { + super::effectcmd::apply(s, q)? + }; + if let Some(f) = copy { + // The copy joins the step that applied it, under that step's name. That step is found by + // its document, not its place: in an undo group both edits join the group's one step. + let h = &s.doc()?.history; + let applied = h.undo.last().filter(|_| h.step().0 != newest).map(|step| (step.label.clone(), step.doc.clone())); + let label = applied.as_ref().map_or_else(|| "SVG Filter".to_string(), |(l, _)| l.clone()); + s.edit(&label, |d, _| { + update_users(d, &f.name, &f.xml); + d.svg_filters.push(f); + Ok(()) + })?; + let undo = &s.doc()?.history.undo; + let below = undo.len().checked_sub(2); + if let (Some(at), Some((_, doc))) = (below, &applied) + && undo.get(at).is_some_and(|e| std::sync::Arc::ptr_eq(&e.doc, doc)) + { + super::menucmds::squash(s, at, &label); + } + } + Ok(out) } diff --git a/crates/engine/src/cmd/swatch.rs b/crates/engine/src/cmd/swatch.rs index 3b98cbd9a6..3388b8344b 100644 --- a/crates/engine/src/cmd/swatch.rs +++ b/crates/engine/src/cmd/swatch.rs @@ -19,7 +19,7 @@ pub fn specs() -> Vec { "New Swatch", ["Window", "Swatches"], None, - "{name?, color? | colors?: [colour] (one swatch each, in one undo step; #rrggbbaa and #rgba are refused) | swatch? | gradient? | pattern?: name (default: the current fill), tint?: 0..100 (% of the global or spot `swatch`, or of the one the current fill links to), mode?: \"gray\"|\"rgb\"|\"hsb\"|\"lab\"|\"cmyk\"|\"web\" (convert the colour; lab: CIE L*a*b*, how spot colours are usually defined), global?, spot? (a spot colour, always global), group?: colour group name (solid colours only; default: ungrouped), none?: true (the None paint), paint?: paint.setFill params, keepModel?: bool (as paint.setFill)} save a colour, gradient or pattern as a swatch. A tint of a global or spot colour (below 100%, without mode, global or spot) becomes a tint swatch, \"Name 40%\", linked to its base: it follows edits to the base and applies as that tint of it. A gradient swatch holds no link to the swatch its gradient came from, and a pattern swatch holds the pattern untransformed. Names are unique (\"Sky 2\"); a colour's default name is its values (\"C=10 M=20 Y=30 K=0\", \"R=255 G=128 B=0\", \"Gray K=40\", \"L=55 a=60 b=40\") → {name, names: [every new swatch]}", + "{name?, color? | colors?: [colour] (one swatch each, in one undo step; #rrggbbaa and #rgba are refused) | swatch? | gradient? | pattern?: name (default: the current fill), tint?: 0..100 (% of the global or spot `swatch`, or of the one the current fill links to), mode?: \"gray\"|\"rgb\"|\"hsb\"|\"lab\"|\"cmyk\"|\"web\" (convert the colour; lab: CIE L*a*b*, how spot colours are usually defined), global?, spot? (a spot colour, always global), group?: colour group name (solid colours only; default: ungrouped), none?: true (the None paint), paint?: paint.setFill params, keepModel?: bool (as paint.setFill)} save a colour, gradient or pattern as a swatch. A tint of a global or spot colour (below 100%, without mode, global or spot) becomes a tint swatch, \"Name 40%\", linked to its base: it follows edits to the base and applies as that tint of it. A gradient swatch keeps the gradient's aspect (with or without start/end) and holds no link to the swatch its gradient came from, and a pattern swatch holds the pattern untransformed. Names are unique (\"Sky 2\"); a colour's default name is its values (\"C=10 M=20 Y=30 K=0\", \"R=255 G=128 B=0\", \"Gray K=40\", \"L=55 a=60 b=40\") → {name, names: [every new swatch]}", has_doc, swatch_new ), @@ -48,7 +48,7 @@ pub fn specs() -> Vec { "Swatch Options", ["Window", "Swatches"], None, - "{name, newName?, color? (e.g. {l, a, b} for a Lab colour; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill; the swatch's own color and a color given with mode keep their model), mode?: \"gray\"|\"rgb\"|\"hsb\"|\"lab\"|\"cmyk\"|\"web\" (convert the colour), global?, spot? (spot colours are always global), paint?: paint.setFill params ({color}, {gradient}, {swatch} or {pattern}) replacing the swatch's colour; gradient or pattern with one of the same kind} edit a swatch in any colour group, as one undo step. Fills, strokes, text, gradient stops and tint swatches linked to a global swatch take its new colour (at their own tint) and name; turning Global off unlinks them (they keep their colour). Colour, mode and spot apply to solid colours only; a tint swatch only takes a new name (edit its base) → {name, relinked: paints changed}", + "{name, newName?, color? (e.g. {l, a, b} for a Lab colour; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill; the swatch's own color and a color given with mode keep their model), mode?: \"gray\"|\"rgb\"|\"hsb\"|\"lab\"|\"cmyk\"|\"web\" (convert the colour), global?, spot? (spot colours are always global), paint?: paint.setFill params ({color}, {gradient} or {swatch}) or {pattern: name} replacing the swatch's colour; gradient or pattern with one of the same kind (stored as swatch.new stores it: a gradient keeps its aspect with or without start/end and holds no swatch link; a pattern is untransformed)} edit a swatch in any colour group, as one undo step. Fills, strokes, text, gradient stops and tint swatches linked to a global swatch take its new colour (at their own tint) and name; turning Global off unlinks them (they keep their colour). Colour, mode and spot apply to solid colours only; a tint swatch only takes a new name (edit its base) → {name, relinked: paints changed}", has_doc, swatch_edit ), @@ -187,11 +187,7 @@ fn swatch_new(s: &mut Session, p: &Value) -> Result { })), Paint::None => Err(bad(C, "a swatch needs a colour, gradient or pattern")), _ if spot || mode.is_some() || group.is_some() => Err(bad(C, "spot, mode and group apply to solid colours only")), - // The swatch holds the gradient itself, not a link to the swatch it may have come from. - // It keeps `geom`, which holds the aspect the swatch is applied with. - Paint::Gradient(g) => Ok(Paint::Gradient(Box::new(vectorcraft_color::GradientPaint { swatch: None, ..*g }))), - // The swatch holds the pattern untransformed, not the placement of the art it came from. - Paint::Pattern { pattern, .. } => Ok(pattern_paint(&pattern)), + paint @ (Paint::Gradient(_) | Paint::Pattern { .. }) => Ok(stored_paint(paint, p)), }) .collect::>>()?; // A name applies to a single new swatch. @@ -220,6 +216,27 @@ fn swatch_new(s: &mut Session, p: &Value) -> Result { Ok(json!({ "name": names[0], "names": names })) } +/// A gradient or pattern `paint`, parsed from the paint params `p`, as a new or edited swatch +/// stores it. +fn stored_paint(paint: Paint, p: &Value) -> Paint { + match paint { + // A gradient given an `aspect` but no vector is placed on a box so that the swatch keeps + // the aspect, as `paint.setFill` places it on each object. + Paint::Gradient(ref g) if g.geom.is_none() && g.freeform.is_none() => { + match super::gradient::place_paint(&paint, p, Some(vectorcraft_geom::Rect::new(0.0, 0.0, 100.0, 100.0))) { + Paint::Gradient(g) => Paint::Gradient(Box::new(vectorcraft_color::GradientPaint { swatch: None, ..*g })), + other => other, + } + } + // The swatch holds the gradient itself, not a link to the swatch it may have come from. + // It keeps `geom`, which holds the aspect the swatch is applied with. + Paint::Gradient(g) => Paint::Gradient(Box::new(vectorcraft_color::GradientPaint { swatch: None, ..*g })), + // The swatch holds the pattern untransformed, not the placement of the art it came from. + Paint::Pattern { pattern, .. } => pattern_paint(&pattern), + other => other, + } +} + /// The `names` list and `name` parameters, without repeats; at least one is required. pub(super) fn names_param(p: &Value, cmd: &str) -> Result> { let mut seen: HashSet = HashSet::new(); @@ -866,12 +883,21 @@ fn swatch_edit(s: &mut Session, p: &Value) -> Result { } // A replacement paint of the swatch's kind (a dropped colour or edited gradient). let paint = match p.get("paint").filter(|v| !v.is_null()) { - Some(v) => match (if given("mode") { paint_from(s, &keeping_model(v))? } else { paint_from(s, v)? }, &sw.paint) { + Some(v) => match ( + // A pattern by name, as `swatch.new` takes it. + match str_param(v, "pattern") { + Some(pat) if d.pattern(pat).is_some() => Some(pattern_paint(pat)), + Some(pat) => return Err(bad(C, format!("no pattern `{pat}`"))), + None if given("mode") => paint_from(s, &keeping_model(v))?, + None => paint_from(s, v)?, + }, + &sw.paint, + ) { (Some(Paint::Solid { color, .. }), Paint::Solid { .. }) => Some(Paint::solid(color)), - (Some(Paint::Gradient(g)), Paint::Gradient(_)) => { - Some(Paint::Gradient(Box::new(vectorcraft_color::GradientPaint { geom: None, swatch: None, ..*g }))) + // Stored as `swatch.new` stores it. + (Some(new @ Paint::Gradient(_)), Paint::Gradient(_)) | (Some(new @ Paint::Pattern { .. }), Paint::Pattern { .. }) => { + Some(stored_paint(new, v)) } - (Some(new @ Paint::Pattern { .. }), Paint::Pattern { .. }) => Some(new), _ => return Err(bad(C, format!("`{name}` takes a paint of its own kind (colour, gradient or pattern)"))), }, None => None, diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index 9ed7f3252b..ee843df8dd 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -40,7 +40,7 @@ pub fn specs() -> Vec { "Character", [], None, - "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), story?: bool = false (all the text of every frame of the threaded story `id` is a frame of, in one undo step; no `start` or `end`), font?, style?, size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\" (the space after each character), kerningBefore?: 1/1000 em -1000..10000 (the space before a character that starts a line by itself: the first character of the text, of a paragraph or after a forced line break; no effect elsewhere; 0 by default), baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), fill?: colour|\"none\", stroke?: colour|\"none\" (#rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", \"salt=2\", …] (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; the range is shaped with its word, so a letter's alternate keeps it joined to its neighbours), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; on a vertical path a positive Up/Down moves it toward the path's start and a positive Left/Right to the path's left; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), warichu?: bool (Character panel menu › Warichu, with Show East Asian Options: the characters are set at warichuScale percent of their size and stacked on warichuLines lines inside their line, one above the other in horizontal type and side by side in vertical type, the first line above or to the right; a stretch of them is one block with the settings of its first character that stays whole on one line and may run past its end; type on a path sets them at their own size), warichuLines?: 1..6 (default 2), warichuGap?: pt 0..100 (the space between the lines, default 0), warichuScale?: % 10..100 (default 50), warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Warichu Settings: how the lines line up along the block, which is as long as its longest line; the justify values spread every line but the last, which is set left, centered or right, or spread with justifyAll; auto, the default, sets them as justifyLeft; left and right are top and bottom in vertical type; none of them turns warichu on), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options: space before and after each character in reading order, on its left and right in left-to-right type, on its right and left in right-to-left type, above and below it in vertical type; a ligature or a letter with its marks takes the values of its first character; line wrapping counts it, alignment keeps it at a line's ends and justification does not stretch or narrow it; 0 by default; a value that is not a number or is outside the range is refused, naming the key), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options: the share of the blank space on each side of each character's ink, inside its own width, that is taken away in horizontal type, the glyph keeping its shape; 100 sets the ink edge to edge; a character without ink, such as a space, keeps its width; a ligature or a letter with its marks takes the value of its first character; tracking, kerning and Insert Aki are added after it, and justification keeps it; vertical type keeps the characters' spacing; 0 by default; a value that is not a number or is outside the range is refused), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference: the height of the font that size measures, the em box by default; with a font that has no such height, or one outside 0.1 to 2 em, the em box), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes), glyphAlternate?: null (takes away the glyph choice text.setGlyphAlternate made on the characters, in the same undo step as the other attributes; any other value is refused)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", + "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), story?: bool = false (all the text of every frame of the threaded story `id` is a frame of, in one undo step; no `start` or `end`), font?, style?, size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\" (the space after each character), kerningBefore?: 1/1000 em -1000..10000 (the space before a character that starts a line by itself: the first character of the text, of a paragraph or after a forced line break; no effect elsewhere; 0 by default), baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), fill?: colour|\"none\", stroke?: colour|\"none\" (#rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", \"salt=2\", …] (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; the range is shaped with its word, so a letter's alternate keeps it joined to its neighbours), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; on a vertical path a positive Up/Down moves it toward the path's start and a positive Left/Right to the path's left; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), warichu?: bool (Character panel menu › Warichu, with Show East Asian Options: the characters are set at warichuScale percent of their size and stacked on warichuLines lines inside their line, one above the other in horizontal type and side by side in vertical type, the first line above or to the right; a stretch of them is one block with the settings of its first character that stays whole on one line and may run past its end; type on a path sets them at their own size), warichuLines?: 1..6 (default 2), warichuGap?: pt 0..100 (the space between the lines, default 0), warichuScale?: % 10..100 (default 50), warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Warichu Settings: how the lines line up along the block, which is as long as its longest line; the justify values spread every line but the last, which is set left, centered or right, or spread with justifyAll; auto, the default, sets them as justifyLeft; left and right are top and bottom in vertical type; none of them turns warichu on), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options: space before and after each character in reading order, on its left and right in left-to-right type, on its right and left in right-to-left type, above and below it in vertical type; a ligature or a letter with its marks takes the values of its first character; line wrapping counts it, alignment keeps it at a line's ends and justification does not stretch or narrow it; 0 by default; a value that is not a number or is outside the range is refused, naming the key), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options: the share of the blank space on each side of each character's ink, inside its own width, that is taken away in horizontal type, the glyph keeping its shape; 100 sets the ink edge to edge; a character without ink, such as a space, keeps its width; a ligature or a letter with its marks takes the value of its first character; tracking, kerning and Insert Aki are added after it, and justification keeps it; vertical type keeps the characters' spacing; 0 by default; a value that is not a number or is outside the range is refused), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), glyphForm?: \"traditional\"|\"expert\"|\"jis04\"|\"jis90\"|\"jis78\"|\"jis83\"|\"fullWidth\"|\"halfWidth\"|\"thirdWidth\"|\"quarterWidth\"|\"default\" (Glyphs panel menu, with Show East Asian Options: the characters are drawn in that form of the font, the OpenType feature trad, expt, jp04, jp90, jp78, jp83, fwid, hwid, twid or qwid, one form at a time; a character the font has no such glyph for keeps its own; \"default\", Revert To Default Forms, draws the font's default glyphs; another value is refused), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference: the height of the font that size measures, the em box by default; with a font that has no such height, or one outside 0.1 to 2 em, the em box), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes), glyphAlternate?: null (takes away the glyph choice text.setGlyphAlternate made on the characters, in the same undo step as the other attributes; any other value is refused)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", has_doc, set_range_style ), @@ -473,6 +473,7 @@ pub(crate) struct CharChange { standard_vertical_roman: Option, no_break: Option, digits: Option, + glyph_form: Option, /// The language to set: a tag, or `None` for the default. language: Option>, font_axes: Option, @@ -571,6 +572,20 @@ pub(crate) fn digits_param(p: &Value, cmd: &str) -> Result Result> { + use vectorcraft_doc::GlyphForm; + let Some(v) = p.get("glyphForm").filter(|v| !v.is_null()) else { return Ok(None) }; + let Some(f) = v.as_str().and_then(GlyphForm::from_id) else { + let ids: Vec = GlyphForm::ALL.iter().map(|f| format!("\"{}\"", f.id())).collect(); + return Err(bad(cmd, format!("`glyphForm` must be one of {}", ids.join(", ")))); + }; + Ok(Some(f)) +} + /// `language: name|tag` (one of Document Setup's languages, case-insensitive) → the language to /// set ([`vectorcraft_doc::CharStyle::language`]: `None` inside for the default). pub(crate) fn language_param(p: &Value, cmd: &str) -> Result>> { @@ -840,6 +855,7 @@ impl CharChange { standard_vertical_roman: flag("standardVerticalRoman"), no_break: flag("noBreak"), digits: digits_param(p, cmd)?, + glyph_form: glyph_form_param(p, cmd)?, language: language_param(p, cmd)?, font_axes: font_axes_param(p, cmd)?, font_height_reference: font_height_reference_param(p, cmd)?, @@ -905,6 +921,7 @@ impl CharChange { && self.standard_vertical_roman.is_none() && self.no_break.is_none() && self.digits.is_none() + && self.glyph_form.is_none() && self.language.is_none() && self.font_axes.is_none() && self.font_height_reference.is_none() @@ -1070,6 +1087,9 @@ impl CharChange { if let Some(v) = self.digits { st.digits = v; } + if let Some(v) = self.glyph_form { + st.glyph_form = v; + } if let Some(v) = self.font_height_reference { st.font_height_reference = v; } diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index 17d453abf4..18f87d44f7 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -228,6 +228,7 @@ pub fn char_attrs(v: &CharStyle) -> Map { ("digits", json!(v.digits)), ("fontHeightReference", json!(v.font_height_reference)), ("language", json!(v.language)), + ("glyphForm", json!(v.glyph_form)), ] { m.insert(k.into(), x); } diff --git a/crates/engine/src/cmd/textwrap.rs b/crates/engine/src/cmd/textwrap.rs index d5eefe9d4d..9ff48848af 100644 --- a/crates/engine/src/cmd/textwrap.rs +++ b/crates/engine/src/cmd/textwrap.rs @@ -8,7 +8,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::{Document, NodeId, NodeKind, TextWrap}; use super::typecmd::refresh_bounds; -use super::{CommandSpec, EngineError, Result, Session, bool_or, checked_ids_or_selection, cmd, f64_or, has_selection}; +use super::{CommandSpec, EngineError, Result, Session, bad, checked_ids_or_selection, cmd, has_selection, number_or, switch_or}; pub fn specs() -> Vec { vec![ @@ -17,7 +17,7 @@ pub fn specs() -> Vec { "Make", ["Object", "Text Wrap"], None, - "{offset?: pt (6), invert?: bool, ids?} area type below the selected objects (same layer) wraps around them; a negative offset (to -1000) lets the text that far into them → {ids}", + "{offset?: pt (6), invert?: bool, ids?} area type below the selected objects (same layer) wraps around them; offset -1000 to 1000 (a negative one lets the text that far into them); an offset outside that range or not a number, or an invert that is not true or false, is an error → {ids}", has_selection, make ), @@ -27,7 +27,7 @@ pub fn specs() -> Vec { "Text Wrap Options…", ["Object", "Text Wrap"], None, - "{offset?: pt, invert?: bool, ids?} set the options of the selected wrap objects (offset -1000 to 1000; a negative one lets text into the objects); no options → the current {offset, invert}", + "{offset?: pt, invert?: bool, ids?} set the options of the selected wrap objects (offset -1000 to 1000; a negative one lets text into the objects); an offset outside that range or not a number, or an invert that is not true or false, is an error; no options (or null ones) → the current {offset, invert}", has_selection, options ), @@ -37,14 +37,23 @@ pub fn specs() -> Vec { /// The Offset a wrap object takes, in points. pub const TEXT_WRAP_OFFSET_RANGE: std::ops::RangeInclusive = -1000.0..=1000.0; -fn wrap_param(p: &Value, base: TextWrap) -> TextWrap { - let (lo, hi) = (*TEXT_WRAP_OFFSET_RANGE.start(), *TEXT_WRAP_OFFSET_RANGE.end()); - TextWrap { offset: f64_or(p, "offset", base.offset).clamp(lo, hi), invert: bool_or(p, "invert", base.invert) } +/// The options `p` gives, with `base` for an omitted or null `offset` or `invert`. An `offset` that is +/// not a number or lies outside [`TEXT_WRAP_OFFSET_RANGE`], or an `invert` that is not true or false, +/// is an error. `base`'s offset is kept as it is. +fn wrap_param(p: &Value, base: TextWrap, cmd: &str) -> Result { + let key = "offset"; + let given = p.get(key).is_some_and(|v| !v.is_null()); + let offset = number_or(p, key, base.offset, cmd)?; + if given && !TEXT_WRAP_OFFSET_RANGE.contains(&offset) { + let (lo, hi) = (TEXT_WRAP_OFFSET_RANGE.start(), TEXT_WRAP_OFFSET_RANGE.end()); + return Err(bad(cmd, format!("`{key}` must be from {lo} to {hi}"))); + } + Ok(TextWrap { offset, invert: switch_or(p, "invert", base.invert, cmd)? }) } fn make(s: &mut Session, p: &Value) -> Result { let ids = checked_ids_or_selection(s, p, "object.textWrap.make")?; - let w = wrap_param(p, TextWrap::default()); + let w = wrap_param(p, TextWrap::default(), "object.textWrap.make")?; s.edit("Make Text Wrap", |d, _| { for id in &ids { let n = d.node_mut(*id).ok_or(EngineError::NoNode(*id))?; @@ -86,10 +95,10 @@ fn options(s: &mut Session, p: &Value) -> Result { let d = &s.doc()?.doc; ids.iter().find_map(|i| d.node(*i).and_then(|n| n.extras().wrap)).unwrap_or_default() }; - if p.get("offset").is_none() && p.get("invert").is_none() { + if ["offset", "invert"].iter().all(|k| p.get(k).is_none_or(Value::is_null)) { return Ok(json!({ "offset": current.offset, "invert": current.invert })); } - let w = wrap_param(p, current); + let w = wrap_param(p, current, "object.textWrap.options")?; s.edit("Text Wrap Options", |d, _| { for id in &ids { if let Some(n) = d.node_mut(*id) @@ -212,11 +221,72 @@ mod tests { s.execute("edit.undo", &json!({})).unwrap(); assert_eq!(s.execute("object.textWrap.options", &json!({})).unwrap()["offset"], json!(6.0)); assert!(beside(&s).iter().all(|x| (x - 206.0).abs() < 1e-6), "{:?}", beside(&s)); - // An offset past -1000 is kept at -1000: the whole object lets text through. - assert_eq!(s.execute("object.textWrap.options", &json!({"offset": -5000})).unwrap()["offset"], json!(-1000.0)); + // An offset of -1000 lets the text through the whole object. + assert_eq!(s.execute("object.textWrap.options", &json!({"offset": -1000})).unwrap()["offset"], json!(-1000.0)); assert!(lines(&s, t).iter().all(|l| l.0 < 1.0 && l.1 > 300.0)); } + /// An offset that is not a number or lies outside -1000 to 1000 pt, or an invert that is not + /// true or false, is an error for Make and Options, and leaves the options and the history as + /// they were. Omitted and null values take the default, and the range's ends are accepted. + #[test] + fn text_wrap_commands_refuse_bad_offsets_and_inverts_without_editing() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 80, "height": 80})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let wrap = |s: &Session| s.doc().unwrap().doc.node(NodeId(id)).unwrap().extras().wrap; + let undo = |s: &Session| s.doc().unwrap().history.undo.len(); + let refused = [ + (json!({"offset": "12"}), "`offset` must be a number"), + (json!({"offset": true}), "`offset` must be a number"), + (json!({"offset": [12]}), "`offset` must be a number"), + (json!({"offset": {"pt": 12}}), "`offset` must be a number"), + (json!({"offset": 1000.5}), "`offset` must be from -1000 to 1000"), + (json!({"offset": -1000.5}), "`offset` must be from -1000 to 1000"), + (json!({"offset": 5000}), "`offset` must be from -1000 to 1000"), + (json!({"offset": 12, "invert": "true"}), "`invert` must be true or false"), + (json!({"offset": 12, "invert": 1}), "`invert` must be true or false"), + (json!({"invert": "false"}), "`invert` must be true or false"), + ]; + let start = undo(&s); + for (p, msg) in &refused { + let e = s.execute("object.textWrap.make", p).unwrap_err().to_string(); + assert!(e.contains(msg), "make {p}: {e}"); + assert!(wrap(&s).is_none(), "make {p} made a wrap"); + assert_eq!(undo(&s), start, "make {p} added history"); + } + // Omitted and null values: Make's 6 pt default. + s.execute("object.textWrap.make", &json!({"offset": null, "invert": null})).unwrap(); + assert_eq!(wrap(&s), Some(vectorcraft_doc::TextWrap { offset: 6.0, invert: false })); + s.execute("object.textWrap.options", &json!({"offset": 40, "invert": true})).unwrap(); + let before = undo(&s); + for (p, msg) in &refused { + let e = s.execute("object.textWrap.options", p).unwrap_err().to_string(); + assert!(e.contains(msg), "options {p}: {e}"); + assert_eq!(wrap(&s), Some(vectorcraft_doc::TextWrap { offset: 40.0, invert: true }), "options {p}"); + assert_eq!(undo(&s), before, "options {p} added history"); + } + // Null options read the current ones without an undo step; a null one keeps its value. + assert_eq!(s.execute("object.textWrap.options", &json!({"offset": null, "invert": null})).unwrap(), json!({"offset": 40.0, "invert": true})); + assert_eq!(undo(&s), before); + assert_eq!( + s.execute("object.textWrap.options", &json!({"offset": null, "invert": false})).unwrap(), + json!({"offset": 40.0, "invert": false}) + ); + // The range's ends are accepted by both commands. + for (command, offset) in + [("object.textWrap.options", 1000), ("object.textWrap.options", -1000), ("object.textWrap.make", 1000), ("object.textWrap.make", -1000)] + { + s.execute(command, &json!({ "offset": offset })).unwrap(); + assert_eq!(wrap(&s).unwrap().offset, f64::from(offset), "{command} {offset}"); + } + // A stored offset outside the range (from a file) is kept when only Invert Wrap changes. + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + d.node_mut(NodeId(id)).unwrap().extras_mut().wrap = Some(vectorcraft_doc::TextWrap { offset: 5000.0, invert: false }); + assert_eq!(s.execute("object.textWrap.options", &json!({"invert": true})).unwrap(), json!({"offset": 5000.0, "invert": true})); + } + #[test] fn text_flows_on_both_sides_of_a_centred_object() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/threads.rs b/crates/engine/src/cmd/threads.rs index 35f67f64c2..ad41d1d220 100644 --- a/crates/engine/src/cmd/threads.rs +++ b/crates/engine/src/cmd/threads.rs @@ -400,6 +400,8 @@ thread_local! { /// Tests: how many times [`story_of`] and [`ThreadIndex::of`] went through the document's /// threads on this thread. static THREAD_SCANS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Tests: how many times [`story_in`] went through a thread's frames on this thread. + static STORY_BUILDS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Tests: how many times [`story_of`] and [`ThreadIndex::of`] have gone through the document's @@ -409,6 +411,12 @@ pub(crate) fn thread_scans() -> usize { THREAD_SCANS.with(std::cell::Cell::get) } +/// Tests: how many times [`story_in`] has gone through a thread's frames on this thread. +#[cfg(test)] +pub(crate) fn story_builds() -> usize { + STORY_BUILDS.with(std::cell::Cell::get) +} + /// The frames of the thread that `id` is a frame of, in thread order, each area type or type on a /// path; empty when `id` is in no thread or the thread has fewer than two such frames. pub(crate) fn story_of(d: &Document, id: NodeId) -> Vec { @@ -420,6 +428,8 @@ pub(crate) fn story_of(d: &Document, id: NodeId) -> Vec { /// [`story_of`] for `id` in `thread`, the first of the document's threads that lists it. pub(crate) fn story_in(d: &Document, thread: &[NodeId], id: NodeId) -> Vec { + #[cfg(test)] + STORY_BUILDS.with(|c| c.set(c.get() + 1)); let frames: Vec = thread.iter().copied().filter(|f| text_of(d, *f).is_some()).collect(); if frames.len() >= 2 && frames.contains(&id) { frames } else { vec![] } } diff --git a/crates/engine/src/cmd/typecmd.rs b/crates/engine/src/cmd/typecmd.rs index b3fab4a2bc..31bcad4671 100644 --- a/crates/engine/src/cmd/typecmd.rs +++ b/crates/engine/src/cmd/typecmd.rs @@ -23,7 +23,7 @@ pub fn specs() -> Vec { "Vertical", ["Type", "Orientation"], None, - "{ids?|id?} set vertical writing for the selected type and every frame of its threads → {vertical, ids}", + "{ids?|id?} set vertical writing for the selected type and every frame of its threads; no undo step when every object is already vertical → {vertical, ids}", has_selection, |s, p| orientation(s, p, true) ), @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Horizontal", ["Type", "Orientation"], None, - "{ids?|id?} set horizontal writing for the selected type and every frame of its threads → {vertical, ids}", + "{ids?|id?} set horizontal writing for the selected type and every frame of its threads; no undo step when every object is already horizontal → {vertical, ids}", has_selection, |s, p| orientation(s, p, false) ), @@ -59,7 +59,7 @@ pub fn specs() -> Vec { "Optical Margin Alignment", ["Type"], None, - "{ids?|id?, on?: bool} turn Optical Margin Alignment on or off for the selected type and every frame of its threads (on omitted: the opposite of the first object's setting): in every paragraph of point and area type, quotation marks, hyphens, full stops and commas at a line's start or end hang wholly outside the margin there; asterisks, tildes, ellipses, en and em dashes, colons and semicolons hang by half; and A, V, W, Y, v, w and y hang by a tenth of their advance; a left-aligned line hangs at its left margin, a right-aligned line hangs at its right margin, and centered and justified lines hang at both; Auto aligns a right-to-left line at its right; type on a path hangs at the start bracket when its line is placed there, hangs at the end bracket when the line is placed there, and hangs at both when it is centered → {on, ids}", + "{ids?|id?, on?: bool} turn Optical Margin Alignment on or off for the selected type and every frame of its threads (on omitted: the opposite of the first object's setting): in every paragraph of point and area type, quotation marks, hyphens, full stops and commas at a line's start or end hang wholly outside the margin there; asterisks, tildes, ellipses, en and em dashes, colons and semicolons hang by half; and A, V, W, Y, v, w and y hang by a tenth of their advance; a left-aligned line hangs at its left margin, a right-aligned line hangs at its right margin, and centered and justified lines hang at both; Auto aligns a right-to-left line at its right; type on a path hangs at the start bracket when its line is placed there, hangs at the end bracket when the line is placed there, and hangs at both when it is centered; no undo step when every object already has the setting → {on, ids}", has_selection, optical_margin_alignment ), @@ -68,7 +68,7 @@ pub fn specs() -> Vec { "System Layout", [], None, - "{on?: bool} turn System Layout on or off for the document (on omitted: the opposite of the document's setting) and every text object in it. On, each character that takes any space advances by a whole number of points, at least one, so small type does not run together; a character with no width stays at none. Off (the default, and what a document from before it reads as), spacing uses fractions of a point. New point, area and path type inherits the document's setting → {on}", + "{on?: bool} turn System Layout on or off for the document (on omitted: the opposite of the document's setting) and every text object in it. On, each character that takes any space advances by a whole number of points, at least one, so small type does not run together; a character with no width stays at none. Off (the default, and what a document from before it reads as), spacing uses fractions of a point. New point, area and path type inherits the document's setting. No undo step when the document and every text object already have the setting → {on}", has_doc, system_layout ), @@ -77,7 +77,7 @@ pub fn specs() -> Vec { "Fractional Widths", [], None, - "{ids?|id?, on?: bool} turn Fractional Widths on or off for the selected type and every frame of its threads (on omitted: the opposite of the first object's setting). On (the default, and what a document from before it reads as), spacing between characters uses fractions of a point. Off, each character that takes any space advances by a whole number of points, at least one, so small type does not run together; a character with no width stays at none. The setting is the whole type object, not a range of characters → {on, ids}", + "{ids?|id?, on?: bool} turn Fractional Widths on or off for the selected type and every frame of its threads (on omitted: the opposite of the first object's setting). On (the default, and what a document from before it reads as), spacing between characters uses fractions of a point. Off, each character that takes any space advances by a whole number of points, at least one, so small type does not run together; a character with no width stays at none. The setting is the whole type object, not a range of characters. No undo step when every object already has the setting → {on, ids}", has_selection, fractional_widths ), @@ -86,7 +86,7 @@ pub fn specs() -> Vec { "Set Text", [], None, - "{id?|ids?, text} replace the contents of text objects (keeps the first run's style) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits)}", + "{id?|ids?, text} replace the contents of text objects (keeps the first run's style); no undo step when no object changes (each already has the text in one style, every paragraph with the first one's attributes, and no ruby) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits)}", has_doc, set_text ), @@ -104,7 +104,7 @@ pub fn specs() -> Vec { "Reshape Type Area", [], None, - "{id, anchors: [[subpath, anchor]…], dx, dy} or {items: [{id, anchors}…], dx, dy} move anchors of area type's frame (the type area) by dx, dy points, with their handles; the text reflows at its size, through its thread too (what Direct Selection does dragging a frame corner or edge, or the frame anchors its marquee selected, and the arrow keys nudging those); with items, every listed frame moves in one step", + "{id, anchors: [[subpath, anchor]…], dx, dy} or {items: [{id, anchors}…], dx, dy} move anchors of area type's frame (the type area) by dx, dy points, with their handles; the text reflows at its size, through its thread too (what Direct Selection does dragging a frame corner or edge, or the frame anchors its marquee selected, and the arrow keys nudging those); with items, every listed frame moves in one step; no undo step when no frame changes (dx and dy both 0)", has_doc, reshape_area ), @@ -113,7 +113,7 @@ pub fn specs() -> Vec { "Reshape Type Path", [], None, - "{id, anchors: [[subpath, anchor]…], dx, dy} move anchors of type on a path's path by dx, dy points, with their handles; the start and end brackets keep their fractions of the path and the text reflows along it (what Direct Selection does dragging an anchor of the path)", + "{id, anchors: [[subpath, anchor]…], dx, dy} move anchors of type on a path's path by dx, dy points, with their handles; the start and end brackets keep their fractions of the path and the text reflows along it (what Direct Selection does dragging an anchor of the path); no undo step when the path does not change (dx and dy both 0)", has_doc, reshape_path ), @@ -122,7 +122,7 @@ pub fn specs() -> Vec { "Move Type Path Handle", [], None, - "{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool} move a direction handle of an anchor of type on a path's path to (x, y), as path.setHandle moves a path's (independent: that side only, the anchor becomes a corner); the start and end brackets keep their fractions of the path and the text reflows along it (what Direct Selection does dragging a handle of the path)", + "{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool} move a direction handle of an anchor of type on a path's path to (x, y), as path.setHandle moves a path's (independent: that side only, the anchor becomes a corner); the start and end brackets keep their fractions of the path and the text reflows along it (what Direct Selection does dragging a handle of the path); no undo step when the handle is already there and the path does not change", has_doc, set_path_handle ), @@ -131,7 +131,7 @@ pub fn specs() -> Vec { "Fit Headline", ["Type"], None, - "{ids?|id?} track the first line of area type so it fills the frame width → {tracking}", + "{ids?|id?} track the first line of area type so it fills the frame width; no undo step when the first line already has that tracking → {tracking}", has_selection, fit_headline ), @@ -140,7 +140,7 @@ pub fn specs() -> Vec { "Character", [], None, - "{ids?|id?, font?, style? (font alone: the style is kept when the new family has it, else its closest), size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", tracking?: 1/1000 em, justify?: \"auto\" (the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\", fill?: colour|\"none\", stroke?: colour|\"none\" (characters without a stroke weight get 1 pt; #rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt (the character stroke's weight, in document points as stroke.set), features?: [\"dlig\", \"-liga\", \"salt=2\", …] OpenType (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), start?: byte, end?: byte} (size/leading are document points after object scaling; with a range: the character attributes style that range and justify the paragraphs it touches; without: all the text) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits), warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", + "{ids?|id?, font?, style? (font alone: the style is kept when the new family has it, else its closest), size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", tracking?: 1/1000 em, justify?: \"auto\" (the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\", fill?: colour|\"none\", stroke?: colour|\"none\" (characters without a stroke weight get 1 pt; #rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt (the character stroke's weight, in document points as stroke.set), features?: [\"dlig\", \"-liga\", \"salt=2\", …] OpenType (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), start?: byte, end?: byte} (size/leading are document points after object scaling; with a range: the character attributes style that range and justify the paragraphs it touches; without: all the text; no undo step when no character, paragraph or graph label style changes) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits), warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", has_doc, set_style ), @@ -149,7 +149,7 @@ pub fn specs() -> Vec { "Ruby…", [], None, - "{ids?|id?, start?: byte, end?: byte, text?: reading, position?: above|below (vertical type: right|left), align?: start|center|end, size?: 1–100 (percent of the base text's size, default 50), overhang?: bool (default true), remove?: bool} set the ruby (furigana) over the selected text's bytes in `start..end` (without them: all its text): the reading over the base characters, above them in horizontal type and right of them in vertical type; `remove` takes the ruby off the range instead → {ids, ruby: [{start, end, text, position, align, sizePercent, overhang}…] (the first object's ruby)}", + "{ids?|id?, start?: byte, end?: byte, text?: reading, position?: above|below (vertical type: right|left), align?: start|center|end, size?: 1–100 (percent of the base text's size, default 50), overhang?: bool (default true), remove?: bool} set the ruby (furigana) over the selected text's bytes in `start..end` (without them: all its text): the reading over the base characters, above them in horizontal type and right of them in vertical type; `remove` takes the ruby off the range instead; no undo step when the ruby does not change (the same reading and options again, or `remove` where there is none) → {ids, ruby: [{start, end, text, position, align, sizePercent, overhang}…] (the first object's ruby)}", has_selection, ruby ), @@ -157,24 +157,30 @@ pub fn specs() -> Vec { } /// Type › Type Orientation: set vertical or horizontal writing on every selected text object and -/// every frame of their threads, in one undo step. +/// every frame of their threads, in one undo step (none when nothing changes). fn orientation(s: &mut Session, p: &Value, vertical: bool) -> Result { let ids = super::threads::with_threads(&s.doc()?.doc, &text_targets(s, p, "Text Orientation")?); - s.edit("Text Orientation", |d, _| { + // When every object already has the orientation, the document and its undo history stay as they are. + super::colorcmds::edit_if_changed(s, "Text Orientation", |_, d| { + let mut changed = false; for id in &ids { let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else { return Err(EngineError::NoNode(*id)); }; - t.vertical = vertical; - refresh_bounds(t); + if t.vertical != vertical { + t.vertical = vertical; + refresh_bounds(t); + changed = true; + } } - Ok(()) + Ok(((), changed)) })?; Ok(json!({"vertical": vertical, "ids": ids.iter().map(|id| id.0).collect::>()})) } /// Type › Optical Margin Alignment: set `on` (without it, the opposite of the first object's -/// setting) on every selected text object and every frame of their threads, in one undo step. +/// setting) on every selected text object and every frame of their threads, in one undo step +/// (none when nothing changes). fn optical_margin_alignment(s: &mut Session, p: &Value) -> Result { let ids = super::threads::with_threads(&s.doc()?.doc, &text_targets(s, p, "Optical Margin Alignment")?); let first = ids.first().and_then(|id| match s.doc().ok()?.doc.node(*id).map(|n| &n.kind) { @@ -182,29 +188,38 @@ fn optical_margin_alignment(s: &mut Session, p: &Value) -> Result { _ => None, }); let on = switch_or(p, "on", !first.unwrap_or(false), "type.opticalMarginAlignment")?; - s.edit("Optical Margin Alignment", |d, _| { + // When every object already has the setting, the document and its undo history stay as they are. + super::colorcmds::edit_if_changed(s, "Optical Margin Alignment", |_, d| { + let mut changed = false; for id in &ids { let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else { return Err(EngineError::NoNode(*id)); }; - t.optical_margin = on; - refresh_bounds(t); + if t.optical_margin != on { + t.optical_margin = on; + refresh_bounds(t); + changed = true; + } } - Ok(()) + Ok(((), changed)) })?; Ok(json!({"on": on, "ids": ids.iter().map(|id| id.0).collect::>()})) } /// Character panel menu › System Layout: set `on` (without it, the opposite of the document's -/// setting) on the document and every text object, in one undo step. Off is the default. +/// setting) on the document and every text object, in one undo step (none when nothing changes). +/// Off is the default. fn system_layout(s: &mut Session, p: &Value) -> Result { let current = s.doc()?.doc.setup.system_layout; let on = switch_or(p, "on", !current, "type.systemLayout")?; - s.edit("System Layout", |d, _| { + // When the document and every text object already have the setting, the document and its undo + // history stay as they are. + super::colorcmds::edit_if_changed(s, "System Layout", |_, d| { + let mut changed = d.setup.system_layout != on; d.setup.system_layout = on; let mut ids = vec![]; d.walk(|n| { - if matches!(n.kind, NodeKind::Text(_)) { + if matches!(&n.kind, NodeKind::Text(t) if t.system_layout != on) { ids.push(n.id); } }); @@ -214,15 +229,16 @@ fn system_layout(s: &mut Session, p: &Value) -> Result { }; t.system_layout = on; refresh_bounds(t); + changed = true; } - Ok(()) + Ok(((), changed)) })?; Ok(json!({ "on": on })) } /// Character panel menu › Fractional Widths: set `on` (without it, the opposite of the first /// object's setting) on every selected text object and every frame of their threads, in one undo -/// step. On is the default. +/// step (none when nothing changes). On is the default. fn fractional_widths(s: &mut Session, p: &Value) -> Result { let ids = super::threads::with_threads(&s.doc()?.doc, &text_targets(s, p, "Fractional Widths")?); let first = ids.first().and_then(|id| match s.doc().ok()?.doc.node(*id).map(|n| &n.kind) { @@ -230,22 +246,27 @@ fn fractional_widths(s: &mut Session, p: &Value) -> Result { _ => None, }); let on = switch_or(p, "on", !first.unwrap_or(true), "type.fractionalWidths")?; - s.edit("Fractional Widths", |d, _| { + // When every object already has the setting, the document and its undo history stay as they are. + super::colorcmds::edit_if_changed(s, "Fractional Widths", |_, d| { + let mut changed = false; for id in &ids { let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else { return Err(EngineError::NoNode(*id)); }; - t.fractional_widths = on; - refresh_bounds(t); + if t.fractional_widths != on { + t.fractional_widths = on; + refresh_bounds(t); + changed = true; + } } - Ok(()) + Ok(((), changed)) })?; Ok(json!({"on": on, "ids": ids.iter().map(|id| id.0).collect::>()})) } /// Type › Ruby: set or remove the ruby (furigana) over a byte range of the selected type in one -/// undo step. Without `start`/`end` the range is all the text; a new reading replaces the ruby -/// over the range. The reply lists the first object's ruby (start/end in bytes of its plain text). +/// undo step (none when nothing changes). Without `start`/`end` the range is all the text; a new +/// reading replaces the ruby over the range. The reply lists the first object's ruby (start/end in bytes of its plain text). fn ruby(s: &mut Session, p: &Value) -> Result { const C: &str = "type.ruby"; let ids = text_targets(s, p, C)?; @@ -272,7 +293,8 @@ fn ruby(s: &mut Session, p: &Value) -> Result { } let overhang = switch_or(p, "overhang", true, C)?; let mut first: Option = None; - s.edit("Ruby", |d, _| { + // The same reading again, or a removal where there is no ruby, is no undo step. + edit_if_nodes_changed(s, "Ruby", &ids, |d| { for id in &ids { let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else { return Err(EngineError::NoNode(*id)); @@ -299,7 +321,7 @@ fn ruby(s: &mut Session, p: &Value) -> Result { first = Some(serde_json::to_value(&t.ruby).unwrap_or(Value::Null)); } } - Ok(()) + Ok(((), false)) })?; Ok(json!({"ids": ids.iter().map(|id| id.0).collect::>(), "ruby": first.unwrap_or(Value::Null)})) } @@ -594,6 +616,21 @@ fn scale_text_attributes(s: &mut Session, p: &Value) -> Result { Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>(), "changed": changed })) } +/// A path (or compound path) of `outline`, a piece of type `t`'s outline in text space, painted as +/// run `run` and placed in the document as the canvas paints it ([`paint_type_piece`]: unplaced +/// gradients fitted to `bounds`, the layout's bounds, stroke weights scaled by the type's +/// transform); `None` when the piece has no path. +fn type_piece(d: &mut Document, t: &TextObject, bounds: kurbo::Rect, run: usize, outline: &kurbo::BezPath) -> Option { + let path = PathData::from_bezpath(outline); + if path.is_empty() { + return None; + } + let st = t.runs.get(run).map(|r| r.style.clone()).unwrap_or_else(|| t.first_style()); + let mut node = shape_node(d, path, None); + vectorcraft_render::effects::paint_type_piece(&mut node, &st, bounds, t.xf); + Some(node) +} + fn create_outlines(s: &mut Session, _: &Value) -> Result { let roots = selected_roots(s)?; let ids = s.edit("Create Outlines", |d, sel| { @@ -601,6 +638,8 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result { if texts.is_empty() { return Err(EngineError::Other("Create Outlines: select text objects".into())); } + // Outlining a graph's labels does not move or scale its plot at the next redraw. + let graphs = super::graph::graphs_holding(d, &texts); let before = (!super::dimension::reached(d, &roots).is_empty()).then(|| d.clone()); let ended = super::dimension::end_links(d, &roots); let mut new_sel: Vec = roots.iter().copied().filter(|r| !texts.contains(r)).collect(); @@ -636,14 +675,9 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result { children.push(Arc::new(d.reid(&art))); break 'glyph; } - let path = PathData::from_bezpath(&g.outline).transformed(t.xf); - if path.is_empty() { - break 'glyph; + if let Some(node) = type_piece(d, t, lay.bounds, g.run, &g.outline) { + children.push(Arc::new(node)); } - let st = t.runs.get(g.run).map(|r| r.style.clone()).unwrap_or_else(|| t.first_style()); - let mut node = shape_node(d, path, None); - node.appearance = st.appearance().into(); - children.push(Arc::new(node)); } run_end.insert(g.run, children.len()); } @@ -652,13 +686,7 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result { // nothing there either). let mut ruby: Vec<(usize, Arc)> = vec![]; for g in &lay.ruby { - let path = PathData::from_bezpath(&g.outline).transformed(t.xf); - if path.is_empty() { - continue; - } - let st = t.runs.get(g.run).map(|r| r.style.clone()).unwrap_or_else(|| t.first_style()); - let mut node = shape_node(d, path, None); - node.appearance = st.appearance().into(); + let Some(node) = type_piece(d, t, lay.bounds, g.run, &g.outline) else { continue }; // After the glyphs of its run and of the runs before it. let at = run_end.range(..=g.run).map(|(_, end)| *end).max().unwrap_or(0); ruby.push((at, Arc::new(node))); @@ -683,10 +711,9 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result { // Underline and strikethrough bars become paths of their run's paint too (#847). for (run, bar) in vectorcraft_text::decorations(&lay, vectorcraft_text::FontDb::global(), t) { all.extend(bar.iter()); - let st = t.runs.get(run).map(|r| r.style.clone()).unwrap_or_else(|| t.first_style()); - let mut node = shape_node(d, PathData::from_bezpath(&bar).transformed(t.xf), None); - node.appearance = st.appearance().into(); - children.push(Arc::new(node)); + if let Some(node) = type_piece(d, t, lay.bounds, run, &bar) { + children.push(Arc::new(node)); + } } // The object's own fills and strokes (not its characters') paint the whole outline: // those below the Characters row under the characters, the others over them, with @@ -728,12 +755,26 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result { } // Outlined frames of threaded text leave their threads with the text they show. super::threads::leave_threads(d, &threaded); + super::graph::keep_placed(d, &graphs); sel.set(new_sel); Ok(out) })?; Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>() })) } +/// [`Session::edit`] for a type command that may set what the type already has: `f` runs on a +/// copy of the document, and it becomes an undo step only when one of the objects `ids` differs +/// afterwards or `f` returns true for a change of its own elsewhere (a graph's kept label styles). +/// When nothing changed, the document, its undo and redo steps and its saved state stay as they +/// were. Only the objects are compared, not the whole document, whose embedded images can be large. +fn edit_if_nodes_changed(s: &mut Session, label: &str, ids: &[NodeId], f: impl FnOnce(&mut Document) -> Result<(T, bool)>) -> Result { + super::colorcmds::edit_if_changed(s, label, |before, d| { + let (v, other) = f(d)?; + let changed = other || ids.iter().any(|id| before.node(*id) != d.node(*id)); + Ok((v, changed)) + }) +} + pub(crate) fn text_targets(s: &Session, p: &Value, cmd: &str) -> Result> { let ids = targets(s, p)?; let t = text_ids(&s.doc()?.doc, &ids); @@ -828,7 +869,8 @@ pub(crate) fn style_chars(t: &mut TextObject, range: Option, mut f: i fn set_text(s: &mut Session, p: &Value) -> Result { let text = str_param(p, "text").ok_or_else(|| bad("text.setText", "missing `text`"))?.to_string(); let ids = text_targets(s, p, "text.setText")?; - s.edit("Typing", |d, _| { + // The text the type already has is no undo step. + edit_if_nodes_changed(s, "Typing", &ids, |d| { for id in &ids { let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else { continue }; let style = t.first_style(); @@ -839,7 +881,7 @@ fn set_text(s: &mut Session, p: &Value) -> Result { t.ruby.clear(); refresh_bounds(t); } - Ok(()) + Ok(((), false)) })?; Ok(with_overflow(s, &ids, json!({ "ids": ids.iter().map(|i| i.0).collect::>() }))) } @@ -912,7 +954,8 @@ fn set_style(s: &mut Session, p: &Value) -> Result { let protect = s.prefs.missing_glyph_protection && (font.is_some() || style.is_some()); // The fonts the styled characters are set in, for the warning. let mut set = std::collections::BTreeSet::new(); - s.edit("Character", |d, _| { + // Attributes the characters already have are no undo step. + edit_if_nodes_changed(s, "Character", &ids, |d| { for id in &ids { let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else { continue }; let size = size.map(|v| local_type_value(t, v, (0.1, 1296.0), false, C)).transpose()?; @@ -987,8 +1030,9 @@ fn set_style(s: &mut Session, p: &Value) -> Result { } // Graph labels keep a change made to all of their text through the graph being drawn again (sizes as given, // not in a scaled label's own units). + let mut labels_changed = false; if range.is_none() { - super::graph::capture_label_styles(d, &ids, &|st| { + labels_changed = super::graph::capture_label_styles(d, &ids, &|st| { if let Some(f) = &font { st.font_family = f.clone(); st.font_version = None; @@ -1031,7 +1075,7 @@ fn set_style(s: &mut Session, p: &Value) -> Result { } }); } - Ok(()) + Ok(((), labels_changed)) })?; let mut out = with_overflow(s, &ids, json!({ "ids": ids.iter().map(|i| i.0).collect::>() })); if let Some(w) = super::fonts::set_font_warning(set) { @@ -1329,14 +1373,16 @@ fn reshape_area(s: &mut Session, p: &Value) -> Result { items.push((id, refs)); } let d = Vec2::new(f64_req(p, "dx", C)?, f64_req(p, "dy", C)?); - s.edit("Reshape Type Area", |doc, _| { + // Anchors moved by no distance are no undo step. + let ids: Vec = items.iter().map(|(id, _)| *id).collect(); + edit_if_nodes_changed(s, "Reshape Type Area", &ids, |doc| { for (id, refs) in &items { let Some(NodeKind::Text(t)) = doc.node_mut(*id).map(|n| &mut n.kind) else { return Err(EngineError::NoNode(*id)) }; if !reshape_area_with(t, |t| t.move_area_anchors(refs, d)) { return Err(bad(C, "no such frame anchor, or the frame would reach past the canvas")); } } - Ok(()) + Ok(((), false)) })?; ok() } @@ -1356,7 +1402,8 @@ fn reshape_path(s: &mut Session, p: &Value) -> Result { if !on_path || node.is_some_and(|n| n.extras().perspective.is_some()) { return Err(bad(C, "not type on a path outside perspective")); } - s.edit("Reshape Type Path", |doc, _| { + // Anchors moved by no distance are no undo step. + edit_if_nodes_changed(s, "Reshape Type Path", &[id], |doc| { let Some(NodeKind::Text(t)) = doc.node_mut(id).map(|n| &mut n.kind) else { return Err(EngineError::NoNode(id)) }; let before = t.kind.clone(); let within = |t: &TextObject| { @@ -1367,7 +1414,7 @@ fn reshape_path(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "no such path anchor, or the path would reach past the canvas")); } refresh_bounds(t); - Ok(()) + Ok(((), false)) })?; ok() } @@ -1385,7 +1432,8 @@ fn set_path_handle(s: &mut Session, p: &Value) -> Result { if !on_path || node.is_some_and(|n| n.extras().perspective.is_some()) { return Err(bad(C, "not type on a path outside perspective")); } - s.edit("Reshape Type Path", |doc, _| { + // A handle moved to where it is is no undo step. + edit_if_nodes_changed(s, "Reshape Type Path", &[id], |doc| { let Some(NodeKind::Text(t)) = doc.node_mut(id).map(|n| &mut n.kind) else { return Err(EngineError::NoNode(id)) }; let before = t.kind.clone(); let within = |t: &TextObject| { @@ -1396,7 +1444,7 @@ fn set_path_handle(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "no such path anchor, or the path would reach past the canvas")); } refresh_bounds(t); - Ok(()) + Ok(((), false)) })?; ok() } @@ -1407,6 +1455,8 @@ mod block; pub(crate) use block::needed_room; #[cfg(test)] mod block_tests; +#[cfg(test)] +mod noop_tests; /// Width of the first line and of the space it can fill, with `tracking` on the first paragraph. /// The third value is where the first line ends in the plain text. @@ -1448,7 +1498,9 @@ fn fit_headline(s: &mut Session, p: &Value) -> Result { plans.push((*id, (lo * 10.0).floor() / 10.0)); } let first = plans.first().map(|p| p.1).ok_or_else(|| bad(C, "select area type whose first line can fit its frame"))?; - s.edit("Fit Headline", |d, _| { + // A headline that already has its fitted tracking is no undo step. + let fitted: Vec = plans.iter().map(|(id, _)| *id).collect(); + edit_if_nodes_changed(s, "Fit Headline", &fitted, |d| { for (id, tr) in &plans { if let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) { let end = t.plain_text().find('\n').unwrap_or(usize::MAX).min(vectorcraft_text::edit::runs_len(&t.runs)); @@ -1456,7 +1508,7 @@ fn fit_headline(s: &mut Session, p: &Value) -> Result { refresh_bounds(t); } } - Ok(()) + Ok(((), false)) })?; Ok(json!({ "tracking": first })) } diff --git a/crates/engine/src/cmd/typecmd/area_tests.rs b/crates/engine/src/cmd/typecmd/area_tests.rs index 35365cd713..ca9e4dc2ed 100644 --- a/crates/engine/src/cmd/typecmd/area_tests.rs +++ b/crates/engine/src/cmd/typecmd/area_tests.rs @@ -199,8 +199,11 @@ fn optical_margin_alignment_is_set_per_object_and_saved_only_when_on() { assert!(left(&s) < inside - 5.0, "{} {inside}", left(&s)); assert_eq!(serde_json::to_value(text(&s)).unwrap()["opticalMarginAlignment"], true); // `on` sets it; without `on` it toggles. + // Setting the value the type already has: no undo step. + let n = s.doc().unwrap().history.undo.len(); assert_eq!(s.execute("type.opticalMarginAlignment", &json!({"on": true})).unwrap()["on"], true); assert!(text(&s).optical_margin); + assert_eq!(s.doc().unwrap().history.undo.len(), n); assert_eq!(s.execute("type.opticalMarginAlignment", &json!({})).unwrap()["on"], false); assert!(!text(&s).optical_margin); assert_eq!(left(&s), inside); @@ -247,6 +250,10 @@ fn system_layout_sets_the_document_and_every_text_object() { assert!(fractional.iter().zip(&whole).any(|(a, b)| (a - b).abs() > 0.05), "{fractional:?} {whole:?}"); assert_eq!(serde_json::to_value(setup(&s)).unwrap()["systemLayout"], true); assert_eq!(serde_json::to_value(text(&s, id)).unwrap()["systemLayout"], true); + // Setting the value the document and its type already have: no undo step. + let n = s.doc().unwrap().history.undo.len(); + assert_eq!(s.execute("type.systemLayout", &json!({"on": true})).unwrap()["on"], true); + assert_eq!(s.doc().unwrap().history.undo.len(), n); // New type inherits the document's setting. let made = s.execute("text.create", &json!({"x": 10, "y": 120, "text": "Z"})).unwrap()["id"].as_u64().unwrap(); assert!(text(&s, made).system_layout); @@ -305,6 +312,10 @@ fn fractional_widths_is_set_per_object_and_saved_only_when_off() { assert!(text(&s).fractional_widths); assert_eq!(s.execute("type.fractionalWidths", &json!({"on": false})).unwrap()["on"], false); assert!(!text(&s).fractional_widths); + // Setting the value the type already has: no undo step. + let n = s.doc().unwrap().history.undo.len(); + assert_eq!(s.execute("type.fractionalWidths", &json!({"on": false})).unwrap()["on"], false); + assert_eq!(s.doc().unwrap().history.undo.len(), n); // One undo step. s.execute("edit.undo", &json!({})).unwrap(); assert!(text(&s).fractional_widths); @@ -1914,6 +1925,55 @@ fn standard_vertical_roman_is_a_character_attribute_saved_only_when_on() { assert!(runs(&s).iter().all(|r| !r.style.standard_vertical_roman)); } +/// The East Asian glyph form (Glyphs panel menu) is one character attribute, `glyphForm`: one +/// form replaces another, "default" (Revert To Default Forms) takes it away, and it is saved +/// only when set. A call that changes nothing records no undo step, an unknown form is refused, +/// and character styles carry it. +#[test] +fn glyph_form_is_one_character_attribute_saved_only_when_set() { + use vectorcraft_doc::GlyphForm; + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "亜唖芦"})).unwrap()["id"].as_u64().unwrap(); + let runs = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => t.runs.clone(), + _ => panic!("text"), + }; + let forms = |s: &Session| runs(s).iter().map(|r| (r.text.clone(), r.style.glyph_form)).collect::>(); + assert!(serde_json::to_value(&runs(&s)[0].style).unwrap().get("glyphForm").is_none()); + s.execute("text.setRangeStyle", &json!({"id": id, "start": 3, "end": 6, "glyphForm": "jis78"})).unwrap(); + assert_eq!(forms(&s), [("亜".into(), GlyphForm::Default), ("唖".into(), GlyphForm::Jis78), ("芦".into(), GlyphForm::Default)]); + assert_eq!(serde_json::to_value(&runs(&s)[1].style).unwrap()["glyphForm"], "jis78"); + // Saved and reopened as it was. + let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + let NodeKind::Text(t) = &back.node(NodeId(id)).unwrap().kind else { panic!("text") }; + assert_eq!(t.runs.iter().map(|r| (r.text.clone(), r.style.glyph_form)).collect::>(), forms(&s)); + // Another form replaces it: one form at a time. + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + s.execute("text.setFormat", &json!({"glyphForm": "fullWidth"})).unwrap(); + assert!(runs(&s).iter().all(|r| r.style.glyph_form == GlyphForm::FullWidth)); + let n = s.doc().unwrap().history.undo.len(); + s.execute("text.setFormat", &json!({"glyphForm": "fullWidth"})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), n, "nothing changed, no undo step"); + for bad in [json!("jis2004"), json!(78), json!(true), json!("Traditional")] { + let e = s.execute("text.setFormat", &json!({"glyphForm": bad})).unwrap_err().to_string(); + assert!(e.contains("`glyphForm` must be one of \"traditional\""), "{bad}: {e}"); + assert!(s.execute("text.setRangeStyle", &json!({"id": id, "glyphForm": bad})).is_err(), "{bad}"); + } + assert!(runs(&s).iter().all(|r| r.style.glyph_form == GlyphForm::FullWidth), "a refused call changes nothing"); + assert_eq!(super::super::textstyles::char_attrs(&runs(&s)[0].style)["glyphForm"], "fullWidth"); + s.execute("text.setFormat", &json!({"glyphForm": "default"})).unwrap(); + assert!(runs(&s).iter().all(|r| r.style.glyph_form == GlyphForm::Default)); + assert!(serde_json::to_value(&runs(&s)[0].style).unwrap().get("glyphForm").is_none()); + // A character style carries the form. + s.execute("charStyle.new", &json!({"name": "Old forms", "attrs": {"glyphForm": "jis83"}})).unwrap(); + s.execute("charStyle.apply", &json!({"name": "Old forms", "id": id})).unwrap(); + assert!(runs(&s).iter().all(|r| r.style.glyph_form == GlyphForm::Jis83)); + assert!(s.execute("charStyle.new", &json!({"name": "Bad", "attrs": {"glyphForm": "jis2004"}})).is_err()); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(runs(&s).iter().all(|r| r.style.glyph_form == GlyphForm::Default)); +} + /// No Break is a character attribute, saved only when on. #[test] fn no_break_is_a_character_attribute_saved_only_when_on() { @@ -2331,8 +2391,17 @@ fn vertical_point_type_keeps_its_anchor_on_the_column_centre_line() { let tall = bounds(&s); assert!(tall.height() > tall.width(), "{tall:?}"); assert!((tall.center().x - 100.0).abs() < 6.0, "the anchor stays on the column's centre line: {tall:?}"); + // Vertical type set vertical again: no undo step. + let n = s.doc().unwrap().history.undo.len(); + s.execute("type.orientation.vertical", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), n); + assert_eq!(bounds(&s), tall); s.execute("edit.undo", &json!({})).unwrap(); assert_eq!(bounds(&s), wide); + // Horizontal type set horizontal: no undo step either. + let n = s.doc().unwrap().history.undo.len(); + s.execute("type.orientation.horizontal", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), n); } #[test] diff --git a/crates/engine/src/cmd/typecmd/noop_tests.rs b/crates/engine/src/cmd/typecmd/noop_tests.rs new file mode 100644 index 0000000000..02481d8bee --- /dev/null +++ b/crates/engine/src/cmd/typecmd/noop_tests.rs @@ -0,0 +1,143 @@ +use super::*; + +/// The document and the number of undo steps, to compare before and after a command that sets +/// what the type already has. +fn state(s: &Session) -> (std::sync::Arc, usize) { + let st = s.doc().unwrap(); + (st.doc.clone(), st.history.undo.len()) +} + +/// Assert that `cmd` with `p` leaves the document and its undo history as they were. +fn records_nothing(s: &mut Session, cmd: &str, p: Value) { + let before = state(s); + s.execute(cmd, &p).unwrap(); + let after = state(s); + assert!(*after.0 == *before.0, "{cmd} {p} changed the document"); + assert_eq!(after.1, before.1, "{cmd} {p} recorded an undo step"); +} + +/// Assert that `cmd` with `p` changes the document in exactly one undo step. +fn records_one_step(s: &mut Session, cmd: &str, p: Value) { + let before = state(s); + s.execute(cmd, &p).unwrap(); + let after = state(s); + assert!(*after.0 != *before.0, "{cmd} {p} left the document as it was"); + assert_eq!(after.1, before.1 + 1, "{cmd} {p} did not record one undo step"); +} + +fn session_with(text: &str, area: Option) -> (Session, u64) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let mut p = json!({"x": 10, "y": 20, "text": text, "size": 24}); + if let Some(a) = area { + p["area"] = a; + } + let id = s.execute("text.create", &p).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + (s, id) +} + +/// Ruby set again with the same reading and options, or removed where there is none, records no +/// undo step; a step that does change the ruby still undoes in one. +#[test] +fn ruby_that_changes_nothing_records_no_undo_step() { + let (mut s, id) = session_with("漢字です", None); + records_nothing(&mut s, "type.ruby", json!({"remove": true})); + let p = json!({"text": "かんじ", "start": 0, "end": 6, "position": "below", "size": 60}); + records_one_step(&mut s, "type.ruby", p.clone()); + records_nothing(&mut s, "type.ruby", p); + s.execute("type.ruby", &json!({"remove": true})).unwrap(); + records_nothing(&mut s, "type.ruby", json!({"remove": true, "start": 0, "end": 6})); + s.execute("edit.undo", &json!({})).unwrap(); + let NodeKind::Text(t) = &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind else { panic!("text") }; + assert_eq!(t.ruby.len(), 1, "undo brings the ruby back"); +} + +/// `text.setStyle` (the Character panel) given the attributes the characters already have +/// records no undo step, with a range too. +#[test] +fn character_attributes_already_set_record_no_undo_step() { + let (mut s, _) = session_with("Headline", None); + records_nothing(&mut s, "text.setStyle", json!({"size": 24})); + s.execute("text.setStyle", &json!({"tracking": 50, "fill": "#ff0000"})).unwrap(); + records_nothing(&mut s, "text.setStyle", json!({"tracking": 50, "fill": "#ff0000"})); + records_nothing(&mut s, "text.setStyle", json!({"tracking": 50, "start": 0, "end": 4})); + s.execute("text.setStyle", &json!({"justify": "center"})).unwrap(); + records_nothing(&mut s, "text.setStyle", json!({"justify": "center"})); + records_one_step(&mut s, "text.setStyle", json!({"tracking": 80, "start": 0, "end": 4})); +} + +/// `text.setStyle` on a graph label that leaves the label's own text as it is but changes the +/// style its kind of label keeps still records one undo step; given again, it records none. +#[test] +fn a_kept_graph_label_style_change_alone_records_one_undo_step() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let csv = ",2024,2025\nQ1,3,2\nQ2,5,4"; + let graph = NodeId( + s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap()["id"] + .as_u64() + .unwrap(), + ); + let doc = s.doc().unwrap().doc.clone(); + let legend = doc.node(graph).unwrap().children().unwrap().iter().find(|c| c.name.as_deref() == Some("Legend")).unwrap(); + let (label, size) = legend + .children() + .unwrap() + .iter() + .find_map(|c| match &c.kind { + NodeKind::Text(t) if t.plain_text() == "2025" => Some((c.id, t.runs[0].style.size)), + _ => None, + }) + .unwrap(); + let kept = |s: &Session| s.doc().unwrap().doc.node(graph).unwrap().extras().graph.as_deref().unwrap().label_styles.legend.clone(); + assert!(kept(&s).is_none()); + let p = json!({"ids": [label.0], "size": size}); + let before = state(&s); + s.execute("text.setStyle", &p).unwrap(); + let after = state(&s); + assert!(after.0.node(label) == before.0.node(label), "the label's own text changed"); + assert!(kept(&s).is_some(), "the legend keeps the style"); + assert_eq!(after.1, before.1 + 1, "the kept style change recorded no undo step"); + records_nothing(&mut s, "text.setStyle", p); +} + +/// `text.setText` with the text the type already has records no undo step; new text records one. +#[test] +fn the_same_text_records_no_undo_step() { + let (mut s, _) = session_with("Same words", None); + records_nothing(&mut s, "text.setText", json!({"text": "Same words"})); + records_one_step(&mut s, "text.setText", json!({"text": "Other words"})); +} + +/// Fit Headline run again on a headline it already fitted records no undo step; the first run +/// records one. +#[test] +fn fit_headline_again_records_no_undo_step() { + let (mut s, _) = session_with("HEADLINE\nbody text", Some(json!({"width": 300, "height": 120}))); + let start = state(&s); + let tracking = s.execute("text.fitHeadline", &json!({})).unwrap()["tracking"].clone(); + let fitted = state(&s); + assert!(*fitted.0 != *start.0 && fitted.1 == start.1 + 1, "the first Fit Headline did not record one undo step"); + let before = state(&s); + assert_eq!(s.execute("text.fitHeadline", &json!({})).unwrap()["tracking"], tracking); + let after = state(&s); + assert!(*after.0 == *before.0 && after.1 == before.1, "a second Fit Headline recorded an undo step"); +} + +/// Reshaping area type or type on a path by no distance, or moving a path handle to where it is, +/// records no undo step; a reshape that moves something records one. +#[test] +fn reshaping_type_by_nothing_records_no_undo_step() { + let (mut s, id) = session_with("Boxed words", Some(json!({"width": 200, "height": 100}))); + records_nothing(&mut s, "text.reshapeArea", json!({"id": id, "anchors": [[0, 2]], "dx": 0, "dy": 0})); + records_one_step(&mut s, "text.reshapeArea", json!({"id": id, "anchors": [[0, 2]], "dx": 20, "dy": 10})); + let path = + s.execute("path.create", &json!({"anchors": [{"x": 100, "y": 300, "in": [50, 300], "out": [150, 300]}, {"x": 400, "y": 300}]})).unwrap(); + let on_path = s.execute("text.createInPath", &json!({"path": path["id"], "mode": "onPath", "text": "Along the curve"})).unwrap()["id"].clone(); + records_nothing(&mut s, "text.reshapePath", json!({"id": on_path, "anchors": [[0, 1]], "dx": 0, "dy": 0})); + records_one_step(&mut s, "text.reshapePath", json!({"id": on_path, "anchors": [[0, 1]], "dx": 0, "dy": 20})); + let handle = json!({"id": on_path, "anchor": 0, "which": "out", "x": 100, "y": 250}); + records_one_step(&mut s, "text.setPathHandle", handle.clone()); + records_nothing(&mut s, "text.setPathHandle", handle); +} diff --git a/crates/engine/src/cmd/typemenu.rs b/crates/engine/src/cmd/typemenu.rs index c140ba6572..d793fc12a3 100644 --- a/crates/engine/src/cmd/typemenu.rs +++ b/crates/engine/src/cmd/typemenu.rs @@ -30,7 +30,7 @@ pub fn specs() -> Vec { "Smart Punctuation…", ["Type"], None, - "{quotes?: true (straight quotes become the Document Setup quotes), dashes?: true (-- → en dash, --- → em dash), ellipsis?: true (... → …), scope?: \"selection\"|\"document\"} → {changed}", + "{fiLigatures?: false (ff, fi, ffi → the ligatures U+FB00, U+FB01, U+FB03), flLigatures?: false (ff, fl, ffl → U+FB00, U+FB02, U+FB04), quotes?: true (straight quotes become the Document Setup quotes), spaces?: false (two or more spaces after a period → one), dashes?: true (-- → en dash, --- → em dash), ellipsis?: true (... → …), fractions?: false (1/2, 1/4, 3/4 and the other fractions Unicode encodes as one character, with no digit, slash or decimal point next to them, → ½, ¼, ¾ …), scope?: \"selection\"|\"document\"} the selected type, or every text object with scope document or nothing selected; a ligature or a fraction is written only where the run's font has a glyph for it. Nothing to replace records no undo step → {changed: text objects changed, replaced: {fiLigatures, flLigatures, quotes, spaces, dashes, ellipses, fractions}: how many of each were replaced}", has_doc, smart_punctuation ), @@ -268,24 +268,227 @@ fn change_case(s: &mut Session, p: &Value) -> Result { // ---------- Smart Punctuation ---------- -#[derive(Default)] -struct PunctState { - prev: Option, +/// What Smart Punctuation replaces: each option of its dialog. +struct Punct { + /// ff, fi and ffi become the ligatures U+FB00, U+FB01 and U+FB03. + fi_ligatures: bool, + /// ff, fl and ffl become the ligatures U+FB00, U+FB02 and U+FB04. + fl_ligatures: bool, + /// Straight quotes become these quotes (the Document Setup quotes). + quotes: Option, + /// Two or more spaces after a period become one. + spaces: bool, + /// `--` becomes an en dash and `---` an em dash. + dashes: bool, + /// `...` becomes an ellipsis. + ellipses: bool, + /// `1/2` and the other fractions [`FRACTIONS`] lists become their one-character forms. + fractions: bool, } -/// Dashes (`--` en, `---` em), ellipses and, with `quotes`, typographer's quotes. -pub(crate) fn smarten(text: &str, prev: &mut Option, quotes: Option<&Quotes>, dashes: bool, ellipsis: bool) -> String { - let mut s = text.to_string(); - if dashes { - s = s.replace("---", "—").replace("--", "–"); +/// How many of each replacement Smart Punctuation made. +#[derive(Default)] +struct PunctCounts { + fi_ligatures: usize, + fl_ligatures: usize, + quotes: usize, + spaces: usize, + dashes: usize, + ellipses: usize, + fractions: usize, +} + +/// The text before the run being rewritten, across the runs of one text object. +#[derive(Default)] +struct PunctState { + /// The character before the run. + prev: Option, + /// The number of spaces since the last period, while only spaces follow it. + after_period: Option, + /// An inline graphic comes right before the run. + after_graphic: bool, +} + +/// The fractions Expert Fractions writes as one character: every fraction Unicode encodes as a +/// vulgar fraction with a numerator of 1 to 7 and a denominator of 2 to 10. +const FRACTIONS: [(&str, char); 18] = [ + ("1/2", '½'), + ("1/3", '⅓'), + ("2/3", '⅔'), + ("1/4", '¼'), + ("3/4", '¾'), + ("1/5", '⅕'), + ("2/5", '⅖'), + ("3/5", '⅗'), + ("4/5", '⅘'), + ("1/6", '⅙'), + ("5/6", '⅚'), + ("1/7", '⅐'), + ("1/8", '⅛'), + ("3/8", '⅜'), + ("5/8", '⅝'), + ("7/8", '⅞'), + ("1/9", '⅑'), + ("1/10", '⅒'), +]; + +/// `s` with every `from` replaced by `to`, adding the number replaced to `n`. +fn replace_counted(s: String, from: &str, to: &str, n: &mut usize) -> String { + let found = s.matches(from).count(); + if found == 0 { + return s; } - if ellipsis { - s = s.replace("...", "…"); + *n += found; + s.replace(from, to) +} + +/// Smart Spaces: `text` without the second and later spaces after a period, adding the number of +/// periods whose spaces it shortened to `n`. `after` carries the spaces after a period from one run +/// to the next. +fn smart_spaces(text: &str, after: &mut Option, n: &mut usize) -> String { + let mut out = String::with_capacity(text.len()); + for c in text.chars() { + match (c, *after) { + (' ', Some(k)) => { + *after = Some(k + 1); + if k >= 1 { + if k == 1 { + *n += 1; + } + continue; + } + } + ('.', _) => *after = Some(0), + _ => *after = None, + } + out.push(c); } - match quotes { - Some(q) => q.apply(&s, prev), + out +} + +/// The fraction `cs` starts with, and its length in characters: one of [`FRACTIONS`] that no digit, +/// slash or decimal part follows, so `1/25`, `1/2/2026` and `1/2.5` are left as they are. A digit +/// counts in any script. +fn fraction_at(cs: &[char]) -> Option<(usize, char)> { + FRACTIONS.iter().find_map(|(text, f)| { + let len = text.chars().count(); + if cs.len() < len || !cs[..len].iter().copied().eq(text.chars()) { + return None; + } + let ends = match &cs[len..] { + [c, ..] if c.is_numeric() || *c == '/' => false, + ['.' | ',', d, ..] if d.is_numeric() => false, + _ => true, + }; + ends.then_some((len, *f)) + }) +} + +/// Expert Fractions: `text` with each fraction [`fraction_at`] finds, and no digit, slash or +/// decimal point before, written as one character when `covers` it. `prev` is the character before +/// `text`, and `next` the two characters after it (in the next runs), so a fraction at the end of +/// a run is checked against what follows it. +fn expert_fractions(text: &str, prev: Option, next: [Option; 2], covers: &mut impl FnMut(char) -> bool, n: &mut usize) -> String { + let mut cs: Vec = text.chars().collect(); + let len_text = cs.len(); + cs.extend(next.into_iter().flatten()); + let mut out = String::with_capacity(text.len()); + let mut i = 0; + while i < len_text { + let before = if i == 0 { prev } else { Some(cs[i - 1]) }; + let free = !before.is_some_and(|c| c.is_numeric() || matches!(c, '/' | '.' | ',')); + let found = fraction_at(&cs[i..]).filter(|(len, f)| i + len <= len_text && covers(*f)); + if free && let Some((len, f)) = found { + out.push(f); + *n += 1; + i += len; + continue; + } + out.push(cs[i]); + i += 1; + } + out +} + +/// The ligatures and their letters, longest first, with whether each comes with the ff, fi, ffi +/// option (else with the ff, fl, ffl option). ff comes with both. +const LIGATURES: [(&str, char, bool); 5] = + [("ffi", '\u{FB03}', true), ("ffl", '\u{FB04}', false), ("ff", '\u{FB00}', true), ("fi", '\u{FB01}', true), ("fl", '\u{FB02}', false)]; + +/// The ligature options: `text` with the letters of each ligature an option `o` asks for written +/// as the ligature, the longest first, when `covers` it. +fn ligatures(text: &str, o: &Punct, covers: &mut impl FnMut(char) -> bool, n: &mut PunctCounts) -> String { + let cs: Vec = text.chars().collect(); + let mut out = String::with_capacity(text.len()); + let mut i = 0; + while i < cs.len() { + let found = (cs[i] == 'f').then(|| { + LIGATURES.iter().find(|(letters, lig, fi)| { + let on = if *letters == "ff" { + o.fi_ligatures || o.fl_ligatures + } else if *fi { + o.fi_ligatures + } else { + o.fl_ligatures + }; + let len = letters.chars().count(); + on && cs.len() - i >= len && cs[i..i + len].iter().copied().eq(letters.chars()) && covers(*lig) + }) + }); + if let Some(&(letters, lig, fi)) = found.flatten() { + out.push(lig); + // ff counts with the ff, fi, ffi option when that option is on. + if fi && (letters != "ff" || o.fi_ligatures) { + n.fi_ligatures += 1; + } else { + n.fl_ligatures += 1; + } + i += letters.chars().count(); + continue; + } + out.push(cs[i]); + i += 1; + } + out +} + +/// One run's text with the replacements `o` asks for, counted in `n`. Ligatures and fractions are +/// written only where the run's font has a glyph for them. `next` holds the two characters after +/// the run. +fn smarten(text: &str, style: &CharStyle, next: [Option; 2], o: &Punct, st: &mut PunctState, n: &mut PunctCounts) -> String { + let mut s = if o.spaces { smart_spaces(text, &mut st.after_period, &mut n.spaces) } else { text.to_string() }; + if o.dashes { + s = replace_counted(s, "---", "—", &mut n.dashes); + s = replace_counted(s, "--", "–", &mut n.dashes); + } + if o.ellipses { + s = replace_counted(s, "...", "…", &mut n.ellipses); + } + // The run's font, looked up once and only for a ligature or a fraction. + let mut face = None; + let mut covers = |c: char| { + face.get_or_insert_with(|| { + vectorcraft_text::FontDb::global().face_version(&style.font_family, &style.font_style, style.font_version.as_deref()) + }) + .as_ref() + .is_some_and(|f| f.covers(c)) + }; + if o.fractions && s.contains('/') { + let before = if st.after_graphic { None } else { st.prev }; + s = expert_fractions(&s, before, next, &mut covers, &mut n.fractions); + } + st.after_graphic = false; + if (o.fi_ligatures || o.fl_ligatures) && s.contains('f') { + s = ligatures(&s, o, &mut covers, n); + } + match &o.quotes { + Some(q) => { + let out = q.apply(&s, &mut st.prev); + n.quotes += s.chars().zip(out.chars()).filter(|(a, b)| a != b).count(); + out + } None => { - *prev = s.chars().last().or(*prev); + st.prev = s.chars().last().or(st.prev); s } } @@ -293,12 +496,20 @@ pub(crate) fn smarten(text: &str, prev: &mut Option, quotes: Option<&Quote fn smart_punctuation(s: &mut Session, p: &Value) -> Result { const C: &str = "type.smartPunctuation"; - let (d, e) = (switch_or(p, "dashes", true, C)?, switch_or(p, "ellipsis", true, C)?); let quotes = switch_or(p, "quotes", true, C)?; + let mut o = Punct { + fi_ligatures: switch_or(p, "fiLigatures", false, C)?, + fl_ligatures: switch_or(p, "flLigatures", false, C)?, + quotes: None, + spaces: switch_or(p, "spaces", false, C)?, + dashes: switch_or(p, "dashes", true, C)?, + ellipses: switch_or(p, "ellipsis", true, C)?, + fractions: switch_or(p, "fractions", false, C)?, + }; let document = choice(p, C, "scope", &["selection", "document"])? == Some("document"); let st = s.doc()?; // Quotes in the document's style (Document Setup → Type). - let q = quotes.then_some(st.doc.setup.quotes); + o.quotes = quotes.then_some(st.doc.setup.quotes); let ids = if document || st.selection.is_empty() { let mut v = vec![]; st.doc.walk(|n| { @@ -310,8 +521,93 @@ fn smart_punctuation(s: &mut Session, p: &Value) -> Result { } else { text_ids(&st.doc, &st.selection.objects) }; - let n = edit_runs::(s, "Smart Punctuation", &ids, |text, st| smarten(text, &mut st.prev, q.as_ref(), d, e))?; - Ok(json!({ "changed": n })) + let mut n = PunctCounts::default(); + let changed = super::overprint::edit_counted(s, "Smart Punctuation", |d| { + let mut changed = 0; + for id in &ids { + let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else { continue }; + let mut st = PunctState::default(); + let mut any = false; + // The ruby spans' ends, in the plain text as it was. Each run is rewritten in pieces + // between them, so no replacement crosses one, and `moved` records where each end and + // each run's start lands in the new text. + let mut edges: Vec = t.ruby.iter().flat_map(|r| [r.start, r.end]).collect(); + edges.sort_unstable(); + edges.dedup(); + let mut moved = vec![]; + let (mut old_at, mut new_at) = (0, 0); + // Inline graphics are art, not characters to rewrite. Each run sees the first two + // characters of the runs after it, up to the next inline graphic, as they were. + for i in 0..t.runs.len() { + let len = t.runs[i].text.len(); + moved.push((old_at, new_at)); + if t.runs[i].inline.is_some() { + // A graphic separates the characters on either side of it for Smart Spaces and + // Expert Fractions; quotes still read the character before it. + st.after_period = None; + st.after_graphic = true; + (old_at, new_at) = (old_at + len, new_at + len); + continue; + } + let mut after = t.runs[i + 1..].iter().take_while(|r| r.inline.is_none()).flat_map(|r| r.text.chars()); + let following = [after.next(), after.next()]; + // Smart Spaces counts no space across a ruby span's end, so it removes no space on + // the other side of one. + if edges.binary_search(&old_at).is_ok() { + st.after_period = None; + } + let r = &mut t.runs[i]; + let mut cuts: Vec = + edges.iter().filter(|&&e| e > old_at && e < old_at + len && r.text.is_char_boundary(e - old_at)).map(|e| e - old_at).collect(); + cuts.push(len); + let mut new = String::with_capacity(len); + let mut from = 0; + for cut in cuts { + if from > 0 { + moved.push((old_at + from, new_at + new.len())); + st.after_period = None; + } + let mut after = r.text[cut..].chars().chain(following.into_iter().flatten()); + let next = [after.next(), after.next()]; + new.push_str(&smarten(&r.text[from..cut], &r.style, next, &o, &mut st, &mut n)); + from = cut; + } + (old_at, new_at) = (old_at + len, new_at + new.len()); + if new != r.text { + r.text = new; + any = true; + } + } + moved.push((old_at, new_at)); + if any { + changed += 1; + // Each ruby end moves with the text before it; an end inside a character keeps its + // distance from the last place recorded before it. + let to_new = |v: usize| { + let k = moved.partition_point(|&(old, _)| old <= v).saturating_sub(1); + moved.get(k).map_or(v, |&(old, new)| new + (v - old.min(v))) + }; + for span in &mut t.ruby { + (span.start, span.end) = (to_new(span.start), to_new(span.end)); + } + t.normalize_ruby(); + refresh_bounds(t); + } + } + Ok(changed) + })?; + Ok(json!({ + "changed": changed, + "replaced": { + "fiLigatures": n.fi_ligatures, + "flLigatures": n.fl_ligatures, + "quotes": n.quotes, + "spaces": n.spaces, + "dashes": n.dashes, + "ellipses": n.ellipses, + "fractions": n.fractions, + }, + })) } // ---------- Area / Point conversion ---------- diff --git a/crates/engine/src/cmd/variablecmds.rs b/crates/engine/src/cmd/variablecmds.rs index 9acd31e664..a73c16448b 100644 --- a/crates/engine/src/cmd/variablecmds.rs +++ b/crates/engine/src/cmd/variablecmds.rs @@ -9,8 +9,8 @@ //! before an image variable); import replaces the datasets, names the rows Data Set 1, 2…, //! also reads tab-separated files, and reads header cells that define new variables (`#` for //! visibility, `@` for image, no prefix for text). `variable.loadLibrary` replaces the variables and data sets with the -//! text variables and data sets of a variable library, the XML file of the reference app's Save -//! Variable Library, and `variable.saveLibrary` writes the text variables and data sets as one. +//! variables and data sets of a variable library, the XML file of the reference app's Save +//! Variable Library, and `variable.saveLibrary` writes the variables and data sets as one. //! Agents reach every command through `run_command`, like all engine commands. use std::collections::{BTreeMap, BTreeSet}; @@ -26,6 +26,7 @@ use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids mod csv; mod library; +pub use csv::utf16_order_without_mark; use csv::{MAX_GRAPH_CSV, dataset_export, dataset_import}; pub(crate) use library::{give_svg_library, svg_library}; use library::{load_library, save_library}; @@ -885,7 +886,7 @@ pub fn specs() -> Vec { "Load Variable Library…", ["Window", "Variables"], None, - "{path? | xml? | dataBase64?} replace the document's variables and data sets with a variable library's (XML: `variableSets` › `variableSet` › `variables` of `variable` elements with `varName` and `trait`, and `sampleDataSets` of `sampleDataSet` elements with `dataSetName`) in one undo step (none when the document already holds what the library gives). Every data set is deleted, and every variable of the document is deleted with its bindings and values except a text variable the library also declares, which keeps its bindings; then the library's other variables whose `trait` is `textcontent` are defined as text variables, unbound, and each data set takes a value for a variable from the `p` elements of the element named after it, one paragraph each. Variables of other kinds are left out and named in `skipped` and `warning`. Refused while the variables are locked when it would delete or define a variable → {variables, deleted, deletedDataSets, names, skipped, warning?}", + "{path? | xml? | dataBase64?} replace the document's variables and data sets with a variable library's (XML: `variableSets` › `variableSet` › `variables` of `variable` elements with `varName` and `trait`, and `sampleDataSets` of `sampleDataSet` elements with `dataSetName`) in one undo step (none when the document already holds what the library gives). Every data set is deleted, and every variable of the document is deleted with its bindings and values except a variable the library also declares with the same kind, which keeps its bindings; then the library's other variables are defined, unbound, with the kind of their `trait`: `textcontent` text, `visibility` visibility, `fileref` image, `graphdata` graph, and any other or none unknown (no values). Each data set takes a variable's value from the element named after it: a text value from its `p` elements, one paragraph each; a visibility value from `true` or `false`; an image value from a file's absolute path or a `file:` URL (the file isn't read); a graph value from a `data` element (`propertyRow` series names, `values` › `row` with a first `value` key=\"name\" category), read as the CSV graph.setData takes. A value that doesn't fit its kind is refused. Refused while the variables are locked when it would delete or define a variable → {variables, deleted, deletedDataSets, names}", has_doc, load_library ), @@ -894,7 +895,7 @@ pub fn specs() -> Vec { "Save Variable Library…", ["Window", "Variables"], None, - "{path?} write the document's text variables and every data set as a variable library, the XML that variable.loadLibrary reads: a `variable` element with `varName` and `trait=\"textcontent\"` per text variable, and a `sampleDataSet` element with `dataSetName` per data set, holding an element named after each text variable it has a value for, with one `p` element per line of the value. Variables of other kinds are left out with their values and named in `skipped` and `warning`. Refused without a text variable, for a text variable whose name isn't an XML name (letters, digits, `-`, `_` and `.`, starting with a letter or `_`), for a data set name or value that holds a control character, for a data set name with white space at either end, for a name longer than 255 characters or used twice, and past variable.loadLibrary's caps (256 variables, 1,000 data sets, 8 MiB). Without path → {xml, variables, datasets, skipped, warning?}; with it → {path, variables, datasets, skipped, warning?}", + "{path?} write the document's variables and every data set as a variable library, the XML that variable.loadLibrary reads: a `variable` element with `varName` per variable, with the `trait` of its kind (`textcontent`, `visibility`, `fileref` for image, `graphdata` for graph; none for an unknown kind), and a `sampleDataSet` element with `dataSetName` per data set, holding an element named after each variable it has a value for: one `p` element per line of a text value, `true` or `false`, an image's path (a `file:///` URL for a path from a Unix root), or graph data as a `data` element. Refused without a variable, for a variable whose name isn't an XML name (letters, digits, `-`, `_` and `.`, starting with a letter or `_`; not asked of an unknown kind), for a name or value that holds a control character, for a name with white space at either end, for a name longer than 255 characters or used twice, for an image value that isn't a file's absolute path, and past variable.loadLibrary's caps (256 variables, 1,000 data sets, 8 MiB). Without path → {xml, variables, datasets}; with it → {path, variables, datasets}", has_doc, save_library ), diff --git a/crates/engine/src/cmd/variablecmds/csv.rs b/crates/engine/src/cmd/variablecmds/csv.rs index 38dd42d922..be9db3b841 100644 --- a/crates/engine/src/cmd/variablecmds/csv.rs +++ b/crates/engine/src/cmd/variablecmds/csv.rs @@ -59,25 +59,35 @@ fn utf16(bytes: &[u8], le: bool) -> Option { char::decode_utf16(units).collect::>().ok().filter(|_| odd.is_empty()) } -/// `bytes`, which hold NUL bytes and no byte-order mark, as UTF-16, or `None`. At least half of -/// the two-byte units must hold a NUL byte, as characters from U+0001 to U+00FF do; a file with -/// fewer, such as UTF-8 or Windows-1252 text with stray NUL bytes, is refused. The byte order is -/// the one that reads a line break (`\n` or `\r`). The other order reads one only from U+0A00 or -/// U+0D00, so a file that reads one in both orders is refused. A file that reads none in either -/// order has no data rows, and is read little-endian so that the import reports that. The text -/// must be valid UTF-16 in that order and hold no NUL character. -fn utf16_without_mark(bytes: &[u8]) -> Option { - let (units, odd) = bytes.as_chunks::<2>(); - if !odd.is_empty() || units.iter().filter(|c| c.contains(&0)).count() * 2 < units.len() { +/// The byte order of `bytes`, which hold NUL bytes and no byte-order mark, read as UTF-16: +/// `Some(true)` for little-endian, or `None` when they don't read as UTF-16. At least half of the +/// two-byte units must hold a NUL byte, as characters from U+0001 to U+00FF do; a file with fewer, +/// such as UTF-8 or Windows-1252 text with stray NUL bytes, is refused. The byte order is the one +/// that reads a line break (`\n` or `\r`). The other order reads one only from U+0A00 or U+0D00, +/// so a file that reads one in both orders is refused. A file that reads none in either order (one +/// line) is big-endian when more of its units start with a NUL byte than end with one, as +/// characters from U+0001 to U+00FF do in that order, and little-endian otherwise. An odd last +/// byte is left out of the count. +pub fn utf16_order_without_mark(bytes: &[u8]) -> Option { + let units = bytes.as_chunks::<2>().0; + if units.iter().filter(|c| c.contains(&0)).count() * 2 < units.len() { return None; } let is_line_break = |u: u16| matches!(u, 0x0A | 0x0D); let lines_le = units.iter().any(|&c| is_line_break(u16::from_le_bytes(c))); let lines_be = units.iter().any(|&c| is_line_break(u16::from_be_bytes(c))); - if lines_le && lines_be { - return None; + match (lines_le, lines_be) { + (true, true) => None, + (false, false) => Some(units.iter().filter(|c| c[0] == 0).count() <= units.iter().filter(|c| c[1] == 0).count()), + (_, lines_be) => Some(!lines_be), } - utf16(bytes, !lines_be).filter(|text| !text.contains('\0')) +} + +/// `bytes`, which hold NUL bytes and no byte-order mark, as UTF-16 in the byte order +/// [`utf16_order_without_mark`] gives, or `None`. The file must have an even length, and the text +/// must be valid UTF-16 in that order and hold no NUL character. +fn utf16_without_mark(bytes: &[u8]) -> Option { + utf16(bytes, utf16_order_without_mark(bytes)?).filter(|text| !text.contains('\0')) } /// A row of a datasets CSV: the file line it starts on, its cells, and for each cell whether it was quoted. diff --git a/crates/engine/src/cmd/variablecmds/library.rs b/crates/engine/src/cmd/variablecmds/library.rs index e1f4ae0bd5..2392a80ee4 100644 --- a/crates/engine/src/cmd/variablecmds/library.rs +++ b/crates/engine/src/cmd/variablecmds/library.rs @@ -1,18 +1,29 @@ use std::collections::HashMap; +use std::fmt::Write as _; + +use vectorcraft_doc::{GraphSpec, MAX_GRAPH_CATEGORIES, MAX_GRAPH_SERIES}; + use super::{ - BTreeMap, BTreeSet, DataSet, DataValue, Document, EngineError, MAX_NAME, NodeId, NodeKind, Result, Session, Value, Variable, VariableKind, - Variables, absolute_path, bad, json, named, read_file_head, str_param, variables_unlocked, write_file, + BTreeMap, BTreeSet, DataSet, DataValue, Document, EngineError, MAX_GRAPH_CSV, MAX_NAME, NodeId, NodeKind, Result, Session, Value, Variable, + VariableKind, Variables, absolute_path, bad, json, named, read_file_head, str_param, variables_unlocked, write_file, }; /// The namespace of a variable library's elements, the default namespace of its data sets' values, -/// and the `category` of its text variables. +/// and the `category` of its visibility and image variables. const NS_VARIABLES: &str = "http://ns.adobe.com/Variables/1.0/"; // brand-ok: the namespace variable libraries use const NS_CUSTOM: &str = "http://ns.adobe.com/GenericCustomNamespace/1.0/"; // brand-ok: the namespace variable libraries use +/// The `category` of a library's text variables. const NS_FLOWS: &str = "http://ns.adobe.com/Flows/1.0/"; // brand-ok: the namespace variable libraries use +/// The `category` of a library's graph variables. +const NS_GRAPHS: &str = "http://ns.adobe.com/Graphs/1.0/"; // brand-ok: the namespace variable libraries use + +/// The white space XML puts round a value: a value's text is read without it at either end. +const XML_SPACE: [char; 4] = [' ', '\t', '\n', '\r']; + /// Caps on a variable library (paths and MCP payloads are untrusted): its size, its XML nodes, how /// deep its elements nest, and the entities, variables and data sets it declares. const MAX_LIBRARY_BYTES: usize = 8 << 20; @@ -170,16 +181,47 @@ fn without_doctype(xml: &str, cmd: &str) -> Result { Ok(out) } -/// A variable library as Load Variable Library reads it: the names of its text variables in the -/// order it declares them, the name and `trait` of each variable of another kind, its data sets -/// with their text values, and the element id each text variable's `docRef` names. +/// One variable a library declares: its name, its kind, and its `trait` as the library spells it +/// (`None` when it has none). +struct LibraryVariable { + name: String, + kind: VariableKind, + trait_name: Option, +} + +/// A variable library as Load Variable Library reads it: its variables in the order it declares +/// them, its data sets with their values, and the element id each text variable's `docRef` names. pub(crate) struct Library { - text: Vec, - other: Vec<(String, String)>, + variables: Vec, datasets: Vec, refs: Vec<(String, String)>, } +/// The kind of a library variable whose `trait` is `t`: `textcontent` is text, `visibility` is +/// visibility, `fileref` (a linked file) is image and `graphdata` is graph. A variable without a +/// `trait`, or with one VectorCraft doesn't know, is of unknown kind. +fn trait_kind(t: Option<&str>) -> VariableKind { + match t { + Some("textcontent") => VariableKind::Text, + Some("visibility") => VariableKind::Visibility, + Some("fileref") => VariableKind::Image, + Some("graphdata") => VariableKind::Graph, + _ => VariableKind::Unknown, + } +} + +/// The `trait` and the `category` reference a library declares a variable of `kind` with, or `None` +/// for a variable of unknown kind, which is declared with neither. +fn kind_trait(kind: VariableKind) -> Option<(&'static str, &'static str)> { + match kind { + VariableKind::Text => Some(("textcontent", "&ns_flows;")), + VariableKind::Visibility => Some(("visibility", "&ns_vars;")), + VariableKind::Image => Some(("fileref", "&ns_vars;")), + VariableKind::Graph => Some(("graphdata", "&ns_graphs;")), + VariableKind::Unknown => None, + } +} + impl Library { /// The element ids the text variables' `docRef`s name. pub(crate) fn elements(&self) -> std::collections::HashSet { @@ -190,13 +232,13 @@ impl Library { /// Read a variable library: XML whose `variableSets` element holds `variableSet` elements, each /// with a `variables` element of `variable` elements (`varName`, `trait`) and a `sampleDataSets` /// element of `sampleDataSet` elements (`dataSetName`). Elements are matched by their local names. -/// A variable whose `trait` is `textcontent` is a text variable. In a data set, an element named -/// after a text variable gives its value: the text of its `p` elements, one paragraph each, and -/// none when it has no `p` element. Values for variables of other kinds are left out. A variable -/// or data set declared twice, a value for a variable the library doesn't declare, and a library -/// past the caps are refused. Entities that its document type declaration defines are read as -/// [`without_doctype`] says. -fn parse_library(xml: &str, cmd: &str) -> Result { +/// A variable's kind comes from its `trait` ([`trait_kind`]). In a data set, an element named after +/// a variable gives its value, as [`library_value`] reads it. A variable or data set declared +/// twice, a value for a variable the library doesn't declare, a value that doesn't fit its +/// variable's kind, and a library past the caps are refused. With `text_only`, only text values +/// are read, and the values of the other kinds are passed over unread. Entities that its document +/// type declaration defines are read as [`without_doctype`] says. +fn parse_library(xml: &str, cmd: &str, text_only: bool) -> Result { let xml = without_doctype(xml, cmd)?; // roxmltree parses nested elements recursively. if crate::cmd::place::docx::nesting(&xml) > MAX_LIBRARY_NESTING { @@ -210,32 +252,29 @@ fn parse_library(xml: &str, cmd: &str) -> Result { return Err(bad(cmd, "the file holds no `variableSets` element")); }; let sets: Vec = root.children().filter(|n| is(n, "variableSet")).collect(); - let (mut text, mut other, mut declared, mut refs) = (Vec::new(), Vec::new(), BTreeSet::new(), Vec::new()); + let (mut variables, mut kinds, mut refs) = (Vec::new(), BTreeMap::new(), Vec::new()); for var in sets.iter().flat_map(|s| s.children()).filter(|n| is(n, "variables")).flat_map(|v| v.children()).filter(|n| is(n, "variable")) { let name = named(var.attribute("varName"), "varName", cmd)?; - if !declared.insert(name.clone()) { + let trait_name = var.attribute("trait").map(|t| t.chars().take(MAX_NAME).collect::()); + let kind = trait_kind(trait_name.as_deref()); + if kinds.insert(name.clone(), kind).is_some() { return Err(bad(cmd, format!("variable `{name}` is declared twice"))); } - if declared.len() > MAX_LIBRARY_VARIABLES { + if kinds.len() > MAX_LIBRARY_VARIABLES { return Err(bad(cmd, format!("the variable library declares more than {MAX_LIBRARY_VARIABLES} variables"))); } - match var.attribute("trait") { - Some("textcontent") => { - // `docRef="id('…')"` names the element of the variable's bound object. - let element = var.attribute("docRef").and_then(|r| r.trim().strip_prefix("id('")?.strip_suffix("')")).filter(|e| !e.is_empty()); - if let Some(element) = element { - refs.push((name.clone(), element.to_string())); - } - text.push(name); + if kind == VariableKind::Text { + // `docRef="id('…')"` names the element of the variable's bound object. + let element = var.attribute("docRef").and_then(|r| r.trim().strip_prefix("id('")?.strip_suffix("')")).filter(|e| !e.is_empty()); + if let Some(element) = element { + refs.push((name.clone(), element.to_string())); } - Some(t) => other.push((name, t.chars().take(MAX_NAME).collect())), - None => return Err(bad(cmd, format!("variable `{name}` has no `trait`"))), } + variables.push(LibraryVariable { name, kind, trait_name }); } - if declared.is_empty() { + if variables.is_empty() { return Err(bad(cmd, "the variable library declares no variables")); } - let text_names: BTreeSet<&str> = text.iter().map(String::as_str).collect(); let (mut datasets, mut seen) = (Vec::new(), BTreeSet::new()); for row in sets.iter().flat_map(|s| s.children()).filter(|n| is(n, "sampleDataSets")).flat_map(|d| d.children()).filter(|n| is(n, "sampleDataSet")) @@ -250,27 +289,197 @@ fn parse_library(xml: &str, cmd: &str) -> Result { let (mut values, mut held) = (BTreeMap::new(), BTreeSet::new()); for el in row.children().filter(roxmltree::Node::is_element) { let var = el.tag_name().name(); - if !declared.contains(var) { + let Some(kind) = kinds.get(var) else { return Err(bad(cmd, format!("data set `{name}` holds a value for `{var}`, which the library doesn't declare"))); - } + }; if !held.insert(var) { return Err(bad(cmd, format!("data set `{name}` holds two values for `{var}`"))); } - if !text_names.contains(var) { + if text_only && *kind != VariableKind::Text { continue; } - let paras: Vec = el - .children() - .filter(|n| is(n, "p")) - .map(|p| p.descendants().filter(roxmltree::Node::is_text).filter_map(|t| t.text()).collect()) - .collect(); - if !paras.is_empty() { - values.insert(var.to_string(), DataValue::Text(paras.join("\n"))); + if let Some(value) = library_value(el, *kind, &name, cmd)? { + values.insert(var.to_string(), value); } } datasets.push(DataSet { name, values }); } - Ok(Library { text, other, datasets, refs }) + Ok(Library { variables, datasets, refs }) +} + +/// The value a data set's element `el` gives a variable of `kind`, or `None` when it gives none. +/// A text value is the text of its `p` elements, one paragraph each, and none without a `p` +/// element. A visibility value is `true` or `false`, in any case. An image value is the absolute +/// path of a file, or a `file:` URL of one ([`library_path`]); the file isn't read. A graph value is +/// a `data` element ([`graph_value`]). Visibility, image and graph values are read without the +/// white space round them, and an element holding only white space gives none. A variable of +/// unknown kind takes no value, so what its element holds is passed over. `set` names the data set +/// in the errors. +fn library_value(el: roxmltree::Node, kind: VariableKind, set: &str, cmd: &str) -> Result> { + let refused = |what: &str| bad(cmd, format!("data set `{set}` holds a value for `{}` that isn't {what}", el.tag_name().name())); + let text = || if elements(el).next().is_some() { None } else { Some(deep_text(el)) }; + match kind { + VariableKind::Text => { + let paras: Vec = elements(el).filter(|n| n.tag_name().name() == "p").map(deep_text).collect(); + Ok((!paras.is_empty()).then(|| DataValue::Text(paras.join("\n")))) + } + VariableKind::Visibility => { + let what = "`true` or `false`"; + let text = text().ok_or_else(|| refused(what))?; + match text.trim_matches(XML_SPACE) { + "" => Ok(None), + t if t.eq_ignore_ascii_case("true") => Ok(Some(DataValue::Visible(true))), + t if t.eq_ignore_ascii_case("false") => Ok(Some(DataValue::Visible(false))), + _ => Err(refused(what)), + } + } + VariableKind::Image => { + let what = "a file's absolute path or `file:` URL"; + let text = text().ok_or_else(|| refused(what))?; + match text.trim_matches(XML_SPACE) { + "" => Ok(None), + t => library_path(t).map(|p| Some(DataValue::Image(p))).ok_or_else(|| refused(what)), + } + } + VariableKind::Graph => graph_value(el, set, cmd), + VariableKind::Unknown => Ok(None), + } +} + +/// The elements among `n`'s children. +fn elements<'a, 'i>(n: roxmltree::Node<'a, 'i>) -> impl Iterator> { + n.children().filter(roxmltree::Node::is_element) +} + +/// The text of every text node inside `n`, in order. +fn deep_text(n: roxmltree::Node) -> String { + n.descendants().filter(roxmltree::Node::is_text).filter_map(|t| t.text()).collect() +} + +/// The absolute path a library's image value `text` names: a `file:` URL's path (`file:///…`, +/// `file://localhost/…` or `file:/…`), its `%XX` escapes decoded (a URL with a host names a share, +/// `//host/…`), or `text` itself. `None` unless that is an absolute path: one starting with `/` or +/// `\\`, or a drive's path from its root (`C:\…`, `C:/…`). +fn library_path(text: &str) -> Option { + let drive = |p: &str| matches!(p.as_bytes(), [l, b':', b'\\' | b'/', ..] if l.is_ascii_alphabetic()); + let url = match (text.strip_prefix("file://"), text.strip_prefix("file:")) { + (Some(rest), _) => Some(rest.strip_prefix("localhost").filter(|r| r.starts_with('/')).unwrap_or(rest)), + // `file:/…` names a path without a host. + (None, Some(rest)) if rest.starts_with('/') => Some(rest), + _ => None, + }; + let path = match url { + Some(rest) => { + if rest.starts_with('/') { + let p = percent_decoded(rest.trim_start_matches('/')); + if drive(&p) { p } else { format!("/{p}") } + } else { + format!("//{}", percent_decoded(rest)) + } + } + None => text.to_string(), + }; + (path.len() > 1 && (path.starts_with('/') || path.starts_with("\\\\") || drive(&path))).then_some(path) +} + +/// `s` with its `%XX` escapes decoded, or as it is when the decoded bytes aren't UTF-8. +fn percent_decoded(s: &str) -> String { + let hex = |b: u8| char::from(b).to_digit(16); + let (mut out, mut rest) = (Vec::with_capacity(s.len()), s.as_bytes()); + while let Some((&b, tail)) = rest.split_first() { + match tail { + [h, l, more @ ..] if b == b'%' && hex(*h).is_some() && hex(*l).is_some() => { + out.push(((hex(*h).unwrap_or(0) << 4) | hex(*l).unwrap_or(0)) as u8); + rest = more; + } + _ => { + out.push(b); + rest = tail; + } + } + } + String::from_utf8(out).unwrap_or_else(|_| s.to_string()) +} + +/// How a library writes the image value `path`: an absolute path from the root of a Unix file +/// system as a `file:` URL (`file:///` and the path, with `%`, `#`, `?`, spaces, controls and +/// bytes past ASCII escaped), any other path as it is. [`library_path`] reads it back. +fn library_file(path: &str) -> String { + if !path.starts_with('/') || path.starts_with("//") { + return path.to_string(); + } + let mut url = String::from("file:///"); + for &b in path.as_bytes() { + if matches!(b, b'%' | b'#' | b'?') || !(0x21..=0x7e).contains(&b) { + let _ = write!(url, "%{b:02X}"); + } else { + url.push(char::from(b)); + } + } + url +} + +/// A library's graph value: the `data` element that `el` holds, read as CSV of the kind Graph +/// Data takes. Its `propertyRow` holds a corner cell and then the names of the series, and each +/// `row` of its `values` holds the row's category in a first `value` whose `key` is `name`, then +/// the row's values. The graph has categories when a row's name isn't blank or is marked +/// `type="string"`. Labels are read as they are; a value is read without the white space round it, +/// and one that is empty, marked `type="string"` or not a finite number is a blank. Without rows or +/// series, or when `el` holds only white space, there is no value. Anything else in `el`, more than +/// [`MAX_GRAPH_CATEGORIES`] rows or [`MAX_GRAPH_SERIES`] series (what a graph holds), and CSV longer +/// than graph values hold, are refused. +fn graph_value(el: roxmltree::Node, set: &str, cmd: &str) -> Result> { + let var = el.tag_name().name(); + let refused = || bad(cmd, format!("data set `{set}` holds a value for `{var}` that isn't a graph's `data` element")); + let named = |name: &'static str| move |n: &roxmltree::Node| n.tag_name().name() == name; + let mut children = elements(el); + let data = match (children.next(), children.next()) { + (None, _) if deep_text(el).trim_matches(XML_SPACE).is_empty() => return Ok(None), + (Some(data), None) if data.tag_name().name() == "data" => data, + _ => return Err(refused()), + }; + // Labels keep their white space; numbers are read without it. + let series: Vec = + elements(data).find(named("propertyRow")).map(|r| elements(r).filter(named("value")).skip(1).map(deep_text).collect()).unwrap_or_default(); + let rows: Vec = + elements(data).filter(named("values")).flat_map(elements).filter(named("row")).take(MAX_GRAPH_CATEGORIES + 1).collect(); + if rows.is_empty() && series.is_empty() { + return Ok(None); + } + let too_many = || bad(cmd, format!("data set `{set}` holds a graph value for `{var}` with {}", graph_limits())); + // A row's values after its name. + let wide = |row: &roxmltree::Node| { + let mut values = elements(*row).filter(named("value")).peekable(); + let _name = values.next_if(|v| v.attribute("key") == Some("name")); + values.count() > MAX_GRAPH_SERIES + }; + if rows.len() > MAX_GRAPH_CATEGORIES || series.len() > MAX_GRAPH_SERIES || rows.iter().any(wide) { + return Err(too_many()); + } + // Each row's name and the values after it. A blank name marked `type="string"` is a blank + // category, so a graph whose categories are all blank keeps them. + let mut labelled = false; + let read: Vec<(Option, Vec>)> = rows + .iter() + .map(|row| { + let mut values = elements(*row).filter(named("value")).peekable(); + let name = values.next_if(|v| v.attribute("key") == Some("name")); + labelled |= name.is_some_and(|v| v.attribute("type") == Some("string") || !deep_text(v).is_empty()); + let name = name.map(deep_text); + let number = |v: roxmltree::Node| deep_text(v).trim_matches(XML_SPACE).parse::().ok().filter(|n| n.is_finite()); + let numbers = values.map(|v| if v.attribute("type") == Some("string") { None } else { number(v) }); + (name, numbers.collect()) + }) + .collect(); + let categories = if labelled { read.iter().map(|(name, _)| name.clone().unwrap_or_default()).collect() } else { vec![] }; + let mut spec = GraphSpec { series, categories, ..GraphSpec::default() }; + spec.set_cells(read.into_iter().map(|(_, numbers)| numbers).collect()); + // Data set values hold graph data without the line break at its end. + let csv = spec.to_csv().trim_end().to_string(); + if csv.len() > MAX_GRAPH_CSV { + return Err(bad(cmd, format!("data set `{set}` holds a graph value for `{var}` longer than {MAX_GRAPH_CSV} bytes"))); + } + Ok(Some(DataValue::Graph(csv))) } /// The variable library an SVG carries (SVG Options › Include Variable Data), read as @@ -317,7 +526,8 @@ pub(crate) fn svg_library(svg: &str) -> Option> { for (name, value) in &entities { element = element.replace(name.as_str(), value); } - parse_library(&format!("{element}"), C) + // The SVG keeps only the text variables, so the values of the other kinds aren't read. + parse_library(&format!("{element}"), C, true) }; Some(read()) } @@ -389,12 +599,16 @@ fn variable_sets_range(svg: &str) -> Option<(usize, Option)> { /// the type object made of the element its `docRef` names, or the one type object among the /// objects a group made of it holds (`found`: the object made of each element, by id). A `docRef` /// that names no type object, or one another variable is bound to already, binds nothing. The art -/// stays as the file draws it. The warning about the variables of other kinds that were left out, -/// if any. +/// stays as the file draws it. Variables of other kinds are left out with their values. The +/// warning about those variables, if any. pub(crate) fn give_svg_library(doc: &mut Document, lib: Library, found: &HashMap) -> Option { + let (text, other): (Vec, Vec) = lib.variables.into_iter().partition(|v| v.kind == VariableKind::Text); let mut vars = - Variables { variables: lib.text.iter().map(|n| Variable { name: n.clone(), kind: VariableKind::Text }).collect(), ..Variables::default() }; + Variables { variables: text.iter().map(|v| Variable { name: v.name.clone(), kind: VariableKind::Text }).collect(), ..Variables::default() }; vars.datasets = lib.datasets; + for ds in &mut vars.datasets { + ds.values.retain(|_, v| matches!(v, DataValue::Text(_))); + } // A type object written with a paint of its own, or with fills and strokes of its appearance, // is a group around its text (and the appearance's paths). let text_of = |id: NodeId| match doc.node(id).map(|n| &n.kind) { @@ -415,32 +629,32 @@ pub(crate) fn give_svg_library(doc: &mut Document, lib: Library, found: &HashMap } } doc.variables = vars.into(); - left_out_warning(lib.other.iter().map(|(_, t)| t.as_str())) + left_out_warning(other.iter().map(|v| v.trait_name.as_deref().unwrap_or_else(|| v.kind.label()))) } /// Load Variable Library: replace the document's variables and data sets with a variable library's /// ([`parse_library`]) in one undo step, or none when the document already holds what the library /// gives. Every data set is deleted, and every variable of the document is deleted with its -/// bindings and values, except a text variable the library also declares: it stays bound to its -/// objects, so the library's data sets change them (#4136; a template's bound variables take a -/// library of the same names: +/// bindings and values, except a variable the library also declares with the same kind: it stays +/// bound to its objects, so the library's data sets change them (#4136; a template's bound +/// variables take a library of the same names: /// ). The -/// library's other text variables are then defined, unbound, and its data sets are added. The -/// library's variables of other kinds are left out, named in `skipped` and in a warning. +/// library's other variables are then defined with their kinds, unbound, and its data sets are +/// added. pub(super) fn load_library(s: &mut Session, p: &Value) -> Result { const C: &str = "variable.loadLibrary"; let bytes = library_bytes(p, C)?; let xml = std::str::from_utf8(bytes.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(&bytes)).map_err(|_| bad(C, "the variable library is not UTF-8"))?; - let lib = parse_library(xml, C)?; + let lib = parse_library(xml, C, false)?; let vars = &s.doc()?.doc.variables; - let kept = |v: &Variable| v.kind == VariableKind::Text && lib.text.contains(&v.name); + let kept = |v: &Variable| lib.variables.iter().any(|l| l.name == v.name && l.kind == v.kind); let deleted: Vec = vars.variables.iter().filter(|v| !kept(v)).map(|v| v.name.clone()).collect(); let deleted_sets: Vec = vars.datasets.iter().map(|d| d.name.clone()).collect(); let added: Vec = lib - .text + .variables .iter() - .filter(|n| !vars.variables.iter().any(|v| kept(v) && &v.name == *n)) - .map(|n| Variable { name: n.clone(), kind: VariableKind::Text }) + .filter(|l| !vars.variables.iter().any(|v| kept(v) && v.name == l.name)) + .map(|l| Variable { name: l.name.clone(), kind: l.kind }) .collect(); // Lock Variables refuses New Variable and Delete Variable, so the load is refused when it would // delete or define a variable. @@ -460,14 +674,8 @@ pub(super) fn load_library(s: &mut Session, p: &Value) -> Result { let st = s.doc_mut()?; st.drop_stale_variables_highlight(); st.revision += 1; - let skipped: Vec = lib.other.iter().map(|(name, t)| json!({"name": name, "trait": t})).collect(); - let mut out = json!({ - "variables": lib.text, "deleted": deleted, "deletedDataSets": deleted_sets, "names": names, "skipped": skipped, - }); - if let Some(warning) = left_out_warning(lib.other.iter().map(|(_, t)| t.as_str())) { - out["warning"] = json!(warning); - } - Ok(out) + let declared: Vec<&str> = lib.variables.iter().map(|l| l.name.as_str()).collect(); + Ok(json!({"variables": declared, "deleted": deleted, "deletedDataSets": deleted_sets, "names": names})) } /// The warning about variables that aren't text and were left out, given the kind of each: every @@ -533,26 +741,95 @@ fn push_escaped(out: &mut String, c: char, attribute: bool) { } } -/// Save Variable Library: the document's text variables and its data sets as a variable library in -/// the layout [`parse_library`] reads, so Load Variable Library reads back the same text variables, -/// data set names and text values. A text value is written as one `p` element per line. Variables -/// of other kinds are left out with their values, named in `skipped` and in a warning. A text -/// variable whose name can't name an element ([`element_name`]), a data set name or text value that -/// holds a character XML can't hold, a name that Load Variable Library would read differently or -/// refuse (white space at either end of a data set name, a name longer than `MAX_NAME` characters, -/// a name used twice), and a library past the caps Load Variable Library reads are refused. With `path` the library is written to the file; without it the reply carries it as -/// `xml`. +/// Add the graph value `csv` of the variable `var` to `xml` as the `data` element [`graph_value`] +/// reads: the CSV read as Graph Data reads it, a `propertyRow` with a blank corner cell and the +/// series names when it names series, and a `row` per category, its name in a first `value` with +/// `key="name"` (blank without categories) and then a `value` per series, blank where the row has +/// none. A label that isn't a number is marked `type="string"`, and so is a blank category. CSV +/// that names series and has no rows is written as the `propertyRow` alone. Refused for CSV with +/// neither rows nor series, which reads back as no value, for more than [`MAX_GRAPH_CATEGORIES`] +/// rows or [`MAX_GRAPH_SERIES`] series (what a graph holds), when a label holds a character XML +/// can't hold, and when `xml` grows past `room` bytes. +fn push_graph(xml: &mut String, var: &str, csv: &str, room: usize) -> std::result::Result<(), GraphRefusal> { + let (series, categories, rows) = super::super::graph::parse_csv(csv); + if rows.is_empty() && series.is_empty() { + return Err(GraphRefusal::Empty); + } + let width = rows.iter().map(Vec::len).max().unwrap_or(0).max(series.len()); + if rows.len() > MAX_GRAPH_CATEGORIES || width > MAX_GRAPH_SERIES { + return Err(GraphRefusal::TooMany); + } + if !series.iter().chain(&categories).all(|l| l.chars().all(xml_char)) { + return Err(GraphRefusal::Control); + } + let labelled = !categories.is_empty(); + let label = |l: &str, category: bool| { + let text = !l.is_empty() && l.trim().parse::().is_err(); + let blank_category = category && labelled && l.is_empty(); + let key = if category { " key=\"name\"" } else { "" }; + let string = if text || blank_category { " type=\"string\"" } else { "" }; + format!("{}", escaped(l, false)) + }; + let _ = writeln!(xml, "\t\t\t\t<{var}>\n\t\t\t\t\t", width + usize::from(labelled)); + if !series.is_empty() { + let names: String = (0..width).map(|s| label(series.get(s).map(String::as_str).unwrap_or_default(), false)).collect(); + let _ = writeln!(xml, "\t\t\t\t\t\t{names}"); + } + xml.push_str("\t\t\t\t\t\t\n"); + for (i, row) in rows.iter().enumerate() { + let name = label(categories.get(i).map(String::as_str).unwrap_or_default(), true); + let values: String = (0..width) + .map(|s| match row.get(s).copied().flatten() { + Some(v) => format!("{v}"), + None => "".to_string(), + }) + .collect(); + let _ = writeln!(xml, "\t\t\t\t\t\t\t{name}{values}"); + if xml.len() > room { + return Err(GraphRefusal::TooLarge); + } + } + let _ = writeln!(xml, "\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t"); + Ok(()) +} + +/// What a graph holds at most, for the errors about graph data past it. +fn graph_limits() -> String { + format!("more than {MAX_GRAPH_CATEGORIES} rows or {MAX_GRAPH_SERIES} series, which a graph doesn't hold") +} + +/// Why [`push_graph`] refused a graph value. +enum GraphRefusal { + /// A label holds a character XML can't hold. + Control, + /// The data has more rows or series than a graph holds. + TooMany, + /// The data has neither rows nor series. + Empty, + /// The library grew past the room it has. + TooLarge, +} + +/// Save Variable Library: the document's variables and its data sets as a variable library in the +/// layout [`parse_library`] reads, so Load Variable Library reads back the same variables with their +/// kinds, data set names and values. Each variable is declared with the `trait` and `category` of +/// its kind ([`kind_trait`]), and a variable of unknown kind with neither. A text value is written +/// as one `p` element per line, a visibility value as `true` or `false`, an image value as +/// [`library_file`] writes its path, and a graph value as a `data` element ([`push_graph`]). A +/// variable whose name can't name an element ([`element_name`]; a variable of unknown kind has no +/// values, so no element is named after it), a name or value that holds a character XML can't +/// hold, a name that Load Variable Library would read differently or refuse (white space at either +/// end, a name longer than `MAX_NAME` characters, a name used twice), an image value that isn't a +/// file's absolute path, and a library past the caps Load Variable Library reads are refused. With +/// `path` the library is written to the file; without it the reply carries it as `xml`. pub(super) fn save_library(s: &mut Session, p: &Value) -> Result { const C: &str = "variable.saveLibrary"; let vars = &s.doc()?.doc.variables; if vars.variables.is_empty() { return Err(bad(C, "define a variable first")); } - let (text, other): (Vec<&Variable>, Vec<&Variable>) = vars.variables.iter().partition(|v| v.kind == VariableKind::Text); - if text.is_empty() { - return Err(bad(C, "a variable library holds text variables, and the document has none")); - } - if let Some(name) = text.iter().map(|v| &v.name).find(|n| !element_name(n)) { + let all: Vec<&Variable> = vars.variables.iter().collect(); + if let Some(name) = all.iter().filter(|v| v.kind != VariableKind::Unknown).map(|v| &v.name).find(|n| !element_name(n)) { return Err(bad( C, format!( @@ -560,48 +837,62 @@ pub(super) fn save_library(s: &mut Session, p: &Value) -> Result { ), )); } - // Load Variable Library refuses a name longer than `MAX_NAME` characters and a name declared - // twice. + // Load Variable Library reads a name trimmed and refuses one longer than `MAX_NAME` characters + // or declared twice. let mut declared = BTreeSet::new(); - for v in &text { - named(Some(&v.name), "varName", C)?; + for v in &all { + if named(Some(&v.name), "varName", C)? != v.name || !v.name.chars().all(xml_char) { + return Err(bad( + C, + format!("variable `{}` starts or ends with white space or holds a control character, which a variable library can't hold", v.name), + )); + } if !declared.insert(v.name.as_str()) { return Err(bad(C, format!("variable `{}` is already defined", v.name))); } } - if text.len() > MAX_LIBRARY_VARIABLES { + if all.len() > MAX_LIBRARY_VARIABLES { return Err(bad(C, format!("the variable library declares more than {MAX_LIBRARY_VARIABLES} variables"))); } if vars.datasets.len() > MAX_LIBRARY_DATASETS { return Err(bad(C, format!("the variable library declares more than {MAX_LIBRARY_DATASETS} data sets"))); } - fn text_value<'a>(ds: &'a DataSet, var: &str) -> Option<&'a str> { - match ds.values.get(var) { - Some(DataValue::Text(t)) => Some(t.as_str()), - _ => None, - } - } let mut xml = format!( "\n\ \n\ \t\n\ \t\n\ + \t\n\ ]>\n\ \n\ \n\ \t\n\ \t\t\n" ); - for v in &text { - xml += &format!("\t\t\t\n", v.name); + for v in &all { + let name = escaped(&v.name, true); + match kind_trait(v.kind) { + Some((t, category)) => xml += &format!("\t\t\t\n"), + None => xml += &format!("\t\t\t\n"), + } } xml += "\t\t\n\t\t\n"; - // Load Variable Library caps the file and the text its entity references expand to: one - // `&ns_flows;` per variable, two `&ns_vars;` and one `&ns_custom;`. The library stays within - // the cap less what the references add. + // Load Variable Library caps the file and the text its entity references expand to: each + // variable's `category`, two `&ns_vars;` and one `&ns_custom;`. The library stays within the + // cap less what the references add. let grows = |value: &str, reference: &str| value.len().saturating_sub(reference.len()); - let growth = text.len() * grows(NS_FLOWS, "&ns_flows;") + 2 * grows(NS_VARIABLES, "&ns_vars;") + grows(NS_CUSTOM, "&ns_custom;"); + let growth = all + .iter() + .filter_map(|v| kind_trait(v.kind)) + .map(|(_, category)| match category { + "&ns_flows;" => grows(NS_FLOWS, category), + "&ns_graphs;" => grows(NS_GRAPHS, category), + _ => grows(NS_VARIABLES, category), + }) + .sum::() + + 2 * grows(NS_VARIABLES, "&ns_vars;") + + grows(NS_CUSTOM, "&ns_custom;"); let room = MAX_LIBRARY_BYTES.saturating_sub(growth); let too_large = || bad(C, format!("the variable library is larger than {MAX_LIBRARY_BYTES} bytes")); let mut seen = BTreeSet::new(); @@ -615,25 +906,61 @@ pub(super) fn save_library(s: &mut Session, p: &Value) -> Result { if !seen.insert(name.as_str()) { return Err(bad(C, format!("dataset `{name}` already exists"))); } - if !name.chars().all(xml_char) || text.iter().filter_map(|v| text_value(ds, &v.name)).any(|t| !t.chars().all(xml_char)) { - return Err(bad(C, format!("data set `{name}` holds a control character, which a variable library can't hold"))); + let control = || bad(C, format!("data set `{name}` holds a control character, which a variable library can't hold")); + let mut text_values = all.iter().filter_map(|v| match ds.values.get(&v.name) { + Some(DataValue::Text(t)) if v.kind == VariableKind::Text => Some(t), + _ => None, + }); + if !name.chars().all(xml_char) || text_values.any(|t| !t.chars().all(xml_char)) { + return Err(control()); } xml += &format!("\t\t\t\n", escaped(name, true)); - for v in &text { - let Some(t) = text_value(ds, &v.name) else { continue }; - xml += &format!("\t\t\t\t<{}>\n", v.name); - for line in t.split('\n') { - xml += "\t\t\t\t\t

"; - // A value can be larger than the cap, so the text stops growing once it passes it. - for c in line.chars() { - push_escaped(&mut xml, c, false); - if xml.len() > room { - return Err(too_large()); + for v in &all { + let Some(value) = ds.values.get(&v.name).filter(|value| value.fits(v.kind)) else { continue }; + let var = &v.name; + match value { + DataValue::Text(t) => { + xml += &format!("\t\t\t\t<{var}>\n"); + for line in t.split('\n') { + xml += "\t\t\t\t\t

"; + // A value can be larger than the cap, so the text stops growing once it passes it. + for c in line.chars() { + push_escaped(&mut xml, c, false); + if xml.len() > room { + return Err(too_large()); + } + } + xml += "

\n"; } + xml += &format!("\t\t\t\t\n"); } - xml += "

\n"; + DataValue::Visible(shown) => xml += &format!("\t\t\t\t<{var}>{shown}\n"), + DataValue::Image(path) => { + // Load Variable Library reads back only a file's absolute path. + let file = library_file(path); + if library_path(file.trim_matches(XML_SPACE)).as_deref() != Some(path.as_str()) { + return Err(bad(C, format!("data set `{name}` holds an image value for `{var}` that isn't a file's absolute path"))); + } + if !file.chars().all(xml_char) { + return Err(control()); + } + xml += &format!("\t\t\t\t<{var}>{}\n", escaped(&file, false)); + } + DataValue::Graph(csv) => match push_graph(&mut xml, var, csv, room) { + Ok(()) => {} + Err(GraphRefusal::Control) => return Err(control()), + Err(GraphRefusal::TooMany) => { + return Err(bad(C, format!("data set `{name}` holds a graph value for `{var}` with {}", graph_limits()))); + } + Err(GraphRefusal::Empty) => { + return Err(bad(C, format!("data set `{name}` holds a graph value for `{var}` without rows or series"))); + } + Err(GraphRefusal::TooLarge) => return Err(too_large()), + }, + } + if xml.len() > room { + return Err(too_large()); } - xml += &format!("\t\t\t\t\n", v.name); } xml += "\t\t\t\n"; if xml.len() > room { @@ -644,13 +971,7 @@ pub(super) fn save_library(s: &mut Session, p: &Value) -> Result { if xml.len() > room { return Err(too_large()); } - let skipped: Vec = other.iter().map(|v| json!({"name": v.name, "kind": v.kind.label()})).collect(); - let mut out = json!({ - "variables": text.iter().map(|v| v.name.as_str()).collect::>(), "datasets": vars.datasets.len(), "skipped": skipped, - }); - if let Some(warning) = left_out_warning(other.iter().map(|v| v.kind.label())) { - out["warning"] = json!(warning); - } + let mut out = json!({"variables": all.iter().map(|v| v.name.as_str()).collect::>(), "datasets": vars.datasets.len()}); match str_param(p, "path") { Some(path) => { let path = absolute_path(path); diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 6ca724d810..9f676e737c 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -222,11 +222,11 @@ pub fn written_elsewhere(path: &str) -> bool { !cfg!(windows) && foreign && current().is_some() } -/// Does a command param named `key` hold a file or folder path: `path`, `paths`, `file`, `files`, -/// `folder`, or a name ending in `Path`, `Paths`, `File`, `Files` or `Folder` (`diffPath`, -/// `destinationFolder`)? +/// Does a command param named `key` hold a file or folder path in a command that gives it no other +/// meaning ([`crate::cmd::key_location`]: `path`, `file`, `diffPath`, `destinationFolder` and the +/// like)? [`crate::cmd::ParamsPlace`] tells what it holds in a given command. pub fn is_path_key(key: &str) -> bool { - matches!(key, "path" | "paths" | "file" | "files" | "folder") || ["Path", "Paths", "File", "Files", "Folder"].iter().any(|end| key.ends_with(end)) + crate::cmd::key_location(key).is_some() } /// May `path` be written here? Always, without roots in force. diff --git a/crates/engine/src/interaction.rs b/crates/engine/src/interaction.rs index e3cd563d55..99a2569005 100644 --- a/crates/engine/src/interaction.rs +++ b/crates/engine/src/interaction.rs @@ -24,6 +24,9 @@ pub struct Interaction { /// The perspective transform the previews make (`perspective.transform` params): Transform /// Again repeats it once the drag is committed. pub perspective_again: Option, + /// A preview drew an object on, or attached one to, a plane held by Automatic Plane + /// Positioning: the plane goes back to its place once the drag is committed. + pub(crate) plane_placed: bool, /// A transform or a perspective edit with `copy` keeps the copies it made of the snapshot here /// ([`PreviewCopies`]). pub(crate) copies: Option>, diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 1e4629e448..86525e9214 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -111,6 +111,9 @@ pub struct Prefs { pub recent_fonts_count: u32, pub missing_glyph_protection: bool, pub highlight_alternate_glyphs: bool, + /// Type › Show Character Alternates: with a Type tool and one character selected, the canvas + /// shows that character's alternate glyphs beside it (on by default). + pub show_character_alternates: bool, /// Type › Highlight Substituted Fonts: on screen, text drawn in a substitute for a missing /// font is highlighted, in every document (on by default). pub highlight_substituted_fonts: bool, @@ -442,6 +445,7 @@ impl Default for Prefs { recent_fonts_count: 10, missing_glyph_protection: true, highlight_alternate_glyphs: false, + show_character_alternates: true, highlight_substituted_fonts: true, placeholder_text: true, typed_lists: true, diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index a87b47be0e..1244b77432 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -24,6 +24,8 @@ impl Session { }); // Clicks find an image's own fills and strokes where their effects draw them. vectorcraft_doc::hit::set_image_paint(vectorcraft_render::effects::image_paint); + // Clicks inside a clip group fall in the region its clipping path's effects give it. + vectorcraft_doc::hit::set_clip_region(vectorcraft_render::effects::reshaped_clip_outline); // Clicks find a blend's steps and an envelope's distorted art where the canvas draws them, // evaluated again when the fonts, the hyphenation exceptions or the plug-ins change. vectorcraft_doc::hit::set_live_art(vectorcraft_render::effects::expand_live, || { @@ -329,6 +331,8 @@ impl Session { // Ruler guides a reader left in the saved list become nodes on their layers. doc.guides_into_nodes(); cmd::dimension::conform(&mut doc); + // A plane held by Automatic Plane Positioning when the file was saved is back in its place. + vectorcraft_tools::distort::perspective::PerspectiveGrid::end_positioning(&mut doc); self.reset_tool_for_doc_switch(); let mut st = DocState::new(doc, path); st.history.limit = self.prefs.history_states as usize; @@ -357,6 +361,7 @@ impl Session { doc.resolve_inline_art(); doc.guides_into_nodes(); cmd::dimension::conform(&mut doc); + vectorcraft_tools::distort::perspective::PerspectiveGrid::end_positioning(&mut doc); // In the back, type set in a font named like a composite font is measured again below, in // the document's own composite fonts, not in the front document's. let back = self.active != Some(index); @@ -415,14 +420,16 @@ impl Session { /// Measure the type not measured yet in open document `index`, which is in the back, in its own /// composite fonts, lent for the measuring, so its type has the bounds it will have when the - /// document comes to the front. The front document stays the one whose composite fonts are - /// registered. The names of the document's composite fonts its type was measured in are kept, - /// so its coming to the front does not measure that type again. + /// document comes to the front: type naming a composite font the document does not define is + /// measured as in a missing font, also when the front document defines one of that name, and + /// also when the document defines none. The front document stays the one whose composite fonts + /// are registered. The names of the document's composite fonts its type was measured in are + /// kept, so its coming to the front does not measure that type again. fn measure_back_document(&mut self, index: usize) { let Some(st) = self.docs.get(index) else { return }; let fonts = st.doc.composite_fonts.clone(); let db = vectorcraft_text::FontDb::global(); - let lent = db.lend_composite_fonts(&fonts); + let lent = db.lend_document_composite_fonts(&fonts); // A name another loan holds with a different definition is not lent: type set in it is // measured again when the document comes to the front. let own: HashSet = diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index 73977f7d64..4f47b325b9 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -289,6 +289,7 @@ impl Session { variables_highlight: st.variables_highlight.clone(), isolation: st.isolation, perspective_again: None, + plane_placed: false, copies: None, move_box: std::sync::OnceLock::new(), }); @@ -319,6 +320,7 @@ impl Session { it.preview_paint = None; it.color_mode_paints = None; it.deferred_color_mode = None; + it.plane_placed = false; if selection_changed { st.selection.clone_from(&it.selection); } @@ -378,6 +380,7 @@ impl Session { after.clone_from(&paint); } let perspective_again = it.perspective_again.take(); + let plane_placed = it.plane_placed; let copy = preview.0 == "object.transform" && preview.1.get("copy").and_then(Value::as_bool).unwrap_or(false); // Alt pressed or released during a move drag turns it into a copy or back: name it for // what it did in the end. @@ -395,6 +398,12 @@ impl Session { preview.1.get("dy").and_then(Value::as_f64).unwrap_or(0.0), ); st.keep_interaction(it); + // The drag drew an object on, or attached one to, the plane Automatic Plane Positioning + // held: the plane is back in its place now, as view state (undoing the drag holds it again). + if plane_placed && changed && vectorcraft_tools::distort::perspective::PerspectiveGrid::positioning(&st.doc) { + vectorcraft_tools::distort::perspective::PerspectiveGrid::end_positioning(Arc::make_mut(&mut st.doc)); + st.revision += 1; + } if preview.0 == "object.transform" && changed { let m = cmd::matrix_param(&preview.1, "matrix"); if let Some(m) = m { diff --git a/crates/engine/src/store.rs b/crates/engine/src/store.rs index 8a18ce9824..9c555d82f7 100644 --- a/crates/engine/src/store.rs +++ b/crates/engine/src/store.rs @@ -17,9 +17,8 @@ //! * **Plug-ins**: the module of each plug-in `plugin.install` installs, as a `.wasm` file named //! after its id (as Illustrator keeps plug-ins in its Plug-ins folder); `plugin.remove` deletes it. //! Attaching the folder installs them again, except in Safe Mode and except the ones the user -//! disabled, which `disabled.json` in the same folder lists (`plugin.setEnabled`; a window locks -//! `disabled.lock` while it writes the list). The Additional Plug-ins Folder preference is not -//! copied: it is loaded from where it is. `grants.json` holds what the user granted the plug-ins +//! disabled, which `disabled.json` in the same folder lists (`plugin.setEnabled`). The Additional +//! Plug-ins Folder preference is not copied: it is loaded from where it is. `grants.json` holds what the user granted the plug-ins //! stored there that list permissions (id, module hash, permissions); a stored plug-in whose //! permissions it doesn't grant is skipped with a log record, and stays in the folder. //! * **Plug-in settings and caches**: `storage/id-/` in the plug-in store, the id written as @@ -27,6 +26,11 @@ //! keeps with the `settings` and `cache` permissions ([`PluginStorage`]): `settings.json` and a //! `cache` folder with one file per entry. The host names every file; a plug-in only names keys. //! Replacing a plug-in keeps them, and `plugin.remove` deletes them. +//! * **Turns on the plug-in store**: a window or process locks `disabled.lock` in the plug-in folder +//! ([`StoreTurn`]) while it reads and changes the stored plug-ins, `grants.json`, `disabled.json` +//! and the plug-ins' settings and caches, so that two of them using one folder change it one after +//! the other: an install's module and grant are written in one turn, and a grant written for one +//! plug-in doesn't undo another one's. //! //! The files are untrusted input like any other: sizes and counts are capped, a file that does not //! parse is skipped with a log record, and every write is atomic. @@ -62,12 +66,15 @@ pub const MAX_PLUGIN_STORE: u64 = 512 << 20; const PLUGIN_EXT: &str = "wasm"; /// The file in the plug-in folder that lists the plug-ins the user disabled. pub const DISABLED_FILE: &str = "disabled.json"; -/// The file in the plug-in folder that a window locks while it reads and writes [`DISABLED_FILE`]. +/// The file in the plug-in folder that a window locks while it reads and changes the plug-in store +/// ([`StoreTurn`]), [`DISABLED_FILE`] included. pub const DISABLED_LOCK: &str = "disabled.lock"; /// The file in the plug-in store that holds the permissions the user granted. const GRANTS_FILE: &str = "grants.json"; /// The error of a `plugin.remove` that can't remove the plug-in's grant from [`GRANTS_FILE`]. pub(crate) const GRANT_NOT_REMOVED: &str = "the plug-in's grant can't be removed from the plug-in store"; +/// The error of a change to the plug-in store that can't take its turn ([`StoreTurn`]). +pub(crate) const STORE_NOT_LOCKED: &str = "the plug-in store can't be locked"; /// The largest grants file read. const MAX_GRANTS_FILE: u64 = 1 << 20; /// The folder in the plug-in store that holds each plug-in's settings and cache. @@ -84,7 +91,7 @@ const CACHE_EXT: &str = "bin"; /// A write to a folder that holds more is refused as full. pub(crate) const MAX_CACHE_SCAN: usize = storage::MAX_CACHE_ENTRIES * 2; /// Held while a plug-in's settings or cache change, so two runs can't pass a cap together or lose -/// each other's settings. +/// each other's settings. Taken after the plug-in store's turn ([`StoreTurn`]), never before it. static PLUGIN_DATA_LOCK: Mutex<()> = Mutex::new(()); /// The state of each plug-in folder's storage, shared by every storage made for the folder until /// the plug-in is removed, which closes it and drops it. @@ -99,7 +106,7 @@ const MAX_GRANT_WRITES_KEPT: usize = 256; struct IgnoredGrants { /// The grants that should be gone but could not be removed: no session in the process counts /// them ([`Session::ignore_stored_grant`]) until one writes the store's grants for the id - /// ([`Session::store_grant`]). + /// ([`Session::store_grant_in`]). ignored: BTreeSet<(PathBuf, String)>, /// The latest grant writes of the process, at most [`MAX_GRANT_WRITES_KEPT`], each with the /// count of writes it made ([`IgnoredGrants::writes`]). @@ -217,23 +224,53 @@ fn write_atomic(_: &Path, _: &[u8]) -> std::io::Result<()> { Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "no file system")) } -/// [`DISABLED_LOCK`] in `dir`, locked until the file is dropped, waiting while another window holds -/// it; `None` when it can't be opened or locked. +/// [`DISABLED_LOCK`] in the plug-in store `dir`, locked until the file is dropped, waiting while +/// another window or process holds it, or another handle in this process. The file is opened for +/// reading and writing (a handle that only appends can't be locked on Windows) and is never +/// replaced or removed, so that every window locks the same file. #[cfg(not(target_arch = "wasm32"))] -fn lock_disabled(dir: &Path) -> Option { - let opened = std::fs::create_dir_all(dir) - .and_then(|()| std::fs::File::options().create(true).truncate(false).read(true).write(true).open(dir.join(DISABLED_LOCK))); - let file = opened.and_then(|f| f.lock().map(|()| f)); - if let Err(e) = &file { - log::warn!("can't lock {}: {e}", dir.join(DISABLED_LOCK).display()); +fn lock_store(dir: &Path) -> std::io::Result { + std::fs::create_dir_all(dir)?; + let file = std::fs::File::options().create(true).truncate(false).read(true).write(true).open(dir.join(DISABLED_LOCK))?; + match file.try_lock() { + Ok(()) => return Ok(file), + Err(std::fs::TryLockError::WouldBlock) => {} + Err(std::fs::TryLockError::Error(e)) => return Err(e), } - file.ok() + #[cfg(test)] + if let Some(waiting) = WHILE_STORE_LOCKED.take() { + waiting(); + } + file.lock()?; + Ok(file) } /// The browser has no folders to keep anything in. #[cfg(target_arch = "wasm32")] -fn lock_disabled(_: &Path) -> Option { - None +fn lock_store(_: &Path) -> std::io::Result { + Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "no file system")) +} + +/// A turn on a plug-in store ([`Session::plugin_store_turn`]): while it is held, no other window or +/// process that takes one reads and changes the store's plug-ins, grants, disabled list, settings +/// or caches. Dropping it ends the turn. A turn is taken once per operation and handed to the +/// functions it calls, since a second lock of the same file by the same thread waits for ever. +pub(crate) struct StoreTurn { + /// [`DISABLED_LOCK`], locked; `None` without a store, and for a load that goes ahead without + /// a turn ([`Session::plugin_store_turn_for_load`]), which then writes nothing to the store. + lock: Option, +} + +impl StoreTurn { + /// A turn that isn't held, for a load that goes ahead without one: it writes nothing. + pub(crate) fn unheld() -> Self { + StoreTurn { lock: None } + } + + /// Whether the store may be written in this turn. + fn held(&self) -> bool { + self.lock.is_some() + } } #[cfg(test)] @@ -252,6 +289,15 @@ thread_local! { /// Tests: writing the `.delete` file beside a folder about to be deleted ([`delete_aside`]) /// fails on this thread, as on a full volume. pub(crate) static MARKER_WRITE_FAILS: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// Tests: runs once on this thread when locking the plug-in store ([`lock_store`]) finds it + /// locked and waits. + pub(crate) static WHILE_STORE_LOCKED: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; + /// Tests: runs once on this thread when a grant write has read `grants.json` and before it + /// writes the file. + pub(crate) static AFTER_GRANTS_READ: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; + /// Tests: runs once on this thread when a change of a plug-in's settings has read them and + /// before it writes them. + pub(crate) static AFTER_SETTINGS_READ: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; } /// Remove `dir/file` → whether it is gone; a file that isn't there is what was wanted. @@ -401,11 +447,14 @@ impl Session { /// Keep the plug-ins this session installs in `dir`, take the disabled plug-ins saved there /// ([`DISABLED_FILE`]), and install the stored ones ([`Session::load_stored_plugins`]). pub fn attach_plugin_store(&mut self, dir: PathBuf) { - let disabled = - read_capped(&dir.join(DISABLED_FILE), safe_mode::MAX_DISABLED_FILE_BYTES).map(|b| safe_mode::parse_disabled_file(&b)).unwrap_or_default(); - safe_mode::set_disabled(disabled); + let path = dir.join(DISABLED_FILE); self.plugin_dir = Some(dir); - self.load_stored_plugins(); + // A `plugin.install` in another session or process writes the store before this reads it. + let _held = crate::cmd::plugin::hold_plugin_changes(); + let turn = self.plugin_store_turn_for_load(); + let disabled = read_capped(&path, safe_mode::MAX_DISABLED_FILE_BYTES).map(|b| safe_mode::parse_disabled_file(&b)).unwrap_or_default(); + safe_mode::set_disabled(disabled); + self.load_stored_plugins_in(&turn); } /// Install the plug-ins kept in the plug-in folder: none in Safe Mode, and none the user @@ -415,14 +464,25 @@ impl Session { /// stays in the folder with its grant. A grant for an id whose stored module lists no /// permissions is forgotten; one that can't be removed from the grants file doesn't count for /// any session in the process attached to the folder until the file can be written for the id - /// ([`Session::ignore_stored_grant`]). + /// ([`Session::ignore_stored_grant`]). The folder is read and changed in one turn on it + /// ([`Session::plugin_store_turn_for_load`]). pub fn load_stored_plugins(&mut self) { + if self.plugin_dir.is_none() || safe_mode::active() { + return; + } + // A `plugin.install` in another session or process writes the store before this reads it. + let _held = crate::cmd::plugin::hold_plugin_changes(); + let turn = self.plugin_store_turn_for_load(); + self.load_stored_plugins_in(&turn); + } + + /// [`Session::load_stored_plugins`] in `turn`, while [`crate::cmd::plugin::hold_plugin_changes`] + /// is held. + fn load_stored_plugins_in(&mut self, turn: &StoreTurn) { let Some(dir) = self.plugin_dir.clone() else { return }; if safe_mode::active() { return; } - // A `plugin.install` in another session writes the store before this reads it. - let _held = crate::cmd::plugin::hold_plugin_changes(); let grants = self.counted_grants(&dir); let limits = vectorcraft_plugins::Limits::default(); let mut left = MAX_PLUGIN_STORE; @@ -454,7 +514,7 @@ impl Session { Some(g) => { asks_nothing.remove(&m.id); vectorcraft_plugins::registry::grant(GrantToken::from_engine_grants_file(g.clone())); - vectorcraft_plugins::registry::set_storage(&m.id, plugin_storage(Some(&dir), &m.id)); + vectorcraft_plugins::registry::set_storage(&m.id, plugin_storage(Some(&dir), &m.id, turn)); if let Err(e) = vectorcraft_plugins::registry::install(plugin.with_source(path.display().to_string())) { log::warn!("skipping the stored plug-in {}: {e}", path.display()); } @@ -466,7 +526,7 @@ impl Session { } Ok(plugin) => { asks_nothing.insert(plugin.id().to_string()); - vectorcraft_plugins::registry::set_storage(plugin.id(), plugin_storage(Some(&dir), plugin.id())); + vectorcraft_plugins::registry::set_storage(plugin.id(), plugin_storage(Some(&dir), plugin.id(), turn)); if let Err(e) = vectorcraft_plugins::registry::install(plugin.with_source(path.display().to_string())) { log::warn!("skipping the stored plug-in {}: {e}", path.display()); } @@ -483,13 +543,34 @@ impl Session { }; if named { let writes = self.grant_writes(); - if !self.store_grant(id, None) && self.holds_plugin_grant(id) { + if !self.store_grant_in(turn, id, None) && self.holds_plugin_grant(id) { self.ignore_stored_grant(id, writes); } } } } + /// Take a turn on the attached plug-in store ([`StoreTurn`]), waiting while another window or + /// process holds one; without a store, a turn that writes nothing. An error, with a log record, + /// when the lock file can't be made, opened or locked. Taken after + /// [`crate::cmd::plugin::hold_plugin_changes`] when both are needed, and never by a thread that + /// holds a turn already. + pub(crate) fn plugin_store_turn(&self) -> std::io::Result { + let Some(dir) = self.plugin_dir.as_deref() else { return Ok(StoreTurn::unheld()) }; + lock_store(dir) + .map(|file| StoreTurn { lock: Some(file) }) + .inspect_err(|e| log::warn!("can't lock {}: {e}", dir.join(DISABLED_LOCK).display())) + } + + /// [`Session::plugin_store_turn`] for a load, which goes ahead without the turn when the store + /// folder isn't there (nothing is stored) or can't be locked, and then writes nothing to it. + pub(crate) fn plugin_store_turn_for_load(&self) -> StoreTurn { + match self.plugin_dir.as_deref() { + Some(dir) if dir.is_dir() => self.plugin_store_turn().unwrap_or_else(|_| StoreTurn::unheld()), + _ => StoreTurn::unheld(), + } + } + /// Write the disabled plug-ins saved for the next launch to the plug-in folder → whether they /// went there, every change included (`false` without a folder, and when a plug-in turned off /// found the file's list full: [`safe_mode::Merged::complete`]). The changes this launch made are applied to the list @@ -499,8 +580,15 @@ impl Session { /// a file that can't be read (too large, say) or that a later version wrote /// ([`safe_mode::read_disabled_file`]): it is kept as it is. pub fn store_disabled_plugins(&self) -> bool { + self.plugin_store_turn().is_ok_and(|turn| self.store_disabled_plugins_in(&turn)) + } + + /// [`Session::store_disabled_plugins`] in `turn`; `false` when it isn't held. + pub(crate) fn store_disabled_plugins_in(&self, turn: &StoreTurn) -> bool { let Some(dir) = self.plugin_dir.as_deref() else { return false }; - let Some(_turn) = lock_disabled(dir) else { return false }; + if !turn.held() { + return false; + } let path = dir.join(DISABLED_FILE); let theirs = match read_capped(&path, safe_mode::MAX_DISABLED_FILE_BYTES) { Ok(bytes) => match safe_mode::read_disabled_file(&bytes) { @@ -580,10 +668,10 @@ impl Session { grants } - /// Write the module `bytes` of the plug-in `id` to the store → whether they went there (`false` - /// without a folder). - pub(crate) fn store_plugin(&self, id: &str, bytes: &[u8]) -> bool { - self.plugin_dir.as_deref().is_some_and(|dir| put(dir, &format!("{}.{PLUGIN_EXT}", file_stem(id)), bytes)) + /// Write the module `bytes` of the plug-in `id` to the store in `turn` → whether they went there + /// (`false` without a folder, and when `turn` isn't held). + pub(crate) fn store_plugin(&self, turn: &StoreTurn, id: &str, bytes: &[u8]) -> bool { + turn.held() && self.plugin_dir.as_deref().is_some_and(|dir| put(dir, &format!("{}.{PLUGIN_EXT}", file_stem(id)), bytes)) } /// The module the store holds for the plug-in `id`: `None` without a folder or such a file, and @@ -601,14 +689,15 @@ impl Session { /// Return the store's module for the plug-in `id` to `previous`, the bytes it held before a /// write ([`Session::stored_plugin_bytes`]): with `None`, the file is removed. → whether the /// write reported success; a write that reports a failure may still have put `previous` back. - pub(crate) fn put_back_plugin(&self, id: &str, previous: Option<&[u8]>) -> bool { + /// In `turn`, the one the write was made in. + pub(crate) fn put_back_plugin(&self, turn: &StoreTurn, id: &str, previous: Option<&[u8]>) -> bool { #[cfg(test)] if PUT_BACK_FAILS.get() { return false; } let back = match previous { - Some(bytes) => self.store_plugin(id, bytes), - None => self.unstore_plugin(id), + Some(bytes) => self.store_plugin(turn, id, bytes), + None => self.unstore_plugin(turn, id), }; #[cfg(test)] if PUT_BACK_FAILS_AFTER_WRITE.get() { @@ -623,15 +712,23 @@ impl Session { self.plugin_dir.as_ref().map(|dir| dir.join(format!("{}.{PLUGIN_EXT}", file_stem(id))).display().to_string()) } + /// Tests: [`Session::store_grant_in`] in a turn of its own ([`Session::plugin_store_turn`]); + /// `false` when it can't be taken. + #[cfg(test)] + pub(crate) fn store_grant(&self, id: &str, grant: Option) -> bool { + self.plugin_store_turn().is_ok_and(|turn| self.store_grant_in(&turn, id, grant)) + } + /// Record in the store what the user granted plug-in `id` (`None`: nothing), leaving the store's /// other grants as they are; with none left, remove the file. Entries this version can't use /// are written back as they were, except one for `id`. A grants file that is too large, can't /// be read or doesn't hold a list is left as it is, with a log record, and nothing is recorded; - /// so is one whose new content would be larger than `MAX_GRANTS_FILE`. → whether the store now - /// holds what was asked (`false` without a folder). When it does, the grant kept for `id` counts - /// again, for every session in the process attached to the store ([`Session::ignore_stored_grant`]). - pub(crate) fn store_grant(&self, id: &str, grant: Option) -> bool { - let done = self.write_grant(id, grant); + /// so is one whose new content would be larger than `MAX_GRANTS_FILE`. The file is read and + /// written in `turn`. → whether the store now holds what was asked (`false` without a folder, + /// and when `turn` isn't held). When it does, the grant kept for `id` counts again, for every + /// session in the process attached to the store ([`Session::ignore_stored_grant`]). + pub(crate) fn store_grant_in(&self, turn: &StoreTurn, id: &str, grant: Option) -> bool { + let done = turn.held() && self.write_grant(id, grant); if done && let Some(key) = self.plugin_dir.as_deref().map(plugin_store_key) { let mut shared = IGNORED_PLUGIN_GRANTS.lock().unwrap_or_else(|e| e.into_inner()); let entry = (key, id.to_string()); @@ -648,7 +745,7 @@ impl Session { done } - /// How many grant writes the sessions of the process have made ([`Session::store_grant`]). + /// How many grant writes the sessions of the process have made ([`Session::store_grant_in`]). /// Taken before a write that may fail, for [`Session::ignore_stored_grant`]. pub(crate) fn grant_writes(&self) -> u64 { IGNORED_PLUGIN_GRANTS.lock().unwrap_or_else(|e| e.into_inner()).writes @@ -661,7 +758,7 @@ impl Session { } /// Stop counting the attached store's grant for the plug-in `id`, in every session in the - /// process attached to the same folder, until [`Session::store_grant`] next succeeds for it in + /// process attached to the same folder, until [`Session::store_grant_in`] next succeeds for it in /// one of them: for a grant that should be gone and could not be removed, which would otherwise /// approve the bytes it covers. `writes` is [`Session::grant_writes`] from before the failed /// write: when a session has written the store's grants for `id` since, the file holds what that @@ -687,6 +784,10 @@ impl Session { return false; } }; + #[cfg(test)] + if let Some(between) = AFTER_GRANTS_READ.take() { + between(); + } let others = file.other.len(); file.other.retain(|entry| entry.get("id").and_then(serde_json::Value::as_str) != Some(id)); let changed = match grant { @@ -724,16 +825,17 @@ impl Session { }) } - /// Remove the plug-in `id` from the store → whether its file is gone (`false` without a folder). - pub(crate) fn unstore_plugin(&self, id: &str) -> bool { - self.plugin_dir.as_deref().is_some_and(|dir| take(dir, &format!("{}.{PLUGIN_EXT}", file_stem(id)))) + /// Remove the plug-in `id` from the store in `turn` → whether its file is gone (`false` without a + /// folder, and when `turn` isn't held). + pub(crate) fn unstore_plugin(&self, turn: &StoreTurn, id: &str) -> bool { + turn.held() && self.plugin_dir.as_deref().is_some_and(|dir| take(dir, &format!("{}.{PLUGIN_EXT}", file_stem(id)))) } /// Keep the settings and cache of plug-in `id` in the attached plug-in store from now on; without /// one, nowhere (its storage calls then fail as unavailable). Settings and cache that a removal - /// kept are moved back first ([`plugin_storage`]). - pub(crate) fn attach_plugin_storage(&self, id: &str) { - vectorcraft_plugins::registry::set_storage(id, plugin_storage(self.plugin_dir.as_deref(), id)); + /// kept are moved back first, in `turn` ([`plugin_storage`]). + pub(crate) fn attach_plugin_storage(&self, turn: &StoreTurn, id: &str) { + vectorcraft_plugins::registry::set_storage(id, plugin_storage(self.plugin_dir.as_deref(), id, turn)); } /// Does the attached plug-in store have a folder of settings and cache for plug-in `id`, or one @@ -757,9 +859,13 @@ impl Session { /// that rename fails too, the error also names both paths and the reason, and the next attach or /// removal for the id moves the folder back. Once `forget` returns `true`, the folder and the /// kept settings are deleted ([`delete_aside`]); what that deletion leaves stays, with a log - /// record, and a later call for the id tries to delete it again. - pub(crate) fn remove_plugin_storage(&self, id: &str, forget: impl FnOnce() -> bool) -> Result<(), StorageError> { + /// record, and a later call for the id tries to delete it again. All of it happens in `turn`; + /// with a store and a turn that isn't held, nothing changes and this fails. + pub(crate) fn remove_plugin_storage(&self, turn: &StoreTurn, id: &str, forget: impl FnOnce() -> bool) -> Result<(), StorageError> { let not_forgotten = || StorageError::Io(GRANT_NOT_REMOVED.to_string()); + if self.plugin_dir.is_some() && !turn.held() { + return Err(StorageError::Io(STORE_NOT_LOCKED.to_string())); + } vectorcraft_plugins::registry::set_storage(id, None); let Some(dir) = &self.plugin_dir else { return if forget() { Ok(()) } else { Err(not_forgotten()) }; @@ -943,13 +1049,16 @@ fn restore_removed(path: &Path) -> std::io::Result<()> { /// Where plug-in `id` keeps its settings and cache in the plug-in store `dir`. Settings and cache /// that a removal kept are moved back first ([`restore_removed`]); when that fails, the failure is /// logged and there is no storage (its calls fail as unavailable), so that nothing the plug-in -/// writes takes their place. A later attach or load tries again. -fn plugin_storage(dir: Option<&Path>, id: &str) -> Option> { +/// writes takes their place. A later attach or load tries again. They are moved in `turn`; when it +/// isn't held, they stay where they are, as when moving them fails. +fn plugin_storage(dir: Option<&Path>, id: &str, turn: &StoreTurn) -> Option> { let dir = dir?; let data = plugin_data_dir(dir, id); if !is_link(&dir.join(PLUGIN_DATA_DIR)) { let _held = PLUGIN_DATA_LOCK.lock().unwrap_or_else(|e| e.into_inner()); - if let Err(e) = restore_removed(&data) { + let kept_aside = || std::fs::symlink_metadata(&data).is_err() && aside_paths(&data).iter().any(|a| is_kept(a)); + let restored = if turn.held() || !kept_aside() { restore_removed(&data) } else { Err(std::io::Error::other(STORE_NOT_LOCKED)) }; + if let Err(e) = restored { log::warn!("can't move the settings and cache of {} back: {e}", data.display()); return None; } @@ -1088,6 +1197,12 @@ impl PluginStorage { Ok(()) } + /// A turn on the plug-in store ([`lock_store`]), taken before [`PLUGIN_DATA_LOCK`], so that a + /// window or process changing the same settings or cache waits for this change. + fn turn(&self) -> Result { + lock_store(&self.root).map_err(|e| StorageError::Io(format!("{STORE_NOT_LOCKED}: {e}"))) + } + fn kept(&self) -> MutexGuard<'_, Kept> { self.state.kept.lock().unwrap_or_else(|e| e.into_inner()) } @@ -1212,6 +1327,8 @@ impl PluginStorage { impl Storage for PluginStorage { fn setting(&self, key: &str, meter: &mut Meter) -> Result>, StorageError> { + // Reading may move a settings file that doesn't read aside. + let _turn = self.turn()?; let _held = PLUGIN_DATA_LOCK.lock().unwrap_or_else(|e| e.into_inner()); self.open()?; let mut kept = self.kept(); @@ -1219,10 +1336,15 @@ impl Storage for PluginStorage { } fn set_setting(&self, key: &str, value: &[u8], meter: &mut Meter) -> Result<(), StorageError> { + let _turn = self.turn()?; let _held = PLUGIN_DATA_LOCK.lock().unwrap_or_else(|e| e.into_inner()); self.open()?; let mut kept = self.kept(); let settings = &mut self.read_settings(&mut kept.settings, meter)?.values; + #[cfg(test)] + if let Some(between) = AFTER_SETTINGS_READ.take() { + between(); + } if value.len() > storage::MAX_SETTING_BYTES || (!settings.contains_key(key) && settings.len() >= storage::MAX_SETTINGS) { return Err(StorageError::Full); } @@ -1234,6 +1356,7 @@ impl Storage for PluginStorage { } fn delete_setting(&self, key: &str, meter: &mut Meter) -> Result { + let _turn = self.turn()?; let _held = PLUGIN_DATA_LOCK.lock().unwrap_or_else(|e| e.into_inner()); self.open()?; let mut kept = self.kept(); @@ -1258,6 +1381,8 @@ impl Storage for PluginStorage { } fn set_cache_entry(&self, name: &str, value: &[u8], meter: &mut Meter) -> Result<(), StorageError> { + // The cache's size and count are added up and the entry written in one turn. + let _turn = self.turn()?; let _held = PLUGIN_DATA_LOCK.lock().unwrap_or_else(|e| e.into_inner()); self.open()?; let path = self.entry_path(name); @@ -1281,6 +1406,7 @@ impl Storage for PluginStorage { } fn remove_cache_entry(&self, name: &str) -> Result { + let _turn = self.turn()?; let _held = PLUGIN_DATA_LOCK.lock().unwrap_or_else(|e| e.into_inner()); self.open()?; let path = self.entry_path(name); @@ -1296,6 +1422,7 @@ impl Storage for PluginStorage { } fn clear_cache(&self) -> Result { + let _turn = self.turn()?; let _held = PLUGIN_DATA_LOCK.lock().unwrap_or_else(|e| e.into_inner()); self.open()?; let dir = self.cache_dir(); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 2f849901a4..3b54a532ef 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -128,6 +128,7 @@ mod pdffidelity; mod pdfmarks; mod pdfpresets; mod pdfraster; +mod persp_infer; mod persp_planes; pub(super) mod persp_select; mod persp_text; @@ -241,6 +242,25 @@ pub(crate) fn key_guide(s: &Session) -> Option { st.selection.key_guide.and_then(|k| crate::cmd::guide_indexes(&st.doc, &[k]).first().copied()) } +/// Runs the unit test `path` (`tests::newdoc::...`) again in a child process of the test binary +/// → whether this is that child. For a test that changes process-wide state the tests running +/// beside it read, such as the active color settings. +pub(crate) fn in_own_process(path: &str) -> bool { + const CHILD: &str = "VECTORCRAFT_TEST_OWN_PROCESS"; + if std::env::var_os(CHILD).is_some() { + return true; + } + let output = + std::process::Command::new(std::env::current_exe().unwrap()).args(["--exact", path, "--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;"), + "{path} failed in its own process:\n{stdout}\n{}", + String::from_utf8_lossy(&output.stderr), + ); + false +} + #[test] fn create_and_undo_redo() { let mut s = session(); diff --git a/crates/engine/src/tests/anchor_edit_work.rs b/crates/engine/src/tests/anchor_edit_work.rs index 7ad50a871d..1055156167 100644 --- a/crates/engine/src/tests/anchor_edit_work.rs +++ b/crates/engine/src/tests/anchor_edit_work.rs @@ -8,7 +8,7 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_doc::{Appearance, Document, Node, NodeId}; use vectorcraft_geom::path::measured_segments; -use vectorcraft_geom::{Anchor, PathData, Point, SubPath}; +use vectorcraft_geom::{Anchor, AnchorKind, PathData, Point, SubPath, Vec2}; use crate::*; @@ -109,3 +109,29 @@ fn an_anchor_edit_that_changes_nothing_records_no_undo_step() { s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 5, "x": a.p.x + 1.0, "y": a.p.y})).unwrap(); assert_eq!(undo_steps(&s), 1); } + +/// `path.setHandle` to where the handle already is, on a smooth anchor whose other handle is not in +/// line with it, leaves both handles as they are and records no undo step. With `independent` it +/// makes the anchor a corner, which records one. +#[test] +fn a_handle_already_in_place_on_a_smooth_anchor_records_no_undo_step() { + let (mut s, id) = long_path(100); + let p = anchor(&s, id, 5).p; + let smooth = Anchor { p, h_in: p + Vec2::new(-3.0, 0.0), h_out: p + Vec2::new(0.0, 4.0), kind: AnchorKind::Smooth }; + let path = Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().path_data_mut().unwrap(); + path.subpaths[0].anchors[5] = smooth; + for which in ["out", "in"] { + let h = if which == "out" { smooth.h_out } else { smooth.h_in }; + s.execute("path.setHandle", &json!({"id": id.0, "anchor": 5, "which": which, "x": h.x, "y": h.y})).unwrap(); + assert_eq!(undo_steps(&s), 0, "path.setHandle on the {which} handle recorded an undo step"); + assert_eq!(anchor(&s, id, 5), smooth, "path.setHandle on the {which} handle changed the anchor"); + } + s.execute("path.setHandle", &json!({"id": id.0, "anchor": 5, "which": "out", "x": smooth.h_out.x, "y": smooth.h_out.y, "independent": true})) + .unwrap(); + assert_eq!(undo_steps(&s), 1); + assert_eq!(anchor(&s, id, 5).kind, AnchorKind::Corner); + // On a corner, the same independent request changes nothing. + s.execute("path.setHandle", &json!({"id": id.0, "anchor": 5, "which": "out", "x": smooth.h_out.x, "y": smooth.h_out.y, "independent": true})) + .unwrap(); + assert_eq!(undo_steps(&s), 1); +} diff --git a/crates/engine/src/tests/assets.rs b/crates/engine/src/tests/assets.rs index 8719873a94..64ef55d7ab 100644 --- a/crates/engine/src/tests/assets.rs +++ b/crates/engine/src/tests/assets.rs @@ -301,6 +301,42 @@ fn an_export_preset_sets_the_shared_settings() { assert_eq!(run(&mut s, "document.exportSettings", json!({}))["settings"]["prefix"], "p_"); } +/// `openLocation` (Open Location after Export) is remembered in the document's export settings, +/// outside presets; null removes it, and only true or false is taken. +#[test] +fn open_location_is_remembered_in_the_export_settings() { + let mut s = session(); + let open = |s: &mut Session| run(s, "document.exportSettings", json!({}))["settings"]["openLocation"].clone(); + let r = run(&mut s, "assets.settings.set", json!({"openLocation": false})); + assert_eq!(open(&mut s), false); + assert!(r["settings"].get("openLocation").is_none(), "{r}"); + // Create Sub-folders, on for a document without settings, stays on. + assert_eq!(r["settings"]["subfolders"], true, "{r}"); + run(&mut s, "document.exportPresets.save", json!({"name": "Kept", "settings": {"formats": [{"format": "svg"}]}})); + run(&mut s, "assets.settings.set", json!({"exportPreset": "Kept"})); + assert_eq!(open(&mut s), false, "a preset leaves it as it is"); + run(&mut s, "assets.settings.set", json!({"openLocation": null})); + assert_eq!(open(&mut s), Value::Null); + for bad in [json!({"openLocation": "yes"}), json!({"openLocation": 1}), json!({"subfolders": "no"})] { + assert!(s.execute("assets.settings.set", &bad).is_err(), "{bad}"); + } +} + +/// Create Sub-folders turned off on its own ends a remembered folder per format or item, so Export +/// for Screens opens with it off too; given with an export preset, the preset's folders stay. +#[test] +fn create_sub_folders_off_alone_ends_a_folder_per_format_or_item() { + let mut s = session(); + let folders = |s: &mut Session| run(s, "document.exportSettings", json!({}))["settings"]["folders"].clone(); + run(&mut s, "document.exportPresets.save", json!({"name": "Items", "settings": {"formats": [{"format": "svg"}], "folders": "item"}})); + for preset in ["Logo Package", "Items"] { + run(&mut s, "assets.settings.set", json!({"exportPreset": preset, "subfolders": false})); + assert_ne!(folders(&mut s), "none", "{preset}"); + run(&mut s, "assets.settings.set", json!({"subfolders": false})); + assert_eq!(folders(&mut s), "none", "{preset}"); + } +} + /// An export preset applied to the shared settings keeps its folders, with Create Sub-folders on /// for a folder per row; with Create Sub-folders off every file goes into the folder itself, /// mobile and density rows too. diff --git a/crates/engine/src/tests/attributes.rs b/crates/engine/src/tests/attributes.rs index d3edf2615b..b6d00111e2 100644 --- a/crates/engine/src/tests/attributes.rs +++ b/crates/engine/src/tests/attributes.rs @@ -163,6 +163,94 @@ fn reverse_path_direction_on_and_off_set_the_winding() { assert!(s.execute("path.reverse", &json!({})).is_err(), "nothing to reverse"); } +#[test] +fn reverse_path_direction_turns_the_width_profile_and_pen_records_with_the_path() { + use vectorcraft_doc::{AngleProfile, PressureProfile, WidthProfile}; + let mut s = session(); + let open = + NodeId(run(&mut s, "path.create", json!({"anchors": [{"x": 0, "y": 50}, {"x": 40, "y": 50}, {"x": 100, "y": 50}]}))["id"].as_u64().unwrap()); + let closed = rect(&mut s, 10.0); + let profile = WidthProfile { points: vec![(0.0, 0.2, 0.6), (0.3, 1.0, 0.4), (1.0, 0.5, 0.9)] }; + let pressure = PressureProfile { points: vec![(0.0, 0.1), (0.25, 0.9), (1.0, 0.4)] }; + let bearing = AngleProfile { points: vec![(0.0, 10.0), (0.6, 80.0), (1.0, 170.0)] }; + s.edit("set", |d, _| { + for id in [open, closed] { + let st = d.node_mut(id).unwrap().appearance.stroke_mut().unwrap(); + st.profile = Some(profile.clone()); + st.pressure = Some(pressure.clone()); + st.tilt = Some(pressure.clone()); + st.bearing = Some(bearing.clone()); + st.rotation = Some(bearing.clone()); + } + Ok(()) + }) + .unwrap(); + // (anchor point, its fraction of the path's length) for each anchor. + let along = |s: &Session, id: NodeId| { + let sp = s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[0].clone(); + let pos = sp.anchor_arc_positions(); + let total = *pos.last().unwrap(); + sp.anchors.iter().zip(pos).map(|(a, at)| (a.p, at / total)).collect::>() + }; + let before = [along(&s, open), along(&s, closed)]; + run(&mut s, "select.set", json!({"ids": [open.0, closed.0]})); + assert_eq!(run(&mut s, "path.reverse", json!({}))["changed"], 2); + for ((id, before), closed) in [open, closed].into_iter().zip(before).zip([false, true]) { + let after = along(&s, id); + let st = s.doc().unwrap().doc.node(id).unwrap().appearance.stroke().unwrap().clone(); + // Each anchor keeps the widths it had (its sides swapped, as the path runs the other way) + // and what the pen recorded there. (A closed path's start is where its profile steps.) A + // closed path now starts part way along a span of the width profile, which is resampled + // there, so its smooth curve moves a little. + let near = if closed { 0.02 } else { 1e-6 }; + for (p, t) in before.iter().filter(|(_, t)| !closed || *t > 0.0) { + let u = after.iter().find(|(q, _)| q.distance(*p) < 1e-9).unwrap().1; + let (l, r) = profile.at(*t); + let (l2, r2) = st.profile.as_ref().unwrap().at(u); + assert!((l - r2).abs() < near && (r - l2).abs() < near, "{id:?} at {p:?}: {:?} then {:?}", (l, r), (l2, r2)); + for got in [&st.pressure, &st.tilt] { + assert!((pressure.at(*t) - got.as_ref().unwrap().at(u)).abs() < 1e-6, "{id:?} pressure at {p:?}"); + } + for got in [&st.bearing, &st.rotation] { + assert!((bearing.at(*t) - got.as_ref().unwrap().at(u)).abs() < 1e-6, "{id:?} bearing at {p:?}"); + } + } + } +} + +#[test] +fn reverse_path_direction_turns_a_compound_paths_own_width_profile_and_pen_records() { + use vectorcraft_doc::{AngleProfile, PressureProfile, WidthProfile}; + let mut s = session(); + let (a, b) = (rect(&mut s, 0.0), rect(&mut s, 50.0)); + run(&mut s, "select.set", json!({"ids": [a.0, b.0]})); + run(&mut s, "object.compoundPath.make", json!({})); + let compound = s.doc().unwrap().selection.objects[0]; + // A lone rectangle of the same shape, whose strokes Reverse Path Direction already turns. + let lone = rect(&mut s, 0.0); + let profile = WidthProfile { points: vec![(0.0, 0.2, 0.6), (0.3, 1.0, 0.4), (1.0, 0.5, 0.9)] }; + let pressure = PressureProfile { points: vec![(0.0, 0.1), (0.25, 0.9), (1.0, 0.4)] }; + let bearing = AngleProfile { points: vec![(0.0, 10.0), (0.6, 80.0), (1.0, 170.0)] }; + s.edit("set", |d, _| { + for id in [compound, lone] { + let st = d.node_mut(id).unwrap().appearance.stroke_mut().unwrap(); + st.profile = Some(profile.clone()); + st.pressure = Some(pressure.clone()); + st.bearing = Some(bearing.clone()); + } + Ok(()) + }) + .unwrap(); + run(&mut s, "select.set", json!({"ids": [compound.0, lone.0]})); + assert_eq!(run(&mut s, "path.reverse", json!({}))["changed"], 3); + let stroke = |id: NodeId| s.doc().unwrap().doc.node(id).unwrap().appearance.stroke().unwrap().clone(); + let (got, want) = (stroke(compound), stroke(lone)); + assert_ne!(want.profile.as_ref(), Some(&profile), "the lone rectangle's profile turned"); + assert_eq!(got.profile, want.profile, "both members turned alike, so the compound path's profile turns as the rectangle's does"); + assert_eq!(got.pressure, want.pressure); + assert_eq!(got.bearing, want.bearing); +} + #[test] fn attributes_survive_a_native_round_trip() { let mut s = session(); diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index e961a59e81..bc4ce76c83 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -963,6 +963,69 @@ fn brush_freehand_paints_with_a_brush_in_one_step() { assert_eq!(brush_of(&s, id).as_deref(), Some("Charcoal")); } +/// `brush.freehand` refuses a `brush` that is not a string or names no brush in the document, +/// and a `style` other than "pencil" or "brush", before it draws: the document, the selection +/// and the undo history stay as they were. A `brush` left out or null draws the plain path. +#[test] +fn brush_freehand_refuses_a_brush_or_style_it_cannot_use() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + select(&mut s, &[a]); + let points = json!([[10, 10], [60, 40], [120, 10]]); + for (extra, words) in [ + (json!({"brush": "Nope"}), "no brush named `Nope`"), + (json!({"brush": ""}), "no brush named ``"), + (json!({"brush": 5}), "`brush` must be a string"), + (json!({"brush": {"name": "Charcoal"}}), "`brush` must be a string"), + (json!({"brush": true}), "`brush` must be a string"), + (json!({"brush": "Charcoal", "style": "marker"}), "`style` must be \"pencil\" or \"brush\", not \"marker\""), + (json!({"brush": "Charcoal", "style": 1}), "`style` must be \"pencil\" or \"brush\", not 1"), + ] { + let mut p = extra.clone(); + p["points"] = points.clone(); + let (before, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + let e = s.execute("brush.freehand", &p).expect_err(&format!("{extra} is refused")); + assert!(e.to_string().contains(words), "{extra}: {e}"); + assert!(*s.doc().unwrap().doc == *before, "{extra} leaves the document"); + assert_eq!(s.doc().unwrap().selection.objects, [a], "{extra} leaves the selection"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{extra} records no undo step"); + } + for extra in [json!({}), json!({"brush": null, "style": null})] { + let mut p = extra.clone(); + p["points"] = points.clone(); + let id = NodeId(s.execute("brush.freehand", &p).unwrap()["id"].as_u64().unwrap()); + assert_eq!(brush_of(&s, id), None, "{extra} draws the plain path"); + } + for style in ["pencil", "brush"] { + let r = s.execute("brush.freehand", &json!({"points": points, "style": style, "brush": "Charcoal"})).unwrap(); + assert!(r["id"].is_u64(), "{style}: {r}"); + } +} + +/// The Paintbrush skips a brush deleted after it was chosen: a deleted tool brush gives way to +/// the document's current brush, and with neither the stroke is drawn without a brush. +#[test] +fn paintbrush_tool_skips_a_deleted_brush() { + let mut s = session(); + s.execute("brush.setCurrent", &json!({"name": "Arrow"})).unwrap(); + let v = ViewInfo::default(); + s.select_tool("paintbrush", v).unwrap(); + s.set_tool_option("brush", &json!("Dots")); + s.execute("brush.delete", &json!({"name": "Dots"})).unwrap(); + let stroke = |s: &mut Session, y: f64| { + for (k, x) in [(PointerKind::Down, 10.0), (PointerKind::Drag, 50.0), (PointerKind::Drag, 90.0), (PointerKind::Up, 130.0)] { + s.pointer(&PointerEvent::new(k, x, y), v).unwrap(); + } + s.doc().unwrap().selection.objects[0] + }; + let id = stroke(&mut s, 10.0); + assert_eq!(brush_of(&s, id).as_deref(), Some("Arrow")); + s.execute("brush.delete", &json!({"name": "Arrow"})).unwrap(); + assert_eq!(s.doc().unwrap().doc.unknown.get("currentBrush"), None); + let id = stroke(&mut s, 110.0); + assert_eq!(brush_of(&s, id), None); +} + #[test] fn paintbrush_tool_uses_the_current_brush() { let mut s = session(); diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index 19ac53494c..b1e90324ba 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -1490,6 +1490,93 @@ fn shape_builder_open_filled_paths_cut_without_open_filled_as_closed() { assert!((area(&s, NodeId(r["merged"].as_u64().unwrap())) - 5000.0).abs() < 1e-6); } +/// The fill rows of an open path's appearance (bottom first) for the open-path tests below, with +/// a 1 pt black stroke on top: a painted fill under an unpainted top fill, a painted fill that is +/// hidden, one with an opacity of 0, and a painted fill under a hidden painted top fill. +fn open_path_fill_stacks() -> [(&'static str, Vec, bool); 4] { + use vectorcraft_doc::{FillLayer, StrokeLayer}; + let fill = |p: Paint, visible: bool, opacity: f32| { + let mut f = FillLayer::new(p); + f.visible = visible; + f.opacity = opacity; + AppearanceItem::Fill(f) + }; + let red = || Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + let blue = || Paint::solid(Color::rgb(0.0, 0.0, 1.0)); + let stroke = || AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::BLACK), 1.0)); + [ + ("a painted fill under an unpainted top fill", vec![fill(red(), true, 1.0), fill(Paint::None, true, 1.0), stroke()], true), + ("a hidden painted fill", vec![fill(red(), false, 1.0), stroke()], false), + ("a painted fill with an opacity of 0", vec![fill(red(), true, 0.0), stroke()], false), + ("a painted fill under a hidden painted top fill", vec![fill(red(), true, 1.0), fill(blue(), false, 1.0), stroke()], true), + ] +} + +/// Consider Open Filled Paths as Closed: an open path counts as filled when any of its fill rows +/// draws (shown, painted and above 0% opacity), whichever row is on top. The map, a merge inside +/// the area and what a merge keeps of the path follow the rows that draw; with the option off, none +/// of the paths closes. +#[test] +fn shape_builder_closes_open_paths_by_the_fill_rows_that_draw() { + for (what, items, closes) in open_path_fill_stacks() { + let mut s = session(); + let r = s.execute("path.create", &json!({"anchors": [{"x": 0, "y": 0}, {"x": 100, "y": 0}, {"x": 100, "y": 100}]})).unwrap(); + let p = NodeId(r["id"].as_u64().unwrap()); + s.edit("t", |d, _| { + d.node_mut(p).unwrap().appearance.items = items; + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [p.0]})).unwrap(); + let r = s.execute("shapeBuilder.regions", &json!({})).unwrap(); + assert_eq!( + (r["regions"].as_array().unwrap().len(), r["lines"].as_array().unwrap().len()), + if closes { (1, 0) } else { (0, 1) }, + "{what}: {r}" + ); + let r = s.execute("shapeBuilder.regions", &json!({"openFilledAsClosed": false})).unwrap(); + assert_eq!((r["regions"].as_array().unwrap().len(), r["lines"].as_array().unwrap().len()), (0, 1), "{what}, option off: {r}"); + let n = node(&s, p); + for on in [true, false] { + let inputs = vectorcraft_tools::builder::merge_inputs(&[&n], on); + assert_eq!(inputs.iter().map(|i| i.fill_closes).collect::>(), vec![closes && on], "{what}, option {on}"); + } + let merged = s.execute("shapeBuilder.merge", &json!({"points": [[75, 25]]})); + if closes { + assert!((area(&s, NodeId(merged.unwrap()["merged"].as_u64().unwrap())) - 5000.0).abs() < 1e-6, "{what}"); + } else { + assert!(merged.is_err(), "{what}: the open path encloses no region"); + } + } +} + +/// Clicking Stroke Splits the Path on the middle side of an open U cuts it along the outline its +/// drawn fill closes: with a fill row that draws, what is left runs on from the cut round the +/// implied closing edge (the top side, then the bottom side); without one, what is left is the +/// open path's two ends in path order (the bottom side, then the top side). +#[test] +fn shape_builder_stroke_split_closes_open_paths_by_the_fill_rows_that_draw() { + for (what, items, closes) in open_path_fill_stacks() { + let mut s = session(); + let r = + s.execute("path.create", &json!({"anchors": [{"x": 0, "y": 0}, {"x": 100, "y": 0}, {"x": 100, "y": 100}, {"x": 0, "y": 100}]})).unwrap(); + let p = NodeId(r["id"].as_u64().unwrap()); + s.edit("t", |d, _| { + d.node_mut(p).unwrap().appearance.items = items; + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [p.0]})).unwrap(); + let r = s.execute("shapeBuilder.merge", &json!({"points": [[101, 50]], "splitStroke": true})).unwrap(); + let out = ids(&r); + assert_eq!(shapes_of(&s, &out), vec![(false, 4, 200.0), (false, 2, 100.0)], "{what}"); + let (rest, _) = outline(&node(&s, out[0])); + let starts: Vec<(f64, f64)> = rest.subpaths.iter().map(|sp| (sp.anchors[0].p.x.round(), sp.anchors[0].p.y.round())).collect(); + let order = if closes { vec![(100.0, 100.0), (0.0, 0.0)] } else { vec![(0.0, 0.0), (100.0, 100.0)] }; + assert_eq!(starts, order, "{what}"); + } +} + /// Pick Color From Color Swatches: the merged shape takes the current fill, not the fill of the /// object under the first point; setting the current fill without `ids` leaves the selection's. #[test] @@ -2694,7 +2781,7 @@ fn live_paint_fill_same_paint_is_no_op() { let mut before = snapshot(&s); let click = s.execute("livePaint.fill", &json!({"group": g.0, "point": [75, 50], "color": "#00ff00"})).unwrap(); let face = vectorcraft_tools::builder::face_at(&node(&s, g), Point::new(75.0, 50.0)).unwrap().id; - assert_eq!(click, json!({"group": g.0, "face": face.0}), "the usual reply"); + assert_eq!(click, json!({"group": g.0, "face": face.0, "count": 1}), "the usual reply"); assert_unchanged(&mut s, &mut before, "a click on a face with the paint"); s.execute("livePaint.fill", &drag).unwrap(); assert_unchanged(&mut s, &mut before, "a drag over faces with the paint"); @@ -2763,6 +2850,42 @@ fn live_paint_stroke_edge_same_paint_and_width_is_no_op() { assert_eq!(history_state(&s).0, before.1.0 + 1); } +/// With `scope`, faces and edges that already have the paint (and the width) are skipped: when +/// every face or edge the call reaches has it, nothing changes, and when some do, only the others +/// are painted, in one undo step. `count` is every face or edge reached. +#[test] +fn live_paint_scoped_fill_and_stroke_skip_parts_with_the_paint() { + let mut s = session(); + let g = live(&mut s); + s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 50], "points": [[25, 50], [125, 50]], "color": "#00ff00"})).unwrap(); + let edges = + s.execute("livePaint.strokeEdge", &json!({"group": g.0, "point": [100, 50], "scope": "samePaint", "color": "#ff0000", "width": 3})).unwrap(); + redo_waiting_and_saved(&mut s, g); + let mut before = snapshot(&s); + let same = json!({"group": g.0, "point": [75, 50], "scope": "samePaint", "color": "#00ff00"}); + assert_eq!(s.execute("livePaint.fill", &same).unwrap()["count"], 3); + assert_unchanged(&mut s, &mut before, "a samePaint fill where every face has the paint"); + let again = json!({"group": g.0, "point": [100, 50], "scope": "samePaint", "color": "#ff0000", "width": 3}); + assert_eq!(s.execute("livePaint.strokeEdge", &again).unwrap()["count"], edges["count"]); + assert_unchanged(&mut s, &mut before, "a samePaint stroke where every edge has the paint and the width"); + // One face of the three without the paint: only it is filled, in one undo step. + let green = Paint::solid(Color::from_hex("#00ff00").unwrap()); + let red = Paint::solid(Color::from_hex("#ff0000").unwrap()); + s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 50], "color": "#ff0000"})).unwrap(); + let depth = history_state(&s).0; + let like = serde_json::to_value(&green).unwrap(); + let r = s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 50], "scope": "samePaint", "match": like, "color": "#00ff00"})).unwrap(); + assert_eq!(r["count"], 3); + assert_eq!(history_state(&s).0, depth + 1); + let fill_at = |s: &Session, x: f64| vectorcraft_tools::builder::face_at(&node(s, g), Point::new(x, 50.0)).unwrap().appearance.fill_paint(); + for x in [25.0, 75.0, 125.0] { + assert_eq!(fill_at(&s, x), green, "{x}"); + } + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(fill_at(&s, 25.0), red); + assert_eq!((fill_at(&s, 75.0), fill_at(&s, 125.0)), (green.clone(), green)); +} + #[test] fn live_paint_gap_options_same_values_are_no_op() { let mut s = session(); @@ -2925,6 +3048,472 @@ fn live_paint_fill_skips_hidden_faces() { assert!(!node(&s, hidden).visible); } +/// A Live Paint group of 50 pt squares side by side, 50 pt tall, with their left sides at each of +/// `xs`. +fn live_squares(s: &mut Session, xs: &[f64]) -> NodeId { + let ids: Vec = xs.iter().map(|&x| rect(s, x, 0.0, 50.0, 50.0).0).collect(); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap()) +} + +/// The ids of the faces of `g` that hold `p`, in the order given. +fn faces_at(s: &Session, g: NodeId, ps: &[(f64, f64)]) -> Vec { + ps.iter().map(|&(x, y)| vectorcraft_tools::builder::face_at(&node(s, g), Point::new(x, y)).unwrap().id).collect() +} + +/// The edges of `g` whose bounds lie within `r`. +fn edges_in(s: &Session, g: NodeId, r: Rect) -> Vec { + let r = r.inflate(1e-6, 1e-6); + vectorcraft_tools::builder::edges(&node(s, g)) + .iter() + .filter(|e| e.geometric_bounds().is_some_and(|bb| r.contains(Point::new(bb.x0, bb.y0)) && r.contains(Point::new(bb.x1, bb.y1)))) + .map(|e| e.id) + .collect() +} + +/// Give `ids` stroke paint `paint` at weight 1 (none: no stroke), and `fill` to the faces in `faces`. +fn paint_parts(s: &mut Session, ids: &[NodeId], paint: &Paint, faces: &[(NodeId, Paint)]) { + s.edit("t", |d, _| { + for id in ids { + let n = d.node_mut(*id).unwrap(); + n.appearance.set_stroke(paint.clone()); + if let Some(st) = n.appearance.stroke_mut() { + st.width = 1.0; + } + } + for (id, fill) in faces { + d.node_mut(*id).unwrap().appearance.set_fill(fill.clone()); + } + Ok(()) + }) + .unwrap(); +} + +fn fill_of(s: &Session, id: NodeId) -> Paint { + node(s, id).appearance.fill_paint() +} + +/// A double-click on a face fills it and the faces reached across edges that draw no stroke; a +/// stroked edge and a hidden face stop the flood. +#[test] +fn live_paint_bucket_double_click_floods_across_unstroked_edges() { + let mut s = session(); + let g = live_squares(&mut s, &[0.0, 50.0, 100.0, 150.0]); + let [a, b, c, d] = faces_at(&s, g, &[(25.0, 25.0), (75.0, 25.0), (125.0, 25.0), (175.0, 25.0)])[..] else { panic!("four faces") }; + let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 201.0, 51.0)); + paint_parts(&mut s, &all, &Paint::None, &[]); + let stroked = edges_in(&s, g, Rect::new(150.0, 0.0, 150.0, 50.0)); + assert!(!stroked.is_empty()); + paint_parts(&mut s, &stroked, &Paint::solid(Color::rgb(0.0, 0.0, 0.0)), &[]); + let white = fill_of(&s, d); + let green = Paint::solid(Color::from_hex("#00ff00").unwrap()); + assert_ne!(white, green); + let depth = s.doc().unwrap().history.undo.len(); + let r = s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 25], "color": "#00ff00", "scope": "connected"})).unwrap(); + assert_eq!((&r["face"], &r["count"]), (&json!(a.0), &json!(3))); + assert_eq!([a, b, c, d].map(|f| fill_of(&s, f)), [green.clone(), green.clone(), green.clone(), white.clone()]); + assert_eq!(s.doc().unwrap().history.undo.len(), depth + 1, "one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!([a, b, c].iter().all(|f| fill_of(&s, *f) != green)); + // A hidden face is not filled and does not pass the flood on. + s.execute("object.setProps", &json!({"ids": [b.0], "visible": false})).unwrap(); + let r = s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 25], "color": "#00ff00", "scope": "connected"})).unwrap(); + assert_eq!(r["count"], 1); + assert_eq!([a, b, c].map(|f| fill_of(&s, f) == green), [true, false, false]); + while s.doc().unwrap().history.undo.len() > depth { + s.execute("edit.undo", &json!({})).unwrap(); + } + // The tool: two clicks and the double-click that follows them. + let v = ViewInfo::default(); + s.select_tool("livePaintBucket", v).unwrap(); + s.paint.fill = green.clone(); + for kind in [PointerKind::Down, PointerKind::Up, PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick] { + s.pointer(&PointerEvent::new(kind, 125.0, 25.0), v).unwrap(); + } + assert_eq!([a, b, c, d].map(|f| fill_of(&s, f)), [green.clone(), green.clone(), green, white]); +} + +/// An edge that draws no stroke (fully transparent, or with its stroke hidden) lets a flood across +/// although it stores a stroke paint, and an edge scope compares the stroke paint each edge draws +/// with. +#[test] +fn live_paint_bucket_scopes_follow_the_stroke_an_edge_draws() { + let mut s = session(); + let g = live_squares(&mut s, &[0.0, 50.0, 100.0]); + let black = Paint::solid(Color::rgb(0.0, 0.0, 0.0)); + let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 151.0, 51.0)); + paint_parts(&mut s, &all, &black, &[]); + let clear = edges_in(&s, g, Rect::new(50.0, 0.0, 50.0, 50.0)); + let hidden = edges_in(&s, g, Rect::new(100.0, 0.0, 100.0, 50.0)); + assert!(!clear.is_empty() && !hidden.is_empty()); + s.edit("t", |d, _| { + for id in &clear { + d.node_mut(*id).unwrap().opacity = 0.0; + } + for id in &hidden { + d.node_mut(*id).unwrap().appearance.stroke_mut().unwrap().visible = false; + } + Ok(()) + }) + .unwrap(); + let r = s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 25], "color": "#00ff00", "scope": "connected"})).unwrap(); + assert_eq!(r["count"], 3, "the flood crosses both middle edges"); + s.execute("edit.undo", &json!({})).unwrap(); + let stroke = |s: &mut Session, at: [f64; 2]| { + let r = s.execute("livePaint.strokeEdge", &json!({"group": g.0, "point": at, "color": "#00ff00", "width": 3, "scope": "samePaint"})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + r["count"].clone() + }; + assert_eq!(stroke(&mut s, [25.0, 0.0]), json!(all.len() - clear.len() - hidden.len()), "the edges that draw black"); + assert_eq!(stroke(&mut s, [50.0, 25.0]), json!(clear.len() + hidden.len()), "the edges that draw no stroke"); + // With the top edge between them fully transparent too, the connected scope walks from the edge + // at x = 50 through it to the edge at x = 100, and reaches no edge that draws black. + let top = edges_in(&s, g, Rect::new(50.0, 0.0, 100.0, 0.0)); + assert_eq!(top.len(), 1); + s.edit("t", |d, _| { + d.node_mut(top[0]).unwrap().opacity = 0.0; + Ok(()) + }) + .unwrap(); + let r = + s.execute("livePaint.strokeEdge", &json!({"group": g.0, "point": [50, 25], "color": "#00ff00", "width": 3, "scope": "connected"})).unwrap(); + assert_eq!(r["count"], json!(clear.len() + top.len() + hidden.len())); +} + +/// `livePaint.strokeEdge` paints an edge's topmost stroke that is shown, so the edge then draws +/// with the paint; an edge whose strokes are all hidden takes a new stroke above them. Painting +/// again changes nothing. +#[test] +fn live_paint_stroke_edge_paints_the_shown_stroke() { + let mut s = session(); + let g = live_squares(&mut s, &[0.0, 50.0]); + let black = Paint::solid(Color::rgb(0.0, 0.0, 0.0)); + let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + let green = Paint::solid(Color::from_hex("#00ff00").unwrap()); + let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 101.0, 51.0)); + paint_parts(&mut s, &all, &black, &[]); + let middle = edges_in(&s, g, Rect::new(50.0, 0.0, 50.0, 50.0)); + let left: Vec = edges_in(&s, g, Rect::new(0.0, 0.0, 50.0, 50.0)).into_iter().filter(|e| !middle.contains(e)).collect(); + let (&[m], &[l]) = (&middle[..], &left[..]) else { panic!("one middle edge and one other edge round the left face") }; + // The middle edge draws red under a hidden black stroke; every stroke of the left face's other + // edge is hidden. + s.edit("t", |d, _| { + let n = d.node_mut(m).unwrap(); + n.appearance.items.insert(0, AppearanceItem::Stroke(vectorcraft_doc::appearance::StrokeLayer::new(red.clone(), 1.0))); + n.appearance.stroke_mut().unwrap().visible = false; + d.node_mut(l).unwrap().appearance.stroke_mut().unwrap().visible = false; + Ok(()) + }) + .unwrap(); + let drawn = |s: &Session, id: NodeId| vectorcraft_tools::builder::lp_stroke_paint(&node(s, id)); + assert_eq!(drawn(&s, m), red); + let paint = |s: &mut Session, at: [f64; 2]| { + s.execute("livePaint.strokeEdge", &json!({"group": g.0, "point": at, "color": "#00ff00", "width": 2})).unwrap(); + }; + for (id, at) in [(m, [50.0, 25.0]), (l, [0.0, 25.0])] { + paint(&mut s, at); + assert_eq!(drawn(&s, id), green, "{id}"); + let depth = history_state(&s).0; + paint(&mut s, at); + assert_eq!(history_state(&s).0, depth, "painting {id} again"); + } + assert_eq!(node(&s, m).appearance.items.len(), 2, "the hidden stroke stays as it was"); + assert_eq!(node(&s, l).appearance.items.len(), 2, "a new stroke above the hidden one"); +} + +/// With Cmd held, the Live Paint Bucket's presses go to the selection tool Cmd lends, and the +/// double-click and triple-click that follow them paint nothing. +#[test] +fn live_paint_bucket_cmd_double_and_triple_click_paint_nothing() { + let mut s = session(); + let g = live_squares(&mut s, &[0.0, 50.0, 100.0]); + let faces = faces_at(&s, g, &[(25.0, 25.0), (75.0, 25.0), (125.0, 25.0)]); + let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 151.0, 51.0)); + paint_parts(&mut s, &all, &Paint::None, &[]); + let before: Vec = faces.iter().map(|f| fill_of(&s, *f)).collect(); + let v = ViewInfo::default(); + s.select_tool("livePaintBucket", v).unwrap(); + s.paint.fill = Paint::solid(Color::from_hex("#00ff00").unwrap()); + let cmd = Mods { cmd: true, ..Default::default() }; + let (down, up) = (PointerKind::Down, PointerKind::Up); + for kind in [down, up, down, up, PointerKind::DoubleClick, down, up, PointerKind::TripleClick] { + s.pointer(&PointerEvent::new(kind, 75.0, 25.0).with_mods(cmd), v).unwrap(); + } + assert_eq!(faces.iter().map(|f| fill_of(&s, *f)).collect::>(), before); + assert_eq!(s.tool_id(), "livePaintBucket"); +} + +/// The flood crosses curved edges, and reaches a face 0.012 pt wide. +#[test] +fn live_paint_bucket_double_click_floods_curved_and_narrow_faces() { + let mut s = session(); + let ids: Vec = [0.0, 60.0] + .iter() + .map(|&x| s.execute("shape.ellipse", &json!({"x": x, "y": 0, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap()) + .collect(); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 161.0, 101.0)); + paint_parts(&mut s, &all, &Paint::None, &[]); + let r = s.execute("livePaint.fill", &json!({"group": g.0, "point": [20, 50], "color": "#00ff00", "scope": "connected"})).unwrap(); + assert_eq!(r["count"], 3, "both lunes and the lens between them"); + + let mut s = session(); + let ids = [rect(&mut s, 0.0, 0.0, 50.0, 50.0).0, rect(&mut s, 49.988, 0.0, 50.0, 50.0).0]; + s.execute("select.set", &json!({"ids": ids})).unwrap(); + let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let [a, sliver, c] = faces_at(&s, g, &[(25.0, 25.0), (49.994, 25.0), (75.0, 25.0)])[..] else { panic!("three faces") }; + assert!(a != sliver && sliver != c); + let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 101.0, 51.0)); + paint_parts(&mut s, &all, &Paint::None, &[]); + let green = Paint::solid(Color::from_hex("#00ff00").unwrap()); + let r = s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 25], "color": "#00ff00", "scope": "connected"})).unwrap(); + assert_eq!(r["count"], 3); + assert_eq!([a, sliver, c].map(|f| fill_of(&s, f)), [green.clone(), green.clone(), green]); +} + +/// The flood crosses a hidden edge, and an edge that a Gap Detection gap meets partway along, but +/// not the gap. +#[test] +fn live_paint_bucket_double_click_floods_across_hidden_edges_and_past_gaps() { + let mut s = session(); + let g = live_squares(&mut s, &[0.0, 50.0]); + let black = Paint::solid(Color::rgb(0.0, 0.0, 0.0)); + let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 101.0, 51.0)); + paint_parts(&mut s, &all, &black, &[]); + let fill = |s: &mut Session, g: NodeId, at: [f64; 2]| { + s.execute("livePaint.fill", &json!({"group": g.0, "point": at, "color": "#00ff00", "scope": "connected"})).unwrap()["count"].clone() + }; + assert_eq!(fill(&mut s, g, [25.0, 25.0]), 1, "a stroked edge stops the flood"); + s.execute("edit.undo", &json!({})).unwrap(); + let middle = edges_in(&s, g, Rect::new(50.0, 0.0, 50.0, 50.0)); + s.execute("object.setProps", &json!({"ids": middle.iter().map(|e| e.0).collect::>(), "visible": false})).unwrap(); + assert_eq!(fill(&mut s, g, [25.0, 25.0]), 2, "a hidden edge does not"); + + // Square B (100..200 by 0..100) over square C (100..200 by 100..200), and a line down the middle + // of B that stops 2 pt short of their shared edge: Gap Detection closes it, so B is two faces + // that each run along part of the shared edge, which is one edge segment. + let mut s = session(); + let mut ids = vec![rect(&mut s, 100.0, 0.0, 100.0, 100.0).0, rect(&mut s, 100.0, 100.0, 100.0, 100.0).0]; + let line = s.execute("path.create", &json!({"anchors": [{"x": 150, "y": 0}, {"x": 150, "y": 98}]})).unwrap(); + ids.push(line["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("livePaint.gapOptions", &json!({"id": g.0, "detect": true, "size": "small"})).unwrap(); + let [b1, b2, c] = faces_at(&s, g, &[(125.0, 50.0), (175.0, 50.0), (150.0, 150.0)])[..] else { panic!("three faces") }; + assert!(b1 != b2 && b2 != c && b1 != c); + let all = edges_in(&s, g, Rect::new(99.0, -1.0, 201.0, 201.0)); + paint_parts(&mut s, &all, &black, &[]); + let shared = edges_in(&s, g, Rect::new(100.0, 100.0, 200.0, 100.0)); + assert!(!shared.is_empty()); + paint_parts(&mut s, &shared, &Paint::None, &[]); + assert_eq!(fill(&mut s, g, [150.0, 150.0]), 3, "from C across the shared edge to both faces of B"); + s.execute("edit.undo", &json!({})).unwrap(); + // With the line and the shared edge stroked, only the gap lies between the two faces of B. + paint_parts(&mut s, &shared, &black, &[]); + assert_eq!(fill(&mut s, g, [125.0, 50.0]), 1, "the flood does not pass the gap"); + + // B alone, its outline drawing no stroke and the line stroked: the two faces of B run along + // different parts of the outline's bottom segment, on the same side, and the flood does not + // join them there. + let mut s = session(); + let mut ids = vec![rect(&mut s, 100.0, 0.0, 100.0, 100.0).0]; + let line = s.execute("path.create", &json!({"anchors": [{"x": 150, "y": 0}, {"x": 150, "y": 98}]})).unwrap(); + ids.push(line["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("livePaint.gapOptions", &json!({"id": g.0, "detect": true, "size": "small"})).unwrap(); + assert_eq!(vectorcraft_tools::builder::faces(&node(&s, g)).len(), 2); + let all = edges_in(&s, g, Rect::new(99.0, -1.0, 201.0, 101.0)); + paint_parts(&mut s, &all, &Paint::None, &[]); + let line = edges_in(&s, g, Rect::new(150.0, 0.0, 150.0, 98.0)); + assert!(!line.is_empty() && line.len() < all.len()); + paint_parts(&mut s, &line, &black, &[]); + assert_eq!(fill(&mut s, g, [125.0, 50.0]), 1, "the gap parts the two faces along the bottom"); +} + +/// The flood crosses an edge into each face along it when a face's outline runs along the edge in +/// one segment and the edge is split where another line meets it. +#[test] +fn live_paint_bucket_double_click_floods_along_edges_split_at_a_junction() { + // A square with a line across its middle, and a line from the top at x = 30 that crosses it and + // stops 20 pt below. The bottom face's outline runs along the middle line in one segment, from + // x = 0 to 100; the middle line's edges are split at x = 30. + let mut s = session(); + let mut ids = vec![rect(&mut s, 0.0, 0.0, 100.0, 100.0).0]; + for anchors in [json!([{"x": 0, "y": 50}, {"x": 100, "y": 50}]), json!([{"x": 30, "y": 0}, {"x": 30, "y": 70}])] { + ids.push(s.execute("path.create", &json!({ "anchors": anchors })).unwrap()["id"].as_u64().unwrap()); + } + s.execute("select.set", &json!({"ids": ids})).unwrap(); + let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let [left, right, bottom] = faces_at(&s, g, &[(15.0, 25.0), (65.0, 25.0), (65.0, 75.0)])[..] else { panic!("three faces") }; + assert!(left != right && right != bottom && left != bottom); + let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 101.0, 101.0)); + paint_parts(&mut s, &all, &Paint::None, &[]); + let down = edges_in(&s, g, Rect::new(30.0, 0.0, 30.0, 70.0)); + assert!(!down.is_empty() && down.len() < all.len()); + paint_parts(&mut s, &down, &Paint::solid(Color::rgb(0.0, 0.0, 0.0)), &[]); + let green = Paint::solid(Color::from_hex("#00ff00").unwrap()); + let r = s.execute("livePaint.fill", &json!({"group": g.0, "point": [65, 75], "color": "#00ff00", "scope": "connected"})).unwrap(); + assert_eq!(r["count"], 3, "from the bottom face to both faces above the line"); + assert_eq!([left, right, bottom].map(|f| fill_of(&s, f)), [green.clone(), green.clone(), green.clone()]); + s.execute("edit.undo", &json!({})).unwrap(); + let r = s.execute("livePaint.fill", &json!({"group": g.0, "point": [15, 25], "color": "#00ff00", "scope": "connected"})).unwrap(); + assert_eq!(r["count"], 3, "from the upper left face down to the bottom face and up again"); +} + +/// A triple-click on a face fills every face of the group with that face's fill, joined to it or +/// not. Through the tool, the fill compared is the face's fill before the first click. +#[test] +fn live_paint_bucket_triple_click_fills_every_face_of_the_same_fill() { + let mut s = session(); + let g = live_squares(&mut s, &[0.0, 50.0, 100.0, 150.0]); + let [a, b, c, d] = faces_at(&s, g, &[(25.0, 25.0), (75.0, 25.0), (125.0, 25.0), (175.0, 25.0)])[..] else { panic!("four faces") }; + let (red, blue) = (Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 0.0, 1.0))); + let green = Paint::solid(Color::from_hex("#00ff00").unwrap()); + let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 201.0, 51.0)); + paint_parts(&mut s, &all, &Paint::None, &[(a, red.clone()), (b, blue.clone()), (c, red.clone()), (d, red.clone())]); + let stroked = edges_in(&s, g, Rect::new(100.0, 0.0, 100.0, 50.0)); + paint_parts(&mut s, &stroked, &Paint::solid(Color::rgb(0.0, 0.0, 0.0)), &[]); + let depth = s.doc().unwrap().history.undo.len(); + let r = s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 25], "color": "#00ff00", "scope": "samePaint"})).unwrap(); + assert_eq!(r["count"], 3); + assert_eq!([a, b, c, d].map(|f| fill_of(&s, f)), [green.clone(), blue.clone(), green.clone(), green.clone()]); + s.execute("edit.undo", &json!({})).unwrap(); + // The tool: the first click fills the face, the double-click floods across x = 50 into B, and + // the triple-click fills the faces that were red. + let v = ViewInfo::default(); + s.select_tool("livePaintBucket", v).unwrap(); + s.paint.fill = green.clone(); + for kind in [ + PointerKind::Down, + PointerKind::Up, + PointerKind::Down, + PointerKind::Up, + PointerKind::DoubleClick, + PointerKind::Down, + PointerKind::Up, + PointerKind::TripleClick, + ] { + s.pointer(&PointerEvent::new(kind, 25.0, 25.0), v).unwrap(); + } + assert_eq!([a, b, c, d].map(|f| fill_of(&s, f)), [green.clone(), green.clone(), green.clone(), green.clone()]); + // A match given by the caller is the fill compared. + while s.doc().unwrap().history.undo.len() > depth { + s.execute("edit.undo", &json!({})).unwrap(); + } + assert_eq!([a, b, c, d].map(|f| fill_of(&s, f)), [red.clone(), blue.clone(), red.clone(), red.clone()]); + let r = s + .execute( + "livePaint.fill", + &json!({"group": g.0, "point": [25, 25], "color": "#00ff00", "scope": "samePaint", "match": serde_json::to_value(&blue).unwrap()}), + ) + .unwrap(); + assert_eq!(r["count"], 2); + assert_eq!([a, b, c, d].map(|f| fill_of(&s, f)), [green.clone(), green, red.clone(), red]); +} + +/// A triple-click whose first click makes the Live Paint group from the selected paths matches the +/// fill the face was made with. +#[test] +fn live_paint_bucket_triple_click_after_making_the_group_matches_the_made_fill() { + let mut s = session(); + let ids: Vec = [0.0, 100.0, 200.0].iter().map(|&x| rect(&mut s, x, 0.0, 50.0, 50.0)).collect(); + let (red, blue) = (Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0)); + for (id, c) in ids.iter().zip([red, red, blue]) { + set_fill(&mut s, *id, c); + } + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); + let green = Paint::solid(Color::from_hex("#00ff00").unwrap()); + let v = ViewInfo::default(); + s.select_tool("livePaintBucket", v).unwrap(); + s.paint.fill = green.clone(); + for kind in [ + PointerKind::Down, + PointerKind::Up, + PointerKind::Down, + PointerKind::Up, + PointerKind::DoubleClick, + PointerKind::Down, + PointerKind::Up, + PointerKind::TripleClick, + ] { + s.pointer(&PointerEvent::new(kind, 25.0, 25.0), v).unwrap(); + } + let g = vectorcraft_tools::builder::live_paint_at(&s.doc().unwrap().doc, Point::new(25.0, 25.0)).expect("the clicks made a group"); + let faces = faces_at(&s, g, &[(25.0, 25.0), (125.0, 25.0), (225.0, 25.0)]); + assert_eq!(faces.iter().map(|f| fill_of(&s, *f)).collect::>(), [green.clone(), green, Paint::solid(blue)]); +} + +/// A double-click on an edge paints the edges joined to it that have its stroke, and a +/// triple-click every edge of the group with that stroke; an edge with another stroke is left. +#[test] +fn live_paint_bucket_double_and_triple_click_paint_joined_and_same_stroke_edges() { + let mut s = session(); + let g = live_squares(&mut s, &[0.0, 50.0, 200.0]); + let black = Paint::solid(Color::rgb(0.0, 0.0, 0.0)); + let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + let green = Paint::solid(Color::from_hex("#00ff00").unwrap()); + let joined = edges_in(&s, g, Rect::new(0.0, 0.0, 100.0, 50.0)); + let apart = edges_in(&s, g, Rect::new(200.0, 0.0, 250.0, 50.0)); + let middle = edges_in(&s, g, Rect::new(50.0, 0.0, 50.0, 50.0)); + assert!(!apart.is_empty() && !middle.is_empty()); + paint_parts(&mut s, &joined, &black, &[]); + paint_parts(&mut s, &apart, &black, &[]); + paint_parts(&mut s, &middle, &red, &[]); + let stroke = |s: &Session, ids: &[NodeId]| ids.iter().map(|id| node(s, *id).appearance.stroke_paint()).collect::>(); + let outer: Vec = joined.iter().copied().filter(|e| !middle.contains(e)).collect(); + let r = + s.execute("livePaint.strokeEdge", &json!({"group": g.0, "point": [25, 0], "color": "#00ff00", "width": 3, "scope": "connected"})).unwrap(); + assert_eq!(r["count"], outer.len()); + assert!(stroke(&s, &outer).iter().all(|p| *p == green)); + assert!(outer.iter().all(|e| node(&s, *e).appearance.stroke_width() == 3.0)); + assert!(stroke(&s, &middle).iter().all(|p| *p == red), "another stroke is left"); + assert!(stroke(&s, &apart).iter().all(|p| *p == black), "edges not joined are left"); + s.execute("edit.undo", &json!({})).unwrap(); + let r = s.execute("livePaint.strokeEdge", &json!({"group": g.0, "point": [25, 0], "color": "#00ff00", "scope": "samePaint"})).unwrap(); + assert_eq!(r["count"], outer.len() + apart.len()); + assert!(stroke(&s, &outer).iter().chain(&stroke(&s, &apart)).all(|p| *p == green)); + assert!(stroke(&s, &middle).iter().all(|p| *p == red)); + // A hidden edge is not painted. + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("object.setProps", &json!({"ids": [apart[0].0], "visible": false})).unwrap(); + let r = s.execute("livePaint.strokeEdge", &json!({"group": g.0, "point": [25, 0], "color": "#00ff00", "scope": "samePaint"})).unwrap(); + assert_eq!(r["count"], outer.len() + apart.len() - 1); + assert_eq!(node(&s, apart[0]).appearance.stroke_paint(), black); +} + +/// A `scope` that is not one of the three, a `match` that is not a paint or is given with a scope +/// that compares none, and a scope with a drag's points are refused; nothing changes. +#[test] +fn live_paint_scope_and_match_are_checked() { + let mut s = session(); + let g = live(&mut s); + let none = serde_json::to_value(Paint::None).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let depth = s.doc().unwrap().history.undo.len(); + for (cmd, p) in [ + ("livePaint.fill", json!({"group": g.0, "point": [75, 50], "scope": "all"})), + ("livePaint.fill", json!({"group": g.0, "point": [75, 50], "scope": 2})), + ("livePaint.fill", json!({"group": g.0, "point": [75, 50], "match": none})), + ("livePaint.fill", json!({"group": g.0, "point": [75, 50], "scope": "connected", "match": none})), + ("livePaint.fill", json!({"group": g.0, "point": [75, 50], "scope": "samePaint", "match": "red"})), + ("livePaint.fill", json!({"group": g.0, "point": [75, 50], "scope": "connected", "points": [[75, 50], [125, 50]]})), + ("livePaint.strokeEdge", json!({"group": g.0, "point": [100, 50], "scope": "Connected"})), + ("livePaint.strokeEdge", json!({"group": g.0, "point": [100, 50], "scope": "one", "match": none})), + ("livePaint.strokeEdge", json!({"group": g.0, "point": [100, 50], "scope": "samePaint", "match": {"type": "plaid"}})), + ] { + assert!(s.execute(cmd, &p).is_err(), "{cmd} {p}"); + } + assert_eq!(s.doc().unwrap().doc, before); + assert_eq!(s.doc().unwrap().history.undo.len(), depth); + // "one" and null are a click's scope. + for scope in [json!("one"), Value::Null] { + let r = s.execute("livePaint.fill", &json!({"group": g.0, "point": [75, 50], "scope": scope})).unwrap(); + assert_eq!(r["count"], 1); + } +} + #[test] fn live_paint_release_and_expand() { let mut s = session(); @@ -3018,6 +3607,76 @@ fn live_paint_expand_keeps_the_faces_and_edges_that_draw() { assert_eq!(rows(&n, lower_stroke), rows(&before, lower_stroke)); } +/// `livePaint.info` lists every fill and stroke row of each face and edge, bottom first, and says +/// which rows draw by Expand's rule, while `fill`, `stroke` and `width` stay the top rows. +#[test] +fn live_paint_info_lists_every_appearance_row() { + use vectorcraft_doc::{FillLayer, StrokeLayer}; + let fill = |p: Paint| AppearanceItem::Fill(FillLayer::new(p)); + let stroke = |p: Paint, w: f64| AppearanceItem::Stroke(StrokeLayer::new(p, w)); + let red = || Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + let blue = || Paint::solid(Color::rgb(0.0, 0.0, 1.0)); + let green = || Paint::solid(Color::rgb(0.0, 1.0, 0.0)); + let hidden = |mut i: AppearanceItem| { + match &mut i { + AppearanceItem::Fill(f) => f.visible = false, + AppearanceItem::Stroke(st) => st.visible = false, + } + i + }; + let faded = |mut i: AppearanceItem, o: f32| { + match &mut i { + AppearanceItem::Fill(f) => f.opacity = o, + AppearanceItem::Stroke(st) => st.opacity = o, + } + i + }; + let mut s = session(); + let g = live(&mut s); + // A drawn lower fill and a half-opaque stroke under an unpainted top fill. + let lower = set_live_part(&mut s, g, Some((25.0, 50.0)), None, vec![fill(red()), faded(stroke(blue(), 2.0), 0.5), fill(Paint::None)], 1.0); + let quiet = set_live_part(&mut s, g, Some((125.0, 50.0)), None, vec![hidden(fill(red())), faded(fill(red()), 0.0)], 1.0); + let bare = set_live_part(&mut s, g, Some((75.0, 50.0)), None, vec![], 1.0); + // Two strokes with a fill between them. + let two = set_live_part(&mut s, g, None, Some((0.0, 50.0)), vec![stroke(red(), 4.0), fill(green()), stroke(blue(), 2.0)], 1.0); + let thin = set_live_part(&mut s, g, None, Some((100.0, 50.0)), vec![stroke(red(), 0.0)], 1.0); + let clear_edge = set_live_part(&mut s, g, None, Some((75.0, 0.0)), vec![stroke(red(), 2.0)], 0.0); + let hidden_edge = set_live_part(&mut s, g, None, Some((150.0, 50.0)), vec![stroke(red(), 2.0)], 1.0); + s.edit("t", |d, _| { + d.node_mut(hidden_edge).unwrap().visible = false; + Ok(()) + }) + .unwrap(); + let parts = [lower, quiet, bare, two, thin, clear_edge, hidden_edge]; + assert_eq!(parts.iter().collect::>().len(), parts.len()); + + let info = s.execute("livePaint.info", &json!({"group": g.0})).unwrap(); + let part = |key: &str, id: NodeId| info[key].as_array().unwrap().iter().find(|p| p["id"] == id.0).unwrap().clone(); + let fill_row = |i: usize, p: Paint, o: f64, v: bool, drawn: bool| json!({"index": i, "kind": "fill", "paint": p.label(), "opacity": o, "visible": v, "drawn": drawn}); + let stroke_row = |i: usize, p: Paint, o: f64, v: bool, w: f64, drawn: bool| json!({"index": i, "kind": "stroke", "paint": p.label(), "opacity": o, "visible": v, "width": w, "drawn": drawn}); + + let f = part("faces", lower); + assert_eq!(f["fill"], json!(Paint::None.label()), "fill stays the top fill"); + assert!(f["bounds"].is_array()); + assert_eq!( + f["appearance"], + json!([fill_row(0, red(), 1.0, true, true), stroke_row(1, blue(), 0.5, true, 2.0, true), fill_row(2, Paint::None, 1.0, true, false)]) + ); + assert_eq!(part("faces", quiet)["appearance"], json!([fill_row(0, red(), 1.0, false, false), fill_row(1, red(), 0.0, true, false)])); + assert_eq!(part("faces", bare)["appearance"], json!([])); + + let e = part("edges", two); + assert_eq!((e["stroke"].clone(), e["width"].clone()), (json!(blue().label()), json!(2.0)), "stroke and width stay the top stroke's"); + assert_eq!( + e["appearance"], + json!([stroke_row(0, red(), 1.0, true, 4.0, true), fill_row(1, green(), 1.0, true, true), stroke_row(2, blue(), 1.0, true, 2.0, true)]) + ); + assert_eq!(part("edges", thin)["appearance"], json!([stroke_row(0, red(), 1.0, true, 0.0, false)])); + for id in [clear_edge, hidden_edge] { + assert_eq!(part("edges", id)["appearance"], json!([stroke_row(0, red(), 1.0, true, 2.0, false)]), "a part that is not shown draws no row"); + } +} + /// Merge carries a face's whole appearance when one of its rows draws, and carries nothing from a /// face that draws nothing. #[test] @@ -3878,6 +4537,37 @@ fn live_paint_bucket_alt_shift_gradient_samples_active_stroke_only() { assert!(matches!(node(&s, src).appearance.fill_paint(), Paint::Gradient(_))); } +#[test] +fn live_paint_selection_double_click_selects_the_faces_no_stroked_edge_parts() { + let mut s = session(); + let g = live(&mut s); + // The edge between the middle and right faces draws no stroke. + s.execute("livePaint.strokeEdge", &json!({"group": g.0, "point": [100.0, 50.0], "none": true})).unwrap(); + let v = ViewInfo::default(); + s.select_tool("livePaintSelection", v).unwrap(); + let gn = node(&s, g); + let face = |x: f64| vectorcraft_tools::builder::face_at(&gn, Point::new(x, 50.0)).unwrap().id; + let before = s.doc().unwrap().doc.clone(); + let double_click = |s: &mut Session, x: f64, m: Mods| { + for kind in [PointerKind::Down, PointerKind::Up, PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick] { + s.pointer(&PointerEvent::new(kind, x, 50.0).with_mods(m), v).unwrap(); + } + let mut ids = s.doc().unwrap().selection.objects.clone(); + ids.sort(); + ids + }; + let sorted = |mut ids: Vec| { + ids.sort(); + ids + }; + assert_eq!(double_click(&mut s, 125.0, Mods::default()), sorted(vec![face(75.0), face(125.0)])); + // The stroked edge at x = 50 parts the left face from the others. + assert_eq!(double_click(&mut s, 25.0, Mods::default()), vec![face(25.0)]); + // Shift-double-click adds the faces reached to the selection. + assert_eq!(double_click(&mut s, 75.0, Mods { shift: true, ..Default::default() }), sorted(vec![face(25.0), face(75.0), face(125.0)])); + assert_eq!(s.doc().unwrap().doc, before, "selecting changes no paint"); +} + #[test] fn live_paint_selection_marquee_selects_what_it_touches() { let mut s = session(); @@ -4004,6 +4694,58 @@ fn shape_builder_uses_the_filled_faces_of_a_live_paint_group() { assert!((stroked_length(&s, &out) - 600.0).abs() < 1.0, "{}", stroked_length(&s, &out)); } +/// The Shape Builder takes a Live Paint face or edge when any of its fill or stroke rows draws, +/// whichever row is on top: a painted lower row under an unpainted top row counts, and a part +/// whose only painted row is hidden, transparent or (for an edge) 0 pt wide, or whose own opacity +/// is 0, does not. +#[test] +fn shape_builder_takes_the_live_paint_faces_and_edges_that_draw() { + use vectorcraft_doc::{FillLayer, StrokeLayer}; + let fill = |p: Paint| AppearanceItem::Fill(FillLayer::new(p)); + let stroke = |p: Paint, w: f64| AppearanceItem::Stroke(StrokeLayer::new(p, w)); + let red = || Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + let hidden = |mut i: AppearanceItem| { + match &mut i { + AppearanceItem::Fill(f) => f.visible = false, + AppearanceItem::Stroke(st) => st.visible = false, + } + i + }; + let clear = |mut i: AppearanceItem| { + match &mut i { + AppearanceItem::Fill(f) => f.opacity = 0.0, + AppearanceItem::Stroke(st) => st.opacity = 0.0, + } + i + }; + let mut s = session(); + let g = live(&mut s); + let lower_fill = set_live_part(&mut s, g, Some((25.0, 50.0)), None, vec![fill(red()), fill(Paint::None)], 1.0); + let hidden_fill = set_live_part(&mut s, g, Some((125.0, 50.0)), None, vec![hidden(fill(red()))], 1.0); + let clear_fill = set_live_part(&mut s, g, Some((75.0, 50.0)), None, vec![clear(fill(red()))], 1.0); + let lower_stroke = set_live_part(&mut s, g, None, Some((0.0, 50.0)), vec![stroke(red(), 2.0), stroke(Paint::None, 1.0)], 1.0); + let hidden_stroke = set_live_part(&mut s, g, None, Some((150.0, 50.0)), vec![hidden(stroke(red(), 2.0))], 1.0); + let thin_stroke = set_live_part(&mut s, g, None, Some((100.0, 50.0)), vec![stroke(red(), 0.0)], 1.0); + let clear_stroke = set_live_part(&mut s, g, None, Some((50.0, 50.0)), vec![clear(stroke(red(), 2.0))], 1.0); + let clear_edge = set_live_part(&mut s, g, None, Some((75.0, 0.0)), vec![stroke(red(), 2.0)], 0.0); + let parts = [lower_fill, hidden_fill, clear_fill, lower_stroke, hidden_stroke, thin_stroke, clear_stroke, clear_edge]; + assert_eq!(parts.iter().collect::>().len(), parts.len()); + let d = s.doc().unwrap(); + let (_, leaves) = vectorcraft_tools::builder::shape_builder_shapes(&d.doc, &[g], true); + let taken: Vec = leaves.iter().map(|l| l.id).collect(); + assert!(taken.contains(&lower_fill) && taken.contains(&lower_stroke), "a painted lower row draws: {taken:?}"); + for id in [hidden_fill, clear_fill, hidden_stroke, thin_stroke, clear_stroke, clear_edge] { + assert!(!taken.contains(&id), "{id:?} draws nothing: {taken:?}"); + } + // A face with a painted fill whose own opacity is 0 is left out too. + let mut s = session(); + let g = live(&mut s); + let clear_face = set_live_part(&mut s, g, Some((75.0, 50.0)), None, vec![fill(red())], 0.0); + let d = s.doc().unwrap(); + let (_, leaves) = vectorcraft_tools::builder::shape_builder_shapes(&d.doc, &[g], true); + assert!(!leaves.iter().any(|l| l.id == clear_face), "a face with an opacity of 0 draws nothing"); +} + /// An edge that closes on itself is a line around its face, not a second shape over it. #[test] fn shape_builder_takes_a_closed_live_paint_edge_as_a_line() { @@ -4415,6 +5157,41 @@ fn a_trace_run_hands_its_trace_to_the_command() { assert!((bb.center().x - 160.0).abs() < 1.5, "traced where the image is now: {bb:?}"); } +/// A trace made in one document applies only there: in another document with the same image, +/// object and settings, the run no longer applies, and both trace commands drop the trace handed +/// in and trace that document's own image, as one undo step. +#[test] +fn a_trace_run_applies_only_in_its_own_document() { + let p = json!({"params": {"ignoreWhite": true}}); + for command in ["imageTrace.make", "imageTrace.makeAndExpand"] { + let mut direct = session(); + image_doc(&mut direct); + let want = direct.execute(command, &p).unwrap(); + let mut s = session(); + let img = image_doc(&mut s); + let a = s.active_index().unwrap(); + let copy = (*s.doc().unwrap().doc).clone(); + let run = cmd::TraceRun::prepare(&s, command, &p).unwrap(); + let traced = run.run(&|_, _| true).unwrap(); + let b = s.add_document(copy, None); + assert_ne!(s.documents()[a].uid, s.documents()[b].uid); + assert!(!run.current(&s), "{command}: another document"); + assert!(s.set_active(a)); + assert!(run.current(&s), "{command}: its own document"); + assert!(s.set_active(b)); + traced.hand_in(&mut s); + let got = s.execute(run.command(), run.params()).unwrap(); + assert!(s.trace_hand_off.is_none(), "{command}: dropped"); + assert_eq!(got, want, "{command}"); + let g = NodeId(got["id"].as_u64().unwrap()); + assert_eq!(node(&s, g), node(&direct, g), "{command}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(matches!(node(&s, img).kind, NodeKind::Image(_)), "{command}: one undo step"); + assert!(s.set_active(a)); + assert!(matches!(node(&s, img).kind, NodeKind::Image(_)), "{command}: the first document is untouched"); + } +} + /// A plug-in run that calls Image Trace and then fails leaves a trace handed in for the command in /// place, as it leaves the document. #[test] diff --git a/crates/engine/src/tests/clip.rs b/crates/engine/src/tests/clip.rs index cbba2f36cc..87af67d95d 100644 --- a/crates/engine/src/tests/clip.rs +++ b/crates/engine/src/tests/clip.rs @@ -119,12 +119,80 @@ fn text_on_top_clips_by_its_glyphs() { assert_eq!(hit(&s, (b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0), Some(art)); assert!(b.x1 < 95.0, "{b:?}"); assert_eq!(hit(&s, b.x1 + 3.0, (b.y0 + b.y1) / 2.0), None, "beside the text"); + // An effect that does not reshape it, such as a drop shadow, leaves clicks on its frame. + s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "params": {}, "ids": [t.0], "item": null})).unwrap(); + assert_eq!(hit(&s, (b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0), Some(art), "in the counter, with a drop shadow"); // Release gives the text back. select(&mut s, &[g]); s.execute("object.clippingMask.release", &json!({})).unwrap(); assert!(matches!(s.doc().unwrap().doc.node(t).unwrap().kind, NodeKind::Text(_))); } +#[test] +fn a_hidden_member_of_a_clipping_group_leaves_clicks_on_the_type_frame() { + // The clipping path is a group of an "O" and a hidden rectangle with a Transform effect. The + // hidden rectangle does not clip, so clicks inside the clip group still count the type by its + // frame, the counter of the "O" included. + let mut s = session(); + let art = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 100})).unwrap()); + let t = id_of(&s.execute("text.create", &json!({"x": 5, "y": 80, "text": "O", "size": 90})).unwrap()); + let b = s.doc().unwrap().doc.node(t).unwrap().geometric_bounds().unwrap(); + let r = id_of(&s.execute("shape.rectangle", &json!({"x": 40, "y": 40, "width": 10, "height": 10})).unwrap()); + s.execute("effect.apply", &json!({"effect": "distort.transform", "params": {"moveH": 20}, "ids": [r.0], "item": null})).unwrap(); + select(&mut s, &[art, t]); + let g = id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap()); + // Make Clipping Mask takes no group on top, so the group goes in place of the type. + let mut d = (*s.doc().unwrap().doc).clone(); + let mut rect = (*d.remove(r).unwrap()).clone(); + rect.visible = false; + let text = d.remove(t).unwrap(); + let group = vectorcraft_doc::Node::group(d.alloc_id(), vec![text, Arc::new(rect)]); + d.insert(Some(g), 0, group).unwrap(); + let leaf = |x: f64, y: f64| vectorcraft_doc::hit::hit_test(&d, vectorcraft_geom::Point::new(x, y), Default::default()).map(|h| h.leaf); + let middle = ((b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0); + assert_eq!(leaf(middle.0, middle.1), Some(art), "in the counter, inside the frame"); + assert_eq!(leaf(b.x1 + 3.0, middle.1), None, "beside the text"); +} + +#[test] +fn clicks_follow_the_region_a_clipping_paths_effects_give_it() { + // Art from 10 to 90 pt, clipped by the artboard's left half, which a Transform effect moves + // 50 pt right: the art shows on the right half, as clicks find it. + let mut s = session(); + let art = id_of(&s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 80, "height": 80})).unwrap()); + let clip = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 100})).unwrap()); + select(&mut s, &[art, clip]); + let g = id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap()); + s.execute("effect.apply", &json!({"effect": "distort.transform", "params": {"moveH": 50}, "ids": [clip.0], "item": null})).unwrap(); + let r = render(&s); + assert!(opaque(&r, 75, 50) && !opaque(&r, 25, 50), "the canvas clips by the moved region"); + assert_eq!(hit(&s, 75.0, 50.0), Some(art), "where the effect moved the clipping path"); + assert_eq!(hit(&s, 25.0, 50.0), None, "the clipping path's own place"); + let d = &s.doc().unwrap().doc; + let at = |x: f64| vectorcraft_doc::hit::objects_at(d, vectorcraft_geom::Point::new(x, 50.0), Default::default(), None); + assert_eq!(at(75.0), [g]); + assert!(at(25.0).is_empty()); + // A marquee across the art's edge reaches it within the moved region only. + let marquee = |x0: f64, x1: f64| vectorcraft_doc::hit::marquee(d, vectorcraft_geom::Rect::new(x0, 40.0, x1, 60.0), None, true); + assert_eq!(marquee(85.0, 95.0), [art], "the right edge, in the moved region"); + assert!(marquee(5.0, 15.0).is_empty(), "the left edge, in the clipping path's own place"); + + // The same with a sublayer that clips by its first object. + let mut d = (**d).clone(); + let members: Vec<_> = d.node(g).unwrap().children().unwrap().to_vec(); + let top = d.layers[0].id; + d.remove(g).unwrap(); + let mut sublayer = (*d.layers[0]).clone(); + sublayer.id = d.alloc_id(); + if let NodeKind::Layer { children, clip, .. } = &mut sublayer.kind { + (*children, *clip) = (members, true); + } + d.insert(Some(top), 0, sublayer).unwrap(); + let leaf = |x: f64| vectorcraft_doc::hit::hit_test(&d, vectorcraft_geom::Point::new(x, 50.0), Default::default()).map(|h| h.leaf); + assert_eq!(leaf(75.0), Some(art)); + assert_eq!(leaf(25.0), None); +} + #[test] fn make_refuses_a_top_object_that_cannot_clip() { let mut s = session(); diff --git a/crates/engine/src/tests/clipboard.rs b/crates/engine/src/tests/clipboard.rs index 6cbfd909a9..be79004be2 100644 --- a/crates/engine/src/tests/clipboard.rs +++ b/crates/engine/src/tests/clipboard.rs @@ -1034,14 +1034,39 @@ fn in_place_pastes_put_a_copy_on_each_artboard_named() { // `artboard` wins over `artboards`. let ids = ids_of(&s.execute(cmd, &json!({"artboard": 2, "artboards": [0, 3]})).unwrap()); assert_eq!(doc(&s).bounds_of(&ids, false).unwrap().origin(), Point::new(boards[2].x0 + 10.0, boards[2].y0 + 5.0), "{cmd}"); - // A list that is empty, names an artboard the document lacks or names one twice, or isn't a - // list: an error, and nothing pasted. - let before = doc(&s).clone(); - for bad in [json!([]), json!([0, 4]), json!([1, 1]), json!([0, -1]), json!(2), json!("0,1")] { - assert!(s.execute(cmd, &json!({"artboards": bad})).is_err(), "{cmd} with artboards {bad}"); + // A list that is empty, names an artboard the document lacks or names one twice, holds a + // value that is not a whole number, or isn't a list, and an `artboard` that is not a whole + // number or not an artboard: an error naming the fault, and nothing pasted. Both keys are + // checked when both are given. + let (before, undo) = (doc(&s).clone(), s.doc().unwrap().history.undo.len()); + let (not_list, missing, not_whole) = ( + "`artboards` must be a list of artboard indices", + "`artboards` names an artboard the document does not have", + "`artboards` must contain whole numbers", + ); + let cases = [ + (json!({"artboards": []}), not_list), + (json!({"artboards": 2}), not_list), + (json!({"artboards": "0,1"}), not_list), + (json!({"artboards": [0, 4]}), missing), + (json!({"artboards": [1, 1]}), "`artboards` names an artboard twice"), + (json!({"artboards": [0, -1]}), not_whole), + (json!({"artboards": [0, 1.5]}), not_whole), + (json!({"artboards": [4, "1"]}), not_whole), + (json!({"artboard": 1, "artboards": [7]}), missing), + (json!({"artboard": 1, "artboards": ["1"]}), not_whole), + (json!({"artboard": 4}), "`artboard` must be the index of an artboard of the document"), + (json!({"artboard": -1}), "`artboard` must be a whole number"), + (json!({"artboard": 1.5}), "`artboard` must be a whole number"), + (json!({"artboard": "1"}), "`artboard` must be a whole number"), + (json!({"artboard": null}), "`artboard` must be a whole number"), + (json!({"artboard": "1", "artboards": [9]}), "`artboard` must be a whole number"), + ]; + for (p, want) in cases { + let e = s.execute(cmd, &p).unwrap_err().to_string(); + assert_eq!(e, format!("invalid parameters for `{cmd}`: {want}"), "{cmd} {p}"); } - assert!(s.execute(cmd, &json!({"artboard": 1, "artboards": [7]})).is_err(), "{cmd}: a bad list with `artboard`"); - assert_eq!(doc(&s), &before, "{cmd}"); + assert_eq!((doc(&s), s.doc().unwrap().history.undo.len()), (&before, undo), "{cmd}"); } } diff --git a/crates/engine/src/tests/colormgmt.rs b/crates/engine/src/tests/colormgmt.rs index 493f569805..2d024f552b 100644 --- a/crates/engine/src/tests/colormgmt.rs +++ b/crates/engine/src/tests/colormgmt.rs @@ -16,7 +16,10 @@ use crate::*; /// Every test here reads or changes the process-wide proof view or colour settings: one at a time. /// Tests that switch the Color Settings away from the defaults live in `tests/color_settings.rs` /// (their own process): every colour shown or rendered goes through them, so no lock could cover -/// all the tests that would see the change. +/// all the tests that would see the change. A unit test that assigns its front document a profile +/// other than the working space changes the active settings the same way until another document +/// comes to the front: it starts with `crate::tests::in_own_process`, which runs it again in a +/// child process. pub(crate) static GLOBAL: Mutex<()> = Mutex::new(()); fn session() -> Session { @@ -184,6 +187,26 @@ fn rgb_cmyk_converts_each_gradient_stop() { } } +/// Each point of a freeform gradient converts on its own, as gradient stops do. +#[test] +fn rgb_cmyk_converts_each_freeform_point() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let mut s = session(); + let id = rect(&mut s, 10.0, 10.0, 50.0, 50.0, json!("#000000")); + let stops = json!([{"offset": 0, "color": Color::rgb(0.912_345, 0.1, 0.2)}, {"offset": 1, "color": Color::rgb(0.3, 0.4, 0.654_321)}]); + let points = json!([{"at": [20, 20], "color": Color::rgb(0.2, 0.876_543, 0.3)}, {"at": [50, 50], "color": Color::rgb(0.6, 0.111_111, 0.9)}]); + let gradient = json!({"kind": "freeform", "stops": stops, "freeform": {"points": points}}); + s.execute("paint.setFill", &json!({"ids": [id.0], "gradient": gradient})).unwrap(); + let points = |s: &Session| match fill_of(s, id) { + Paint::Gradient(g) => g.freeform.map(|f| f.points.iter().map(|p| p.color).collect::>()).unwrap_or_default(), + p => panic!("not a gradient: {p:?}"), + }; + let old = points(&s); + assert!(!old.is_empty(), "the freeform fill has points"); + s.execute("object.convertDocumentColorMode", &json!({"mode": "cmyk"})).unwrap(); + assert_eq!(points(&s), old.into_iter().map(to_cmyk).collect::>()); +} + /// A pattern's tile art converts, and the art filled with the pattern keeps it. #[test] fn rgb_cmyk_converts_a_pattern_tile() { diff --git a/crates/engine/src/tests/distort.rs b/crates/engine/src/tests/distort.rs index d033fadee6..6f56a09b68 100644 --- a/crates/engine/src/tests/distort.rs +++ b/crates/engine/src/tests/distort.rs @@ -1,6 +1,6 @@ //! Width points, Liquify, Puppet Warp and Perspective Grid commands and tools. -use serde_json::json; +use serde_json::{Value, json}; use vectorcraft_geom::{PathData, Point, Rect, Shape}; use vectorcraft_tools::distort::perspective::{PerspectiveGrid, Plane}; use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey}; @@ -625,6 +625,25 @@ fn attach_projects_onto_the_plane_and_releases() { assert_eq!(path(&s, a).bounds().unwrap(), Rect::new(450.0, 300.0, 550.0, 400.0)); } +#[test] +fn a_repeated_id_attaches_moves_and_transforms_an_object_once() { + let edited = |cmd: &str, ids: &[u64], extra: Value| { + let mut s = session(); + s.execute("perspective.grid.preset", &json!({"kind": 2})).unwrap(); + let a = rect(&mut s, 450.0, 300.0, 100.0, 100.0); + let ids: Vec = ids.iter().map(|_| a.0).collect(); + let mut p = json!({"ids": ids, "plane": "right"}); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + s.execute(cmd, &p).unwrap(); + path(&s, a) + }; + let moved = json!({"from": [480.0, 330.0], "to": [500.0, 350.0], "constrain": true}); + let scaled = json!({"matrix": [1.5, 0.0, 0.0, 1.5, 10.0, 0.0]}); + for (cmd, extra) in [("perspective.attach", json!({})), ("perspective.move", moved), ("perspective.transform", scaled)] { + assert_eq!(edited(cmd, &[0, 0], extra.clone()), edited(cmd, &[0], extra), "{cmd}"); + } +} + #[test] fn rectangle_tool_draws_in_perspective_on_the_active_plane() { let mut s = session(); diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 8936f8bc6f..e5e6174af0 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -1651,6 +1651,97 @@ fn smoothing_a_whole_closed_path_smooths_a_bump_at_its_start() { assert!(start <= far + 0.5, "the bump at the start stays {start} pt high, the far one {far} pt"); } +/// Checks that the closed path `p` starts at its point nearest `old`, within `reach` of it: its first +/// anchor is no farther from `old` than any other point along the path, and its outline starts there. +fn assert_starts_nearest(p: &PathData, old: Point, reach: f64) { + let sp = &p.subpaths[0]; + assert!(sp.closed, "the path stays closed"); + let first = sp.anchors[0].p; + let nearest = smooth_test_samples(p).iter().map(|q| q.distance(old)).fold(f64::INFINITY, f64::min); + let d = first.distance(old); + assert!(d <= nearest + 1e-6 && d <= reach, "the path starts {d} pt from its old start, its nearest point is {nearest} pt away: {sp:?}"); + let mut bp = kurbo::BezPath::new(); + sp.to_bezpath_into(&mut bp); + assert_eq!(bp.elements().first(), Some(&kurbo::PathEl::MoveTo(first))); +} + +/// A drag over a closed path's first anchor and the anchors either side of it smooths the bump there, +/// and the path starts at the point of the smoothed path nearest the old first anchor. The anchors out +/// of reach keep their places, and undo brings the path back. +#[test] +fn smoothing_over_a_closed_paths_first_anchor_keeps_its_start() { + let mut s = session(); + let (c, r) = (Point::new(300.0, 300.0), 100.0); + let at = |deg: f64, rr: f64| c + rr * kurbo::Vec2::from_angle(deg.to_radians()); + let anchors: Vec<_> = (0..12) + .map(|i| { + let q = at(30.0 * f64::from(i), if i == 0 { r + 8.0 } else { r }); + json!({"x": q.x, "y": q.y}) + }) + .collect(); + let id = smooth_test_path(&mut s, &anchors, true); + let before = path(&s, id); + let old = before.subpaths[0].anchors[0].p; + // Along the circle from -40° to 40°, over anchors 11, 0 and 1. + let drag: Vec = (-20..=20).map(|k| at(2.0 * f64::from(k), r)).collect(); + smooth_pass(&mut s, &drag); + let after = path(&s, id); + assert_ne!(after, before, "the bump is smoothed"); + assert_starts_nearest(&after, old, 12.0); + let kept = &after.subpaths[0].anchors; + for a in &before.subpaths[0].anchors[2..=10] { + assert!(kept.iter().any(|k| k.p == a.p), "{:?} is out of reach and stays: {kept:?}", a.p); + } + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(path(&s, id), before); +} + +/// A drag over the whole of a closed path with a spike that turns back on itself, which the refit +/// keeps as a corner, leaves the path starting at its point nearest the old first anchor. +#[test] +fn smoothing_a_whole_closed_path_with_a_spike_keeps_its_start() { + let mut s = session(); + let mut seed = 5u64; + let (c, r) = (Point::new(300.0, 300.0), 80.0); + let at = |a: f64, rr: f64| c + rr * kurbo::Vec2::from_angle(a); + use std::f64::consts::{PI, TAU}; + let mut pts: Vec = (0..64).map(|i| at(f64::from(i) / 64.0 * TAU, r + 2.5 * smooth_noise(&mut seed))).collect(); + // Out from the anchor at 180° to a tip 40 pt beyond the circle and back. + pts.splice(33..33, [at(PI, r + 40.0), at(PI + 0.002, r)]); + let anchors: Vec<_> = pts.iter().map(|q| json!({"x": q.x, "y": q.y})).collect(); + let id = smooth_test_path(&mut s, &anchors, true); + let before = path(&s, id); + let mut drag: Vec = (0..=128).map(|i| at(f64::from(i) / 128.0 * TAU, r)).collect(); + drag.splice(65..65, (0..=16).chain((0..=16).rev()).map(|k| at(PI, r + 2.5 * f64::from(k)))); + smooth_pass(&mut s, &drag); + let after = path(&s, id); + assert_ne!(after, before, "the path is smoothed"); + assert_starts_nearest(&after, pts[0], 12.0); +} + +/// A drag that reaches a closed path but not its first anchor leaves that anchor first, where it was. +#[test] +fn smoothing_a_closed_path_away_from_its_first_anchor_keeps_it_first() { + let mut s = session(); + let (c, r) = (Point::new(300.0, 300.0), 100.0); + let at = |deg: f64, rr: f64| c + rr * kurbo::Vec2::from_angle(deg.to_radians()); + let anchors: Vec<_> = (0..12) + .map(|i| { + let q = at(30.0 * f64::from(i), if i == 6 { r + 8.0 } else { r }); + json!({"x": q.x, "y": q.y}) + }) + .collect(); + let id = smooth_test_path(&mut s, &anchors, true); + let before = path(&s, id); + // Along the circle from 140° to 220°, over anchors 5, 6 and 7. + let drag: Vec = (70..=110).map(|k| at(2.0 * f64::from(k), r)).collect(); + smooth_pass(&mut s, &drag); + let after = path(&s, id); + assert_ne!(after, before, "the bump is smoothed"); + assert!(after.subpaths[0].closed); + assert_eq!(after.subpaths[0].anchors[0], before.subpaths[0].anchors[0]); +} + /// A straight line along y = 200 from x = 100 to 400, one anchor every 5 pt, whose second and /// second-to-last anchors are 1.5 pt off the line: its first and last segments leave and arrive at /// 16.7° to it. @@ -1932,6 +2023,260 @@ fn smoothing_leaves_paths_out_of_reach_and_straight_segments_alone() { assert_eq!(path(&s, line), before); } +/// The turn, in degrees, of `sp` at each of its anchors: round a closed path, and 0 at an open +/// path's first and last anchors. +fn smooth_anchor_turns(sp: &vectorcraft_geom::SubPath) -> Vec { + let (n, segs) = (sp.anchors.len(), sp.segment_count()); + (0..n) + .map(|i| { + if segs == 0 || !sp.closed && (i == 0 || i == n - 1) { + return 0.0; + } + let (a, b) = (sp.segment((i + segs - 1) % segs), sp.segment(i % segs)); + let tin = [a.p3 - a.p2, a.p3 - a.p1, a.p3 - a.p0].into_iter().find(|d| d.hypot() > 1e-9).unwrap_or_default(); + let tout = [b.p1 - b.p0, b.p2 - b.p0, b.p3 - b.p0].into_iter().find(|d| d.hypot() > 1e-9).unwrap_or_default(); + tin.cross(tout).atan2(tin.dot(tout)).abs().to_degrees() + }) + .collect() +} + +/// The turn of `sp` at its anchor on `at`, `None` when no anchor is there. +fn smooth_turn_at(sp: &vectorcraft_geom::SubPath, at: Point) -> Option { + let i = sp.anchors.iter().position(|a| a.p.distance(at) < 1e-9)?; + smooth_anchor_turns(sp).get(i).copied() +} + +/// An open polyline with a corner at (300, 300) whose angle inside is `inside` degrees: a 100 pt +/// leg along y = 300 from the left, then a 100 pt leg turning by 180 - `inside` degrees, each leg cut +/// into `per_leg` segments. Returns the path, the corner, and a drag along the path from 40 pt +/// before the corner to 40 pt after it. +fn smooth_corner_path(s: &mut Session, inside: f64, per_leg: usize) -> (NodeId, Point, Vec) { + let v = Point::new(300.0, 300.0); + let d = kurbo::Vec2::from_angle(-(180.0 - inside).to_radians()); + let back = kurbo::Vec2::new(-100.0, 0.0); + let legs = per_leg as f64; + let mut pts: Vec = (0..per_leg).map(|k| v + back * (1.0 - k as f64 / legs)).collect(); + pts.extend((0..=per_leg).map(|k| v + d * (100.0 * k as f64 / legs))); + let anchors: Vec<_> = pts.iter().map(|p| json!({"x": p.x, "y": p.y})).collect(); + let id = smooth_test_path(s, &anchors, false); + let mut drag: Vec = (0..8).map(|k| v - kurbo::Vec2::new(40.0 - 5.0 * f64::from(k), 0.0)).collect(); + drag.extend((0..=8).map(|k| v + d * (5.0 * f64::from(k)))); + (id, v, drag) +} + +/// A Smooth drag over a corner keeps it where the path turns there by more than 57.5° (an angle +/// inside the corner under 122.5°), whether each leg is one segment or ten and at any Fidelity. A +/// wider corner is not kept: when the drag changes the path, no anchor is left turning as sharply +/// there, and a leg of ten segments at the default Fidelity always rounds it. +#[test] +fn the_smooth_tool_keeps_corners_sharper_than_its_threshold() { + let mut wrong = vec![]; + for inside in [30.0f64, 60.0, 90.0, 120.0, 122.4, 122.6, 125.0, 135.0, 150.0, 170.0] { + let kept = inside < 122.5; + for per_leg in [1, 10] { + for fidelity in [0.5, 2.5, 10.0] { + let mut s = session(); + let (id, v, drag) = smooth_corner_path(&mut s, inside, per_leg); + let before = path(&s, id); + let pts: Vec<_> = drag.iter().map(|p| json!([p.x, p.y])).collect(); + s.execute("path.smoothRegion", &json!({"points": pts, "radius": 12, "fidelity": fidelity})).unwrap(); + let p = path(&s, id); + let turn = 180.0 - inside; + let at = smooth_turn_at(&p.subpaths[0], v); + let changed = p != before; + let rounded = changed && at.is_none_or(|t| t < turn - 1.0); + let right = if kept { at.is_some_and(|t| (t - turn).abs() < 0.01) } else { rounded || !changed && per_leg == 1 }; + let most = smooth_anchor_turns(&p.subpaths[0]).into_iter().fold(0.0, f64::max); + if !right || !kept && most > 57.5 || !kept && per_leg == 10 && fidelity == 2.5 && !rounded { + wrong.push(format!( + "{inside}° inside, {per_leg} segments a leg, Fidelity {fidelity}: turn {at:?}, changed {changed}, sharpest {most}°" + )); + } + } + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); +} + +/// Three Smooth drags over a 90° and a 120° corner leave the corner where it was and as sharp, while +/// the first one smooths a wobble on the same leg. +#[test] +fn smooth_drags_again_and_again_keep_a_corner_in_place() { + for inside in [90.0f64, 120.0] { + let mut s = session(); + let v = Point::new(300.0, 300.0); + let d = kurbo::Vec2::from_angle(-(180.0 - inside).to_radians()); + let mut anchors: Vec<_> = (0..=18).map(|k| json!({"x": 180.0 + 5.0 * f64::from(k), "y": if k % 2 == 1 { 301.5 } else { 300.0 }})).collect(); + anchors.push(json!({"x": v.x, "y": v.y})); + let c = v + d * 100.0; + anchors.push(json!({"x": c.x, "y": c.y})); + let id = smooth_test_path(&mut s, &anchors, false); + let mut drag = smooth_drag_along(300.0, 175.0, 300.0); + drag.extend((1..=8).map(|k| v + d * (5.0 * f64::from(k)))); + let mut before = path(&s, id); + for pass in 1..=3 { + smooth_pass(&mut s, &drag); + let p = path(&s, id); + let at = smooth_turn_at(&p.subpaths[0], v); + assert!(at.is_some_and(|t| (t - (180.0 - inside)).abs() < 0.01), "{inside}°, pass {pass}: {at:?}"); + if pass == 1 { + assert!(p.anchor_count() < before.anchor_count(), "{inside}°: the wobble is smoothed: {} anchors", p.anchor_count()); + assert!(total_turning(&p) < total_turning(&before), "{inside}°: the path turns less"); + } + before = p; + } + } +} + +/// A Smooth drag along a line with 1 pt jags, each turning by 90°, smooths them all: none is kept +/// as a corner, since the line hardly turns over the tool's reach. +#[test] +fn smoothing_keeps_no_small_jag_as_a_corner() { + let mut s = session(); + let anchors: Vec<_> = (0..=200).map(|i| json!({"x": 100.0 + f64::from(i), "y": if i % 2 == 1 { 201.0 } else { 200.0 }})).collect(); + let id = smooth_test_path(&mut s, &anchors, false); + assert!(smooth_anchor_turns(&path(&s, id).subpaths[0]).iter().skip(1).take(199).all(|t| (t - 90.0).abs() < 1e-6)); + smooth_pass(&mut s, &smooth_drag_along(200.5, 90.0, 310.0)); + let p = path(&s, id); + let sp = &p.subpaths[0]; + assert!(sp.anchors.len() < 50, "the jags are smoothed: {} anchors", sp.anchors.len()); + let most = smooth_anchor_turns(sp).into_iter().fold(0.0, f64::max); + assert!(most <= 57.5, "a jag is kept, turning {most}°"); +} + +/// A closed path with 90° corners at (200, 200), where it starts, and at (400, 200), 75° ones at +/// (400, 400) and (200, 400), a 30° bend at (300, 426.79), and a top side jagged by 1 pt. With +/// `from_bend` the path starts at the bend instead. +fn smooth_house(s: &mut Session, from_bend: bool) -> (NodeId, [Point; 4], Point) { + let corners = [Point::new(200.0, 200.0), Point::new(400.0, 200.0), Point::new(400.0, 400.0), Point::new(200.0, 400.0)]; + let bend = Point::new(300.0, 400.0 + 100.0 / 75f64.to_radians().tan()); + let mut anchors = vec![json!({"x": 200.0, "y": 200.0})]; + anchors.extend((1..40).map(|k| json!({"x": 200.0 + 5.0 * f64::from(k), "y": if k % 2 == 1 { 201.0 } else { 200.0 }}))); + for p in [corners[1], corners[2], bend, corners[3]] { + anchors.push(json!({"x": p.x, "y": p.y})); + } + if from_bend { + let at_bend = anchors.len() - 2; + anchors.rotate_left(at_bend); + } + (smooth_test_path(s, &anchors, true), corners, bend) +} + +/// A Smooth drag round the whole of a closed path, and one along its top side only, keep its corners, +/// the one where the path starts included, and smooth the jags; the path still starts where it did, +/// at a corner or at the bend, which the refit keeps, and the bend out of the second drag's reach +/// stays as it was. +#[test] +fn smoothing_a_closed_path_keeps_its_corners() { + let turns: Vec = { + let mut s = session(); + let (id, corners, _) = smooth_house(&mut s, false); + corners.iter().map(|c| smooth_turn_at(&path(&s, id).subpaths[0], *c).unwrap()).collect() + }; + for from_bend in [false, true] { + let mut s = session(); + let (id, corners, bend) = smooth_house(&mut s, from_bend); + let before = path(&s, id); + let mut ring: Vec = vec![]; + for (a, b) in [(corners[0], corners[1]), (corners[1], corners[2]), (corners[2], bend), (bend, corners[3]), (corners[3], corners[0])] { + let n = (a.distance(b) / 5.0).ceil(); + ring.extend((0..n as usize).map(|k| a.lerp(b, k as f64 / n))); + } + ring.push(corners[0]); + smooth_pass(&mut s, &ring); + let p = path(&s, id); + let sp = &p.subpaths[0]; + assert!(sp.closed && sp.anchors.len() < before.subpaths[0].anchors.len(), "{} anchors", sp.anchors.len()); + assert_eq!(sp.anchors[0].p, before.subpaths[0].anchors[0].p, "the path still starts where it did"); + for (c, t) in corners.iter().zip(&turns) { + let at = smooth_turn_at(sp, *c); + assert!(at.is_some_and(|a| (a - t).abs() < 0.01), "the corner at {c:?} turning {t}° is kept: {at:?}"); + } + } + + let mut s = session(); + let (id, corners, bend) = smooth_house(&mut s, false); + let before = path(&s, id); + smooth_pass(&mut s, &smooth_drag_along(200.0, 190.0, 410.0)); + let p = path(&s, id); + let sp = &p.subpaths[0]; + assert!(sp.closed && sp.anchors.len() < before.subpaths[0].anchors.len(), "the top is smoothed: {} anchors", sp.anchors.len()); + for (c, t) in corners.iter().zip(&turns) { + let at = smooth_turn_at(sp, *c); + assert!(at.is_some_and(|a| (a - t).abs() < 0.01), "part of the path: the corner at {c:?} turning {t}° is kept: {at:?}"); + } + assert!(smooth_turn_at(sp, bend).is_some_and(|t| (t - 30.0).abs() < 0.01), "the bend out of reach stays"); +} + +/// A Smooth drag over an anchor whose curved legs meet at a corner keeps the corner, taking the turn +/// from the directions the curves arrive and leave along, a handle of no length included. +#[test] +fn smoothing_keeps_a_corner_between_curves() { + use kurbo::ParamCurve; + let v = Point::new(200.0, 300.0); + let with_in = json!({"x": 200.0, "y": 300.0, "in": [170.0, 270.0], "out": [230.0, 270.0]}); + let no_in = json!({"x": 200.0, "y": 300.0, "out": [230.0, 270.0]}); + for (corner, first_out) in [(with_in, [130.0, 260.0]), (no_in, [170.0, 230.0])] { + let mut s = session(); + let anchors = [json!({"x": 100.0, "y": 300.0, "out": first_out}), corner, json!({"x": 300.0, "y": 300.0, "in": [270.0, 260.0]})]; + let id = smooth_test_path(&mut s, &anchors, false); + let before = path(&s, id); + let turn = smooth_turn_at(&before.subpaths[0], v).unwrap(); + assert!(turn > 80.0, "{turn}"); + let (a, b) = (before.subpaths[0].segment(0), before.subpaths[0].segment(1)); + let mut drag: Vec = (0..=10).map(|k| a.eval(0.6 + 0.04 * f64::from(k))).collect(); + drag.extend((1..=10).map(|k| b.eval(0.04 * f64::from(k)))); + smooth_pass(&mut s, &drag); + let at = smooth_turn_at(&path(&s, id).subpaths[0], v); + assert!(at.is_some_and(|t| (t - turn).abs() < 0.01), "the corner turning {turn}° is kept: {at:?}"); + } +} + +/// A corner at the first anchor of the stretch a drag smooths, just out of its reach, keeps its +/// place and its turn. +#[test] +fn a_corner_at_the_end_of_the_smoothed_stretch_stays() { + let mut s = session(); + let mut anchors = vec![json!({"x": 100.0, "y": 300.0}), json!({"x": 200.0, "y": 300.0})]; + anchors.extend((1..=20).map(|k| json!({"x": if k % 2 == 1 { 201.0 } else { 200.0 }, "y": 300.0 - 5.0 * f64::from(k)}))); + let id = smooth_test_path(&mut s, &anchors, false); + let before = path(&s, id); + let turn = smooth_turn_at(&before.subpaths[0], Point::new(200.0, 300.0)).unwrap(); + let drag: Vec = (0..=19).map(|k| Point::new(200.0, 287.0 - 5.0 * f64::from(k))).collect(); + smooth_pass(&mut s, &drag); + let p = path(&s, id); + let sp = &p.subpaths[0]; + assert_ne!(p, before, "the jagged leg is smoothed"); + assert_eq!(sp.anchors[0], before.subpaths[0].anchors[0]); + let at = smooth_turn_at(sp, Point::new(200.0, 300.0)); + assert!(at.is_some_and(|t| (t - turn).abs() < 0.01), "the corner turning {turn}° stays: {at:?}"); +} + +/// A Smooth drag over corners it keeps, with nothing else to smooth, changes nothing and adds no +/// undo step: an open path's corner and a square's four corners. +#[test] +fn a_smooth_drag_that_only_meets_corners_adds_no_undo_step() { + let mut s = session(); + let (id, v, drag) = smooth_corner_path(&mut s, 90.0, 1); + let before = path(&s, id); + let undo = s.doc().unwrap().history.undo.len(); + assert_eq!(smooth_pass_ids(&mut s, &drag), json!([]), "a corner at {v:?}"); + assert_eq!(path(&s, id), before); + assert_eq!(s.doc().unwrap().history.undo.len(), undo); + + let square = [(100.0, 100.0), (200.0, 100.0), (200.0, 200.0), (100.0, 200.0)].map(|(x, y)| json!({"x": x, "y": y})); + let id = smooth_test_path(&mut s, &square, true); + let before = path(&s, id); + let undo = s.doc().unwrap().history.undo.len(); + let mut ring = smooth_drag_along(100.0, 100.0, 200.0); + ring.extend((1..=20).map(|k| Point::new(200.0, 100.0 + 5.0 * f64::from(k)))); + ring.extend(smooth_drag_along(200.0, 100.0, 200.0).into_iter().rev().skip(1)); + ring.extend((1..=20).map(|k| Point::new(100.0, 200.0 - 5.0 * f64::from(k)))); + assert_eq!(smooth_pass_ids(&mut s, &ring), json!([]), "a square"); + assert_eq!(path(&s, id), before); + assert_eq!(s.doc().unwrap().history.undo.len(), undo); +} + #[test] fn join_tool_joins_two_lines() { let mut s = session(); @@ -5178,6 +5523,47 @@ fn pencil_extend_closes_within_400_pt_at_any_fidelity() { } } +/// `closed`, when given, decides whether a stroke continuing an open path closes it (the tools +/// send it by Close Paths When Ends Are Within): false leaves it open even ending on the other end; +/// true closes one ending 50 pt away with a straight segment back, the stroke's end kept, and one +/// ending 2 pt away on the other end itself. +#[test] +fn pencil_extend_closes_as_closed_says() { + let mut s = session(); + for (end, closed, ends_on_start) in [([0i32, 0], false, false), ([0, 50], true, false), ([0, 2], true, true)] { + let l = line(&mut s, 0.0, 0.0, 200.0, 0.0); + let points = json!([[200, 0], [200, 100], [100, 150], end]); + let p = json!({"points": points, "fidelity": 1.5, "closed": closed, "extend": {"id": l.0}, "keepSelected": false}); + s.execute("path.freehand", &p).unwrap(); + let pd = path(&s, l); + let sp = &pd.subpaths[0]; + assert_eq!(sp.closed, closed, "ending at {end:?}"); + if closed { + let stroke_end = Point::new(f64::from(end[0]), f64::from(end[1])); + let kept = sp.anchors.iter().any(|a| a.p.distance(stroke_end) < 1e-6); + assert_eq!(kept, !ends_on_start, "ending at {end:?}: {:?}", sp.anchors); + let on_start = sp.anchors.iter().filter(|a| a.p.distance(Point::new(0.0, 0.0)) < 1e-6).count(); + assert_eq!((sp.anchors[0].p, on_start), (Point::new(0.0, 0.0), 1), "ending at {end:?}"); + } + } +} + +/// A continued path closed from away from its other end closes with a straight segment, even when +/// that end carries a handle the open path didn't use. +#[test] +fn pencil_extend_closes_far_away_with_a_straight_segment() { + let mut s = session(); + let anchors = json!([{"x": 0, "y": 0, "in": [-40, 30]}, {"x": 200, "y": 0}]); + let l = NodeId(s.execute("path.create", &json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap()); + let points = json!([[200, 0], [200, 100], [100, 150], [0, 50]]); + let p = json!({"points": points, "fidelity": 1.5, "closed": true, "extend": {"id": l.0}, "keepSelected": false}); + s.execute("path.freehand", &p).unwrap(); + let sp = path(&s, l).subpaths[0].clone(); + assert!(sp.closed); + let (first, last) = (sp.anchors[0], sp.anchors[sp.anchors.len() - 1]); + assert_eq!((first.h_in, last.h_out), (first.p, last.p), "the closing segment has no handles: {:?}", sp.anchors); +} + /// At Fidelity 0.01 short, one-point and repeated-point strokes still draw or are refused, never /// crash, and what they draw has finite anchors. #[test] diff --git a/crates/engine/src/tests/globaledit.rs b/crates/engine/src/tests/globaledit.rs index fa86248cdb..9a4cb7d138 100644 --- a/crates/engine/src/tests/globaledit.rs +++ b/crates/engine/src/tests/globaledit.rs @@ -4,7 +4,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::{Node, NodeKind}; -use vectorcraft_geom::{Affine, PathData, Rect}; +use vectorcraft_geom::{Affine, PathData, Point, Rect}; use crate::*; @@ -320,16 +320,16 @@ fn global_edit_needs_one_supported_object() { let t = NodeId(s.execute("text.create", &json!({"x": 50, "y": 500, "text": "Hi"})).unwrap()["id"].as_u64().unwrap()); sel(&mut s, &[t]); assert!(matches!(s.execute("select.globalEdit", &json!({})), Err(EngineError::Disabled(..))), "type"); - let lone = rect(&mut s, 0.0, 500.0, 30.0, 70.0); - // A copy turned a quarter turn (70 × 30) is not taken: rotated copies are not matched, and the - // message says so. - let turned = rect(&mut s, 200.0, 500.0, 30.0, 70.0); - sel(&mut s, &[turned]); - s.execute("object.rotate", &json!({"angle": 90})).unwrap(); + // A reflected copy is not taken, and the message says so. + let lone = kite(&mut s, 0.0, 500.0, 1.0); + let mirrored = kite(&mut s, 200.0, 500.0, 1.0); + sel(&mut s, &[mirrored]); + s.execute("object.reflect", &json!({"axis": "vertical"})).unwrap(); sel(&mut s, &[lone]); let e = s.execute("select.globalEdit", &json!({})).unwrap_err().to_string(); - assert!(e.contains("no similar objects") && e.contains("rotated"), "{e}"); + assert!(e.contains("no similar objects") && e.contains("reflected copies are not matched") && !e.contains("rotated"), "{e}"); assert!(s.doc().unwrap().global_edit.is_none()); + assert!(crate::cmd::globaledit::highlights(&s).is_empty(), "and it is not highlighted"); // A group holding type is not offered, though another such group exists. let group = |s: &mut Session, x: f64| { let p = rect(s, x, 100.0, 10.0, 10.0); @@ -851,3 +851,159 @@ fn groups_nested_as_deep_as_a_document_allows_are_edited_together() { s.execute("paint.setFill", &json!({"color": "#12ab34"})).unwrap(); assert_eq!(fill(&s, other_inner), "#12ab34"); } + +/// A four-sided path with no symmetry, `k` times the size, its box's top left near (`x`, `y`): a +/// 30 × 70 rectangle whose first anchor is moved. +fn kite(s: &mut Session, x: f64, y: f64, k: f64) -> NodeId { + let id = rect(s, x, y, 30.0 * k, 70.0 * k); + s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 0]]})).unwrap(); + s.execute("path.moveAnchors", &json!({"dx": 10.0 * k, "dy": -20.0 * k})).unwrap(); + id +} + +/// Rotate `id` by `deg` (counter-clockwise) about the centre of its box → that rotation. +fn rotate(s: &mut Session, id: NodeId, deg: f64) -> Affine { + let c = bounds(s, id).center(); + sel(s, &[id]); + s.execute("object.rotate", &json!({"angle": deg})).unwrap(); + Affine::rotate_about(-deg.to_radians(), c) +} + +/// A kite at the origin side of the page, a copy of it turned a quarter turn, and a copy at half +/// the size turned by 30° → the three and the transforms that lay the first on the other two. +fn turned_kites(s: &mut Session) -> ([NodeId; 3], [Affine; 2]) { + let a = kite(s, 0.0, 100.0, 1.0); + let (b, c) = (kite(s, 200.0, 100.0, 1.0), kite(s, 400.0, 100.0, 0.5)); + let quarter = rotate(s, b, 90.0) * Affine::translate((200.0, 0.0)); + let small = rotate(s, c, 30.0) * Affine::translate((400.0, 100.0)) * Affine::scale(0.5) * Affine::translate((0.0, -100.0)); + assert!(placed(s, a, b, quarter) && placed(s, a, c, small), "the copies as made"); + ([a, b, c], [quarter, small]) +} + +#[test] +fn start_global_edit_takes_rotated_copies_and_an_edit_reaches_each_turned_by_its_angle() { + let mut s = session(); + let ([a, b, c], [quarter, small]) = turned_kites(&mut s); + sel(&mut s, &[a]); + assert_eq!(crate::cmd::globaledit::highlights(&s).len(), 2, "both are highlighted before the start"); + assert_eq!(s.execute("select.globalEditOptions", &json!({})).unwrap()["count"], 3); + assert_eq!(start(&mut s, a, json!({})), [a, b, c]); + let before = (*s.doc().unwrap().doc).clone(); + let steps = s.doc().unwrap().history.undo.len(); + // An anchor moved on the selected kite moves on each copy along the copy's own directions. + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]]})).unwrap(); + s.execute("path.moveAnchors", &json!({"dx": 12, "dy": 5})).unwrap(); + assert!(placed(&s, a, b, quarter), "the quarter-turned copy"); + assert!(placed(&s, a, c, small), "the smaller copy turned by 30°"); + assert!(!placed(&s, a, b, Affine::translate((200.0, 0.0))), "the copy is still turned"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one undo step"); + crate::tests_large_edits::undo_gives_back(&mut s, &before); + // A move of the whole kite to the right moves the quarter-turned copy up (counter-clockwise). + sel(&mut s, &[a]); + let was = bounds(&s, b); + s.execute("object.move", &json!({"dx": 10, "dy": 0})).unwrap(); + let now = bounds(&s, b); + assert!((now.x0 - was.x0).abs() < 1e-6 && (now.y0 - (was.y0 - 10.0)).abs() < 1e-6, "{was:?} → {now:?}"); + assert!(placed(&s, a, b, quarter) && placed(&s, a, c, small), "each copy lies on the kite as before"); +} + +#[test] +fn a_rotated_copy_leads_an_edit_as_any_other_member_does() { + let mut s = session(); + let ([a, b, c], [quarter, small]) = turned_kites(&mut s); + // Started on the turned copy, and edited from the smaller one. + assert_eq!(start(&mut s, b, json!({})), [b, a, c]); + s.execute("select.anchors", &json!({"id": c.0, "anchors": [[0, 2]]})).unwrap(); + s.execute("path.moveAnchors", &json!({"dx": 3, "dy": -4})).unwrap(); + assert!(placed(&s, a, b, quarter) && placed(&s, a, c, small)); + // A fill reaches the turned copies as it is. + s.execute("paint.setFill", &json!({"color": "#12ab34"})).unwrap(); + assert_eq!((fill(&s, a), fill(&s, b)), ("#12ab34".to_string(), "#12ab34".to_string())); +} + +#[test] +fn size_takes_a_rotated_copy_of_the_same_size_and_other_shapes_stay_out() { + let mut s = session(); + let ([a, b, c], _) = turned_kites(&mut s); + // A quarter-turned copy is 70 × 30 by its box: it has the size of the 30 × 70 kite all the same. + assert_eq!(start(&mut s, a, json!({"size": true})), [a, b], "not the half-size copy {c}"); + s.execute("select.globalEdit", &json!({})).unwrap(); + // A copy turned and then stretched, and one whose anchor was moved, are other shapes. + let stretched = kite(&mut s, 0.0, 300.0, 1.0); + rotate(&mut s, stretched, 30.0); + s.execute("object.scale", &json!({"sx": 150, "sy": 100})).unwrap(); + let bent = kite(&mut s, 200.0, 300.0, 1.0); + rotate(&mut s, bent, 45.0); + s.execute("select.anchors", &json!({"id": bent.0, "anchors": [[0, 2]]})).unwrap(); + s.execute("path.moveAnchors", &json!({"dx": 1, "dy": 0})).unwrap(); + // A copy turned by half a turn and by a full turn in two steps. + let half = kite(&mut s, 400.0, 300.0, 1.0); + rotate(&mut s, half, 180.0); + let full = kite(&mut s, 600.0, 300.0, 1.0); + rotate(&mut s, full, 135.0); + rotate(&mut s, full, 225.0); + assert_eq!(start(&mut s, a, json!({})), [a, b, c, half, full], "not the stretched {stretched} nor the bent {bent}"); +} + +#[test] +fn a_square_whose_anchors_were_turned_is_a_rotated_copy() { + let mut s = session(); + let [a, b, ..] = squares(&mut s); + let turn = rotate(&mut s, b, 90.0) * Affine::translate((300.0, 0.0)); + assert_eq!(start(&mut s, a, json!({})).len(), 3, "the turned square is still taken, with the small one"); + // The first anchor of the turned square lies at another corner, and that is the one that moves. + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0]]})).unwrap(); + s.execute("path.moveAnchors", &json!({"dx": 10, "dy": 30})).unwrap(); + assert!(placed(&s, a, b, turn)); + assert!(!placed(&s, a, b, Affine::translate((300.0, 0.0)))); +} + +#[test] +fn rotated_groups_are_like_the_group_and_an_edit_inside_one_reaches_the_others_turned() { + let mut s = session(); + let (g, [sq, dot, _]) = card(&mut s, 0.0, 1.0); + let (copy, [csq, cdot, cbar]) = card(&mut s, 300.0, 1.0); + let turn = rotate(&mut s, copy, 90.0) * Affine::translate((300.0, 0.0)); + // The same three objects, each turned in place: not the group turned as a whole. + let (apart, objects) = card(&mut s, 500.0, 1.0); + for id in objects { + rotate(&mut s, id, 90.0); + } + assert_eq!(start(&mut s, g, json!({})), [g, copy], "not the group {apart} whose objects were turned one by one"); + sel(&mut s, &[dot]); + s.execute("paint.setFill", &json!({"color": "#12ab34"})).unwrap(); + assert_eq!(fill(&s, cdot), "#12ab34"); + sel(&mut s, &[sq]); + s.execute("object.setBounds", &json!({"height": 20, "reference": 0})).unwrap(); + assert!(placed(&s, sq, csq, turn), "the square in the turned group is halved along the group's own direction"); + assert_eq!(kids(&s, copy), [csq, cdot, cbar], "each object keeps its id"); + s.execute("select.globalEdit", &json!({})).unwrap(); + // An object inside one group takes the object at its place in the turned group, as the + // objects of rotated copies of a group are edited together. + assert_eq!(start(&mut s, sq, json!({})), [sq, csq]); +} + +#[test] +fn a_rotated_symbol_instance_is_taken_and_a_reflected_one_is_not() { + let mut s = session(); + let r = rect(&mut s, 0.0, 0.0, 40.0, 40.0); + let first = NodeId(s.execute("symbol.new", &json!({"ids": [r.0], "name": "Tile"})).unwrap()["id"].as_u64().unwrap()); + let place = + |s: &mut Session, x: f64| NodeId(s.execute("symbol.place", &json!({"name": "Tile", "x": x, "y": 300})).unwrap()["id"].as_u64().unwrap()); + let (turned, mirrored) = (place(&mut s, 200.0), place(&mut s, 400.0)); + sel(&mut s, &[turned]); + s.execute("object.rotate", &json!({"angle": 30, "origin": [220, 320]})).unwrap(); + sel(&mut s, &[mirrored]); + s.execute("object.reflect", &json!({"axis": "vertical", "origin": [420, 320]})).unwrap(); + assert_eq!(start(&mut s, first, json!({})), [first, turned], "not the reflected instance {mirrored}"); + let xf = |s: &Session, id: NodeId| match node(s, id).kind { + NodeKind::SymbolInstance { xf, .. } => xf, + _ => panic!("not an instance"), + }; + let was = xf(&s, turned); + s.execute("object.move", &json!({"dx": 10, "dy": 0})).unwrap(); + // The instance turned by 30° counter-clockwise moves along its own direction. + let moved = Affine::rotate((-30f64).to_radians()) * Point::new(10.0, 0.0); + let (now, want) = (xf(&s, turned).as_coeffs(), (Affine::translate(moved.to_vec2()) * was).as_coeffs()); + assert!(now.iter().zip(want).all(|(p, q)| (p - q).abs() < 1e-6), "{now:?} vs {want:?}"); +} diff --git a/crates/engine/src/tests/history_document.rs b/crates/engine/src/tests/history_document.rs index 3c2c9b9eb4..9e05eabeac 100644 --- a/crates/engine/src/tests/history_document.rs +++ b/crates/engine/src/tests/history_document.rs @@ -79,18 +79,29 @@ fn the_source_stays_as_it_is() { assert!(s.doc().unwrap().is_dirty(), "the new document is unsaved"); } -/// An index that names no state, or is not a whole number, is an error and changes nothing: no -/// document, no step and no Untitled number is used up. +/// An index that names no state (`no history state N`), or is not a whole number ("`index` must be +/// a whole number"), is an error and changes nothing: no document, no step and no Untitled number +/// is used up. #[test] fn a_bad_index_is_an_error_and_changes_nothing() { let mut s = three_rectangles_one_undone(); let source = s.doc().unwrap().doc.clone(); let untitled = s.peek_untitled(); - let bad: [Value; 8] = [json!(4), json!(99), json!(-1), json!(1.5), json!("1"), json!(true), json!([1]), json!(u64::MAX)]; - for index in bad { + let bad: [(Value, bool); 8] = [ + (json!(4), true), + (json!(99), true), + (json!(u64::MAX), true), + (json!(-1), false), + (json!(1.5), false), + (json!("1"), false), + (json!(true), false), + (json!([1]), false), + ]; + for (index, whole) in bad { let e = s.execute(CMD, &json!({ "index": index })).unwrap_err(); assert!(matches!(e, EngineError::BadParams { .. }), "{index}: {e}"); - assert!(e.to_string().contains(&format!("no history state {index}")), "{e}"); + let want = if whole { format!("no history state {index}") } else { "`index` must be a whole number".to_string() }; + assert_eq!(e.to_string(), format!("invalid parameters for `{CMD}`: {want}"), "{index}"); assert_eq!(s.documents().len(), 1, "{index}"); assert_eq!(steps(&s), (2, 1), "{index}"); assert!(Arc::ptr_eq(&s.doc().unwrap().doc, &source), "{index}"); diff --git a/crates/engine/src/tests/inline.rs b/crates/engine/src/tests/inline.rs index f7c72956ad..71caf14bf8 100644 --- a/crates/engine/src/tests/inline.rs +++ b/crates/engine/src/tests/inline.rs @@ -1,8 +1,12 @@ //! Inline graphics in text: `text.insertInline`, editing over them, undo, following their symbol. +use std::sync::Arc; + use serde_json::json; +use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::text::INLINE_CHAR; use vectorcraft_doc::{Node, NodeId, NodeKind, TextObject}; +use vectorcraft_geom::{Affine, Rect}; use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey}; use crate::*; @@ -325,6 +329,143 @@ fn a_symbol_that_shows_itself_inline_is_an_empty_slot() { assert_eq!(d.inline_art_bounds("Loop"), None); } +/// A rectangle `r` filled black, without a stroke. +fn filled_rect(d: &mut vectorcraft_doc::Document, r: Rect) -> Arc { + let look = vectorcraft_doc::Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0); + Arc::new(Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(r), look)) +} + +/// An instance of symbol `name` placed by `xf`. +fn symbol_instance(d: &mut vectorcraft_doc::Document, name: &str, xf: Affine) -> Arc { + Arc::new(Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: name.into(), xf })) +} + +/// Gives symbol `name` the art `art` in a group, adding the symbol when there is none of that name. +fn set_symbol_art(d: &mut vectorcraft_doc::Document, name: &str, art: Vec>) { + let art = Arc::new(Node::group(d.alloc_id(), art)); + match d.symbols.iter_mut().find(|x| x.name == name) { + Some(x) => x.art = art, + None => d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: name.into(), art }), + } +} + +/// An inline graphic of a symbol whose art holds an instance of another symbol is sized by that +/// symbol's art, and follows it when it changes, through undo, redo and a saved copy. +#[test] +fn an_inline_graphic_follows_the_art_of_a_symbol_nested_in_its_symbol() { + let mut s = session(); + s.edit("Symbols", |d, _| { + let far = filled_rect(d, Rect::new(100.0, 0.0, 160.0, 20.0)); + set_symbol_art(d, "Far", vec![far]); + let inner = symbol_instance(d, "Far", Affine::IDENTITY); + set_symbol_art(d, "Holder", vec![inner]); + Ok(()) + }) + .unwrap(); + let id = text(&mut s, "ab"); + let w0 = obj(&s, id).bounds().unwrap().width(); + s.execute("text.insertInline", &json!({"id": id.0, "at": 1, "symbol": "Holder", "scale": 1})).unwrap(); + let wide = Some(Rect::new(100.0, 0.0, 160.0, 20.0)); + let t = obj(&s, id); + assert_eq!(inline_bounds(&t), wide); + // 20 pt tall at 20 pt type and 3 times as wide: the text grows by 60 pt. + let w1 = t.bounds().unwrap().width(); + assert!((w1 - w0 - 60.0).abs() < 1.5, "{w0} → {w1}"); + // Far redefined as a 10 × 40 rectangle: the graphic is 20 pt tall and 5 pt wide. + s.edit("Redefine Far", |d, _| { + let tall = filled_rect(d, Rect::new(0.0, 0.0, 10.0, 40.0)); + set_symbol_art(d, "Far", vec![tall]); + Ok(()) + }) + .unwrap(); + let tall = Some(Rect::new(0.0, 0.0, 10.0, 40.0)); + let t = obj(&s, id); + assert_eq!(inline_bounds(&t), tall); + assert_eq!(s.doc().unwrap().doc.symbol_art_bounds("Holder"), tall); + let w2 = t.bounds().unwrap().width(); + assert!((w2 - w0 - 5.0).abs() < 1.5, "{w0} → {w2}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(inline_bounds(&obj(&s, id)), wide); + assert!((obj(&s, id).bounds().unwrap().width() - w1).abs() < 1e-6); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(inline_bounds(&obj(&s, id)), tall); + // Opening a saved copy measures it the same way. + let doc = (*s.doc().unwrap().doc).clone(); + let mut back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap(); + back.title = "copy".into(); + let mut s2 = Session::new(); + s2.add_document(back, None); + assert_eq!(inline_bounds(&obj(&s2, id)), tall); + assert!((obj(&s2, id).bounds().unwrap().width() - w2).abs() < 1e-6); +} + +/// Symbol C shows Holder inline, Holder holds an instance of B, and B shows A inline: with the +/// symbols listed C, Holder, B, A, a change to A reaches C through B's and Holder's new sizes. +#[test] +fn symbols_are_resolved_after_the_symbols_their_instances_show() { + let mut s = session(); + circle_symbol(&mut s, "A", 10.0); + let t = text(&mut s, "z"); + s.execute("text.insertInline", &json!({"id": t.0, "at": 0, "symbol": "A"})).unwrap(); + s.execute("symbol.new", &json!({"name": "B", "ids": [t.0]})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + s.edit("Holder", |d, _| { + let inner = symbol_instance(d, "B", Affine::IDENTITY); + set_symbol_art(d, "Holder", vec![inner]); + Ok(()) + }) + .unwrap(); + let t = text(&mut s, "z"); + s.execute("text.insertInline", &json!({"id": t.0, "at": 0, "symbol": "Holder"})).unwrap(); + s.execute("symbol.new", &json!({"name": "C", "ids": [t.0]})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + s.edit("Reverse the symbols", |d, _| { + d.symbols.reverse(); + Ok(()) + }) + .unwrap(); + let h0 = s.doc().unwrap().doc.symbol_art_bounds("Holder"); + redefine_as_wide_ellipse(&mut s, "A"); + let d = &s.doc().unwrap().doc; + assert_ne!(d.symbol_art_bounds("Holder"), h0); + assert_eq!(inline_bounds(&art_text(&s, "C")), d.symbol_art_bounds("Holder")); +} + +/// Symbol A holds an instance of B, and B's type shows A inline: the size of each would depend on +/// itself, so both are empty slots, and stay so through later edits. +#[test] +fn a_symbol_that_shows_itself_through_an_instance_is_an_empty_slot() { + let mut s = session(); + circle_symbol(&mut s, "A", 10.0); + let t = text(&mut s, "ab"); + s.execute("text.insertInline", &json!({"id": t.0, "at": 1, "symbol": "A"})).unwrap(); + s.execute("symbol.new", &json!({"name": "B", "ids": [t.0]})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + s.edit("A holds B", |d, _| { + let inner = symbol_instance(d, "B", Affine::IDENTITY); + set_symbol_art(d, "A", vec![inner]); + Ok(()) + }) + .unwrap(); + let line = text(&mut s, "x"); + s.execute("text.insertInline", &json!({"id": line.0, "at": 0, "symbol": "A"})).unwrap(); + for _ in 0..2 { + for name in ["A", "B"] { + assert_eq!(s.doc().unwrap().doc.inline_art_bounds(name), None, "{name}"); + } + assert_eq!(inline_bounds(&art_text(&s, "B")), None); + assert_eq!(inline_bounds(&obj(&s, line)), None); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + } + let _ = s.execute("document.serialize", &json!({"format": "png"})).unwrap(); + // Redefined without the instance, A is on no cycle. + redefine_as_wide_ellipse(&mut s, "A"); + let d = &s.doc().unwrap().doc; + assert!(d.inline_art_bounds("A").is_some()); + assert_eq!(inline_bounds(&art_text(&s, "B")), d.symbol_art_bounds("A")); + assert_eq!(inline_bounds(&obj(&s, line)), d.symbol_art_bounds("A")); +} + /// A list paragraph that starts with an inline graphic draws its bullet before the graphic, and /// live SVG text writes the bullet. #[test] diff --git a/crates/engine/src/tests/journal.rs b/crates/engine/src/tests/journal.rs index 1c4287e9c1..700c17883d 100644 --- a/crates/engine/src/tests/journal.rs +++ b/crates/engine/src/tests/journal.rs @@ -611,15 +611,18 @@ fn edit_copy_and_cut_read_the_recorded_artboards() { s.execute("select.none", &json!({})).unwrap(); assert!(matches!(s.execute(id, &json!({})), Err(crate::EngineError::Disabled(..))), "{id}"); let before = documents(&s); - for bad in [ - json!({"selectedArtboards": [9]}), - json!({"selectedArtboards": []}), - json!({"selectedArtboards": "1"}), - json!({"selectedArtboards": null}), - json!({"selectedArtboards": [1], "art": "yes"}), + for (bad, want) in [ + (json!({"selectedArtboards": [9]}), "no such artboard"), + (json!({"selectedArtboards": []}), "`selectedArtboards` must be a non-empty list of artboard indices"), + (json!({"selectedArtboards": "1"}), "`selectedArtboards` must be a list of artboard indices"), + (json!({"selectedArtboards": null}), "`selectedArtboards` must be a list of artboard indices"), + (json!({"selectedArtboards": [1, "0"]}), "`selectedArtboards` must contain whole numbers"), + (json!({"selectedArtboards": [1, -1]}), "`selectedArtboards` must contain whole numbers"), + (json!({"selectedArtboards": [1], "art": "yes"}), "`art` must be true or false"), ] { let err = s.execute(id, &bad).unwrap_err().to_string(); - assert!(err.contains(id) || err.contains("no such artboard"), "{id} {bad}: {err}"); + assert!(err.ends_with(want), "{id} {bad}: {err}"); + assert!(err.contains(id) || want == "no such artboard", "{id} {bad}: {err}"); assert_eq!(documents(&s), before, "{id} {bad}"); assert!(s.clipboard.artboards.is_empty(), "{id} {bad}"); } diff --git a/crates/engine/src/tests/library.rs b/crates/engine/src/tests/library.rs index c2dccc7bb5..a75bc532bf 100644 --- a/crates/engine/src/tests/library.rs +++ b/crates/engine/src/tests/library.rs @@ -733,6 +733,38 @@ fn a_library_character_style_linked_to_a_missing_swatch_is_added_unlinked() { assert_eq!((r["style"].as_str(), r["existing"].as_bool()), (Some("Accent"), Some(true))); } +/// A gradient stop linked to a spot swatch with process plates, as a library file can hold one. +fn plated_stops() -> Value { + let ink = vectorcraft_color::Color::cmyk(0.0, 0.5, 0.0, 0.0); + json!([ + {"offset": 0, "color": vectorcraft_color::Color::WHITE}, + {"offset": 1, "color": ink, "swatch": "Brand", "tint": 0.5, "plates": [0.3, 0, 0, 0]} + ]) +} + +/// Library gradients and the gradient stops of library character styles lose their links to +/// swatches the document does not have together with the process plates those links print with. +#[test] +fn library_stops_unlinked_from_their_swatch_keep_no_process_plates() { + let data = json!({ + "name": "Plated", + "gradients": [{"name": "Glow", "gradient": {"gradient": {"kind": "Linear", "stops": plated_stops()}, "angle": 0}}], + "charStyles": [{"name": "Accent", "attrs": {"fill": {"type": "gradient", "gradient": {"kind": "Linear", "stops": plated_stops()}}}}] + }); + let mut s = session(); + let lib = run(&mut s, "library.import", json!({"data": data.to_string()}))["id"].as_str().unwrap().to_string(); + let a = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 20}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [a]})); + run(&mut s, "library.use", json!({"library": lib, "kind": "fillGradient", "item": "Glow"})); + let st = gradient(&paint_of(&s, &a, false)).gradient.stops[1].clone(); + assert_eq!((st.swatch.as_deref(), st.tint, st.plates), (None, 1.0, None), "{st:?}"); + run(&mut s, "library.addToCharacterStyles", json!({"library": lib, "item": "Accent"})); + let style = s.doc().unwrap().doc.char_styles.iter().find(|c| c.name == "Accent").map(|c| c.attrs["fill"].clone()).unwrap(); + let fill = serde_json::from_value::(style).unwrap(); + let st = gradient(&fill).gradient.stops[1].clone(); + assert_eq!((st.swatch.as_deref(), st.tint, st.plates), (None, 1.0, None), "{st:?}"); +} + /// A library style is compared with the document's in the form the document stores it in, so a /// style whose file writes a size as a whole number is reused, by Add to Character Styles and by a /// click alike. diff --git a/crates/engine/src/tests/linked_stops.rs b/crates/engine/src/tests/linked_stops.rs index 9ed3db2724..62955e6065 100644 --- a/crates/engine/src/tests/linked_stops.rs +++ b/crates/engine/src/tests/linked_stops.rs @@ -213,6 +213,24 @@ fn spot_stops_with_process_plates_export_both_in_device_n_shadings() { assert_eq!(gradient(&s, id).gradient.stops[1].plates, None); } +#[test] +fn deleting_a_spot_swatch_takes_the_process_plates_of_the_stops_it_unlinks() { + let (mut s, id) = setup(); + let plated = json!({"stops": [{"offset": 0, "color": "#ffffff"}, {"offset": 1, "swatch": "Ink", "tint": 50, "plates": [0.3, 0, 0, 0]}]}); + run(&mut s, "paint.editGradient", plated.clone()); + run(&mut s, "swatch.new", json!({"name": "Glow", "gradient": plated})); + let linked = gradient(&s, id).gradient.stops[1].clone(); + assert_eq!((linked.swatch.as_deref(), linked.plates), (Some("Ink"), Some([0.3, 0.0, 0.0, 0.0]))); + run(&mut s, "swatch.delete", json!({"name": "Ink"})); + // The art's stop and the gradient swatch's stop keep the color they show, unlinked and without plates. + let Paint::Gradient(sw) = doc(&s).swatch("Glow").unwrap().paint.clone() else { panic!("a gradient swatch") }; + for st in [&gradient(&s, id).gradient.stops[1], &sw.gradient.stops[1]] { + assert_eq!((st.color, st.swatch.as_deref(), st.tint, st.plates), (linked.color, None, 1.0, None), "{st:?}"); + } + run(&mut s, "edit.undo", json!({})); + assert_eq!(gradient(&s, id).gradient.stops[1], linked, "undo brings back the link and the plates"); +} + #[test] fn radial_spot_gradients_mixed_with_other_inks_export_as_device_n_shadings() { let (mut s, _) = setup(); diff --git a/crates/engine/src/tests/links.rs b/crates/engine/src/tests/links.rs index e683b156e1..62d3e36bad 100644 --- a/crates/engine/src/tests/links.rs +++ b/crates/engine/src/tests/links.rs @@ -768,6 +768,223 @@ fn nested_objects_that_repeat_ids_open_with_ids_of_their_own() { assert!(image(&s, layer_image).link.is_some(), "the image in the layers stays linked"); } +/// The files of the linked images that the stored brushes of [`brush_links`] are made of: a scatter +/// brush's, an art brush's and a pattern brush's side tile. +const BRUSHED: [(&str, &str, &str); 3] = [("scatter.png", "scatter", "Specks"), ("art.png", "art", "Band"), ("side.png", "pattern", "Frame")]; + +/// A document whose stored brushes are made of [`BRUSHED`]'s linked images in `dir`. The art +/// brush's image is still in the layers too, so its brush art repeats that object's id; the other +/// two images were cleared from the layers. +fn brush_links(dir: &Folder) -> (Session, NodeId) { + for (i, (name, ..)) in (0u8..).zip(BRUSHED) { + write(&dir.file(name), &png(20, 10, [30 + 60 * i, 120, 90])); + } + let mut s = session(); + let mut kept = NodeId(0); + for (name, kind, brush) in BRUSHED { + let id = place(&mut s, &dir.file(name)); + s.execute("brush.new", &json!({"type": kind, "name": brush, "ids": [id.0]})).unwrap(); + if kind == "art" { + kept = id; + } else { + s.execute("edit.clear", &json!({"ids": [id.0]})).unwrap(); + } + } + s.execute("select.set", &json!({"ids": []})).unwrap(); + (s, kept) +} + +/// The image in the art of stored brush `name`, as the document stores it. +fn brush_image(s: &Session, name: &str) -> ImageObject { + let b = vectorcraft_brush::find(&s.doc().unwrap().doc, name).unwrap_or_else(|| panic!("no brush {name}")); + let mut found = None; + b.art()[0].walk(&mut |n| { + if let (None, NodeKind::Image(im)) = (&found, &n.kind) { + found = Some((**im).clone()); + } + }); + found.unwrap_or_else(|| panic!("no image in brush {name}")) +} + +/// The id of the image in the art of stored brush `name`, as the document stores it. +fn brush_image_id(s: &Session, name: &str) -> u64 { + let b = vectorcraft_brush::find(&s.doc().unwrap().doc, name).unwrap(); + let mut found = None; + b.art()[0].walk(&mut |n| { + if found.is_none() && matches!(n.kind, NodeKind::Image(_)) { + found = Some(n.id.0); + } + }); + found.unwrap() +} + +/// Images in the art of stored brushes are listed after the others, one row per image in each brush tile, +/// each with an id no other object has (the layer tree keeps its own), the brush named as what holds it; Check +/// Links and the missing filter count them, and the ids stay the same from one list to the next. +#[test] +fn links_in_stored_brush_art_are_listed_and_checked_with_ids() { + let dir = Folder::new("brush-ids"); + let (mut s, kept) = brush_links(&dir); + let list = s.execute("links.list", &json!({})).unwrap(); + let rows = list["links"].as_array().unwrap(); + let owners: Vec<(&str, &Value)> = rows.iter().map(|r| (r["name"].as_str().unwrap(), &r["owner"])).collect(); + let library = vectorcraft_brush::library(&s.doc().unwrap().doc); + let index = |name: &str| library.iter().position(|b| b.name == name).unwrap(); + assert_eq!( + owners, + [ + ("art.png", &Value::Null), + ("scatter.png", &json!({"kind": "brush", "name": "Specks", "index": index("Specks")})), + ("art.png", &json!({"kind": "brush", "name": "Band", "index": index("Band")})), + ("side.png", &json!({"kind": "brush", "name": "Frame", "index": index("Frame"), "tile": "side"})), + ], + "{list}" + ); + assert_eq!(rows[0]["id"], json!(kept.0), "the layer tree keeps its ids: {list}"); + let ids: std::collections::BTreeSet = rows.iter().map(|r| r["id"].as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 4, "{list}"); + assert!(!ids.contains(&0), "{list}"); + assert!(rows.iter().all(|r| r["status"] == "ok" && r["linked"] == true), "{list}"); + assert_eq!(s.execute("links.list", &json!({})).unwrap(), list, "the same ids each time"); + let other = super::rect(&mut s, 0.0, 0.0, 5.0, 5.0); + s.execute("edit.clear", &json!({"ids": [other.0]})).unwrap(); + assert_eq!(s.execute("links.list", &json!({})).unwrap(), list, "the same ids after other objects are made"); + let check = s.execute("links.check", &json!({})).unwrap(); + assert_eq!(check["links"].as_array().unwrap().len(), 3, "{check}"); + std::fs::remove_file(dir.file("side.png")).unwrap(); + let check = s.execute("links.check", &json!({})).unwrap(); + assert_eq!(check["missing"].as_u64(), Some(1), "{check}"); + let missing = s.execute("links.list", &json!({"show": "missing"})).unwrap(); + assert_eq!(missing["links"][0]["id"], rows[3]["id"], "{missing}"); +} + +/// Every links command takes the id of an image in a stored brush's art and acts on that brush's art, +/// never on the image in the layers whose id the art repeated: Link Info, Go To (which clears the +/// selection and names the brush), Placement Options, Relink, Update and Embed. The ids each change +/// gives the art are kept in the library, so the next list names the same rows. +#[test] +fn links_commands_act_on_images_in_stored_brush_art_by_id() { + let dir = Folder::new("brush-act"); + let (mut s, kept) = brush_links(&dir); + let band = row_id_owned(&mut s, "art.png", "brush"); + assert_ne!(band, kept.0); + let info = s.execute("links.info", &json!({"id": band})).unwrap(); + assert_eq!((info["fileName"].as_str(), info["status"].as_str(), info["id"].as_u64()), (Some("art.png"), Some("ok"), Some(band)), "{info}"); + s.execute("select.set", &json!({"ids": [kept.0]})).unwrap(); + let go = s.execute("links.goTo", &json!({"id": band})).unwrap(); + assert_eq!( + (go["onCanvas"].clone(), go["owner"]["kind"].clone(), go["owner"]["name"].clone()), + (json!(false), json!("brush"), json!("Band")), + "{go}" + ); + assert!(s.doc().unwrap().selection.objects.is_empty(), "nothing on the canvas is selected"); + s.execute("links.placementOptions", &json!({"ids": [band], "preserve": "fit"})).unwrap(); + assert_eq!(s.execute("links.placementOptions", &json!({"ids": [band]})).unwrap()["placement"]["preserve"], "fit"); + assert_eq!(brush_image(&s, "Band").placement.preserve, vectorcraft_doc::links::Preserve::Fit); + assert_eq!(brush_image_id(&s, "Band"), band, "the brush keeps the id it is listed by"); + assert_ne!(image(&s, kept).placement.preserve, vectorcraft_doc::links::Preserve::Fit, "the image in the layers is left as it was"); + // Relink: the brush's image shows the new file; the image in the layers keeps its file. + let other = dir.file("other.png"); + write(&other, &png(40, 20, BLUE)); + let r = s.execute("links.relink", &json!({"ids": [band], "path": other})).unwrap(); + assert_eq!(r["relinked"], json!([band]), "{r}"); + assert_eq!(brush_image(&s, "Band").link.unwrap().path, other); + assert_eq!(image(&s, kept).link.unwrap().path, dir.file("art.png")); + assert_eq!(row_id_owned(&mut s, "other.png", "brush"), band, "{}", s.execute("links.list", &json!({})).unwrap()); + // Update: a changed file is read again for the scatter brush's image. + let dots = row_id_owned(&mut s, "scatter.png", "brush"); + let changed = png(30, 30, RED); + write(&dir.file("scatter.png"), &changed); + let r = s.execute("links.update", &json!({"ids": [dots]})).unwrap(); + assert_eq!(r["updated"], json!([dots]), "{r}"); + assert_eq!(brush_image(&s, "Specks").link.unwrap().size, Some(changed.len() as u64)); + // Embed: the pattern brush's side tile keeps its pixels and no longer links. + let frame = row_id_owned(&mut s, "side.png", "brush"); + let r = s.execute("links.embed", &json!({"ids": [frame]})).unwrap(); + assert_eq!(r["embedded"], json!([frame]), "{r}"); + assert!(brush_image(&s, "Frame").link.is_none()); + let embedded = s.execute("links.list", &json!({"show": "embedded"})).unwrap(); + assert_eq!(embedded["links"][0]["id"], json!(frame), "{embedded}"); + // Relink All Instances takes the image in the layers and the brush's image of the same file. + let r = s.execute("links.relink", &json!({"ids": [kept.0], "path": dir.file("scatter.png"), "scope": "all"})).unwrap(); + assert_eq!(r["relinked"], json!([kept.0]), "{r}"); + let r = s.execute("links.relink", &json!({"ids": [dots], "path": other, "scope": "all"})).unwrap(); + let mut relinked: Vec = r["relinked"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + relinked.sort(); + let mut both = vec![kept.0, dots]; + both.sort(); + assert_eq!(relinked, both, "{r}"); + assert_eq!(image(&s, kept).link.unwrap().path, other); + // One undo step puts the brushes back as they were. + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(brush_image(&s, "Specks").link.unwrap().path, dir.file("scatter.png")); +} + +/// The id of the `links.list` row of file `name` whose owner is of `kind`. +fn row_id_owned(s: &mut Session, name: &str, kind: &str) -> u64 { + let list = s.execute("links.list", &json!({})).unwrap(); + let row = list["links"].as_array().unwrap().iter().find(|r| r["name"] == name && r["owner"]["kind"] == kind); + row.unwrap_or_else(|| panic!("{name} in {kind}: {list}"))["id"].as_u64().unwrap() +} + +/// A document saved with links in its stored brushes opens with them reported by the ids the list +/// gives them, and a library entry that does not read as a brush is kept as it was. +#[test] +fn links_in_stored_brush_art_open_by_id_and_unreadable_entries_stay() { + let dir = Folder::new("brush-open"); + let (mut s, _) = brush_links(&dir); + let odd = json!({"name": "Odd", "type": "unknown", "art": {"id": 3}}); + s.edit("Odd brush", |d, _| { + if let Some(list) = d.unknown.get_mut(vectorcraft_brush::DOC_KEY).and_then(Value::as_array_mut) { + list.push(odd.clone()); + } + Ok(()) + }) + .unwrap(); + let path = dir.file("poster.vectorcraft"); + save(&mut s, &path); + std::fs::remove_file(dir.file("scatter.png")).unwrap(); + let r = open(&mut s, &path); + let dots = row_id_owned(&mut s, "scatter.png", "brush"); + assert_eq!(r["missingLinks"][0]["ids"], json!([dots]), "{r}"); + assert_eq!(brush_image_id(&s, "Specks"), dots, "the library keeps the ids opening gave"); + let band = row_id_owned(&mut s, "art.png", "brush"); + s.execute("links.embed", &json!({"ids": [band]})).unwrap(); + let doc = &s.doc().unwrap().doc; + let stored = doc.unknown[vectorcraft_brush::DOC_KEY].as_array().unwrap(); + assert_eq!(stored.last(), Some(&odd), "the unreadable entry is left as it was"); + assert!(doc.mounted_art.is_empty()); +} + +/// The Color Mask of an image in a stored brush's art is made again for the new pixels when Update +/// reads the image's changed file. +#[test] +fn updating_an_image_in_stored_brush_art_makes_its_color_mask_again() { + let dir = Folder::new("brush-mask"); + let path = dir.file("logo.png"); + write(&path, &png(12, 10, RED)); + let mut s = session(); + let id = place(&mut s, &path); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let hide_white = json!({"background": "colors", "colors": "#ffffff", "contiguous": false, "tolerance": 0, "softness": 0}); + s.execute("addon.image.colorMask", &hide_white).unwrap(); + s.execute("brush.new", &json!({"type": "scatter", "name": "Masked", "ids": [id.0]})).unwrap(); + s.execute("edit.clear", &json!({"ids": [id.0]})).unwrap(); + write(&path, &png(14, 10, BLUE)); + let row = row_id_owned(&mut s, "logo.png", "brush"); + let r = s.execute("links.update", &json!({"ids": [row]})).unwrap(); + assert_eq!(r["updated"], json!([row]), "{r}"); + let doc = &s.doc().unwrap().doc; + let brush = vectorcraft_brush::find(doc, "Masked").unwrap(); + let mut masks = vec![]; + brush.art()[0].walk(&mut |n| { + if let (NodeKind::Image(im), Some(m)) = (&n.kind, Document::color_mask_of(n)) { + masks.push((m.made_for(im), doc.images.contains_key(&m.key))); + } + }); + assert_eq!(masks, [(true, true)], "the mask is made for the new pixels"); +} + /// An image that Placement Options clip, alone in a group the user made, goes into a new clip group /// inside that group when its file grows, in the layers and in a symbol's art; the user's group /// stays a plain group. diff --git a/crates/engine/src/tests/linkspanel.rs b/crates/engine/src/tests/linkspanel.rs index a9a3a17ec7..a1402cc43f 100644 --- a/crates/engine/src/tests/linkspanel.rs +++ b/crates/engine/src/tests/linkspanel.rs @@ -248,7 +248,42 @@ fn the_list_shows_each_image_with_its_status() { assert_eq!(run(&mut s, "links.list", json!({"show": "missing"}))["links"][0]["id"], linked.0); assert_eq!(run(&mut s, "links.list", json!({"sort": "name"}))["links"][0]["name"], "a.png"); assert!(s.execute("links.list", &json!({"show": "broken"})).is_err()); - assert!(s.execute("links.list", &json!({"sort": "size"})).is_err()); + assert!(s.execute("links.list", &json!({"sort": "date"})).is_err()); +} + +#[test] +fn sort_by_size_lists_the_smallest_file_first() { + let dir = Folder::new("list-size"); + let files = [("a.png", png(600, 300, RED)), ("b.png", png(10, 10, BLUE)), ("c.png", png(100, 100, RED)), ("d.png", png(10, 10, BLUE))]; + let mut s = session(); + for (name, bytes) in &files { + let path = dir.file(name); + write(&path, bytes); + place(&mut s, &path); + } + let e = dir.file("e.png"); + write(&e, &png(1, 1, RED)); + place_embedded(&mut s, &e); + let names = |s: &mut Session| -> Vec { + let l = run(s, "links.list", json!({"sort": "size"})); + l["links"].as_array().unwrap().iter().map(|r| r["name"].as_str().unwrap_or_default().to_string()).collect() + }; + // Smallest first, equal sizes by name, the embedded image (no file) last. + let mut want: Vec<(usize, &str)> = files.iter().map(|(n, b)| (b.len(), *n)).collect(); + want.sort(); + assert!(want[0].0 < want[2].0 && want[2].0 < want[3].0, "{want:?}"); + let mut want: Vec = want.iter().map(|(_, n)| n.to_string()).collect(); + want.push("e.png".into()); + assert_eq!(names(&mut s), want); + // A missing file sorts by the size the document keeps of it. + std::fs::remove_file(dir.file("a.png")).unwrap(); + assert_eq!(names(&mut s), want); + // A modified file sorts by its size now. + let bigger = png(900, 900, BLUE); + assert!(bigger.len() > files[0].1.len()); + write(&dir.file("c.png"), &bigger); + let got = names(&mut s); + assert_eq!(got[got.len() - 2..], ["c.png".to_string(), "e.png".to_string()]); } #[test] diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index abb0bf31eb..1151f83910 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -1979,9 +1979,10 @@ fn fit_to_artwork_bounds_fits_each_artboard_to_its_own_art() { assert_eq!(boards(&s), [Rect::new(100.0, 100.0, 1050.0, 280.0), was[1], was[2]], "the first artboard by default"); } -/// Artboard Options and Fit to Selected Art fail with `no such artboard` on an `index` that names -/// no artboard (past the last, negative, fractional, a string or null), and the artboards stay as -/// they were. Artboard Options needs an `index`; Fit to Selected Art without one fits the first +/// Artboard Options and Fit to Selected Art fail with `no such artboard` on a whole-number `index` +/// past the last artboard, with "`index` must be a whole number" on one that is negative, +/// fractional or a string, and with `missing index` on a null one, and the artboards stay as they +/// were. Artboard Options needs an `index`; Fit to Selected Art without one fits the first /// artboard. #[test] fn artboard_options_and_fit_to_selected_art_refuse_an_index_that_names_no_artboard() { @@ -1992,9 +1993,16 @@ fn artboard_options_and_fit_to_selected_art_refuse_an_index_that_names_no_artboa s.execute("paint.setStroke", &json!({"none": true})).unwrap(); let boards = |s: &Session| s.doc().unwrap().doc.artboards.iter().map(|a| a.rect).collect::>(); let (was, n) = (boards(&s), undo_len(&s)); - for index in [json!(99), json!(-1), json!(1.5), json!("1"), Value::Null] { + for (index, error) in [ + (json!(99), None), + (json!(-1), Some("`index` must be a whole number")), + (json!(1.5), Some("`index` must be a whole number")), + (json!("1"), Some("`index` must be a whole number")), + (Value::Null, Some("missing index")), + ] { for (cmd, p) in [("artboard.setProps", json!({"index": index, "width": 300})), ("artboard.fitToSelection", json!({"index": index}))] { - assert_eq!(s.execute(cmd, &p).unwrap_err().to_string(), "no such artboard", "{cmd} {p}"); + let want = error.map_or_else(|| "no such artboard".to_string(), |e| format!("invalid parameters for `{cmd}`: {e}")); + assert_eq!(s.execute(cmd, &p).unwrap_err().to_string(), want, "{cmd} {p}"); } } let e = s.execute("artboard.setProps", &json!({"width": 300})).unwrap_err().to_string(); @@ -2226,6 +2234,10 @@ fn type_menu_and_find_commands_refuse_a_param_of_the_wrong_type() { ("type.smartPunctuation", json!({"dashes": "false"}), switch("dashes")), ("type.smartPunctuation", json!({"ellipsis": 0}), switch("ellipsis")), ("type.smartPunctuation", json!({"quotes": "no"}), switch("quotes")), + ("type.smartPunctuation", json!({"fiLigatures": 1}), switch("fiLigatures")), + ("type.smartPunctuation", json!({"flLigatures": "true"}), switch("flLigatures")), + ("type.smartPunctuation", json!({"spaces": "on"}), switch("spaces")), + ("type.smartPunctuation", json!({"fractions": [true]}), switch("fractions")), ("type.smartPunctuation", json!({"scope": 5}), scope.clone()), ("type.smartPunctuation", json!({"scope": "page"}), scope), ("type.changeCase", json!({"case": 5}), string("case")), @@ -3555,12 +3567,154 @@ fn smart_punctuation_with_nothing_to_change_records_no_undo_step() { for id in [t, r] { select_with_a_step_to_redo(&mut s, &[id]); let before = history(&s); - assert_eq!(s.execute("type.smartPunctuation", &json!({})).unwrap(), json!({"changed": 0}), "{id:?}"); + let r = s.execute("type.smartPunctuation", &json!({})).unwrap(); + assert_eq!(r["changed"], 0, "{id:?}"); + assert!(r["replaced"].as_object().unwrap().values().all(|n| n == 0), "{id:?}: {r}"); assert_eq!(history(&s), before, "{id:?}"); } assert_eq!(plain(&s, t), "“Hi” it’s 1–2 and 3—4…"); } +/// Does the face text `font` draws with have a glyph for every character of `chars`? +fn font_covers(font: &str, chars: &str) -> bool { + let face = vectorcraft_text::FontDb::global().face(font, "Regular"); + face.is_some_and(|f| chars.chars().all(|c| f.covers(c))) +} + +/// Every option on: the ligatures, Smart Spaces and Expert Fractions, each counted on its own, in +/// one undo step. Fractions next to a digit, a slash or a decimal part are left as they are. +#[test] +fn smart_punctuation_ligatures_spaces_and_fractions_are_counted() { + let mut s = session(); + assert!(font_covers("Source Sans 3", "\u{FB00}\u{FB01}\u{FB02}\u{FB03}\u{FB04}½¾"), "Source Sans 3 draws the ligatures and fractions"); + let words = "An office's fluffy flow. Then 1/2 and 3/4, not 1/25, 1/2/26 or 1/2.5."; + let t = id_of(&s.execute("text.create", &json!({"x": 50, "y": 50, "text": words, "font": "Source Sans 3"})).unwrap()); + sel(&mut s, &[t]); + let undo = history(&s).0; + let all = json!({"fiLigatures": true, "flLigatures": true, "quotes": true, "spaces": true, "dashes": true, "ellipsis": true, "fractions": true}); + let r = s.execute("type.smartPunctuation", &all).unwrap(); + assert_eq!(plain(&s, t), "An o\u{FB03}ce’s \u{FB02}u\u{FB00}y \u{FB02}ow. Then ½ and ¾, not 1/25, 1/2/26 or 1/2.5."); + let replaced = json!({"fiLigatures": 2, "flLigatures": 2, "quotes": 1, "spaces": 1, "dashes": 0, "ellipses": 0, "fractions": 2}); + assert_eq!(r, json!({"changed": 1, "replaced": replaced})); + assert_eq!(history(&s).0, undo + 1); +} + +/// The ff, fl, ffl option alone leaves fi and ffi as letters (ffi keeps its ff ligature, counted +/// with this option), and the other options are off unless asked for. +#[test] +fn smart_punctuation_fl_ligatures_alone() { + let mut s = session(); + let t = id_of(&s.execute("text.create", &json!({"x": 50, "y": 50, "text": "office fit baffle. 1/2", "font": "Source Sans 3"})).unwrap()); + sel(&mut s, &[t]); + let r = s.execute("type.smartPunctuation", &json!({"flLigatures": true})).unwrap(); + assert_eq!(plain(&s, t), "o\u{FB00}ice fit ba\u{FB04}e. 1/2"); + assert_eq!(r["replaced"], json!({"fiLigatures": 0, "flLigatures": 2, "quotes": 0, "spaces": 0, "dashes": 0, "ellipses": 0, "fractions": 0})); +} + +/// A ligature or a fraction the run's font has no glyph for stays as its letters, while the run's +/// other replacements still happen. +#[test] +fn smart_punctuation_skips_ligatures_and_fractions_the_font_lacks() { + let mut s = session(); + let mono = "JetBrains Mono"; + assert!(!font_covers(mono, "\u{FB01}") && !font_covers(mono, "⅐"), "{mono} has no fi ligature or one-seventh"); + let t = id_of(&s.execute("text.create", &json!({"x": 50, "y": 50, "text": "fit 1/7 a--b", "font": mono})).unwrap()); + sel(&mut s, &[t]); + let r = s.execute("type.smartPunctuation", &json!({"fiLigatures": true, "fractions": true})).unwrap(); + assert_eq!(plain(&s, t), "fit 1/7 a–b"); + let counts = (&r["replaced"]["fiLigatures"], &r["replaced"]["fractions"], &r["replaced"]["dashes"]); + assert_eq!(counts, (&json!(0), &json!(0), &json!(1))); +} + +/// A fraction at the end of a run is checked against the start of the next run: 1/25 and 1/2.5 +/// split after their 1/2 stay as they are, and a 1/2 the next run's space ends is replaced. +#[test] +fn expert_fractions_look_past_the_end_of_a_run() { + let mut s = session(); + let t = id_of(&s.execute("text.create", &json!({"x": 50, "y": 50, "text": "1/25 1/2.5 1/2 x", "font": "Source Sans 3"})).unwrap()); + for (start, end) in [(0, 3), (5, 8), (11, 14)] { + s.execute("text.setRangeStyle", &json!({"id": t.0, "start": start, "end": end, "size": 30})).unwrap(); + } + sel(&mut s, &[t]); + let r = s.execute("type.smartPunctuation", &json!({"fractions": true})).unwrap(); + assert_eq!(plain(&s, t), "1/25 1/2.5 ½ x"); + assert_eq!(r["replaced"]["fractions"], 1); +} + +/// An inline graphic separates the text on either side of it: the space after it is not a second +/// space after the period before it, and the digit before it does not stop a fraction after it. +#[test] +fn an_inline_graphic_separates_smart_spaces_and_fractions() { + let mut s = session(); + let r = rect(&mut s, 600.0, 500.0, 10.0, 10.0); + sel(&mut s, &[r]); + s.execute("symbol.new", &json!({"name": "Mark"})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + let t = id_of(&s.execute("text.create", &json!({"x": 50, "y": 50, "text": "A. B 71/2", "font": "Source Sans 3"})).unwrap()); + s.execute("text.insertInline", &json!({"id": t.0, "at": 7, "symbol": "Mark"})).unwrap(); + s.execute("text.insertInline", &json!({"id": t.0, "at": 3, "symbol": "Mark"})).unwrap(); + let texts = |s: &Session| match node(s, t).kind { + NodeKind::Text(o) => o.runs.iter().map(|r| if r.inline.is_some() { "[g]".to_string() } else { r.text.clone() }).collect::(), + _ => String::new(), + }; + assert_eq!(texts(&s), "A. [g] B 7[g]1/2"); + sel(&mut s, &[t]); + let r = s.execute("type.smartPunctuation", &json!({"spaces": true, "fractions": true})).unwrap(); + assert_eq!(texts(&s), "A. [g] B 7[g]½"); + assert_eq!((&r["replaced"]["spaces"], &r["replaced"]["fractions"]), (&json!(0), &json!(1))); +} + +/// Smart Spaces keeps one space after each period, also when the spaces start in the next run, +/// and leaves single spaces and spaces after other characters alone. +#[test] +fn smart_spaces_keeps_one_space_after_a_period() { + let mut s = session(); + let t = text(&mut s, "A. B. C. D E"); + // "C." is in a run of its own, and the spaces after it start the next one. + s.execute("text.setRangeStyle", &json!({"id": t.0, "start": 8, "end": 10, "size": 30})).unwrap(); + assert!(matches!(node(&s, t).kind, NodeKind::Text(ref o) if o.runs.len() > 1)); + sel(&mut s, &[t]); + let r = s.execute("type.smartPunctuation", &json!({"spaces": true, "quotes": false, "dashes": false, "ellipsis": false})).unwrap(); + assert_eq!(plain(&s, t), "A. B. C. D E"); + assert_eq!(r["replaced"]["spaces"], 2); +} + +/// Ruby stays on the characters it was set on when Smart Punctuation makes the text before them +/// longer (curly quotes) or shorter (Smart Spaces), and no replacement takes in characters on both +/// sides of a ruby span's end: the fi with ruby on its i stays as letters, and a second space after +/// a period with ruby of its own stays. +#[test] +fn smart_punctuation_keeps_ruby_on_its_characters() { + let mut s = session(); + let spans = |s: &Session, t| match node(s, t).kind { + NodeKind::Text(o) => o.ruby.iter().map(|r| (r.start, r.end)).collect::>(), + _ => vec![], + }; + let t = id_of(&s.execute("text.create", &json!({"x": 50, "y": 50, "text": "'A'. base fit X. Y", "font": "Source Sans 3"})).unwrap()); + sel(&mut s, &[t]); + for (start, end) in [(1, 2), (6, 10), (12, 13), (18, 19)] { + s.execute("type.ruby", &json!({"text": "r", "start": start, "end": end})).unwrap(); + } + let r = s.execute("type.smartPunctuation", &json!({"spaces": true, "fiLigatures": true})).unwrap(); + assert_eq!(plain(&s, t), "‘A’. base fit X. Y"); + assert_eq!((&r["replaced"]["spaces"], &r["replaced"]["fiLigatures"]), (&json!(1), &json!(0))); + let text = plain(&s, t); + let on: Vec<&str> = spans(&s, t).into_iter().map(|(a, b)| &text[a..b]).collect(); + assert_eq!(on, ["A", "base", "i", " "]); +} + +/// Expert Fractions leaves a fraction next to a digit of another script as it is. +#[test] +fn expert_fractions_skip_fractions_next_to_digits_of_any_script() { + let mut s = session(); + let words = "\u{662}1/2 1/2\u{662} 1/2.\u{662} 1/2"; + let t = id_of(&s.execute("text.create", &json!({"x": 50, "y": 50, "text": words, "font": "Source Sans 3"})).unwrap()); + sel(&mut s, &[t]); + let r = s.execute("type.smartPunctuation", &json!({"fractions": true})).unwrap(); + assert_eq!(plain(&s, t), "\u{662}1/2 1/2\u{662} 1/2.\u{662} ½"); + assert_eq!(r["replaced"]["fractions"], 1); +} + #[test] fn convert_point_area_roundtrip() { let mut s = session(); diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index 209d22a42a..094f634799 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -683,6 +683,9 @@ fn the_new_document_links_from_the_profile_file() { /// is a warning. #[test] fn a_profile_brings_the_color_profile_its_file_carries() { + if !super::in_own_process("tests::newdoc::a_profile_brings_the_color_profile_its_file_carries") { + return; + } use vectorcraft_color::cms; let (mut s, dir) = with_profiles("icc"); let builtin = cms::profiles().into_iter().find(|p| p.kind == cms::ProfileKind::Rgb && p.builtin && p.name != cms::SRGB).unwrap(); diff --git a/crates/engine/src/tests/objexpand.rs b/crates/engine/src/tests/objexpand.rs index c8b51033fe..3788185ae6 100644 --- a/crates/engine/src/tests/objexpand.rs +++ b/crates/engine/src/tests/objexpand.rs @@ -257,6 +257,27 @@ fn shadows_under_a_groups_or_an_objects_transform_expand_appearance_as_the_canva } } +/// Each copy of a Transform effect draws the drop shadow listed before the effect under itself, +/// scaled with it, and Expand Appearance keeps those shadows: the square (20..40) has its shadow +/// 20 pt to its right, and its copy scaled 200 % and moved 80 pt down (10..50 across, 90..130 +/// down) has its own 40 pt to its right. +#[test] +fn each_copys_shadow_expands_as_the_canvas_draws_it() { + let mut s = session(); + run(&mut s, "shape.rectangle", json!({"x": 20, "y": 20, "width": 20, "height": 20})); + run(&mut s, "paint.setFill", json!({"color": "#ff0000"})); + run(&mut s, "paint.setStroke", json!({"none": true})); + let shadow = json!({"x": 20, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"}); + run(&mut s, "effect.apply", json!({"effect": "stylize.dropShadow", "params": shadow})); + run(&mut s, "effect.apply", json!({"effect": "distort.transform", "params": {"scaleH": 200, "scaleV": 200, "moveV": 80, "copies": 1}})); + let before = render(&s); + assert_eq!(before.pixel(70, 110), [0, 255, 0, 255], "the copy's shadow"); + run(&mut s, "effect.expandAppearance", json!({})); + let after = render(&s); + let diff = differing(&before, &after, 64); + assert_eq!(diff, 0, "{diff} pixels differ"); +} + /// A group's Transform effect runs after its member's own Offset Path in Expand Appearance as on /// the canvas: the 100 pt square offset to 120 pt and scaled by half expands 60 pt wide. #[test] @@ -754,6 +775,78 @@ fn create_outlines_draws_the_type_objects_own_paint() { assert!(differing(&before, &render(&session()), 24) > 1000, "the type paints something"); } +/// Selected type "HIH" at 40 pt with ruby, underlined and struck through, its characters filled +/// with `fill` (a `paint.setFill` param) and stroked 2 pt wide, then scaled to 150% and rotated 20 +/// degrees (the stroke keeps its 2 pt, which is 4/3 pt in text space). +fn transformed_gradient_type(s: &mut Session, fill: Value) -> NodeId { + let t = run(s, "text.create", json!({"x": 30, "y": 110, "text": "HIH", "size": 40}))["id"].as_u64().unwrap(); + run(s, "select.set", json!({"ids": [t]})); + run(s, "type.ruby", json!({"text": "ab"})); + run(s, "text.setFormat", json!({"ids": [t], "underline": true, "strikethrough": true})); + run(s, "paint.setFill", fill); + run(s, "paint.setStroke", json!({"color": "#008000"})); + run(s, "stroke.set", json!({"weight": 2})); + run(s, "object.scale", json!({"ids": [t], "sx": 150, "sy": 150})); + run(s, "object.rotate", json!({"ids": [t], "angle": 20})); + NodeId(t) +} + +/// Create Outlines draws what the type drew: a gradient on the characters that has no vector of +/// its own keeps one gradient across every glyph, ruby glyph and bar, fitted to the layout's box, +/// and one with a vector keeps it where it was, both with the type's scale and rotation. The +/// characters' stroke keeps the weight it was drawn at. +#[test] +fn create_outlines_keeps_a_character_gradient_across_the_type() { + let placed = json!({"gradient": {"kind": "linear", "start": [40, 100], "end": [110, 100], + "stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]}}); + for fill in [red_blue(), placed] { + let mut s = session(); + let t = transformed_gradient_type(&mut s, fill.clone()); + let NodeKind::Text(text) = &node(&s, t).kind else { panic!("not type") }; + assert!(!text.ruby.is_empty() && text.runs.iter().all(|r| r.style.underline && r.style.strikethrough), "{fill}"); + // The characters' stroke is kept in text space and drawn scaled by the type's transform. + let weight = text.runs[0].style.stroke_layer().width; + let drawn = weight * vectorcraft_doc::Scaling::factor(text.xf).unwrap_or(1.0); + assert!((drawn - weight).abs() > 0.1, "the type's transform scales: {weight} {drawn}"); + let before = render(&s); + let g = run(&mut s, "type.createOutlines", json!({}))["ids"][0].as_u64().unwrap(); + let after = render(&s); + let n = differing(&before, &after, 24); + assert!(n < 60, "{fill}: {n} pixels differ"); + assert!(differing(&before, &render(&session()), 24) > 1000, "the type paints something"); + // Every glyph, ruby glyph and bar takes the same gradient, placed, and the stroke at the + // weight it was drawn at. + let mut gradients = vec![]; + let mut widths = vec![]; + node(&s, NodeId(g)).walk(&mut |c: &Node| { + if let Paint::Gradient(gr) = c.appearance.fill_paint() { + gradients.push(gr.clone()); + } + widths.extend(c.appearance.stroke().map(|st| st.width)); + }); + assert!(gradients.len() >= 6, "{fill}: three glyphs, ruby and two bars: {}", gradients.len()); + assert!(gradients.iter().all(|gr| gr.is_placed() && *gr == gradients[0]), "{fill}: {gradients:?}"); + assert!(widths.len() == gradients.len() && widths.iter().all(|w| (w - drawn).abs() < 1e-9), "{fill}: {drawn} {widths:?}"); + } +} + +/// Expand outlines the type before its fills expand, so a gradient on its characters that has no +/// vector of its own expands across the whole type, as the canvas draws it, and the query reports +/// it. +#[test] +fn expand_keeps_a_character_gradient_across_the_type() { + let mut s = session(); + transformed_gradient_type(&mut s, red_blue()); + let info = run(&mut s, "object.expand.info", json!({})); + assert_eq!((info["gradient"].clone(), info["fill"].clone(), info["object"].clone()), (json!(true), json!(true), json!(true)), "{info}"); + let before = render(&s); + run(&mut s, "object.expand", json!({})); + let after = render(&s); + assert_eq!(gradients_and_type(&s), (0, 0), "outlined and expanded"); + let d = mean_diff(&before, &after); + assert!(d < 0.5, "{d}"); +} + /// `object.expand.info` reports the type object's own stroke, pattern fill and gradient fill, which /// Object turns into paths of its whole outline: a gradient only when that outline's box needs no /// more runs than are written. diff --git a/crates/engine/src/tests/package.rs b/crates/engine/src/tests/package.rs index e61c4bb4a4..952693d7c1 100644 --- a/crates/engine/src/tests/package.rs +++ b/crates/engine/src/tests/package.rs @@ -90,6 +90,38 @@ fn two_links_and_a_font_are_collected_and_relinked() { assert!(s.doc().unwrap().doc.images.values().all(|b| !b.is_proxy()), "the copies' pixels"); } +/// A file linked only from a stored brush's art is copied, and the packaged document's brush +/// links to the copy. +#[test] +fn a_file_linked_from_a_stored_brush_is_collected_and_relinked() { + let dir = Folder::new("package-brush"); + let file = dir.file("art/leaf.png"); + write(&file, &png(40, 20, RED)); + let mut s = session(); + let id = place(&mut s, &file); + run(&mut s, "brush.new", json!({"type": "scatter", "name": "Leaves Here", "ids": [id.0]})); + run(&mut s, "edit.clear", json!({"ids": [id.0]})); + save(&mut s, &dir.file("poster.vectorcraft")); + let out = dir.file("out"); + let r = run(&mut s, "file.package", json!({"folder": out, "copyFonts": false})); + let files: Vec<&str> = r["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap()).collect(); + assert!(files.contains(&"Links/leaf.png"), "{r}"); + let root = std::path::Path::new(&out).join("poster Folder"); + std::fs::remove_dir_all(dir.0.join("art")).unwrap(); + let r = open(&mut s, &root.join("poster.vectorcraft").to_string_lossy()); + assert_eq!(r["missingLinks"], json!([]), "{r}"); + let brush = vectorcraft_brush::find(&s.doc().unwrap().doc, "Leaves Here").unwrap(); + let mut paths = vec![]; + brush.art()[0].walk(&mut |n| { + if let vectorcraft_doc::NodeKind::Image(im) = &n.kind { + paths.push(im.link.as_ref().map(|l| (l.path.clone(), l.relative.clone()))); + } + }); + let [Some((path, relative))] = paths.as_slice() else { panic!("{paths:?}") }; + assert!(std::path::Path::new(path).starts_with(root.join("Links")), "{path}"); + assert_eq!(relative.as_deref(), Some("Links/leaf.png")); +} + #[test] fn an_unsaved_document_cant_be_packaged() { let mut s = session(); diff --git a/crates/engine/src/tests/panelcmds.rs b/crates/engine/src/tests/panelcmds.rs index 8174cf36d1..715bf2b8ce 100644 --- a/crates/engine/src/tests/panelcmds.rs +++ b/crates/engine/src/tests/panelcmds.rs @@ -492,9 +492,11 @@ fn new_and_renamed_artboards_trim_their_names() { assert_eq!(names(&s), ["Back", "Artboard 2", "Artboard 3", "Artboard 4"]); } -/// Duplicate, Copy and Cut Artboard and Move Artboard Up/Down fail with `no such artboard` on an -/// `index` that names no artboard (past the last, negative, fractional, a string or null), and the -/// artboards, the art and the clipboard stay as they were. +/// Duplicate, Copy and Cut Artboard and Move Artboard Up/Down fail with `no such artboard` on a +/// whole-number `index` past the last artboard, with "`index` must be a whole number" on one that +/// is negative, fractional, a string, true or a list, and with `missing index` on a null one, +/// instead of acting on the Artboard tool's active artboard. The artboards, the art and the +/// clipboard stay as they were. #[test] fn artboard_copies_refuse_an_index_that_names_no_artboard() { let mut s = session(); @@ -502,10 +504,22 @@ fn artboard_copies_refuse_an_index_that_names_no_artboard() { s.execute("artboard.new", &json!({})).unwrap(); s.set_tool_options(Some("artboard"), json!({"active": 1}).as_object().unwrap()); let (was, n) = (boards(&s), s.doc().unwrap().history.undo.len()); - for index in [json!(99), json!(-1), json!(1.5), json!("1"), serde_json::Value::Null] { + let not_whole = Some("`index` must be a whole number"); + let cases = [ + (json!(99), None), + (json!(u64::MAX), None), + (json!(-1), not_whole), + (json!(1.5), not_whole), + (json!("1"), not_whole), + (json!(true), not_whole), + (json!([1]), not_whole), + (serde_json::Value::Null, Some("missing index")), + ]; + for (index, error) in cases { for cmd in ["artboard.duplicate", "artboard.copy", "artboard.cut", "artboard.reorder"] { let p = if cmd == "artboard.reorder" { json!({"index": index, "to": 0}) } else { json!({"index": index}) }; - assert_eq!(s.execute(cmd, &p).unwrap_err().to_string(), "no such artboard", "{cmd} {p}"); + let want = error.map_or_else(|| "no such artboard".to_string(), |e| format!("invalid parameters for `{cmd}`: {e}")); + assert_eq!(s.execute(cmd, &p).unwrap_err().to_string(), want, "{cmd} {p}"); } } let st = s.doc().unwrap(); @@ -513,6 +527,90 @@ fn artboard_copies_refuse_an_index_that_names_no_artboard() { assert!(s.clipboard.nodes.is_empty() && s.clipboard.artboards.is_empty(), "nothing copied"); } +/// The artboard commands that take `indices` (and `selectedArtboards`, a replay of the journal) +/// name the fault: a value that is not a list, an empty list and a list with an entry that is not a +/// whole number each have their own message naming the key, and a whole number past the last +/// artboard is `no such artboard`, also when another entry is malformed after it. The artboards, +/// the art, the undo history and the clipboard stay as they were. +#[test] +fn artboard_lists_name_the_fault_and_the_key() { + let mut s = session(); + rect(&mut s); + s.execute("artboard.new", &json!({})).unwrap(); + let (was, n) = (boards(&s), s.doc().unwrap().history.undo.len()); + let cmds = [ + ("artboard.duplicate", json!({})), + ("artboard.copy", json!({})), + ("artboard.cut", json!({})), + ("artboard.rename", json!({"name": "A"})), + ("artboard.switchOrientation", json!({})), + ("artboard.delete", json!({})), + ("artboard.fitToArt", json!({})), + ("artboard.move", json!({"dx": 10, "dy": 0})), + ("artboard.align", json!({"horizontal": "left"})), + ]; + for key in ["indices", "selectedArtboards"] { + let cases = [ + (json!(null), format!("`{key}` must be a list of artboard indices")), + (json!(1), format!("`{key}` must be a list of artboard indices")), + (json!("0,1"), format!("`{key}` must be a list of artboard indices")), + (json!([]), format!("`{key}` must be a non-empty list of artboard indices")), + (json!([0, -1]), format!("`{key}` must contain whole numbers")), + (json!([0, 1.5]), format!("`{key}` must contain whole numbers")), + (json!(["1"]), format!("`{key}` must contain whole numbers")), + (json!([null]), format!("`{key}` must contain whole numbers")), + (json!([9, "1"]), format!("`{key}` must contain whole numbers")), + (json!([0, 9]), "no such artboard".to_string()), + ]; + for (cmd, base) in &cmds { + if key == "selectedArtboards" && matches!(*cmd, "artboard.delete" | "artboard.fitToArt" | "artboard.move") { + continue; + } + for (value, want) in &cases { + let mut p = base.clone(); + p[key] = value.clone(); + let want = if want.starts_with('`') { format!("invalid parameters for `{cmd}`: {want}") } else { want.clone() }; + assert_eq!(s.execute(cmd, &p).unwrap_err().to_string(), want, "{cmd} {p}"); + } + } + } + let st = s.doc().unwrap(); + assert_eq!((boards(&s), st.doc.layers[0].children().unwrap().len(), st.history.undo.len()), (was, 1, n)); + assert!(s.clipboard.nodes.is_empty() && s.clipboard.artboards.is_empty(), "nothing copied"); +} + +/// Align, Distribute and Distribute Spacing for artboards name the key that holds a malformed +/// artboard to align to (`artboard` or `activeArtboard`), not `index`; a null one is left out, and +/// a whole number past the last artboard is `no such artboard`. +#[test] +fn artboard_align_names_the_key_of_a_malformed_reference() { + let mut s = session(); + s.execute("artboard.new", &json!({})).unwrap(); + s.execute("artboard.new", &json!({})).unwrap(); + let cmds = [ + ("artboard.align", json!({"indices": [0, 1, 2], "horizontal": "left", "to": "artboard"})), + ("artboard.distribute", json!({"indices": [0, 1, 2], "horizontal": "left", "to": "artboard"})), + ("artboard.distributeSpacing", json!({"indices": [0, 1, 2], "to": "artboard"})), + ]; + for (cmd, base) in &cmds { + for key in ["artboard", "activeArtboard"] { + let (was, n) = (boards(&s), s.doc().unwrap().history.undo.len()); + for value in [json!(-1), json!(1.5), json!("1"), json!(true)] { + let mut p = base.clone(); + p[key] = value; + let want = format!("invalid parameters for `{cmd}`: `{key}` must be a whole number"); + assert_eq!(s.execute(cmd, &p).unwrap_err().to_string(), want, "{cmd} {p}"); + } + let mut p = base.clone(); + p[key] = json!(9); + assert_eq!(s.execute(cmd, &p).unwrap_err().to_string(), "no such artboard", "{cmd} {p}"); + assert_eq!((boards(&s), s.doc().unwrap().history.undo.len()), (was, n), "{cmd} {key}: nothing moved"); + p[key] = json!(null); + s.execute(cmd, &p).unwrap(); + } + } +} + /// Artboard Options, Move Artboard, Duplicate Artboards, Copy Artboard and Cut Artboard refuse an /// option given as text or as another value that is not true or false, such as "true", and /// Artboard Options and Move Artboard a position, size or move given as text, such as "10". The diff --git a/crates/engine/src/tests/persp_infer.rs b/crates/engine/src/tests/persp_infer.rs new file mode 100644 index 0000000000..79569a2437 --- /dev/null +++ b/crates/engine/src/tests/persp_infer.rs @@ -0,0 +1,273 @@ +//! Automatic Plane Positioning: Shift held over an anchor point of art in perspective or over a +//! gridline intersection moves the active plane through it for now (`perspective.plane.infer`), +//! the two Perspective Grid Options that turn the targets on and off, and what ends it. + +use serde_json::json; +use vectorcraft_geom::{Point, Vec2}; +use vectorcraft_tools::distort::perspective::{PerspectiveGrid, Plane}; +use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey}; + +use crate::tests_persp_select::{attached, bounds_of, drag, grid, persp_session, plane_pts, undo_len}; +use crate::*; + +fn shift() -> Mods { + Mods { shift: true, ..Default::default() } +} + +/// The top anchor of path `id` (on the right wall at depth 0): its page point and its height. +fn top_anchor(s: &Session, id: NodeId) -> (Point, f64) { + let page: Vec = s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().anchors().map(|(_, _, a)| a.p).collect(); + let plane = plane_pts(s, id, Plane::Right, 0.0); + page.into_iter().zip(plane).map(|(p, q)| (p, q.y)).max_by(|a, b| a.1.total_cmp(&b.1)).unwrap() +} + +fn hover(s: &mut Session, p: Point, mods: Mods) { + s.pointer(&PointerEvent::new(PointerKind::Move, p.x, p.y).with_mods(mods), ViewInfo::default()).unwrap(); +} + +fn revision(s: &Session) -> u64 { + s.doc().unwrap().revision +} + +#[test] +fn shift_over_an_anchor_holds_the_active_plane_at_its_height_until_an_object_is_drawn() { + let (mut s, id) = persp_session(); + let v = ViewInfo::default(); + let (anchor, height) = top_anchor(&s, id); + assert!(height > 10.0, "{height}"); + s.execute("perspective.plane.set", &json!({"plane": "ground"})).unwrap(); + s.select_tool("perspectiveSelection", v).unwrap(); + let steps = undo_len(&s); + // Without Shift the pointer only hovers. + hover(&mut s, anchor, Mods::default()); + assert_eq!(grid(&s).inferred, None); + hover(&mut s, anchor, shift()); + let g = grid(&s); + assert!(g.inferred.is_some()); + assert!((g.offset(Plane::Ground) - height).abs() < 1e-6, "{} {height}", g.offset(Plane::Ground)); + assert_eq!((g.ground_offset, g.shown_planes(), undo_len(&s)), (0.0, vec![Plane::Ground], steps)); + // Held there already, another hover over the anchor changes nothing. + let rev = revision(&s); + hover(&mut s, anchor, shift()); + assert_eq!(revision(&s), rev); + // The Rectangle tool draws on the plane where it is held, and the plane stays put for the drag. + s.select_tool("rectangle", v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 420.0, 400.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 470.0, 430.0), v).unwrap(); + assert!(grid(&s).inferred.is_some(), "held while the object is drawn"); + s.pointer(&PointerEvent::new(PointerKind::Up, 470.0, 430.0), v).unwrap(); + let drawn = s.doc().unwrap().selection.objects[0]; + assert_ne!(drawn, id); + let (plane, depth) = attached(&s, drawn).unwrap(); + assert!(plane == Plane::Ground && (depth - height).abs() < 1e-6, "{plane:?} {depth}"); + // Drawn, the plane is back in its place and the other planes show: one undo step for the drag. + let g = grid(&s); + assert_eq!((g.inferred, g.offset(Plane::Ground), g.shown_planes().len(), undo_len(&s)), (None, 0.0, 3, steps + 1)); + // Undoing the drag holds the plane again; Escape with the Perspective Selection tool ends that. + s.execute("edit.undo", &json!({})).unwrap(); + assert!(grid(&s).inferred.is_some()); + s.select_tool("perspectiveSelection", v).unwrap(); + s.tool_key(ToolKey::Escape, Mods::default(), v).unwrap(); + assert_eq!(grid(&s).inferred, None); +} + +#[test] +fn shift_during_a_drag_still_constrains_the_move() { + let (mut s, id) = persp_session(); + let v = ViewInfo::default(); + s.select_tool("perspectiveSelection", v).unwrap(); + let before = plane_pts(&s, id, Plane::Right, 0.0); + let h = grid(&s).homography(Plane::Right).unwrap(); + // From the middle of the object, along the wall and a little up. + let start = bounds_of(&before).center(); + let (from, to) = (h.apply(start).unwrap(), h.apply(start + Vec2::new(80.0, 20.0)).unwrap()); + drag(&mut s, &[from, to, to], shift()); + assert_eq!(grid(&s).inferred, None, "with a button down Shift constrains the move"); + for (a, b) in before.iter().zip(plane_pts(&s, id, Plane::Right, 0.0)) { + assert!((b - *a - Vec2::new(80.0, 0.0)).hypot() < 1e-6, "{a:?} → {b:?}"); + } +} + +#[test] +fn a_gridline_intersection_brings_each_plane_made_active_through_it() { + let (mut s, _) = persp_session(); + let (g, steps) = (grid(&s), undo_len(&s)); + s.execute("perspective.plane.set", &json!({"plane": "left"})).unwrap(); + let at = g.to_page(Plane::Left, Point::new(3.0 * g.cell, 2.0 * g.cell)).unwrap(); + let r = s.execute("perspective.plane.infer", &json!({"at": [at.x, at.y], "tolerance": 1})).unwrap(); + assert_eq!((r["active"].as_bool(), r["source"].as_str(), r["plane"].as_str()), (Some(true), Some("gridline"), Some("left"))); + for (got, want) in r["point"].as_array().unwrap().iter().zip([0.0, 2.0 * g.cell, 3.0 * g.cell]) { + assert!((got.as_f64().unwrap() - want).abs() < 1e-6, "{r}"); + } + for (plane, want) in [("ground", 2.0 * g.cell), ("right", 3.0 * g.cell), ("left", 0.0)] { + s.execute("perspective.plane.set", &json!({"plane": plane})).unwrap(); + let r = s.execute("perspective.plane.infer", &json!({})).unwrap(); + assert!((r["offset"].as_f64().unwrap() - want).abs() < 1e-6 && r["active"] == json!(true) && r.get("source").is_none(), "{plane}: {r}"); + } + let held = grid(&s); + assert_eq!((held.left_offset, held.right_offset, held.ground_offset, undo_len(&s)), (0.0, 0.0, 0.0, steps)); + // Nothing within reach leaves the plane where it is held. + let rev = revision(&s); + let mid = held.to_page(Plane::Left, Point::new(3.5 * g.cell, 2.5 * g.cell)).unwrap(); + let r = s.execute("perspective.plane.infer", &json!({"at": [mid.x, mid.y], "tolerance": 0.5})).unwrap(); + assert!(r["active"] == json!(true) && r.get("source").is_none() && revision(&s) == rev, "{r}"); + // With no active plane nothing is held. + s.execute("perspective.plane.set", &json!({"plane": "none"})).unwrap(); + assert_eq!(grid(&s).inferred, None); + assert!(s.execute("perspective.plane.infer", &json!({"at": [at.x, at.y]})).is_err(), "no active plane"); + assert_eq!(s.execute("perspective.plane.infer", &json!({})).unwrap()["active"], json!(false)); +} + +#[test] +fn the_two_options_turn_the_targets_on_and_off_and_are_kept() { + let (mut s, id) = persp_session(); + assert!(s.prefs.perspective_widget.anchor_point && s.prefs.perspective_widget.gridline_intersection, "both on by default"); + let (anchor, _) = top_anchor(&s, id); + let infer = |s: &mut Session| s.execute("perspective.plane.infer", &json!({"at": [anchor.x, anchor.y], "tolerance": 0.01})); + assert_eq!(infer(&mut s).unwrap()["source"], json!("anchor")); + s.execute("perspective.plane.infer", &json!({"clear": true})).unwrap(); + let r = s.execute("perspective.widget.options", &json!({"anchorPoint": false})).unwrap(); + assert_eq!((r["anchorPoint"].as_bool(), r["gridlineIntersection"].as_bool(), r["show"].as_bool()), (Some(false), Some(true), Some(true))); + assert!(infer(&mut s).unwrap().get("source").is_none(), "the anchor is no target now"); + assert_eq!(grid(&s).inferred, None); + let back: Prefs = serde_json::from_value(serde_json::to_value(&s.prefs).unwrap()).unwrap(); + assert!(!back.perspective_widget.anchor_point && back.perspective_widget.gridline_intersection); + s.execute("perspective.widget.options", &json!({"gridlineIntersection": false})).unwrap(); + assert!(infer(&mut s).is_err(), "both off"); + for bad in [json!({"anchorPoint": "yes"}), json!({"gridlineIntersection": 1})] { + assert!(s.execute("perspective.widget.options", &bad).is_err(), "{bad}"); + } + assert!(!s.prefs.perspective_widget.anchor_point, "a refused value changes nothing"); + s.execute("prefs.set", &json!({"key": "perspectiveWidget", "value": {"anchorPoint": true}})).unwrap(); + assert!(s.prefs.perspective_widget.anchor_point && !s.prefs.perspective_widget.gridline_intersection); + // Preferences saved before the options existed read as both on. + let old: vectorcraft_tools::distort::perspective::widget::WidgetOptions = serde_json::from_value(json!({"show": false})).unwrap(); + assert!(old.anchor_point && old.gridline_intersection && !old.show); +} + +#[test] +fn bad_params_are_refused_and_leave_the_grid_as_it_is() { + let (mut s, id) = persp_session(); + let (anchor, _) = top_anchor(&s, id); + let rev = revision(&s); + for bad in [ + json!({"at": "here"}), + json!({"at": [1]}), + json!({"at": [anchor.x, anchor.y], "tolerance": -1}), + json!({"at": [anchor.x, anchor.y], "tolerance": "wide"}), + json!({"at": [anchor.x, anchor.y], "clear": true}), + json!({"clear": "yes"}), + ] { + assert!(s.execute("perspective.plane.infer", &bad).is_err(), "{bad}"); + } + assert_eq!((grid(&s).inferred, revision(&s)), (None, rev)); + // Clearing when nothing is held changes nothing. + assert_eq!(s.execute("perspective.plane.infer", &json!({"clear": true})).unwrap()["active"], json!(false)); + assert_eq!(revision(&s), rev); + s.execute("perspective.grid.show", &json!({"visible": false})).unwrap(); + assert!(s.execute("perspective.plane.infer", &json!({"at": [anchor.x, anchor.y]})).is_err(), "hidden grid"); +} + +/// A session whose ground plane is held at the height of the attached rectangle's top anchor. +fn held_session() -> (Session, NodeId, f64) { + let (mut s, id) = persp_session(); + let (anchor, height) = top_anchor(&s, id); + s.execute("perspective.plane.set", &json!({"plane": "ground"})).unwrap(); + let r = s.execute("perspective.plane.infer", &json!({"at": [anchor.x, anchor.y], "tolerance": 0.01})).unwrap(); + assert_eq!(r["source"], json!("anchor")); + (s, id, height) +} + +#[test] +fn attaching_an_object_ends_it_and_the_object_sits_where_the_plane_was_held() { + let (mut s, _, height) = held_session(); + let r = s.execute("shape.rectangle", &json!({"x": 420, "y": 400, "width": 40, "height": 30})).unwrap(); + let flat = NodeId(r["id"].as_u64().unwrap()); + s.execute("perspective.attach", &json!({"ids": [flat.0]})).unwrap(); + let (plane, depth) = attached(&s, flat).unwrap(); + assert!(plane == Plane::Ground && (depth - height).abs() < 1e-6, "{plane:?} {depth}"); + assert_eq!((grid(&s).inferred, grid(&s).ground_offset), (None, 0.0)); + // An attach of nothing, or to a plane it doesn't hold, leaves it held. + let (mut s, ..) = held_session(); + s.execute("perspective.attach", &json!({"ids": []})).unwrap(); + assert!(grid(&s).inferred.is_some()); + let r = s.execute("shape.rectangle", &json!({"x": 420, "y": 400, "width": 40, "height": 30})).unwrap(); + let other = NodeId(r["id"].as_u64().unwrap()); + s.execute("perspective.attach", &json!({"ids": [other.0], "plane": "right"})).unwrap(); + assert_eq!(attached(&s, other).map(|a| a.0), Some(Plane::Right)); + assert!(grid(&s).inferred.is_some()); + // A move of an object already in perspective leaves it held; one brought into perspective ends it. + let (mut s, id, height) = held_session(); + s.execute("perspective.move", &json!({"ids": [id.0], "from": [460, 400], "to": [470, 400]})).unwrap(); + assert!(grid(&s).inferred.is_some()); + let r = s.execute("shape.rectangle", &json!({"x": 420, "y": 400, "width": 40, "height": 30})).unwrap(); + let flat = NodeId(r["id"].as_u64().unwrap()); + s.execute("perspective.move", &json!({"ids": [flat.0], "from": [430, 410], "to": [440, 410]})).unwrap(); + let (plane, depth) = attached(&s, flat).unwrap(); + assert!(plane == Plane::Ground && (depth - height).abs() < 1e-6, "{plane:?} {depth}"); + assert_eq!(grid(&s).inferred, None); +} + +#[test] +fn moving_a_plane_hiding_the_grid_and_reopening_the_file_end_it() { + // A moved plane moves from where it is held and is placed there for good, in one undo step; + // undoing the move holds it again. + let (mut s, _, height) = held_session(); + let steps = undo_len(&s); + s.execute("perspective.plane.move", &json!({"plane": "ground", "by": 10})).unwrap(); + let g = grid(&s); + assert_eq!((g.inferred, undo_len(&s)), (None, steps + 1)); + assert!((g.ground_offset - (height + 10.0)).abs() < 1e-6, "{}", g.ground_offset); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!((grid(&s).inferred.is_some(), grid(&s).ground_offset), (true, 0.0)); + // A refused move leaves it held. + let (mut s, ..) = held_session(); + assert!(s.execute("perspective.plane.move", &json!({"plane": "ground", "offset": 1, "objects": "all"})).is_err()); + assert!(grid(&s).inferred.is_some()); + // A plane dragged while it is held, then the drag canceled, is held again. + let (mut s, ..) = held_session(); + s.begin_interaction("Move Plane").unwrap(); + s.preview("perspective.plane.move", &json!({"plane": "ground", "by": 20})).unwrap(); + assert_eq!(grid(&s).inferred, None); + s.cancel_interaction().unwrap(); + assert!(grid(&s).inferred.is_some()); + // Move Plane to Match Object. + let (mut s, id, _) = held_session(); + s.execute("perspective.plane.matchObject", &json!({"id": id.0})).unwrap(); + assert_eq!((grid(&s).inferred, grid(&s).plane), (None, Plane::Right)); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!((grid(&s).inferred.is_some(), grid(&s).plane), (true, Plane::Ground), "undo holds it again"); + // With the plane placed at the object already, matching only puts the held plane back there. + s.execute("perspective.plane.set", &json!({"plane": "right"})).unwrap(); + assert!(grid(&s).inferred.is_some()); + let steps = undo_len(&s); + s.execute("perspective.plane.matchObject", &json!({"id": id.0})).unwrap(); + assert_eq!((grid(&s).inferred, grid(&s).offset(Plane::Right), undo_len(&s)), (None, 0.0, steps)); + // Hide Grid. + let (mut s, ..) = held_session(); + s.execute("perspective.grid.show", &json!({"visible": false})).unwrap(); + assert_eq!(grid(&s).inferred, None); + // The grid's definition changing leaves it held, and it is not `perspective.grid.set`'s to set. + let (mut s, ..) = held_session(); + let held = grid(&s).inferred; + s.execute("perspective.grid.set", &json!({"cell": 31, "inferred": [1, 2, 3]})).unwrap(); + assert_eq!(grid(&s).inferred, held); + // `perspective.grid.set` hiding the grid or choosing no plane ends it. + for patch in [json!({"visible": false}), json!({"plane": "none"})] { + let (mut s, ..) = held_session(); + s.execute("perspective.grid.set", &patch).unwrap(); + assert_eq!(grid(&s).inferred, None, "{patch}"); + } + // Another preset leaves it held, as other changes to the grid's definition do. + let (mut preset, ..) = held_session(); + let before = grid(&preset).inferred; + preset.execute("perspective.grid.preset", &json!({"kind": 3})).unwrap(); + assert_eq!((grid(&preset).kind, grid(&preset).inferred), (3, before)); + // A file saved while a plane is held opens with the plane in its place. + let saved = vectorcraft_format::save(&s.doc().unwrap().doc, false); + let back = vectorcraft_format::load(&saved).unwrap(); + assert!(PerspectiveGrid::positioning(&back), "the saved file still holds the point"); + s.add_document(back, None); + assert_eq!(grid(&s).inferred, None); + assert_eq!(grid(&s).cell, 31.0); +} diff --git a/crates/engine/src/tests/perspgrid.rs b/crates/engine/src/tests/perspgrid.rs index 07fce547da..4b7c1c2ae4 100644 --- a/crates/engine/src/tests/perspgrid.rs +++ b/crates/engine/src/tests/perspgrid.rs @@ -150,6 +150,42 @@ fn built_in_views_apply_by_name_or_type() { assert!(s.execute("perspective.grid.preset", &json!({})).is_err()); } +#[test] +fn reapplying_the_current_grid_preset_records_no_undo_step() { + let mut s = session(); + // On a document with no grid defined, a preset defines and shows one: an undo step. + run(&mut s, "perspective.grid.preset", json!({"kind": 2})); + assert_eq!(undo_len(&s), 1); + let g = grid(&s); + // The same preset again, by type or by name, leaves the grid as it is: no undo step. + run(&mut s, "perspective.grid.preset", json!({"kind": 2})); + run(&mut s, "perspective.grid.preset", json!({"name": "[2P-Normal View]"})); + assert_eq!((grid(&s), undo_len(&s)), (g.clone(), 1)); + // Another active plane, or a hidden grid, is set back without an undo step. + run(&mut s, "perspective.plane.set", json!({"plane": "ground"})); + run(&mut s, "perspective.grid.show", json!({"visible": false})); + assert_ne!(grid(&s), g); + run(&mut s, "perspective.grid.preset", json!({"kind": 2})); + assert_eq!((grid(&s), undo_len(&s)), (g, 1)); + // Another preset changes the grid. + run(&mut s, "perspective.grid.preset", json!({"kind": 3})); + assert_eq!((grid(&s).kind, undo_len(&s)), (3, 2)); +} + +#[test] +fn define_grid_with_unchanged_fields_records_no_undo_step() { + let mut s = session(); + // On a document with no grid defined, `perspective.grid.set` stores the grid: an undo step, + // and the grid no longer follows the first artboard. + run(&mut s, "perspective.grid.set", json!({})); + assert_eq!((run(&mut s, "perspective.grid.get", json!({}))["defined"].clone(), undo_len(&s)), (json!(true), 1)); + // The stored grid's own values leave it as it is: no undo step. + let g = grid(&s); + run(&mut s, "perspective.grid.set", json!({})); + run(&mut s, "perspective.grid.set", json!({"cell": g.cell, "horizon": g.horizon})); + assert_eq!((grid(&s), undo_len(&s)), (g, 1)); +} + #[test] fn presets_save_rename_delete_and_protect_the_built_in_ones() { let mut s = session(); @@ -484,7 +520,10 @@ fn the_plane_widget_stays_on_screen_and_takes_clicks_with_any_tool() { click(&mut s, q, view); assert_eq!(grid(&s).plane, Plane::Ground); // Perspective Grid Options move it to another corner or hide it. - assert_eq!(run(&mut s, "perspective.widget.options", json!({"position": "bottomRight"})), json!({"show": true, "position": "bottomRight"})); + assert_eq!( + run(&mut s, "perspective.widget.options", json!({"position": "bottomRight"})), + json!({"show": true, "position": "bottomRight", "anchorPoint": true, "gridlineIntersection": true}) + ); let r = face(&s, view, WidgetCorner::BottomRight, Plane::Left); assert!(r.x > 100.0 + 450.0 && r.y > 50.0 + 300.0, "{r:?}"); click(&mut s, r, view); diff --git a/crates/engine/src/tests/placed_document.rs b/crates/engine/src/tests/placed_document.rs index 2420ef265c..65808d2360 100644 --- a/crates/engine/src/tests/placed_document.rs +++ b/crates/engine/src/tests/placed_document.rs @@ -599,6 +599,100 @@ fn with_link_a_pdf_page_places_linked() { assert!(near(centre_colour(&s.doc().unwrap().doc), RED)); } +/// The colour at the centre of `r` in `doc`. +fn colour_at(doc: &Document, r: Rect) -> [u8; 3] { + let img = vectorcraft_render::Renderer::new().render_region(doc, r, 1.0, true); + let [red, g, b, _] = img.pixel((r.width() / 2.0) as u32, (r.height() / 2.0) as u32); + [red, g, b] +} + +#[test] +fn link_pages_opens_each_picked_pdf_page_as_a_linked_placed_document() { + let dir = Folder::new("open-pdf-link-pages"); + let src = dir.file("flyer.pdf"); + pdf_source(&src, "pdf", &[RED, BLUE, RED], 0); + let mut s = Session::new(); + let r = s.execute("document.open", &json!({"path": src, "linkPages": true, "pages": "2-3"})).unwrap(); + assert_eq!((r["format"].as_str(), r["restored"].as_bool()), (Some("pdf"), Some(false)), "{r}"); + let st = s.doc().unwrap(); + assert_eq!(st.path, None, "Save asks for a name instead of writing over the PDF"); + let d = &st.doc; + let boards: Vec = d.artboards.iter().map(|a| a.rect).collect(); + assert_eq!(boards, [Rect::new(0.0, 0.0, 100.0, 50.0), Rect::new(136.0, 0.0, 236.0, 50.0)]); + let layers: Vec<_> = d.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect(); + assert_eq!(layers, ["Page 2", "Page 3"]); + let mut ids = vec![]; + for (layer, (page, board)) in d.layers.iter().zip([(2, boards[0]), (3, boards[1])]) { + let kids = layer.children().unwrap(); + assert_eq!(kids.len(), 1); + let p = placed(&s, kids[0].id); + assert_eq!((p.link.path.as_str(), p.link.page, p.bounding), (src.as_str(), Some(page), false), "{p:?}"); + assert_eq!(bounds(&s, kids[0].id), board); + ids.push(kids[0].id); + } + assert!(near(colour_at(d, boards[0]), BLUE)); + assert!(near(colour_at(d, boards[1]), RED)); + let links = s.execute("links.list", &json!({})).unwrap()["links"].clone(); + assert_eq!(links.as_array().map(Vec::len), Some(2), "{links}"); + assert!(links.as_array().unwrap().iter().all(|row| row["document"] == true && row["status"] == "ok"), "{links}"); + // Embed makes a page editable art. + s.execute("links.embed", &json!({"ids": [ids[0].0]})).unwrap(); + let d = &s.doc().unwrap().doc; + assert_eq!(d.node(ids[0]).unwrap().kind_label(), "Clip Group"); + assert_eq!(bounds(&s, ids[0]), boards[0]); + assert!(near(colour_at(d, boards[0]), BLUE)); + // Every page, with the art's bounds as the artboard. + s.execute("document.open", &json!({"path": src, "linkPages": true, "cropTo": "bounding"})).unwrap(); + let d = &s.doc().unwrap().doc; + assert_eq!(d.artboards.len(), 3); + assert!(d.layers.iter().flat_map(|l| l.children().unwrap()).all(|n| matches!(&n.kind, NodeKind::PlacedDocument(p) if p.bounding))); +} + +#[test] +fn linked_pages_share_one_copy_of_the_file_and_open_in_the_pages_color_mode() { + use vectorcraft_testkit::pdf::{PdfPage, pdf}; + let dir = Folder::new("open-pdf-link-pages-cmyk"); + let src = dir.file("cmyk.pdf"); + let page = || PdfPage::new(100.0, 50.0, "0 0.5 1 0 k 0 0 100 50 re f"); + write(&src, &pdf(&[page(), page(), page()], None)); + let mut s = Session::new(); + s.execute("document.open", &json!({"path": src, "linkPages": true})).unwrap(); + let d = &s.doc().unwrap().doc; + assert_eq!(d.color_mode, vectorcraft_doc::ColorMode::Cmyk, "pages painted in CMYK open as a CMYK document"); + let blobs: Vec<_> = d.images.values().map(|b| b.bytes.clone()).collect(); + assert_eq!(blobs.len(), 3); + assert!(blobs.iter().all(|b| std::sync::Arc::ptr_eq(b, &blobs[0])), "one copy of the file for every page"); + s.execute("document.open", &json!({"path": src, "linkPages": true, "colorMode": "rgb"})).unwrap(); + assert_eq!(s.doc().unwrap().doc.color_mode, vectorcraft_doc::ColorMode::Rgb, "colorMode wins"); +} + +#[test] +fn link_pages_is_refused_without_a_path_for_other_files_and_with_a_password_or_outlines() { + let dir = Folder::new("open-pdf-link-pages-refused"); + let src = dir.file("flyer.pdf"); + pdf_source(&src, "pdf", &[RED, BLUE], 0); + let bytes = std::fs::read(&src).unwrap(); + let logo = dir.file("logo.vectorcraft"); + source(&logo, 100.0, 50.0, RED, 0); + let mut s = Session::new(); + let cases = [ + (json!({"name": "flyer.pdf", "dataBase64": vectorcraft_format::base64_encode(&bytes), "linkPages": true}), "needs the file's path"), + (json!({"path": logo, "linkPages": true}), "isn't a PDF"), + (json!({"path": src, "linkPages": true, "password": "secret"}), "password"), + (json!({"path": src, "linkPages": true, "textAs": "outlines"}), "textAs: outlines"), + (json!({"path": src, "linkPages": "yes"}), "linkPages must be true or false"), + (json!({"path": src, "linkPages": true, "pages": "3"}), "pages:"), + ]; + for (p, says) in cases { + let e = s.execute("document.open", &p).unwrap_err().to_string(); + assert!(e.contains(says), "{p}: {e}"); + } + assert!(s.documents().is_empty(), "nothing opened"); + // Off, the pages open as editable art. + s.execute("document.open", &json!({"path": src, "linkPages": false})).unwrap(); + assert!(!s.doc().unwrap().doc.has_placed()); +} + #[test] fn a_changed_pdf_is_modified_and_update_links_reads_it_again() { let dir = Folder::new("placed-pdf-update"); @@ -1042,6 +1136,57 @@ fn saving_a_document_refreshes_its_placed_copies_inside_symbols_and_patterns() { assert_eq!(hashes, [hash.clone(), hash], "the symbol's, then the pattern's"); } +/// Saving a document reads it again for its placed copy in the art of a stored brush of another +/// open document, the only place that document shows it. +#[test] +fn saving_a_document_refreshes_its_placed_copy_in_a_stored_brush() { + let dir = Folder::new("placed-refresh-brush"); + let src = dir.file("logo.vectorcraft"); + source(&src, 100.0, 50.0, RED, 0); + let mut s = session(); + let id = place(&mut s, &src); + s.execute("brush.new", &json!({"type": "scatter", "name": "Logos", "ids": [id.0]})).unwrap(); + s.execute("edit.clear", &json!({"ids": [id.0]})).unwrap(); + let parent = s.active_index().unwrap(); + s.execute("document.open", &json!({"path": src})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#1414e6"})).unwrap(); + s.execute("document.save", &json!({})).unwrap(); + let hash = Some(vectorcraft_doc::links::hash_bytes(&std::fs::read(&src).unwrap())); + let doc = &s.documents()[parent]; + assert_eq!(doc.history.undo.last().unwrap().label, "Update Links"); + let brush = vectorcraft_brush::find(&doc.doc, "Logos").unwrap(); + let mut hashes = vec![]; + brush.art()[0].walk(&mut |n| { + if let NodeKind::PlacedDocument(p) = &n.kind { + hashes.push(p.link.hash.clone()); + } + }); + assert_eq!(hashes, [hash]); +} + +/// A placed document kept only in a stored brush's art, whose file is gone and of which the +/// document holds only the preview, is output as its preview with the warning that says so. +#[test] +fn a_placed_document_in_a_stored_brush_without_its_file_is_output_as_its_preview() { + let dir = Folder::new("placed-brush-preview"); + let src = dir.file("logo.vectorcraft"); + // Content of its own: files read are cached by content, and this one is removed. + source(&src, 100.0, 50.0, RED, 3); + let mut s = session(); + let id = place(&mut s, &src); + s.execute("brush.new", &json!({"type": "scatter", "name": "Logos", "ids": [id.0]})).unwrap(); + // The copy in the layers has the save keep only the preview. + let doc_path = dir.file("poster.vectorcraft"); + save(&mut s, &doc_path); + std::fs::remove_file(&src).unwrap(); + let r = open(&mut s, &doc_path); + assert_eq!(r["missingLinks"].as_array().map(Vec::len), Some(1), "{r}"); + s.execute("edit.clear", &json!({"ids": [id.0]})).unwrap(); + let svg = s.execute("document.serialize", &json!({"format": "svg"})).unwrap(); + assert!(svg["warnings"].to_string().contains("1 placed document output as its preview"), "{svg}"); +} + #[test] fn link_info_gives_the_artboards_size_not_pixels() { let dir = Folder::new("placed-info"); diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 499f2d15c6..a294cc9036 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -1921,6 +1921,12 @@ fn disabled_plugins_name_files_outside_the_read_root_by_their_names() { run(&mut s, "plugin.remove", json!({"id": id})); } +/// The files and folders in the plug-in store `dir`, without the file windows lock while they +/// change it. +fn store_files(dir: &std::path::Path) -> usize { + std::fs::read_dir(dir).unwrap().filter(|e| e.as_ref().is_ok_and(|e| e.file_name() != crate::store::DISABLED_LOCK)).count() +} + /// #2541: a plug-in installed in a session with a plug-in store is installed again in the next /// session that attaches the store, and Remove Plug-in takes it out of the store. #[test] @@ -1931,14 +1937,14 @@ fn installed_plugins_are_kept_in_the_store() { let mut s = session(); s.attach_plugin_store(folder.0.clone()); install_wat(&mut s, &src); - assert_eq!(std::fs::read_dir(&folder.0).unwrap().count(), 1, "one file in the store"); + assert_eq!(store_files(&folder.0), 1, "one file in the store"); vectorcraft_plugins::registry::remove(id); let mut next = session(); next.attach_plugin_store(folder.0.clone()); assert!(vectorcraft_plugins::registry::get(id).is_some(), "installed again from the store"); run(&mut next, "plugin.remove", json!({"id": id})); - assert_eq!(std::fs::read_dir(&folder.0).unwrap().count(), 0, "removed from the store"); + assert_eq!(store_files(&folder.0), 0, "removed from the store"); // A file that isn't a plug-in is skipped; the store still attaches. std::fs::write(folder.0.join("broken.wasm"), b"\0asm?").unwrap(); @@ -3274,6 +3280,198 @@ fn a_store_loaded_while_installing_loads_the_new_version() { run(&mut s, "plugin.remove", json!({"id": id})); } +/// A grant of `doc.read` to plug-in `id`, the module with the SHA-256 `hash`. +fn doc_read_grant(id: &str, hash: &str) -> vectorcraft_plugins::permissions::Grant { + serde_json::from_value(json!({"id": id, "hash": hash, "permissions": ["doc.read"]})).unwrap() +} + +/// A session that uses the plug-in store `dir` without loading it, as another process using the +/// same folder does: it doesn't wait for the installs and removals of this process's sessions. +fn other_process(dir: std::path::PathBuf) -> Session { + let mut s = Session::new(); + s.plugin_dir = Some(dir); + s +} + +/// Waits on this thread for a turn on a plug-in store, telling `waiting` before it waits. +fn tell_when_waiting(waiting: std::sync::mpsc::Sender<&'static str>) { + crate::store::WHILE_STORE_LOCKED.set(Some(Box::new(move || { + let _ = waiting.send("waiting"); + }))); +} + +/// The ids `grants.json` in `dir` holds grants for, and the hash of each. +fn stored_grant_hashes(dir: &std::path::Path) -> std::collections::BTreeMap { + let entries: Vec = serde_json::from_slice(&std::fs::read(dir.join("grants.json")).unwrap()).unwrap(); + entries.iter().map(|e| (e["id"].as_str().unwrap().to_string(), e["hash"].as_str().unwrap().to_string())).collect() +} + +/// An install into a `Plug-ins` folder that another process also installs the same id into keeps a +/// module with its own grant: the other process's install waits for this one's turn on the folder, +/// between this install's module and its grant, and then writes both of its own. +#[test] +fn installs_from_two_processes_into_one_store_keep_each_module_with_its_grant() { + use vectorcraft_plugins::permissions::sha256_hex; + let folder = crate::tests_links::Folder::new("plugin-store-installs-take-turns"); + let id = "test.engine.permissions.installsturns"; + let ours = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let theirs = asking(id, r#"["doc.read"]"#, &json!({"objects": [], "documentData": null})); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + + let (said, heard) = std::sync::mpsc::channel::<&'static str>(); + let (handed, other) = std::sync::mpsc::channel(); + let (dir, module) = (folder.0.clone(), theirs.clone()); + crate::cmd::plugin::BEFORE_GRANT_STORED.set(Some(Box::new(move || { + let thread = std::thread::spawn(move || { + tell_when_waiting(said.clone()); + let other = other_process(dir); + let turn = other.plugin_store_turn().unwrap(); + let stored = crate::cmd::plugin::keep_installed(&other, &turn, id, &module, Some(doc_read_grant(id, &sha256_hex(&module)))); + let _ = said.send(if stored { "stored" } else { "not stored" }); + }); + // The other install has written the store, or waits for this one. + let first = heard.recv().unwrap_or("gone"); + let _ = handed.send((first, thread)); + }))); + run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&ours), "grant": ["doc.read"]})); + let (first, thread) = other.recv().unwrap(); + thread.join().unwrap(); + + let module = std::fs::read(s.stored_plugin_file(id).unwrap()).unwrap(); + assert_eq!(stored_grant_hashes(&folder.0).get(id), Some(&sha256_hex(&module)), "the stored grant covers the stored module"); + assert_eq!(module, theirs, "the install that waited wrote last"); + assert_eq!(first, "waiting", "the other install waits for this one"); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// Grants written for two plug-ins into one `Plug-ins` folder by two processes are both kept: the +/// second write reads `grants.json` only once the first has written it. +#[test] +fn grants_written_by_two_processes_into_one_store_keep_both() { + let folder = crate::tests_links::Folder::new("plugin-store-grants-take-turns"); + let (ours, theirs) = ("test.engine.permissions.grantturnsa", "test.engine.permissions.grantturnsb"); + let hash = vectorcraft_plugins::permissions::sha256_hex(b"module"); + let s = other_process(folder.0.clone()); + + let (said, heard) = std::sync::mpsc::channel::<&'static str>(); + let (handed, other) = std::sync::mpsc::channel(); + let (dir, other_hash) = (folder.0.clone(), hash.clone()); + crate::store::AFTER_GRANTS_READ.set(Some(Box::new(move || { + let thread = std::thread::spawn(move || { + tell_when_waiting(said.clone()); + let written = other_process(dir).store_grant(theirs, Some(doc_read_grant(theirs, &other_hash))); + let _ = said.send(if written { "written" } else { "not written" }); + }); + // The other write has written the file, or waits for this one. + let first = heard.recv().unwrap_or("gone"); + let _ = handed.send((first, thread)); + }))); + assert!(s.store_grant(ours, Some(doc_read_grant(ours, &hash))), "the grant is written"); + let (first, thread) = other.recv().unwrap(); + thread.join().unwrap(); + + let kept = stored_grant_hashes(&folder.0); + assert_eq!(kept.keys().map(String::as_str).collect::>(), [ours, theirs], "both grants are kept"); + assert_eq!(first, "waiting", "the other write waits for this one"); +} + +/// A setting a plug-in changes in one process and another setting it changes in a second process +/// using the same `Plug-ins` folder are both kept: the second process waits for the first's turn on +/// the folder and reads what it wrote. The second process is this test run again with +/// `VECTORCRAFT_TEST_PLUGIN_SETTINGS_STORE` naming the folder; it prints when it waits and when it +/// is done. +#[test] +fn settings_changed_by_two_processes_keep_both() { + use std::io::{BufRead, Write}; + use vectorcraft_plugins::storage::Meter; + const CHILD: &str = "VECTORCRAFT_TEST_PLUGIN_SETTINGS_STORE"; + const NAME: &str = "tests::plugins::settings_changed_by_two_processes_keep_both"; + let id = "test.engine.storagetwoprocesses"; + // Nothing a removal kept is moved back, so the storage is made without a turn on the folder. + let attached = |s: &Session| { + s.attach_plugin_storage(&crate::store::StoreTurn::unheld(), id); + vectorcraft_plugins::registry::storage(id).unwrap() + }; + if let Some(dir) = std::env::var_os(CHILD) { + let st = attached(&other_process(std::path::PathBuf::from(dir))); + crate::store::WHILE_STORE_LOCKED.set(Some(Box::new(|| { + println!("settings-child-waiting"); + let _ = std::io::stdout().flush(); + }))); + st.set_setting("theirs", b"2", &mut Meter::unlimited()).unwrap(); + println!("settings-child-done"); + let _ = std::io::stdout().flush(); + return; + } + let folder = crate::tests_links::Folder::new("plugin-settings-two-processes"); + let st = attached(&other_process(folder.0.clone())); + + let (handed, child) = std::sync::mpsc::channel(); + let dir = folder.0.clone(); + crate::store::AFTER_SETTINGS_READ.set(Some(Box::new(move || { + let mut process = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", NAME, "--nocapture", "--test-threads=1"]) + .env(CHILD, &dir) + .stdout(std::process::Stdio::piped()) + .spawn() + .unwrap(); + let mut lines = std::io::BufReader::new(process.stdout.take().unwrap()).lines(); + // The other process has written the settings, or waits for this change. + let first = lines + .by_ref() + .map_while(std::io::Result::ok) + .find_map(|l| ["waiting", "done"].into_iter().find(|said| l.contains(&format!("settings-child-{said}")))); + let _ = handed.send((first, process, lines)); + }))); + st.set_setting("ours", b"1", &mut Meter::unlimited()).unwrap(); + let (first, mut process, lines) = child.recv().unwrap(); + let rest: Vec = lines.map_while(std::io::Result::ok).collect(); + assert!(process.wait().unwrap().success(), "the other process failed: {rest:?}"); + + let file: std::collections::BTreeMap = + serde_json::from_slice(&std::fs::read(crate::store::plugin_data_dir(&folder.0, id).join("settings.json")).unwrap()).unwrap(); + assert_eq!(file.keys().map(String::as_str).collect::>(), ["ours", "theirs"], "both settings are kept"); + assert_eq!(first, Some("waiting"), "the other process waits for this change"); + vectorcraft_plugins::registry::set_storage(id, None); +} + +/// When the `Plug-ins` folder can't be locked (here `disabled.lock` is a folder), `plugin.install` +/// and `plugin.remove` change nothing and say why: the plug-in installed with the id, its grant and +/// the stored module stay as they were. +#[test] +fn a_store_that_cant_be_locked_refuses_installs_and_removals() { + use vectorcraft_plugins::{permissions::sha256_hex, registry}; + let folder = crate::tests_links::Folder::new("plugin-store-not-locked"); + let id = "test.engine.permissions.notlocked"; + let first = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let second = asking(id, r#"["doc.read"]"#, &json!({"objects": [], "documentData": null})); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&first), "grant": ["doc.read"]})); + let lock = folder.0.join(crate::store::DISABLED_LOCK); + std::fs::remove_file(&lock).unwrap(); + std::fs::create_dir(&lock).unwrap(); + let grants = std::fs::read(folder.0.join("grants.json")).unwrap(); + + let update = json!({"dataBase64": vectorcraft_format::base64_encode(&second), "grant": ["doc.read"], "replace": true}); + let refused = s.execute("plugin.install", &update).unwrap_err().to_string(); + assert!(refused.contains(crate::store::STORE_NOT_LOCKED) && refused.contains("nothing was installed"), "{refused}"); + assert_eq!(registry::get(id).map(|p| p.hash().to_string()), Some(sha256_hex(&first)), "the installed plug-in stays"); + assert_eq!(registry::granted(id).map(|g| g.hash), Some(sha256_hex(&first)), "its grant stays"); + assert_eq!(std::fs::read(s.stored_plugin_file(id).unwrap()).unwrap(), first, "the store keeps its module"); + assert_eq!(std::fs::read(folder.0.join("grants.json")).unwrap(), grants, "and its grant"); + + let refused = s.execute("plugin.remove", &json!({"id": id})).unwrap_err().to_string(); + assert!(refused.contains(crate::store::STORE_NOT_LOCKED) && refused.contains("nothing was removed"), "{refused}"); + assert!(registry::get(id).is_some(), "the plug-in stays installed"); + assert!(std::path::Path::new(&s.stored_plugin_file(id).unwrap()).exists(), "and stored"); + + std::fs::remove_dir(&lock).unwrap(); + run(&mut s, "plugin.remove", json!({"id": id})); + assert!(registry::get(id).is_none()); +} + /// Runs the test `name` of this module again in a process of its own → whether this is that /// process. The list of disabled plug-ins is kept for the whole process, and the other tests here /// read it again each time they attach a plug-in store. @@ -3740,7 +3938,7 @@ fn granted_permissions_are_kept_and_folders_skip_the_rest() { let mut third = session(); third.attach_plugin_store(folder.0.clone()); assert!(vectorcraft_plugins::registry::get(id).is_none(), "nobody granted it"); - assert_eq!(std::fs::read_dir(&folder.0).unwrap().count(), 1, "the module stays in the store"); + assert_eq!(store_files(&folder.0), 1, "the module stays in the store"); // The Additional Plug-ins Folder skips it with a note until it is granted. let dir = crate::tests_links::Folder::new("plugin-folder-grants"); @@ -4678,7 +4876,7 @@ fn plugin_storage_is_capped_and_survives_a_damaged_settings_file() { // An id that differs only in case has storage of its own, which removing this one leaves. let upper_id = "test.engine.StorageCaps"; - s.attach_plugin_storage(upper_id); + s.attach_plugin_storage(&s.plugin_store_turn().unwrap(), upper_id); let upper = vectorcraft_plugins::registry::storage(upper_id).unwrap(); assert_eq!(upper.setting("k0", m).unwrap(), None); upper.set_setting("k0", b"upper", m).unwrap(); @@ -4690,13 +4888,13 @@ fn plugin_storage_is_capped_and_survives_a_damaged_settings_file() { // Removing the plug-in closes the storage a run still holds, even one from before the plug-in // was replaced, so nothing is written back. - s.attach_plugin_storage(id); + s.attach_plugin_storage(&s.plugin_store_turn().unwrap(), id); run(&mut s, "plugin.remove", json!({"id": id})); assert_eq!(st.set_setting("zoom", b"again", m), Err(StorageError::Unavailable)); assert_eq!(st.set_cache_entry("tile", b"again", m), Err(StorageError::Unavailable)); assert!(!dir.exists()); assert_eq!(upper.setting("k0", m).unwrap(), Some(b"upper".to_vec())); - s.remove_plugin_storage(upper_id, || true).unwrap(); + s.remove_plugin_storage(&s.plugin_store_turn().unwrap(), upper_id, || true).unwrap(); } /// Files larger than the storage reads are not read: a settings file larger than 1 MiB, although @@ -4874,12 +5072,12 @@ fn removing_a_plugin_drops_its_settings_from_memory() { std::fs::create_dir_all(file.parent().unwrap()).unwrap(); std::fs::write(&file, &bytes).unwrap(); set_modified(&file, written); - s.attach_plugin_storage(id); + s.attach_plugin_storage(&s.plugin_store_turn().unwrap(), id); let st = vectorcraft_plugins::registry::storage(id).unwrap(); let mut m = Meter::unlimited(); assert_eq!(st.setting("zoom", &mut m).unwrap(), Some(b"hello".to_vec())); assert_eq!(m.used(), bytes.len() as u64, "read from the file"); - s.remove_plugin_storage(id, || true).unwrap(); + s.remove_plugin_storage(&s.plugin_store_turn().unwrap(), id, || true).unwrap(); } /// The cache's total stays in memory while the cache folder keeps its time; a write and a clear diff --git a/crates/engine/src/tests/prefs.rs b/crates/engine/src/tests/prefs.rs index d88b8250a2..521d2eabde 100644 --- a/crates/engine/src/tests/prefs.rs +++ b/crates/engine/src/tests/prefs.rs @@ -1978,6 +1978,26 @@ fn highlight_alternate_glyphs_preference_is_off_by_default() { assert!(!s.prefs.highlight_alternate_glyphs); } +/// Preferences › Type › Show Character Alternates: on by default, listed in the Type category, +/// saved with the other preferences, and a value that is not true or false is refused. +#[test] +fn show_character_alternates_preference_is_on_by_default_and_saved() { + let mut s = Session::new(); + assert!(s.prefs.show_character_alternates, "on by default"); + let spec = crate::cmd::prefscmds::PREF_SPECS.iter().find(|p| p.key == "showCharacterAlternates").expect("listed"); + assert_eq!((spec.category, spec.label), ("Type", "Show Character Alternates")); + assert_eq!(s.execute("prefs.get", &json!({"key": "showCharacterAlternates"})).unwrap(), json!(true)); + set_pref(&mut s, "showCharacterAlternates", json!(false)); + assert!(!s.prefs.show_character_alternates); + assert!(s.execute("prefs.set", &json!({"key": "showCharacterAlternates", "value": "yes"})).is_err(), "not a boolean"); + assert!(!s.prefs.show_character_alternates, "a refused value changes nothing"); + let saved: Prefs = serde_json::from_value(serde_json::to_value(&s.prefs).unwrap()).unwrap(); + assert!(!saved.show_character_alternates); + // Preferences saved before the key existed read it as on. + let old: Prefs = serde_json::from_value(json!({"highlightAlternateGlyphs": true})).unwrap(); + assert!(old.show_character_alternates); +} + /// Preferences › Type › Highlight Substituted Fonts: on by default, listed in the Type category, /// and saved with the other preferences. /// diff --git a/crates/engine/src/tests/rasterfilters.rs b/crates/engine/src/tests/rasterfilters.rs index 236580d5b7..521ba0adbf 100644 --- a/crates/engine/src/tests/rasterfilters.rs +++ b/crates/engine/src/tests/rasterfilters.rs @@ -5,6 +5,7 @@ //! as images of the effected object. use serde_json::{Value, json}; +use vectorcraft_color::cms; use vectorcraft_doc::NodeKind; use vectorcraft_geom::Rect; use vectorcraft_render::{Rendered, Renderer}; @@ -142,19 +143,22 @@ fn listed_applied_edited_and_undone() { } } // Numbers far out of range are stored as given and read clamped; the canvas still draws. + // Radial Blur's Blur Center is refused outside 0 to 1 instead. + let center = |id: &str, k: &str| id == "blur.radial" && matches!(k, "centerX" | "centerY"); for (id, _) in EFFECTS { let defaults = vectorcraft_render::effects::default_params(id).unwrap(); let junk: serde_json::Map = defaults .as_object() .unwrap() .iter() - .filter(|(_, v)| v.is_number()) + .filter(|(k, v)| v.is_number() && !center(id, k)) .enumerate() .map(|(i, (k, _))| (k.clone(), json!(if i % 2 == 0 { 1e308 } else { -1e308 }))) .collect(); assert!(!junk.is_empty(), "{id}"); s.execute("effect.apply", &json!({"effect": id, "ids": [g], "params": junk})).unwrap(); } + assert!(s.execute("effect.apply", &json!({"effect": "blur.radial", "ids": [g], "params": {"centerX": 1e308}})).is_err()); let _ = render(&s); let n = s.doc().unwrap().doc.node(NodeId(g)).unwrap().clone(); assert_eq!(n.appearance.effects.len(), 3); @@ -173,16 +177,22 @@ fn each_effect_changes_the_canvas_and_draws_the_same_twice() { EFFECTS.into_iter().chain(ARTISTIC).chain(BRUSH_STROKES).chain(DISTORT).chain(PIXELATE).chain(SKETCH).chain(TEXTURE).chain(VIDEO) { let (mut s, g) = striped(); + // Every color drawn goes through the process-wide color settings. A test that changes them + // runs in a process of its own (`crate::tests::in_own_process`). + let colors = cms::active(); + assert_eq!(cms::active_settings(), cms::ColorSettings::default(), "{id}: another test left the color settings changed"); let plain = render(&s); let params: Value = serde_json::from_str(params).unwrap(); s.execute("effect.apply", &json!({"effect": id, "ids": [g], "params": params})).unwrap(); let a = render(&s); - assert!(mean_diff(&plain, &a) > 0.0005, "{id} shows: {}", mean_diff(&plain, &a)); - assert_eq!(a.pixels, render(&s).pixels, "{id} is deterministic"); + let again = render(&s); // The multithreaded pipeline draws the same. let mut mt = Renderer::new(); mt.threads = 4; let b = mt.render_region(&s.doc().unwrap().doc, Rect::new(0.0, 0.0, 200.0, 200.0), 1.0, true); + assert!(std::sync::Arc::ptr_eq(&colors, &cms::active()), "{id}: another test changed the color settings while this one drew"); + assert!(mean_diff(&plain, &a) > 0.0005, "{id} shows: {}", mean_diff(&plain, &a)); + assert_eq!(a.pixels, again.pixels, "{id} is deterministic"); assert!(mean_diff(&a, &b) < 0.002, "{id}: multithreaded differs by {}", mean_diff(&a, &b)); } } diff --git a/crates/engine/src/tests/saveoptions.rs b/crates/engine/src/tests/saveoptions.rs index a5b19563a9..0f7205eaae 100644 --- a/crates/engine/src/tests/saveoptions.rs +++ b/crates/engine/src/tests/saveoptions.rs @@ -112,6 +112,9 @@ fn a_linked_pngs_bytes_are_embedded() { #[test] fn an_embedded_profile_is_restored() { + if !super::in_own_process("tests::saveoptions::an_embedded_profile_is_restored") { + return; + } let builtin = cms::profiles().into_iter().find(|p| p.kind == cms::ProfileKind::Rgb && p.builtin && p.name != cms::SRGB).unwrap(); let icc = cms::icc_bytes(&builtin.name).unwrap(); let name = format!("Studio RGB {}", std::process::id()); diff --git a/crates/engine/src/tests/svgfilter.rs b/crates/engine/src/tests/svgfilter.rs index 10f0ad75ca..e42d7f9736 100644 --- a/crates/engine/src/tests/svgfilter.rs +++ b/crates/engine/src/tests/svgfilter.rs @@ -715,3 +715,179 @@ fn svg_export_draws_a_filter_svg_1_1_lacks_as_an_image() { assert_eq!((out.contains(" Vec<(String, bool)> { + let listed = run(s, "svgFilter.list", json!({}))["defaults"].as_array().cloned().unwrap_or_default(); + listed.iter().map(|f| (f["name"].as_str().unwrap().to_string(), f["inDocument"].as_bool().unwrap())).collect() +} + +/// Every document lists the default filters without holding them; applying one adds the effect and +/// the document's copy in one undo step. +#[test] +fn a_default_filter_is_listed_and_copied_into_the_document_when_applied() { + use vectorcraft_render::effects::svg_filter::defaults::DEFAULT_FILTERS; + let mut s = session(); + let listed = defaults(&mut s); + assert_eq!(listed.len(), DEFAULT_FILTERS.len()); + assert!(listed.iter().all(|(_, held)| !held), "a new document holds none of them"); + assert!(names(&mut s).is_empty()); + let soft = DEFAULT_FILTERS.iter().find(|f| f.name == "Soft Shadow").unwrap(); + assert_eq!(run(&mut s, "svgFilter.list", json!({}))["defaults"][2], json!({"name": "Soft Shadow", "xml": soft.xml, "inDocument": false})); + let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 50.0)); + run(&mut s, "select.set", json!({"ids": [a.0, b.0]})); + let before = steps(&s); + let r = run(&mut s, "svgFilter.apply", json!({"name": "Soft Shadow"})); + assert_eq!((r["ids"].as_array().unwrap().len(), &r["index"]), (2, &json!(0))); + assert_eq!(steps(&s), before + 1, "the effect and the copy are one step"); + assert_eq!(s.doc().unwrap().history.undo.last().unwrap().label, "SVG Filter"); + assert_eq!(names(&mut s), ["Soft Shadow"]); + assert_eq!(drawn(&s, a), json!(soft.xml)); + assert!(defaults(&mut s).contains(&("Soft Shadow".to_string(), true))); + // Applied again, the document's copy is the filter: nothing more is added. + run(&mut s, "svgFilter.apply", json!({"name": "Soft Shadow", "ids": [a.0]})); + assert_eq!(names(&mut s), ["Soft Shadow"]); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + assert!(names(&mut s).is_empty(), "undo takes the copy back with the effect"); + assert!(s.doc().unwrap().doc.node(a).unwrap().appearance.effects.is_empty()); + run(&mut s, "edit.redo", json!({})); + assert_eq!((names(&mut s), drawn(&s, b)), (vec!["Soft Shadow".to_string()], json!(soft.xml))); + // Nothing to apply it to: no copy and no step. + let mut s = session(); + assert!(s.execute("svgFilter.apply", &json!({"name": "Glow"})).is_err(), "nothing selected"); + assert!(names(&mut s).is_empty()); + assert_eq!(steps(&s), 0); + assert!(err(&mut s, "svgFilter.apply", json!({"name": "glow", "ids": []})).contains("no SVG filter named \"glow\""), "names match exactly"); +} + +/// With a full history, applying a default lets one old step go, as any edit does: the copy joins +/// the step that applied it, and one Undo takes both back. +#[test] +fn a_default_applied_with_a_full_history_is_still_one_step() { + let mut s = session(); + s.active_mut().unwrap().history.limit = 3; + let a = rect(&mut s, 10.0); + rect(&mut s, 30.0); + rect(&mut s, 50.0); + assert_eq!(steps(&s), 3); + run(&mut s, "svgFilter.apply", json!({"name": "Invert", "ids": [a.0]})); + // The application takes one place in the history: only the oldest step went. + assert_eq!(steps(&s), 3); + assert_eq!(s.doc().unwrap().history.undo.last().unwrap().label, "SVG Filter"); + run(&mut s, "edit.undo", json!({})); + assert!(names(&mut s).is_empty(), "the copy is undone with the effect"); + assert!(s.doc().unwrap().doc.node(a).unwrap().appearance.effects.is_empty()); +} + +/// Edit SVG Filter on a default saves the edited copy in the document under the default's name; +/// the document's filter then stands in the default's place, and deleting it lists the default again. +#[test] +fn an_edited_default_is_saved_in_the_document_and_delete_restores_the_default() { + use vectorcraft_render::effects::svg_filter::defaults::default_filter; + let mut s = session(); + let glow = default_filter("Glow").unwrap(); + // Saved with its own code: nothing to keep, and no undo step. + run(&mut s, "svgFilter.define", json!({"xml": glow.xml, "replace": "Glow"})); + assert_eq!((names(&mut s).len(), steps(&s)), (0, 0)); + let edited = r#""#; + assert_eq!(run(&mut s, "svgFilter.define", json!({"xml": edited, "replace": "Glow"}))["name"], "Glow"); + assert_eq!((names(&mut s), steps(&s)), (vec!["Glow".to_string()], 1)); + assert_eq!(s.doc().unwrap().history.undo[0].label, "Edit SVG Filter"); + let kept = r#""#; + assert_eq!(run(&mut s, "svgFilter.list", json!({}))["filters"][0]["xml"], kept, "it keeps the default's name"); + // Applying the name now applies the document's filter. + let a = rect(&mut s, 10.0); + run(&mut s, "svgFilter.apply", json!({"name": "Glow", "ids": [a.0]})); + assert_eq!(drawn(&s, a), json!(kept)); + // Deleting the copy leaves the effect drawing nothing, as for any filter, and lists the default. + run(&mut s, "svgFilter.delete", json!({"name": "Glow"})); + assert_eq!(drawn(&s, a), json!("")); + assert!(defaults(&mut s).contains(&("Glow".to_string(), false))); + // The default itself is not deleted. + let before = steps(&s); + assert!(err(&mut s, "svgFilter.delete", json!({"name": "Glow"})).contains("is a default SVG filter")); + assert!(err(&mut s, "svgFilter.delete", json!({"name": "Nope"})).contains("no SVG filter named")); + assert_eq!(steps(&s), before); + // Applied again, the default is copied back, and the object that named it draws with it. + let b = rect(&mut s, 50.0); + run(&mut s, "svgFilter.apply", json!({"name": "Glow", "ids": [b.0]})); + assert_eq!((drawn(&s, a), drawn(&s, b)), (json!(glow.xml), json!(glow.xml))); + assert_eq!(steps(&s), before + 2, "the rectangle and one step for the application"); + // A new filter may take a default's name the document does not hold. + let mut s = session(); + run(&mut s, "svgFilter.define", json!({"xml": r#""#})); + assert!(defaults(&mut s).contains(&("Invert".to_string(), true))); + // An unknown name is still refused. + assert!(err(&mut s, "svgFilter.define", json!({"xml": SHIFT, "replace": "Nope"})).contains("no SVG filter named \"Nope\"")); +} + +/// With `index`, the filter takes the place of an applied SVG filter, a default with its copy in +/// the same undo step; any other effect keeps its place. +#[test] +fn apply_with_an_index_replaces_an_applied_filter() { + let mut s = session(); + let a = rect(&mut s, 10.0); + run(&mut s, "svgFilter.define", json!({"xml": SHIFT})); + run(&mut s, "svgFilter.apply", json!({"name": "Shift", "ids": [a.0]})); + run(&mut s, "effect.apply", json!({"effect": "stylize.feather", "ids": [a.0]})); + let before = steps(&s); + let r = run(&mut s, "svgFilter.apply", json!({"name": "Invert", "ids": [a.0], "index": 0, "item": null})); + assert_eq!(r["ids"], json!([a.0])); + assert_eq!(steps(&s), before + 1, "one step"); + let fx = s.doc().unwrap().doc.node(a).unwrap().appearance.effects.clone(); + assert_eq!((fx.len(), fx[0].params["name"].as_str(), fx[1].id.as_str()), (2, Some("Invert"), "stylize.feather")); + assert_eq!(names(&mut s), ["Shift", "Invert"]); + run(&mut s, "edit.undo", json!({})); + assert_eq!(names(&mut s), ["Shift"]); + assert_eq!(s.doc().unwrap().doc.node(a).unwrap().appearance.effects[0].params["name"], "Shift"); + // Not an SVG filter, no effect there, or not an index: refused, and the default is not copied. + let before = steps(&s); + for (index, why) in [ + (json!(1), "applied SVG filter"), + (json!(7), "applied SVG filter"), + (json!("x"), "`index`"), + (json!(-1), "`index`"), + (json!(null), "`index`"), + ] { + let e = err(&mut s, "svgFilter.apply", json!({"name": "Invert", "ids": [a.0], "index": index, "item": null})); + assert!(e.contains(why), "{index}: {e}"); + } + assert_eq!((names(&mut s), steps(&s)), (vec!["Shift".to_string()], before)); +} + +/// A default needs room in the document: at 64 filters applying one is refused, and a filter the +/// document holds still applies. +#[test] +fn a_full_document_refuses_a_default_it_does_not_hold() { + let mut s = session(); + let a = rect(&mut s, 10.0); + for i in 0..64 { + run(&mut s, "svgFilter.define", json!({"xml": format!("")})); + } + let before = steps(&s); + assert!(err(&mut s, "svgFilter.apply", json!({"name": "Glow", "ids": [a.0]})).contains("at most 64 SVG filters")); + let edited = r#""#; + assert!(err(&mut s, "svgFilter.define", json!({"xml": edited, "replace": "Glow"})).contains("at most 64 SVG filters")); + assert_eq!(steps(&s), before); + assert!(s.doc().unwrap().doc.node(a).unwrap().appearance.effects.is_empty()); + run(&mut s, "svgFilter.apply", json!({"name": "f3", "ids": [a.0]})); +} + +/// A default applied in one document is written to SVG as a filter and read back from the native +/// format with the document's copy. +#[test] +fn an_applied_default_survives_svg_export_and_a_native_round_trip() { + let mut s = session(); + let a = rect(&mut s, 10.0); + run(&mut s, "svgFilter.apply", json!({"name": "Grayscale", "ids": [a.0]})); + let out = svg(&mut s); + assert!(out.contains(" (Paint, Paint) { /// in the batch, and one drawn after it, the same fill and stroke. Returns the batch's rectangle's /// fill and stroke. fn batch_matches_steps(steps: &[(&str, Value)]) -> (Paint, Paint) { + batch_matches_steps_from(brand_defaults_session, steps) +} + +/// [`batch_matches_steps`] with both sessions made by `setup`. +fn batch_matches_steps_from(setup: impl Fn() -> Session, steps: &[(&str, Value)]) -> (Paint, Paint) { let shape = ("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})); - let mut one_by_one = brand_defaults_session(); + let mut one_by_one = setup(); for (id, p) in steps { run(&mut one_by_one, id, p.clone()); } let single = rect(&mut one_by_one); - let mut batched = brand_defaults_session(); + let mut batched = setup(); let commands: Vec = steps.iter().chain([&shape]).map(|(id, p)| json!({"command": id, "params": p})).collect(); let r = run(&mut batched, "command.batch", json!({ "commands": commands })); let in_batch = NodeId(r["results"][steps.len()]["id"].as_u64().unwrap()); @@ -1133,6 +1138,43 @@ fn swatch_steps_in_a_batch_change_the_new_art_paints_as_commands_do() { assert_eq!(batch_matches_steps(&[("swatch.editGroup", json!({"group": "G", "colors": ["#ababab"]}))]), (gray.clone(), gray)); } +#[test] +fn spot_colors_options_in_a_batch_change_the_new_art_paints_as_the_command_does() { + let _g = crate::tests_colormgmt::GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let lab = Color::Lab { l: 55.0, a: 60.0, b: 40.0 }; + let cms = vectorcraft_color::cms::active(); + let cmyk = cms.convert(&lab, vectorcraft_color::cms::Model::Cmyk, cms.settings().intent); + assert!(matches!(cmyk, Color::Cmyk { .. })); + // The default fill and stroke for new art are linked to 40 % of the Lab spot swatch "Lab Ink". + let lab_ink_defaults = |use_lab: bool| { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Lab Ink", "color": {"l": 55, "a": 60, "b": 40}, "spot": true})); + run(&mut s, "swatch.spotOptions", json!({ "useLab": use_lab })); + run(&mut s, "select.set", json!({"ids": []})); + run(&mut s, "paint.setFill", json!({"swatch": "Lab Ink", "tint": 40})); + run(&mut s, "paint.setStroke", json!({"swatch": "Lab Ink", "tint": 40})); + s + }; + let ink = |color: Color| Paint::Solid { color: color.tinted(0.4), swatch: Some("Lab Ink".into()), tint: 0.4 }; + assert_eq!(lab_ink_defaults(true).paint.fill, ink(lab)); + let to_cmyk = [("swatch.spotOptions", json!({"useLab": false}))]; + assert_eq!(batch_matches_steps_from(|| lab_ink_defaults(true), &to_cmyk), (ink(cmyk), ink(cmyk))); + assert_eq!(lab_ink_defaults(false).paint.fill, ink(cmyk)); + let to_lab = [("swatch.spotOptions", json!({"useLab": true}))]; + assert_eq!(batch_matches_steps_from(|| lab_ink_defaults(false), &to_lab), (ink(lab), ink(lab))); +} + +#[test] +fn default_swatches_replace_in_a_batch_unlinks_the_new_art_paints_as_the_command_does() { + // Brand and Other are not default swatches, so replacing the swatches drops the links to them. + let blue = Paint::solid(Color::from_hex("#2a6fb0").unwrap()); + let replace = [("swatch.resetDefaults", json!({"replace": true}))]; + assert_eq!(batch_matches_steps(&replace), (blue.clone(), blue)); + // Without replace the swatches stay, and so do the links. + let link = linked("#2a6fb0", "Brand"); + assert_eq!(batch_matches_steps(&[("swatch.resetDefaults", json!({}))]), (link.clone(), link)); +} + #[test] fn undo_and_redo_of_a_swatch_edit_put_back_the_new_art_paints() { let edit = json!({"name": "Brand", "newName": "Signal", "color": "#00ff00"}); diff --git a/crates/engine/src/tests/swatchlib.rs b/crates/engine/src/tests/swatchlib.rs index 445ce38ea7..dbf32eba7c 100644 --- a/crates/engine/src/tests/swatchlib.rs +++ b/crates/engine/src/tests/swatchlib.rs @@ -636,6 +636,114 @@ fn gradient_libraries_are_listed_and_gradient_swatches_rename_and_take_new_gradi assert_eq!(doc(&s).swatch("Red").unwrap().paint.color().map(|c| c.to_hex()), Some("#00ff00".into())); } +/// A radial gradient from red to blue, with `extra` keys. +fn radial_gradient(extra: Value) -> Value { + let mut g = json!({"kind": "radial", "stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]}); + if let (Some(g), Some(extra)) = (g.as_object_mut(), extra.as_object()) { + g.extend(extra.clone()); + } + g +} + +/// The gradient swatch `name` keeps an aspect of 50%, holds no swatch link, and applies with that +/// aspect, fitted to the object it is applied to. +fn assert_swatch_applies_with_half_aspect(s: &mut Session, name: &str) { + let Paint::Gradient(sw) = &doc(s).swatch(name).unwrap().paint else { panic!("{name}: a gradient swatch") }; + assert!(sw.geom.is_some_and(|g| (g.aspect - 0.5).abs() < 1e-9), "{name} keeps the aspect: {:?}", sw.geom); + assert_eq!(sw.swatch, None, "{name} holds no link to the swatch its gradient came from"); + let r = run(s, "shape.rectangle", json!({"x": 100, "y": 0, "width": 100, "height": 60})); + let id = r["id"].as_u64().unwrap(); + run(s, "paint.setFill", json!({"ids": [id], "swatch": name})); + let fill = doc(s).node(vectorcraft_doc::NodeId(id)).unwrap().appearance.fill_paint(); + let Paint::Gradient(g) = fill else { panic!("{name}: a gradient fill") }; + let geom = g.geom.unwrap(); + assert!( + geom.start.distance(vectorcraft_geom::Point::new(150.0, 30.0)) < 1e-9 && (geom.aspect - 0.5).abs() < 1e-9, + "{name} fits the object with its aspect: {geom:?}" + ); +} + +/// An edited gradient with a vector and an aspect that replaces a gradient swatch keeps its aspect, +/// as a new swatch made from it does. +#[test] +fn a_gradient_swatch_takes_an_edited_gradient_with_its_aspect() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Edited", "gradient": radial_gradient(json!({}))})); + let placed = radial_gradient(json!({"start": [25, 25], "end": [50, 25], "aspect": 50})); + run(&mut s, "swatch.edit", json!({"name": "Edited", "paint": {"gradient": placed}})); + assert_swatch_applies_with_half_aspect(&mut s, "Edited"); +} + +/// A gradient swatch Alt-dropped on another gradient swatch gives it its gradient with its aspect. +#[test] +fn a_gradient_swatch_takes_a_dropped_swatch_with_its_aspect() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Dropped", "gradient": radial_gradient(json!({}))})); + let placed = radial_gradient(json!({"start": [25, 25], "end": [50, 25], "aspect": 50})); + run(&mut s, "swatch.new", json!({"name": "Oval", "gradient": placed})); + run(&mut s, "swatch.edit", json!({"name": "Dropped", "paint": {"swatch": "Oval"}})); + assert_swatch_applies_with_half_aspect(&mut s, "Dropped"); +} + +/// A gradient given an aspect but no vector keeps the aspect in a new swatch and in a replacement, +/// as `paint.setFill` keeps it on the object. +#[test] +fn a_gradient_without_a_vector_keeps_its_aspect_in_a_swatch() { + let mut s = session(); + let oval = radial_gradient(json!({"aspect": 50})); + run(&mut s, "swatch.new", json!({"name": "New", "gradient": oval})); + assert_swatch_applies_with_half_aspect(&mut s, "New"); + run(&mut s, "swatch.new", json!({"name": "Edited", "gradient": radial_gradient(json!({}))})); + run(&mut s, "swatch.edit", json!({"name": "Edited", "paint": {"gradient": oval}})); + assert_swatch_applies_with_half_aspect(&mut s, "Edited"); + // Without an aspect the swatch stays unplaced. + run(&mut s, "swatch.new", json!({"name": "Round", "gradient": radial_gradient(json!({}))})); + let Paint::Gradient(round) = &doc(&s).swatch("Round").unwrap().paint else { panic!("a gradient swatch") }; + assert_eq!(round.geom, None); +} + +/// A pattern that replaces a pattern swatch is stored untransformed, as a new swatch stores it, so +/// art the swatch is applied to keeps its own tile placement. +#[test] +fn a_pattern_swatch_takes_a_new_pattern_untransformed() { + let mut s = session(); + for (name, color) in [("Dots", "#ff0000"), ("Bars", "#0000ff")] { + let r = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})); + run(&mut s, "paint.setFill", json!({"ids": [r["id"]], "color": color})); + run(&mut s, "select.set", json!({"ids": [r["id"]]})); + run(&mut s, "object.pattern.make", json!({"name": name, "width": 20, "height": 20})); + run(&mut s, "object.pattern.done", json!({})); + } + // A pattern swatch holding a tile transform, as documents saved by older versions can. + let moved = vectorcraft_geom::Affine::new([2.0, 0.0, 0.0, 2.0, 15.0, 10.0]); + let st = s.doc_mut().unwrap(); + let Some(Paint::Pattern { xf, .. }) = std::sync::Arc::make_mut(&mut st.doc).swatch_mut("Bars").map(|w| &mut w.paint) else { + panic!("the Bars pattern swatch") + }; + *xf = moved; + run(&mut s, "swatch.edit", json!({"name": "Dots", "paint": {"swatch": "Bars"}})); + assert_eq!(doc(&s).swatch("Dots").unwrap().paint, vectorcraft_doc::pattern::pattern_paint("Bars")); +} + +/// A pattern swatch takes a pattern given by name, as an Alt-drop of a pattern fill sends it, and +/// an unknown pattern is an error that leaves the swatch as it was. +#[test] +fn a_pattern_swatch_takes_a_pattern_by_name() { + let mut s = session(); + for (name, color) in [("Dots", "#ff0000"), ("Bars", "#0000ff")] { + let r = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})); + run(&mut s, "paint.setFill", json!({"ids": [r["id"]], "color": color})); + run(&mut s, "select.set", json!({"ids": [r["id"]]})); + run(&mut s, "object.pattern.make", json!({"name": name, "width": 20, "height": 20})); + run(&mut s, "object.pattern.done", json!({})); + } + run(&mut s, "swatch.edit", json!({"name": "Dots", "paint": {"pattern": "Bars"}})); + assert_eq!(doc(&s).swatch("Dots").unwrap().paint, vectorcraft_doc::pattern::pattern_paint("Bars")); + let before = doc(&s).swatch("Dots").unwrap().paint.clone(); + assert!(s.execute("swatch.edit", &json!({"name": "Dots", "paint": {"pattern": "Nope"}})).is_err()); + assert_eq!(doc(&s).swatch("Dots").unwrap().paint, before); +} + #[test] fn organic_fades_add_with_their_method_midpoints_and_opacities_in_rgb_and_cmyk() { let lib = vectorcraft_color::libraries::builtin_library("organic-fades").unwrap(); diff --git a/crates/engine/src/tests/textedit.rs b/crates/engine/src/tests/textedit.rs index adcc35d352..9dc35ff99b 100644 --- a/crates/engine/src/tests/textedit.rs +++ b/crates/engine/src/tests/textedit.rs @@ -2265,6 +2265,36 @@ fn remove_breaks_takes_the_whole_story_that_select_all_selected() { assert!(obj(&s, a).plain_text().contains('\n') && obj(&s, b).plain_text().contains('\n')); } +#[test] +fn remove_breaks_of_the_whole_story_takes_locked_and_hidden_frames() { + for command in ["object.lock", "object.hide"] { + for held_first in [false, true] { + let (mut s, a, b, story) = threaded_list_edited_in_its_second_frame(); + let (held, other) = if held_first { (a, b) } else { (b, a) }; + let unrelated = s.execute("text.create", &json!({"x": 10, "y": 500, "text": "One\nTwo", "size": 12})).unwrap()["id"].as_u64().unwrap(); + let unrelated = NodeId(unrelated); + s.execute(command, &json!({"ids": [held.0]})).unwrap(); + s.execute("select.set", &json!({"ids": [other.0]})).unwrap(); + s.select_tool("type", ViewInfo::default()).unwrap(); + s.set_tool_option("textSelection", &json!({"editing": other.0, "anchor": 0, "caret": 0})); + assert_eq!(s.execute("select.all", &json!({})).unwrap()["story"], json!([a.0, b.0])); + let case = format!("{command}, held first: {held_first}"); + let steps = undo_labels(&s).len(); + let r = s.execute("addon.cleanup.removeBreaks", &json!({"kind": "paragraph"})).unwrap(); + assert_eq!(undo_labels(&s).len(), steps + 1, "{case}: one undo step"); + assert!(r["ids"].as_array().unwrap().contains(&json!(held.0)), "{case}: the held frame is changed"); + let joined = format!("{}{}", obj(&s, a).plain_text(), obj(&s, b).plain_text()); + assert_eq!(joined, story.trim_end_matches('\n').replace('\n', " "), "{case}: every frame's returns go"); + assert_eq!(obj(&s, unrelated).plain_text(), "One\nTwo", "{case}: other type is as it was"); + // No return is left: another call fails and adds no undo step. + assert!(s.execute("addon.cleanup.removeBreaks", &json!({"kind": "paragraph"})).is_err()); + assert_eq!(undo_labels(&s).len(), steps + 1, "{case}: no undo step when nothing changes"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(format!("{}{}", obj(&s, a).plain_text(), obj(&s, b).plain_text()), story, "{case}: undo restores the text"); + } + } +} + #[test] fn remove_breaks_on_a_selected_threaded_story_puts_a_space_between_its_frames() { let (mut s, a, b, story) = threaded_list_edited_in_its_second_frame(); @@ -2306,41 +2336,72 @@ fn convert_to_text_takes_the_whole_story_that_select_all_selected() { } } +/// Whether no paragraph of type `id` is a list. +fn no_list(s: &Session, id: NodeId) -> bool { + let t = obj(s, id); + (0..t.paragraph_count()).all(|k| t.para_at(k).list.is_none()) +} + +/// The bullets held as characters in the frames `ids`. +fn bullet_chars(s: &Session, ids: &[NodeId]) -> usize { + ids.iter().map(|id| obj(s, *id).plain_text().matches("\u{2022}\t").count()).sum() +} + #[test] -fn convert_to_text_of_the_whole_story_leaves_a_locked_frame() { - // Over MCP without ids, and as the Paragraph panel sends it, with every frame of the story. - for named in [false, true] { - let (mut s, a, b, _) = threaded_list_edited_in_its_second_frame(); - s.execute("object.lock", &json!({"ids": [b.0]})).unwrap(); - s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); - s.set_tool_option("textSelection", &json!({"editing": a.0, "anchor": 0, "caret": 0})); - assert_eq!(s.execute("select.all", &json!({})).unwrap()["story"], json!([a.0, b.0])); - // The first frame ends with a paragraph return, so the paragraph that starts the locked - // frame takes in the first frame's empty last part and starts its text there. - let in_a = obj(&s, a).plain_text(); - assert!(in_a.ends_with('\n')); - let own = in_a.split('\n').filter(|piece| !piece.is_empty()).count(); - let p = if named { json!({"ids": [a.0, b.0]}) } else { json!({}) }; - let r = s.execute("text.convertListToText", &p).unwrap(); - assert_eq!(r["ids"], json!([a.0]), "only the editable frame is changed (ids named: {named})"); - assert_eq!(r["converted"], json!(own), "only the paragraphs whose text starts in the editable frame convert"); - assert!(r["inserted"].as_array().unwrap().iter().all(|i| i["id"] == json!(a.0))); - let (ta, tb) = (obj(&s, a), obj(&s, b)); - assert!(ta.plain_text().contains("\u{2022}\t"), "the editable frame is converted"); - let markers = ta.plain_text().matches("\u{2022}\t").count() + tb.plain_text().matches("\u{2022}\t").count(); - assert_eq!(markers, own, "the locked frame's first paragraph keeps its list"); - // The converted text is longer, so the story flows on into the locked frame; its own - // paragraphs stay a list. - let last = tb.paragraph_count() - 2; - assert!(tb.para_at(last).list.is_some(), "the locked frame's paragraphs stay a list (ids named: {named})"); - assert!(!tb.plain_text().ends_with("\u{2022}\tAlpha beta.\n")); - assert!(s.tool_options().get("story").is_some(), "the whole story stays selected"); +fn convert_to_text_of_the_whole_story_converts_locked_and_hidden_frames() { + // Over MCP without ids, as the Paragraph panel sends it with every frame of the story, and with + // ids naming only the held frame. + for command in ["object.lock", "object.hide"] { + for held_first in [false, true] { + for call in ["none", "story", "held"] { + let (mut s, a, b, story) = threaded_list_edited_in_its_second_frame(); + let (held, other) = if held_first { (a, b) } else { (b, a) }; + let unrelated = + s.execute("text.create", &json!({"x": 10, "y": 500, "text": "One\nTwo", "size": 12})).unwrap()["id"].as_u64().unwrap(); + let unrelated = NodeId(unrelated); + s.execute("text.setFormat", &json!({"ids": [unrelated.0], "list": "bullet"})).unwrap(); + let unrelated_before = obj(&s, unrelated); + s.execute(command, &json!({"ids": [held.0]})).unwrap(); + s.execute("select.set", &json!({"ids": [other.0]})).unwrap(); + s.select_tool("type", ViewInfo::default()).unwrap(); + s.set_tool_option("textSelection", &json!({"editing": other.0, "anchor": 0, "caret": 0})); + assert_eq!(s.execute("select.all", &json!({})).unwrap()["story"], json!([a.0, b.0])); + let case = format!("{command}, held first: {held_first}, ids: {call}"); + let p = match call { + "none" => json!({}), + "story" => json!({"ids": [a.0, b.0]}), + _ => json!({"ids": [held.0]}), + }; + let steps = undo_labels(&s).len(); + let r = s.execute("text.convertListToText", &p).unwrap(); + assert_eq!(undo_labels(&s).len(), steps + 1, "{case}: one undo step"); + assert!(r["ids"].as_array().unwrap().contains(&json!(held.0)), "{case}: the held frame is changed"); + assert!(no_list(&s, held), "{case}: the held frame leaves its list"); + assert_eq!(obj(&s, unrelated), unrelated_before, "{case}: other type is as it was"); + if call == "held" { + // The other frame's paragraphs whose text starts there keep their list. + assert!(!no_list(&s, other), "{case}: the frame not named keeps its list"); + continue; + } + assert!(no_list(&s, other), "{case}: the other frame leaves its list"); + assert_eq!(bullet_chars(&s, &[a, b]), 12, "{case}: each paragraph's bullet is held once as characters"); + assert!(s.tool_options().get("story").is_some(), "{case}: the whole story stays selected"); + // Nothing is a list any more: another call changes nothing and adds no undo step. + s.execute("text.convertListToText", &p).unwrap(); + assert_eq!(undo_labels(&s).len(), steps + 1, "{case}: no undo step when nothing changes"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(format!("{}{}", obj(&s, a).plain_text(), obj(&s, b).plain_text()), story, "{case}: undo restores the text"); + assert!(!no_list(&s, a) && !no_list(&s, b), "{case}: undo restores the lists"); + } + } } } #[test] -fn convert_to_text_of_the_whole_story_leaves_a_paragraph_that_starts_in_a_locked_frame() { - for named in [false, true] { +fn convert_to_text_of_the_whole_story_converts_a_paragraph_that_runs_across_a_locked_frame() { + // The paragraph that runs from the first frame into the second starts in the locked frame, or + // ends in it. + for (named, lock_first) in [(false, true), (true, true), (false, false), (true, false)] { let mut s = session(); let story = format!("Alpha beta.\nAlpha beta.\n{}end.\nAlpha beta.\nAlpha beta.\n", "Gamma delta ".repeat(40)); let a = NodeId( @@ -2354,22 +2415,23 @@ fn convert_to_text_of_the_whole_story_leaves_a_paragraph_that_starts_in_a_locked s.execute("text.setFormat", &json!({"ids": [a.0, b.0], "list": "bullet"})).unwrap(); let in_a = obj(&s, a).plain_text(); assert!(!in_a.ends_with('\n') && !obj(&s, b).plain_text().starts_with('\n'), "a paragraph runs on from the first frame into the second"); - s.execute("object.lock", &json!({"ids": [a.0]})).unwrap(); - s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + let (locked, other) = if lock_first { (a, b) } else { (b, a) }; + s.execute("object.lock", &json!({"ids": [locked.0]})).unwrap(); + s.execute("select.set", &json!({"ids": [other.0]})).unwrap(); s.select_tool("type", ViewInfo::default()).unwrap(); - s.set_tool_option("textSelection", &json!({"editing": b.0, "anchor": 0, "caret": 0})); + s.set_tool_option("textSelection", &json!({"editing": other.0, "anchor": 0, "caret": 0})); assert_eq!(s.execute("select.all", &json!({})).unwrap()["story"], json!([a.0, b.0])); + let case = format!("ids named: {named}, first frame locked: {lock_first}"); let p = if named { json!({"ids": [a.0, b.0]}) } else { json!({}) }; let r = s.execute("text.convertListToText", &p).unwrap(); - assert_eq!(r["ids"], json!([b.0]), "only the editable frame is changed (ids named: {named})"); - // The two paragraphs that start in the editable frame, and the empty one that ends the story. - assert_eq!(r["converted"], json!(3), "only the paragraphs that start in the editable frame convert"); + assert_eq!(r["ids"], json!([a.0, b.0]), "{case}: both frames are changed"); + // The five paragraphs with text, and the empty one that ends the story. + assert_eq!(r["converted"], json!(6), "{case}: every paragraph of the story converts"); let (ta, tb) = (obj(&s, a), obj(&s, b)); - assert_eq!(ta.plain_text(), in_a, "the locked frame's text is as it was"); - assert!((0..ta.paragraph_count()).all(|k| ta.para_at(k).list.is_some()), "the locked frame stays a list"); - assert!(tb.para_at(0).list.is_some(), "the paragraph the locked frame starts stays a list"); - assert!(!tb.plain_text().starts_with('\u{2022}')); - assert_eq!(tb.plain_text().matches("\u{2022}\t").count(), 2); + assert!(no_list(&s, a) && no_list(&s, b), "{case}: the story leaves its list"); + assert_eq!(bullet_chars(&s, &[a, b]), 5, "{case}: each paragraph's bullet is held once as characters"); + assert!(ta.plain_text().contains("\u{2022}\tGamma"), "{case}: the paragraph across the frames takes its bullet where its text starts"); + assert!(!tb.plain_text().starts_with('\u{2022}'), "{case}"); } } diff --git a/crates/engine/src/tests/textimport.rs b/crates/engine/src/tests/textimport.rs index 0749964ee6..b369346096 100644 --- a/crates/engine/src/tests/textimport.rs +++ b/crates/engine/src/tests/textimport.rs @@ -68,6 +68,49 @@ fn type_placed_on_an_artboard_edge_takes_that_artboards_frame() { } } +/// `text` as UTF-16 without a byte-order mark, little-endian when `le` is set. +fn utf16(text: &str, le: bool) -> Vec { + text.encode_utf16().flat_map(|u| if le { u.to_le_bytes() } else { u.to_be_bytes() }).collect() +} + +/// Unicode text in UTF-16 without a byte-order mark is read as UTF-16 when at least half of its +/// two-byte units hold a NUL byte, in the byte order that reads a line break, or for one line, the +/// order its NUL bytes give. Other bytes keep today's reading. +#[test] +fn utf16_without_a_byte_order_mark_places_by_its_nul_bytes_and_line_breaks() { + let mut s = session(); + for le in [true, false] { + let r = place_text(&mut s, &utf16("Hello, 世界 café!\r\nSecond line", le), json!({})); + assert_eq!(placed(&s, &r).0, "Hello, 世界 café!\nSecond line", "little-endian: {le}"); + let r = place_text(&mut s, &utf16("One line, 世界", le), json!({})); + assert_eq!(placed(&s, &r).0, "One line, 世界", "little-endian: {le}"); + } + // One line with NUL bytes in both places (U+4E00 ends in a zero byte) takes the order more of + // its units give, and a tie is little-endian. + let r = place_text(&mut s, &utf16("一AB", false), json!({})); + assert_eq!(placed(&s, &r).0, "一AB"); + let r = place_text(&mut s, &utf16("一A", true), json!({})); + assert_eq!(placed(&s, &r).0, "一A"); + // Not read as UTF-16, so read as UTF-8 or else Windows-1252 with NUL bytes dropped: an odd + // length, an unpaired surrogate, a NUL character, and line breaks in both byte orders (U+0A00). + let r = place_text(&mut s, b"A\0B", json!({})); + assert_eq!(placed(&s, &r).0, "AB"); + let r = place_text(&mut s, b"\0a\0b\xd8\0", json!({})); + assert_eq!(placed(&s, &r).0, "abØ"); + let r = place_text(&mut s, b"\0\0\xc3\xa9", json!({})); + assert_eq!(placed(&s, &r).0, "é"); + let r = place_text(&mut s, &utf16("A\u{0A00}\nB", true), json!({})); + assert_eq!(placed(&s, &r).0, "A\n\nB"); + // Fewer than half of the two-byte units hold a NUL byte: UTF-8, and Windows-1252. + let r = place_text(&mut s, "Fünf\0 Zeilen!".as_bytes(), json!({})); + assert_eq!(placed(&s, &r).0, "Fünf Zeilen!"); + let r = place_text(&mut s, b"caf\xe9\0x", json!({})); + assert_eq!(placed(&s, &r).0, "caféx"); + // ANSI reads each byte as a character of the 8-bit set; NUL and other control bytes are dropped. + let r = place_text(&mut s, &utf16("Hi, 世界", true), json!({"text": {"characterSet": "ansi"}})); + assert_eq!(placed(&s, &r).0, "Hi, NLu"); +} + #[test] fn text_files_report_and_queue_with_their_options() { let mut s = session(); diff --git a/crates/engine/src/tests/toolsettings.rs b/crates/engine/src/tests/toolsettings.rs index e896a0ab32..2ec7667bde 100644 --- a/crates/engine/src/tests/toolsettings.rs +++ b/crates/engine/src/tests/toolsettings.rs @@ -241,6 +241,69 @@ fn options_are_saved_with_the_preferences() { assert_eq!(t.prefs.tool_settings["polygon"]["sides"], json!(9)); } +#[test] +fn spiral_decay_is_normalized_for_active_and_inactive_tools_and_preferences() { + let mut s = session(); + for active in [false, true] { + select(&mut s, if active { "spiral" } else { "selection" }); + let options = s.set_tool_option_cmd(&json!({"tool": "spiral", "values": {"decay": 150, "segments": 4, "clockwise": false}})).unwrap(); + assert_eq!(options["decay"], json!(99.99)); + assert_eq!(s.tool_options_of("spiral")["decay"], json!(99.99)); + assert_eq!(s.prefs.tool_settings["spiral"]["decay"], json!(99.99)); + assert_eq!(s.tool_id(), if active { "spiral" } else { "selection" }); + select(&mut s, "selection"); + select(&mut s, "spiral"); + assert_eq!(s.tool_options()["decay"], json!(99.99)); + } + let saved = serde_json::to_string(&s.prefs).unwrap(); + let mut restored = session(); + restored.apply_prefs(serde_json::from_str(&saved).unwrap()); + select(&mut restored, "spiral"); + assert_eq!(restored.tool_options(), json!({"decay": 99.99, "segments": 4, "clockwise": false})); +} + +#[test] +fn legacy_spiral_decay_preferences_report_the_ratio_drawn_after_reopening() { + use vectorcraft_geom::Point; + use vectorcraft_tools::{PointerEvent, PointerKind}; + + // Older versions saved 100–150, although their geometry already capped the ratio at 0.9999. + for clockwise in [false, true] { + let mut s = session(); + let mut prefs = Prefs::default(); + prefs.tool_settings.insert("spiral".into(), json!({"decay": 150, "segments": 4, "clockwise": clockwise}).as_object().unwrap().clone()); + s.apply_prefs(serde_json::from_str(&serde_json::to_string(&prefs).unwrap()).unwrap()); + let view = ViewInfo { smart_guides: false, ..Default::default() }; + s.select_tool("spiral", view).unwrap(); + let decay = s.tool_options()["decay"].as_f64().unwrap(); + assert_eq!(decay, 99.99); + let before = s.doc().unwrap().history.undo.len(); + for (kind, x) in [(PointerKind::Down, 200.0), (PointerKind::Drag, 300.0), (PointerKind::Up, 300.0)] { + s.pointer(&PointerEvent::new(kind, x, 200.0), view).unwrap(); + } + let d = s.doc().unwrap(); + assert_eq!(d.history.undo.len(), before + 1); + assert_eq!(d.selection.objects.len(), 1); + let id = d.selection.objects[0]; + let path = d.doc.node(id).unwrap().path_data().unwrap().clone(); + let anchors = &path.subpaths[0].anchors; + assert_eq!(anchors.len(), 5); + assert!(!path.is_closed()); + let center = Point::new(200.0, 200.0); + // The path runs from the centre end outwards, and decay is per full wind: four quarter-turn + // segments give the decay. + for pair in anchors.windows(2) { + let ratio = pair[0].p.distance(center) / pair[1].p.distance(center); + assert!((100.0 * ratio.powi(4) - decay).abs() < 1e-9); + } + assert_eq!(s.prefs.tool_settings["spiral"]["decay"], json!(99.99)); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.node(id).is_none()); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap(), &path); + } +} + /// Escape on a polygon or rounded rectangle drag puts back the side count or corner radius its /// arrows changed, in the saved options and the Corner Radius preference too. #[test] diff --git a/crates/engine/src/tests/variables.rs b/crates/engine/src/tests/variables.rs index eea8ae4986..bb5b73b2f2 100644 --- a/crates/engine/src/tests/variables.rs +++ b/crates/engine/src/tests/variables.rs @@ -2201,6 +2201,16 @@ fn datasets_csv_reads_utf16_files_without_a_byte_order_mark() { let e = import(&mut s, &bytes).unwrap_err().to_string(); assert!(e.contains("CSV has a header but no data rows"), "{e}"); } + // With no line break, the side of each unit that holds the NUL byte gives the byte order, and a + // tie is little-endian. + let order = crate::cmd::utf16_order_without_mark; + assert_eq!(order(&utf16("City", false)), Some(false)); + assert_eq!(order(&utf16("City", true)), Some(true)); + assert_eq!(order(b"\0aa\0"), Some(true)); + assert_eq!(order(&[utf16("City\n", false), vec![0x0A]].concat()), Some(false), "an odd last byte is left out"); + // Read big-endian, this one-line file ends in an unpaired surrogate. + let e = import(&mut s, b"\0a\0b\xd8\0").unwrap_err().to_string(); + assert!(e.contains("CSV holds NUL bytes"), "{e}"); import(&mut s, &utf16("City\tName\n一二三丁目\tKai\n", true)).unwrap(); assert_eq!(value(&s, "Data Set 1"), text_value("一二三丁目")); // Most units hold their NUL byte where a big-endian file would (U+4E00); the line breaks @@ -2274,7 +2284,7 @@ fn a_variable_library_defines_text_variables_and_data_sets() { assert_eq!(r["variables"], json!(["Name", "Note"])); assert_eq!((r["deleted"].clone(), r["deletedDataSets"].clone()), (json!([]), json!([]))); assert_eq!(r["names"], json!(["Row 1", "Row 2"])); - assert_eq!((r["skipped"].clone(), r.get("warning")), (json!([]), None)); + assert_eq!((r.get("skipped"), r.get("warning")), (None, None)); let listed = s.execute("variable.list", &json!({})).unwrap(); assert_eq!(listed["variables"], json!([{"name": "Name", "kind": "text", "bindings": 0}, {"name": "Note", "kind": "text", "bindings": 0}])); let sets = s.execute("dataset.list", &json!({})).unwrap(); @@ -2395,13 +2405,14 @@ fn an_import_or_library_load_that_changes_nothing_records_no_undo_step() { s.execute("variable.loadLibrary", &json!({"xml": other})).unwrap(); assert_eq!(super::history(&s), (undo + 1, 0, true)); - // While the variables are locked, a library without text variables still loads its data sets, - // and loading it again changes nothing. + // While the variables are locked, a library of the variables the document has, with their + // kinds, still loads its data sets, and loading it again changes nothing. let mut s = session(); let t = text(&mut s, "Alice"); - s.execute("variable.lock", &json!({"locked": true})).unwrap(); let xml = library(&[("Shown", "other")], &[("B", &[])]); s.execute("variable.loadLibrary", &json!({"xml": xml})).unwrap(); + s.execute("variable.lock", &json!({"locked": true})).unwrap(); + s.execute("variable.loadLibrary", &json!({"xml": xml})).unwrap(); super::select_with_a_step_to_redo(&mut s, &[t]); let before = super::history(&s); s.execute("variable.loadLibrary", &json!({"xml": xml})).unwrap(); @@ -2422,22 +2433,89 @@ fn a_refused_variable_library_deletes_nothing() { assert_eq!(s.doc().unwrap().doc.variables, before); } -/// A library's variables of other kinds are left out with their values, named in `skipped` and -/// in a warning that gives each kind once with its count; its text variables load. +/// A library of every kind, in the layout the public grammar gives: visibility (`visibility`), +/// image (`fileref`) and graph (`graphdata`) variables beside a text variable, a variable without a +/// `trait` and one whose `trait` VectorCraft doesn't know, with values in the forms +/// [`a_variable_library_defines_every_kind_with_its_values`] reads. +fn every_kind_library() -> String { + "\n\ + ]>\n\ + \ + \ + \ + \ + \ +

Bravo

true\ + \n\t\tfile:////Users/me/Art%20Work/logo%23one.png\n\t\t\ + NorthSouth\ + Q1102.5\ + 2024-4\ + ignored\ + FALSE C:\\Art\\logo.png\ + 78\ + \n\ + \n" + .to_string() +} + +/// Load Variable Library defines a library's variables of every kind, unbound, with their values: +/// a visibility value from `true` or `false` in any case, an image value from a file's absolute +/// path or a `file:` URL (escapes decoded, the white space round it left out, the file not read), +/// and a graph value from a `data` element, as the CSV Graph Data takes (series from its +/// `propertyRow`, a category from each row's `key="name"` value, blanks where a row has no +/// number). A variable without a `trait`, or with one VectorCraft doesn't know, is defined of +/// unknown kind, without values. An element holding only white space gives no value. #[test] -fn a_variable_library_leaves_out_variables_that_are_not_text() { +fn a_variable_library_defines_every_kind_with_its_values() { let mut s = session(); - let xml = library( - &[("Shown", "kindB"), ("Name", "textcontent"), ("Photo", "kindC"), ("Other", "kindB")], - &[("A", &[("Shown", &["true"]), ("Name", &["Bravo"]), ("Photo", &["a.png"])])], - ); - let r = s.execute("variable.loadLibrary", &json!({"xml": xml})).unwrap(); - assert_eq!(r["variables"], json!(["Name"])); - assert_eq!(r["skipped"], json!([{"name": "Shown", "trait": "kindB"}, {"name": "Photo", "trait": "kindC"}, {"name": "Other", "trait": "kindB"}])); - assert_eq!(r["warning"], "variables that aren't text were left out: kindB (2), kindC (1)"); + let r = s.execute("variable.loadLibrary", &json!({"xml": every_kind_library()})).unwrap(); + assert_eq!(r["variables"], json!(["Name", "Shown", "Photo", "Chart", "Loose", "Odd"])); let vars = &s.doc().unwrap().doc.variables; - assert_eq!(vars.variables.len(), 1); - assert_eq!(vars.dataset("A").map(|d| d.values.len()), Some(1)); + let kinds: Vec<(&str, &str)> = vars.variables.iter().map(|v| (v.name.as_str(), v.kind.label())).collect(); + assert_eq!(kinds, [("Name", "text"), ("Shown", "visibility"), ("Photo", "image"), ("Chart", "graph"), ("Loose", "unknown"), ("Odd", "unknown")]); + assert!(vars.bindings.is_empty()); + use vectorcraft_doc::DataValue::{Graph, Image, Text, Visible}; + let a = &vars.dataset("A").unwrap().values; + assert_eq!(a.get("Name"), Some(&Text("Bravo".into()))); + assert_eq!(a.get("Shown"), Some(&Visible(true))); + assert_eq!(a.get("Photo"), Some(&Image("/Users/me/Art Work/logo#one.png".into()))); + assert_eq!(a.get("Chart"), Some(&Graph(",North,South\nQ1,10,2.5\n\"2024\",,-4".into()))); + assert_eq!((a.get("Loose"), a.get("Odd")), (None, None)); + let b = &vars.dataset("B").unwrap().values; + assert_eq!((b.get("Shown"), b.get("Photo")), (Some(&Visible(false)), Some(&Image("C:\\Art\\logo.png".into())))); + assert_eq!(b.get("Chart"), Some(&Graph(",,\n7,8".into()))); + assert!(vars.dataset("C").unwrap().values.is_empty(), "{:?}", vars.dataset("C")); +} + +/// A library's visibility, image and graph variables drive the art they are bound to: a variable +/// the document already has with the same name and kind stays bound (#4136), so selecting a +/// library's data set shows or hides the object, swaps the linked image's path and replaces the +/// graph's data. A variable of the same name and another kind is replaced, and its bindings go. +#[test] +fn a_variable_library_keeps_bound_variables_of_every_kind() { + let mut s = session(); + let r = rect(&mut s); + let graph = s.execute("graph.create", &json!({"type": "column", "x": 10, "y": 10, "width": 120, "height": 80, "csv": ",a\nX,1"})).unwrap()["id"] + .as_u64() + .unwrap(); + for (name, kind, id) in [("Shown", "visibility", r.0), ("Chart", "graph", graph), ("Photo", "text", r.0)] { + s.execute("variable.define", &json!({"name": name, "kind": kind})).unwrap(); + if kind != "text" { + s.execute("variable.bind", &json!({"variable": name, "ids": [id]})).unwrap(); + } + } + let loaded = s.execute("variable.loadLibrary", &json!({"xml": every_kind_library()})).unwrap(); + assert_eq!(loaded["deleted"], json!(["Photo"]), "Photo is an image variable in the library"); + let listed = s.execute("variable.list", &json!({})).unwrap(); + let bindings: Vec<(String, u64)> = + listed["variables"].as_array().unwrap().iter().map(|v| (v["name"].as_str().unwrap().to_string(), v["bindings"].as_u64().unwrap())).collect(); + assert_eq!(bindings.iter().find(|(n, _)| n == "Shown").map(|b| b.1), Some(1)); + assert_eq!(bindings.iter().find(|(n, _)| n == "Chart").map(|b| b.1), Some(1)); + s.execute("dataset.select", &json!({"name": "B"})).unwrap(); + let doc = &s.doc().unwrap().doc; + assert!(!doc.node(r).unwrap().visible, "Shown is false in B"); + let csv = doc.node(NodeId(graph)).and_then(|n| n.extras().graph.as_ref()).map(|g| g.to_csv()); + assert_eq!(csv.as_deref(), Some(",,\n7,8\n"), "B's graph data"); } /// A library that isn't one, or that breaks its grammar or the caps, is refused, and the document @@ -2467,12 +2545,36 @@ fn malformed_variable_libraries_are_refused() { "&big;".repeat(8000), " ".repeat(300_000) ); + // A library of one variable `Shown` of the trait given, and a data set holding `value`. + let kind_value = |t: &str, value: &str| { + format!( + "\ + {value}" + ) + }; + // A library graph value of more rows or series than a graph holds. + let rows_past = format!("{}", "1".repeat(10_001)); + let series_past = + format!("Q{}", "1".repeat(257)); + // 2,000 rows of 20 values of eight digits are more CSV than a graph value holds. + let row = format!("{}", "12345678".repeat(20)); + let long_graph = format!("{}", row.repeat(2_000)); let cases = [ ("not well-formed XML", "".to_string()), ("no `variableSets` element", "".to_string()), ("declares no variables", "".to_string()), ("is declared twice", library(&[("Name", "textcontent"), ("Name", "textcontent")], &[])), - ("has no `trait`", ok.replace(" trait=\"textcontent\"", "")), + ("for `Shown` that isn't `true` or `false`", kind_value("visibility", "maybe")), + ("for `Shown` that isn't `true` or `false`", kind_value("visibility", "

true

")), + ("for `Shown` that isn't a file's absolute path or `file:` URL", kind_value("fileref", "logo.png")), + ("for `Shown` that isn't a file's absolute path or `file:` URL", kind_value("fileref", "C:logo.png")), + ("for `Shown` that isn't a file's absolute path or `file:` URL", kind_value("fileref", "file:logo.png")), + ("for `Shown` that isn't a graph's `data` element", kind_value("graphdata", "1,2")), + ("for `Shown` that isn't a graph's `data` element", kind_value("graphdata", "")), + ("for `Shown` that isn't a graph's `data` element", kind_value("graphdata", "")), + ("graph value for `Shown` longer than 262144 bytes", kind_value("graphdata", &long_graph)), + ("graph value for `Shown` with more than 10000 rows or 256 series", kind_value("graphdata", &rows_past)), + ("graph value for `Shown` with more than 10000 rows or 256 series", kind_value("graphdata", &series_past)), ("missing `varName`", ok.replace("varName=\"Name\"", "varName=\" \"")), ("missing `dataSetName`", ok.replace(" dataSetName=\"A\"", "")), ("data set `A` is declared twice", library(&[("Name", "textcontent")], &[("A", &[]), ("A", &[])])), @@ -2521,51 +2623,50 @@ fn a_variable_library_expands_entities_of_plain_text() { assert_eq!(value, Some(vectorcraft_doc::DataValue::Text("x-y \"z\"-x&a;".into()))); } -/// Save Variable Library writes what Load Variable Library reads back: the text variables in their -/// order, every data set by name and in order, and each text value as it was, with several lines, -/// markup characters, quotes, a carriage return and an empty value. Variables of other kinds are -/// left out with their values, named in `skipped` and in the warning. The library is written while -/// the variables are locked too, to a file with `path`. +/// Save Variable Library writes what Load Variable Library reads back: the variables of every kind +/// in their order, every data set by name and in order, and each value as it was: text with several +/// lines, markup characters, quotes, a carriage return and an empty value; visibility values; +/// image paths with spaces, markup characters, `%`, `#` and letters past ASCII, from a Unix root, +/// a drive and a share; and graph data with series, categories, a numeric category and blanks. A +/// variable of unknown kind is declared without a `trait` and loads back as one. The library is +/// written while the variables are locked too, to a file with `path`. #[test] -fn a_saved_variable_library_loads_back_the_text_variables_and_data_sets() { +fn a_saved_variable_library_loads_back_every_variable_and_data_set() { let mut s = session(); let t = text(&mut s, "Alice"); - for (name, kind) in [("Name", "text"), ("Shown", "visibility"), ("Note", "text"), ("Photo", "image"), ("Badge", "visibility")] { + for (name, kind) in [("Name", "text"), ("Shown", "visibility"), ("Note", "text"), ("Photo", "image"), ("Chart", "graph"), ("Badge", "visibility")] + { s.execute("variable.define", &json!({"name": name, "kind": kind})).unwrap(); } s.execute("variable.bind", &json!({"variable": "Name", "ids": [t.0]})).unwrap(); - s.execute("dataset.new", &json!({"name": "First", "values": {"Name": "Bravo", "Note": "One\nTwo & \r\n'four' \"five\"", "Shown": true}})) - .unwrap(); - s.execute("dataset.new", &json!({"name": "Say \"hi\" & \tnow", "values": {"Name": "", "Photo": "a.png"}})).unwrap(); + let chart = ",North,\"S, \"\"q\"\"\"\nQ1,10,2.5\n\"2024\",,-4"; + let first = json!({"Name": "Bravo", "Note": "One\nTwo & \r\n'four' \"five\"", "Shown": true, "Photo": "/Users/me/Art & 100%/#1 ü.png", "Chart": chart}); + s.execute("dataset.new", &json!({"name": "First", "values": first})).unwrap(); + let second = json!({"Name": "", "Photo": "C:\\Art\\logo.png", "Badge": false, "Chart": ",,\n7,8"}); + s.execute("dataset.new", &json!({"name": "Say \"hi\" & \tnow", "values": second})).unwrap(); + s.execute("dataset.new", &json!({"name": "Share", "values": {"Photo": "\\\\server\\share\\a.png"}})).unwrap(); s.execute("dataset.new", &json!({"name": "Empty"})).unwrap(); + // A file can declare a variable of unknown kind, which no command defines. + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc) + .variables + .variables + .push(vectorcraft_doc::Variable { name: "Loose name".into(), kind: vectorcraft_doc::VariableKind::Unknown }); s.execute("variable.lock", &json!({"locked": true})).unwrap(); let before = s.doc().unwrap().doc.variables.clone(); let saved = s.execute("variable.saveLibrary", &json!({})).unwrap(); - assert_eq!(saved["variables"], json!(["Name", "Note"])); - assert_eq!(saved["datasets"], json!(3)); - assert_eq!( - saved["skipped"], - json!([{"name": "Shown", "kind": "visibility"}, {"name": "Photo", "kind": "image"}, {"name": "Badge", "kind": "visibility"}]) - ); - assert_eq!(saved["warning"], "variables that aren't text were left out: visibility (2), image (1)"); + assert_eq!(saved["variables"], json!(["Name", "Shown", "Note", "Photo", "Chart", "Badge", "Loose name"])); + assert_eq!(saved["datasets"], json!(4)); + assert_eq!((saved.get("skipped"), saved.get("warning")), (None, None)); assert_eq!(s.doc().unwrap().doc.variables, before, "saving changes nothing"); let mut other = session(); - let loaded = other.execute("variable.loadLibrary", &json!({"xml": saved["xml"]})).unwrap(); - assert_eq!((loaded["skipped"].clone(), loaded.get("warning")), (json!([]), None)); + other.execute("variable.loadLibrary", &json!({"xml": saved["xml"]})).unwrap(); let vars = &other.doc().unwrap().doc.variables; - assert_eq!(vars.variables.iter().map(|v| (v.name.as_str(), v.kind.label())).collect::>(), [("Name", "text"), ("Note", "text")]); - let text_only: Vec = before - .datasets - .iter() - .map(|d| { - let mut d = d.clone(); - d.values.retain(|k, _| k == "Name" || k == "Note"); - d - }) - .collect(); - assert_eq!(vars.datasets, text_only); + assert_eq!(vars.variables, before.variables); + assert_eq!(vars.datasets, before.datasets); + // Saving the loaded library again writes the same file. + assert_eq!(other.execute("variable.saveLibrary", &json!({})).unwrap()["xml"], saved["xml"]); let dir = Folder::new("vars-save-library"); let path = dir.file("library.xml"); @@ -2575,19 +2676,78 @@ fn a_saved_variable_library_loads_back_the_text_variables_and_data_sets() { assert_eq!(std::fs::read_to_string(&path).unwrap(), saved["xml"].as_str().unwrap()); let mut from_file = session(); from_file.execute("variable.loadLibrary", &json!({"path": path})).unwrap(); - assert_eq!(from_file.doc().unwrap().doc.variables.datasets, text_only); + assert_eq!(from_file.doc().unwrap().doc.variables.datasets, before.datasets); +} + +/// Graph data whose categories are all blank keeps them through a save and a load, and so does +/// graph data of series names without rows; graph data with neither is refused. An image value +/// written as a `file:/…` URL without a host loads as its path, graph data with more series than a +/// graph holds is refused, and wide graph data is checked against the size cap as it is written. +#[test] +fn saved_graph_values_and_file_urls_load_back_at_their_edges() { + let mut s = session(); + s.execute("variable.define", &json!({"name": "Chart", "kind": "graph"})).unwrap(); + s.execute("dataset.new", &json!({"name": "A", "values": {"Chart": ",S\n\"\",1\n\"\",2"}})).unwrap(); + let xml = s.execute("variable.saveLibrary", &json!({})).unwrap()["xml"].as_str().unwrap().to_string(); + assert!(xml.contains("1"), "{xml}"); + let mut other = session(); + other.execute("variable.loadLibrary", &json!({"xml": xml})).unwrap(); + assert_eq!(other.doc().unwrap().doc.variables.datasets, s.doc().unwrap().doc.variables.datasets); + // Series names without rows load back, and graph data with neither is refused. + s.execute("dataset.set", &json!({"name": "A", "values": {"Chart": ",North,South"}})).unwrap(); + let xml = s.execute("variable.saveLibrary", &json!({})).unwrap()["xml"].clone(); + let mut other = session(); + other.execute("variable.loadLibrary", &json!({"xml": xml})).unwrap(); + assert_eq!(other.doc().unwrap().doc.variables.datasets, s.doc().unwrap().doc.variables.datasets); + s.execute("dataset.set", &json!({"name": "A", "values": {"Chart": ","}})).unwrap(); + let e = s.execute("variable.saveLibrary", &json!({})).unwrap_err().to_string(); + assert!(e.contains("graph value for `Chart` without rows or series"), "{e}"); + + let url = "\ + file:/tmp/logo%20one.png\ + file:/C:/Art/logo.png"; + let mut s = session(); + s.execute("variable.loadLibrary", &json!({"xml": url})).unwrap(); + let image = |set: &str| s.doc().unwrap().doc.variables.dataset(set).and_then(|d| d.values.get("Photo")).cloned(); + assert_eq!(image("A"), Some(vectorcraft_doc::DataValue::Image("/tmp/logo one.png".into()))); + assert_eq!(image("B"), Some(vectorcraft_doc::DataValue::Image("C:/Art/logo.png".into()))); + + // More series than a graph holds are refused. + let mut s = session(); + s.execute("variable.define", &json!({"name": "Chart", "kind": "graph"})).unwrap(); + let wide = (0..257).map(|i| i.to_string()).collect::>().join(","); + s.execute("dataset.new", &json!({"name": "A", "values": {"Chart": wide}})).unwrap(); + let e = s.execute("variable.saveLibrary", &json!({})).unwrap_err().to_string(); + assert!(e.contains("graph value for `Chart` with more than 10000 rows or 256 series"), "{e}"); + // One row of 256 values and 1,000 rows of one: every row is written 256 values wide. + let mut csv = (0..256).map(|i| i.to_string()).collect::>().join(","); + for i in 0..1_000 { + csv += &format!("\n{i}"); + } + s.execute("dataset.set", &json!({"name": "A", "values": {"Chart": csv.clone()}})).unwrap(); + let xml = s.execute("variable.saveLibrary", &json!({})).unwrap()["xml"].as_str().unwrap().to_string(); + assert_eq!(xml.matches("").count(), 1_001); + assert!(xml.contains("")); + // Rows that make the library larger than 8 MiB are refused as each is written. + for i in 1_000..9_000 { + csv += &format!("\n{i}"); + } + s.execute("dataset.set", &json!({"name": "A", "values": {"Chart": csv}})).unwrap(); + let e = s.execute("variable.saveLibrary", &json!({})).unwrap_err().to_string(); + assert!(e.contains("larger than 8388608 bytes"), "{e}"); } /// The library is the XML of the public grammar: a document type declaration with the namespace -/// entities, `variableSets` › `variableSet` › `variables` with a `textcontent` variable per text -/// variable, and `sampleDataSets` with a `sampleDataSet` per data set, holding an element per text -/// variable it has a value for, with a `p` element per line. Markup characters, a carriage return, -/// and a tab or quote in a data set name are escaped. A document with text variables and no data -/// sets writes an empty `sampleDataSets`. +/// entities, `variableSets` › `variableSet` › `variables` with a variable per variable, its `trait` +/// and `category` those of its kind, and `sampleDataSets` with a `sampleDataSet` per data set, +/// holding an element per variable it has a value for: a `p` element per line of a text value, +/// `true` or `false`, a `file:` URL for an image's path from a Unix root, and a `data` element for +/// graph data. Markup characters, a carriage return, and a tab or quote in a data set name are +/// escaped. A document with variables and no data sets writes an empty `sampleDataSets`. #[test] fn a_saved_variable_library_has_the_library_layout() { let mut s = session(); - for (name, kind) in [("Name", "text"), ("Shown", "visibility"), ("Note", "text")] { + for (name, kind) in [("Name", "text"), ("Shown", "visibility"), ("Note", "text"), ("Photo", "image"), ("Chart", "graph")] { s.execute("variable.define", &json!({"name": name, "kind": kind})).unwrap(); } let head = "\n\ @@ -2595,13 +2755,17 @@ fn a_saved_variable_library_has_the_library_layout() { \t\n\ \t\n\ \t\n\ + \t\n\ ]>\n\ \n\ \n\ \t\n\ \t\t\n\ \t\t\t\n\ + \t\t\t\n\ \t\t\t\n\ + \t\t\t\n\ + \t\t\t\n\ \t\t\n\ \t\t\n"; let tail = "\t\t\n\t\n\n\n"; @@ -2609,7 +2773,8 @@ fn a_saved_variable_library_has_the_library_layout() { assert_eq!(empty["xml"].as_str().unwrap(), format!("{head}{tail}")); assert_eq!(empty["datasets"], json!(0)); - s.execute("dataset.new", &json!({"name": "A &\t\"B\"", "values": {"Name": "x\r\ny < z", "Shown": false}})).unwrap(); + let values = json!({"Name": "x\r\ny < z", "Shown": false, "Photo": "/art/a b.png", "Chart": ",S\nQ1,1\n2,"}); + s.execute("dataset.new", &json!({"name": "A &\t\"B\"", "values": values})).unwrap(); s.execute("dataset.new", &json!({"name": "C", "values": {"Note": ""}})).unwrap(); let xml = s.execute("variable.saveLibrary", &json!({})).unwrap()["xml"].as_str().unwrap().to_string(); let sets = "\t\t\t\n\ @@ -2617,6 +2782,17 @@ fn a_saved_variable_library_has_the_library_layout() { \t\t\t\t\t

x

\n\ \t\t\t\t\t

y < z

\n\ \t\t\t\t\n\ + \t\t\t\tfalse\n\ + \t\t\t\tfile:////art/a%20b.png\n\ + \t\t\t\t\n\ + \t\t\t\t\t\n\ + \t\t\t\t\t\tS\n\ + \t\t\t\t\t\t\n\ + \t\t\t\t\t\t\tQ11\n\ + \t\t\t\t\t\t\t2\n\ + \t\t\t\t\t\t\n\ + \t\t\t\t\t\n\ + \t\t\t\t\n\ \t\t\t
\n\ \t\t\t\n\ \t\t\t\t\n\ @@ -2626,10 +2802,11 @@ fn a_saved_variable_library_has_the_library_layout() { assert_eq!(xml, format!("{head}{sets}{tail}")); } -/// Save Variable Library refuses a document without variables or without text variables, a text -/// variable whose name can't name an element, a data set name or text value with a character XML -/// can't hold, a name that Load Variable Library would read differently or refuse, and a library -/// past the caps that Load Variable Library reads. A refused save writes no file. +/// Save Variable Library refuses a document without variables, a variable whose name can't name an +/// element (but for a variable of unknown kind), a data set name, text value or graph label with a +/// character XML can't hold, an image value that isn't a file's absolute path, a name that Load +/// Variable Library would read differently or refuse, and a library past the caps that Load +/// Variable Library reads. A refused save writes no file. #[test] fn save_variable_library_refuses_what_a_library_cant_hold() { let dir = Folder::new("vars-save-refused"); @@ -2642,14 +2819,41 @@ fn save_variable_library_refuses_what_a_library_cant_hold() { let mut s = session(); refused(&mut s, "define a variable first"); + // A library without text variables is saved. s.execute("variable.define", &json!({"name": "Shown", "kind": "visibility"})).unwrap(); - refused(&mut s, "holds text variables, and the document has none"); + assert_eq!(s.execute("variable.saveLibrary", &json!({})).unwrap()["variables"], json!(["Shown"])); - for name in ["First Name", "1st", "a:b", "x/y", "-dash"] { + for (name, kind) in [("First Name", "text"), ("1st", "visibility"), ("a:b", "image"), ("x/y", "graph"), ("-dash", "text")] { let mut s = session(); - s.execute("variable.define", &json!({"name": name, "kind": "text"})).unwrap(); + s.execute("variable.define", &json!({"name": name, "kind": kind})).unwrap(); refused(&mut s, &format!("variable `{name}` can't be saved in a variable library")); } + // No element is named after a variable of unknown kind, so its name can be any name. + let mut s = session(); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc) + .variables + .variables + .push(vectorcraft_doc::Variable { name: "First \"Name\" & ".into(), kind: vectorcraft_doc::VariableKind::Unknown }); + let xml = s.execute("variable.saveLibrary", &json!({})).unwrap()["xml"].clone(); + let mut other = session(); + other.execute("variable.loadLibrary", &json!({"xml": xml})).unwrap(); + assert_eq!(other.doc().unwrap().doc.variables.variables, s.doc().unwrap().doc.variables.variables); + + // An image value that isn't a file's absolute path, which Load Variable Library refuses. + for path in ["a.png", "C:a.png", "C:\\a.png ", "/"] { + let mut s = session(); + s.execute("variable.define", &json!({"name": "Photo", "kind": "image"})).unwrap(); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).variables.datasets.push(vectorcraft_doc::DataSet { + name: "A".into(), + values: [("Photo".to_string(), vectorcraft_doc::DataValue::Image(path.into()))].into(), + }); + refused(&mut s, "data set `A` holds an image value for `Photo` that isn't a file's absolute path"); + } + // A graph label with a character XML can't hold. + let mut s = session(); + s.execute("variable.define", &json!({"name": "Chart", "kind": "graph"})).unwrap(); + s.execute("dataset.new", &json!({"name": "A", "values": {"Chart": ",S\u{1}\nQ1,1"}})).unwrap(); + refused(&mut s, "data set `A` holds a control character"); for name in ["Ünïcode", "_x", "a.b-c_d", "名前"] { let mut s = session(); s.execute("variable.define", &json!({"name": name, "kind": "text"})).unwrap(); @@ -2747,10 +2951,10 @@ fn a_saved_variable_library_near_the_size_cap_loads_back() { /// While the variables are locked, a library that would delete or define a variable is refused, as /// Delete Variable and New Variable are, and the document keeps its variables and data sets. That -/// covers a library without text variables loaded into a document with variables, and one that -/// adds a text variable to the document's. A library of the document's own text variables, and -/// one without text variables loaded into a document without variables, delete and define none: -/// they load, replacing the data sets. +/// covers a library of other variables loaded into a document with variables, one that adds a +/// variable to the document's, one that declares a document variable's name with another kind, and +/// any library loaded into a document without variables. A library of the document's own variables +/// with their kinds deletes and defines none: it loads, replacing the data sets. #[test] fn locked_variables_refuse_a_library_that_deletes_or_defines_variables() { let mut s = session(); @@ -2758,7 +2962,7 @@ fn locked_variables_refuse_a_library_that_deletes_or_defines_variables() { s.execute("dataset.new", &json!({"name": "A", "values": {"Name": "Old"}})).unwrap(); s.execute("variable.lock", &json!({"locked": true})).unwrap(); let before = s.doc().unwrap().doc.variables.clone(); - for vars in [&[("Shown", "other")][..], &[("Name", "textcontent"), ("Note", "textcontent")][..]] { + for vars in [&[("Shown", "other")][..], &[("Name", "textcontent"), ("Note", "textcontent")][..], &[("Name", "visibility")][..]] { let e = s.execute("variable.loadLibrary", &json!({"xml": library(vars, &[("B", &[])])})).unwrap_err(); assert!(matches!(&e, EngineError::Disabled(cmd, why) if cmd == "variable.loadLibrary" && why == "variables are locked"), "{e}"); assert_eq!(s.doc().unwrap().doc.variables, before); @@ -2770,13 +2974,13 @@ fn locked_variables_refuse_a_library_that_deletes_or_defines_variables() { let mut s = session(); s.execute("dataset.new", &json!({"name": "A"})).unwrap(); s.execute("variable.lock", &json!({"locked": true})).unwrap(); - let e = s.execute("variable.loadLibrary", &json!({"xml": library(&[("Name", "textcontent")], &[])})).unwrap_err(); - assert!(matches!(&e, EngineError::Disabled(_, why) if why == "variables are locked"), "{e}"); - let r = s.execute("variable.loadLibrary", &json!({"xml": library(&[("Shown", "other")], &[("B", &[])])})).unwrap(); - assert_eq!((r["deletedDataSets"].clone(), r["names"].clone()), (json!(["A"]), json!(["B"]))); + for vars in [&[("Name", "textcontent")][..], &[("Shown", "other")][..]] { + let e = s.execute("variable.loadLibrary", &json!({"xml": library(vars, &[("B", &[])])})).unwrap_err(); + assert!(matches!(&e, EngineError::Disabled(_, why) if why == "variables are locked"), "{e}"); + } let vars = &s.doc().unwrap().doc.variables; assert!(vars.variables.is_empty() && vars.locked); - assert_eq!(vars.datasets.iter().map(|d| d.name.as_str()).collect::>(), ["B"]); + assert_eq!(vars.datasets.iter().map(|d| d.name.as_str()).collect::>(), ["A"]); } /// A graph variable's data set applies its CSV as `graph.setData` does: a right-axis series the row's data no longer @@ -3099,6 +3303,10 @@ fn an_svg_without_readable_variable_data_opens_its_art() { let head = ""; let art = ""; let untraited = format!("{head}{art}"); + let relative = format!( + "{head}\ +

kept

a.png{art}" + ); let refs = "&ns_big;".repeat(40_000); let big = "x".repeat(250); let growing = format!( @@ -3154,11 +3362,23 @@ fn an_svg_without_readable_variable_data_opens_its_art() { assert!(warnings.is_empty(), "{warnings:?}"); assert_eq!(o.doc().unwrap().doc.variables.variables.len(), 1); - for (svg, why) in [(untraited, "variable `A` has no `trait`"), (growing, "entities expand to more than")] { - let (o, warnings) = svg_opened(&svg, "broken.svg"); - assert!(warnings.iter().any(|w| w.as_str().is_some_and(|w| w.contains("variable data wasn't read") && w.contains(why))), "{warnings:?}"); - let d = &o.doc().unwrap().doc; - assert!(d.variables.variables.is_empty()); - assert_eq!(vectorcraft_testkit::svg_shapes(&vectorcraft_svg::export(d, &Default::default())), 1, "the art opens"); - } + // A variable without a `trait` is of unknown kind: the SVG leaves it out like the other kinds + // that aren't text. + let (o, warnings) = svg_opened(&untraited, "untraited.svg"); + assert!(warnings.contains(&json!("variables that aren't text were left out: unknown (1)")), "{warnings:?}"); + assert!(o.doc().unwrap().doc.variables.variables.is_empty()); + // The values of the other kinds aren't read, so one that Load Variable Library would refuse + // leaves the text variables and their values as they open. + let (o, warnings) = svg_opened(&relative, "relative.svg"); + assert!(warnings.contains(&json!("variables that aren't text were left out: fileref (1)")), "{warnings:?}"); + let vars = &o.doc().unwrap().doc.variables; + assert_eq!(vars.variables.iter().map(|v| v.name.as_str()).collect::>(), ["T"]); + assert_eq!(vars.dataset("D").map(|d| d.values.clone()), Some([("T".to_string(), vectorcraft_doc::DataValue::Text("kept".into()))].into())); + + let (o, warnings) = svg_opened(&growing, "broken.svg"); + let why = "entities expand to more than"; + assert!(warnings.iter().any(|w| w.as_str().is_some_and(|w| w.contains("variable data wasn't read") && w.contains(why))), "{warnings:?}"); + let d = &o.doc().unwrap().doc; + assert!(d.variables.variables.is_empty()); + assert_eq!(vectorcraft_testkit::svg_shapes(&vectorcraft_svg::export(d, &Default::default())), 1, "the art opens"); } diff --git a/crates/engine/src/tests/xform.rs b/crates/engine/src/tests/xform.rs index f507b765c6..1a41488285 100644 --- a/crates/engine/src/tests/xform.rs +++ b/crates/engine/src/tests/xform.rs @@ -1115,6 +1115,92 @@ fn lasso_picks_gradient_mesh_points() { assert_eq!(red, top, "only the points inside the loop are recoloured"); } +/// With gradient mesh points picked, the Fill proxy (and the Color panel that edits it) shows +/// the color a solid fill gives them, not the mesh object's own fill: "?" when the picked +/// points' colors differ, the object's fill again once no point is picked. +#[test] +fn the_fill_proxy_shows_the_picked_mesh_points_color() { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 100.0, 100.0); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff8500"})).unwrap(); + s.execute("object.mesh.create", &json!({"rows": 2, "cols": 2})).unwrap(); + let object_fill = s.proxy_paints().0; + // Round the top row of points. + gesture(&mut s, "lasso", &[(90.0, 90.0), (210.0, 90.0), (210.0, 110.0), (90.0, 110.0), (90.0, 110.0)], Mods::default()); + s.execute("paint.setFill", &json!({"color": "#3366ff"})).unwrap(); + let shown = s.execute("paint.proxies", &json!({})).unwrap(); + assert_eq!(s.proxy_paints().0.color().map(|c| c.to_hex()), Some("#3366ff".into()), "the picked points' color: {shown}"); + assert_eq!(shown["fillMixed"], json!(false)); + assert_eq!(shown["fill"], json!(s.proxy_paints().0)); + // One picked point takes another color: the points differ. + let Some(NodeKind::Mesh(m)) = s.doc().unwrap().doc.node(a).map(|n| &n.kind) else { panic!("still a gradient mesh") }; + let first = m.idx(0, 0); + s.execute("object.mesh.setPointColor", &json!({"id": a.0, "index": first, "color": "#00ff00"})).unwrap(); + assert!(s.proxy_mixed().0, "the picked points' colors differ"); + // Picking none (the Selection tool) shows the object's fill again. + s.select_tool("selection", ViewInfo::default()).unwrap(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + assert_eq!(s.proxy_paints().0, object_fill); + assert!(!s.proxy_mixed().0); +} + +/// With the Appearance panel's stroke row active, a solid fill still recolors the picked mesh +/// points, so the Fill proxy shows them; with its fill row active, the fill goes to that row, and +/// the proxy shows the row. +#[test] +fn the_fill_proxy_follows_where_the_fill_goes_with_an_appearance_row_active() { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 100.0, 100.0); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("object.mesh.create", &json!({"rows": 2, "cols": 2})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff8500"})).unwrap(); + s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap(); + let items = &s.doc().unwrap().doc.node(a).unwrap().appearance.items; + let fill_row = items.iter().position(|it| it.is_fill()).expect("a fill row"); + let stroke_row = items.iter().position(|it| !it.is_fill()).expect("a stroke row"); + gesture(&mut s, "lasso", &[(90.0, 90.0), (210.0, 90.0), (210.0, 110.0), (90.0, 110.0), (90.0, 110.0)], Mods::default()); + assert_eq!(s.fill_mesh_points().first().map(|(_, v)| v.len()), Some(3), "the top row is picked"); + let point_color = |s: &Session| { + let Some(NodeKind::Mesh(m)) = s.doc().unwrap().doc.node(a).map(|n| &n.kind) else { panic!("still a gradient mesh") }; + m.points[m.idx(0, 0)].color.to_hex() + }; + + s.execute("appearance.setActiveItem", &json!({"index": stroke_row})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#3366ff"})).unwrap(); + assert_eq!(point_color(&s), "#3366ff", "the stroke row leaves the fill on the picked points"); + assert_eq!(s.proxy_paints().0.color().map(|c| c.to_hex()), Some("#3366ff".into())); + assert!(!s.proxy_mixed().0); + + s.execute("appearance.setActiveItem", &json!({"index": fill_row})).unwrap(); + assert!(s.fill_mesh_points().is_empty()); + s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap(); + assert_eq!(point_color(&s), "#3366ff", "the fill row takes the fill"); + assert_eq!(s.proxy_paints().0.color().map(|c| c.to_hex()), Some("#00ff00".into())); +} + +/// A gradient mesh with points picked selected with another object: a solid fill recolors the +/// points and fills the other object, and the Fill proxy and its "?" count the points' colors. +#[test] +fn the_fill_proxy_counts_picked_mesh_points_beside_other_objects() { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 100.0, 100.0); + let b = rect(&mut s, 300.0, 300.0, 50.0, 50.0); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("object.mesh.create", &json!({"rows": 2, "cols": 2})).unwrap(); + gesture(&mut s, "lasso", &[(90.0, 90.0), (210.0, 90.0), (210.0, 110.0), (90.0, 110.0), (90.0, 110.0)], Mods::default()); + s.execute("select.add", &json!({"ids": [b.0]})).unwrap(); + assert_eq!(s.doc().unwrap().selection.objects, vec![a, b]); + assert_eq!(s.fill_mesh_points().first().map(|(id, v)| (*id, v.len())), Some((a, 3)), "the top row is still picked"); + s.execute("paint.setFill", &json!({"color": "#3366ff"})).unwrap(); + let Some(NodeKind::Mesh(m)) = s.doc().unwrap().doc.node(a).map(|n| &n.kind) else { panic!("still a gradient mesh") }; + assert_eq!(m.points[m.idx(0, 0)].color.to_hex(), "#3366ff"); + assert_eq!(s.proxy_paints().0.color().map(|c| c.to_hex()), Some("#3366ff".into())); + assert!(!s.proxy_mixed().0, "the points and the other object are the same color"); + s.execute("paint.setFill", &json!({"ids": [b.0], "color": "#00ff00"})).unwrap(); + assert!(s.proxy_mixed().0, "the picked points and the other object's fill differ"); +} + /// Shift-drag a marquee with the Selection tool (#483): the selected objects it reaches are /// deselected and the others selected, the rest of the selection staying as it was. #[test] diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index bb29b06e75..f6bc163e65 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -429,6 +429,7 @@ impl Session { }, screen: view.screen, plane_widget: self.prefs.perspective_widget.show.then_some(self.prefs.perspective_widget.position), + plane_targets: self.prefs.perspective_widget.targets(), precise_cursors: self.precise_cursors(), global_edit: st.global_edit.as_ref().map_or(&[], |g| g.members.as_slice()), }; @@ -650,7 +651,7 @@ impl Session { match ev.kind { PointerKind::Down | PointerKind::Drag => self.pointer_held = true, PointerKind::Up | PointerKind::Move => self.pointer_held = false, - PointerKind::DoubleClick => {} + PointerKind::DoubleClick | PointerKind::TripleClick => {} } match ev.kind { PointerKind::Down => { @@ -1543,7 +1544,7 @@ impl Session { if !std::sync::Arc::ptr_eq(&it.doc, &st.doc) { return None; } - let interaction_fields = (it.preview.clone(), it.copies.clone(), it.perspective_again.clone()); + let interaction_fields = (it.preview.clone(), it.copies.clone(), it.perspective_again.clone(), it.plane_placed); (st.doc.clone(), st.selection.clone(), st.revision, self.pending_paint.clone(), interaction_fields) }; let (overlays, transform_box) = if self.preview(cmd, p).is_ok() { @@ -1565,6 +1566,7 @@ impl Session { it.preview = interaction_fields.0; it.copies = interaction_fields.1; it.perspective_again = interaction_fields.2; + it.plane_placed = interaction_fields.3; } } self.pending_paint = paint; diff --git a/crates/engine/tests/color_settings.rs b/crates/engine/tests/color_settings.rs index e8b3ab0906..b02e34690b 100644 --- a/crates/engine/tests/color_settings.rs +++ b/crates/engine/tests/color_settings.rs @@ -149,6 +149,34 @@ fn loading_an_assigned_profile_again_keeps_it_in_use() { assert_eq!(cms::working_settings(), working); } +/// A document behind the front one draws through its own assigned profile: loading that profile's +/// file again or removing it redraws the document, and the front document stays as it was. +#[test] +fn loading_or_removing_a_back_documents_profile_redraws_it() { + const NAME: &str = "Back RGB P"; + let _g = settings(); + let dir = fresh_dir("back-assigned"); + let _reset = ColorSettingsReset { profile: Some(NAME), paths: vec![dir.clone()] }; + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("back.icc"); + std::fs::write(&path, icc_named(NAME)).unwrap(); + let mut s = session(); + let load = |s: &mut Session| assert_eq!(exec(s, "color.loadProfile", json!({"path": path.to_str().unwrap()}))["name"], NAME); + load(&mut s); + exec(&mut s, "edit.assignProfile", json!({"rgb": NAME})); + exec(&mut s, "file.new", json!({"width": 100, "height": 100})); + let revisions = |s: &Session| s.documents().iter().map(|d| d.revision).collect::>(); + let before = revisions(&s); + load(&mut s); + let loaded = revisions(&s); + assert!(loaded[0] > before[0], "the back document assigned the profile redraws after a load"); + assert_eq!(loaded[1], before[1], "the front document does not use it"); + exec(&mut s, "color.removeProfile", json!({"name": NAME})); + let removed = revisions(&s); + assert!(removed[0] > loaded[0], "the back document assigned the profile redraws after a removal"); + assert_eq!(removed[1], loaded[1], "the front document does not use it"); +} + /// A batch that assigns a profile and then changes the color mode, as Document Setup's OK does, /// converts the colors through the profile it assigns. #[test] diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index 797ca39f52..fce3742d11 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -5,6 +5,7 @@ #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use serde_json::{Value, json}; +use vectorcraft_engine::cmd::{Location, ParamsPlace}; use vectorcraft_engine::{Session, command_specs}; use vectorcraft_testkit::catch_quiet; use vectorcraft_testkit::fixtures::Fixture; @@ -272,44 +273,46 @@ fn tool_edit_cases(c: &vectorcraft_engine::CommandSpec, path: &str) -> Vec) { +/// The strings in `v`, the value at `at` (found at `place`) in a case of command `id`, that name a +/// place on disk outside `dir`, as `id at: value`: `v` itself and the members of arrays in it when +/// `named` (it is under a key that names a file or folder), and in objects at any depth, the values +/// under such keys as the command reads them (`vectorcraft_engine::cmd::ParamsPlace`). +fn outside_locations( + id: &str, + at: &str, + v: &Value, + place: ParamsPlace, + named: bool, + dir: &std::path::Path, + out: &mut std::collections::BTreeSet, +) { match v { Value::String(s) if named && !std::path::Path::new(s).starts_with(dir) => { out.insert(format!("{id} {at}: {v}")); } Value::Array(a) => { + let step = ParamsPlace::step(a); for (i, x) in a.iter().enumerate() { - outside_locations(id, &format!("{at}[{i}]"), x, named, dir, out); + outside_locations(id, &format!("{at}[{i}]"), x, place.item(i, step), named, dir, out); } } Value::Object(o) => { + let carried = ParamsPlace::carried(o); for (k, x) in o { - outside_locations(id, &format!("{at}.{k}"), x, names_location(None, k), dir, out); + let (below, location) = place.member(k, carried); + outside_locations(id, &format!("{at}.{k}"), x, below, location.is_some(), dir, out); } } _ => {} } } -/// Does `key` name a file or folder, in command `spec` when given: a key in -/// `vectorcraft_engine::cmd::key_location`'s list that `vectorcraft_engine::cmd::location_in` keeps -/// for `spec`. -fn names_location(spec: Option<&vectorcraft_engine::CommandSpec>, key: &str) -> bool { - match spec { - Some(spec) => vectorcraft_engine::cmd::location_in(spec, key).is_some(), - None => vectorcraft_engine::cmd::key_location(key).is_some(), - } -} - /// Every string the sweeps send under a key that names a file or folder, in the command catalog /// (`vectorcraft_engine::cmd::location_keys`, so a command added later is checked too) or inside /// an object or an array at any depth, is inside the sweep's temp folder, so no run reads or /// writes in the working directory. `every_command_with_junk_params` sends every such key of every -/// command alone in at least one case ([`junk_cases`]). +/// command alone in at least one case ([`junk_cases`]). Which catalog keys name a file or folder is +/// checked on its own by [`catalog_path_keys_match_location_policy`]. #[test] fn sweep_cases_name_files_only_inside_the_temp_folder() { let dir = vectorcraft_testkit::TempDir::new("sweep"); @@ -330,7 +333,8 @@ fn sweep_cases_name_files_only_inside_the_temp_folder() { for p in &cases { let Some(o) = p.as_object() else { continue }; for (k, v) in o { - outside_locations(c.id, k, v, names_location(Some(c), k), &dir, &mut outside); + let (below, location) = ParamsPlace::top(Some(c)).member(k, None); + outside_locations(c.id, k, v, below, location.is_some(), &dir, &mut outside); } } } @@ -339,6 +343,104 @@ fn sweep_cases_name_files_only_inside_the_temp_folder() { assert!(outside.is_empty(), "{} cases name a location outside {}:\n{}", outside.len(), dir.display(), outside.join("\n")); } +/// The param keys that name a file or a folder, and which. +const LOCATION_KEYS: &[(&str, Location)] = &[ + ("path", Location::File), + ("paths", Location::File), + ("file", Location::File), + ("files", Location::File), + ("diffPath", Location::File), + ("folder", Location::Folder), + ("dir", Location::Folder), + ("directory", Location::Folder), + ("destinationFolder", Location::Folder), + ("sourceFolder", Location::Folder), + ("fontsFolder", Location::Folder), + ("pluginsFolder", Location::Folder), + ("recoveryFolder", Location::Folder), + ("templatesFolder", Location::Folder), +]; + +/// Param keys that read like a file or folder key ([`reads_like_a_location`]) and name neither: +/// web links, an export's grouping of its files, and choices and switches. +const NOT_LOCATIONS: &[&str] = &[ + "url", + "copyrightUrl", + "folders", + "alignToPath", + "wholePaths", + "emptyTextPaths", + "sortPaths", + "alterPaths", + "includeLinkedFiles", + "linksFolder", +]; + +/// Commands and the key in [`LOCATION_KEYS`] that, at the top of their params, names part of the +/// document (a path of its art, a result field), not a file. +const DOCUMENT_PARTS: &[(&str, &str)] = &[ + ("object.setLiveShape", "path"), + ("path.reverse", "paths"), + ("object.pathfinder.options", "paths"), + ("object.maskImage", "path"), + ("text.createInPath", "path"), + ("symbol.instance.setAppearance", "path"), + ("symbol.instance.selectPart", "path"), + ("object.objectsOnPath.attach", "path"), + ("svgInteractivity.info", "files"), + ("addon.cleanup.rejoin", "paths"), +]; + +/// Does param key `k` read like one that names a file, a folder or a link: a bare name for one, or a +/// name that ends like one? +fn reads_like_a_location(k: &str) -> bool { + const ENDS: &[&str] = &["Path", "Paths", "File", "Files", "Folder", "Folders", "Dir", "Directory", "Url", "URL"]; + matches!(k, "path" | "paths" | "file" | "files" | "folder" | "folders" | "dir" | "directory" | "url") || ENDS.iter().any(|end| k.ends_with(end)) +} + +/// Every key of every command that reads like a file or folder key (in its params description, the +/// commands its `…` entries name and its schema) is in [`LOCATION_KEYS`] or [`NOT_LOCATIONS`], so a +/// command that adds one fails here until it is sorted. The generic classifications +/// (`vectorcraft_engine::cmd::key_location`, `vectorcraft_engine::file_access::is_path_key`) agree +/// with those lists, and each command reads such a key as they say (`location_in`), less +/// [`DOCUMENT_PARTS`]. +#[test] +fn catalog_path_keys_match_location_policy() { + use vectorcraft_engine::cmd::{key_location, location_in, params::takes_key}; + let catalog: Vec<(&vectorcraft_engine::CommandSpec, Vec)> = command_specs().iter().map(|c| (c, command_param_keys(c))).collect(); + let mut keys: std::collections::BTreeSet = + catalog.iter().flat_map(|(_, keys)| keys.iter().filter(|k| reads_like_a_location(k)).cloned()).collect(); + keys.extend(LOCATION_KEYS.iter().map(|(k, _)| k.to_string()).chain(NOT_LOCATIONS.iter().map(|k| k.to_string()))); + let mut wrong = vec![]; + for k in &keys { + let want = LOCATION_KEYS.iter().find(|(l, _)| l == k).map(|(_, l)| *l); + if want.is_none() && !NOT_LOCATIONS.contains(&k.as_str()) { + wrong.push(format!("`{k}` is in neither LOCATION_KEYS nor NOT_LOCATIONS")); + continue; + } + if key_location(k) != want { + wrong.push(format!("key_location(`{k}`) is {:?}, not {want:?}", key_location(k))); + } + if vectorcraft_engine::file_access::is_path_key(k) != want.is_some() { + wrong.push(format!("is_path_key(`{k}`) is {}", want.is_none())); + } + for (c, named) in &catalog { + if !named.contains(k) && !(c.params.contains('…') && takes_key(c.params, k)) { + continue; + } + let here = if DOCUMENT_PARTS.contains(&(c.id, k.as_str())) { None } else { want }; + if location_in(c, k) != here { + wrong.push(format!("{}: location_in(`{k}`) is {:?}, not {here:?}", c.id, location_in(c, k))); + } + } + } + for (id, key) in DOCUMENT_PARTS { + let named = catalog.iter().any(|(c, _)| c.id == *id && c.params.contains(key)); + assert!(named, "{id} doesn't name `{key}`"); + } + assert!(wrong.is_empty(), "{} keys are classified unlike the reviewed lists:\n{}", wrong.len(), wrong.join("\n")); +} + /// The cases sweep keys the command catalog names as files and folders: `document.open`'s /// `{path | name …}`, `addon.document.saveTimestampedCopy`'s `{folder? (…)}`, `document.compare`'s /// `diffPath`, `file.saveAs`'s `path` after `{…as document.save}` and `links.relink`'s @@ -650,6 +752,10 @@ fn structured_junk() { )}), ), ("svgFilter.apply", json!({"name": "\u{0}", "ids": [u64::MAX]})), + ("svgFilter.apply", json!({"name": "Glow", "index": u64::MAX, "item": -1})), + ("svgFilter.apply", json!({"name": "Rough Edges", "index": [0], "ids": "x"})), + ("svgFilter.define", json!({"xml": "", "replace": "Glow"})), + ("svgFilter.delete", json!({"name": "Glow"})), ("svgFilter.delete", json!({"name": ["a"]})), ( "effect.apply", @@ -914,6 +1020,12 @@ fn structured_junk() { ("addon.cutting.banner", json!({"hem": 0, "grommetInset": 0, "spacing": 0.01, "allArtboards": true})), ("addon.cutting.banner", json!({"spacing": "1 mm", "grommets": false, "swatch": 5, "left": null})), ("addon.cutting.banner", json!({"top": false, "right": false, "bottom": false, "left": false, "allArtboards": false})), + ("addon.cutting.nest", json!({"width": 1e6, "height": 1e6, "margin": 1e5, "spacing": 1e5, "roll": true})), + ("addon.cutting.nest", json!({"width": 1e-300, "height": f64::MAX, "margin": -1, "spacing": "1 mm", "artboard": u64::MAX})), + ("addon.cutting.nest", json!({"width": 0, "height": 0, "margin": 0, "spacing": 0, "usePreviewBounds": "no", "patterns": 1})), + ("addon.cutting.nest", json!({"roll": null, "artboard": -1, "width": "1 in", "height": [1]})), + ("addon.cutting.nest", json!({"rotate": true, "roll": true, "width": 1e-6, "margin": 0, "spacing": 0, "usePreviewBounds": true})), + ("addon.cutting.nest", json!({"rotate": "yes", "width": f64::NAN, "spacing": -0.0})), // Type Tools add-on. ("addon.type.textTweaker", json!({"attribute": "size", "from": 1296, "to": 0.1, "shape": "random", "seed": u64::MAX})), ("addon.type.textTweaker", json!({"attribute": "tracking", "from": f64::MAX, "to": -1e308, "shape": "spike"})), diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 79178d6233..c2235eca77 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -664,6 +664,29 @@ proptest! { survive(&svg, || vectorcraft_svg::import(&svg).ok())?; } + /// Style sheets of descendant, child, sibling and `:not()` selectors over nested groups and the + /// `` copies of a rectangle inside them, in an SVG and in an SVG image it shows: the import + /// measures their matching before its own cascade and the SVG reader run. + #[test] + fn svg_hostile_selectors_over_copies_never_panic( + sheet in r#"([a-z.#:()>+* ]{1,24}\{fill:red\} ?){1,6}"#, + depth in 1usize..12, + copies in 0usize..4, + ) { + let groups = format!("{}{}", "".repeat(depth), "".repeat(depth)); + let inner = format!( + "{groups}{}", + "".repeat(copies) + ); + let image = format!( + "", + vectorcraft_svg::base64_encode(inner.as_bytes()) + ); + for svg in [inner, image] { + survive(&svg, || vectorcraft_svg::import(&svg).ok())?; + } + } + /// Clip paths made of text, of `` elements showing text, and of both with shapes, each with /// hostile attributes, clipping art that may clip by them in turn. #[test] @@ -2904,9 +2927,9 @@ fn arb_body() -> impl Strategy> { } /// WMF record functions VectorCraft reads, and one it doesn't. -const WMF_FUNCTIONS: [u16; 33] = [ +const WMF_FUNCTIONS: [u16; 35] = [ 0x0324, 0x0325, 0x0538, 0x041B, 0x0418, 0x061C, 0x0817, 0x081A, 0x0830, 0x0416, 0x0415, 0x02FA, 0x02FC, 0x02FB, 0x012D, 0x01F0, 0x0521, 0x0A32, - 0x0F43, 0x0B41, 0x0940, 0x061D, 0x0213, 0x0214, 0x001E, 0x0127, 0x0106, 0x0209, 0x012E, 0x00F7, 0x01F9, 0x0142, 0x0999, + 0x0F43, 0x0B41, 0x0940, 0x061D, 0x0213, 0x0214, 0x001E, 0x0127, 0x0106, 0x0209, 0x012E, 0x00F7, 0x01F9, 0x0142, 0x0103, 0x0104, 0x0999, ]; proptest! { @@ -2933,6 +2956,30 @@ proptest! { survive_metafile("WMF records", "x.wmf", &wmf_of(&records))?; } + #[test] + fn random_headerless_wmf_records_never_panic(records in prop::collection::vec((prop::sample::select(WMF_FUNCTIONS.to_vec()), arb_body()), 0..32)) { + // Without the placeable header, the map and mix modes the records set decide the scale. + survive_metafile("headerless WMF records", "x.wmf", &wmf_of(&records)[22..])?; + } + + #[test] + fn random_emf_plus_records_never_panic(records in prop::collection::vec((0x4001u16..0x403B, any::(), arb_body()), 0..32)) { + // One comment of EMF+ records (type, flags, data) after an EmfPlusHeader. + let mut plus = vec![]; + let header = (0x4001u16, 0u16, [0xDBC0_1002u32, 0, 96, 96].iter().flat_map(|v| v.to_le_bytes()).collect::>()); + for (kind, flags, data) in std::iter::once(&header).chain(&records) { + plus.extend(kind.to_le_bytes()); + plus.extend(flags.to_le_bytes()); + plus.extend((12 + data.len() as u32).to_le_bytes()); + plus.extend((data.len() as u32).to_le_bytes()); + plus.extend(data); + } + let mut comment = (4 + plus.len() as u32).to_le_bytes().to_vec(); + comment.extend(b"EMF+"); + comment.extend(plus); + survive_metafile("EMF+ records", "x.emf", &emf_of(&[(70, comment)]))?; + } + #[test] fn pasted_metafiles_never_panic(which in 0usize..2, cut in 0usize..200_000, edits in prop::collection::vec((0usize..200_000, any::()), 0..12)) { paste_from_elsewhere("clipboard.importEmf", json!({"dataBase64": mutated_b64(metafile_samples()[which].clone(), cut, &edits)}))?; @@ -4329,7 +4376,8 @@ proptest! { "0 R", "0 O", "0 1 1 0 K", "1 0 0 0 k", "0 0 0 0 1 0 0 Xa", "0 0 0 0 1 0 0 XA", "0.5 G", "0 g", "K", "Xa", "0 J 0 j 2 w 10 M []0 d", "-1 w", "1e400 w", "0 M", "[3 -1]0 d", "[]0 d", "1 0 Xd", "0 1 Xd", "1 1 Xd", "0 0 Xd", "1 Xd", "Xd", "0 1 0 0 0 Xy", "1 0.5 1 1 0 Xy", "Xy", - "0 Bb", "2 (Sky) 0 0 0 100 1 0 0 1 0 0 Bg", "0 BB", "(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p", + "0 Bb", "1 Bb", "2 (Sky) 0 0 0 100 1 0 0 1 0 0 Bg", "2 (Sky) 0 0 1e400 100 1 0 0 1 0 0 Bg", "2 (Dusk) 0 0 0 100 1 0 0 1 0 0 Bg", + "0 BB", "(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p", "(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] P", "0 XR", ]).prop_map(|op| (op.to_string(), true)), "[ -~]{0,12}".prop_map(|text| (text, false)), @@ -4338,9 +4386,11 @@ proptest! { ) { use vectorcraft_testkit::ai; let close = if closed { "/Paint ;\n/Def ;\n" } else { "" }; - // C, a red 2 pt stroke, comes first, so that it reads whatever A holds. + // C, a red 2 pt stroke, comes first, so that it reads whatever A holds. The file defines the + // gradient Sky, which a gradient paint of A may name. let header = format!( - "%AI9_BeginArtStyles\n/KnownStyle :\n(C) /Name ,\n/SimpleStyle :\n0 R\n0 1 1 0 K\n2 w\n1 0 Xd\n/Paint ;\n/Def ;\n\ + "%AI5_BeginGradient: (Sky)\n(Sky) 0 2 Bd\n[\n%_0 0 0 0 0 1 0 2 1 6 50 0 Bs\n%_0 0 0 0 1 1 1 2 1 6 50 100 Bs\nBD\n%AI5_EndGradient\n\ + %AI9_BeginArtStyles\n/KnownStyle :\n(C) /Name ,\n/SimpleStyle :\n0 R\n0 1 1 0 K\n2 w\n1 0 Xd\n/Paint ;\n/Def ;\n\ /KnownStyle :\n(A) /Name ,\n/SimpleStyle :\n{}\n{close}/KnownStyle :\n(B) /Name ,\n/SimpleStyle :\n1 0 Xd\n/Paint ;\n/Def ;\n\ %AI9_EndArtStyles\n%AI9_BeginArtStyleList\n(A)\n(B)\n(C)\n%AI9_EndArtStyleList\n", ops.iter().map(|(op, _)| op.as_str()).collect::>().join("\n") diff --git a/crates/engine/tests/it/dimensions.rs b/crates/engine/tests/it/dimensions.rs index 56ee67be17..c2d47e9d5e 100644 --- a/crates/engine/tests/it/dimensions.rs +++ b/crates/engine/tests/it/dimensions.rs @@ -419,6 +419,56 @@ fn a_reflected_horizontal_dimension_keeps_its_line_on_the_reflected_side() { assert_eq!(text(&s, id), "100.00 pt"); } +/// An unlinked aligned dimension reflected on its own has its line on the reflected side of its +/// points: a line 30 pt above a level pair is 30 pt below it after a flip top to bottom, and a +/// half turn moves it below them as well, by turning it. +#[test] +fn a_reflected_aligned_dimension_keeps_its_line_on_the_reflected_side() { + let mut s = session(); + let id = run(&mut s, "dimension.create", json!({"a":[100,200],"b":[200,200],"offset":-30}))["id"].as_u64().unwrap(); + assert_eq!(path_ends(&s, id)[2], vec![(100.0, 170.0), (200.0, 170.0)]); + run(&mut s, "select.set", json!({"ids":[id]})); + run(&mut s, "object.reflect", json!({"axis":"horizontal","origin":[0,200]})); + assert_eq!(path_ends(&s, id)[2], vec![(100.0, 230.0), (200.0, 230.0)]); + assert_eq!(text(&s, id), "100.00 pt"); + // Reflected left to right, the points swap ends and the line stays below them. + run(&mut s, "object.reflect", json!({"axis":"vertical","origin":[150,0]})); + assert_eq!(path_ends(&s, id)[2], vec![(200.0, 230.0), (100.0, 230.0)]); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + assert_eq!(path_ends(&s, id)[2], vec![(100.0, 170.0), (200.0, 170.0)]); + // A half turn about the points' midpoint puts the line below them by turning it. + run(&mut s, "object.rotate", json!({"angle":180,"origin":[150,200]})); + let ends = path_ends(&s, id)[2].iter().map(|(x, y)| (x.round(), y.round())).collect::>(); + assert_eq!(ends, vec![(200.0, 230.0), (100.0, 230.0)]); +} + +/// An unlinked aligned dimension of a diagonal pair reflected about a mirror line through its +/// points has its line on the other side of them, and a scale by a negative factor reverses the +/// side as a reflection does, while a scale by positive factors keeps it. +#[test] +fn an_aligned_dimension_reflected_about_an_angle_or_scaled_by_a_negative_factor_changes_sides() { + let mut s = session(); + let id = run(&mut s, "dimension.create", json!({"a":[100,200],"b":[200,100],"offset":-30}))["id"].as_u64().unwrap(); + let k = 30.0 / 2f64.sqrt(); + let near = |got: &[(f64, f64)], want: [(f64, f64); 2]| got.iter().zip(want).all(|(g, w)| (g.0 - w.0).abs() < 1e-6 && (g.1 - w.1).abs() < 1e-6); + let ends = path_ends(&s, id)[2].clone(); + assert!(near(&ends, [(100.0 - k, 200.0 - k), (200.0 - k, 100.0 - k)]), "{ends:?}"); + run(&mut s, "select.set", json!({"ids":[id]})); + // The mirror line at 45 degrees through (150, 150) holds both points. + run(&mut s, "object.reflect", json!({"axis":45,"origin":[150,150]})); + let ends = path_ends(&s, id)[2].clone(); + assert!(near(&ends, [(100.0 + k, 200.0 + k), (200.0 + k, 100.0 + k)]), "{ends:?}"); + run(&mut s, "edit.undo", json!({})); + let level = run(&mut s, "dimension.create", json!({"a":[100,200],"b":[200,200],"offset":-30}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids":[level]})); + run(&mut s, "object.scale", json!({"sx":-200,"sy":100,"origin":[150,0]})); + assert_eq!(path_ends(&s, level)[2], vec![(250.0, 170.0), (50.0, 170.0)]); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "object.scale", json!({"sx":200,"sy":200,"origin":[150,200]})); + assert_eq!(path_ends(&s, level)[2], vec![(50.0, 170.0), (250.0, 170.0)]); +} + /// The line of a linked horizontal dimension below both points stays below them when the art /// turns a half turn; a line between the points keeps its distance from the first point. #[test] @@ -1721,8 +1771,9 @@ fn both_points_snap_onto_anchors_with_a_visible_indicator() { } /// Smart Guides for the Linear picks: hovering away from any line, the first point slides into -/// line with another object's corner and its guides show before the click; the second slides onto -/// the construction guide through the first. The dimension measures between the snapped points. +/// line with another object's corner and its guides show before the click; the second slides into +/// line with the other corner, with no construction guide through the first point pulling it +/// sideways. The dimension measures between the snapped points. #[test] fn linear_picks_show_and_snap_to_smart_guides() { use vectorcraft_engine::tools::Overlay; @@ -1738,18 +1789,20 @@ fn linear_picks_show_and_snap_to_smart_guides() { assert!(o.iter().any(|o| matches!(o, Overlay::Line { .. } | Overlay::Label { .. })), "its guides show before the click: {o:?}"); ev(&mut s, PointerKind::Down, 250.0, 202.5); ev(&mut s, PointerKind::Up, 250.0, 202.5); - // Straight below the first point, 1.5 pt off: the rubber band ends on the vertical through it. - ev(&mut s, PointerKind::Move, 251.5, 260.0); + // Below the first point, 1.5 pt to its right and 2.5 pt off the bottom edge's level: the + // rubber band ends on that level, where the pointer is across it. + ev(&mut s, PointerKind::Move, 251.5, 262.5); let end = overlays(&mut s).into_iter().find_map(|o| if let Overlay::Line { b, dashed: true, .. } = o { Some(b) } else { None }).unwrap(); - assert_eq!((end.x, end.y), (250.0, 260.0), "on the construction guide"); - ev(&mut s, PointerKind::Down, 251.5, 260.0); - ev(&mut s, PointerKind::Up, 251.5, 260.0); + assert_eq!((end.x, end.y), (251.5, 260.0), "in line with the bottom edge, not on a vertical through the first point"); + ev(&mut s, PointerKind::Down, 251.5, 262.5); + ev(&mut s, PointerKind::Up, 251.5, 262.5); ev(&mut s, PointerKind::Move, 220.0, 230.0); assert!(!overlays(&mut s).iter().any(|o| matches!(o, Overlay::Label { .. })), "placing: the guides are gone"); ev(&mut s, PointerKind::Down, 220.0, 230.0); ev(&mut s, PointerKind::Up, 220.0, 230.0); let id = s.doc().unwrap().selection.objects[0].0; - assert_eq!(text(&s, id), "60.00 pt"); + // Aligned from (250, 200) to (251.5, 260): √(1.5² + 60²). + assert_eq!(text(&s, id), "60.02 pt"); } /// The page content streams of exported PDF `v`, inflated. diff --git a/crates/engine/tests/it/three_d_light_color.rs b/crates/engine/tests/it/three_d_light_color.rs index 38013a372b..381bc92f15 100644 --- a/crates/engine/tests/it/three_d_light_color.rs +++ b/crates/engine/tests/it/three_d_light_color.rs @@ -481,6 +481,151 @@ fn solid_gradient_opacity_is_applied_once_even_without_shading() { } } +/// How `image`, `d` drawn at 1:1 on 400 × 400 pixels, differs from `d` drawn at 3x and averaged +/// down, on the pixels inside the art: those whose 3x average has some alpha, the same as every +/// pixel within 3 of them. Left out too are pixels where the 3x average bends sharply (a channel's +/// second difference across the pixel, along x or y, over 4 levels), such as the rim where a cap +/// meets a body: a gradient sampled at each pixel's center matches an area average only where the +/// light changes close to linearly across the pixel. Returns (pixels measured, premultiplied RGB +/// channels more than 3 levels off, the largest RGB difference, alphas off: below 255 where the 3x +/// average is opaque, otherwise more than 3 levels off, the first few pixels off). +fn seams_against_supersampled(d: &Document, image: &vectorcraft_render::Rendered) -> (usize, usize, u8, usize, Vec) { + let fine = vectorcraft_render::Renderer::new().render( + d, + 1200, + 1200, + kurbo::Affine::scale(3.0), + &vectorcraft_render::RenderOptions { background: None, artboards: false, ..Default::default() }, + ); + let average = fine.area_resized(400, 400).unwrap(); + let (mut measured, mut color, mut max, mut holes) = (0, 0, 0, 0); + let mut worst = vec![]; + for y in 3..397 { + for x in 3..397 { + let q = average.pixel(x, y); + if q[3] == 0 || !(y - 3..=y + 3).all(|y| (x - 3..=x + 3).all(|x| average.pixel(x, y)[3] == q[3])) { + continue; + } + let bend = |a: [u8; 4], b: [u8; 4]| (0..3).any(|c| (i32::from(a[c]) + i32::from(b[c]) - 2 * i32::from(q[c])).abs() > 4); + if bend(average.pixel(x - 1, y), average.pixel(x + 1, y)) || bend(average.pixel(x, y - 1), average.pixel(x, y + 1)) { + continue; + } + measured += 1; + let p = image.pixel(x, y); + for c in 0..3 { + let diff = p[c].abs_diff(q[c]); + max = max.max(diff); + color += usize::from(diff > 3); + } + let hole = if q[3] == 255 { p[3] < 255 } else { p[3].abs_diff(q[3]) > 3 }; + holes += usize::from(hole); + if (p.into_iter().zip(q).any(|(a, b)| a.abs_diff(b) > 3) || hole) && worst.len() < 4 { + worst.push(format!("({x},{y}) {p:?} vs {q:?}")); + } + } + } + (measured, color, max, holes, worst) +} + +/// Colored lights on smooth 3D surfaces, compared at 1:1 with a 3x render averaged down, on every +/// pixel inside the art ([`seams_against_supersampled`]). A solid fill draws as one batched surface; +/// a source gradient composes each facet on its own, and one with transparent stops applies their +/// opacity once over the surface. Inflate seen straight on, one layer of facets, has no alpha off, and +/// in opaque fills no RGB channel more than 3 levels off. Inflate turned so facets narrow to slivers +/// at the edges, and Revolve with a cap over its body, draw facets over other facets, and have no +/// alpha off. +#[test] +fn colored_light_surfaces_match_supersampling_at_internal_facet_edges() { + let lights = json!([ + {"color":"#ff0000","rotation":135,"height":35,"intensity":70}, + {"color":"#0000ff","rotation":-35,"height":25,"intensity":65} + ]); + let fills = |start: [u32; 2], end: [u32; 2]| { + [ + json!({"color":"#ffcc66"}), + json!({"gradient":{"kind":"linear","start":start,"end":end,"stops":[ + {"offset":0,"color":"#ffffff"},{"offset":1,"color":"#808080"} + ]}}), + json!({"gradient":{"kind":"linear","start":start,"end":end,"stops":[ + {"offset":0,"color":"#ffffff","opacity":0.6},{"offset":1,"color":"#808080","opacity":0.6} + ]}}), + ] + }; + let mut cases = vec![]; + for rotation in [(0, 0), (50, 35)] { + let (mut s, _) = setup("threeD.inflate"); + let change = json!({"index":0,"item":null,"params":{"ambient":10,"lights":lights,"rotationX":rotation.0,"rotationY":rotation.1}}); + s.execute("effect.setParams", &change).unwrap(); + cases.push((format!("inflate {rotation:?}"), s, fills([100, 150], [200, 150]), rotation == (0, 0))); + } + let (mut s, _) = capped_profile(); + s.execute("effect.setParams", &json!({"index":0,"item":null,"params":{"ambient":10,"lights":lights}})).unwrap(); + cases.push(("revolve".into(), s, fills([80, 200], [240, 200]), false)); + let mut failures = vec![]; + for (name, mut s, fills, one_layer) in cases { + for fill in fills { + s.execute("paint.setFill", &fill).unwrap(); + let image = render(doc(&s)); + let (measured, color, max, holes, worst) = seams_against_supersampled(doc(&s), &image); + assert!(measured > 2_000, "{name} {fill}: {measured} pixels inside"); + let opaque = !fill.to_string().contains("opacity"); + if holes > 0 || (one_layer && opaque && color > 0) { + failures.push(format!( + "{name} {fill}: of {measured} pixels, {color} channels off by more than 3 (at most {max}), {holes} alphas off: {worst:?}" + )); + } + } + } + assert!(failures.is_empty(), "{failures:#?}"); +} + +/// The closed facet edges of colored-light surfaces survive SVG and PDF, read back and drawn at +/// 1:1, and Expand Appearance: inside the art, every pixel stays opaque and within 6 levels of the +/// live art. +#[test] +fn colored_light_seams_stay_closed_in_svg_pdf_and_expansion() { + let lights = json!([ + {"color":"#ff0000","rotation":135,"height":35,"intensity":70}, + {"color":"#0000ff","rotation":-35,"height":25,"intensity":65} + ]); + for fill in [ + json!({"color":"#ffcc66"}), + json!({"gradient":{"kind":"linear","start":[100,150],"end":[200,150],"stops":[ + {"offset":0,"color":"#ffffff"},{"offset":1,"color":"#808080"} + ]}}), + ] { + let (mut s, _) = setup("threeD.inflate"); + s.execute("effect.setParams", &json!({"index":0,"item":null,"params":{"ambient":10,"lights":lights}})).unwrap(); + s.execute("paint.setFill", &fill).unwrap(); + let live = render(doc(&s)); + let svg = s.execute("document.serialize", &json!({"format":"svg"})).unwrap()["text"].as_str().unwrap().to_owned(); + assert!(svg.contains(">(); - prop_assert!(names(&folder).len() <= 4, "{:?}", names(&folder)); + prop_assert!(names(&folder).len() <= 5, "{:?}", names(&folder)); prop_assert!(names(&folder.join("storage")).len() <= 2, "{:?}", names(&folder.join("storage"))); let _ = s.execute("plugin.remove", &json!({"id": "fuzz.storage"})); let _ = s.execute("plugin.remove", &json!({"id": "fuzz.storage.other"})); diff --git a/crates/eps/src/ai_editing.rs b/crates/eps/src/ai_editing.rs index 0048cb945f..3df902b97f 100644 --- a/crates/eps/src/ai_editing.rs +++ b/crates/eps/src/ai_editing.rs @@ -228,8 +228,9 @@ const GRID_GRAY: f64 = 200.0 / 255.0; /// `%%Creator`: the creator line VectorCraft writes in the header of the editing data. It names /// VectorCraft and the format's app, and holds no version number; the version is written on its -/// own in `%%AI8_CreatorVersion` ([`CREATOR_VERSION`]). -const CREATOR_TEXT: &str = "VectorCraft, editing data for Illustrator"; // brand-ok: the creator line VectorCraft writes +/// own in `%%AI8_CreatorVersion` ([`CREATOR_VERSION`]). The reader reads the symbols of data with +/// this creator at their own size, as [`export_ai_editing`] writes them on a large canvas. +pub(crate) const CREATOR_TEXT: &str = "VectorCraft, editing data for Illustrator"; // brand-ok: the creator line VectorCraft writes /// The first line of a PostScript file (the DSC version comment). const PS_HEADER: &str = "%!PS-Adobe-3.0"; // brand-ok: the PostScript header comment diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index 4779afaa27..a01f631638 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -1187,6 +1187,54 @@ fn a_symbol_definition_is_written_only_with_room_for_its_instance() { } } +/// A live instance inside a stained instance's art, whose definition has no room left, is left out +/// without upsetting the art around it: with room for any number of objects the export finishes, +/// within that room. +#[test] +fn a_definition_without_room_inside_drawn_art_is_left_out() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let leaf = square(&mut doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF); + doc.symbols.push(Symbol { dynamic: false, name: "Leaf".into(), art: Arc::new(leaf) }); + let inner = instance(&mut doc, "Leaf", Affine::translate((5.0, 5.0))); + let side = square(&mut doc, Rect::new(20.0, 0.0, 30.0, 10.0), Color::gray(0.5)); + let art = group(&mut doc, vec![inner, side], false); + doc.symbols.push(Symbol { dynamic: false, name: "Branch".into(), art: Arc::new(art) }); + let mut stained = instance(&mut doc, "Branch", Affine::translate((50.0, 10.0))); + stained.appearance = Appearance::basic(solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0).into(); + doc.insert(Some(layer), usize::MAX, stained).unwrap(); + add_rect(&mut doc, Rect::new(150.0, 10.0, 160.0, 20.0)); + let read = crate::import::objects_read(&export_ai_editing(&doc, &opts()).unwrap().program).unwrap(); + for max in 0..read { + let out = export_within(&doc, &opts(), max).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::OBJECT_LIMIT), "art is left out with room for {max} of {read} objects"); + let objects = crate::import::objects_read(&out.program).unwrap(); + assert!(objects <= max, "{objects} objects read with room for {max}"); + } +} + +/// A symbol definition without room for its group, asked for by an instance in art drawn for an +/// object (a stained instance's art), is left out and leaves the writing of that art as it was. +#[test] +fn a_symbol_definition_without_room_in_drawn_art_is_left_out() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let dot = square(&mut doc, Rect::new(0.0, 0.0, 10.0, 10.0), Color::gray(0.5)); + doc.symbols.push(Symbol { dynamic: false, name: "Dot".into(), art: Arc::new(dot) }); + let inner = instance(&mut doc, "Dot", Affine::IDENTITY); + doc.symbols.push(Symbol { dynamic: false, name: "Badge".into(), art: Arc::new(inner) }); + let mut stained = instance(&mut doc, "Badge", Affine::translate((50.0, 10.0))); + stained.appearance = Appearance::basic(solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0).into(); + doc.insert(Some(layer), usize::MAX, stained).unwrap(); + let read = crate::import::objects_read(&export_ai_editing(&doc, &opts()).unwrap().program).unwrap(); + for max in 0..read { + let out = export_within(&doc, &opts(), max).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::OBJECT_LIMIT), "room for {max} of {read}"); + let objects = crate::import::objects_read(&out.program).unwrap(); + assert!(objects <= max, "{objects} objects read with room for {max}"); + } +} + /// The writer's limit is the reader's, which its warning names. #[test] fn the_object_limit_is_the_readers() { @@ -4143,6 +4191,57 @@ fn standard_vertical_roman_alignment_comes_back() { assert_eq!(flags(&texts(&read_back(&both))[0])[2], (false, true)); } +/// Insert Aki Left and Right come back on each run, in vertical and horizontal type: a run with +/// either writes it as key 49 or 50 in 1/1000 em, a run without writes neither, and nothing is +/// reported. Each object lays out as it did. A run that also has an attribute the text document +/// leaves out is still reported. +#[test] +fn insert_aki_comes_back() { + use vectorcraft_doc::{CharStyle, TextObject, TextRun}; + let plain = style(14.0, Color::BLACK); + let left = CharStyle { aki_left: 250.0, ..plain.clone() }; + let both = CharStyle { aki_left: 125.5, aki_right: 500.0, ..plain.clone() }; + let mut doc = Document::new(200.0, 200.0); + let layer = doc.layers[0].id; + let mut down = TextObject::point(vectorcraft_geom::Point::new(150.0, 20.0), "", plain.clone()); + down.runs = vec![TextRun::new("AB", left.clone()), TextRun::new("CD", plain.clone()), TextRun::new("EF", both.clone())]; + down.vertical = true; + let mut across = TextObject::point(vectorcraft_geom::Point::new(20.0, 40.0), "", plain.clone()); + across.runs = vec![TextRun::new("GH", both.clone()), TextRun::new("IJ", plain.clone())]; + for t in [down, across] { + let n = text_node(&mut doc, t); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + let back = read_back(&doc); + same_lines(&type_lines(&back), &type_lines(&doc)); + let texts = |d: &Document| -> Vec { + d.layers[0].children().unwrap().iter().filter_map(|n| if let NodeKind::Text(t) = &n.kind { Some((**t).clone()) } else { None }).collect() + }; + let aki = |t: &TextObject| t.runs.iter().map(|r| (r.style.aki_left, r.style.aki_right)).collect::>(); + let (written, read) = (texts(&doc), texts(&back)); + assert_eq!(read.iter().map(aki).collect::>(), [vec![(250.0, 0.0), (0.0, 0.0), (125.5, 500.0)], vec![(125.5, 500.0), (0.0, 0.0)]]); + let origins = |t: &TextObject| { + vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).glyphs.iter().map(|g| (r3(g.origin.x), r3(g.origin.y))).collect::>() + }; + for (w, r) in written.iter().zip(&read) { + assert_eq!(origins(r), origins(w), "vertical={}", w.vertical); + } + let decoded = text_document(&program(&doc)); + for (key, count) in [("/49 250.0", 1), ("/49 125.5", 2), ("/50 500.0", 2)] { + assert_eq!(decoded.matches(key).count(), count, "{key}: {decoded}"); + } + assert_eq!(decoded.matches("/49 ").count() + decoded.matches("/50 ").count(), 5, "{decoded}"); + // Underline is still left out, and reported. + let mut lossy = doc.clone(); + let id = lossy.layers[0].children().unwrap()[0].id; + if let Some(NodeKind::Text(t)) = lossy.node_mut(id).map(|n| &mut n.kind) { + t.runs[0].style.underline = true; + } + assert_eq!(export_ai_editing(&lossy, &opts()).unwrap().warnings, [writer::TYPE_ATTRIBUTES]); +} + /// The text document of program `text` (LF line ends), decoded, with its UTF-16 strings' zero /// bytes left out. fn text_document(text: &str) -> String { @@ -4473,8 +4572,8 @@ fn type_the_data_cant_hold_is_written_as_its_outlines() { rings.subpaths.extend(shapes::rectangle(Rect::new(120.0, 30.0, 170.0, 70.0)).subpaths); holed.kind = vectorcraft_doc::TextKind::Area { frame: rings }; holed.xf = Affine::IDENTITY; - // A carriage return in the characters: a story ends its paragraphs with it. Area type that - // flows around a wrap object: the wrap object's settings aren't written. + // A carriage return in the characters: a story ends its paragraphs with it. Area type with + // wrap shapes and no wrap object: the text document doesn't hold the shapes. let returned = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(10.0, 90.0), "A\rB", style(10.0, Color::BLACK)); let mut wrapped = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::ZERO, "Wrapped round", style(10.0, Color::BLACK)); wrapped.kind = vectorcraft_doc::TextKind::Area { frame: shapes::rectangle(Rect::new(10.0, 10.0, 90.0, 60.0)) }; @@ -10146,6 +10245,119 @@ fn envelopes_past_the_readers_checks_are_written_as_their_art() { assert!(!notes.iter().any(|n| n == crate::import::ENVELOPE_DRAWN), "{notes:?}"); } +/// A document of `envelopes` envelopes and `images` embedded images with one Warp, the images first +/// when `images_first`, saved and opened again: the live envelopes, the images with their Warp live +/// and all the objects it opens with, the save's warnings and the open's notes. +fn envelopes_and_warped_images(envelopes: usize, images: usize, images_first: bool) -> (usize, usize, usize, Vec, Vec) { + use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions}; + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let add_images = |doc: &mut Document| { + for _ in 0..images { + let photo = warped_photo(doc, vec![fx("warp.arc", serde_json::json!({"bend": 40.0}))]); + doc.insert(Some(layer), usize::MAX, photo).unwrap(); + } + }; + if images_first { + add_images(&mut doc); + } + for _ in 0..envelopes { + let points = [(30.0, 10.0), (170.0, 0.0), (30.0, 90.0), (170.0, 90.0)].map(kurbo::Point::from).to_vec(); + let kind = EnvelopeKind::Mesh { rows: 1, cols: 1, points, handles: vec![] }; + let envelope = envelope_node(&mut doc, kind, 50.0, false, EnvelopeOptions::NEW); + doc.insert(Some(layer), usize::MAX, envelope).unwrap(); + } + if !images_first { + add_images(&mut doc); + } + let (p, warnings) = private_data(&doc, &opts()).unwrap(); + let (back, notes) = crate::ai_alone(&p.data).unwrap(); + let a = back.layers[0].children().unwrap(); + let live = a.iter().filter(|n| matches!(n.kind, NodeKind::Envelope { .. })).count(); + let warped = a.iter().filter(|n| matches!(n.kind, NodeKind::Image(_)) && n.appearance.effects.iter().any(|e| e.id == "warp.arc")).count(); + (live, warped, a.len(), warnings, notes) +} + +/// Images with a Warp take the reader's checks as envelopes do: past them, an image is written as +/// its drawn look, with a warning, and the file opens with every object written live still live. +#[test] +fn warped_images_past_the_readers_checks_are_written_as_their_drawn_look() { + // GUARDS: images with a Warp were written live past the checks the envelopes left, and the + // file opened with the last one as its drawn look and no warning on saving. + let limit = crate::import::ENVELOPE_CHECKS; + let (live, warped, all, warnings, notes) = envelopes_and_warped_images(limit - 1, 2, false); + assert_eq!((live, warped, all), (limit - 1, 1, limit + 1), "{warnings:?} {notes:?}"); + assert!(warnings.iter().any(|w| w == writer::WARPED_IMAGES), "{warnings:?}"); + assert!(!warnings.iter().any(|w| w == writer::ENVELOPES), "{warnings:?}"); + assert!(!notes.iter().any(|n| n.contains("drawn look") || n == crate::import::ENVELOPE_DRAWN), "{notes:?}"); +} + +/// An image with a Warp whose pixels can't be read is written as its gray outline, which the reader +/// doesn't check: it leaves its check to the objects after it. +#[test] +fn a_warped_image_written_as_its_outline_takes_no_check() { + // GUARDS: an image written as its gray outline took a check, and the image after it lost its Warp. + use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions}; + let limit = crate::import::ENVELOPE_CHECKS; + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + for _ in 0..limit - 1 { + let points = [(30.0, 10.0), (170.0, 0.0), (30.0, 90.0), (170.0, 90.0)].map(kurbo::Point::from).to_vec(); + let kind = EnvelopeKind::Mesh { rows: 1, cols: 1, points, handles: vec![] }; + let envelope = envelope_node(&mut doc, kind, 50.0, false, EnvelopeOptions::NEW); + doc.insert(Some(layer), usize::MAX, envelope).unwrap(); + } + let arc = || fx("warp.arc", serde_json::json!({"bend": 40.0})); + let mut broken = image_node(&mut doc, ImageBlob::png(b"not a png".to_vec()), (8, 8), Affine::new([10.0, 0.0, 0.0, 10.0, 20.0, 10.0]), None); + broken.appearance = Appearance { effects: vec![arc()], ..Appearance::default() }.into(); + doc.insert(Some(layer), usize::MAX, broken).unwrap(); + let photo = warped_photo(&mut doc, vec![arc()]); + doc.insert(Some(layer), usize::MAX, photo).unwrap(); + let (p, warnings) = private_data(&doc, &opts()).unwrap(); + assert!(warnings.iter().any(|w| w == writer::IMAGES), "{warnings:?}"); + assert!(!warnings.iter().any(|w| w == writer::WARPED_IMAGES), "{warnings:?}"); + let (back, notes) = crate::ai_alone(&p.data).unwrap(); + let a = back.layers[0].children().unwrap(); + let warped = a.iter().filter(|n| matches!(n.kind, NodeKind::Image(_)) && n.appearance.effects.iter().any(|e| e.id == "warp.arc")).count(); + assert_eq!(warped, 1, "{notes:?}"); +} + +/// Past the reader's checks, an image with a Warp whose pixels can't be read is still written as its +/// gray outline, with the warning for its pixels and not the one for the checks. +#[test] +fn an_unreadable_warped_image_past_the_checks_is_warned_about_its_pixels() { + // GUARDS: an image whose pixels can't be read was warned about as past the checks. + use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions}; + let limit = crate::import::ENVELOPE_CHECKS; + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + for _ in 0..limit { + let points = [(30.0, 10.0), (170.0, 0.0), (30.0, 90.0), (170.0, 90.0)].map(kurbo::Point::from).to_vec(); + let kind = EnvelopeKind::Mesh { rows: 1, cols: 1, points, handles: vec![] }; + let envelope = envelope_node(&mut doc, kind, 50.0, false, EnvelopeOptions::NEW); + doc.insert(Some(layer), usize::MAX, envelope).unwrap(); + } + let mut broken = image_node(&mut doc, ImageBlob::png(b"not a png".to_vec()), (8, 8), Affine::new([10.0, 0.0, 0.0, 10.0, 20.0, 10.0]), None); + broken.appearance = Appearance { effects: vec![fx("warp.arc", serde_json::json!({"bend": 40.0}))], ..Appearance::default() }.into(); + doc.insert(Some(layer), usize::MAX, broken).unwrap(); + let (_, warnings) = private_data(&doc, &opts()).unwrap(); + assert!(warnings.iter().any(|w| w == writer::IMAGES), "{warnings:?}"); + assert!(!warnings.iter().any(|w| w == writer::WARPED_IMAGES), "{warnings:?}"); +} + +/// Envelopes after images with a Warp get the checks the images left: past them, an envelope is +/// written as its art, with a warning. +#[test] +fn envelopes_get_the_checks_warped_images_left() { + // GUARDS: envelopes were written live past the checks the images with a Warp before them left. + let limit = crate::import::ENVELOPE_CHECKS; + let (live, warped, all, warnings, notes) = envelopes_and_warped_images(limit - 1, 2, true); + assert_eq!((live, warped, all), (limit - 2, 2, limit + 1), "{warnings:?} {notes:?}"); + assert!(warnings.iter().any(|w| w == writer::ENVELOPES), "{warnings:?}"); + assert!(!warnings.iter().any(|w| w == writer::WARPED_IMAGES), "{warnings:?}"); + assert!(!notes.iter().any(|n| n.contains("drawn look") || n == crate::import::ENVELOPE_DRAWN), "{notes:?}"); +} + /// Every Envelope Options switch and the ends of Fidelity come back as saved. #[test] fn envelope_options_and_fidelity_are_read_back() { @@ -10562,15 +10774,106 @@ fn text_wrap_options_of_type_and_envelopes_are_read_back() { same_wraps(&wraps(top), &[(Some("Bent".into()), 2.5, true)]); } +/// Type written as its outlines wraps area type below it by its bounds, as it did before saving, +/// not by its glyphs: its text wrap options go on an unpainted rectangle of its bounds, the last +/// member of the outlines' group, which keeps the type's name and has no options of its own. +/// Mirrored point type with a positive offset, a negative offset with Invert Wrap, hidden and +/// locked, type of only white space, and no room for the rectangle within the object limit. +#[test] +fn type_written_as_outlines_keeps_wrapping_by_its_bounds() { + use vectorcraft_doc::{TextKind, TextObject, TextRun}; + type Region = Vec<([f64; 4], f64, bool)>; + // The wrap shapes of the area type, in its own space: each one's bounds and options. + let region = |doc: &Document| -> Region { + let mut doc = doc.clone(); + vectorcraft_doc::text::resolve_wrap(None, &mut doc); + let top = doc.layers[0].children().unwrap(); + let Some(NodeKind::Text(t)) = top.iter().map(|n| &n.kind).find(|k| matches!(k, NodeKind::Text(t) if matches!(t.kind, TextKind::Area { .. }))) + else { + panic!("no area type"); + }; + t.wrap + .iter() + .map(|s| { + let b = s.path.bounds().unwrap_or_default(); + ([b.x0, b.y0, b.x1, b.y1], s.wrap.offset, s.wrap.invert) + }) + .collect() + }; + let make = |text: &str, offset: f64, invert: bool, visible: bool, locked: bool| { + let mut doc = Document::new(300.0, 200.0); + let layer = doc.layers[0].id; + let mut body = TextObject::point(vectorcraft_geom::Point::ZERO, "", style(10.0, Color::BLACK)); + body.runs = vec![TextRun::new("one two three four five six seven eight nine ten eleven twelve", style(10.0, Color::BLACK))]; + body.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(10.0, 10.0, 290.0, 190.0)) }; + body.xf = Affine::IDENTITY; + let body = named(text_node(&mut doc, body), "Body"); + let mut label = TextObject::point(vectorcraft_geom::Point::ZERO, text, style(60.0, Color::BLACK)); + // Mirrored, so written as its outlines. + label.xf = Affine::new([-1.0, 0.0, 0.0, 1.0, 150.0, 120.0]); + let mut label = wrapped(named(text_node(&mut doc, label), "Label"), offset, invert); + (label.visible, label.locked) = (visible, locked); + for n in [body, label] { + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + doc + }; + for (text, offset, invert, visible, locked) in + [("Ill", 4.5, false, true, false), ("Ill", -2.0, true, true, false), ("Ill", 3.0, false, false, true), (" ", 3.0, false, true, false)] + { + let doc = make(text, offset, invert, visible, locked); + let bounds = doc.layers[0].children().unwrap()[1].geometric_bounds(); + let text_out = program(&doc); + let back = read_back(&doc); + let (before, after) = (region(&doc), region(&back)); + let same = before.len() == after.len() + && before + .iter() + .zip(&after) + .all(|(b, a)| b.0.iter().zip(a.0).all(|(x, y)| (x - y).abs() < 1e-3) && (b.1 - a.1).abs() < 1e-6 && b.2 == a.2); + assert!(same, "{text:?}\n{before:?}\n{after:?}\n{text_out}"); + let top = back.layers[0].children().unwrap(); + let group = &top[1]; + assert!(matches!(group.kind, NodeKind::Group { clip: false, .. }), "{text_out}"); + assert_eq!((group.name.as_deref(), group.extras().wrap, group.visible, group.locked), (Some("Label"), None, visible, locked)); + if let Some(want) = bounds { + assert_eq!(text_out.matches("(AI11TextWrapOffset)").count(), 1, "{text_out}"); + same_wraps(&wraps(top), &[(None, offset, invert)]); + let last = group.children().unwrap().last().unwrap(); + assert!(matches!(last.kind, NodeKind::Path { guide: false, .. }) && last.appearance.items.is_empty(), "{text_out}"); + assert_eq!((last.visible, last.locked), (visible, locked)); + let b = last.geometric_bounds().unwrap(); + assert!([b.x0 - want.x0, b.y0 - want.y0, b.x1 - want.x1, b.y1 - want.y1].iter().all(|d| d.abs() < 1e-3), "{b:?} {want:?}"); + } else { + assert!(wraps(top).is_empty(), "{text_out}"); + } + } + // The rectangle counts toward the object limit. Without room for it, the type's wrap options + // are left out with the limit's warning, and the glyphs do not take them. + let doc = make("Ill", 4.5, false, true, false); + let read = crate::import::objects_read(&export_ai_editing(&doc, &opts()).unwrap().program).unwrap(); + let all = export_within(&doc, &opts(), read).unwrap(); + assert!(!all.warnings.iter().any(|w| w == writer::OBJECT_LIMIT), "{:?}", all.warnings); + let out = export_within(&doc, &opts(), read - 1).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::OBJECT_LIMIT), "{:?}", out.warnings); + let text_out = String::from_utf8_lossy(&out.program).replace("\r\n", "\n"); + assert!(!text_out.contains("(AI11TextWrapOffset)"), "{text_out}"); + let (back, _) = crate::ai_alone(&out.program).unwrap(); + let top = back.layers[0].children().unwrap(); + assert!(wraps(top).is_empty(), "{text_out}"); + assert_eq!(top[1].name.as_deref(), Some("Label"), "{text_out}"); +} + /// A clipping path inside art cut to a clipping object is written as its fills and its strokes, -/// two objects: its text wrap options are written once, whether it has both or only strokes. +/// two objects: its text wrap options are written once, whether it has both or only strokes, and +/// with its strokes when the region outside leaves nothing of its fills. #[test] fn a_clipping_path_written_as_its_paint_keeps_one_text_wrap() { - for fill in [solid(Color::gray(0.5)), Paint::None] { + for (fill, left, width) in [(solid(Color::gray(0.5)), 20.0, 2.0), (Paint::None, 20.0, 2.0), (solid(Color::gray(0.5)), 101.0, 4.0)] { let mut doc = Document::new(200.0, 100.0); let layer = doc.layers[0].id; - let mut cutter = clipping(&mut doc, shapes::rectangle(Rect::new(20.0, 20.0, 80.0, 80.0))); - cutter.appearance = Appearance::basic(fill, solid(Color::BLACK), 2.0).into(); + let mut cutter = clipping(&mut doc, shapes::rectangle(Rect::new(left, 20.0, left + 60.0, 80.0))); + cutter.appearance = Appearance::basic(fill, solid(Color::BLACK), width).into(); let cutter = wrapped(cutter, 5.0, true); let member = square(&mut doc, Rect::new(30.0, 30.0, 120.0, 60.0), Color::rgb(1.0, 0.0, 0.0)); let inner = group(&mut doc, vec![cutter, member], true); @@ -10582,4 +10885,25 @@ fn a_clipping_path_written_as_its_paint_keeps_one_text_wrap() { assert_eq!(text.matches("(AI11TextWrapOffset)").count(), 1, "{text}"); same_wraps(&wraps(read_back(&doc).layers[0].children().unwrap()), &[(None, 5.0, true)]); } + + // The outer clipping object ends at x = 100 and the clipping path's fill starts at x = 101: the + // fill is cut away and writes nothing, and its 4 pt stroke, which reaches x = 99, keeps the + // options, whether or not the fill's lock state is written before it. + for locked in [false, true] { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut cutter = clipping(&mut doc, shapes::rectangle(Rect::new(101.0, 20.0, 150.0, 80.0))); + cutter.appearance = Appearance::basic(solid(Color::gray(0.5)), solid(Color::BLACK), 4.0).into(); + cutter.locked = locked; + let cutter = wrapped(cutter, 5.0, true); + let member = square(&mut doc, Rect::new(110.0, 30.0, 140.0, 60.0), Color::rgb(1.0, 0.0, 0.0)); + let inner = group(&mut doc, vec![cutter, member], true); + let frame = square(&mut doc, Rect::new(0.0, 0.0, 100.0, 100.0), Color::gray(0.9)); + let frame = group(&mut doc, vec![frame], false); + let outer = group(&mut doc, vec![frame, inner], true); + doc.insert(Some(layer), usize::MAX, outer).unwrap(); + let text = program(&doc); + assert_eq!(text.matches("(AI11TextWrapOffset)").count(), 1, "locked {locked}: {text}"); + same_wraps(&wraps(read_back(&doc).layers[0].children().unwrap()), &[(None, 5.0, true)]); + } } diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index 64583d3949..98b027f79d 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -9,7 +9,7 @@ use vectorcraft_color::swatch::{REGISTRATION, Swatch}; use vectorcraft_color::{BlendMode, Color, Paint}; use vectorcraft_doc::{AppearanceItem, Document, FillLayer, Knockout, LayerColor, Node, NodeId, NodeKind, OpacityMask, StrokeLayer, TextWrap}; use vectorcraft_effects::stroke; -use vectorcraft_geom::{Affine, FillRule, PathData, Shape, SubPath}; +use vectorcraft_geom::{Affine, FillRule, PathData, Shape, SubPath, shapes}; use vectorcraft_pathops::BoolOp; use crate::ai_ops::{self, unit}; @@ -30,7 +30,7 @@ pub(super) use brushes::BRUSHES; pub(super) use envelopes::ENVELOPES; pub(super) use styles::{LARGE_CANVAS_STYLES, style_links, styled_objects}; #[cfg(test)] -pub(super) use styles::{PANEL_EMPTY, PANEL_STYLES, STYLE_LINKS, same_appearance}; +pub(super) use styles::{PANEL_EMPTY, PANEL_STYLES, STYLE_LINKS, WARPED_IMAGES, same_appearance}; pub(super) use images::PAYLOAD; #[cfg(test)] @@ -271,6 +271,9 @@ pub(super) struct Writer<'a> { /// brushed stroke's pieces) the art being written is in. Text wrap options are written only /// outside them, since only the document's own objects wrap type. drawn: u32, + /// The type just written as outlines has its text wrap options on the rectangle of its bounds + /// ([`Self::wrap_bounds`]), not in the group's dictionary. + wrap_moved: bool, /// The brushes written ([`brushes`]). brush_set: brushes::Brushes, /// Brushes may be written; false on a large canvas, where they are left out. @@ -278,9 +281,9 @@ pub(super) struct Writer<'a> { /// The object just written is an envelope's distorted art, which the plugin's `XP` follows /// ([`Self::envelope`]). deform: bool, - /// How many more envelopes may be written live: as many as the reader checks in one file - /// ([`crate::import::ENVELOPE_CHECKS`]). - envelopes_left: usize, + /// How many more envelopes and images with a Warp may be written live: as many as the reader + /// checks in one file ([`crate::import::ENVELOPE_CHECKS`]), which it spends on both. + checks_left: usize, /// The image read last and its pixels ([`images::Samples::of`], `None` when they can't be /// read): the pieces of a warped image, which follow one another, read them once. last_samples: Option<(vectorcraft_doc::ImageBlob, Option)>, @@ -350,10 +353,11 @@ impl<'a> Writer<'a> { styles: styles::Styles::default(), in_look: false, drawn: 0, + wrap_moved: false, brush_set: brushes::Brushes::default(), brushes_live: true, deform: false, - envelopes_left: crate::import::ENVELOPE_CHECKS, + checks_left: crate::import::ENVELOPE_CHECKS, objects: 0, left_out: 0, definition_objects: 0, @@ -658,6 +662,7 @@ impl<'a> Writer<'a> { && self.clip.is_none() && !self.in_symbol && let Some(orig) = self.styled.get(&n.id).cloned() + && self.check_left(&orig) && let Some(name) = self.object_style(n, &orig) { return self.styled_object(n, &orig, &name); @@ -829,7 +834,8 @@ impl<'a> Writer<'a> { /// deep, or its art doesn't fit. fn dictionary(&mut self, n: &Node) -> bool { let name = n.name.as_deref().filter(|s| !s.is_empty()); - let wrap = n.extras().wrap.filter(|_| self.drawn == 0 && !self.in_look); + let moved = std::mem::take(&mut self.wrap_moved); + let wrap = n.extras().wrap.filter(|_| self.drawn == 0 && !self.in_look && !moved); let placed = std::mem::take(&mut self.placed); let typed = std::mem::take(&mut self.typed); let bound = self.bound_variables(n, placed, typed); @@ -1102,22 +1108,25 @@ impl<'a> Writer<'a> { /// A container's members, the first one's outline cutting the others: its fills painted /// behind them (cut to the region outside too), its strokes over them, not cut by it. Its text - /// wrap options are written once: with its fills, or without fills with its strokes. + /// wrap options are written once: with its fills, or with its strokes when no fill object is + /// written (it has no fills, or the region outside leaves nothing of them). fn clip_contents(&mut self, children: &[Arc]) { let Some((first, rest)) = children.split_first() else { return }; // Nothing to clip by hides the clipped art. let Some((outline, rule)) = vectorcraft_effects::clip_outline(first) else { return }; let mut paint = first.clip_paint(); - if let (Some(_), Some(stroke)) = (&paint.fill, &mut paint.stroke) - && stroke.extras().wrap.is_some() - { - stroke.extras_mut().wrap = None; - } let outer = self.clip.clone(); let region = self.cut(&PathData::from_bezpath(&outline), rule); self.clip = Some(region); if let Some(fill) = &paint.fill { + let objects = self.objects; self.node(fill); + if self.objects > objects + && let Some(stroke) = &mut paint.stroke + && stroke.extras().wrap.is_some() + { + stroke.extras_mut().wrap = None; + } } for c in rest { self.node(c); @@ -1401,7 +1410,8 @@ impl<'a> Writer<'a> { /// ([`vectorcraft_effects::outline_text`]): each run's glyphs with their underline and /// strikethrough, its color glyphs, and the object's own fills and strokes; then its inline /// graphics as their symbols' art where the layout places them, as the PDF page draws them; - /// the group has the type's transparency `xy`. + /// last, with text wrap options, the rectangle of its bounds ([`Self::wrap_bounds`]). The group + /// has the type's transparency `xy`. fn outlined_text(&mut self, n: &Node, xy: Xy) { if !self.open_group("u") { return; @@ -1457,12 +1467,34 @@ impl<'a> Writer<'a> { for c in over { self.node(c); } + // Type wraps by its bounds: its text wrap options go on a rectangle of its bounds, the + // group's last member, and the group's dictionary leaves them out. + if let Some(w) = n.extras().wrap.filter(|_| self.drawn == 0 && !self.in_look) { + self.wrap_bounds(n, w); + self.wrap_moved = true; + } if let Some((locked, hidden)) = state { self.state(locked, hidden); } self.end_group("U", xy); } + /// An unpainted closed rectangle at the geometric bounds of type `n`, the region its text wraps + /// around, with `n`'s lock and hidden state and text wrap options `w` in its dictionary. Nothing + /// when `n` has no finite bounds, or without room for it ([`Self::take_objects`]). + fn wrap_bounds(&mut self, n: &Node, w: TextWrap) { + let Some(b) = n.geometric_bounds().filter(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite())) else { return }; + self.state(n.locked, !n.visible); + let objects = self.objects; + self.plain_object(&shapes::rectangle(b), FillRule::NonZero, None, None, Xy::PLAIN); + if self.objects == objects { + return; + } + self.body.push_str("%_/ArtDictionary :\n"); + self.text_wrap(w); + self.body.push_str("%_;\n%_\n"); + } + // ---------- color ---------- /// Set the fill (or with `stroke`, the stroke) to paint `p`: a spot or global swatch by its diff --git a/crates/eps/src/ai_editing/writer/envelopes.rs b/crates/eps/src/ai_editing/writer/envelopes.rs index dcd7274291..5e5e9068c0 100644 --- a/crates/eps/src/ai_editing/writer/envelopes.rs +++ b/crates/eps/src/ai_editing/writer/envelopes.rs @@ -26,7 +26,7 @@ use super::{MAX_NEST, Writer, Xy, hide}; use crate::import::{DEFORM_PLUGIN, EnvelopeGridPoint as GridPoint, envelope_outline, envelope_upright, warp_number}; use crate::ps; -pub(in crate::ai_editing) const ENVELOPES: &str = "envelopes of type, envelopes without contents, envelopes in opacity masks, pattern tiles, art cut to a clipping object or other envelopes' contents, envelopes on the layers of a large canvas or in a turned or mirrored frame, warps drawn without their style's net, meshes and top objects that the data would open in another shape, envelopes with a Fidelity that isn't a whole number, envelopes that map from a box other than their contents' bounds with or without strokes or keep bounds margins with Distort Appearance off, envelopes after the first 256, and envelopes nested more than 8 deep are written as their art in the editing data for other apps"; +pub(in crate::ai_editing) const ENVELOPES: &str = "envelopes of type, envelopes without contents, envelopes in opacity masks, pattern tiles, art cut to a clipping object or other envelopes' contents, envelopes on the layers of a large canvas or in a turned or mirrored frame, warps drawn without their style's net, meshes and top objects that the data would open in another shape, envelopes with a Fidelity that isn't a whole number, envelopes that map from a box other than their contents' bounds with or without strokes or keep bounds margins with Distort Appearance off, envelopes after the first 256 envelopes and images with a Warp, and envelopes nested more than 8 deep are written as their art in the editing data for other apps"; /// The most rows or columns of an envelope's grid written (Make with Mesh's own limit, and the /// reader's). @@ -287,7 +287,7 @@ impl Writer<'_> { /// another shape, or some of it is left out for the object limit ([`Self::take_objects`]). pub(super) fn envelope(&mut self, n: &Node, xy: Xy) -> bool { let NodeKind::Envelope { content, kind, fidelity, editing, options, frame } = &n.kind else { return false }; - if self.hidden > 0 || self.clip.is_some() || self.nest >= MAX_NEST || !self.symbols_live || self.envelopes_left == 0 { + if self.hidden > 0 || self.clip.is_some() || self.nest >= MAX_NEST || !self.symbols_live || self.checks_left == 0 { return false; } let Some(record) = record(n, content, kind, *fidelity, *editing, options, **frame) else { return false }; @@ -339,7 +339,7 @@ impl Writer<'_> { return false; } self.deform = true; - self.envelopes_left -= 1; + self.checks_left -= 1; true } diff --git a/crates/eps/src/ai_editing/writer/images.rs b/crates/eps/src/ai_editing/writer/images.rs index 1d5b9a8c4c..3813deccf9 100644 --- a/crates/eps/src/ai_editing/writer/images.rs +++ b/crates/eps/src/ai_editing/writer/images.rs @@ -121,29 +121,37 @@ impl Samples { } impl Writer<'_> { + /// Whether [`Self::image`] can read `im`'s pixels, rather than write its gray outline. + pub(super) fn image_readable(&mut self, im: &ImageObject) -> bool { + let doc = self.doc; + doc.image_blob(im).and_then(|b| self.samples(b)).is_some() + } + /// Image object `im` of transparency `xy`: embedded, a raster ([`Self::raster`]); linked, a /// placed file with a preview ([`Self::placed_file`]), except in a part of the data written on /// `%_` lines (other than a styled object's copy on the layers, [`Self::styled_object`]) and in /// a symbol's art. One whose pixels can't be read is its outline filled mid gray. Where the art is /// cut to a clipping path, the image is in a clipping group of that path; a raster of pixels /// written whole already is then the part of them that the path shows ([`ai_ops::image_window`]). - pub(super) fn image(&mut self, im: &ImageObject, xy: Xy) { + /// True when the image is written as an image. + pub(super) fn image(&mut self, im: &ImageObject, xy: Xy) -> bool { let doc = self.doc; let blob = doc.image_blob(im); let read = blob.and_then(|b| self.samples(b)); let Some((samples, deep)) = read.as_deref() else { let bounds = PathData::from_bezpath(&(im.xf * Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height)).to_path(0.1))); self.warn(IMAGES); - return self.fill_object(&bounds, FillRule::NonZero, &FillLayer::new(Paint::solid(Color::gray(0.5))), xy); + self.fill_object(&bounds, FillRule::NonZero, &FillLayer::new(Paint::solid(Color::gray(0.5))), xy); + return false; }; // A region that has nothing left hides the image. if self.clip.as_ref().is_some_and(|c| c.subpaths.iter().all(|sp| sp.anchors.is_empty())) { - return; + return false; } // The image, and where it is cut, the clipping group and its clipping path. let clipping = self.clip.as_ref().map_or(0, |c| 1 + super::object_count(c.subpaths.iter().filter(|sp| !sp.anchors.is_empty()).count())); if !self.take_objects(1 + clipping) { - return; + return false; } if *deep { self.warn(IMAGE_DEPTH); @@ -217,6 +225,7 @@ impl Writer<'_> { self.end_group("Q", Xy::PLAIN); } self.clip = cut; + true } /// An embedded image whose pixels `xf` places in the document: `%AI5_File:`, diff --git a/crates/eps/src/ai_editing/writer/styles.rs b/crates/eps/src/ai_editing/writer/styles.rs index ab9ed6a482..a8a2da677c 100644 --- a/crates/eps/src/ai_editing/writer/styles.rs +++ b/crates/eps/src/ai_editing/writer/styles.rs @@ -23,6 +23,7 @@ pub(in crate::ai_editing) const LARGE_CANVAS_STYLES: &str = "on a large canvas, pub(in crate::ai_editing) const PANEL_STYLES: &str = "graphic styles with gradient or pattern fills, with fills, strokes or effects the editing data can't hold as a graphic style, with a name another style has, with names over 1,024 bytes, or past 4,096 styles, are left out of the editing data for other apps"; pub(in crate::ai_editing) const PANEL_EMPTY: &str = "a Graphic Styles panel with no style written opens from the editing data with a new document's styles"; +pub(in crate::ai_editing) const WARPED_IMAGES: &str = "images with a Warp after the first 256 envelopes and images with a Warp are written as their drawn look, without their Warp, in the editing data for other apps"; pub(in crate::ai_editing) const STYLE_LINKS: &str = "links to graphic styles are left out of the editing data for other apps on type, images, symbol instances, knockout shapes and other objects that aren't written with their graphic style"; /// How many objects of `doc`'s layers, opacity masks and symbols are linked to a graphic style. @@ -719,6 +720,24 @@ impl Writer<'_> { items_keep && m.children().is_none_or(|c| c.iter().all(|c| self.member_keeps_outline(c))) } + /// Whether `orig` may be written with its art style as far as the reader's checks go: an image + /// with a Warp takes one of them, as an envelope does ([`Self::envelope`]); with none left, it is + /// written as its drawn look, with a warning. One whose pixels can't be read takes none: it is + /// written as its gray outline ([`Self::image`]). + pub(super) fn check_left(&mut self, orig: &Node) -> bool { + if !warped_image(orig) || self.checks_left > 0 { + return true; + } + let doc = self.doc; + if let NodeKind::Image(im) = &orig.kind + && !self.image_readable(&doc.shown_image(orig, im)) + { + return true; + } + self.warn(WARPED_IMAGES); + false + } + /// Object `n` (as baking left it; `orig` before baking) with the style `name`: its lock and /// hidden state; its drawn look (a group of its vector art as baking left it, without shadows, /// glows or feathers, the object's transparency @@ -729,7 +748,8 @@ impl Writer<'_> { /// `1 (name) XW`. /// The look's group and the object itself are counted first ([`Self::take_objects`]): without /// room for them, nothing is written, and the object counts neither as written with its graphic - /// style nor as written with a brush on its stroke. + /// style nor as written with a brush on its stroke. An image written as an image takes one of + /// the reader's checks ([`Self::check_left`]). pub(super) fn styled_object(&mut self, n: &Node, orig: &Node, name: &str) { let own = match &orig.kind { NodeKind::Path { path, .. } => super::object_count(path.subpaths.iter().filter(|sp| !sp.anchors.is_empty()).count()), @@ -787,9 +807,12 @@ impl Writer<'_> { match &orig.kind { NodeKind::Path { path, rule, .. } => self.styled_outline(orig, path, *rule, fit, xy), NodeKind::Compound { rule, .. } => self.styled_outline(orig, &compound_path(orig), *rule, fit, xy), + // The reader checks the object only when it is an image, not its gray outline. NodeKind::Image(im) => { let was = std::mem::replace(&mut self.styled_copy, on_layers); - self.image(&self.doc.shown_image(orig, im), xy); + if self.image(&self.doc.shown_image(orig, im), xy) { + self.checks_left = self.checks_left.saturating_sub(1); + } self.styled_copy = was; } NodeKind::Group { children, .. } => { diff --git a/crates/eps/src/ai_editing/writer/symbols.rs b/crates/eps/src/ai_editing/writer/symbols.rs index d058c9b770..0c8d2c7d3b 100644 --- a/crates/eps/src/ai_editing/writer/symbols.rs +++ b/crates/eps/src/ai_editing/writer/symbols.rs @@ -233,6 +233,7 @@ impl Writer<'_> { if !self.take_objects(1) { self.defining_symbols.pop(); self.keep_since(before); + (self.in_look, self.drawn) = (in_look, drawn); return false; } // The art is written in the symbol's space, from the state `0 A` and `0 Xw` set, from the diff --git a/crates/eps/src/ai_editing/writer/texts.rs b/crates/eps/src/ai_editing/writer/texts.rs index 6bc3c63b09..2e90817b98 100644 --- a/crates/eps/src/ai_editing/writer/texts.rs +++ b/crates/eps/src/ai_editing/writer/texts.rs @@ -20,6 +20,7 @@ use std::fmt::Write; use kurbo::{ParamCurveArclen, PathSeg}; use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::text::MAX_AKI; use vectorcraft_doc::{ AreaOptions, Burasagari, CharStyle, Document, FirstBaseline, Justify, LineCap, LineJoin, Mojikumi, Node, NodeId, NodeKind, ParaDirection, ParaStyle, PathAlign, PathEffect, TextKind, TextObject, VerticalAlign, @@ -29,7 +30,7 @@ use vectorcraft_geom::{Affine, PathData, Point}; use crate::ps; /// What the text document holds of type, and what it leaves out. -pub(in crate::ai_editing) const TYPE_ATTRIBUTES: &str = "attributes of type other than its font, size, leading, tracking, baseline shift, horizontal and vertical scale, solid fill, solid stroke and its weight, cap, join and miter limit, capitals, small capitals at the document's size, Tate-chu-yoko, Standard Vertical Roman Alignment, paragraph alignment, indents, space before and after, hyphenation on or off and right-to-left direction (for example underline, kerning, OpenType features, swatch links of its colors, character and paragraph styles, tabs, lists, optical margin alignment, area type's inset spacing, vertical alignment and flow, a minimum first baseline with the Ascent first baseline, and type on a path's effect, alignment and spacing and an end bracket at the very end of an open path) are left out of the editing data for other apps"; +pub(in crate::ai_editing) const TYPE_ATTRIBUTES: &str = "attributes of type other than its font, size, leading, tracking, baseline shift, horizontal and vertical scale, solid fill, solid stroke and its weight, cap, join and miter limit, capitals, small capitals at the document's size, Tate-chu-yoko, Standard Vertical Roman Alignment, Insert Aki, paragraph alignment, indents, space before and after, hyphenation on or off and right-to-left direction (for example underline, kerning, OpenType features, swatch links of its colors, character and paragraph styles, tabs, lists, optical margin alignment, area type's inset spacing, vertical alignment and flow, a minimum first baseline with the Ascent first baseline, and type on a path's effect, alignment and spacing and an end bracket at the very end of an open path) are left out of the editing data for other apps"; /// The version of the text document's form (`/98 << /0 n >>`), as the newest files users sent have it. const STREAM_VERSION: u32 = 14; @@ -204,7 +205,9 @@ pub(in crate::ai_editing) fn holds(n: &Node, t: &TextObject) -> bool { shape(t).as_ref().and_then(segments).is_some_and(|s| !(open && closed(&s))) } }; - // Area type that flows around wrap objects: the data doesn't hold their wrap settings. + // Area type with wrap shapes: the text document doesn't hold them. The reader works them out + // again from the art above the type, which can wrap it differently (a live object written as + // its drawn pieces) or not at all. shape_ok && t.wrap.is_empty() && t.ruby.is_empty() @@ -324,6 +327,12 @@ fn end_read_as_none(t: &TextObject) -> bool { !closed(&segs) && end < 1.0 - 1e-9 && place_on(&segs, end) >= segs.len() as f64 - 0.02 } +/// Insert Aki Left or Right `v` as the text document holds it: 0 to [`MAX_AKI`] in 1/1000 em, and 0 +/// for a value that is not a number. +fn held_aki(v: f64) -> f64 { + if v.is_nan() { 0.0 } else { v.clamp(0.0, MAX_AKI) } +} + /// Has type `t` attributes the text document leaves out ([`TYPE_ATTRIBUTES`])? pub(in crate::ai_editing) fn loses(t: &TextObject) -> bool { // Small capitals are read back at Document Setup's default size. @@ -358,6 +367,8 @@ pub(in crate::ai_editing) fn loses(t: &TextObject) -> bool { tate_chu_yoko: s.tate_chu_yoko, // Key 35 holds one of the two: a Tate-chu-yoko run is read back without the other. standard_vertical_roman: s.standard_vertical_roman && !s.tate_chu_yoko, + aki_left: held_aki(s.aki_left), + aki_right: held_aki(s.aki_right), ..CharStyle::default() } }; @@ -675,6 +686,14 @@ impl TextDoc { }; d.push((12, V::Int(caps))); d.push((35, V::Int(baseline_direction(st)))); + // Insert Aki Left and Right in 1/1000 em, as the reader reads keys 49 and 50. No key is no + // space added: neither the stories' character attributes nor `[Normal Character Style]` set one. + for (key, v) in [(49, st.aki_left), (50, st.aki_right)] { + let v = held_aki(v); + if v > 0.0 { + d.push((key, real(v))); + } + } let fill = solid(&st.fill).flatten(); // A stroke of no width keeps its paint. let stroke = solid(&st.stroke).flatten(); @@ -962,6 +981,7 @@ impl TextDoc { matches!(t.kind, TextKind::Area { .. }) && t.vertical == vertical && writable(n.id) + // The text document doesn't hold wrap shapes (see `holds`). && t.wrap.is_empty() && plain(n) && t.ruby.is_empty() diff --git a/crates/eps/src/import.rs b/crates/eps/src/import.rs index bdb3b9cf50..c791f7c459 100644 --- a/crates/eps/src/import.rs +++ b/crates/eps/src/import.rs @@ -94,7 +94,7 @@ pub(crate) use ai::{ }; pub(crate) use ate::{MAX_BYTES as MAX_TEXT_DOCUMENT, MAX_FRAMES, MAX_SEGMENTS, MAX_STORY, MAX_VALUES as MAX_TEXT_VALUES, record_version}; pub use native::{AiLayers, ai_alone, ai_alone_on_page, ai_alone_with, ai_layers_alone, ai_opened_artboard, is_loss, layered_ai, layered_ai_from}; -pub(crate) use native::{MAX_TEXT, scale_document}; +pub(crate) use native::{MAX_TEXT, scale_document, scale_symbols}; pub use text::family_style; pub(crate) use text::{document_font, postscript_face}; diff --git a/crates/eps/src/import/ai/read.rs b/crates/eps/src/import/ai/read.rs index 5ef013ecb5..0cf1c64a89 100644 --- a/crates/eps/src/import/ai/read.rs +++ b/crates/eps/src/import/ai/read.rs @@ -215,6 +215,9 @@ pub struct Structure { pub text_patterns: HashMap, /// The file's `%AI24_LargeCanvasScale` (1 when it declares none), applied or not. pub canvas_scale: f64, + /// The data's symbols are at their own size, whatever its scale: VectorCraft wrote it (its + /// `%%Creator` is [`crate::ai_editing::CREATOR_TEXT`]). + pub symbols_own_size: bool, /// The objects by their XML id (`AI10_ArtUID`), a text object by its slot's id: `None` for an /// id two objects have. pub xml_ids: HashMap>, @@ -648,6 +651,8 @@ struct Reader<'a> { page_art: bool, /// The declared `%AI24_LargeCanvasScale` (1 without one), applied or not. canvas_scale: f64, + /// [`Structure::symbols_own_size`], from the header's `%%Creator`. + symbols_own_size: bool, /// `%AI5_RulerUnits` from the header (Illustrator 7 spec table 3, plus centimeters and pixels). ruler_units: Option, /// This reader reads a pattern's definition (see [`Reader::define_pattern`]). @@ -823,6 +828,7 @@ impl<'a> Reader<'a> { large_canvas: None, page_art: false, canvas_scale: 1.0, + symbols_own_size: false, ruler_units: None, pattern: None, pattern_tiles: HashMap::new(), diff --git a/crates/eps/src/import/ai/read/directives.rs b/crates/eps/src/import/ai/read/directives.rs index f86ee6603b..0fe6b9da87 100644 --- a/crates/eps/src/import/ai/read/directives.rs +++ b/crates/eps/src/import/ai/read/directives.rs @@ -79,6 +79,10 @@ impl<'a> Reader<'a> { } return Ok(()); } + if let Some(v) = bytes.strip_prefix(b"%Creator:") { + self.symbols_own_size = v.trim_ascii() == crate::ai_editing::CREATOR_TEXT.as_bytes(); + return Ok(()); + } if bytes == b"%EndComments" { self.header_done = true; } diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs index a7451c8b99..ba6a8bd2de 100644 --- a/crates/eps/src/import/ai/read/document.rs +++ b/crates/eps/src/import/ai/read/document.rs @@ -467,6 +467,10 @@ pub struct Symbols { /// The global and spot colors the symbols' art is linked to, as swatches, as [`read`] adds /// them to a document read from the layers. pub swatches: Vec, + /// The data's declared large canvas scale (1 when it declares none), not applied to the art. + pub canvas_scale: f64, + /// [`Structure::symbols_own_size`]. + pub own_size: bool, } /// The symbols of the editing data `data`, for a file whose layers aren't read (a symbol library @@ -529,7 +533,7 @@ pub fn symbols(data: &[u8], names: &mut obj::Names) -> Option { .chain(art_names(symbols.iter().map(|(s, _)| &*s.art))) .collect(); names.absorb_among(std::mem::take(&mut r.names), &used); - Some(Symbols { symbols, images, swatches }) + Some(Symbols { symbols, images, swatches, canvas_scale: r.canvas_scale, own_size: r.symbols_own_size }) } /// [`artboards`] as far as reading `data` from its start gets: those read before an error, and @@ -1147,7 +1151,7 @@ impl<'a> Reader<'a> { continue; } let Some(st) = self.styles.get(&name) else { continue }; - let Some(mut appearance) = appearance_from_art_style(st) else { continue }; + let Some(mut appearance) = appearance_from_art_style(st, &self.gradients) else { continue }; // A Large Canvas copy's styles are at its art's scale ([`Self::ensure_space`]). if let Some(s) = self.large_canvas.filter(|s| *s != 1.0) { appearance.scale_strokes(s); @@ -1194,6 +1198,11 @@ impl<'a> Reader<'a> { drop_commented_copies(&mut self.doc.layers, &self.hidden_ids); super::on_path::apply(&mut self.doc, &self.on_path); let mut doc = std::mem::replace(&mut self.doc, Document::new(1.0, 1.0)); + // A Large Canvas copy's symbols are at its art's scale too ([`Self::ensure_space`]), except + // in data VectorCraft wrote. + if let Some(s) = self.large_canvas.filter(|s| *s != 1.0 && !self.symbols_own_size) { + crate::import::scale_symbols(&mut doc, s); + } // The active artboard, when it is not the first (the default). let active = self.active_board.filter(|i| *i > 0 && *i < self.artboards.len()); let boards: Vec = if self.artboards.is_empty() { @@ -1374,6 +1383,7 @@ impl<'a> Reader<'a> { styles_read, text_patterns, canvas_scale: self.canvas_scale, + symbols_own_size: self.symbols_own_size, xml_ids: self.xml_ids, bindings, bindings_skipped, diff --git a/crates/eps/src/import/ai/read/graph.rs b/crates/eps/src/import/ai/read/graph.rs index 759eb4e1cd..609713fe16 100644 --- a/crates/eps/src/import/ai/read/graph.rs +++ b/crates/eps/src/import/ai/read/graph.rs @@ -631,6 +631,7 @@ impl<'a> Reader<'a> { let Some(paints) = series_paints(art, &tags, spec.kind == GraphKind::Line) else { return false }; spec.series_paints = paints; spec.placed = Some(placed); + spec.placed_art = art.children().and_then(|c| vectorcraft_doc::graph::graph_art_without_type(c)); tag_series(art, &tags); art.extras_mut().graph = Some(Box::new(spec)); true diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index 6b963a74ad..8c032d5d83 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -1323,9 +1323,11 @@ fn styled(object: &Node, look: &Node, st: &crate::import::ai::style::ArtStyle, p } /// A graphic style's appearance from art style `st`, on no object: `None` when the style isn't one -/// this reads, or paints with a gradient or a pattern (placed on each object as its drawn look has them). +/// this reads, paints with a pattern, or paints with a gradient that names no swatch of `gradients`. /// A style that is one paint is its fill and stroke ([`crate::import::ai::style::ArtStyle::one_paint`]). -pub(super) fn appearance_from_art_style(st: &crate::import::ai::style::ArtStyle) -> Option { +/// A style keeps only its gradients' names and angles, so each one's gradient, by VectorCraft's own +/// rule, is fitted to the bounds of whatever object the style is applied to, at its angle. +pub(super) fn appearance_from_art_style(st: &crate::import::ai::style::ArtStyle, gradients: &HashMap) -> Option { use crate::import::ai::style::StyleItem; if !st.plain { return None; @@ -1341,8 +1343,15 @@ pub(super) fn appearance_from_art_style(st: &crate::import::ai::style::ArtStyle) // A graphic style's brush isn't checked against the file's brushes: it is left out. StyleItem::Stroke { brush: Some(_), .. } => return None, StyleItem::Stroke { .. } => stroke_layer(item)?, - StyleItem::Gradient { .. } | StyleItem::Pattern { .. } => return None, + StyleItem::Gradient { name, angle } => AppearanceItem::Fill(FillLayer::new(named_gradient(name.as_deref()?, *angle, gradients)?)), + StyleItem::Pattern { .. } => return None, }; + // A one-paint style's gradient stroke names its swatch (`style::OnePaint::items`). + if let AppearanceItem::Stroke(s) = &mut layer + && let Paint::Gradient(g) = &s.paint + { + s.paint = named_gradient(g.swatch.as_deref()?, g.angle, gradients)?; + } if let Some(look) = st.looks.get(n) { with_look(&mut layer, look); } @@ -1351,6 +1360,14 @@ pub(super) fn appearance_from_art_style(st: &crate::import::ai::style::ArtStyle) Some(Appearance { items, effects: st.effects.clone(), contents_index: st.contents_index }) } +/// The gradient of `gradients` named `name` at `angle` degrees, fitted to the bounds of the object it +/// paints (`None` when there is no such gradient). +fn named_gradient(name: &str, angle: f64, gradients: &HashMap) -> Option { + let mut g = vectorcraft_color::gradient::GradientPaint::new(gradients.get(name)?.clone()); + g.angle = angle; + Some(Paint::Gradient(Box::new(g))) +} + /// What the reader makes of art style `name` in `section` (the text between `%AI9_BeginArtStyles` /// and its end), for writers that check a style before they write it. #[derive(Clone, Debug)] @@ -1400,7 +1417,9 @@ pub(crate) fn read_art_style(section: &[u8], name: &str, own_gradient: Option<&P _ => None, }) .collect(); - let mut appearance = appearance_from_art_style(&st)?; + // No gradient is taken by name: on an object, one that isn't its own is placed where its drawn + // look has it. + let mut appearance = appearance_from_art_style(&st, &HashMap::new())?; for (item, brush) in appearance.items.iter_mut().zip(brushes) { if let (AppearanceItem::Stroke(s), Some(brush)) = (item, brush) { s.brush = Some(brush); diff --git a/crates/eps/src/import/ai/style.rs b/crates/eps/src/import/ai/style.rs index 7d570fca65..e0068a52be 100644 --- a/crates/eps/src/import/ai/style.rs +++ b/crates/eps/src/import/ai/style.rs @@ -216,7 +216,8 @@ pub(super) struct ArtStyle { pub simple_pattern: Option, /// A style that is one paint: its fill and stroke, bottom first, each there when its /// `stroke fill Xd` turns it on (none when neither is on). `Err` when it turns on a fill or - /// stroke whose paint isn't read here (a gradient, a pattern, a color that isn't read) or has + /// stroke whose paint isn't read here (a gradient that names no swatch or isn't in a gradient + /// instance, a pattern, a color that isn't read) or has /// no `Xd`. `None` for a style with filters, whose paint is [`Self::items`]. pub one_paint: Option, ()>>, } @@ -313,6 +314,8 @@ struct Filter { gradient_of: Option<(Option, f64)>, /// `(name) … [matrix] p`, and the numbers between the name and the matrix. pattern: Option<(String, Option<[f64; 6]>, Vec)>, + /// Its last fill paint, which replaces those before it. + fill_last: LastPaint, /// The plug-in object it refers to (`/GObjRef : (name) (plug-in) /PluginObject`): its name and /// plug-in name. plugin_object: Option<(String, String)>, @@ -346,6 +349,7 @@ impl Default for Filter { gradient: false, gradient_of: None, pattern: None, + fill_last: LastPaint::None, plugin_object: None, xy: None, xy_group: None, @@ -354,6 +358,15 @@ impl Default for Filter { } } +/// Which paint a filter's paint operators set last. +#[derive(Clone, Copy, Debug, PartialEq)] +enum LastPaint { + None, + Color, + Gradient, + Pattern, +} + /// Most filters read in one style. const MAX_FILTERS: usize = 4096; @@ -662,7 +675,7 @@ fn paint_op(f: &mut Filter, op: &str, vals: &[V], names: &mut Names) { | "xz" => { let Some((p, _)) = paint::color_op_in(op, vals, names) else { return }; if op.ends_with(|c: char| c.is_ascii_lowercase()) { - f.fill = Some(p); + (f.fill, f.fill_last) = (Some(p), LastPaint::Color); } else { f.stroke = Some(p); } @@ -719,7 +732,7 @@ fn paint_op(f: &mut Filter, op: &str, vals: &[V], names: &mut Names) { } // `flag (name) x y angle length a b c d tx ty Bg`. "Bg" => { - f.gradient = true; + (f.gradient, f.fill_last) = (true, LastPaint::Gradient); let at = vals.iter().rposition(|v| matches!(v, V::Str(_))); let name = at.and_then(|i| vals.get(i)).and_then(|v| names.text(v)); let n: Vec = at.map_or(&[][..], |i| vals.get(i + 1..).unwrap_or_default()).iter().filter_map(V::num).collect(); @@ -728,7 +741,7 @@ fn paint_op(f: &mut Filter, op: &str, vals: &[V], names: &mut Names) { } "p" => { if let Some(pattern) = pattern_operands(vals, names) { - f.pattern = Some(pattern); + (f.pattern, f.fill_last) = (Some(pattern), LastPaint::Pattern); } } _ => {} @@ -786,6 +799,11 @@ struct OnePaint { stroke_unread: bool, /// Inside a gradient instance (`flag Bb` … `BB`): whether it paints the stroke (flag 1). instance: Option, + /// The gradient swatch's name and angle of its last fill paint, when that is a gradient + /// instance's `Bg`. + fill_gradient: Option<(String, f64)>, + /// The same for its last stroke paint. + stroke_gradient: Option<(String, f64)>, } impl OnePaint { @@ -811,9 +829,26 @@ impl OnePaint { _ => {} } paint_op(&mut self.paint, op, vals, names); + // A gradient instance's `Bg` names the swatch its fill or stroke paints with; any other + // paint of that side replaces it. Outside an instance, which side it paints isn't known. + let named = || match (op, &self.paint.gradient_of) { + ("Bg", Some((Some(name), angle))) => Some((name.clone(), *angle)), + _ => None, + }; + match op { + "Bg" if self.instance == Some(true) => self.stroke_gradient = named(), + "Bg" if self.instance == Some(false) => self.fill_gradient = named(), + "Bg" => (self.fill_gradient, self.stroke_gradient) = (None, None), + "p" | "Xa" | "k" | "g" | "x" | "Xx" | "Xk" | "Xs" | "Xz" | "xa" | "xx" | "xk" | "xs" | "xz" => self.fill_gradient = None, + "P" | "XA" | "K" | "G" | "X" | "XX" | "XK" | "XS" | "XZ" => self.stroke_gradient = None, + _ => {} + } } - /// Its fill and stroke ([`ArtStyle::one_paint`]). + /// Its fill and stroke ([`ArtStyle::one_paint`]). A gradient fill is its [`StyleItem::Gradient`]; + /// a gradient stroke's paint is a gradient that only names its swatch (`swatch`) at its angle, + /// with default stops: `read::ops`' `appearance_from_art_style` gives it the file's gradient of + /// that name. fn items(&self) -> Result, ()> { let f = &self.paint; if !self.xd { @@ -822,14 +857,22 @@ impl OnePaint { let (stroked, filled) = f.paints; let mut items = vec![]; if filled { - match &f.fill { - Some(p) if !self.fill_unread => items.push(StyleItem::Fill(p.clone())), + match (&f.fill, &self.fill_gradient) { + (Some(p), _) if !self.fill_unread => items.push(StyleItem::Fill(p.clone())), + (_, Some((name, angle))) if self.fill_unread => items.push(StyleItem::Gradient { name: Some(name.clone()), angle: *angle }), _ => return Err(()), } } if stroked { - match &f.stroke { - Some(p) if !self.stroke_unread => items.push(StyleItem::Stroke { + let named = self.stroke_gradient.as_ref().filter(|_| self.stroke_unread).map(|(name, angle)| { + Paint::Gradient(Box::new(vectorcraft_color::gradient::GradientPaint { + angle: *angle, + swatch: Some(name.clone()), + ..vectorcraft_color::gradient::GradientPaint::new(vectorcraft_color::gradient::Gradient::default()) + })) + }); + match named.as_ref().or(f.stroke.as_ref().filter(|_| !self.stroke_unread)) { + Some(p) => items.push(StyleItem::Stroke { paint: p.clone(), width: f.width, cap: f.cap, @@ -1396,6 +1439,8 @@ fn paint_item(f: &Filter) -> Result, ()> { match f.name.as_str() { FILL if !f.paints.1 => Ok(None), FILL => match (&f.pattern, &f.gradient_of, &f.fill) { + (.., Some(p)) if f.fill_last == LastPaint::Color => Ok(Some(StyleItem::Fill(p.clone()))), + (_, Some((name, angle)), _) if f.fill_last == LastPaint::Gradient => Ok(Some(StyleItem::Gradient { name: name.clone(), angle: *angle })), (Some((name, matrix, controls)), ..) => Ok(Some(StyleItem::Pattern { name: name.clone(), matrix: *matrix, controls: controls.clone() })), (None, Some((name, angle)), _) => Ok(Some(StyleItem::Gradient { name: name.clone(), angle: *angle })), (None, None, _) if f.gradient => Ok(Some(StyleItem::Gradient { name: None, angle: 0.0 })), diff --git a/crates/eps/src/import/ai/style/tests.rs b/crates/eps/src/import/ai/style/tests.rs index ea8428809c..c4b006fe2a 100644 --- a/crates/eps/src/import/ai/style/tests.rs +++ b/crates/eps/src/import/ai/style/tests.rs @@ -471,6 +471,28 @@ fn lettering() -> String { format!("/KnownStyle :\n(Lettering) /Name ,\n/ActiveStyle :\n{root}\n/Execution ;\n /Def ;\n") } +/// A fill filter's last paint is its fill: a color, a gradient or a pattern replaces whichever of the +/// others came before it. +#[test] +fn a_fill_filter_paints_with_its_last_paint() { + let gradient = "0 Bb\n2 (Sky) 0 0 30 1 1 0 0 1 0 0 1 Bg\n0 BB"; + let pattern = "(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p"; + let color = "0 0 0 0 1 0 0 Xa"; + let items = |paint: String| { + let root = compound("Chain Style Filter", &[fill(&paint)]); + let data = format!("/KnownStyle :\n(S) /Name ,\n/ActiveStyle :\n{root}\n/Execution ;\n /Def ;\n"); + art_styles(data.as_bytes()).remove("S").map(|s| s.items).unwrap_or_default() + }; + for before in [gradient, pattern] { + assert!(matches!(items(format!("{before}\n{color}")).as_slice(), [StyleItem::Fill(Paint::Solid { .. })]), "{before}"); + } + for before in [color, pattern] { + assert_eq!(items(format!("{before}\n{gradient}")), [StyleItem::Gradient { name: Some("Sky".into()), angle: 30.0 }], "{before}"); + } + assert!(matches!(items(format!("{color}\n{pattern}")).as_slice(), [StyleItem::Pattern { .. }])); + assert!(matches!(items(format!("{gradient}\n{pattern}")).as_slice(), [StyleItem::Pattern { .. }])); +} + #[test] fn a_stack_of_fills_with_effects_of_their_own_is_read_as_itself() { // GUARDS: more than one fill, or an effect on a fill, made the style not plain, and type @@ -1544,14 +1566,22 @@ fn a_style_of_one_paint_reads_as_the_fill_and_stroke_its_xd_turns_on() { // A gradient instance's flag says which one it paints: a stroke gradient leaves a solid fill read. let fill_and_stroke_gradient = one("0 0 1 0 k\n1 Bb\n2 (Ramp) 0 0 90 1 1 0 0 1 0 0 1 Bg\n0 BB\n0 1 Xd\n"); assert!(matches!(fill_and_stroke_gradient, Some(Ok(i)) if matches!(i.as_slice(), [StyleItem::Fill(_)]))); - // Not read: no `Xd`, a gradient or pattern fill, a pattern stroke, a gradient stroke after a solid one, a paint - // turned on with no color. + // A gradient instance's fill is its swatch at its angle; its stroke, after a solid one too, is a + // gradient naming its swatch at its angle, at the stroke's weight. + let gradient_fill = one("0 Bb\n2 (Sky) 0 0 30 100 1 0 0 1 0 0 Bg\n0 BB\n0 1 Xd\n"); + assert_eq!(gradient_fill, Some(Ok(vec![StyleItem::Gradient { name: Some("Sky".into()), angle: 30.0 }]))); + let gradient_stroke = one("0 R\n0 1 1 0 K\n1 Bb\n0 0 0 0 Bh\n2 (Ramp) 0 0 90 1 1 0 0 1 0 0 1 Bg\n0 BB\n2 w\n1 0 Xd\n"); + let Some(Ok(items)) = &gradient_stroke else { panic!("{gradient_stroke:?}") }; + let [StyleItem::Stroke { paint: Paint::Gradient(g), width, .. }] = items.as_slice() else { panic!("{items:?}") }; + assert_eq!((g.swatch.as_deref(), g.angle, g.geom, *width), (Some("Ramp"), 90.0, None, 2.0)); + // Not read: no `Xd`, a pattern fill, a pattern stroke, a gradient outside a gradient instance, a + // paint turned on with no color. for paint in [ format!("0 0 1 0 k\n{stroke}"), - "0 Bb\n2 (Sky) 0 0 0 100 1 0 0 1 0 0 Bg\n0 BB\n0 1 Xd\n".to_string(), "(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n0 1 Xd\n".to_string(), "(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] P\n1 0 Xd\n".to_string(), - "0 R\n0 1 1 0 K\n1 Bb\n0 0 0 0 Bh\n2 (Ramp) 0 0 90 1 1 0 0 1 0 0 1 Bg\n0 BB\n2 w\n1 0 Xd\n".to_string(), + "2 (Sky) 0 0 0 100 1 0 0 1 0 0 Bg\n0 1 Xd\n".to_string(), + "0 Bb\n2 (Sky) 0 0 0 100 1 0 0 1 0 0 Bg\n0 BB\n(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n0 1 Xd\n".to_string(), "0 0 1 0 k\n1 1 Xd\n".to_string(), ] { assert_eq!(one(&paint), Some(Err(())), "{paint}"); diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index d160248a2d..8b081782d3 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -10339,13 +10339,35 @@ fn a_brushed_path_with_samples_of_the_pen_keeps_its_drawn_look() { let a = art(&read_ok(&format!("{def}{style}{}", layer(&first))).doc); assert_eq!(a.len(), 1, "{a:#?}"); assert!(matches!(a[0].kind, NodeKind::Path { .. }), "the path, brushed: {a:#?}"); - // A brush whose modes are Fixed and Random, one whose pen modes vary by 0, and an Art brush - // don't follow the pen: the path comes in brushed. + // Each setting that follows the pen keeps the drawn look on its own, with the other two fixed: + // the diameter with the pressure or the tilt, the roundness with the bearing and the angle with + // the barrel's rotation. + let one_setting = [ + ("the diameter with the pressure", "1 4 8 40 40 30 30 2 0 0 0", [(6.0, 2.0), (40.0, 0.0), (30.0, 0.0)], [2, 0, 0]), + ("the diameter with the tilt", "1 4 8 40 40 30 30 4 0 0 0", [(6.0, 2.0), (40.0, 0.0), (30.0, 0.0)], [4, 0, 0]), + ("the roundness with the bearing", "1 6 6 30 50 30 30 0 5 0 0", [(6.0, 0.0), (40.0, 10.0), (30.0, 0.0)], [0, 5, 0]), + ("the angle with the rotation", "1 6 6 40 40 -150 210 0 0 6 0", [(6.0, 0.0), (40.0, 0.0), (30.0, 180.0)], [0, 0, 6]), + ]; + for (why, params, settings, codes) in one_setting { + let def = plugin_object(CALLIGRAPHIC, "Six D", params); + let style = brushed_style("Six D", 0.5, settings, codes, 0); + let r = read_ok(&format!("{def}{style}{}", layer(&path))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{why}: {a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Group { .. }), "{why}: the drawn look, {a:#?}"); + assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{why}: {:?}", r.warnings); + } + // A brush whose modes are Fixed and Random, one whose pen modes vary by 0, one whose only + // varying setting is Random beside a pen setting that varies by 0, and an Art brush don't + // follow the pen: the path comes in brushed. let fixed_def = plugin_object(CALLIGRAPHIC, "Six D", &SIX_D.replace(" 2 5 6 0", " 0 1 0 0")); let fixed = brushed_style("Six D", 0.5, SIX_D_SETTINGS, [0, 1, 0], 0); let even_def = plugin_object(CALLIGRAPHIC, "Six D", "1 6 6 40 40 30 30 2 5 6 0"); let even = brushed_style("Six D", 0.5, [(6.0, 0.0), (40.0, 0.0), (30.0, 0.0)], [2, 5, 6], 0); - for (why, def, style) in [("Fixed and Random", fixed_def, fixed), ("no variation", even_def, even)] { + let random_def = plugin_object(CALLIGRAPHIC, "Six D", "1 4 8 40 40 30 30 1 2 0 0"); + let random = brushed_style("Six D", 0.5, [(6.0, 2.0), (40.0, 0.0), (30.0, 0.0)], [1, 2, 0], 0); + let cases = [("Fixed and Random", fixed_def, fixed), ("no variation", even_def, even), ("Random beside an even pen setting", random_def, random)]; + for (why, def, style) in cases { let r = read_ok(&format!("{def}{style}{}", layer(&path))); let a = art(&r.doc); assert_eq!(a.len(), 1, "{why}: {a:#?}"); diff --git a/crates/eps/src/import/ate.rs b/crates/eps/src/import/ate.rs index 28994527a7..a45c203d75 100644 --- a/crates/eps/src/import/ate.rs +++ b/crates/eps/src/import/ate.rs @@ -25,6 +25,7 @@ use std::collections::{BTreeMap, HashMap}; use kurbo::{BezPath, CubicBez, ParamCurve, ParamCurveArclen}; use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::text::MAX_AKI; use vectorcraft_doc::{ Burasagari, CharStyle, HyphenationOptions, JustificationOptions, Justify, Kinsoku, KinsokuShoriType, LineCap, LineJoin, Node, NodeId, NodeKind, ParaDirection, ParaStyle, PathAlign, PathEffect, TabAlign, TabStop, TextKind, TextObject, TextRun, @@ -525,6 +526,17 @@ struct Style { /// Key 35 at 1 (Standard): Standard Vertical Roman Alignment, half-width characters upright in /// a column. Any other value, or no key in the run, its character style or the defaults, is off. standard_vertical_roman: bool, + /// Keys 49 and 50, Insert Aki Left and Right ([`CharStyle::aki_left`]), in 1/1000 em. + aki_left: f64, + aki_right: f64, +} + +/// Insert Aki Left or Right as key `v` of a character style gives it, in 1/1000 em (the unit the +/// scripting reference gives `aki left` and `aki right`), 0 to [`MAX_AKI`]. A negative value, one +/// that is not a finite number, or no key is 0: no space added. A key the run itself carries wins +/// over its styles' even when it is not a number, so a bad value never shows a style's. +fn aki(v: Option<&Val>) -> f64 { + v.and_then(Val::num).filter(|v| v.is_finite() && *v > 0.0).map_or(0.0, |v| v.min(MAX_AKI)) } /// The longest font version string read from a font record: name ID 5 strings are short (`Version @@ -922,6 +934,8 @@ impl Texts { caps: num("12").filter(|v| *v == 1.0 || *v == 2.0).map_or(0, |v| v as u8), tate_chu_yoko: num("35") == Some(3.0), standard_vertical_roman: num("35") == Some(1.0), + aki_left: aki(pick("49")), + aki_right: aki(pick("50")), } } } @@ -1549,6 +1563,9 @@ fn char_style(s: &Style, scale: f64, to_text: Affine) -> CharStyle { small_caps: (s.caps == 1).then(|| vectorcraft_doc::DocSetup::default().small_caps_size), tate_chu_yoko: s.tate_chu_yoko, standard_vertical_roman: s.standard_vertical_roman, + // In ems of the type's own size, so the art's scale does not apply. + aki_left: s.aki_left, + aki_right: s.aki_right, ..CharStyle::default() } } @@ -1922,6 +1939,48 @@ mod tests { assert!(texts(b"/35 3").style(None).tate_chu_yoko && !texts(b"/35 3").style(None).standard_vertical_roman); } + /// Keys 49 and 50 of a character style are Insert Aki Left and Right in 1/1000 em, each from the + /// run, its character style and the styles that is based on, `[Normal Character Style]`, then the + /// document's defaults. A run's own 0 wins over a style's value, a value past 1000 is 1000, and a + /// negative value, one that is not a number or no key at all is 0. + #[test] + fn a_run_keeps_its_insert_aki() { + let texts = |defaults: &[u8], normal: &[u8]| Texts { + stories: vec![], + fonts: vec![], + defaults: read(defaults).unwrap(), + para_defaults: Val::Dict(BTreeMap::new()), + char_sheets: vec![ + read(&[&b"/0 ([Normal Character Style]) /6 << "[..], normal, b" >>"].concat()).unwrap(), + read(b"/0 (Base) /6 << /49 125.0 >>").unwrap(), + read(b"/0 (Spaced) /5 1 /6 << /50 500.0 >>").unwrap(), + ], + para_sheets: vec![], + frames: vec![], + patterns: HashMap::new(), + kinsoku_sets: vec![], + }; + let aki = |defaults: &[u8], normal: &[u8], run: &[u8]| { + let s = texts(defaults, normal).style(Some(&read(run).unwrap())); + (s.aki_left, s.aki_right) + }; + assert_eq!(aki(b"/0 0", b"", b"/6 << /49 250.0 /50 750.0 >>"), (250.0, 750.0), "the run's own"); + assert_eq!(aki(b"/0 0", b"", b"/5 2 /6 << >>"), (125.0, 500.0), "its style's, and the style that is based on"); + assert_eq!(aki(b"/0 0", b"", b"/5 2 /6 << /49 0.0 /50 0 >>"), (0.0, 0.0), "the run's own zero wins"); + assert_eq!(aki(b"/49 10.0 /50 20.0", b"/49 30.0", b"/6 << >>"), (30.0, 20.0), "Normal, then the document's"); + assert_eq!(aki(b"/49 10.0 /50 20.0", b"", b"/6 << >>"), (10.0, 20.0), "the document's"); + assert_eq!(aki(b"/0 0", b"", b"/6 << >>"), (0.0, 0.0), "no key"); + assert_eq!(aki(b"/0 0", b"", b"/6 << /49 1000.5 /50 1e300 >>"), (MAX_AKI, MAX_AKI), "clamped"); + for bad in [&b"-1.0"[..], b"-250", b"(125)", b"true", b"[ 125 ]", b"1e400", b"-1e400"] { + let run = [&b"/5 2 /6 << /49 "[..], bad, b" /50 ", bad, b" >>"].concat(); + assert_eq!(aki(b"/0 0", b"", &run), (0.0, 0.0), "{}", String::from_utf8_lossy(bad)); + } + // In ems of the type's size: the art's scale leaves it as it is. + let s = texts(b"/0 0", b"").style(Some(&read(b"/6 << /49 250.0 /50 125.0 >>").unwrap())); + let c = char_style(&s, 10.0, Affine::IDENTITY); + assert_eq!((c.aki_left, c.aki_right), (250.0, 125.0)); + } + /// Keys 61, 62 and 64 of a character style are its stroke's cap (0 butt, 1 round, 2 /// projecting), join (0 miter, 1 round, 2 bevel) and miter limit, from the run, its character /// style or the document's defaults. A value that isn't one of theirs keeps the default, a miter @@ -2397,6 +2456,8 @@ mod tests { caps: 0, tate_chu_yoko: false, standard_vertical_roman: false, + aki_left: 0.0, + aki_right: 0.0, }, )], kerns: vec![], diff --git a/crates/eps/src/import/cid.rs b/crates/eps/src/import/cid.rs index 4c00486de9..18498352f7 100644 --- a/crates/eps/src/import/cid.rs +++ b/crates/eps/src/import/cid.rs @@ -70,6 +70,8 @@ pub(super) struct CidChar { /// The base-font code or glyph name a `bfchar` or `bfrange` mapping gives it, instead of a /// CID. pub base: Option, + /// The value of its code (`<8001>` is 32769). + pub value: u32, } impl CMap { @@ -146,12 +148,12 @@ impl CMap { work += at.map_or(self.bases.len(), |k| k + 1) as u64; let base = at.and_then(|k| self.bases.get(k)).and_then(|m| Some((m.4, base_of(&m.3, c - m.1)?))); out.push(match (matched.is_some(), find(&self.cids, &mut work), base) { - (true, Some((font, cid, _)), _) => CidChar { font, cid, notdef, base: None }, - (true, None, Some((font, base))) => CidChar { font, cid: 0, notdef: None, base: Some(base) }, + (true, Some((font, cid, _)), _) => CidChar { font, cid, notdef, base: None, value: c }, + (true, None, Some((font, base))) => CidChar { font, cid: 0, notdef: None, base: Some(base), value: c }, // No character mapping: the notdef mapping's CID, else font 0's CID 0. _ => match find(&self.notdefs, &mut work) { - Some((font, _, base)) if matched.is_some() => CidChar { font, cid: base, notdef: None, base: None }, - _ => CidChar { font: 0, cid: 0, notdef: None, base: None }, + Some((font, _, base)) if matched.is_some() => CidChar { font, cid: base, notdef: None, base: None, value: c }, + _ => CidChar { font: 0, cid: 0, notdef: None, base: None, value: c }, }, }); i += n; diff --git a/crates/eps/src/import/interp.rs b/crates/eps/src/import/interp.rs index 0ea7017c11..43346988ff 100644 --- a/crates/eps/src/import/interp.rs +++ b/crates/eps/src/import/interp.rs @@ -98,7 +98,7 @@ pub(crate) struct Interp<'a> { /// The font a `kshow` procedure sees as current while type in a CIDFont only named is set in /// a font of its own (see `text`). pub kshow_font: Option, - /// The `cshow` procedure running over type in a CIDFont only named, with the font it sees as + /// The `cshow` procedure running over a composite font's type, with the font it sees as /// current (see `text`). pub cshow: Option, pub g: GState, diff --git a/crates/eps/src/import/native.rs b/crates/eps/src/import/native.rs index eb5e815e80..5acaba34a4 100644 --- a/crates/eps/src/import/native.rs +++ b/crates/eps/src/import/native.rs @@ -47,9 +47,9 @@ mod layers; mod plan; mod slots; -pub(crate) use build::scale_document; #[cfg(test)] use build::{Frame, MADE, prune_unseen}; +pub(crate) use build::{scale_document, scale_symbols}; #[cfg(test)] use compare::{ MAX_DIFFERENCE, MAX_SOLID_DIFFERENCE, PageView, Shares, compare, compared, comparison_render, comparison_samples, differ, differ_in_colour, diff --git a/crates/eps/src/import/native/build.rs b/crates/eps/src/import/native/build.rs index 1b212194a1..c469f02cd4 100644 --- a/crates/eps/src/import/native/build.rs +++ b/crates/eps/src/import/native/build.rs @@ -10,7 +10,7 @@ use super::slots::{ use super::{ Affine, Arc, BTreeSet, Document, Node, NodeId, NodeKind, PathData, Rect, Scaling, Story, Structure, Texts, Unit, VariableKind, Vec2, ai, }; -use vectorcraft_doc::PlacedDocument; +use vectorcraft_doc::{PlacedDocument, Symbol}; /// Which box of the editing copy is the page. #[derive(Clone, Copy)] @@ -83,12 +83,11 @@ pub(super) fn build_on_page(data: &[u8], page: (f64, f64), unit: f64, names: ai: }; let in_units = |r: Option, k: f64| k.is_finite() && k > 1.0 && fits(r, k) && !fits(r, 1.0); let scale = [unit, structure.canvas_scale].into_iter().find(|&k| in_units(board, k) || (!fits(board, 1.0) && in_units(art, k))); - let styles = structure.styles_read; + let (styles, own_size) = (structure.styles_read, structure.symbols_own_size); let (mut doc, notes) = build_from(structure, data, None, Page::Artboard, false, false, 1.0)?; if let Some(k) = scale { // The graphic styles read from the file are drawn in its units too. - scale_document(&mut doc, k, styles); - relayout_wrapped(&mut doc); + scale_read_document(&mut doc, k, styles, own_size); } Ok((doc, notes)) } @@ -108,12 +107,11 @@ pub(super) fn build_without_page(structure: Structure, data: &[u8], pages: &[(f6 let Some(scale) = alone_scale(&structure, data, pages, unit) else { return Err(Box::new(structure)); }; - let styles = structure.styles_read; + let (styles, own_size) = (structure.styles_read, structure.symbols_own_size); let built = build_from(structure, data, None, Page::Artboard, false, false, 1.0).map(|(mut doc, notes)| { if scale != 1.0 { // The graphic styles read from the file are drawn in its units too. - scale_document(&mut doc, scale, styles); - relayout_wrapped(&mut doc); + scale_read_document(&mut doc, scale, styles, own_size); } (doc, notes) }); @@ -268,6 +266,7 @@ pub(super) fn build_weighing( styles_read, text_patterns, canvas_scale, + symbols_own_size, xml_ids, bindings, bindings_skipped, @@ -577,8 +576,7 @@ pub(super) fn build_weighing( bind_variables(&mut doc, &bindings, bindings_skipped, &xml_ids, &filled, &mut notes); placed_documents(&mut doc, &placed_pages); if small.is_some() { - scale_document(&mut doc, unit, styles_read); - relayout_wrapped(&mut doc); + scale_read_document(&mut doc, unit, styles_read, symbols_own_size); } Ok((doc, notes)) } @@ -1916,7 +1914,7 @@ fn drop_guides_off_boards(doc: &mut Document) { /// styles. pub(crate) fn scale_document(doc: &mut Document, k: f64, styles: bool) { let a = Affine::scale(k); - let scaling = Scaling { strokes: true, effects: Some(vectorcraft_effects::scale_effect), patterns: true, ..Default::default() }; + let scaling = document_scaling(); for layer in &mut doc.layers { let layer = Arc::make_mut(layer); layer.transform(a, scaling); @@ -1935,6 +1933,101 @@ pub(crate) fn scale_document(doc: &mut Document, k: f64, styles: bool) { } } +/// What [`scale_document`] and [`scale_symbols`] scale with the art: strokes, effects and pattern +/// tiles. +fn document_scaling() -> Scaling { + Scaling { strokes: true, effects: Some(vectorcraft_effects::scale_effect), patterns: true, ..Default::default() } +} + +/// A document read in units of `1/k` points drawn at its size: [`scale_document`], and its wrapped +/// type laid out again. Unless `own_size` (data VectorCraft wrote, whose symbols and opacity masks +/// that don't move with their object are at their own size), also the art of those masks on the +/// layers and its symbols ([`scale_symbols`]). +fn scale_read_document(doc: &mut Document, k: f64, styles: bool, own_size: bool) { + scale_document(doc, k, styles); + if !own_size { + let a = Affine::scale(k); + for layer in &mut doc.layers { + transform_unlinked_masks(Arc::make_mut(layer), a, document_scaling()); + } + scale_symbols(doc, k); + } + relayout_wrapped(doc); +} + +/// Draw the art of `doc`'s symbols `k` times as large ([`scale_symbol_art`]), with every instance +/// on the layers and in a pattern's tile (opacity masks included) placed by its transform times +/// `1/k`, so it draws where and as large as before, with the symbol's strokes and effects `k` +/// times as wide. +pub(crate) fn scale_symbols(doc: &mut Document, k: f64) { + if !(k.is_finite() && k > 0.0) || k == 1.0 || doc.symbols.is_empty() { + return; + } + scale_symbol_art(&mut doc.symbols, k); + let back = Affine::scale(1.0 / k); + for n in doc.layers.iter_mut().chain(doc.patterns.iter_mut().flat_map(|p| p.art.iter_mut())) { + place_instances_by(n, back); + } +} + +/// Draw the art of `symbols` `k` times as large, from each symbol's origin, with its strokes, +/// effects and pattern tiles, as [`scale_document`] draws the layers. An instance in the art keeps +/// its own scale and turn: it is placed by its transform times `1/k`. +pub(crate) fn scale_symbol_art(symbols: &mut [Symbol], k: f64) { + if !(k.is_finite() && k > 0.0) || k == 1.0 { + return; + } + let (a, back) = (Affine::scale(k), Affine::scale(1.0 / k)); + for s in symbols { + let art = Arc::make_mut(&mut s.art); + art.transform(a, document_scaling()); + transform_unlinked_masks(art, a, document_scaling()); + scale_wrap_offsets(art, k); + place_instances_by(&mut s.art, back); + } +} + +/// The art of the opacity masks in `n` that don't move with their object, which +/// [`Node::transform`] leaves where it is, transformed by `a` with `scaling` as `n` was: a change of +/// units moves them too. +fn transform_unlinked_masks(n: &mut Node, a: Affine, scaling: Scaling) { + if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) { + let linked = m.linked; + let art = Arc::make_mut(&mut m.art); + if !linked { + art.transform(a, scaling); + } + transform_unlinked_masks(art, a, scaling); + } + if let Some(children) = n.children_mut() { + for c in children { + transform_unlinked_masks(Arc::make_mut(c), a, scaling); + } + } +} + +/// Every symbol instance in `n` (opacity masks included) placed by its transform times `m`. Only +/// the objects on the way to an instance are copied. +fn place_instances_by(n: &mut Arc, m: Affine) { + let mut holds = false; + vectorcraft_doc::swatches::walk_with_masks(n, &mut |c| holds |= matches!(c.kind, NodeKind::SymbolInstance { .. })); + if !holds { + return; + } + let n = Arc::make_mut(n); + if let NodeKind::SymbolInstance { xf, .. } = &mut n.kind { + *xf *= m; + } + if let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_mut()) { + place_instances_by(&mut mask.art, m); + } + if let Some(children) = n.children_mut() { + for c in children { + place_instances_by(c, m); + } + } +} + /// The text wrap offsets of `n` and what it holds, times `k` (within the -1000 to 1000 points /// they may be). fn scale_wrap_offsets(n: &mut Node, k: f64) { @@ -2256,6 +2349,85 @@ mod candidate_tests { assert_eq!(offsets, [wrap(60.0), wrap(1000.0), wrap(-1000.0)]); } + /// Symbols drawn ten times as large keep every instance where and as large as it was (on a layer, + /// in an opacity mask's art, linked or not, and in a pattern's tile), and an instance in a + /// symbol's art keeps its own scale and turn, moved with the art. + #[test] + fn scaling_the_symbols_keeps_their_instances_in_place() { + let mut doc = Document::new(100.0, 100.0); + let boxed = Node::path(doc.alloc_id(), vectorcraft_geom::shapes::rectangle(Rect::new(-1.0, -0.5, 1.0, 0.5)), Default::default()); + doc.symbols.push(Symbol { name: "Box".into(), art: Arc::new(boxed), dynamic: false }); + let turn = Affine::translate((3.0, 4.0)) * Affine::rotate(0.5) * Affine::scale(2.0); + let nested = Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "Box".into(), xf: turn }); + let mut pair = Node::group(doc.alloc_id(), vec![Arc::new(nested)]); + // An opacity mask that doesn't move with its object, holding an instance too. + let masking = Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "Box".into(), xf: turn }); + let mut unlinked = vectorcraft_doc::OpacityMask::new(masking, true); + unlinked.linked = false; + pair.extras_mut().mask = Some(Box::new(unlinked)); + doc.symbols.push(Symbol { name: "Pair".into(), art: Arc::new(pair), dynamic: false }); + let place = Affine::translate((40.0, 30.0)) * Affine::scale(3.0); + let mut on_layer = Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "Pair".into(), xf: place }); + let in_mask = Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "Box".into(), xf: place }); + on_layer.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(in_mask, true))); + doc.insert(Some(doc.layers[0].id), 0, on_layer).unwrap(); + let tiled = Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "Box".into(), xf: place }); + doc.patterns.push(vectorcraft_doc::PatternDef::new("Tiles", vec![Arc::new(tiled)])); + // Each instance's box on the page, by the art of Box it places (through Pair's instance). + let placed = |d: &Document| { + let xf = |n: &Node| match &n.kind { + NodeKind::SymbolInstance { xf, .. } => *xf, + other => panic!("an instance: {other:?}"), + }; + let art = d.symbols[0].art.geometric_bounds().unwrap(); + let layer = &d.layers[0].children().unwrap()[0]; + let mask = &layer.extras().mask.as_ref().unwrap().art; + let tile = &d.patterns[0].art[0]; + let nested = &d.symbols[1].art.children().unwrap()[0]; + let masking = &d.symbols[1].art.extras().mask.as_ref().unwrap().art; + [xf(layer) * xf(nested), xf(layer) * xf(masking), xf(mask), xf(tile)].map(|m| m.transform_rect_bbox(art)) + }; + let before = placed(&doc); + scale_symbols(&mut doc, 10.0); + let after = placed(&doc); + for (a, b) in after.iter().zip(&before) { + let far = [a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().fold(0.0f64, |m, v| m.max(v.abs())); + assert!(far < 1e-9, "{after:?} {before:?}"); + } + let pair = &doc.symbols[1].art.children().unwrap()[0]; + let NodeKind::SymbolInstance { xf, .. } = &pair.kind else { panic!("an instance") }; + let want = Affine::translate((30.0, 40.0)) * Affine::rotate(0.5) * Affine::scale(2.0); + let far = xf.as_coeffs().iter().zip(want.as_coeffs()).fold(0.0f64, |m, (a, b)| m.max((a - b).abs())); + assert!(far < 1e-9, "{xf:?}"); + let art = doc.symbols[0].art.geometric_bounds().unwrap(); + assert_eq!(art, Rect::new(-10.0, -5.0, 10.0, 5.0)); + } + + /// Layers read in the units of a page scaled up to points take the art of their opacity masks + /// with them, a mask that doesn't move with its object included, except in data VectorCraft + /// wrote, where that mask's art is at its own size. + #[test] + fn scaling_a_read_document_scales_unlinked_opacity_masks() { + for own_size in [false, true] { + let mut doc = Document::new(100.0, 100.0); + let mut boxes = vec![]; + for linked in [true, false] { + let mask = Node::path(doc.alloc_id(), vectorcraft_geom::shapes::rectangle(Rect::new(1.0, 2.0, 3.0, 4.0)), Default::default()); + let mut mask = vectorcraft_doc::OpacityMask::new(mask, true); + mask.linked = linked; + let mut n = Node::path(doc.alloc_id(), vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Default::default()); + n.extras_mut().mask = Some(Box::new(mask)); + boxes.push((linked, doc.insert(Some(doc.layers[0].id), 0, n).unwrap())); + } + scale_read_document(&mut doc, 10.0, false, own_size); + for (linked, id) in boxes { + let mask = doc.node(id).and_then(|n| n.extras().mask.as_ref().and_then(|m| m.art.geometric_bounds())); + let want = if linked || !own_size { Rect::new(10.0, 20.0, 30.0, 40.0) } else { Rect::new(1.0, 2.0, 3.0, 4.0) }; + assert_eq!(mask, Some(want), "linked {linked}, own size {own_size}"); + } + } + } + /// Area type in `doc`'s first layer at `index`, in the frame `r`. fn insert_area(doc: &mut Document, index: usize, r: Rect) -> NodeId { let mut t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::ZERO, "Wrapped", Default::default()); diff --git a/crates/eps/src/import/native/layers.rs b/crates/eps/src/import/native/layers.rs index d1af3301df..afd8f2568c 100644 --- a/crates/eps/src/import/native/layers.rs +++ b/crates/eps/src/import/native/layers.rs @@ -1,4 +1,6 @@ -use super::build::{PAGE_MOVE, Page, alone_scale, build, build_from, build_on_page, build_weighing, 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, scale_symbol_art, +}; use super::slots::LAYERS_UNREAD; use super::{Affine, Arc, Cow, Document, Imported, Node, NodeKind, PathData, Rect, Vec2, ai}; @@ -45,7 +47,7 @@ pub(in super::super) fn layered(ps: &[u8], visible: Imported, trust: bool, illus let own_palette = use_palette(data, &mut v.document, &mut read); use_brushes(data, &mut v.document, have, &mut v.warnings, &mut read); use_styles(data, &mut v.document, true, 1.0, None, &mut read); - use_symbols(data, &mut v.document, own_palette, &mut v.warnings, &mut read); + use_symbols(data, &mut v.document, own_palette, None, &mut v.warnings, &mut read); use_variables(data, &mut v.document, &mut v.warnings, &mut read); add_notes(&mut v.warnings, read.notes()); } @@ -153,7 +155,7 @@ pub fn layered_ai_from( let own_palette = use_palette(&data, &mut visible, &mut read); use_brushes(&data, &mut visible, have, &mut warnings, &mut read); use_styles(&data, &mut visible, false, unit, Some(&boards), &mut read); - use_symbols(&data, &mut visible, own_palette, &mut warnings, &mut read); + use_symbols(&data, &mut visible, own_palette, Some((unit, boards.as_slice())), &mut warnings, &mut read); use_variables(&data, &mut visible, &mut warnings, &mut read); add_notes(&mut warnings, read.notes()); return (visible, warnings, false); @@ -172,7 +174,7 @@ pub fn layered_ai_from( use_brushes(&data, &mut visible, have, &mut warnings, &mut read); use_styles(&data, &mut visible, false, unit, Some(&boards), &mut read); let mut all = unread(warnings, why); - use_symbols(&data, &mut visible, own_palette, &mut all, &mut read); + use_symbols(&data, &mut visible, own_palette, Some((unit, boards.as_slice())), &mut all, &mut read); use_variables(&data, &mut visible, &mut all, &mut read); add_notes(&mut all, read.notes()); (visible, all, false) @@ -377,26 +379,34 @@ fn use_styles(data: &[u8], doc: &mut Document, large_canvas: bool, unit: f64, bo if styles.is_empty() { return; } - if !large_canvas && (unit != 1.0 || canvas != 1.0) { - let read; - let boards = match boards { - Some(b) => b, - None => { - read = ai::artboards(data, &mut ai::Names::default()).0; - &read - } - }; - let k = board_scale(boards, doc, unit).or_else(|| board_scale(boards, doc, canvas)); - if let Some(k) = k.filter(|k| *k != 1.0) { - for g in &mut styles { - g.appearance.scale_strokes(k); - g.appearance.scale_effects(k, vectorcraft_effects::scale_effect); - } + if !large_canvas && let Some(k) = data_scale(data, doc, unit, canvas, boards) { + for g in &mut styles { + g.appearance.scale_strokes(k); + g.appearance.scale_effects(k, vectorcraft_effects::scale_effect); } } doc.graphic_styles = styles.into(); } +/// How many times as large `doc` (a file read as its PDF part) draws the art of its editing data +/// `data`, whose declared large canvas scale is `canvas`, when it isn't 1: `unit` when the editing +/// data's artboards (`boards`, or read from `data`) are the size of `doc`'s pages in units of +/// `unit` points, else `canvas` when they are the pages' size at that scale ([`board_scale`]). +fn data_scale(data: &[u8], doc: &Document, unit: f64, canvas: f64, boards: Option<&[(String, Rect)]>) -> Option { + if unit == 1.0 && canvas == 1.0 { + return None; + } + let read; + let boards = match boards { + Some(b) => b, + None => { + read = ai::artboards(data, &mut ai::Names::default()).0; + &read + } + }; + board_scale(boards, doc, unit).or_else(|| board_scale(boards, doc, canvas)).filter(|k| *k != 1.0) +} + /// `doc` (a file read as its page or PDF part, in place of its layers) with the symbols of its /// editing data `data` ([`ai::symbols`]), their registration points, the images their art shows and /// the global and spot colors it is linked to that `doc` has no such swatch for (a color whose name @@ -405,15 +415,34 @@ fn use_styles(data: &[u8], doc: &mut Document, large_canvas: bool, unit: f64, bo /// of the name, which the art then names, as does one whose name a color group has), as [`build`] gives a document read from the layers, and /// the note about instances that can't be drawn added to `warnings`. An object of their art linked /// to a graphic style keeps the link when [`use_styles`] gave `doc` the editing data's styles. The -/// symbols' art keeps the editing data's units, as in a document read from the layers: when -/// [`use_styles`] draws the styles' strokes and effects larger (a file in larger units), linked art -/// isn't scaled with them. Left as it is when `doc` has symbols already or the editing data has -/// none this reads. `names` reads the symbols' names and keeps the notes on them. -fn use_symbols(data: &[u8], doc: &mut Document, own_palette: bool, warnings: &mut Vec, names: &mut ai::Names) { +/// symbols' art is drawn as large as a document read from the layers draws it +/// ([`scale_symbol_art`]): with `units` `None` (an EPS's page), as many times as large as the data's +/// declared large canvas scale; with `Some((unit, boards))`, as many times as large as +/// [`use_styles`] draws the styles' strokes and effects ([`data_scale`], `boards` the editing data's +/// artboards); at its own size in data VectorCraft wrote. Left as it is when `doc` has symbols +/// already or the editing data has none this reads. `names` reads the symbols' names and keeps the +/// notes on them. +fn use_symbols( + data: &[u8], + doc: &mut Document, + own_palette: bool, + units: Option<(f64, &[(String, Rect)])>, + warnings: &mut Vec, + names: &mut ai::Names, +) { if !doc.symbols.is_empty() { return; } - let Some(ai::Symbols { symbols, images, swatches }) = ai::symbols(data, names) else { return }; + let Some(ai::Symbols { symbols, images, swatches, canvas_scale, own_size }) = ai::symbols(data, names) else { return }; + let (mut symbols, registrations): (Vec<_>, Vec<_>) = symbols.into_iter().unzip(); + let k = match units { + _ if own_size => None, + None => Some(canvas_scale), + Some((unit, boards)) => data_scale(data, doc, unit, canvas_scale, Some(boards)), + }; + if let Some(k) = k { + scale_symbol_art(&mut symbols, k); + } for (key, blob) in images { doc.images.entry(key).or_insert(blob); } @@ -444,7 +473,7 @@ fn use_symbols(data: &[u8], doc: &mut Document, own_palette: bool, warnings: &mu *link = Some(new.clone()); true }; - for (mut symbol, registration) in symbols { + for (mut symbol, registration) in symbols.into_iter().zip(registrations) { let mut art = reid_page_art(doc, &symbol.art); if !renamed.is_empty() { vectorcraft_doc::swatches::map_node_solid_paints(&mut art, &mut follow); diff --git a/crates/eps/src/import/predefined_cmap.rs b/crates/eps/src/import/predefined_cmap.rs index c688ebf9ae..46890af653 100644 --- a/crates/eps/src/import/predefined_cmap.rs +++ b/crates/eps/src/import/predefined_cmap.rs @@ -279,6 +279,7 @@ fn code_space(cmap: &str) -> Option { const CNS_EUC: CodeSpace = &[(b"\x00", b"\x80"), (b"\xa1\xa1", b"\xfe\xfe"), (b"\x8e\xa1\xa1\xa1", b"\x8e\xa3\xfe\xfe")]; const KSC_PC: CodeSpace = &[(b"\x00", b"\x84"), (b"\xfe", b"\xff"), (b"\xa1\x41", b"\xfd\xfe")]; const UHC: CodeSpace = &[(b"\x00", b"\x80"), (b"\x81\x41", b"\xfe\xfe")]; + const JOHAB: CodeSpace = &[(b"\x00", b"\x80"), (b"\x84\x41", b"\xd3\xfe"), (b"\xd8\x31", b"\xde\xfe"), (b"\xe0\x31", b"\xf9\xfe")]; let stem = match cmap { "H" | "V" => "", _ => cmap.strip_suffix("-H").or_else(|| cmap.strip_suffix("-V"))?, @@ -301,6 +302,7 @@ fn code_space(cmap: &str) -> Option { "CNS-EUC" => CNS_EUC, "KSCpc-EUC" => KSC_PC, "KSCms-UHC" => UHC, + "KSC-Johab" => JOHAB, _ => return None, }) } diff --git a/crates/eps/src/import/tests_cid.rs b/crates/eps/src/import/tests_cid.rs index 8350cd514b..b44a5410ee 100644 --- a/crates/eps/src/import/tests_cid.rs +++ b/crates/eps/src/import/tests_cid.rs @@ -136,6 +136,41 @@ fn codes_map_by_their_codespace_with_notdef_fallbacks() { width("<01>", 30.0); } +/// `cshow` over a CMap runs its procedure once for each code, whatever its length, with the +/// code's last byte and its width (PLRM 3rd ed., `cshow`). +#[test] +fn cshow_runs_once_for_each_cmap_code() { + let fonts = String::from_utf8(cid_font(true)).unwrap() + CMAP; + let check = |cond: &str| check(&format!("{fonts} /TestFont 50 selectfont {cond}")); + check("[ {pop pop} <418001> cshow ] dup length 2 eq exch aload pop 1 eq exch 65 eq and and"); + check("0 {pop exch pop add} <418001> cshow 55 sub abs 0.01 lt"); + check( + "{pop pop pop currentfont /CIDFontName get /seen exch def rootfont /FontName get /root exch def} <41> cshow seen /TestCID eq root /TestFont eq and", + ); + // With the CIDFont current, the byte the procedure was given shows the glyph of its code's + // CID: <8001>'s last byte draws CID 2, not code 01's CID 1. Another string is an error. + let shown = "{pop pop ( ) dup 0 4 -1 roll put show} <418001> cshow"; + check(&format!("gsave nulldevice 10 20 moveto {shown} currentpoint grestore pop 65 sub abs 0.01 lt")); + check("gsave nulldevice 10 20 moveto {{pop pop pop (B) show} <41> cshow} stopped grestore"); + let r = import(&program(true, &format!("/TestFont 50 selectfont 10 20 moveto {shown}"))).unwrap(); + let want = import(&program(true, "/TestFont 50 selectfont 10 20 moveto <418001> show")).unwrap(); + let (p, q) = (paths(&r), paths(&want)); + assert_eq!(p.len(), 2, "{p:?}"); + for (a, b) in p.iter().zip(&q) { + assert!((a.x0 - b.x0).abs() < 0.01 && (a.width() - b.width()).abs() < 0.01 && (a.height() - b.height()).abs() < 0.01, "{p:?} {q:?}"); + } +} + +/// `kshow` over a CMap runs its procedure between each two codes with their values, whatever +/// their length, and the next character follows where it moves the point (PLRM 3rd ed., `kshow`). +#[test] +fn kshow_runs_between_each_two_cmap_codes() { + let fonts = String::from_utf8(cid_font(true)).unwrap() + CMAP; + let check = |cond: &str| check(&format!("{fonts} /TestFont 50 selectfont {cond}")); + check("gsave nulldevice 10 20 moveto [ {} <418001> kshow ] grestore aload length 2 eq exch 16#8001 eq and exch 65 eq and"); + check("gsave nulldevice 10 20 moveto {pop pop 100 0 rmoveto} <418001> kshow currentpoint grestore pop 165 sub abs 0.01 lt"); +} + /// `usecmap` brings in another CMap's ranges and mappings; the CMap's own come after them. #[test] fn usecmap_takes_the_parents_mappings() { @@ -178,6 +213,22 @@ fn type2_cidfonts_draw_their_truetype_glyphs_through_cidmap() { } } +/// A `cshow` procedure over a Type 2 CIDFont without a `FontMatrix` sees the CIDFont current at +/// the scale its glyphs are drawn at: an em of the composite font's size, as with the identity. +#[test] +fn cshow_over_a_type2_cidfont_without_a_matrix_sees_it_at_its_drawn_scale() { + let (h, i) = (glyph('H').0, glyph('I').0); + let with = cid2_font(&format!("<0000{h:04x}{i:04x}>")); + let without = with.replace("/FontMatrix [1 0 0 1 0 0] def", ""); + assert_ne!(with, without); + for fonts in [with, without] { + check(&format!( + "{fonts}/T2 /Identity-H [/TestCID2] composefont 50 scalefont setfont \ + {{pop pop pop currentfont /FontMatrix get 0 get /m exch def}} <0001> cshow m 50 sub abs 0.01 lt" + )); + } +} + /// `Identity-V`: each glyph an em below the one before (writing mode 1). #[test] fn identity_v_sets_glyphs_downwards() { @@ -375,6 +426,30 @@ fn cmaps_map_codes_to_base_fonts_codes_and_glyph_names() { }) .collect(); assert_eq!(text, "ABC"); + // A `cshow` procedure that shows the byte it was given, in the base font current while it + // runs, shows the character the code maps to, as `show` does. + let body = format!( + "{plain}{BF_CMAP}/BF /TestBF-H [/Plain42 /Helvetica] composefont 20 scalefont setfont 10 20 moveto \ + {{pop pop ( ) dup 0 4 -1 roll put show}} <001000110012> cshow" + ); + let r = super::tests::read(&body); + let text: String = all(&r.document) + .iter() + .filter_map(|n| match &n.kind { + NodeKind::Text(t) => Some(t.plain_text()), + _ => None, + }) + .collect(); + assert_eq!(text, "ABC"); + let body = format!( + "{plain}{BF_CMAP}/BF /TestBF-H [/Plain42 /Helvetica] composefont 50 scalefont setfont 10 20 moveto \ + {{pop pop ( ) dup 0 4 -1 roll put show}} <000100020003> cshow" + ); + let q = paths(&super::tests::read(&body)); + assert_eq!(q.len(), 3, "{q:?}"); + for (a, b) in p.iter().zip(&q) { + assert!((a.x0 - b.x0).abs() < 0.01 && (a.width() - b.width()).abs() < 0.01, "{p:?} {q:?}"); + } } /// A CID-keyed font over a predefined Unicode CMap the file doesn't define, its CIDFont only @@ -638,10 +713,11 @@ fn named_cid_type_in_charpath_cshow_and_glyphshow() { } /// A font name ending in the row-and-cell CMap `H` or `V` stays a font of the whole name, its -/// strings read byte by byte, unless the part before the CMap names a CIDFont the file defines (or -/// an installed face that covers Japanese). Type in a predefined CMap whose mappings aren't -/// available is left out with a warning, each code moving the point one em, and a long string in a -/// CID-keyed font over a predefined CMap shown in a loop runs out of the budget. +/// strings read byte by byte, unless the part before the CMap names a CIDFont the file defines, a +/// Japanese CIDFont a printer carries (or an installed face that covers Japanese). Type in a +/// predefined CMap whose mappings aren't available is left out with a warning, each code moving +/// the point one em, and a long string in a CID-keyed font over a predefined CMap shown in a loop +/// runs out of the budget. #[test] fn latin_names_ending_in_h_and_cmaps_that_cannot_be_read() { for (font, family, style) in [("Futura-H", "Futura", "H"), ("Foo-Bold-H", "Foo", "Bold-H"), ("Foo-Condensed-V", "Foo", "Condensed-V")] { @@ -665,6 +741,18 @@ fn latin_names_ending_in_h_and_cmaps_that_cannot_be_read() { let r = super::tests::read(&format!("{define} findfont 20 scalefont setfont 10 20 moveto <467c> show")); assert_eq!(texts(&r).iter().map(|t| t.plain_text()).collect::>(), ["日"], "{define}: {:?}", r.warnings); } + // The Japanese CIDFonts a printer carries (Adobe Technical Note #5014, appendix A.2) split at + // `H` or `V` without the file defining them or a face of their name being installed. A face + // with the whole name, when installed, is that face's. + for (font, vertical) in [("Ryumin-Light-H", false), ("GothicBBB-Medium-V", true)] { + if vectorcraft_text::FontDb::global().find_postscript(font).is_some() { + continue; + } + let r = super::tests::read(&format!("/{font} findfont 20 scalefont setfont 10 20 moveto <467c> show")); + let t = texts(&r); + assert_eq!(t.iter().map(|t| t.plain_text()).collect::>(), ["日"], "{font}: {:?}", r.warnings); + assert_eq!(t[0].vertical, vertical, "{font}"); + } let r = super::tests::read("/Ryumin-Light-GBT-H findfont 20 scalefont setfont 10 20 moveto (AB) show 0 0 10 10 rectfill"); assert!(texts(&r).is_empty(), "{:?}", all(&r.document)); assert_eq!(super::tests::program_warnings(&r.warnings), [super::text::UNREAD_CMAP], "{:?}", r.warnings); @@ -677,6 +765,10 @@ fn latin_names_ending_in_h_and_cmaps_that_cannot_be_read() { "/Ryumin-Light-GBT-H findfont 20 scalefont setfont <09092121> stringwidth abs 0.01 lt exch 60 sub abs 0.01 lt and", // A byte that starts no row-and-cell code is a code of its own, also before a tab: three. "/Ryumin-Light-GBT-H findfont 20 scalefont setfont <21092121> stringwidth abs 0.01 lt exch 60 sub abs 0.01 lt and", + // In the Johab code space each ASCII byte is a one-byte code and a Hangul code takes two + // bytes: three codes, across and down. + "/Ryumin-Light-KSC-Johab-H findfont 20 scalefont setfont <41428441> stringwidth abs 0.01 lt exch 60 sub abs 0.01 lt and", + "/Ryumin-Light-KSC-Johab-V findfont 20 scalefont setfont 10 100 moveto <41428441> show currentpoint 40 sub abs 0.01 lt exch 10 sub abs 0.01 lt and", ] { let r = super::tests::read(&format!("{cond} {{ 0 0 10 10 rectfill }} if")); assert!(all(&r.document).iter().any(|n| matches!(n.kind, NodeKind::Path { .. })), "{cond}"); diff --git a/crates/eps/src/import/tests_composite.rs b/crates/eps/src/import/tests_composite.rs index e682ce10ec..ff3b3382d3 100644 --- a/crates/eps/src/import/tests_composite.rs +++ b/crates/eps/src/import/tests_composite.rs @@ -119,6 +119,74 @@ fn widthshow_matches_a_composite_character_by_font_number_and_code() { check(format!("{} {} sub abs 0.01 lt", end(2), 10.0 + 100.0 * wh)); } +/// `cshow` runs its procedure once for each character of a composite font, not for each byte, +/// with the last byte of its code and its width, and with the descendant that draws it as the +/// current font while `rootfont` gives the composite font (PLRM 3rd ed., `cshow` and `rootfont`). +#[test] +fn cshow_runs_once_for_each_composite_character_in_its_descendant() { + let (_, wh) = glyph('H'); + let (_, wi) = glyph('I'); + let check = |cond: String| super::tests::check(&format!("{} /Comp findfont 50 scalefont setfont {cond}", fonts())); + check("[ {pop pop} (\\000\\001\\000\\002) cshow ] dup length 2 eq exch aload pop 2 eq exch 1 eq and and".into()); + check(format!("0 {{pop exch pop add}} (\\000\\001\\000\\002) cshow {} sub abs 0.01 lt", 50.0 * (wh + wi))); + check("{pop pop pop currentfont /FontName get /seen exch def rootfont /FontName get /root exch def} (\\000\\001) cshow seen /T42 eq root /Comp eq and".into()); + check("{pop pop pop} (\\000\\001) cshow currentfont /FontName get /Comp eq".into()); + // A character the procedure shows in the descendant is as wide as the composite font sets it. + check(format!( + "gsave nulldevice 10 20 moveto {{pop pop ( ) dup 0 4 -1 roll put show}} (\\000\\001\\000\\002) cshow currentpoint grestore pop {} sub abs 0.01 lt", + 10.0 + 50.0 * (wh + wi) + )); + // A character in font number 1 still gives only the last byte of its code, not 258. + let two = fonts().replace("/Encoding [0] def", "/Encoding [0 0] def"); + super::tests::check(&format!("{two} /Comp findfont 50 scalefont setfont [ {{pop pop}} (\\001\\002) cshow ] dup length 1 eq exch 0 get 2 eq and")); +} + +/// A `cshow` procedure over a Type 42 descendant without a `FontMatrix` sees it current at the +/// scale its characters are drawn at: another character it measures there is as wide as the +/// composite font sets it, as with the identity. +#[test] +fn cshow_over_a_type42_descendant_without_a_matrix_sees_it_at_its_drawn_scale() { + let (_, wi) = glyph('I'); + let with = fonts(); + let without = with.replacen("/FontType 42 def /FontMatrix [1 0 0 1 0 0] def", "/FontType 42 def", 1); + assert_ne!(with, without); + for fonts in [with, without] { + super::tests::check(&format!( + "{fonts} /Comp findfont 50 scalefont setfont {{pop pop pop (\\002) stringwidth pop /w exch def}} (\\000\\001) cshow w {} sub abs 0.01 lt", + 50.0 * wi + )); + } +} + +/// `kshow` runs its procedure between each two characters of a composite font, with the values of +/// their codes (font number times 256 plus code), and the next character follows where it moves +/// the current point (PLRM 3rd ed., `kshow`). +#[test] +fn kshow_runs_between_each_two_composite_characters() { + let (_, wh) = glyph('H'); + let (_, wi) = glyph('I'); + let fonts = fonts().replace("/Encoding [0] def", "/Encoding [0 0] def"); + let check = |cond: String| super::tests::check(&format!("{fonts} /Comp findfont 50 scalefont setfont {cond}")); + check("gsave nulldevice 10 20 moveto [ {} (\\000\\001\\001\\002\\000\\001) kshow ] grestore aload length 4 eq exch 1 eq and exch 258 eq and exch 258 eq and exch 1 eq and".into()); + check(format!( + "gsave nulldevice 10 20 moveto {{pop pop 100 0 rmoveto}} (\\000\\001\\000\\002) kshow currentpoint grestore pop {} sub abs 0.01 lt", + 10.0 + 50.0 * (wh + wi) + 100.0 + )); + // Drawn, the I starts where the procedure moved the point. + let r = read(&format!("{fonts}/Comp findfont 50 scalefont setfont 10 20 moveto {{pop pop 100 0 rmoveto}} (\\000\\001\\000\\002) kshow")); + let paths: Vec<_> = all(&r.document).iter().filter(|n| matches!(n.kind, NodeKind::Path { .. })).map(|n| bounds(n)).collect(); + assert_eq!(paths.len(), 2, "{paths:?}"); + assert!(paths[1].x0 > 10.0 + 50.0 * wh + 100.0 - 1.0, "{paths:?}"); + // A procedure that draws: its square goes after the glyphs' group, outside it. + let r = read(&format!( + "{fonts}/Comp findfont 50 scalefont setfont 10 20 moveto {{pop pop currentpoint 2 2 rectfill}} (\\000\\001\\000\\002\\000\\001) kshow" + )); + let top = super::tests::objects(&r.document); + assert_eq!(top.len(), 3, "{top:?}"); + assert_eq!(top[0].children().map(Vec::len), Some(3)); + assert!(top[1..].iter().all(|n| matches!(n.kind, NodeKind::Path { .. }) && (bounds(n).width() - 2.0).abs() < 0.01), "{top:?}"); +} + /// Measuring a composite font's Type 42 glyphs (`stringwidth` on a long string in a `loop`) /// counts against the operation budget, as drawing them does. #[test] diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index 1f634b3744..738f02d857 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -1809,6 +1809,44 @@ fn an_eps_without_layers_keeps_its_symbols() { assert_eq!(symbol_names(&r.document), ["Bar", "Masked", "Dot"], "{:?}", r.warnings); } +/// The box of the art of `d`'s first symbol (Bar, 12 × 2 about the origin in the editing data). +fn bar_bounds(d: &Document) -> Option { + d.symbols.first().and_then(|s| s.art.geometric_bounds()) +} + +/// A symbol library without layers whose editing data is drawn larger than its units comes in with +/// its symbols' art as large as a document read from its layers has it: an EPS of a Large Canvas +/// copy at its declared scale, and a `.ai` whose artboard is its PDF part's page at that scale or +/// in the units of its `UserUnit`. One whose artboard is the page in points keeps its art's size. +#[test] +fn a_symbol_library_in_larger_units_comes_in_at_the_pages_size() { + let board = "%_/Document :\n%_/Dictionary :\n%_/Array :\n\ + %_/Dictionary :\n%_0 100 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_100 0 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n\ + %_; (ArtboardArray) ,\n%_; /NotRecorded ,\n%_;\n"; + let library = |setup: &str| symbol_library().replace("%%BeginSetup\n", &format!("%%BeginSetup\n{setup}")); + let ten = Some(vectorcraft_geom::Rect::new(-60.0, -10.0, 60.0, 10.0)); + let r = import(&eps(&page_square(50, 50), &library("%AI24_LargeCanvasScale: 10\n"))).unwrap(); + assert_eq!(bar_bounds(&r.document), ten, "{:?}", r.warnings); + let large = format!("%AI24_LargeCanvasScale: 10\n{board}"); + let (d, warnings, read) = crate::layered_ai(&private(&library(&large)), in_points(pdf_part(10.0, 86.0), 10.0), vec![], false, true, 1.0); + assert!(!read, "{warnings:?}"); + assert_eq!(bar_bounds(&d), ten, "{warnings:?}"); + let (d, warnings, _) = crate::layered_ai(&private(&library(board)), in_points(pdf_part(10.0, 86.0), 10.0), vec![], false, true, 10.0); + assert_eq!(bar_bounds(&d), ten, "{warnings:?}"); + let points = board.replace("0 100 /Real", "0 1000 /Real").replace("100 0 /Real", "1000 0 /Real"); + let (d, warnings, _) = crate::layered_ai(&private(&library(&points)), in_points(pdf_part(10.0, 86.0), 10.0), vec![], false, true, 10.0); + assert_eq!(bar_bounds(&d), Some(vectorcraft_geom::Rect::new(-6.0, -1.0, 6.0, 1.0)), "{warnings:?}"); + // A library VectorCraft wrote (its `%%Creator`) has its symbols at their own size, whatever its + // scale. + let own = + |setup: &str| library(setup).replacen("%!PS-Adobe-3.0 \n", &format!("%!PS-Adobe-3.0 \n%%Creator: {}\n", crate::ai_editing::CREATOR_TEXT), 1); + let own_size = Some(vectorcraft_geom::Rect::new(-6.0, -1.0, 6.0, 1.0)); + let r = import(&eps(&page_square(50, 50), &own("%AI24_LargeCanvasScale: 10\n"))).unwrap(); + assert_eq!(bar_bounds(&r.document), own_size, "{:?}", r.warnings); + let (d, warnings, _) = crate::layered_ai(&private(&own(&large)), in_points(pdf_part(10.0, 86.0), 10.0), vec![], false, true, 1.0); + assert_eq!(bar_bounds(&d), own_size, "{warnings:?}"); +} + /// A `.ai` that comes in as its PDF part, and an EPS that comes in as its page, because their /// layers can't be used (their editing data is for another page) get the symbols defined before /// their layers. @@ -2769,6 +2807,94 @@ fn a_large_canvas_eps_keeps_its_graphic_styles_at_the_pages_size() { assert_eq!((object.appearance.stroke_width(), object.extras().graphic_style), (2.0, Some(1)), "{object:#?}"); } +/// The definition of the symbol Box: a rectangle 2 × 1 about the origin, stroked 0.4 wide. +fn stroked_box_symbol() -> String { + let art = "0 0 0 1 K\n0.4 w\n-1 -0.5 m\n-1 0.5 L\n1 0.5 L\n1 -0.5 L\n-1 -0.5 L\nS\n"; + format!("%AI5_Begin_NonPrinting\n{}%AI5_End_NonPrinting--\n", symbol_def("Box", art, 5)) +} + +/// The art of `d`'s symbol Box ([`stroked_box_symbol`]) is ten times as large, its stroke 4 wide, +/// and its instance on `d`'s second layer, placed in the file at twice its size about (`x`, `y`), +/// keeps that scale and draws a box of 40 × 20 about `center`. +fn box_symbol_at_ten_times(d: &Document, center: (f64, f64), notes: &[String]) { + let art = &d.symbols.iter().find(|s| s.name == "Box").unwrap_or_else(|| panic!("{notes:?}")).art; + let b = art.geometric_bounds().unwrap(); + let close = |r: vectorcraft_geom::Rect, e: [f64; 4]| [r.x0, r.y0, r.x1, r.y1].iter().zip(e).all(|(a, b)| (a - b).abs() < 1e-6); + assert!(close(b, [-10.0, -5.0, 10.0, 5.0]), "the art at the page's size: {b:?} {notes:?}"); + let mut widths = vec![]; + art.walk(&mut |n| { + if matches!(n.kind, NodeKind::Path { .. }) { + widths.push(n.appearance.stroke_width()); + } + }); + assert_eq!(widths, [4.0], "{notes:?}"); + let instance = d.layers[1].children().unwrap().first().unwrap_or_else(|| panic!("{:#?} {notes:?}", d.layers)); + let NodeKind::SymbolInstance { xf, .. } = &instance.kind else { panic!("an instance: {:?}", instance.kind) }; + let [a, b0, c, d0, ..] = xf.as_coeffs(); + assert!((a.hypot(b0) - 2.0).abs() < 1e-9 && (c.hypot(d0) - 2.0).abs() < 1e-9, "the instance's own scale: {xf:?}"); + let (x, y) = center; + assert!(close(xf.transform_rect_bbox(b), [x - 20.0, y - 10.0, x + 20.0, y + 10.0]), "{:?}", xf.transform_rect_bbox(b)); +} + +/// The symbols of a Large Canvas editing copy come in at the page's size, as its art does: their +/// art and its strokes ten times as large, and each instance with the scale the file gives it, +/// drawn where and as large as before. +#[test] +fn a_large_canvas_eps_keeps_its_symbols_at_the_pages_size() { + let instance = "/SymbolInstance :\n(Box) /SymbolRef ,\n2 0 0 -2 5 5 /RTransformMatrix\n;\n9 () XW"; + let square = "0 0 1 0 k\n5 5 m\n5.4 5 L\n5.4 5.4 L\n5 5.4 L\nf"; + let art = native_large_canvas(10.0, 10.0, &format!("{}{}{}", stroked_box_symbol(), layer("Art", true, square), layer("Box", false, instance))); + let r = import(&eps(&page_square(50, 50), &art)).unwrap(); + assert_eq!(names(&r.document), ["Art", "Box"], "{:?}", r.warnings); + box_symbol_at_ten_times(&r.document, (50.0, 50.0), &r.warnings); +} + +/// A large canvas `.ai` 100 units square at a scale of 10, with the symbol Box +/// ([`stroked_box_symbol`]) and an instance of it at twice its size about (50, 50), its header +/// carrying `creator` when given, read with its PDF part, on a page whose PDF part can't be read, +/// and without a page. +fn large_canvas_ai_box_reads(creator: Option<&str>) -> Vec<(&'static str, Document, Vec)> { + let instance = "/SymbolInstance :\n(Box) /SymbolRef ,\n2 0 0 -2 50 50 /RTransformMatrix\n;\n9 () XW"; + let layers = format!("{}{}{}", stroked_box_symbol(), layer("Art", true, &square(10, 10)), layer("Box", false, instance)); + let mut art = native_large_canvas(100.0, 10.0, &layers); + if let Some(creator) = creator { + art = art.replacen("%!PS-Adobe-3.0 \n", &format!("%!PS-Adobe-3.0 \n%%Creator: {creator}\n"), 1); + } + let data = private(&art); + let (d, notes, read) = crate::layered_ai(&data, in_points(pdf_part(10.0, 86.0), 10.0), vec![], false, false, 1.0); + assert!(read, "{notes:?}"); + let on_page = crate::ai_alone_on_page(&data, (1000.0, 1000.0), 10.0, Default::default()).unwrap(); + let no_page = crate::ai_alone(&data).unwrap(); + vec![("PDF part", d, notes), ("on a page", on_page.0, on_page.1), ("no page", no_page.0, no_page.1)] +} + +/// A `.ai` whose editing data is read at its declared large canvas scale has its symbols scaled +/// with the art, as an EPS has, however the file opens. +#[test] +fn a_large_canvas_ai_keeps_its_symbols_at_the_pages_size() { + for (how, d, notes) in large_canvas_ai_box_reads(None) { + let notes: Vec = notes.into_iter().chain([how.to_string()]).collect(); + box_symbol_at_ten_times(&d, (500.0, 500.0), ¬es); + } +} + +/// A large canvas `.ai` that VectorCraft wrote (its `%%Creator`) has its symbols defined at their +/// own size, as its `.ai` save writes them: their art keeps that size, and the instance, scaled with +/// the layers, draws the same box, however the file opens. +#[test] +fn a_large_canvas_ai_vectorcraft_wrote_keeps_its_symbols_at_their_own_size() { + for (how, d, notes) in large_canvas_ai_box_reads(Some(crate::ai_editing::CREATOR_TEXT)) { + let art = &d.symbols.iter().find(|s| s.name == "Box").unwrap_or_else(|| panic!("{how}: {notes:?}")).art; + let b = art.geometric_bounds().unwrap(); + assert_eq!(b, vectorcraft_geom::Rect::new(-1.0, -0.5, 1.0, 0.5), "{how}: {notes:?}"); + let instance = d.layers[1].children().unwrap().first().unwrap_or_else(|| panic!("{how}: {:#?} {notes:?}", d.layers)); + let NodeKind::SymbolInstance { xf, .. } = &instance.kind else { panic!("{how}: an instance: {:?}", instance.kind) }; + let drawn = xf.transform_rect_bbox(b); + let close = [drawn.x0 - 480.0, drawn.y0 - 490.0, drawn.x1 - 520.0, drawn.y1 - 510.0].iter().all(|v| v.abs() < 1e-6); + assert!(close, "{how}: {drawn:?}"); + } +} + #[test] fn type_with_a_listed_art_style_is_linked_to_its_graphic_style() { let doc = text_document(&[("Bang\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]); diff --git a/crates/eps/src/import/text.rs b/crates/eps/src/import/text.rs index 515e0b12ec..3de16d7bbf 100644 --- a/crates/eps/src/import/text.rs +++ b/crates/eps/src/import/text.rs @@ -251,6 +251,15 @@ impl Interp<'_> { self.g.font = root; return r; } + // In a composite font the file carries, once for each character it maps. + if let Some(glyphs) = self.composite_glyphs(&s)? { + let root = self.g.font.clone(); + let before = self.cshow.take(); + let r = self.composite_cshow(&glyphs, &proc, root.clone()); + self.cshow = before; + self.g.font = root; + return r; + } for b in s { let v = self.width_of(&[b])?; self.push(Obj::Int(i64::from(b)))?; @@ -509,9 +518,11 @@ impl Interp<'_> { /// Font name `name` as a CIDFont's name and the name of a predefined CMap other than a Unicode /// CMap ([`super::predefined_cmap::composite_font`]), unless an installed face has the whole /// name. A name that ends in the row-and-cell CMap `H` or `V` splits only when the part before - /// it names a CIDFont the file defines, or has a hyphen and names an installed face that covers - /// Japanese; otherwise it stays a font of the whole name (`Futura-H`, `Foo-Bold-H`), its - /// strings read byte by byte. + /// it names a CIDFont the file defines, one of the Japanese CIDFonts a printer carries + /// (`Ryumin-Light`, `GothicBBB-Medium`: Adobe Technical Note #5014, appendix A.2, + /// ), or has a + /// hyphen and names an installed face that covers Japanese; otherwise it stays a font of the + /// whole name (`Futura-H`, `Foo-Bold-H`), its strings read byte by byte. fn predefined_split<'a>(&mut self, name: &'a str) -> Option<(&'a str, &'a str)> { let (cid_font, cmap) = super::predefined_cmap::composite_font(name)?; let db = vectorcraft_text::FontDb::global(); @@ -525,7 +536,8 @@ impl Interp<'_> { let defined = self.instances(&Obj::name("CIDFont")).is_ok_and(|d| d.borrow().contains_key(&key)) || cid_font_in(&self.fonts); // 日 is in the row-and-cell CMaps' character set (JIS X 0208). let installed = || db.find_postscript(cid_font).is_some_and(|face| face.covers('日')); - if !(defined || (cid_font.contains('-') && installed())) { + let printer = matches!(cid_font, "Ryumin-Light" | "GothicBBB-Medium"); + if !(defined || printer || (cid_font.contains('-') && installed())) { return None; } } @@ -989,6 +1001,7 @@ impl Spacing { /// A character of a composite font: the descendant font that draws it, its code there (its last /// byte for a CID), its CID and the notdef mapping's (`FMapType` 9), the composite font's matrix /// (over the descendant's own) and whether it is set vertically (`WMode` 1). +#[derive(Clone)] struct Mapped { font: DictRef, /// The byte that picked the descendant (the font number). @@ -999,6 +1012,15 @@ struct Mapped { cid: Option<(u32, Option)>, outer: Affine, vertical: bool, + /// The value of the character's code in the shown string (what `kshow` gives its procedure). + value: u32, +} + +impl Mapped { + /// The last byte of the character's code in the shown string (what `cshow` gives its procedure). + fn last(&self) -> u8 { + (self.value & 0xff) as u8 + } } /// Type in a CIDFont only named, over a predefined CMap ([`Interp::named_cid_type`]): its codes @@ -1011,13 +1033,15 @@ struct NamedCid { ems: bool, } -/// A `cshow` procedure running over type in a CIDFont only named ([`Interp::named_cshow`]): the -/// CIDFont it sees as current, the composite font `rootfont` gives while that CIDFont is current, -/// and the type of the code it was given. +/// A `cshow` procedure running over a composite font's type ([`Interp::named_cshow`], +/// [`Interp::composite_cshow`]): the descendant it sees as current, the composite font `rootfont` +/// gives while that descendant is current, and the code it was given: over a CIDFont only named, +/// its type; over a composite font the file carries, the character it maps to. pub(super) struct CShowFont { selected: DictRef, root: DictRef, - code: NamedCid, + code: Option, + mapped: Option, } /// What drawing a glyph does with it. @@ -1064,6 +1088,22 @@ impl Interp<'_> { /// codes mapped to a descendant and a CID, §5.11.5); `None` for other fonts and mappings, /// which are set as type in the font of the composite font's name. fn composite_glyphs(&mut self, s: &[u8]) -> Res>> { + // Inside a `cshow` procedure over a composite font the file carries, with the descendant + // it selected current, the one byte the procedure was given stands for the character its + // code maps to: a CMap's CID, base-font code or glyph name. In a CIDFont any other string + // is a `rangecheck` error (PLRM 3rd ed., `cshow`: the glyph of the selected CID); in a + // base font it is shown as it is. + if let Some(c) = self.cshow.as_ref() + && let Some(mapped) = c.mapped.as_ref() + && self.g.font.as_ref().is_some_and(|f| f.same(&c.selected)) + { + if s == [mapped.last()] { + return Ok(Some(vec![mapped.clone()])); + } + if mapped.cid.is_some() { + return ps_err("rangecheck", "a string shown in cshow"); + } + } let Some(font) = self.g.font.clone() else { return Ok(None) }; let map = { let f = font.borrow(); @@ -1097,7 +1137,8 @@ impl Interp<'_> { if let Some(Obj::Dict(d)) = index.and_then(|i| fonts.get(i as usize)) && font_type(&d.borrow()) != Some(0.0) { - out.push(Mapped { font: d.clone(), pick, code, name: None, cid: None, outer, vertical: false }); + let value = u32::from(pick) * 256 + u32::from(code); + out.push(Mapped { font: d.clone(), pick, code, name: None, cid: None, outer, vertical: false, value }); } } Ok(Some(out)) @@ -1124,21 +1165,28 @@ impl Interp<'_> { .filter_map(|c| match (fonts.get(c.font), c.base) { // A base font's code, or its glyph name (at the code its encoding gives it, if any). (Some(Obj::Dict(d)), Some(Base::Code(code))) => { - Some(Mapped { font: d.clone(), pick: 0, code, name: None, cid: None, outer, vertical }) + Some(Mapped { font: d.clone(), pick: 0, code, name: None, cid: None, outer, vertical, value: c.value }) } (Some(Obj::Dict(d)), Some(Base::Name(name))) => { let code = encoded(&d.borrow(), &name); let name = code.is_none().then_some(name); - Some(Mapped { font: d.clone(), pick: 0, code: code.unwrap_or(0), name, cid: None, outer, vertical }) + Some(Mapped { font: d.clone(), pick: 0, code: code.unwrap_or(0), name, cid: None, outer, vertical, value: c.value }) } // A code without a mapping in a base font (not a CIDFont): its code 0, the // `.notdef` glyph CID 0 stands for in a CIDFont. (Some(Obj::Dict(d)), None) if !d.borrow().contains_key(&Key::name("CIDFontType")) => { - Some(Mapped { font: d.clone(), pick: 0, code: 0, name: None, cid: None, outer, vertical }) - } - (Some(Obj::Dict(d)), None) => { - Some(Mapped { font: d.clone(), pick: 0, code: (c.cid & 0xff) as u8, name: None, cid: Some((c.cid, c.notdef)), outer, vertical }) + Some(Mapped { font: d.clone(), pick: 0, code: 0, name: None, cid: None, outer, vertical, value: c.value }) } + (Some(Obj::Dict(d)), None) => Some(Mapped { + font: d.clone(), + pick: 0, + code: (c.cid & 0xff) as u8, + name: None, + cid: Some((c.cid, c.notdef)), + outer, + vertical, + value: c.value, + }), _ => None, }) .collect()) @@ -1207,17 +1255,18 @@ impl Interp<'_> { /// that code when `code` and with none otherwise, while the CIDFont it selected is current. fn cshow_code(&self, code: bool) -> Option { let c = self.cshow.as_ref()?; + let given = c.code.as_ref()?; if !self.g.font.as_ref().is_some_and(|f| f.same(&c.selected)) { return None; } let mut codes = Decoded::default(); if code { - let mut chars = c.code.codes.text.chars(); - for &(value, n) in &c.code.codes.codes { + let mut chars = given.codes.text.chars(); + for &(value, n) in &given.codes.codes { codes.push(value, chars.by_ref().take(n)); } } - Some(NamedCid { codes, font: c.code.font.clone(), vertical: c.code.vertical, ems: c.code.ems }) + Some(NamedCid { codes, font: given.font.clone(), vertical: given.vertical, ems: given.ems }) } /// The CMap's name, the composite font, the CIDFont's name and the writing mode of @@ -1305,7 +1354,7 @@ impl Interp<'_> { self.push(Obj::Int(i64::from(code & 0xff)))?; self.push_num(v.x)?; self.push_num(v.y)?; - self.cshow = Some(CShowFont { selected: selected.clone(), root: composite.clone(), code: one }); + self.cshow = Some(CShowFont { selected: selected.clone(), root: composite.clone(), code: Some(one), mapped: None }); self.g.font = Some(selected.clone()); let go = self.body(proc); self.g.font = root.clone(); @@ -1316,6 +1365,41 @@ impl Interp<'_> { Ok(()) } + /// `cshow`'s procedure `proc` run for each character `glyphs` of composite font `root` maps, + /// with the last byte of its code and its width (PLRM 3rd ed., `cshow`). While it runs the + /// descendant that draws the character, at the size the composite font sets it, is the current + /// font and `rootfont` gives `root`. The current font is restored when the procedure completes. + fn composite_cshow(&mut self, glyphs: &[Mapped], proc: &Obj, root: Option) -> Res { + let Some(composite) = root.clone() else { return Ok(()) }; + for g in glyphs { + let v = self.composite_glyph(g, Point::ZERO, Draw::No)?; + self.push(Obj::Int(i64::from(g.last())))?; + self.push_num(v.x)?; + self.push_num(v.y)?; + // Scaling the descendant copies its dictionary for every character: charged by its + // size, so a huge font dictionary in a loop runs out of the budget. + let entries = g.font.borrow().len(); + self.spend(entries as u64)?; + // Without a matrix, a Type 42 font or a Type 2 CIDFont is in ems, as `composite_glyph` + // and `cid_glyph_at` draw it. + let selected = { + let f = g.font.borrow(); + let default = if units(&f) == 1.0 { 1.0 } else { 0.001 }; + let mut d = f.clone(); + d.insert(Key::name("FontMatrix"), matrix_obj(g.outer * font_matrix(&f, default))); + DictRef::new(d) + }; + self.cshow = Some(CShowFont { selected: selected.clone(), root: composite.clone(), code: None, mapped: Some(g.clone()) }); + self.g.font = Some(selected); + let go = self.body(proc); + self.g.font = root.clone(); + if !go? { + break; + } + } + Ok(()) + } + /// How far codes `codes` of type `named` move the current point (user space) when /// [`Self::show_named_cid`] shows them with no extra spacing. fn named_cid_width(&mut self, named: &NamedCid, codes: &Decoded) -> Res { @@ -1346,6 +1430,12 @@ impl Interp<'_> { fn show_composite(&mut self, glyphs: &[Mapped], spacing: &Spacing) -> Res { let start = self.out.drawn.len(); let mut text = String::new(); + let kern: Vec = match spacing { + Spacing::Kern(_) => glyphs.iter().map(|g| g.value).collect(), + _ => Vec::new(), + }; + // Where in the objects drawn each run of `kshow`'s procedure put its art. + let mut kerned = Vec::new(); for (i, g) in glyphs.iter().enumerate() { let at = self.user_point()?; let w = self.composite_glyph(g, at, Draw::Fill)?; @@ -1353,6 +1443,12 @@ impl Interp<'_> { // times 256 plus its code (PLRM 3rd ed., `widthshow` in chapter 8). let d = spacing.advance(i, i64::from(g.pick) * 256 + i64::from(g.code), w); self.g.cur = Some(self.xf() * (at + d)); + // `kshow`'s procedure runs between each two characters with the values of their codes. + let before = self.out.drawn.len(); + self.kern(spacing, &kern, i, at + d)?; + if self.out.drawn.len() > before { + kerned.push(before..self.out.drawn.len()); + } // A CID stands for no character (its code is only the CID's low byte). let c = if g.cid.is_some() { '\u{2022}' } else { g.name.as_deref().map_or_else(|| code_char(&g.font.borrow(), g.code), glyph_char) }; if c != '\u{2022}' { @@ -1364,7 +1460,13 @@ impl Interp<'_> { { text = name.to_string(); } + // What `kshow`'s procedure draws goes after the type, outside its group. + let mut art = Vec::new(); + for run in kerned.into_iter().rev() { + art.splice(0..0, self.out.drawn.drain(run)); + } self.group_glyphs(start, &text); + self.out.drawn.extend(art); Ok(()) } diff --git a/crates/eps/src/legacy_ai.rs b/crates/eps/src/legacy_ai.rs index 7e38b5ba51..76980f4b7e 100644 --- a/crates/eps/src/legacy_ai.rs +++ b/crates/eps/src/legacy_ai.rs @@ -101,7 +101,7 @@ const HEX_LINE: usize = 60; pub const SUBLAYERS: &str = "sublayers are written as groups in their top-level layer (legacy .ai files have no sublayers)"; pub const TYPE: &str = "type a legacy .ai can't hold as text (characters outside Windows Latin-1, vertical type, ruby, inline graphics, gradient or pattern fills) is written as outlines"; pub const ROTATED_TYPE: &str = "type with rotated characters is written as outlines, which keep the rotation, and is no longer editable text (legacy .ai text can't rotate characters)"; -pub const TYPE_ATTRIBUTES: &str = "type attributes legacy .ai files don't have (underline, strikethrough, optical kerning, small caps, superscript and subscript, OpenType features, Variable Font settings, optical margin alignment, System Layout, fractional widths off, area type options, type on a path's effect, alignment and spacing, an end bracket short of the path's end, subpaths after the first in an area type frame or a type path, space after paragraphs, tabs, bulleted and numbered lists) are left out"; +pub const TYPE_ATTRIBUTES: &str = "type attributes legacy .ai files don't have (underline, strikethrough, optical kerning, small caps, superscript and subscript, Insert Aki, OpenType features, Variable Font settings, optical margin alignment, System Layout, fractional widths off, area type options, type on a path's effect, alignment and spacing, an end bracket short of the path's end, subpaths after the first in an area type frame or a type path, space after paragraphs, tabs, bulleted and numbered lists) are left out"; pub const DYNAMIC_TEXT: &str = "Dynamic Text is written as the sizes the type is drawn at (legacy .ai files don't have it)"; pub const HIDDEN: &str = "hidden objects are left out (hidden layers are kept, hidden)"; pub const HIDDEN_LAYER: &str = "hidden objects are moved to a hidden layer above their own (legacy .ai files can hide only layers)"; diff --git a/crates/eps/src/legacy_ai/encoding.rs b/crates/eps/src/legacy_ai/encoding.rs index 7ebae72123..d971e5249e 100644 --- a/crates/eps/src/legacy_ai/encoding.rs +++ b/crates/eps/src/legacy_ai/encoding.rs @@ -123,6 +123,9 @@ pub(super) fn lost_attributes(t: &TextObject) -> bool { || s.optical_kerning || s.small_caps.is_some() || s.position != CharPosition::Normal + // Its text operators (§15.4) have no Insert Aki. + || s.aki_left != 0.0 + || s.aki_right != 0.0 || !s.features.is_empty() || !s.font_axes.is_empty() }; diff --git a/crates/eps/src/legacy_ai/tests.rs b/crates/eps/src/legacy_ai/tests.rs index 663e21bec6..ad27eb4a03 100644 --- a/crates/eps/src/legacy_ai/tests.rs +++ b/crates/eps/src/legacy_ai/tests.rs @@ -1435,6 +1435,41 @@ fn variable_font_settings_are_warned_as_left_out() { assert!(String::from_utf8(out.bytes).unwrap().contains("(H\\351llo \\2005\\r) Tx\n"), "still written as text"); } +/// A legacy `.ai` text object has no Insert Aki (§15.4): type with Insert Aki Left or Right is +/// written as text with the warning that it is left out. Written as outlines, the glyphs keep the +/// space it adds, and nothing is reported. +#[test] +fn insert_aki_is_warned_as_left_out_of_text() { + for (left, right) in [(250.0, 0.0), (0.0, 125.0)] { + let mut doc = typed(); + let id = texts(&doc)[0].0.id; + if let Some(NodeKind::Text(t)) = doc.node_mut(id).map(|n| &mut n.kind) { + t.runs[0].style.aki_left = left; + t.runs[0].style.aki_right = right; + } + let out = write(&doc); + assert!(out.warnings.iter().any(|w| w == TYPE_ATTRIBUTES), "{left} {right}: {:?}", out.warnings); + assert!(String::from_utf8(out.bytes).unwrap().contains("(H\\351llo \\2005\\r) Tx\n"), "still written as text"); + } + let width = |aki: f64| { + let mut st = style(20.0, red()); + st.aki_left = aki; + st.aki_right = aki; + let t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(20.0, 40.0), "HH", st); + let mut doc = Document::new(300.0, 200.0); + let layer = doc.layers[0].id; + let n = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t))); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let out = write_with(&doc, LegacyAiOptions { outline_text: true, ..LegacyAiOptions::default() }); + assert!(!out.warnings.iter().any(|w| w == TYPE_ATTRIBUTES), "{:?}", out.warnings); + let back = crate::import(&out.bytes).unwrap().document; + children(&children(&back.layers[0])[0])[0].visual_bounds().unwrap().width() + }; + // Between the two H's: 0.5 em after the first and 0.5 em before the second, 20 pt. + let (plain, spaced) = (width(0.0), width(500.0)); + assert!((spaced - plain - 20.0).abs() < 0.05, "{plain} {spaced}"); +} + /// Standard Vertical Roman Alignment is written as `Tv` and Tate-chu-yoko in horizontal type as a /// Kumi block recorded for later use, `TY` (§15.3.4), each where it changes: the marks read back /// on the same characters, a block is closed before its text object ends, and type with neither diff --git a/crates/eps/src/lib.rs b/crates/eps/src/lib.rs index 49b64f4bce..534778286a 100644 --- a/crates/eps/src/lib.rs +++ b/crates/eps/src/lib.rs @@ -230,7 +230,8 @@ pub fn export(doc: &Document, opts: &EpsOptions, preview: Option<&Raster>, thumb } // Type in the document's composite fonts is drawn in them, whether or not an app has the document open. let _lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&doc.composite_fonts); - let baked = vectorcraft_effects::bake_document(doc); + let baked = + vectorcraft_effects::bake_document_placing_symbols(doc, true, vectorcraft_effects::WrittenLayers { hidden: false, non_printing: true }); let doc = baked.as_ref().unwrap_or(doc); let page = scene::Scene::new(doc, opts).run(); let mut setting_notes = vec![]; diff --git a/crates/eps/src/scene.rs b/crates/eps/src/scene.rs index 299d130f7d..8d147cb2d1 100644 --- a/crates/eps/src/scene.rs +++ b/crates/eps/src/scene.rs @@ -489,8 +489,11 @@ impl<'a> Scene<'a> { self.warn(TOO_LARGE); return; } + // Off the region, an object is still written when brush art painted along its brushed + // strokes, or those of the objects in it, can reach the region. + let off = |b: Rect, reach: f64| !overlaps(b.inflate(1.0 + reach, 1.0 + reach), self.o.region); match n.visual_bounds_with(&self.symbols) { - Some(b) if !force && !overlaps(b.inflate(1.0, 1.0), self.o.region) => return, + Some(b) if !force && off(b, 0.0) && off(b, vectorcraft_brush::reach_within(n)) => return, None if !n.is_container() => return, _ => {} } diff --git a/crates/eps/src/tests.rs b/crates/eps/src/tests.rs index 8547c4d015..963e78c9ef 100644 --- a/crates/eps/src/tests.rs +++ b/crates/eps/src/tests.rs @@ -1324,6 +1324,79 @@ fn the_page_limit_counts_a_repeated_images_samples_once() { assert!(page.body.len() + page.setup.len() <= inline + 1000 + 400, "{}", page.body.len()); } +/// Type whose color bitmap glyphs fit under the page limit but whose run fill passes it is left +/// out with its glyph image placements: the page is the page without that type. A glyph image +/// that other art draws once more is written inline there again, and an image that other art +/// draws twice keeps its shared samples. +#[test] +fn type_taken_back_for_the_page_limit_takes_its_glyph_images_with_it() { + use vectorcraft_doc::{CharStyle, TextObject}; + use vectorcraft_text::test_fonts::{COLOUR_CHAR, colour_bitmap_family, colour_bitmap_font}; + vectorcraft_text::FontDb::global().add_font(colour_bitmap_font(false).unwrap()); + let black = Paint::solid(Color::rgb(0.0, 0.0, 0.0)); + let type_node = |d: &mut Document, at: Point, text: &str, fill: Paint| { + let st = CharStyle { font_family: colour_bitmap_family(false).into(), size: 32.0, fill, ..CharStyle::default() }; + Node::new(d.alloc_id(), NodeKind::Text(Box::new(TextObject::point(at, text, st)))) + }; + // Six glyph images, then outlines enough for the fill to pass the limit. + let target = format!("{}{}", COLOUR_CHAR.to_string().repeat(6), "W".repeat(40)); + // `shared`: an image drawn twice comes first; `before`: one glyph drawn with the type's image; + // `fill`: the type's run fill (`None`: no type). A red rectangle comes last. + let build = |shared: bool, before: bool, fill: Option| { + let mut d = if shared { + let mut d = image_doc(&noise(8, 8), 1.0); + place_again(&mut d, 0, Affine::translate((40.0, 0.0))); + d + } else { + Document::new(200.0, 200.0) + }; + let mut nodes = vec![]; + if before { + nodes.push(type_node(&mut d, Point::new(20.0, 40.0), &COLOUR_CHAR.to_string(), black.clone())); + } + if let Some(fill) = fill { + nodes.push(type_node(&mut d, Point::new(20.0, 100.0), &target, fill)); + } + nodes.push(red_rect(&mut d)); + for n in nodes { + d.insert(d.default_layer(), usize::MAX, n).unwrap(); + } + d + }; + for shared in [false, true] { + for before in [false, true] { + let case = format!("shared {shared}, before {before}"); + let (without, unfilled, filled) = + (build(shared, before, None), build(shared, before, Some(Paint::None)), build(shared, before, Some(black.clone()))); + let o = opts(&filled); + let glyph = usize::from(shared); + let fits = crate::scene::Scene::new(&unfilled, &o).run(); + let full = crate::scene::Scene::new(&filled, &o).run(); + assert!(fits.warnings.is_empty() && full.warnings.is_empty(), "{case}: {:?} {:?}", fits.warnings, full.warnings); + assert_eq!(reuses(&fits.body, glyph, o.level), 6 + usize::from(before), "{case}: {}", fits.body); + assert_eq!(reuses(&full.body, glyph, o.level), 6 + usize::from(before), "{case}: {}", full.body); + let (fits_len, full_len) = (fits.body.len() + fits.setup.len(), full.body.len() + full.setup.len()); + assert!(full_len > fits_len + 2000, "{case}: {fits_len} {full_len}"); + let limit = (fits_len + full_len) / 2; + // Without its fill the type fits, every glyph image with it. + let page = crate::scene::Scene::new(&unfilled, &o).with_max_body(limit).run(); + assert!(page.warnings.is_empty(), "{case}: {:?}", page.warnings); + assert_eq!((page.setup, page.body), (fits.setup, fits.body), "{case}"); + // With it the type is taken back after its glyph images were placed. + let page = crate::scene::Scene::new(&filled, &o).with_max_body(limit).run(); + assert!(page.warnings.iter().any(|w| w.contains("too large")), "{case}: {:?}", page.warnings); + let alone = crate::scene::Scene::new(&without, &o).run(); + assert!(alone.warnings.is_empty(), "{case}: {:?}", alone.warnings); + assert_eq!(reuses(&page.body, glyph, o.level), 0, "{case}: {}", page.body); + assert!(!page.setup.contains(&format!("/VCim{glyph} ")), "{case}: {}", page.setup); + assert_eq!(page.body.matches("/Width 16 /Height 16").count(), usize::from(before), "{case}: {}", page.body); + assert_eq!(reuses(&page.body, 0, o.level), if shared { 2 } else { 0 }, "{case}: {}", page.body); + assert_eq!((&page.setup, &page.body), (&alone.setup, &alone.body), "{case}"); + checked_page(&page.body); + } + } +} + /// A freeform gradient of `points` (x, y and color). fn freeform(points: &[(f64, f64, Color)]) -> Paint { let mut g = GradientPaint::new(Gradient { kind: GradientKind::Freeform, ..Default::default() }); @@ -1581,6 +1654,76 @@ fn an_instance_whose_brush_art_reaches_the_region_is_written() { assert!(page.contains("1 0 0 rg"), "{page}"); } +#[test] +fn a_path_whose_brush_art_reaches_the_region_is_written() { + // A line from (-5, 40) to (-5, 60) with a 1 pt red stroke painted by a 20 pt round nib lies + // left of the artboard, and the nib paints 10 pt either side of it, onto the artboard: alone, in + // a group and as a compound path. Without its brush, or 100 pt left of the artboard, where the + // nib does not reach it, the line is left out. + let red = |x: f64, brushed: bool| { + let mut n = Node::path( + vectorcraft_doc::NodeId(0), + shapes::line((x, 40.0).into(), (x, 60.0).into()), + Appearance::basic(Paint::None, Paint::solid(Color::rgb(1.0, 0.0, 0.0)), 1.0), + ); + if brushed { + n.appearance.stroke_mut().unwrap().brush = Some("3 pt. Round".into()); + } + n + }; + let cases: [(&str, f64, bool, bool); 5] = [ + ("path", -5.0, true, true), + ("group", -5.0, true, true), + ("compound path", -5.0, true, true), + ("unbrushed path", -5.0, false, false), + ("far path", -100.0, true, false), + ]; + for (what, x, brushed, written) in cases { + let mut d = Document::new(200.0, 200.0); + let mut lib = vectorcraft_brush::library(&d); + let Some(vectorcraft_brush::BrushKind::Calligraphic(c)) = lib.iter_mut().find(|b| b.name == "3 pt. Round").map(|b| &mut b.kind) else { + panic!("the 3 pt. Round brush") + }; + c.size = 20.0; + vectorcraft_brush::store(&mut d, &lib); + let line = red(x, brushed); + let mut n = match what { + "group" => Node::group(vectorcraft_doc::NodeId(0), vec![Arc::new(line)]), + "compound path" => { + let mut c = Node::new( + vectorcraft_doc::NodeId(0), + NodeKind::Compound { children: vec![Arc::new(red(x, false))], rule: vectorcraft_geom::FillRule::NonZero }, + ); + c.appearance = line.appearance; + c + } + _ => line, + }; + n.id = d.alloc_id(); + let layer = d.layers[0].id; + d.insert(Some(layer), usize::MAX, n).unwrap(); + let page = page_of(&d, &opts(&d)); + assert_eq!(page.contains("1 0 0 rg") || page.contains("1 0 0 RG"), written, "{what}: {page}"); + } +} + +#[test] +fn symbol_art_effects_are_written_where_they_draw() { + // The symbol's square at (10, 40), which a Transform effect moves 100 pt right, is drawn from + // x = 110 and not from x = 10. + let mut d = doc_with(|d| vec![Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Moved".into(), xf: Affine::IDENTITY })]); + let mut art = path(&mut d, shapes::rectangle(Rect::new(10.0, 40.0, 20.0, 50.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); + art.appearance.effects.push(vectorcraft_doc::Effect { + id: "distort.transform".into(), + params: serde_json::json!({"moveH": 100.0}), + visible: true, + }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Moved".into(), art: Arc::new(art) }); + let page = page_of(&d, &opts(&d)); + let starts: Vec = page.lines().filter(|l| l.ends_with(" m")).filter_map(|l| l.split_whitespace().next()?.parse().ok()).collect(); + assert!(!starts.is_empty() && starts.iter().all(|x| (110.0..=120.0).contains(x)), "{starts:?}\n{page}"); +} + #[test] fn level_preview_and_overprint_ids_read_back() { for l in Level::ALL { diff --git a/crates/js/src/builtins/object.rs b/crates/js/src/builtins/object.rs index 969a9c6094..af41bb7782 100644 --- a/crates/js/src/builtins/object.rs +++ b/crates/js/src/builtins/object.rs @@ -166,10 +166,11 @@ fn create(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult JsResult { let o = require_object(interp, &arg(args, 0), "defineProperty")?; - let k = interp.to_key(&arg(args, 1))?; - let desc = to_desc(interp, &arg(args, 2))?; - let roots = desc_values(&desc); - interp.rooted(&roots, |interp| interp.define_own_property(o, k, &desc, true))?; + interp.with_key(&arg(args, 1), |interp, k| { + let desc = to_desc(interp, &arg(args, 2))?; + let roots = desc_values(&desc); + interp.rooted(&roots, |interp| interp.define_own_property(o, k, &desc, true)) + })?; Ok(Value::Object(o)) } diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index edc5282fe5..aa4a4c5c78 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -1779,8 +1779,7 @@ impl Interp { return self.replace(2, v); } self.check_coercible(&base, &[])?; - let name = self.to_key(&k)?; - let v = self.get_value(&base, &name)?; + let v = self.with_key(&k, |i, name| i.get_value(&base, &name))?; self.replace(2, v)?; if with_this { self.push(base) } else { Ok(()) } } @@ -1852,8 +1851,7 @@ impl Interp { return self.replace(2, Value::Number(if prefix { new } else { old })); } self.check_coercible(&base, &[])?; - let name = self.to_key(&k)?; - let r = self.inc_property(&base, name, prefix, dec)?; + let r = self.with_key(&k, |i, name| i.inc_property(&base, name, prefix, dec))?; self.replace(2, r) } @@ -2670,6 +2668,18 @@ impl Interp { } } + /// Runs `f` with the property name [`Self::to_key`] makes from `v`. A name converted from a + /// value that is not a string is kept reachable while `f` runs, so a collection that a getter + /// or setter starts still counts its units. + pub(crate) fn with_key(&mut self, v: &Value, f: impl FnOnce(&mut Self, Key) -> JsResult) -> JsResult { + let name = self.to_key(v)?; + if matches!(v, Value::String(_)) { + return f(self, name); + } + let root = Value::String(Str::from_rc(name.clone())); + self.rooted(&[root], |i| f(i, name)) + } + /// The code units of `s`. Flattening a rope makes a copy of its units, so for a rope that /// copy's bytes are reserved and added to the heap first, without taking fuel. The rope stays /// rooted while the copy is reserved; everything else the caller still needs must be diff --git a/crates/js/src/text_tests.rs b/crates/js/src/text_tests.rs index 01fc613cc3..62145b6117 100644 --- a/crates/js/src/text_tests.rs +++ b/crates/js/src/text_tests.rs @@ -434,6 +434,32 @@ fn a_call_keeps_its_operands_while_a_string_receiver_is_boxed() { assert_eq!(realm.run(src), Ok(JsValue::Number(1.0))); } +#[test] +fn a_computed_key_stays_counted_while_its_getter_or_setter_runs() { + // `o` has an accessor named by a flat string of 131,073 units. `key`'s toString returns a new + // rope with the same units, so using `key` as a name makes a second flat copy, which must stay + // counted while an accessor makes a third. The heap has room for one more copy, not two. + let build = "var s = 'x'; for (var i = 0; i < 17; i++) s = s + s; function f(c) { return s + c; } \ + function copy() { var g = f('g'); g[0]; return 1; } var o = {}, name = f('k'); name[0]; \ + Object.defineProperty(o, name, { get: copy, set: copy }); \ + var key = { toString: function () { return f('k'); } }; 0"; + let realm = || { + let mut realm = Realm::with_options(Options::default(), Limits::default()); + assert_eq!(realm.run(build), Ok(JsValue::Number(0.0))); + let interp = realm.interp(); + interp.collect_garbage(); + let copy = crate::heap::string_bytes(131_073); + interp.limits.heap_bytes = interp.heap.bytes + copy + copy / 2; + interp.reset_gc_threshold(); + realm + }; + assert_eq!(realm().run("o[name]"), Ok(JsValue::Number(1.0)), "the accessor's own copy fits"); + for read in ["o[key]", "o[key] = 1", "o[key]++", "Object.defineProperty({}, key, { get value() { return copy(); } })"] { + let result = realm().run(read); + assert!(matches!(result, Err(ref e) if e.kind == RunErrorKind::Limit(LimitKind::Heap)), "{read}: {result:?}"); + } +} + #[test] fn compiling_a_pattern_counts_against_the_heap() { let src = "var s = '[\\\\s\\\\S]a*'; for (var i = 0; i < 14; i++) s = s + s; new RegExp(s).source.length"; diff --git a/crates/mcp/src/headless.rs b/crates/mcp/src/headless.rs index 69c7b5ba0e..8bd8afc2e5 100644 --- a/crates/mcp/src/headless.rs +++ b/crates/mcp/src/headless.rs @@ -81,6 +81,7 @@ pub(crate) fn pointer_kind(k: &str) -> Option { "up" => PointerKind::Up, "move" => PointerKind::Move, "doubleclick" | "dblclick" => PointerKind::DoubleClick, + "tripleclick" => PointerKind::TripleClick, _ => return None, }) } @@ -238,7 +239,7 @@ impl Headless { .map(|(e, backquote)| { let mods = packet_mods(e)?.unwrap_or(base); let kind = s(e, "kind").unwrap_or(""); - let kind = pointer_kind(kind).ok_or_else(|| format!("unknown pointer kind `{kind}` (down|drag|up|move|doubleclick)"))?; + let kind = pointer_kind(kind).ok_or_else(|| format!("unknown pointer kind `{kind}` (down|drag|up|move|doubleclick|tripleclick)"))?; PointerEvent::json_check(e)?; if s(e, "space") == Some("screen") { return Err("screen-space pointer events need the desktop app; use document coordinates".to_string()); diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 6529cf175d..b5fd1135aa 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -16,6 +16,7 @@ mod gradient; mod limits; mod links; mod liquify; +mod livepaint; mod pen; mod persp; mod place; @@ -490,6 +491,43 @@ fn trace_and_style_prompt_steps_run_in_order() { assert!(fills.len() > 1 && fills.contains("#00aa00") && !fills.contains(&from), "{fills:?}"); } +/// A window capture and an artboard preview scaled down keep the color of opaque pixels beside +/// clear ones: the clear black beside them does not darken them. +#[test] +fn scaled_down_pictures_keep_the_color_beside_clear_pixels() { + struct Striped; + impl Backend for Striped { + fn call(&mut self, method: &str, _: Value) -> Result { + let mut png = std::io::Cursor::new(Vec::new()); + image::RgbaImage::from_fn(64, 4, |x, _| if x % 2 == 0 { image::Rgba([200, 30, 30, 255]) } else { image::Rgba([0, 0, 0, 0]) }) + .write_to(&mut png, image::ImageFormat::Png) + .unwrap(); + let png = vectorcraft_format::base64_encode(png.get_ref()); + Ok(match method { + "document.inspect" => json!({"artboards": [{"width": 64, "height": 4}]}), + _ => json!({"pngBase64": png, "width": 64, "height": 4}), + }) + } + fn has_ui(&self) -> bool { + true + } + fn describe(&self) -> String { + "test".into() + } + } + + let mut s = Server::new(Box::new(Striped)); + let shots = [("screenshot", json!({"window": true, "max_side": 16})), ("render_preview", json!({"max_side": 16}))]; + for (id, (tool, args)) in (1..).zip(shots) { + let r = call(&mut s, id, tool, args); + let data = + r["content"].as_array().unwrap().iter().find(|c| c["type"] == "image").unwrap_or_else(|| panic!("{tool}: {r}"))["data"].as_str().unwrap(); + let img = image::load_from_memory(&vectorcraft_format::base64_decode(data).unwrap()).unwrap().into_rgba8(); + assert_eq!(img.dimensions(), (16, 1), "{tool}"); + assert!(img.pixels().all(|p| p.0 == [200, 30, 30, 128]), "{tool}: {:?}", img.get_pixel(0, 0)); + } +} + /// `screenshot` and `render_preview` with `traceViews: true` draw an Image Trace object in the /// view set with imageTrace.setView, as the app's window does; without it they draw the tracing /// result, as exports do. The image is a dark disc (r = 30 px) on blue, traced with Ignore White. @@ -1597,6 +1635,27 @@ fn text_effect_pathfinder_transform_graph_and_wrap_tools() { let ds = d.to_string(); // The wrap object carries the options and the area type resolved its shape. assert!(ds.contains("\"wrap\":{\"invert\":false,\"offset\":8.0}") && ds.contains("\"wrap\":[{\"invert\":false,\"offset\":8.0"), "{area}"); + // An offset outside -1000 to 1000 pt, an invert or a release that is not true or false is an + // error, with release too, and the wrap and the selection stay as they were. + let r = call(&mut s, 20, "run_command", json!({"command": "select.set", "params": {"ids": [g]}})); + assert_eq!(r["isError"], false, "{r}"); + for (id, args) in [ + (21, json!({"ids": [c], "offset": 5000})), + (22, json!({"ids": [c], "offset": "8"})), + (23, json!({"ids": [c], "invert": "true"})), + (24, json!({"ids": [c], "release": "true"})), + (25, json!({"ids": [c], "release": true, "offset": -5000})), + ] { + let r = call(&mut s, id, "text_wrap", args.clone()); + assert_eq!(r["isError"], true, "{args}: {r}"); + assert!(doc_json(&mut s).to_string().contains("\"wrap\":{\"invert\":false,\"offset\":8.0}"), "{args}"); + } + // The graph is still the selection: a wrap made without ids goes on it, not on the circle. + let r = call(&mut s, 26, "text_wrap", json!({"offset": 9})); + assert_eq!(r["isError"], false, "{r}"); + let made: Value = serde_json::from_str(&text_of(&r)).unwrap(); + assert_eq!(made["ids"], json!([g]), "{r}"); + call(&mut s, 27, "text_wrap", json!({"release": true})); call(&mut s, 15, "text_wrap", json!({"ids": [c], "release": true})); assert!(!doc_json(&mut s).to_string().contains("\"offset\":8.0")); } diff --git a/crates/mcp/src/tests/livepaint.rs b/crates/mcp/src/tests/livepaint.rs new file mode 100644 index 0000000000..0165823e6f --- /dev/null +++ b/crates/mcp/src/tests/livepaint.rs @@ -0,0 +1,73 @@ +//! The Live Paint Bucket through MCP: `pointer_gesture` sends a triple-click as `tripleclick`. + +use serde_json::{Value, json}; + +use crate::{Backend, Headless, call_tool}; + +fn ok(h: &mut Headless, name: &str, args: Value) -> Value { + let r = call_tool(h, name, &args); + assert!(!r.is_error, "{name} {args}: {r:?}"); + serde_json::from_str(r.content[0]["text"].as_str().unwrap()).unwrap_or(Value::Null) +} + +fn run(h: &mut Headless, command: &str, params: Value) -> Value { + ok(h, "run_command", json!({"command": command, "params": params})) +} + +/// The fill of each face of Live Paint group `g`, left to right. +fn fills(h: &mut Headless, g: &Value) -> Vec { + let info = run(h, "livePaint.info", json!({"group": g})); + let mut faces = info["faces"].as_array().unwrap().clone(); + faces.sort_by(|a, b| a["bounds"][0].as_f64().unwrap().total_cmp(&b["bounds"][0].as_f64().unwrap())); + faces.iter().map(|f| f["fill"].clone()).collect() +} + +#[test] +fn a_triple_click_fills_every_face_of_the_same_fill() { + let mut h = Headless::new(); + h.call("engine.execute", json!({"command": "file.new", "params": {"width": 300, "height": 300}})).unwrap(); + let a = run(&mut h, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50}))["id"].clone(); + let b = run(&mut h, "shape.rectangle", json!({"x": 100, "y": 0, "width": 50, "height": 50}))["id"].clone(); + let g = run(&mut h, "livePaint.make", json!({"ids": [a, b]}))["id"].clone(); + for x in [25, 125] { + run(&mut h, "livePaint.fill", json!({"group": g, "point": [x, 25], "color": "#ff0000"})); + } + let red = fills(&mut h, &g); + assert_eq!(red[0], red[1]); + // With nothing selected, the current fill changes and the group keeps its faces' fills. + run(&mut h, "select.none", json!({})); + run(&mut h, "paint.setFill", json!({"color": "#00ff00"})); + assert_eq!(fills(&mut h, &g), red); + let ev = |kind: &str| json!({"kind": kind, "x": 25, "y": 25}); + let clicks = [ev("down"), ev("up"), ev("down"), ev("up"), ev("doubleclick"), ev("down"), ev("up")]; + ok(&mut h, "pointer_gesture", json!({"tool": "livePaintBucket", "events": clicks})); + let after_two = fills(&mut h, &g); + assert_eq!(after_two[1], red[1], "the face apart is left by the clicks and the double-click"); + assert_ne!(after_two[0], red[0]); + ok(&mut h, "pointer_gesture", json!({"events": [ev("tripleclick")]})); + assert_eq!(fills(&mut h, &g), [after_two[0].clone(), after_two[0].clone()], "both faces were red"); +} + +/// With Space held (`mods.space`), the Live Paint Bucket's clicks, double-click and triple-click +/// paint nothing. +#[test] +fn clicks_with_space_held_paint_nothing() { + let mut h = Headless::new(); + h.call("engine.execute", json!({"command": "file.new", "params": {"width": 300, "height": 300}})).unwrap(); + let a = run(&mut h, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50}))["id"].clone(); + let b = run(&mut h, "shape.rectangle", json!({"x": 100, "y": 0, "width": 50, "height": 50}))["id"].clone(); + let g = run(&mut h, "livePaint.make", json!({"ids": [a, b]}))["id"].clone(); + for x in [25, 125] { + run(&mut h, "livePaint.fill", json!({"group": g, "point": [x, 25], "color": "#ff0000"})); + } + run(&mut h, "select.none", json!({})); + run(&mut h, "paint.setFill", json!({"color": "#00ff00"})); + let red = fills(&mut h, &g); + let ev = |kind: &str| json!({"kind": kind, "x": 25, "y": 25}); + let clicks = [ev("down"), ev("up"), ev("down"), ev("up"), ev("doubleclick"), ev("down"), ev("up"), ev("tripleclick")]; + ok(&mut h, "pointer_gesture", json!({"tool": "livePaintBucket", "mods": {"space": true}, "events": clicks})); + assert_eq!(fills(&mut h, &g), red); + // Without Space, the same clicks paint. + ok(&mut h, "pointer_gesture", json!({"events": [ev("down"), ev("up")]})); + assert_ne!(fills(&mut h, &g)[0], red[0]); +} diff --git a/crates/mcp/src/tools/definitions.rs b/crates/mcp/src/tools/definitions.rs index e583753e4d..ee3bd56095 100644 --- a/crates/mcp/src/tools/definitions.rs +++ b/crates/mcp/src/tools/definitions.rs @@ -205,7 +205,7 @@ pub fn tool_definitions() -> Vec { "type": "array", "minItems": 1, "items": obj(json!({ - "kind": {"type": "string", "enum": ["down", "drag", "up", "move", "doubleclick"]}, + "kind": {"type": "string", "enum": ["down", "drag", "up", "move", "doubleclick", "tripleclick"]}, "x": num("Document x (pt)"), "y": num("Document y (pt)"), "mods": mods_schema(), @@ -507,7 +507,7 @@ pub fn tool_definitions() -> Vec { tool( "text_wrap", "Text wrap", - "Make the selected (or `ids`) objects wrap objects: area type below them in the same layer flows around them (offset in pt, invert = flow inside). `release: true` removes the wrap.", + "Make the selected (or `ids`) objects wrap objects: area type below them in the same layer flows around them (offset in pt, invert = flow inside). `release: true` removes the wrap. An offset outside -1000 to 1000 or not a number, or an invert or release that is not true or false, is an error and changes nothing.", obj( json!({ "ids": {"type": "array", "items": {"type": "integer"}}, diff --git a/crates/mcp/src/tools/dispatch.rs b/crates/mcp/src/tools/dispatch.rs index b1c5af70bb..8b9db99564 100644 --- a/crates/mcp/src/tools/dispatch.rs +++ b/crates/mcp/src/tools/dispatch.rs @@ -4,6 +4,7 @@ use super::handlers::{ select_ids, transform, }; use super::{ARTBOARD_PARAMS, Backend, Map, ToolResult, Value, json, writable_format}; +use vectorcraft_doc::resample::{Resample, fitted}; /// The `menu` argument of the command listings. pub(super) const MENU_FILTER: &str = @@ -19,6 +20,29 @@ pub(super) const MAX_SIDE_WINDOW: &str = /// The `traceViews` argument of the artboard renders. pub(super) const TRACE_VIEWS: &str = "Draw Image Trace objects in the view set with imageTrace.setView (outlines, the source image…), as the app's window does; by default they draw their tracing result, as exports do"; +/// The `text_wrap` tool's `release` and its `offset` and `invert` for `object.textWrap.make`, checked +/// before the tool changes the selection: an omitted or null value is left out, an `offset` that is +/// not a number or lies outside [`vectorcraft_engine::TEXT_WRAP_OFFSET_RANGE`] is an error, and so is +/// an `invert` or `release` that is not true or false. +fn text_wrap_args(a: &Args) -> Result<(bool, Value), String> { + let mut p = json!({}); + for k in ["offset", "invert", "release"] { + let Some(v) = a.get(k).filter(|v| !v.is_null()) else { continue }; + if k == "offset" { + let range = vectorcraft_engine::TEXT_WRAP_OFFSET_RANGE; + let n = v.as_f64().ok_or_else(|| format!("`{k}` must be a number, not {v}"))?; + if !range.contains(&n) { + return Err(format!("`{k}` must be from {} to {}", range.start(), range.end())); + } + } else if !v.is_boolean() { + return Err(format!("`{k}` must be true or false")); + } + p[k] = v.clone(); + } + let release = p.as_object_mut().and_then(|m| m.remove("release")).is_some_and(|v| v == true); + Ok((release, p)) +} + /// `traceViews`: false when absent. pub(super) fn trace_views(a: &Args) -> Result { match a.get("traceViews") { @@ -121,7 +145,7 @@ fn dispatch(b: &mut dyn Backend, name: &str, a: &Args) -> Result Result { + let (release, p) = text_wrap_args(a)?; select_ids(b, a)?; - if a.get("release").and_then(Value::as_bool) == Some(true) { + if release { return j(exec(b, "object.textWrap.release", json!({}))?); } - let mut p = json!({}); - for k in ["offset", "invert"] { - if let Some(v) = a.get(k) { - p[k] = v.clone(); - } - } j(exec(b, "object.textWrap.make", p)?) } "undo" => j(exec(b, "edit.undo", json!({}))?), @@ -445,7 +464,7 @@ fn render_preview(b: &mut dyn Backend, a: &Args) -> Result { let png = vectorcraft_format::base64_decode(encoded).ok_or("renderer returned bad base64")?; // The render was asked for at most 4096 a side. let img = super::handlers::decode_png(&png, 8192).map_err(|e| format!("read preview: {e}"))?; - let img = if img.width() > max || img.height() > max { img.thumbnail(max, max) } else { img }; + let img = if img.width() > max || img.height() > max { fitted(img, max, max, Resample::Average) } else { img }; let mut out = std::io::Cursor::new(Vec::new()); img.write_to(&mut out, image::ImageFormat::Png).map_err(|e| format!("encode preview: {e}"))?; Ok(image_result(out.get_ref(), json!({"width":img.width(),"height":img.height()}))) diff --git a/crates/mcp/src/tools/handlers.rs b/crates/mcp/src/tools/handlers.rs index 39d3f3f8e1..5aefa20d31 100644 --- a/crates/mcp/src/tools/handlers.rs +++ b/crates/mcp/src/tools/handlers.rs @@ -1,5 +1,6 @@ use super::dispatch::trace_views; use super::{Backend, Map, ToolResult, Value, json}; +use vectorcraft_doc::resample::{Resample, fitted}; // ---------- implementation ---------- @@ -521,7 +522,7 @@ fn fit_capture(png: Vec, max: Option, info: &mut Value) -> Result { - data: &'a [u8], - pos: usize, -} - -impl<'a> Reader<'a> { - pub fn new(data: &'a [u8]) -> Self { - Self { data, pos: 0 } - } - pub fn bytes(&mut self, n: usize) -> Option<&'a [u8]> { - let b = self.data.get(self.pos..self.pos.checked_add(n)?)?; - self.pos += n; - Some(b) - } - fn array(&mut self) -> Option<[u8; N]> { - self.bytes(N)?.try_into().ok() - } - pub fn u16(&mut self) -> Option { - self.array().map(u16::from_le_bytes) - } - pub fn i16(&mut self) -> Option { - self.array().map(i16::from_le_bytes) - } - pub fn u32(&mut self) -> Option { - self.array().map(u32::from_le_bytes) - } - pub fn i32(&mut self) -> Option { - self.array().map(i32::from_le_bytes) - } - pub fn f32(&mut self) -> Option { - self.array().map(f32::from_le_bytes) - } - pub fn skip(&mut self, n: usize) -> Option<()> { - self.bytes(n).map(drop) - } - /// The bytes not read yet. - pub fn rest(&self) -> &'a [u8] { - self.data.get(self.pos..).unwrap_or_default() - } -} - -/// `len` bytes of `data` from `offset` (record-relative offsets read from untrusted files). -pub(crate) fn slice(data: &[u8], offset: u32, len: u32) -> Option<&[u8]> { - let start = usize::try_from(offset).ok()?; - data.get(start..start.checked_add(usize::try_from(len).ok()?)?) -} diff --git a/crates/metafile/src/dib.rs b/crates/metafile/src/dib.rs index 4aeb5b4381..a1f1df8cc3 100644 --- a/crates/metafile/src/dib.rs +++ b/crates/metafile/src/dib.rs @@ -1,28 +1,24 @@ //! Device-independent bitmaps (DIBs), the pixels inside image records: written bottom-up as 24-bit -//! (opaque, composited over white) or 32-bit premultiplied BGRA (AlphaBlend's source); read from 1, -//! 4, 8, 16, 24 and 32-bit uncompressed and bit-field bitmaps and from embedded JPEG and PNG. +//! (opaque, composited over white) or 32-bit premultiplied BGRA (AlphaBlend's source). use std::io::Cursor; -use crate::bytes::Reader; +use vectorcraft_doc::resample::{Resample, resized}; /// Most pixels along a side of an image the writers store (larger ones are scaled down). const MAX_SIDE: u32 = 8192; /// Most pixels an image the writers store holds. const MAX_PIXELS: u64 = 1 << 24; -/// Most pixels along a side, and in all, of a bitmap the reader decodes. +/// Most pixels along a side, and in all, of a bitmap the PICT reader decodes. pub(crate) const MAX_READ_SIDE: u32 = 1 << 15; pub(crate) const MAX_READ_PIXELS: u64 = 1 << 26; /// Most pixels the bitmaps of one file may decode to together (four of the largest one), so a small /// file of many image records can't cost minutes of decoding (#3600). pub(crate) const MAX_FILE_PIXELS: u64 = 1 << 28; -/// What [`decode`] says of a bitmap past what is left of the file's budget. +/// What [`charge`] says of a bitmap past what is left of the file's budget. pub(crate) const OVER_BUDGET: &str = "the bitmaps hold more pixels than one file may"; const BI_RGB: u32 = 0; -const BI_BITFIELDS: u32 = 3; -const BI_JPEG: u32 = 4; -const BI_PNG: u32 = 5; /// Pixels with straight (not premultiplied) alpha, row by row from the top. #[derive(Clone, Debug, PartialEq)] @@ -42,7 +38,8 @@ impl Rgba { let img = if k > 1.0 { let nw = ((f64::from(w) / k).floor() as u32).max(1); let nh = ((f64::from(h) / k).floor() as u32).max(1); - image::imageops::resize(&img, nw, nh, image::imageops::FilterType::Triangle) + let how = Resample::Filter(image::imageops::FilterType::Triangle); + resized(image::DynamicImage::ImageRgba8(img), nw, nh, how).into_rgba8() } else { img }; @@ -121,48 +118,6 @@ pub(crate) fn bgra32(img: &Rgba, opacity: f32) -> (Vec, Vec) { (header(img.width, img.height, 32, bits.len()), bits) } -/// How the fourth byte of 32-bit pixels reads. -#[derive(Clone, Copy, PartialEq, Eq)] -pub(crate) enum Alpha { - /// Unused (StretchDIBits and BitBlt ignore it): every pixel opaque. - Ignore, - /// Premultiplied alpha (AlphaBlend with per-pixel alpha). - Premultiplied, -} - -/// A colour channel of `v` under `mask`, scaled to 0–255. -fn channel(v: u32, mask: u32) -> u8 { - if mask == 0 { - return 0; - } - let shift = mask.trailing_zeros(); - let max = u64::from(mask >> shift); - let x = u64::from((v & mask) >> shift); - ((x * 255 + max / 2) / max.max(1)).min(255) as u8 -} - -/// PNG `bytes` without its compressed or text ancillary chunks (`iCCP`, `zTXt`, `iTXt`, `tEXt`), -/// which the pixels don't need and which a decoder expands when it is made. Other bytes, and a PNG -/// whose chunks don't read to the end, are returned as they are. -fn png_without_metadata(bytes: &[u8]) -> std::borrow::Cow<'_, [u8]> { - const SIGNATURE: &[u8] = b"\x89PNG\r\n\x1a\n"; - if !bytes.starts_with(SIGNATURE) { - return bytes.into(); - } - let mut out = SIGNATURE.to_vec(); - let mut at = SIGNATURE.len(); - while at < bytes.len() { - let (Some(len), Some(kind)) = (bytes.get(at..at + 4), bytes.get(at + 4..at + 8)) else { return bytes.into() }; - let len = u32::from_be_bytes([len[0], len[1], len[2], len[3]]) as usize; - let Some(end) = at.checked_add(12).and_then(|n| n.checked_add(len)).filter(|end| *end <= bytes.len()) else { return bytes.into() }; - if !matches!(kind, b"iCCP" | b"zTXt" | b"iTXt" | b"tEXt") { - out.extend_from_slice(&bytes[at..end]); - } - at = end; - } - out.into() -} - /// Take a bitmap of `w` × `h` from what is `left` of the file's budget, before it is decoded. pub(crate) fn charge(w: u32, h: u32, left: &mut u64) -> Result<(), String> { let n = u64::from(w) * u64::from(h); @@ -170,215 +125,24 @@ pub(crate) fn charge(w: u32, h: u32, left: &mut u64) -> Result<(), String> { Ok(()) } -/// Read a DIB from its BITMAPINFO (`bmi`: the header and colour table) and pixel `bits`, taking its -/// pixels from what is `left` of the file's budget ([`MAX_FILE_PIXELS`]). -pub(crate) fn decode(bmi: &[u8], bits: &[u8], alpha: Alpha, left: &mut u64) -> Result { - let bad = || "a bitmap is damaged".to_string(); - let mut r = Reader::new(bmi); - let size = r.u32().ok_or_else(bad)?; - let (width, height, bpp, compression, colors, palette_entry, masks_at) = if size == 12 { - // BITMAPCOREHEADER: 16-bit sizes, RGB triples. - let w = i32::from(r.u16().ok_or_else(bad)?); - let h = i32::from(r.u16().ok_or_else(bad)?); - r.skip(2).ok_or_else(bad)?; - let bpp = r.u16().ok_or_else(bad)?; - (w, h, bpp, BI_RGB, 0, 3, 0) - } else if size >= 40 { - let w = r.i32().ok_or_else(bad)?; - let h = r.i32().ok_or_else(bad)?; - r.skip(2).ok_or_else(bad)?; - let bpp = r.u16().ok_or_else(bad)?; - let c = r.u32().ok_or_else(bad)?; - r.skip(12).ok_or_else(bad)?; - let used = r.u32().ok_or_else(bad)?; - (w, h, bpp, c, used, 4, 40) - } else { - return Err(bad()); - }; - if compression == BI_JPEG || compression == BI_PNG { - // The size comes from the image header, so an over-limit bitmap is refused before any pixels are decoded. - // A PNG's compressed ICC profile and text chunks expand when its decoder is made, and - // nothing here uses them: they are left out before the size is read and the pixels decoded. - let bits = png_without_metadata(bits); - let (w, h) = image::ImageReader::new(Cursor::new(&*bits)).with_guessed_format().map_err(|_| bad())?.into_dimensions().map_err(|_| bad())?; - if w > MAX_READ_SIDE || h > MAX_READ_SIDE || u64::from(w) * u64::from(h) > MAX_READ_PIXELS { - return Err("a bitmap is too large to read".into()); - } - charge(w, h, left)?; - let img = image::load_from_memory(&bits).map_err(|_| bad())?.to_rgba8(); - return Ok(Rgba { width: w, height: h, pixels: img.into_raw() }); - } - if compression != BI_RGB && compression != BI_BITFIELDS { - return Err("compressed (RLE) bitmaps can't be read yet".into()); - } - let top_down = height < 0; - let (w, h) = (width.unsigned_abs(), height.unsigned_abs()); - if w == 0 || h == 0 { - return Err("a bitmap is empty".into()); - } - if w > MAX_READ_SIDE || h > MAX_READ_SIDE || u64::from(w) * u64::from(h) > MAX_READ_PIXELS { - return Err("a bitmap is too large to read".into()); - } - let header_len = size as usize; - // Bit-field masks follow a plain 40-byte header, or sit inside the larger ones. - let fields = compression == BI_BITFIELDS; - let masks: Option<[u32; 4]> = fields.then(|| { - let mut m = Reader::new(bmi.get(masks_at..).unwrap_or_default()); - let rgb = [m.u32().unwrap_or(0), m.u32().unwrap_or(0), m.u32().unwrap_or(0)]; - // An alpha mask comes with BITMAPV3INFOHEADER and later. - let a = if header_len >= 56 { m.u32().unwrap_or(0) } else { 0 }; - [rgb[0], rgb[1], rgb[2], a] - }); - let palette_at = header_len + if fields && header_len == 40 { 12 } else { 0 }; - let bpp_u = u32::from(bpp); - let palette: Vec<[u8; 3]> = if bpp_u <= 8 { - let n = if colors == 0 { 1usize << bpp_u } else { (colors as usize).min(256) }; - bmi.get(palette_at..) - .unwrap_or_default() - .chunks_exact(palette_entry) - .take(n) - .map(|e| [e.get(2).copied().unwrap_or(0), e.get(1).copied().unwrap_or(0), e.first().copied().unwrap_or(0)]) - .collect() - } else { - vec![] - }; - if !matches!(bpp, 1 | 4 | 8 | 16 | 24 | 32) { - return Err(format!("{bpp}-bit bitmaps can't be read")); - } - let row = stride(w, bpp_u).ok_or_else(bad)?; - if bits.len() < row.checked_mul(h as usize).ok_or_else(bad)? { - return Err(bad()); - } - charge(w, h, left)?; - let (mr, mg, mb, ma) = match (masks, bpp) { - (Some([r, g, b, a]), _) => (r, g, b, a), - (None, 16) => (0x7c00, 0x03e0, 0x001f, 0), - _ => (0x00ff_0000, 0x0000_ff00, 0x0000_00ff, 0xff00_0000), - }; - let mut pixels = Vec::with_capacity(w as usize * h as usize * 4); - for y in 0..h as usize { - let src_row = if top_down { y } else { h as usize - 1 - y }; - let line = bits.get(src_row * row..src_row * row + row).ok_or_else(bad)?; - for x in 0..w as usize { - let px: [u8; 4] = match bpp { - 1 | 4 | 8 => { - let bit = x * bpp_u as usize; - let byte = line.get(bit / 8).copied().unwrap_or(0); - let idx = (byte >> (8 - bpp_u as usize - bit % 8)) & ((1u16 << bpp_u) - 1) as u8; - let [r, g, b] = palette.get(idx as usize).copied().unwrap_or([0, 0, 0]); - [r, g, b, 255] - } - 16 => { - let v = u32::from(u16::from_le_bytes([line.get(x * 2).copied().unwrap_or(0), line.get(x * 2 + 1).copied().unwrap_or(0)])); - [channel(v, mr), channel(v, mg), channel(v, mb), 255] - } - 24 => { - let p = line.get(x * 3..x * 3 + 3).unwrap_or(&[0, 0, 0]); - [p[2], p[1], p[0], 255] - } - _ => { - let p = line.get(x * 4..x * 4 + 4).unwrap_or(&[0, 0, 0, 0]); - let v = u32::from_le_bytes([p[0], p[1], p[2], p[3]]); - let a = if alpha == Alpha::Premultiplied && ma != 0 { channel(v, ma) } else { 255 }; - let un = - |c: u8| if alpha == Alpha::Premultiplied && a < 255 { (u32::from(c) * 255 / u32::from(a.max(1))).min(255) as u8 } else { c }; - [un(channel(v, mr)), un(channel(v, mg)), un(channel(v, mb)), if alpha == Alpha::Premultiplied { a } else { 255 }] - } - }; - pixels.extend_from_slice(&px); - } - } - Ok(Rgba { width: w, height: h, pixels }) -} - -/// A packed DIB (a BITMAPINFO and its bits, one after the other, as WMF records hold them) split -/// into the two. -pub(crate) fn split(packed: &[u8]) -> Option<(&[u8], &[u8])> { - let mut r = Reader::new(packed); - let size = r.u32()? as usize; - let (bpp, compression, used, entry) = if size == 12 { - r.skip(6)?; - (r.u16()?, BI_RGB, 0, 3) - } else { - r.skip(10)?; - let bpp = r.u16()?; - let c = r.u32()?; - r.skip(12)?; - (bpp, c, r.u32()? as usize, 4) - }; - let masks = if compression == BI_BITFIELDS && size == 40 { 12 } else { 0 }; - let colors = if used > 0 { - used.min(256) - } else if bpp <= 8 { - 1usize << bpp - } else { - 0 - }; - let len = size.checked_add(masks)?.checked_add(colors * entry)?; - Some((packed.get(..len)?, packed.get(len..)?)) -} - #[cfg(test)] mod tests { use super::*; - #[test] - fn a_pngs_compressed_metadata_is_left_out_before_it_is_decoded() { - use image::ImageEncoder; - let mut png = vec![]; - let mut encoder = image::codecs::png::PngEncoder::new(&mut png); - encoder.set_icc_profile(vec![0; 1 << 20]).unwrap(); - encoder.write_image(&[10, 20, 30], 1, 1, image::ExtendedColorType::Rgb8).unwrap(); - assert!(png.windows(4).any(|w| w == b"iCCP")); - let stripped = png_without_metadata(&png); - assert!(!stripped.windows(4).any(|w| w == b"iCCP") && stripped.len() < png.len()); - let img = image::load_from_memory(&stripped).unwrap().to_rgba8(); - assert_eq!(img.get_pixel(0, 0).0, [10, 20, 30, 255]); - // Not a PNG, or a PNG cut short: unchanged. - assert_eq!(&*png_without_metadata(b"BM...."), b"BM...."); - assert_eq!(&*png_without_metadata(&png[..png.len() - 3]), &png[..png.len() - 3]); - } - fn sample() -> Rgba { // 3 × 2: red, green, blue / half-transparent black, transparent, white. let pixels = vec![255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 0, 0, 0, 128, 0, 0, 0, 0, 255, 255, 255, 255]; Rgba { width: 3, height: 2, pixels } } - /// A whole file's budget. - fn budget() -> u64 { - MAX_FILE_PIXELS - } - - /// A BITMAPINFOHEADER of an embedded PNG. - fn png_header() -> Vec { - let mut bmi = vec![0u8; 40]; - bmi[..4].copy_from_slice(&40u32.to_le_bytes()); - bmi[16..20].copy_from_slice(&BI_PNG.to_le_bytes()); - bmi - } - - #[test] - fn oversized_png_is_refused_from_its_header() { - // A width over the limit in the IHDR chunk: decoding the pixels would fail with a different error. - let png = crate::tests::png_claiming(MAX_READ_SIDE + 1, 1); - let err = decode(&png_header(), &png, Alpha::Ignore, &mut budget()).unwrap_err(); - assert_eq!(err, "a bitmap is too large to read"); - } - #[test] fn bitmaps_share_the_file_budget() { // #3600: each bitmap is charged before it is decoded, and one past what is left is refused. - let (bmi, bits) = rgb24(&sample(), 1.0); let mut left = 6 + 5; - assert!(decode(&bmi, &bits, Alpha::Ignore, &mut left).is_ok()); + assert!(charge(3, 2, &mut left).is_ok()); assert_eq!(left, 5); - assert_eq!(decode(&bmi, &bits, Alpha::Ignore, &mut left).unwrap_err(), OVER_BUDGET); + assert_eq!(charge(3, 2, &mut left).unwrap_err(), OVER_BUDGET); assert_eq!(left, 5, "a refused bitmap costs nothing"); - // An embedded PNG is charged from its header, so one past the budget is never decoded. - let mut left = (1 << 20) - 1; - let png = crate::tests::png_claiming(1 << 10, 1 << 10); - assert_eq!(decode(&png_header(), &png, Alpha::Ignore, &mut left).unwrap_err(), OVER_BUDGET); } #[test] @@ -402,49 +166,24 @@ mod tests { assert_eq!(&half[12..16], &[0, 0, 128, 128]); } - #[test] - fn rgb24_round_trips_over_white() { - let (bmi, bits) = rgb24(&sample(), 1.0); - assert_eq!(bmi.len(), 40); - // Rows of 9 bytes padded to 12. - assert_eq!(bits.len(), 24); - let back = decode(&bmi, &bits, Alpha::Ignore, &mut budget()).unwrap(); - assert_eq!((back.width, back.height), (3, 2)); - assert_eq!(&back.pixels[..12], &[255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255]); - // Half-transparent black over white is mid grey; transparent is white. - assert_eq!(&back.pixels[12..16], &[127, 127, 127, 255]); - assert_eq!(&back.pixels[16..20], &[255, 255, 255, 255]); - } - - #[test] - fn bgra32_round_trips_with_alpha() { - let (bmi, bits) = bgra32(&sample(), 1.0); - let back = decode(&bmi, &bits, Alpha::Premultiplied, &mut budget()).unwrap(); - assert_eq!(&back.pixels[..12], &sample().pixels[..12]); - assert_eq!(back.pixels[15], 128); - assert_eq!(back.pixels[19], 0); - // Read as StretchDIBits does, alpha is ignored. - assert!(decode(&bmi, &bits, Alpha::Ignore, &mut budget()).unwrap().opaque()); - } - - #[test] - fn palette_bitmaps_and_damage() { - // A 1-bit 2 × 1 bitmap: black then white. - let mut bmi = header(2, 1, 1, 4); - bmi.extend_from_slice(&[0, 0, 0, 0, 255, 255, 255, 0]); - let back = decode(&bmi, &[0b0100_0000, 0, 0, 0], Alpha::Ignore, &mut budget()).unwrap(); - assert_eq!(back.pixels, vec![0, 0, 0, 255, 255, 255, 255, 255]); - // Too few bits, a silly size, an unknown depth: errors, no panic. - assert!(decode(&bmi, &[0], Alpha::Ignore, &mut budget()).is_err()); - assert!(decode(&header(1 << 20, 1 << 20, 24, 0), &[], Alpha::Ignore, &mut budget()).is_err()); - assert!(decode(&header(1, 1, 7, 0), &[0; 4], Alpha::Ignore, &mut budget()).is_err()); - assert!(decode(&[1, 2], &[], Alpha::Ignore, &mut budget()).is_err()); - } - #[test] fn large_images_are_scaled_to_fit() { let img = image::RgbaImage::new(MAX_SIDE * 2, 4); let f = Rgba::fitted(img); assert_eq!((f.width, f.height), (MAX_SIDE, 2)); } + + /// A large image scaled to fit keeps the color of its opaque pixels beside clear ones: the + /// clear black beside them does not darken them. + #[test] + fn large_images_keep_their_color_beside_clear_pixels() { + let img = + image::RgbaImage::from_fn(MAX_SIDE * 2, 4, |x, _| if x % 2 == 0 { image::Rgba([200, 30, 30, 255]) } else { image::Rgba([0, 0, 0, 0]) }); + let f = Rgba::fitted(img); + assert_eq!((f.width, f.height), (MAX_SIDE, 2)); + let m = |c: u8, a: u8| (u16::from(c) * u16::from(a) / 255) as u8; + for p in f.pixels.as_chunks::<4>().0 { + assert!(p[3] > 0 && [200, 30, 30].iter().zip(p).all(|(&want, &c)| m(c, p[3]).abs_diff(m(want, p[3])) <= 1), "{p:?}"); + } + } } diff --git a/crates/metafile/src/import.rs b/crates/metafile/src/import.rs index da7816663e..c87dd83d72 100644 --- a/crates/metafile/src/import.rs +++ b/crates/metafile/src/import.rs @@ -1,16 +1,14 @@ -//! The metafile reader: the format parsers (`emf`, `wmf`, and `pict` for QuickDraw pictures) play -//! their records on a [`Player`], a small model of the device context they draw into (objects, -//! transforms, the current position, the path bracket, the clip), which turns what they draw into -//! document objects. +//! The metafile readers. EMF (with its EMF+ records) and WMF files are read by `craft_metafile`, +//! and `picture` turns what they draw into document objects. QuickDraw pictures (`pict`) play their +//! opcodes on a [`Player`], a small model of the drawing state (pen, brush, font, the clip), which +//! turns what they draw into document objects. //! //! Fills and strokes become paths with a fill and a stroke; lines drawn one after another with the //! same pen join into one path. Clips become clipping groups around what they clip. Images keep -//! their pixels (as PNG), text becomes point type in the font the file names. Records the reader -//! doesn't know are counted and skipped, with one warning. +//! their pixels (as PNG), text becomes point type in the font the file names. -mod emf; pub(crate) mod pict; -mod wmf; +mod picture; use std::sync::Arc; @@ -20,7 +18,7 @@ use vectorcraft_doc::{ Appearance, AppearanceItem, CharStyle, Dash, Document, FillLayer, ImageBlob, ImageObject, Justify, LayerColor, LineCap, LineJoin, Node, NodeKind, StrokeLayer, TextObject, }; -use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, PathEl, Point, Rect, Shape, Vec2, shapes}; +use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, PathEl, Point, Rect, Shape, shapes}; use crate::dib::{self, Rgba}; use crate::{Imported, Kind}; @@ -30,24 +28,13 @@ const MAX_NODES: usize = 1 << 20; /// Objects and clips reaching further than this from the origin (points, well inside the canvas) /// are left out: they come from damaged or hostile coordinates. const LIMIT: f64 = 1e6; -/// Most nested saved device contexts. -const MAX_SAVED: usize = 1024; /// Width of a cosmetic pen (one pixel of a 96 ppi screen), points. const HAIRLINE: f64 = 0.75; -/// Curves made for arcs and ellipses are this close to the true curve (logical units are -/// transformed after, so it is relative). -const ARC_TOLERANCE: f64 = 0.01; /// Raster operations. pub(crate) const SRCCOPY: u32 = 0x00CC_0020; -const PATCOPY: u32 = 0x00F0_0021; -const WHITENESS: u32 = 0x00FF_0062; -const BLACKNESS: u32 = 0x0000_0042; const SKIPPED_ROPS: &str = "images drawn with raster operations other than a plain copy (masks, inversions) were left out"; -const HATCHES: &str = "hatched brushes are filled with their colour"; -const PATTERN_BRUSHES: &str = "pattern brushes are filled grey"; -const EXCLUDED_CLIPS: &str = "clip areas cut out of the clip (excluded rectangles, differences) are ignored"; const BAD_IMAGE: &str = "an image that couldn't be read was left out"; const TOO_MANY_PIXELS: &str = "images past the most pixels one file may hold were left out"; const FAR_AWAY: &str = "objects far outside the picture were left out"; @@ -57,6 +44,58 @@ fn sane(r: Rect) -> bool { [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite() && v.abs() <= LIMIT) } +/// Is `path` one upright rectangle around the whole of `frame`? Writers clip to one first; it clips +/// nothing in the picture. A path of more than one figure is not one rectangle, even when its +/// figures run along the sides of a box. Nor is one figure that runs back over its own edges, so +/// that it encloses less than the whole box. +fn around(path: &BezPath, frame: Rect) -> bool { + if path.elements().len() > 6 { + return false; + } + let b = path.bounding_box(); + let corners = [Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x1, b.y1), Point::new(b.x0, b.y1)]; + let near = |p: Point, q: Point| (p - q).hypot() <= 1e-6 * (1.0 + b.width().max(b.height())); + // Each edge, the closing one included, runs along a side: from a corner to itself or to a + // neighbor (corners are in order around the box), never across it. + let along = |i: usize, j: usize| (i + 4 - j) % 4 != 2; + let mut seen = [false; 4]; + let mut points = Vec::with_capacity(6); + let (mut first, mut last) = (None, None); + for e in path.elements() { + let (p, start) = match e { + PathEl::MoveTo(p) => (*p, true), + PathEl::LineTo(p) => (*p, false), + PathEl::ClosePath => continue, + PathEl::QuadTo(..) | PathEl::CurveTo(..) => return false, + }; + let Some(i) = corners.iter().position(|c| near(*c, p)) else { return false }; + if start { + if first.is_some() { + return false; + } + first = Some(i); + } else if last.is_some_and(|l| !along(l, i)) { + return false; + } + last = Some(i); + seen[i] = true; + points.push(corners[i]); + } + if let (Some(f), Some(l)) = (first, last) + && !along(f, l) + { + return false; + } + // Every edge runs along a side, so the figure winds the same number of times around every + // point inside the box: once, when its area is the box's. + let twice_area: f64 = points.iter().zip(points.iter().cycle().skip(1)).map(|(p, q)| (*p - corners[0]).cross(*q - corners[0])).sum(); + if (twice_area.abs() - 2.0 * b.area()).abs() > 1e-6 * (1.0 + 2.0 * b.area()) { + return false; + } + let b = b.inflate(0.5, 0.5); + seen.iter().all(|s| *s) && b.contains(frame.origin()) && b.contains(Point::new(frame.x1, frame.y1)) +} + /// A pen: its style flags (`PS_*`), width in logical units, colour and dash entries. #[derive(Clone, Debug, PartialEq)] pub(crate) struct PenObj { @@ -68,7 +107,6 @@ pub(crate) struct PenObj { } impl PenObj { - pub const NULL: PenObj = PenObj { style: PS_NULL, width: 0.0, color: [0; 3], entries: vec![] }; pub fn solid(color: [u8; 3]) -> Self { Self { style: 0, width: 0.0, color, entries: vec![] } } @@ -77,28 +115,6 @@ impl PenObj { pub(crate) const PS_NULL: u32 = 5; const PS_GEOMETRIC: u32 = 0x0001_0000; -/// A brush. -#[derive(Clone, Debug, PartialEq)] -pub(crate) enum BrushObj { - Null, - Solid([u8; 3]), - Hatched([u8; 3]), - /// A bitmap pattern (written grey). - Pattern, -} - -impl BrushObj { - /// From a LOGBRUSH's style and colour. - pub fn from_log(style: u32, color: [u8; 3]) -> Self { - match style { - 0 => Self::Solid(color), - 1 => Self::Null, - 2 => Self::Hatched(color), - _ => Self::Pattern, - } - } -} - /// A font: its height in logical units (negative: the character height, positive: the cell /// height), escapement (tenths of a degree), weight, italics and face. #[derive(Clone, Debug, Default, PartialEq)] @@ -110,35 +126,17 @@ pub(crate) struct FontObj { pub face: String, } -/// A GDI object. -#[derive(Clone, Debug)] -pub(crate) enum Obj { - Pen(PenObj), - Brush(BrushObj), - Font(FontObj), - /// Palettes, regions, colour spaces: they take a slot but don't change the drawing. - Other, -} - -/// The state records change, saved and restored as a whole. +/// The drawing state. #[derive(Clone, Debug)] struct Dc { pen: PenObj, - brush: BrushObj, + /// The brush's color. + brush: [u8; 3], font: FontObj, text_color: [u8; 3], text_align: u32, fill_rule: FillRule, miter: f64, - /// Arcs run counterclockwise (the default). - arc_ccw: bool, - /// Logical → page (EMF world transform). - world: Affine, - map_mode: u32, - win_org: Vec2, - win_ext: Vec2, - vp_org: Vec2, - vp_ext: Vec2, clips: Vec>, } @@ -146,105 +144,38 @@ impl Default for Dc { fn default() -> Self { Self { pen: PenObj::solid([0; 3]), - brush: BrushObj::Solid([255; 3]), + brush: [255; 3], font: FontObj::default(), text_color: [0; 3], text_align: 0, fill_rule: FillRule::EvenOdd, miter: 10.0, - arc_ccw: true, - world: Affine::IDENTITY, - map_mode: 1, - win_org: Vec2::ZERO, - win_ext: Vec2::new(1.0, 1.0), - vp_org: Vec2::ZERO, - vp_ext: Vec2::new(1.0, 1.0), clips: vec![], } } } -/// How an arc closes. -#[derive(Clone, Copy, PartialEq, Eq)] -pub(crate) enum ArcKind { - Open, - Chord, - Pie, -} - pub(crate) struct Player { kind: Kind, - /// Device units (EMF) or logical units (WMF) → document points. + /// Picture units → document points. dev_to_doc: Affine, - /// Millimetres per device pixel (EMF's fixed mapping modes). - mm_per_px: f64, dc: Dc, - saved: Vec, - objects: Vec>, - /// The lowest object slot that may be free (WMF numbering). - free_hint: usize, - /// The path being recorded (document space), whether a figure is open in it and where that - /// figure started (logical). - path: Option, - figure: bool, - figure_start: Point, /// The artboard (document space): clips holding all of it clip nothing worth keeping. frame: Rect, - /// The current position (logical). - pos: Point, - /// Lines drawn one after another outside a path bracket, not drawn yet. + /// Lines drawn one after another, not drawn yet. pending: BezPath, out: Drawn, doc: Document, warnings: Vec, - skipped: usize, next_clip: u32, /// Pixels the file's bitmaps may still decode to ([`dib::MAX_FILE_PIXELS`]). pub pixels_left: u64, - /// The file holds EMF+ records (which aren't read). - pub emf_plus: bool, } fn rgb(c: [u8; 3]) -> Paint { Paint::solid(Color::rgb8(c[0], c[1], c[2])) } -/// The arc of the ellipse in `r` from the ray through `start` to the ray through `end`. -pub(crate) fn arc_path(r: Rect, start: Point, end: Point, ccw: bool, kind: ArcKind) -> BezPath { - let r = r.abs(); - let c = r.center(); - let radii = Vec2::new(r.width() / 2.0, r.height() / 2.0); - let mut bp = BezPath::new(); - if radii.x <= 0.0 || radii.y <= 0.0 { - return bp; - } - let angle = |p: Point| ((p.y - c.y) / radii.y).atan2((p.x - c.x) / radii.x); - let (a0, a1) = (angle(start), angle(end)); - let tau = std::f64::consts::TAU; - // Counterclockwise on a y-down device is towards smaller angles. - let sweep = if ccw { - let s = (a0 - a1).rem_euclid(tau); - -(if s == 0.0 { tau } else { s }) - } else { - let s = (a1 - a0).rem_euclid(tau); - if s == 0.0 { tau } else { s } - }; - let arc = kurbo::Arc { center: c, radii, start_angle: a0, sweep_angle: sweep, x_rotation: 0.0 }; - let tol = ARC_TOLERANCE * radii.x.max(radii.y).max(1e-9); - if kind == ArcKind::Pie { - bp.move_to(c); - let first = c + Vec2::new(radii.x * a0.cos(), radii.y * a0.sin()); - bp.line_to(first); - arc.append_iter(tol).for_each(|el| bp.push(el)); - } else { - kurbo::Shape::path_elements(&arc, tol).for_each(|el| bp.push(el)); - } - if kind != ArcKind::Open { - bp.close_path(); - } - bp -} - /// A rectangle with elliptical corners `rx` × `ry`. pub(crate) fn round_rect(r: Rect, rx: f64, ry: f64) -> BezPath { let r = r.abs(); @@ -261,7 +192,7 @@ pub(crate) fn round_rect(r: Rect, rx: f64, ry: f64) -> BezPath { } impl Player { - fn new(kind: Kind, dev_to_doc: Affine, mm_per_px: f64, artboard: Rect) -> Self { + fn new(kind: Kind, dev_to_doc: Affine, artboard: Rect) -> Self { let side = |v: f64| if v.is_finite() { v.clamp(1.0, LIMIT) } else { 1.0 }; let (w, h) = (side(artboard.width()), side(artboard.height())); let mut doc = Document::new(w, h); @@ -269,24 +200,14 @@ impl Player { Self { kind, dev_to_doc, - mm_per_px, dc: Dc::default(), - saved: vec![], - objects: vec![], - free_hint: 0, - path: None, - figure: false, - figure_start: Point::ZERO, frame: artboard, - pos: Point::ZERO, pending: BezPath::new(), out: vec![], doc, warnings: vec![], - skipped: 0, next_clip: 0, pixels_left: dib::MAX_FILE_PIXELS, - emf_plus: false, } } @@ -296,188 +217,19 @@ impl Player { } } - /// A record of a kind the reader doesn't know. - pub fn skip(&mut self) { - self.skipped += 1; - } - // ---------- mapping ---------- - /// Logical → document. + /// Picture units → document. fn xf(&self) -> Affine { - if self.kind == Kind::Wmf { - return self.dev_to_doc; - } - let d = &self.dc; - let page_to_dev = match d.map_mode { - // Fixed modes: millimetres a unit, y up. - 2..=6 => { - let mm = [0.1, 0.01, 0.254, 0.0254, 25.4 / 1440.0][(d.map_mode - 2) as usize]; - let s = mm / self.mm_per_px.max(1e-12); - Affine::translate(d.vp_org) * Affine::scale_non_uniform(s, -s) * Affine::translate(-d.win_org) - } - 7 | 8 => { - let ratio = |v: f64, w: f64| if w.abs() > 1e-12 && v.is_finite() { v / w } else { 1.0 }; - let (mut sx, mut sy) = (ratio(d.vp_ext.x, d.win_ext.x), ratio(d.vp_ext.y, d.win_ext.y)); - if d.map_mode == 7 { - // Isotropic: the same scale both ways, the smaller one. - let s = sx.abs().min(sy.abs()); - (sx, sy) = (s.copysign(sx), s.copysign(sy)); - } - Affine::translate(d.vp_org) * Affine::scale_non_uniform(sx, sy) * Affine::translate(-d.win_org) - } - _ => Affine::translate(d.vp_org - d.win_org), - }; - self.dev_to_doc * page_to_dev * d.world + self.dev_to_doc } - /// How much logical lengths grow in the document. + /// How much picture lengths grow in the document. fn scale(&self) -> f64 { let s = self.xf().determinant().abs().sqrt(); if s.is_finite() { s } else { 0.0 } } - pub fn set_map_mode(&mut self, m: u32) { - self.dc.map_mode = m; - } - pub fn set_window_org(&mut self, x: f64, y: f64) { - self.dc.win_org = Vec2::new(x, y); - } - pub fn set_window_ext(&mut self, x: f64, y: f64) { - self.dc.win_ext = Vec2::new(x, y); - } - pub fn set_viewport_org(&mut self, x: f64, y: f64) { - self.dc.vp_org = Vec2::new(x, y); - } - pub fn set_viewport_ext(&mut self, x: f64, y: f64) { - self.dc.vp_ext = Vec2::new(x, y); - } - pub fn scale_ext(&mut self, window: bool, x: (f64, f64), y: (f64, f64)) { - let e = if window { &mut self.dc.win_ext } else { &mut self.dc.vp_ext }; - if x.1 != 0.0 && y.1 != 0.0 { - *e = Vec2::new(e.x * x.0 / x.1, e.y * y.0 / y.1); - } - } - /// `SetWorldTransform` / `ModifyWorldTransform` (`mode`: 1 identity, 2 left, 3 right, 4 set). - pub fn world(&mut self, x: Affine, mode: u32) { - if !x.as_coeffs().iter().all(|v| v.is_finite()) { - return; - } - self.dc.world = match mode { - 1 => Affine::IDENTITY, - 2 => self.dc.world * x, - 3 => x * self.dc.world, - _ => x, - }; - } - - // ---------- state ---------- - - pub fn set_fill_mode(&mut self, alternate: bool) { - self.dc.fill_rule = if alternate { FillRule::EvenOdd } else { FillRule::NonZero }; - } - pub fn set_miter(&mut self, m: f64) { - if m.is_finite() && m >= 1.0 { - self.dc.miter = m; - } - } - pub fn set_arc_ccw(&mut self, ccw: bool) { - self.dc.arc_ccw = ccw; - } - pub fn set_text_color(&mut self, c: [u8; 3]) { - self.dc.text_color = c; - } - pub fn set_text_align(&mut self, a: u32) { - self.dc.text_align = a; - } - - pub fn save(&mut self) { - if self.saved.len() < MAX_SAVED { - self.saved.push(self.dc.clone()); - } - } - - /// `RestoreDC(n)`: a negative `n` counts back from the latest save, a positive one is a save's - /// number. - pub fn restore(&mut self, n: i32) { - let len = self.saved.len(); - let keep = if n < 0 { len.checked_sub(n.unsigned_abs() as usize) } else { (n as usize).checked_sub(1).filter(|k| *k < len) }; - if let Some(k) = keep { - self.saved.truncate(k + 1); - if let Some(dc) = self.saved.pop() { - self.dc = dc; - } - } - } - - // ---------- objects ---------- - - /// Put `obj` in slot `index` (EMF numbers its objects). - pub fn create_at(&mut self, index: u32, obj: Obj) { - let i = index as usize; - if i == 0 || i > u16::MAX as usize { - return; - } - if self.objects.len() <= i { - self.objects.resize(i + 1, None); - } - if let Some(s) = self.objects.get_mut(i) { - *s = Some(obj); - } - } - - /// Put `obj` in the lowest free slot (WMF). - pub fn create(&mut self, obj: Obj) { - let start = self.free_hint.min(self.objects.len()); - let i = self.objects.iter().skip(start).position(Option::is_none).map_or(self.objects.len(), |p| p + start); - if i > u16::MAX as usize { - // The table is full past the hint: the next creation looks from the end, not again - // through every slot. - self.free_hint = i; - return; - } - if i == self.objects.len() { - self.objects.push(None); - } - if let Some(s) = self.objects.get_mut(i) { - *s = Some(obj); - } - self.free_hint = i + 1; - } - - pub fn delete(&mut self, index: u32) { - if let Some(s) = self.objects.get_mut(index as usize) { - *s = None; - self.free_hint = self.free_hint.min(index as usize); - } - } - - /// Select object `index`, or a stock object (EMF: the high bit set). - pub fn select(&mut self, index: u32) { - if self.kind == Kind::Emf && index & 0x8000_0000 != 0 { - match index & 0x7fff_ffff { - 0 | 18 => self.dc.brush = BrushObj::Solid([255; 3]), - 1 => self.dc.brush = BrushObj::Solid([0xc0; 3]), - 2 => self.dc.brush = BrushObj::Solid([0x80; 3]), - 3 => self.dc.brush = BrushObj::Solid([0x40; 3]), - 4 => self.dc.brush = BrushObj::Solid([0; 3]), - 5 => self.dc.brush = BrushObj::Null, - 6 => self.dc.pen = PenObj::solid([255; 3]), - 7 | 19 => self.dc.pen = PenObj::solid([0; 3]), - 8 => self.dc.pen = PenObj::NULL, - 10..=17 => self.dc.font = FontObj::default(), - _ => {} - } - return; - } - match self.objects.get(index as usize).cloned().flatten() { - Some(Obj::Pen(p)) => self.dc.pen = p, - Some(Obj::Brush(b)) => self.dc.brush = b, - Some(Obj::Font(f)) => self.dc.font = f, - _ => {} - } - } - // ---------- output ---------- fn push(&mut self, mut node: Node) { @@ -491,19 +243,8 @@ impl Player { self.out.push((self.dc.clips.clone(), node)); } - fn fill_paint(&mut self) -> Option { - match self.dc.brush.clone() { - BrushObj::Null => None, - BrushObj::Solid(c) => Some(rgb(c)), - BrushObj::Hatched(c) => { - self.warn(HATCHES); - Some(rgb(c)) - } - BrushObj::Pattern => { - self.warn(PATTERN_BRUSHES); - Some(rgb([0x80; 3])) - } - } + fn fill_paint(&self) -> Paint { + rgb(self.dc.brush) } fn stroke_layer(&self) -> Option { @@ -549,8 +290,8 @@ impl Player { return; } let mut items = vec![]; - if fill && let Some(p) = self.fill_paint() { - items.push(AppearanceItem::Fill(FillLayer::new(p))); + if fill { + items.push(AppearanceItem::Fill(FillLayer::new(self.fill_paint()))); } if stroke && let Some(st) = self.stroke_layer() { items.push(AppearanceItem::Stroke(st)); @@ -573,124 +314,7 @@ impl Player { } } - /// A figure in logical units: added to the path being recorded, else drawn (filled when it is - /// an area). - pub fn figure(&mut self, mut bp: BezPath, area: bool) { - bp.apply_affine(self.xf()); - match &mut self.path { - Some(path) => { - path.extend(bp); - self.figure = false; - } - None => self.draw(bp, area, true), - } - } - - /// Polygon / Polyline (and Bézier ones): `pts` in logical units. - pub fn poly(&mut self, pts: &[Point], closed: bool, bezier: bool) { - let Some((first, rest)) = pts.split_first() else { return }; - let mut bp = BezPath::new(); - bp.move_to(*first); - if bezier { - for c in rest.as_chunks::<3>().0 { - bp.curve_to(c[0], c[1], c[2]); - } - } else { - rest.iter().for_each(|p| bp.line_to(*p)); - } - if closed { - bp.close_path(); - } - self.figure(bp, closed); - } - - /// Several polygons (one area) or polylines. - pub fn poly_poly(&mut self, polys: &[Vec], closed: bool) { - let mut bp = BezPath::new(); - for p in polys { - let Some((first, rest)) = p.split_first() else { continue }; - bp.move_to(*first); - rest.iter().for_each(|q| bp.line_to(*q)); - if closed { - bp.close_path(); - } - } - self.figure(bp, closed); - } - - pub fn move_to(&mut self, p: Point) { - self.pos = p; - self.figure = false; - } - - /// LineTo / PolylineTo / PolyBezierTo: from the current position through `pts` (logical). - pub fn poly_to(&mut self, pts: &[Point], bezier: bool) { - let Some(last) = pts.last().copied() else { return }; - let xf = self.xf(); - let start = xf * self.pos; - let target = match &mut self.path { - Some(path) => { - if !self.figure { - path.move_to(start); - self.figure = true; - self.figure_start = self.pos; - } - path - } - None => { - if self.pending.elements().last().and_then(|e| e.end_point()) != Some(start) { - self.pending.move_to(start); - } - &mut self.pending - } - }; - if bezier { - for c in pts.as_chunks::<3>().0 { - target.curve_to(xf * c[0], xf * c[1], xf * c[2]); - } - } else { - pts.iter().for_each(|p| target.line_to(xf * *p)); - } - self.pos = last; - } - - pub fn arc(&mut self, r: Rect, start: Point, end: Point, kind: ArcKind) { - let bp = arc_path(r, start, end, self.dc.arc_ccw, kind); - self.figure(bp, kind != ArcKind::Open); - } - - // ---------- paths and clips ---------- - - pub fn begin_path(&mut self) { - self.path = Some(BezPath::new()); - self.figure = false; - } - pub fn end_path(&mut self) { - // The path stays until it is filled, stroked or made the clip. - } - pub fn close_figure(&mut self) { - if let Some(p) = &mut self.path - && self.figure - { - p.close_path(); - self.figure = false; - self.pos = self.figure_start; - } - } - pub fn abort_path(&mut self) { - self.path = None; - } - - /// FillPath / StrokePath / StrokeAndFillPath. - pub fn paint_path(&mut self, fill: bool, stroke: bool) { - if let Some(mut bp) = self.path.take() { - // Filling closes the open figure. - if fill && self.figure { - bp.close_path(); - } - self.draw(bp, fill, stroke); - } - } + // ---------- clips ---------- fn push_clip(&mut self, path: BezPath, rule: FillRule, replace: bool) { if replace { @@ -699,10 +323,7 @@ impl Player { if !sane(path.bounding_box()) { return self.warn(FAR_AWAY); } - // A rectangle around the whole picture (what writers clip to first) clips nothing in it. - let lines = path.elements().iter().all(|e| !matches!(e, PathEl::QuadTo(..) | PathEl::CurveTo(..))); - let around = path.bounding_box().inflate(0.5, 0.5); - if lines && path.elements().len() <= 6 && around.contains(self.frame.origin()) && around.contains(Point::new(self.frame.x1, self.frame.y1)) { + if around(&path, self.frame) { return; } if self.dc.clips.len() >= MAX_NEST { @@ -712,69 +333,10 @@ impl Player { self.dc.clips.push(Arc::new(Clip { id: self.next_clip, region: Some((path, rule)) })); } - /// SelectClipPath (`mode`: 1 and, 5 copy; the others cut out, which isn't read). - pub fn clip_path(&mut self, mode: u32) { - let Some(bp) = self.path.take() else { return }; - match mode { - 1 => self.push_clip(bp, self.dc.fill_rule, false), - 5 => self.push_clip(bp, self.dc.fill_rule, true), - _ => self.warn(EXCLUDED_CLIPS), - } - } - - /// IntersectClipRect (logical units). - pub fn clip_rect(&mut self, r: Rect) { - let mut bp = shapes::rectangle(r.abs()).to_bezpath(); - bp.apply_affine(self.xf()); - self.push_clip(bp, FillRule::NonZero, false); - } - - /// A clip region of `rects` in device units (`mode` as [`Self::clip_path`]); none with mode - /// copy removes the clip. - pub fn clip_region(&mut self, rects: &[Rect], mode: u32) { - if rects.is_empty() { - if mode == 5 { - self.dc.clips.clear(); - } - return; - } - let mut bp = BezPath::new(); - for r in rects { - bp.extend(shapes::rectangle(r.abs()).to_bezpath()); - } - bp.apply_affine(self.dev_to_doc); - match mode { - 1 => self.push_clip(bp, FillRule::NonZero, false), - 5 => self.push_clip(bp, FillRule::NonZero, true), - _ => self.warn(EXCLUDED_CLIPS), - } - } - - pub fn exclude_clip(&mut self) { - self.warn(EXCLUDED_CLIPS); - } - - // ---------- blits, images and text ---------- - - /// A raster operation without a source over `dest` (logical): the brush, white or black. - pub fn pattern_blit(&mut self, dest: Rect, rop: u32) { - let brush = match rop { - PATCOPY => self.dc.brush.clone(), - WHITENESS => BrushObj::Solid([255; 3]), - BLACKNESS => BrushObj::Solid([0; 3]), - _ => return self.skip(), - }; - let pen = std::mem::replace(&mut self.dc.pen, PenObj::NULL); - let outer = std::mem::replace(&mut self.dc.brush, brush); - let mut bp = shapes::rectangle(dest.abs()).to_bezpath(); - bp.apply_affine(self.xf()); - self.draw(bp, true, false); - self.dc.pen = pen; - self.dc.brush = outer; - } + // ---------- images and text ---------- /// An image whose source rectangle `src` (pixels, from the top-left) is drawn into `dest` - /// (logical: origin and signed size) with raster operation `rop`, at `opacity`. + /// (picture units: origin and signed size) with raster operation `rop`, at `opacity`. pub fn image(&mut self, img: Result, src: Rect, dest: Rect, rop: u32, opacity: f64) { if rop != SRCCOPY { self.warn(SKIPPED_ROPS); @@ -793,8 +355,8 @@ impl Player { self.image_xf(img, Affine::translate((dest.x0, dest.y0)) * Affine::scale_non_uniform(dest.width() / w, dest.height() / h), opacity); } - /// An image placed by `xf` (its pixels, from the top-left, → logical), at `opacity`. An image - /// that `xf` flattens or sends past finite numbers is left out, and adds nothing to the + /// An image placed by `xf` (its pixels, from the top-left, → picture units), at `opacity`. An + /// image that `xf` flattens or sends past finite numbers is left out, and adds nothing to the /// document's images. pub(crate) fn image_xf(&mut self, img: Rgba, xf: Affine, opacity: f64) { if img.width == 0 || img.height == 0 { @@ -814,14 +376,13 @@ impl Player { self.push(n); } - /// Text at `at` (logical; the current position with TA_UPDATECP) in the current font. + /// Text at `at` (picture units) in the current font. pub fn text(&mut self, at: Point, s: &str) { let s: String = s.chars().filter(|c| *c != '\0').collect(); if s.trim().is_empty() { return; } let align = self.dc.text_align; - let at = if align & 1 != 0 { self.pos } else { at }; let f = self.dc.font.clone(); let k = self.scale(); // A negative height is the em; a positive one the cell (the em and the internal leading). @@ -863,18 +424,7 @@ impl Player { /// The document: what was drawn on one layer, clipped art in clipping groups. fn finish(mut self) -> Imported { self.flush(); - if self.skipped > 0 { - let n = self.skipped; - self.warnings.push(format!( - "{n} record{} of kinds VectorCraft doesn't read {} skipped", - if n == 1 { "" } else { "s" }, - if n == 1 { "was" } else { "were" } - )); - } let out = std::mem::take(&mut self.out); - if out.is_empty() && self.emf_plus { - self.warnings.push("the picture is drawn with EMF+ records, which aren't read yet: nothing was imported".into()); - } let children = nest(&mut self.doc, out); let mut layer = Node::layer(self.doc.alloc_id(), "Layer 1", LayerColor::Preset(0)); if let Some(c) = layer.children_mut() { @@ -904,33 +454,7 @@ fn crop(img: Rgba, src: Rect) -> Rgba { Rgba { width: x1 - x0, height: y1 - y0, pixels } } -/// Read a metafile. +/// Read an EMF or WMF file. pub(crate) fn import(bytes: &[u8]) -> Result { - match crate::sniff(bytes) { - Some(Kind::Emf) => emf::play(bytes), - Some(Kind::Wmf) => wmf::play(bytes), - None => Err("not an EMF or WMF file".into()), - } -} - -#[cfg(test)] -mod table_tests { - use super::*; - - /// Once the WMF table is full, a rejected creation leaves the hint at its end, so the next - /// ones don't scan every slot again; a freed slot is still found. - #[test] - fn a_full_object_table_is_not_rescanned() { - let mut p = Player::new(Kind::Wmf, Affine::IDENTITY, 1.0, Rect::new(0.0, 0.0, 10.0, 10.0)); - for _ in 0..=u16::MAX as usize + 1 { - p.create(Obj::Other); - } - p.delete(5); - p.create(Obj::Other); - p.create(Obj::Other); - assert!(p.free_hint > u16::MAX as usize); - p.delete(7); - p.create(Obj::Other); - assert!(p.objects[7].is_some()); - } + picture::import(bytes) } diff --git a/crates/metafile/src/import/emf.rs b/crates/metafile/src/import/emf.rs deleted file mode 100644 index ece16c7864..0000000000 --- a/crates/metafile/src/import/emf.rs +++ /dev/null @@ -1,392 +0,0 @@ -//! EMF records (MS-EMF) played on a [`Player`]: the header gives the frame (the artboard) and the -//! reference device (device pixels → millimetres), then every record in turn until EMR_EOF. - -use vectorcraft_geom::{Affine, Point, Rect}; - -use super::{ArcKind, BrushObj, FontObj, Obj, PenObj, Player}; -use crate::bytes::{Reader, slice}; -use crate::dib::{self, Alpha}; -use crate::{Imported, Kind}; - -/// Points per millimetre. -const PT_PER_MM: f64 = 72.0 / 25.4; -/// Most points one record may give (a hostile count can't make a huge allocation). -const MAX_POINTS: usize = 1 << 22; -/// Records that change nothing VectorCraft keeps (background mode and colour, raster modes, -/// palettes, colour management, comments…). -const IGNORED: &[u32] = - &[1, 13, 15, 16, 18, 20, 21, 23, 25, 28, 48, 50, 51, 52, 65, 66, 70, 98, 100, 101, 104, 110, 111, 112, 113, 115, 119, 120, 121]; - -fn rect(r: &mut Reader) -> Option { - Some(Rect::new(f64::from(r.i32()?), f64::from(r.i32()?), f64::from(r.i32()?), f64::from(r.i32()?))) -} - -fn point32(r: &mut Reader) -> Option { - Some(Point::new(f64::from(r.i32()?), f64::from(r.i32()?))) -} - -fn point16(r: &mut Reader) -> Option { - Some(Point::new(f64::from(r.i16()?), f64::from(r.i16()?))) -} - -fn color(r: &mut Reader) -> Option<[u8; 3]> { - let [red, g, b, _] = r.u32()?.to_le_bytes(); - Some([red, g, b]) -} - -fn xform(r: &mut Reader) -> Option { - let mut v = [0.0; 6]; - for x in &mut v { - *x = f64::from(r.f32()?); - } - Some(Affine::new(v)) -} - -/// `n` points (32-bit or 16-bit), `None` when the record is shorter. -fn points(r: &mut Reader, n: u32, wide: bool) -> Option> { - let n = n as usize; - if n > MAX_POINTS || r.rest().len() < n * if wide { 8 } else { 4 } { - return None; - } - (0..n).map(|_| if wide { point32(r) } else { point16(r) }).collect() -} - -/// The polygons of a PolyPolygon / PolyPolyline record. -fn polys(r: &mut Reader, wide: bool) -> Option>> { - r.skip(16)?; - let n = r.u32()? as usize; - let total = r.u32()?; - if n > MAX_POINTS || r.rest().len() < n * 4 { - return None; - } - let counts: Vec = (0..n).map(|_| r.u32()).collect::>()?; - let mut all = points(r, total, wide)?.into_iter(); - Some(counts.iter().map(|c| all.by_ref().take(*c as usize).collect()).collect()) -} - -/// A LOGFONTW → the font. -fn font(r: &mut Reader) -> Option { - let height = f64::from(r.i32()?); - r.skip(4)?; - let escapement = f64::from(r.i32()?); - r.skip(4)?; - let weight = r.i32()?; - let italic = r.bytes(1)?.first().is_some_and(|b| *b != 0); - r.skip(7)?; - let units: Vec = (0..32).map_while(|_| r.u16()).take_while(|c| *c != 0).collect(); - Some(FontObj { height, escapement, weight, italic, face: String::from_utf16_lossy(&units) }) -} - -/// The bitmap of an image record: its BITMAPINFO and bits at the offsets the record gives. -fn bitmap(rec: &[u8], off_bmi: u32, cb_bmi: u32, off_bits: u32, cb_bits: u32, alpha: Alpha, left: &mut u64) -> Result { - let bmi = slice(rec, off_bmi, cb_bmi).ok_or("damaged")?; - let bits = slice(rec, off_bits, cb_bits).ok_or("damaged")?; - dib::decode(bmi, bits, alpha, left) -} - -/// The rows a DIB's source rectangle counts from the bottom in (StretchDIBits on a bottom-up DIB). -fn bottom_up(rec: &[u8], off_bmi: u32) -> bool { - let at = off_bmi as usize; - let size = rec.get(at..at + 4).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes); - let height = rec.get(at + 8..at + 12).and_then(|b| b.try_into().ok()).map(i32::from_le_bytes); - size.is_some_and(|s| s >= 40) && height.is_some_and(|h| h > 0) -} - -/// The source rectangle `(x, y, w, h)` of an image of `img`'s height, counted from the top. -fn source(x: i32, y: i32, w: i32, h: i32, img: &Result, from_bottom: bool) -> Rect { - let ih = img.as_ref().map_or(0.0, |i| f64::from(i.height)); - let (x, y, w, h) = (f64::from(x), f64::from(y), f64::from(w), f64::from(h)); - let top = if from_bottom { ih - y - h } else { y }; - Rect::new(x, top, x + w, top + h) -} - -/// The size and placement of the picture: (device → document, millimetres a pixel, the artboard). -fn frame(bytes: &[u8]) -> Option<(Affine, f64, Rect)> { - let mut r = Reader::new(bytes); - r.skip(4)?; - let header_size = r.u32()?; - let bounds = rect(&mut r)?; - let frame = rect(&mut r)?; - // Signature, version, bytes, records, handles, description and palette size. - r.skip(32)?; - let device = (f64::from(r.i32()?), f64::from(r.i32()?)); - let mm = (f64::from(r.i32()?), f64::from(r.i32()?)); - // The device in micrometres (more precise), when the header has it. - let micro = if header_size >= 108 { - r.skip(12)?; - Some((f64::from(r.u32()?), f64::from(r.u32()?))) - } else { - None - }; - let ok = |v: f64| v.is_finite() && v > 0.0; - let mm_per_px = match micro { - Some((mx, _)) if ok(mx) && ok(device.0) => mx / 1000.0 / device.0, - _ if ok(mm.0) && ok(device.0) => mm.0 / device.0, - _ => 25.4 / 96.0, - }; - let mm_per_px = if mm_per_px.is_finite() && mm_per_px > 1e-9 { mm_per_px } else { 25.4 / 96.0 }; - let k = mm_per_px * PT_PER_MM; - // The frame (0.01 mm) in device pixels; an empty frame falls back to the bounds. - let f = frame.abs(); - let (origin, size) = if f.width() > 0.0 && f.height() > 0.0 { - (Point::new(f.x0 / 100.0 / mm_per_px, f.y0 / 100.0 / mm_per_px), (f.width() / 100.0 * PT_PER_MM, f.height() / 100.0 * PT_PER_MM)) - } else { - let b = bounds.abs(); - (b.origin(), ((b.width() + 1.0) * k, (b.height() + 1.0) * k)) - }; - let dev_to_doc = Affine::scale(k) * Affine::translate(-origin.to_vec2()); - let side = |v: f64| if v.is_finite() { v.clamp(1.0, 1e6) } else { 1.0 }; - Some((dev_to_doc, mm_per_px, Rect::new(0.0, 0.0, side(size.0), side(size.1)))) -} - -pub(super) fn play(bytes: &[u8]) -> Result { - let (dev_to_doc, mm_per_px, artboard) = frame(bytes).ok_or("the EMF header is damaged")?; - let mut p = Player::new(Kind::Emf, dev_to_doc, mm_per_px, artboard); - let mut at = 0usize; - let mut ended = false; - while let Some(head) = bytes.get(at..at + 8) { - let kind = u32::from_le_bytes([head[0], head[1], head[2], head[3]]); - let size = u32::from_le_bytes([head[4], head[5], head[6], head[7]]) as usize; - let Some(rec) = bytes.get(at..at.saturating_add(size)).filter(|_| size >= 8) else { break }; - if kind == 14 { - ended = true; - break; - } - if !matches!(kind, 27 | 54 | 5 | 6 | 88 | 89) { - p.flush(); - } - if record(&mut p, kind, rec).is_none() { - p.skip(); - } - at += size; - } - if !ended { - p.warn("the file ends early: what it held was imported"); - } - Ok(p.finish()) -} - -/// PolyBezier, Polygon, Polyline, PolyBezierTo, PolylineTo and their 16-bit forms. -fn rec_poly(p: &mut Player, kind: u32, r: &mut Reader) -> Option<()> { - let wide = kind < 85; - r.skip(16)?; - let n = r.u32()?; - let pts = points(r, n, wide)?; - match if wide { kind } else { kind - 83 } { - 2 => p.poly(&pts, false, true), - 3 => p.poly(&pts, true, false), - 4 => p.poly(&pts, false, false), - 5 => p.poly_to(&pts, true), - _ => p.poly_to(&pts, false), - } - Some(()) -} - -/// CreatePen (38). -fn rec_create_pen(p: &mut Player, r: &mut Reader) -> Option<()> { - let ih = r.u32()?; - let style = r.u32()?; - let width = f64::from(r.i32()?); - r.skip(4)?; - p.create_at(ih, Obj::Pen(PenObj { style, width, color: color(r)?, entries: vec![] })); - Some(()) -} - -/// ExtCreatePen (95). -fn rec_ext_create_pen(p: &mut Player, r: &mut Reader) -> Option<()> { - let ih = r.u32()?; - r.skip(16)?; - let style = r.u32()?; - let width = f64::from(r.u32()?); - let brush = r.u32()?; - let c = color(r)?; - r.skip(4)?; - let n = (r.u32()? as usize).min(64); - let entries: Vec = (0..n).map_while(|_| r.u32()).map(f64::from).collect(); - // A pen painted with the null brush draws nothing. - let style = if brush == 1 { super::PS_NULL } else { style }; - p.create_at(ih, Obj::Pen(PenObj { style, width, color: c, entries })); - Some(()) -} - -/// GdiComment (70): EMF+ records ride in comments starting "EMF+". -fn rec_comment(p: &mut Player, r: &mut Reader) -> Option<()> { - r.skip(4)?; - p.emf_plus |= r.u32()? == 0x2B46_4D45; - Some(()) -} - -/// ExtSelectClipRgn (75). -fn rec_clip_region(p: &mut Player, r: &mut Reader) -> Option<()> { - let cb = r.u32()?; - let mode = r.u32()?; - let data = r.bytes(cb as usize)?; - let mut d = Reader::new(data); - let rects = if cb >= 32 { - d.skip(8)?; - let n = d.u32()? as usize; - d.skip(20)?; - if n > MAX_POINTS || d.rest().len() < n * 16 { - return None; - } - (0..n).map(|_| rect(&mut d)).collect::>>()? - } else { - vec![] - }; - p.clip_region(&rects, mode); - Some(()) -} - -/// The rectangle at `(x, y)` of size `(w, h)`. -fn at_size(x: i32, y: i32, w: i32, h: i32) -> Rect { - Rect::new(f64::from(x), f64::from(y), f64::from(x) + f64::from(w), f64::from(y) + f64::from(h)) -} - -/// BitBlt (76) and StretchBlt (77). -fn rec_blt(p: &mut Player, kind: u32, rec: &[u8], r: &mut Reader) -> Option<()> { - r.skip(16)?; - let dest = (r.i32()?, r.i32()?, r.i32()?, r.i32()?); - let rop = r.u32()?; - let (xs, ys) = (r.i32()?, r.i32()?); - r.skip(24 + 4 + 4)?; - let (off_bmi, cb_bmi, off_bits, cb_bits) = (r.u32()?, r.u32()?, r.u32()?, r.u32()?); - let (ws, hs) = if kind == 77 { (r.i32()?, r.i32()?) } else { (dest.2, dest.3) }; - let d = at_size(dest.0, dest.1, dest.2, dest.3); - if cb_bmi == 0 { - p.pattern_blit(d, rop); - } else { - let img = bitmap(rec, off_bmi, cb_bmi, off_bits, cb_bits, Alpha::Ignore, &mut p.pixels_left); - let src = source(xs, ys, ws, hs, &img, false); - p.image(img, src, d, rop, 1.0); - } - Some(()) -} - -/// StretchDIBits (81). -fn rec_stretch_dibits(p: &mut Player, rec: &[u8], r: &mut Reader) -> Option<()> { - r.skip(16)?; - let (xd, yd, xs, ys, ws, hs) = (r.i32()?, r.i32()?, r.i32()?, r.i32()?, r.i32()?, r.i32()?); - let (off_bmi, cb_bmi, off_bits, cb_bits) = (r.u32()?, r.u32()?, r.u32()?, r.u32()?); - r.skip(4)?; - let rop = r.u32()?; - let (wd, hd) = (r.i32()?, r.i32()?); - let img = bitmap(rec, off_bmi, cb_bmi, off_bits, cb_bits, Alpha::Ignore, &mut p.pixels_left); - let src = source(xs, ys, ws, hs, &img, bottom_up(rec, off_bmi)); - p.image(img, src, at_size(xd, yd, wd, hd), rop, 1.0); - Some(()) -} - -/// AlphaBlend (114). -fn rec_alpha_blend(p: &mut Player, rec: &[u8], r: &mut Reader) -> Option<()> { - r.skip(16)?; - let (xd, yd, wd, hd) = (r.i32()?, r.i32()?, r.i32()?, r.i32()?); - let blend = r.bytes(4)?; - let (constant, per_pixel) = (blend.get(2).copied().unwrap_or(255), blend.get(3).is_some_and(|f| *f & 1 != 0)); - let (xs, ys) = (r.i32()?, r.i32()?); - r.skip(24 + 4 + 4)?; - let (off_bmi, cb_bmi, off_bits, cb_bits) = (r.u32()?, r.u32()?, r.u32()?, r.u32()?); - let (ws, hs) = (r.i32()?, r.i32()?); - let alpha = if per_pixel { Alpha::Premultiplied } else { Alpha::Ignore }; - let img = bitmap(rec, off_bmi, cb_bmi, off_bits, cb_bits, alpha, &mut p.pixels_left); - let src = source(xs, ys, ws, hs, &img, false); - p.image(img, src, at_size(xd, yd, wd, hd), crate::import::SRCCOPY, f64::from(constant) / 255.0); - Some(()) -} - -/// ExtTextOutA (83) and ExtTextOutW (84). -fn rec_text(p: &mut Player, kind: u32, rec: &[u8], r: &mut Reader) -> Option<()> { - r.skip(16 + 4 + 8)?; - let at = point32(r)?; - let n = r.u32()? as usize; - let off = r.u32()?; - let s = if kind == 84 { - let raw = slice(rec, off, u32::try_from(n.checked_mul(2)?).ok()?)?; - String::from_utf16_lossy(&raw.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).collect::>()) - } else { - slice(rec, off, u32::try_from(n).ok()?)?.iter().map(|b| char::from(*b)).collect() - }; - p.text(at, &s); - Some(()) -} - -/// Play one record (`rec`: all of it, with its type and size). `None`: unknown or damaged. -fn record(p: &mut Player, kind: u32, rec: &[u8]) -> Option<()> { - let mut r = Reader::new(rec.get(8..)?); - match kind { - 2..=6 | 85..=89 => rec_poly(p, kind, &mut r)?, - 7 | 90 => p.poly_poly(&polys(&mut r, kind == 7)?, false), - 8 | 91 => p.poly_poly(&polys(&mut r, kind == 8)?, true), - 9 => p.set_window_ext(f64::from(r.i32()?), f64::from(r.i32()?)), - 10 => p.set_window_org(f64::from(r.i32()?), f64::from(r.i32()?)), - 11 => p.set_viewport_ext(f64::from(r.i32()?), f64::from(r.i32()?)), - 12 => p.set_viewport_org(f64::from(r.i32()?), f64::from(r.i32()?)), - 17 => p.set_map_mode(r.u32()?), - 19 => p.set_fill_mode(r.u32()? == 1), - 22 => p.set_text_align(r.u32()?), - 24 => p.set_text_color(color(&mut r)?), - 27 => p.move_to(point32(&mut r)?), - 29 => p.exclude_clip(), - 30 => p.clip_rect(rect(&mut r)?), - 31 | 32 => { - let (xn, xd, yn, yd) = (r.i32()?, r.i32()?, r.i32()?, r.i32()?); - p.scale_ext(kind == 32, (f64::from(xn), f64::from(xd)), (f64::from(yn), f64::from(yd))); - } - 33 => p.save(), - 34 => p.restore(r.i32()?), - 35 => p.world(xform(&mut r)?, 4), - 36 => { - let x = xform(&mut r)?; - p.world(x, r.u32()?); - } - 37 => p.select(r.u32()?), - 38 => rec_create_pen(p, &mut r)?, - 39 => { - let ih = r.u32()?; - let style = r.u32()?; - p.create_at(ih, Obj::Brush(BrushObj::from_log(style, color(&mut r)?))); - } - 40 => p.delete(r.u32()?), - 42 => p.figure(vectorcraft_geom::shapes::ellipse(rect(&mut r)?.abs()).to_bezpath(), true), - 43 => p.figure(vectorcraft_geom::shapes::rectangle(rect(&mut r)?.abs()).to_bezpath(), true), - 44 => { - let b = rect(&mut r)?; - let (cx, cy) = (f64::from(r.i32()?), f64::from(r.i32()?)); - p.figure(super::round_rect(b, cx, cy), true); - } - 45..=47 => { - let b = rect(&mut r)?; - let (s, e) = (point32(&mut r)?, point32(&mut r)?); - p.arc(b, s, e, [ArcKind::Open, ArcKind::Chord, ArcKind::Pie][(kind - 45) as usize]); - } - 49 | 99 | 122 => p.create_at(r.u32()?, Obj::Other), - 54 => { - let pt = point32(&mut r)?; - p.poly_to(&[pt], false); - } - 57 => p.set_arc_ccw(r.u32()? != 2), - 58 => p.set_miter(f64::from(r.u32()?)), - 59 => p.begin_path(), - 60 => p.end_path(), - 61 => p.close_figure(), - 62 => p.paint_path(true, false), - 63 => p.paint_path(true, true), - 64 => p.paint_path(false, true), - 67 => p.clip_path(r.u32()?), - 68 => p.abort_path(), - 70 => rec_comment(p, &mut r)?, - 75 => rec_clip_region(p, &mut r)?, - 76 | 77 => rec_blt(p, kind, rec, &mut r)?, - 81 => rec_stretch_dibits(p, rec, &mut r)?, - 82 => { - let ih = r.u32()?; - p.create_at(ih, Obj::Font(font(&mut r)?)); - } - 83 | 84 => rec_text(p, kind, rec, &mut r)?, - 93 | 94 => p.create_at(r.u32()?, Obj::Brush(BrushObj::Pattern)), - 95 => rec_ext_create_pen(p, &mut r)?, - 114 => rec_alpha_blend(p, rec, &mut r)?, - k if IGNORED.contains(&k) => {} - _ => return None, - } - Some(()) -} diff --git a/crates/metafile/src/import/pict.rs b/crates/metafile/src/import/pict.rs index a9b4cae9da..f6abbc6b83 100644 --- a/crates/metafile/src/import/pict.rs +++ b/crates/metafile/src/import/pict.rs @@ -24,7 +24,7 @@ use std::io::Cursor; use vectorcraft_geom::{Affine, BezPath, FillRule, Point, Rect, Shape, Vec2, shapes}; -use super::{BAD_IMAGE, BrushObj, FontObj, PS_GEOMETRIC, PenObj, Player, SRCCOPY, TOO_MANY_PIXELS, crop, round_rect}; +use super::{BAD_IMAGE, FontObj, PS_GEOMETRIC, PenObj, Player, SRCCOPY, TOO_MANY_PIXELS, crop, round_rect}; use crate::dib::{self, Rgba}; use crate::{Imported, Kind}; @@ -600,7 +600,7 @@ impl Pict { let base = Affine::translate(-frame.origin().to_vec2()); let artboard = Rect::new(0.0, 0.0, frame.width(), frame.height()); // A picture's coordinates map straight onto the document, as a WMF's do. - let p = Player::new(Kind::Wmf, base, 25.4 / 72.0, artboard); + let p = Player::new(Kind::Wmf, base, artboard); Self { p, frame, @@ -783,7 +783,7 @@ impl Pict { /// Fill `bp` (picture space) with `color`. fn fill(&mut self, mut bp: BezPath, color: [u8; 3], rule: FillRule) { bp.apply_affine(self.p.xf()); - self.p.dc.brush = BrushObj::Solid(color); + self.p.dc.brush = color; self.p.dc.fill_rule = rule; self.p.draw(bp, true, false); } diff --git a/crates/metafile/src/import/picture.rs b/crates/metafile/src/import/picture.rs new file mode 100644 index 0000000000..03a2e5628e --- /dev/null +++ b/crates/metafile/src/import/picture.rs @@ -0,0 +1,658 @@ +//! EMF (with or without EMF+ records) and WMF files: `craft_metafile` plays the records into a +//! picture, and the picture's items become document objects here. +//! +//! - A filled or stroked path becomes a path with a fill and a stroke (caps, joins, miter limit +//! and dashes from the pen). Opaque solid strokes with round caps and round joins drawn one after +//! another, each starting where the last one ended, with the same pen and clip, join into one +//! path. Other strokes stay apart, each with its own caps and its own dashes. +//! - A path filled with a pattern or hatched brush is filled with the average color of the +//! brush's tile. +//! - A bitmap becomes an image (its pixels as PNG) placed where the picture draws it, turned or +//! skewed with it. +//! - Text becomes point type in the font the file names, underlined or struck through as the font +//! is, and clipped to its rectangle when the file clips it. +//! - Clip regions and clip paths become clipping groups around what they clip; a rectangle around +//! the whole picture clips nothing and is left out. +//! +//! A WMF without a placeable header is read at 1440 units an inch, and one whose placeable box is +//! empty or inverted at the units an inch the header gives. Either one that draws in a metric map +//! mode (MM_LOMETRIC to MM_TWIPS) is read at 96 pixels an inch, as `craft_metafile` plays those +//! modes. An EMF without a usable frame is read at its device's pixels a millimetre (96 +//! pixels an inch when the header doesn't say). + +use std::collections::HashMap; +use std::sync::{Arc, Weak}; + +use craft_metafile::{Cap, ClipPath, HAlign, Item, Join, LineStyle, Seg, VAlign}; +use vectorcraft_color::Paint; +use vectorcraft_doc::clipnest::{Clip, Drawn, MAX_NEST, deep_clips, nest}; +use vectorcraft_doc::{ + Appearance, AppearanceItem, CharStyle, Dash, Document, FillLayer, ImageBlob, ImageObject, Justify, LayerColor, LineCap, LineJoin, Node, NodeId, + NodeKind, StrokeLayer, TextObject, +}; +use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, PathEl, Point, Rect, Shape, shapes}; + +use super::{BAD_IMAGE, FAR_AWAY, HAIRLINE, LIMIT, MAX_NODES, around, rgb, sane}; +use crate::dib::Rgba; +use crate::wmf::PLACEABLE_KEY; +use crate::{Imported, Kind}; + +const PATTERNS: &str = "hatched and pattern brushes are filled with their average color"; +const ENDS_EARLY: &str = "the file ends early: what it held was imported"; +const TOO_MANY: &str = "objects past the most one file may hold were left out"; +const AT_LIMIT: &str = "the file reached the most objects one file may hold: any after them were not read"; + +/// The most items `craft_metafile` keeps from one file (its `MAX_ITEMS`). It stops reading at the +/// limit and does not say whether more items followed, so a picture holding this many may have +/// been cut short. +const READER_ITEMS: usize = 200_000; + +/// Points a unit of a WMF without a placeable header (1440 units an inch). +const WMF_UNIT: f64 = 72.0 / 1440.0; +/// The SAVEDC levels `craft_metafile` keeps; it stops reading at a SAVEDC past them. +const SAVED_LEVELS: usize = 1024; +/// Points a pixel at 96 pixels an inch. +const PT_PER_PX: f64 = 72.0 / 96.0; +/// Points a millimetre. +const PT_PER_MM: f64 = 72.0 / 25.4; + +/// WMF records that draw lines and shapes, which `craft_metafile` plays only when the mix mode +/// lets them draw. +const WMF_SHAPES: [u16; 10] = [0x0213, 0x0324, 0x0325, 0x0418, 0x041B, 0x0538, 0x061C, 0x0817, 0x081A, 0x0830]; +/// WMF records that draw text and bitmaps, which `craft_metafile` plays whatever the mix mode. +const WMF_DRAWS: [u16; 5] = [0x0521, 0x0940, 0x0A32, 0x0B41, 0x0F43]; +/// SETROP2 mix modes under which `craft_metafile` draws no lines, shapes or brush fills: R2_XORPEN +/// and R2_NOP. +const WMF_MIX_SKIPS: [u16; 2] = [7, 11]; +/// The mix mode a WMF starts in (R2_COPYPEN). +const WMF_MIX_START: u16 = 13; +/// PATBLT raster operations `craft_metafile` draws: PATCOPY (with the brush, as the mix mode +/// allows), BLACKNESS and WHITENESS. +const PATCOPY: u32 = 0x00F0_0021; +const BLACKNESS: u32 = 0x0000_0042; +const WHITENESS: u32 = 0x00FF_0062; + +/// Does a WMF draw in a metric map mode (MM_LOMETRIC to MM_TWIPS)? `craft_metafile` plays those +/// at 96 pixels an inch, whatever the window. The mode that more drawing records are played in +/// decides, counting only records the reader draws (not lines and shapes under R2_NOP or +/// R2_XORPEN, nor a PATBLT it does not fill); a file that draws nothing goes by its last mode. +/// `start` is where the standard header begins. +fn wmf_metric(bytes: &[u8], start: usize) -> bool { + let u16_at = |at: usize| bytes.get(at..at.checked_add(2)?).map(|b| u16::from_le_bytes([b[0], b[1]])); + let u32_at = |at: usize| bytes.get(at..at.checked_add(4)?).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])); + let Some(words) = start.checked_add(2).and_then(u16_at) else { return false }; + let mut at = start.saturating_add(usize::from(words) * 2); + let mut mode = 1; + let mut mix = WMF_MIX_START; + let metric = |mode: u16| (2..=6).contains(&mode); + // Drawing records played in a metric mode, and in any other. + let (mut in_metric, mut in_other) = (0usize, 0usize); + // The map and mix modes SAVEDC kept, which RESTOREDC brings back as the reader does. + let mut saved: Vec<(u16, u16)> = Vec::new(); + // The records as the reader walks them: it stops at the end record, a record shorter than its + // header, one that runs past the file and a SAVEDC past its 1,024 levels. + while let (Some(words), Some(function)) = (u32_at(at), u16_at(at.saturating_add(4))) { + let size = (words as usize).saturating_mul(2); + let Some(next) = at.checked_add(size) else { break }; + if function == 0 || size < 6 || next > bytes.len() { + break; + } + match function { + // SETMAPMODE, when the record holds its mode. + 0x0103 if size >= 8 => mode = u16_at(at + 6).unwrap_or(mode), + // SETROP2, when the record holds its mix mode. + 0x0104 if size >= 8 => mix = u16_at(at + 6).unwrap_or(mix), + // SAVEDC. + 0x001E => { + if saved.len() >= SAVED_LEVELS { + break; + } + saved.push((mode, mix)); + } + // RESTOREDC: a negative count pops that many levels, a positive one goes back to that + // level. One that names no saved level changes nothing. + 0x0127 if size >= 8 => { + let n = u16_at(at + 6).map_or(0, |v| i32::from(i16::from_le_bytes(v.to_le_bytes()))); + let level = if n < 0 { saved.len().checked_sub(n.unsigned_abs() as usize) } else { (n as usize).checked_sub(1) }; + if let Some(level) = level + && let Some((m, x)) = saved.get(level).copied() + { + mode = m; + mix = x; + saved.truncate(level); + } + } + f => { + let draws = match f { + _ if WMF_DRAWS.contains(&f) => true, + _ if WMF_SHAPES.contains(&f) => !WMF_MIX_SKIPS.contains(&mix), + // PATBLT: its raster operation, when the record holds one. + 0x061D => match u32_at(at + 6).filter(|_| size >= 10) { + Some(PATCOPY) => !WMF_MIX_SKIPS.contains(&mix), + Some(rop) => rop == BLACKNESS || rop == WHITENESS, + None => false, + }, + _ => false, + }; + if draws && metric(mode) { + in_metric += 1; + } else if draws { + in_other += 1; + } + } + } + at = next; + } + if in_metric == in_other { metric(mode) } else { in_metric > in_other } +} + +/// Points a picture unit across and down. `craft_metafile` gives a placeable WMF with a box and an +/// EMF with a frame in points, and other files in their logical units (WMF; pixels in a metric map +/// mode) or device units (EMF). +fn unit(bytes: &[u8], kind: Kind) -> (f64, f64) { + let u16_at = |at: usize| bytes.get(at..at.checked_add(2)?).map(|b| u16::from_le_bytes([b[0], b[1]])); + let i16_at = |at: usize| bytes.get(at..at.checked_add(2)?).map(|b| i16::from_le_bytes([b[0], b[1]])); + let u32_at = |at: usize| bytes.get(at..at.checked_add(4)?).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])); + let i32_at = |at: usize| bytes.get(at..at.checked_add(4)?).map(|b| i32::from_le_bytes([b[0], b[1], b[2], b[3]])); + let positive = |v: Option| v.filter(|v| *v > 0).map(f64::from); + match kind { + Kind::Wmf => { + let placeable = bytes.get(..4) == Some(&PLACEABLE_KEY.to_le_bytes()[..]); + if placeable + && let (Some(l), Some(t), Some(r), Some(b)) = (i16_at(6), i16_at(8), i16_at(10), i16_at(12)) + && r > l + && b > t + { + return (1.0, 1.0); + } + if wmf_metric(bytes, if placeable { 22 } else { 0 }) { + return (PT_PER_PX, PT_PER_PX); + } + if !placeable { + return (WMF_UNIT, WMF_UNIT); + } + let k = 72.0 / u16_at(14).filter(|v| *v > 0).map_or(1440.0, f64::from); + (k, k) + } + Kind::Emf => { + // Device pixels a millimetre on each axis: szlDevice over szlMicrometers when the header + // has them, else over szlMillimeters (both sizes must be positive). + let device = positive(i32_at(72)).zip(positive(i32_at(76))); + let micro = (u32_at(4).is_some_and(|s| s >= 108)) + .then(|| u32_at(100).zip(u32_at(104)).filter(|(w, h)| *w > 0 && *h > 0).map(|(w, h)| (f64::from(w) / 1000.0, f64::from(h) / 1000.0))) + .flatten(); + let mm = micro.or_else(|| positive(i32_at(80)).zip(positive(i32_at(84)))); + let px_mm = device.zip(mm).map(|((w, h), (mw, mh))| (w / mw, h / mh)); + let frame = matches!((i32_at(24), i32_at(28), i32_at(32), i32_at(36)), (Some(l), Some(t), Some(r), Some(b)) if r > l && b > t); + let ok = |v: f64| v.is_finite() && v > 0.0; + match px_mm { + Some(_) if frame => (1.0, 1.0), + Some((x, y)) if ok(x) && ok(y) => (PT_PER_MM / x, PT_PER_MM / y), + _ => (PT_PER_PX, PT_PER_PX), + } + } + } +} + +/// What a stroke is drawn with, to tell whether two strokes join into one path. +#[derive(Clone, PartialEq)] +struct Pen { + color: [u8; 4], + width: f32, + line: LineStyle, + even_odd: bool, + chain: Vec, +} + +/// Strokes drawn one after another, not added yet: their pen, clips and path (document space). +struct Pending { + pen: Pen, + clips: Vec>, + path: BezPath, +} + +/// Clip paths already made, by address (the `Arc` keeps the address from being reused); None for +/// one that clips nothing in the picture. +type MadeClips = HashMap<*const ClipPath, (Arc, Option>)>; +/// The last clip region and the clip made for it. +type MadeRegion = (Vec<[f32; 4]>, Option>); +/// Brush tiles already averaged, by address: items filled with the same brush share its tile. The +/// `Weak` keeps the address from being reused, and the tile's pixels are freed once the last item +/// that uses it has been read. +type Averaged = HashMap<*const craft_metafile::Tile, (Weak, Option<[u8; 4]>)>; + +struct Mapper { + /// Picture units → points. + xf: Affine, + /// How much lengths (stroke widths, dashes) grow from the picture to points. + k: f64, + frame: Rect, + doc: Document, + out: Drawn, + warnings: Vec, + next_clip: u32, + paths: MadeClips, + region: Option, + pending: Option, + averaged: Averaged, +} + +fn color(c: [u8; 4]) -> Paint { + rgb([c[0], c[1], c[2]]) +} + +/// The average color of a tile's pixels, weighted by their alpha, and their average alpha; None +/// for a clear tile. +fn average(rgba: &[u8]) -> Option<[u8; 4]> { + let pixels = rgba.as_chunks::<4>().0; + let mut sum = [0u64; 4]; + for p in pixels { + let a = u64::from(p[3]); + sum[0] += u64::from(p[0]) * a; + sum[1] += u64::from(p[1]) * a; + sum[2] += u64::from(p[2]) * a; + sum[3] += a; + } + let a = sum[3]; + let alpha = (a / pixels.len().max(1) as u64) as u8; + (a > 0).then(|| [(sum[0] / a) as u8, (sum[1] / a) as u8, (sum[2] / a) as u8, alpha.max(1)]) +} + +impl Mapper { + fn new(width: f64, height: f64, (kx, ky): (f64, f64)) -> Self { + let side = |v: f64| if v.is_finite() { v.clamp(1.0, LIMIT) } else { 1.0 }; + let (w, h) = (side(width * kx), side(height * ky)); + let mut doc = Document::new(w, h); + doc.layers.clear(); + Self { + xf: Affine::scale_non_uniform(kx, ky), + // The mean of the two, as the reader scales stroke lengths. + k: (kx + ky) / 2.0, + frame: Rect::new(0.0, 0.0, w, h), + doc, + out: vec![], + warnings: vec![], + next_clip: 0, + paths: HashMap::new(), + region: None, + pending: None, + averaged: HashMap::new(), + } + } + + fn warn(&mut self, w: &str) { + if !self.warnings.iter().any(|x| x == w) { + self.warnings.push(w.to_string()); + } + } + + fn path(&self, segs: &[Seg]) -> BezPath { + let mut bp = craft_metafile::bez_path(segs); + bp.apply_affine(self.xf); + bp + } + + /// A clip of `path` (document space), or None when it clips nothing in the picture. + fn clip(&mut self, path: BezPath, rule: FillRule) -> Option> { + if around(&path, self.frame) { + return None; + } + self.next_clip += 1; + Some(Arc::new(Clip { id: self.next_clip, region: Some((path, rule)) })) + } + + /// The clips an item is drawn under, outermost first; None when it shows nowhere. + fn chain(&mut self, region: Option>, clips: &[Arc]) -> Option>> { + let mut chain = vec![]; + if let Some(rects) = region { + if rects.is_empty() { + return None; + } + let made = match &self.region { + Some((last, made)) if *last == rects => made.clone(), + _ => { + let mut bp = BezPath::new(); + for [x0, y0, x1, y1] in &rects { + bp.extend(shapes::rectangle(Rect::new(f64::from(*x0), f64::from(*y0), f64::from(*x1), f64::from(*y1))).to_bezpath()); + } + bp.apply_affine(self.xf); + if !sane(bp.bounding_box()) { + self.warn(FAR_AWAY); + return None; + } + let made = self.clip(bp, FillRule::NonZero); + self.region = Some((rects, made.clone())); + made + } + }; + chain.extend(made); + } + for c in clips { + let key = Arc::as_ptr(c); + let made = match self.paths.get(&key) { + Some((_, made)) => made.clone(), + None => { + let bp = self.path(&c.segs); + if !sane(bp.bounding_box()) { + self.warn(FAR_AWAY); + return None; + } + let made = self.clip(bp, if c.even_odd { FillRule::EvenOdd } else { FillRule::NonZero }); + self.paths.insert(key, (c.clone(), made.clone())); + made + } + }; + chain.extend(made); + } + if chain.len() > MAX_NEST { + chain.truncate(MAX_NEST); + self.warn(&deep_clips()); + } + Some(chain) + } + + fn push(&mut self, clips: Vec>, mut node: Node) { + if self.out.len() >= MAX_NODES { + return self.warn(TOO_MANY); + } + if !node.visual_bounds().is_none_or(sane) { + return self.warn(FAR_AWAY); + } + node.id = self.doc.alloc_id(); + self.out.push((clips, node)); + } + + /// Add the strokes waiting to be joined. + fn flush(&mut self) { + if let Some(p) = self.pending.take() { + let node = self.path_node(p.path, None, Some((p.pen.color, p.pen.width, &p.pen.line)), p.pen.even_odd); + if let Some(n) = node { + self.push(p.clips, n); + } + } + } + + fn stroke_layer(&self, c: [u8; 4], width: f32, line: &LineStyle) -> StrokeLayer { + let w = f64::from(width) * self.k; + let mut st = StrokeLayer::new(color(c), if w > 0.0 && w.is_finite() { w } else { HAIRLINE }); + st.opacity = f32::from(c[3]) / 255.0; + st.cap = match line.cap { + Cap::Round => LineCap::Round, + Cap::Square => LineCap::Square, + Cap::Flat => LineCap::Butt, + }; + st.join = match line.join { + Join::Round => LineJoin::Round, + Join::Bevel => LineJoin::Bevel, + Join::Miter => LineJoin::Miter, + }; + let miter = f64::from(line.miter_limit); + if miter.is_finite() && miter >= 1.0 { + st.miter_limit = miter; + } + let dash = Dash { pattern: line.dash.iter().map(|d| f64::from(*d) * self.k).collect(), offset: 0.0, align_corners: false }; + st.dash = dash.is_dashed().then_some(dash); + st + } + + /// A path node painted with `fill` and `stroke`; None when neither shows. + fn path_node(&self, bp: BezPath, fill: Option<[u8; 4]>, stroke: Option<([u8; 4], f32, &LineStyle)>, even_odd: bool) -> Option { + if bp.elements().is_empty() { + return None; + } + let mut items = vec![]; + if let Some(c) = fill.filter(|c| c[3] > 0) { + let mut f = FillLayer::new(color(c)); + f.opacity = f32::from(c[3]) / 255.0; + items.push(AppearanceItem::Fill(f)); + } + if let Some((c, w, line)) = stroke.filter(|s| s.0[3] > 0) { + items.push(AppearanceItem::Stroke(self.stroke_layer(c, w, line))); + } + if items.is_empty() { + return None; + } + let mut n = Node::path(NodeId(0), PathData::from_bezpath(&bp), Appearance { items, ..Appearance::default() }); + if let NodeKind::Path { rule, .. } = &mut n.kind { + *rule = if even_odd { FillRule::EvenOdd } else { FillRule::NonZero }; + } + Some(n) + } + + fn item(&mut self, item: Item) { + match item { + Item::Path { segs, fill, stroke, line, even_odd, region, clips } => { + let Some(chain) = self.chain(region, &clips) else { return self.flush() }; + let bp = self.path(&segs); + // An open stroke with nothing filled waits, to join the next one. + if let (None, Some((c, w))) = (fill, stroke) + && !segs.iter().any(|s| matches!(s, Seg::Close)) + { + // A stroke that reaches too far is left out here, before it joins the strokes + // waiting, so they are still added. + let half = f64::from(w) * self.k; + let half = if half > 0.0 && half.is_finite() { half / 2.0 } else { HAIRLINE / 2.0 }; + if !sane(bp.bounding_box().inflate(half, half)) { + self.flush(); + return self.warn(FAR_AWAY); + } + let pen = Pen { color: c, width: w, line, even_odd, chain: chain.iter().map(|c| c.id).collect() }; + let start = bp.elements().first().and_then(|e| match e { + PathEl::MoveTo(p) => Some(*p), + _ => None, + }); + // A translucent stroke stays apart, so where strokes overlap each one shows. So + // does a dashed one, whose dashes start at its own start, and one whose caps + // or joins aren't round: a join where two strokes meet is not their two caps. + if let Some(p) = &mut self.pending + && p.pen == pen + && pen.color[3] == u8::MAX + && pen.line.dash.is_empty() + && matches!((&pen.line.cap, &pen.line.join), (Cap::Round, Join::Round)) + && start.is_some() + && p.path.elements().last().and_then(|e| e.end_point()) == start + { + p.path.extend(bp.elements().iter().skip(1).copied()); + return; + } + self.flush(); + self.pending = Some(Pending { pen, clips: chain, path: bp }); + return; + } + self.flush(); + let stroke = stroke.map(|(c, w)| (c, w, &line)); + if let Some(n) = self.path_node(bp, fill, stroke, even_odd) { + self.push(chain, n); + } + } + Item::Pattern { segs, even_odd, tile, region, clips } => { + self.flush(); + let Some(chain) = self.chain(region, &clips) else { return }; + let Some(c) = self.averaged.entry(Arc::as_ptr(&tile)).or_insert_with(|| (Arc::downgrade(&tile), average(&tile.rgba))).1 else { + return; + }; + self.warn(PATTERNS); + let bp = self.path(&segs); + if let Some(n) = self.path_node(bp, Some(c), None, even_odd) { + self.push(chain, n); + } + } + Item::Bitmap { transform, width, height, rgba, region, clips, .. } => { + self.flush(); + let Some(chain) = self.chain(region, &clips) else { return }; + self.image(Rgba { width, height, pixels: rgba }, Affine::new(transform), chain); + } + Item::Text(t) => { + self.flush(); + let Some(mut chain) = self.chain(t.region.clone(), &t.clips) else { return }; + // The text's own clip rectangle, inside the others. + if let Some([x0, y0, x1, y1]) = t.clip { + let mut bp = shapes::rectangle(Rect::new(f64::from(x0), f64::from(y0), f64::from(x1), f64::from(y1)).abs()).to_bezpath(); + bp.apply_affine(self.xf); + if !sane(bp.bounding_box()) { + return self.warn(FAR_AWAY); + } + if let Some(own) = self.clip(bp, FillRule::NonZero) { + // Past the stack, the text's own clip takes the innermost place kept. + if chain.len() >= MAX_NEST { + chain.truncate(MAX_NEST.saturating_sub(1)); + self.warn(&deep_clips()); + } + chain.push(own); + } + } + self.text(&t, chain); + } + } + } + + /// An image whose unit square `unit` places in the picture. + fn image(&mut self, img: Rgba, unit: Affine, chain: Vec>) { + if img.width == 0 || img.height == 0 { + return; + } + let xf = self.xf * unit * Affine::scale_non_uniform(1.0 / f64::from(img.width), 1.0 / f64::from(img.height)); + if !xf.as_coeffs().iter().all(|v| v.is_finite()) || xf.determinant().abs() < 1e-12 { + return; + } + let Ok(png) = img.to_png() else { return self.warn(BAD_IMAGE) }; + let blob = ImageBlob::new("image/png", png); + let key = blob.content_key(); + self.doc.images.entry(key.clone()).or_insert(blob); + let im = ImageObject { key, width: img.width, height: img.height, xf, link: None, placement: Default::default(), pixels: None }; + self.push(chain, Node::new(NodeId(0), NodeKind::Image(Box::new(im)))); + } + + fn text(&mut self, t: &craft_metafile::Text, chain: Vec>) { + let s: String = t.text.chars().filter(|c| *c != '\0').collect(); + if s.trim().is_empty() || t.color[3] == 0 { + return; + } + // Text space → document without the move: its vertical scale gives the type size, and what + // is left of it (a turn, a stretch across) goes on the text object. + let [a, b, c, d, ..] = t.transform; + let linear = self.xf * Affine::new([a, b, c, d, 0.0, 0.0]); + let [_, _, c, d, ..] = linear.as_coeffs(); + let k = c.hypot(d); + let shape = if k > 1e-12 && k.is_finite() && linear.determinant().abs() > 1e-24 { Affine::scale(1.0 / k) * linear } else { Affine::IDENTITY }; + let f = &t.font; + let h = f64::from(f.height); + // A negative height is the em; a positive one the cell (the em and the internal leading). + let em = if h < 0.0 { -h } else { h * 0.85 }; + let size = if em > 0.0 && (em * k).is_finite() { (em * k).clamp(0.5, 5000.0) } else { 12.0 }; + let mut style = CharStyle { size, fill: color(t.color), stroke: Paint::None, ..CharStyle::default() }; + if !f.family.trim().is_empty() { + style.font_family = f.family.trim().to_string(); + } + style.font_style = match (f.weight >= 600, f.italic) { + (true, true) => "Bold Italic", + (true, false) => "Bold", + (false, true) => "Italic", + (false, false) => "Regular", + } + .into(); + style.underline = f.underline; + style.strikethrough = f.strike; + // Where the baseline is below the reference point. + let drop = match t.v_align { + VAlign::Baseline => 0.0, + VAlign::Bottom => -0.2 * size, + VAlign::Top => 0.8 * size, + }; + let origin = self.xf * Point::new(t.transform[4], t.transform[5]); + let mut text = TextObject::point(Point::ZERO, &s, style); + text.xf = Affine::translate(origin.to_vec2()) * shape * Affine::translate((0.0, drop)); + text.para.justify = match t.h_align { + HAlign::Center => Justify::Center, + HAlign::Right => Justify::Right, + HAlign::Left => Justify::Left, + }; + text.cached_bounds = Some(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &text).bounds); + let mut n = Node::new(NodeId(0), NodeKind::Text(Box::new(text))); + n.opacity = f32::from(t.color[3]) / 255.0; + self.push(chain, n); + } + + /// The document: what was drawn on one layer, clipped art in clipping groups. + fn finish(mut self, kind: Kind, skipped: u32) -> Imported { + self.flush(); + if skipped > 0 { + let n = skipped; + self.warnings.push(format!( + "{n} record{} of kinds VectorCraft doesn't read {} skipped", + if n == 1 { "" } else { "s" }, + if n == 1 { "was" } else { "were" } + )); + } + let out = std::mem::take(&mut self.out); + let children = nest(&mut self.doc, out); + let mut layer = Node::layer(self.doc.alloc_id(), "Layer 1", LayerColor::Preset(0)); + if let Some(c) = layer.children_mut() { + *c = children; + } + self.doc.layers = vec![Arc::new(layer)]; + Imported { document: self.doc, kind, warnings: self.warnings } + } +} + +/// Does the file stop before its end-of-file record? +fn ends_early(bytes: &[u8], kind: Kind) -> bool { + let u32_at = |at: usize| bytes.get(at..at.checked_add(4)?).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])); + let u16_at = |at: usize| bytes.get(at..at.checked_add(2)?).map(|b| u16::from_le_bytes([b[0], b[1]])); + let mut at = match kind { + Kind::Emf => 0, + Kind::Wmf => { + let start = if u32_at(0) == Some(PLACEABLE_KEY) { 22 } else { 0 }; + let Some(words) = u16_at(start + 2) else { return true }; + start + usize::from(words) * 2 + } + }; + loop { + let size = match kind { + Kind::Emf => { + let (Some(kind), Some(size)) = (u32_at(at), u32_at(at.saturating_add(4))) else { return true }; + if kind == 14 { + return false; + } + // Records are a multiple of 4 bytes long; reading stops at one that isn't. + if !size.is_multiple_of(4) { + return true; + } + size as usize + } + Kind::Wmf => { + let (Some(words), Some(function)) = (u32_at(at), u16_at(at.saturating_add(4))) else { return true }; + if function == 0 { + return false; + } + (words as usize).saturating_mul(2) + } + }; + if size < 6 { + return true; + } + at = at.saturating_add(size); + } +} + +/// Read an EMF or WMF file. +pub(crate) fn import(bytes: &[u8]) -> Result { + let kind = crate::sniff(bytes).ok_or("not an EMF or WMF file")?; + let pic = craft_metafile::parse(bytes).map_err(|e| match e { + craft_metafile::Error::NotMetafile => "not an EMF or WMF file".to_string(), + craft_metafile::Error::BadHeader => format!("the {} header is damaged", kind.id().to_uppercase()), + craft_metafile::Error::NoRecords => format!("the {} file holds no records", kind.id().to_uppercase()), + })?; + let k = unit(bytes, kind); + let mut m = Mapper::new(f64::from(pic.width), f64::from(pic.height), k); + if ends_early(bytes, kind) { + m.warn(ENDS_EARLY); + } + if pic.items.len() >= READER_ITEMS { + m.warn(AT_LIMIT); + } + for item in pic.items { + m.item(item); + } + Ok(m.finish(kind, pic.skipped_records)) +} diff --git a/crates/metafile/src/import/wmf.rs b/crates/metafile/src/import/wmf.rs deleted file mode 100644 index 7a682e59a9..0000000000 --- a/crates/metafile/src/import/wmf.rs +++ /dev/null @@ -1,338 +0,0 @@ -//! WMF records (MS-WMF) played on a [`Player`]. A placeable header gives the picture's box in -//! logical units and the units an inch; without one, the first window origin and extent are the -//! box, at 1440 units an inch. - -use vectorcraft_geom::{Affine, Point, Rect, shapes}; - -use super::{ArcKind, BrushObj, FontObj, Obj, PenObj, Player}; -use crate::bytes::Reader; -use crate::dib::{self, Alpha}; -use crate::wmf::PLACEABLE_KEY; -use crate::{Imported, Kind}; - -/// Units an inch when the file doesn't say (twips). -const DEFAULT_INCH: f64 = 1440.0; -/// Records that change nothing VectorCraft keeps (background, raster and mapping details, palettes, -/// escapes). -const IGNORED: &[u16] = &[ - 0x0102, 0x0103, 0x0104, 0x0105, 0x0107, 0x0108, 0x0201, 0x020A, 0x020B, 0x020C, 0x020D, 0x020E, 0x020F, 0x0211, 0x0410, 0x0412, 0x0231, 0x0234, - 0x0035, 0x0037, 0x0139, 0x0436, 0x0626, -]; - -fn point(r: &mut Reader) -> Option { - Some(Point::new(f64::from(r.i16()?), f64::from(r.i16()?))) -} - -/// A point stored y first. -fn point_yx(r: &mut Reader) -> Option { - let y = f64::from(r.i16()?); - Some(Point::new(f64::from(r.i16()?), y)) -} - -/// A rectangle stored bottom, right, top, left. -fn rect_brtl(r: &mut Reader) -> Option { - let (b, rt, t, l) = (r.i16()?, r.i16()?, r.i16()?, r.i16()?); - Some(Rect::new(f64::from(l), f64::from(t), f64::from(rt), f64::from(b))) -} - -fn color(r: &mut Reader) -> Option<[u8; 3]> { - let [red, g, b, _] = r.u32()?.to_le_bytes(); - Some([red, g, b]) -} - -fn points(r: &mut Reader, n: usize) -> Option> { - if r.rest().len() < n * 4 { - return None; - } - (0..n).map(|_| point(r)).collect() -} - -/// ANSI text (read as Latin-1). -fn ansi(b: &[u8]) -> String { - b.iter().map(|c| char::from(*c)).collect() -} - -/// The records' start, and the box and units an inch of a placeable header. -fn header(bytes: &[u8]) -> Option<(usize, Option<(Rect, f64)>)> { - let mut r = Reader::new(bytes); - let placeable = if r.u32()? == PLACEABLE_KEY { - r.skip(2)?; - let (l, t, rt, b) = (r.i16()?, r.i16()?, r.i16()?, r.i16()?); - let inch = r.u16()?; - let inch = if inch == 0 { DEFAULT_INCH } else { f64::from(inch) }; - Some((Rect::new(f64::from(l), f64::from(t), f64::from(rt), f64::from(b)).abs(), inch)) - } else { - None - }; - let start = if placeable.is_some() { 22 } else { 0 }; - let mut h = Reader::new(bytes.get(start..)?); - h.skip(2)?; - let words = usize::from(h.u16()?); - if words < 9 { - return None; - } - Some((start + words * 2, placeable)) -} - -/// The first window origin and extent, as the picture's box when there is no placeable header. -fn window(bytes: &[u8], mut at: usize) -> Option { - let (mut org, mut ext) = (None, None); - while let Some(head) = bytes.get(at..at + 6) { - let words = u32::from_le_bytes([head[0], head[1], head[2], head[3]]) as usize; - let function = u16::from_le_bytes([head[4], head[5]]); - if words < 3 || function == 0 { - break; - } - let mut r = Reader::new(bytes.get(at + 6..).unwrap_or_default()); - match function { - 0x020B if org.is_none() => org = point_yx(&mut r), - 0x020C if ext.is_none() => ext = point_yx(&mut r), - _ => {} - } - if org.is_some() && ext.is_some() { - break; - } - at = at.saturating_add(words.saturating_mul(2)); - } - let o = org.unwrap_or(Point::ZERO); - let e = ext?; - Some(Rect::new(o.x, o.y, o.x + e.x, o.y + e.y).abs()) -} - -/// Logical → document for a placeable file whose window (`org`, `ext`) is mapped onto its box `b`; -/// a negative extent flips that axis, as in GDI. -fn window_map(b: Rect, k: f64, org: Point, ext: Point) -> Affine { - let ratio = |box_len: f64, e: f64| if e.abs() > 1e-12 { box_len / e } else { 1.0 }; - Affine::scale_non_uniform(k * ratio(b.width(), ext.x), k * ratio(b.height(), ext.y)) * Affine::translate(-org.to_vec2()) -} - -pub(super) fn play(bytes: &[u8]) -> Result { - let (start, placeable) = header(bytes).ok_or("the WMF header is damaged")?; - let (frame, inch) = match placeable { - Some((b, inch)) if b.width() > 0.0 && b.height() > 0.0 => (Some(b), inch), - _ => (window(bytes, start).filter(|w| w.width() > 0.0 && w.height() > 0.0), DEFAULT_INCH), - }; - let k = 72.0 / inch; - let origin = frame.map_or(Point::ZERO, |f| f.origin()); - let artboard = frame.map_or(Rect::new(0.0, 0.0, 1.0, 1.0), |f| Rect::new(0.0, 0.0, f.width() * k, f.height() * k)); - let mut p = Player::new(Kind::Wmf, Affine::scale(k) * Affine::translate(-origin.to_vec2()), 25.4 / inch, artboard); - // With a placeable header, the window records map the window onto the box. - let placed = placeable.map(|(b, _)| b).filter(|b| b.width() > 0.0 && b.height() > 0.0); - let mut win = (placed.map_or(Point::ZERO, |b| b.origin()), placed.map_or(Point::ZERO, |b| Point::new(b.width(), b.height()))); - let mut at = start; - let mut ended = false; - while let Some(head) = bytes.get(at..at + 6) { - let words = u32::from_le_bytes([head[0], head[1], head[2], head[3]]) as usize; - let function = u16::from_le_bytes([head[4], head[5]]); - if function == 0 { - ended = true; - break; - } - let Some(rec) = words.checked_mul(2).and_then(|n| bytes.get(at..at.checked_add(n)?)).filter(|_| words >= 3) else { break }; - if !matches!(function, 0x0213 | 0x0214) { - p.flush(); - } - if let (Some(b), 0x020B | 0x020C) = (placed, function) { - if let Some(v) = point_yx(&mut Reader::new(rec.get(6..).unwrap_or_default())) { - if function == 0x020B { - win.0 = v; - } else { - win.1 = v; - } - p.dev_to_doc = window_map(b, k, win.0, win.1); - } - } else if record(&mut p, function, rec.get(6..).unwrap_or_default()).is_none() { - p.skip(); - } - at += rec.len(); - } - if !ended { - p.warn("the file ends early: what it held was imported"); - } - let mut out = p.finish(); - // No box given: the art's bounds. - if frame.is_none() - && let Some(b) = out.document.layers.first().and_then(|l| vectorcraft_doc::live::nodes_bounds(l.children().map_or(&[][..], |c| c.as_slice()))) - && let Some(a) = out.document.artboards.first_mut() - { - a.rect = Rect::from_origin_size(b.origin(), (b.width().max(1.0), b.height().max(1.0))); - } - Ok(out) -} - -/// An image record's source rectangle (from the bottom for a bottom-up DIB) and destination. -fn blit(p: &mut Player, rop: u32, src: (i16, i16, i16, i16), dest: (i16, i16, i16, i16), packed: Option<&[u8]>) { - let (xd, yd, wd, hd) = (f64::from(dest.0), f64::from(dest.1), f64::from(dest.2), f64::from(dest.3)); - let d = Rect::new(xd, yd, xd + wd, yd + hd); - let Some(packed) = packed else { return p.pattern_blit(d, rop) }; - let parts = dib::split(packed); - let img = parts.ok_or_else(|| "damaged".to_string()).and_then(|(bmi, bits)| dib::decode(bmi, bits, Alpha::Ignore, &mut p.pixels_left)); - let bottom_up = parts.and_then(|(bmi, _)| bmi.get(8..12)).is_some_and(|h| i32::from_le_bytes([h[0], h[1], h[2], h[3]]) > 0); - let ih = img.as_ref().map_or(0.0, |i| f64::from(i.height)); - let (xs, ys, ws, hs) = (f64::from(src.0), f64::from(src.1), f64::from(src.2), f64::from(src.3)); - let top = if bottom_up { ih - ys - hs } else { ys }; - p.image(img, Rect::new(xs, top, xs + ws, top + hs), d, rop, 1.0); -} - -/// PolyPolygon (0x0538). -fn rec_poly_polygon(p: &mut Player, r: &mut Reader) -> Option<()> { - let n = usize::from(r.u16()?); - if r.rest().len() < n * 2 { - return None; - } - let counts: Vec = (0..n).map(|_| r.u16().map(usize::from)).collect::>()?; - let mut polys = Vec::with_capacity(n); - for c in counts { - polys.push(points(r, c)?); - } - p.poly_poly(&polys, true); - Some(()) -} - -/// Arc (0x0817), Pie (0x081A) and Chord (0x0830). -fn rec_arc(p: &mut Player, function: u16, r: &mut Reader) -> Option<()> { - let (end, start) = (point_yx(r)?, point_yx(r)?); - let b = rect_brtl(r)?; - let kind = match function { - 0x0817 => ArcKind::Open, - 0x081A => ArcKind::Pie, - _ => ArcKind::Chord, - }; - p.arc(b, start, end, kind); - Some(()) -} - -/// CreateFontIndirect (0x02FB). -fn rec_create_font(p: &mut Player, r: &mut Reader) -> Option<()> { - let height = f64::from(r.i16()?); - r.skip(2)?; - let escapement = f64::from(r.i16()?); - r.skip(2)?; - let weight = i32::from(r.i16()?); - let italic = r.bytes(1)?.first().is_some_and(|b| *b != 0); - r.skip(7)?; - let face: Vec = r.rest().iter().take(32).take_while(|b| **b != 0).copied().collect(); - p.create(Obj::Font(FontObj { height, escapement, weight, italic, face: ansi(&face) })); - Some(()) -} - -/// TextOut (0x0521). -fn rec_text_out(p: &mut Player, r: &mut Reader) -> Option<()> { - let n = usize::try_from(r.i16()?).ok()?; - let s = ansi(r.bytes(n)?); - r.skip(n % 2)?; - let at = point_yx(r)?; - p.text(at, &s); - Some(()) -} - -/// ExtTextOut (0x0A32). -fn rec_ext_text_out(p: &mut Player, r: &mut Reader) -> Option<()> { - let at = point_yx(r)?; - let n = usize::try_from(r.i16()?).ok()?; - let opts = r.u16()?; - // ETO_OPAQUE or ETO_CLIPPED: a rectangle comes first. - if opts & 0x6 != 0 { - r.skip(8)?; - } - let s = ansi(r.bytes(n)?); - p.text(at, &s); - Some(()) -} - -/// StretchDIB (0x0F43). -fn rec_stretch_dib(p: &mut Player, r: &mut Reader) -> Option<()> { - let rop = r.u32()?; - r.skip(2)?; - let (hs, ws, ys, xs) = (r.i16()?, r.i16()?, r.i16()?, r.i16()?); - let (hd, wd, yd, xd) = (r.i16()?, r.i16()?, r.i16()?, r.i16()?); - blit(p, rop, (xs, ys, ws, hs), (xd, yd, wd, hd), Some(r.rest())); - Some(()) -} - -/// StretchBlt (0x0B41). -fn rec_stretch_blt(p: &mut Player, body: &[u8], r: &mut Reader) -> Option<()> { - let rop = r.u32()?; - let (hs, ws, ys, xs) = (r.i16()?, r.i16()?, r.i16()?, r.i16()?); - // Without a bitmap, a reserved word comes before the destination. - let with_bitmap = body.len() > 22; - if !with_bitmap { - r.skip(2)?; - } - let (hd, wd, yd, xd) = (r.i16()?, r.i16()?, r.i16()?, r.i16()?); - blit(p, rop, (xs, ys, ws, hs), (xd, yd, wd, hd), with_bitmap.then(|| r.rest())); - Some(()) -} - -/// BitBlt (0x0940). -fn rec_bit_blt(p: &mut Player, body: &[u8], r: &mut Reader) -> Option<()> { - let rop = r.u32()?; - let (ys, xs) = (r.i16()?, r.i16()?); - let with_bitmap = body.len() > 20; - if !with_bitmap { - r.skip(2)?; - } - let (h, w, yd, xd) = (r.i16()?, r.i16()?, r.i16()?, r.i16()?); - blit(p, rop, (xs, ys, w, h), (xd, yd, w, h), with_bitmap.then(|| r.rest())); - Some(()) -} - -/// Play one record (`r`: its parameters). `None`: unknown or damaged. -fn record(p: &mut Player, function: u16, body: &[u8]) -> Option<()> { - let mut r = Reader::new(body); - match function { - 0x001E => p.save(), - 0x0127 => p.restore(i32::from(r.i16()?)), - 0x0106 => p.set_fill_mode(r.u16()? == 1), - 0x0209 => p.set_text_color(color(&mut r)?), - 0x012E => p.set_text_align(u32::from(r.u16()?)), - 0x0214 => p.move_to(point_yx(&mut r)?), - 0x0213 => { - let pt = point_yx(&mut r)?; - p.poly_to(&[pt], false); - } - 0x0324 | 0x0325 => { - let n = usize::try_from(r.i16()?).ok()?; - let pts = points(&mut r, n)?; - p.poly(&pts, function == 0x0324, false); - } - 0x0538 => rec_poly_polygon(p, &mut r)?, - 0x041B => p.figure(shapes::rectangle(rect_brtl(&mut r)?.abs()).to_bezpath(), true), - 0x0418 => p.figure(shapes::ellipse(rect_brtl(&mut r)?.abs()).to_bezpath(), true), - 0x061C => { - let (h, w) = (f64::from(r.i16()?), f64::from(r.i16()?)); - p.figure(super::round_rect(rect_brtl(&mut r)?, w, h), true); - } - 0x0817 | 0x081A | 0x0830 => rec_arc(p, function, &mut r)?, - 0x0416 => p.clip_rect(rect_brtl(&mut r)?), - 0x0415 => p.exclude_clip(), - 0x012D => p.select(u32::from(r.u16()?)), - 0x01F0 => p.delete(u32::from(r.u16()?)), - 0x02FA => { - let style = u32::from(r.u16()?); - let width = f64::from(r.i16()?); - r.skip(2)?; - p.create(Obj::Pen(PenObj { style, width, color: color(&mut r)?, entries: vec![] })); - } - 0x02FC => { - let style = u32::from(r.u16()?); - p.create(Obj::Brush(BrushObj::from_log(style, color(&mut r)?))); - } - 0x02FB => rec_create_font(p, &mut r)?, - 0x00F7 | 0x06FF => p.create(Obj::Other), - 0x01F9 | 0x0142 => p.create(Obj::Brush(BrushObj::Pattern)), - 0x0521 => rec_text_out(p, &mut r)?, - 0x0A32 => rec_ext_text_out(p, &mut r)?, - 0x0F43 => rec_stretch_dib(p, &mut r)?, - 0x0B41 => rec_stretch_blt(p, body, &mut r)?, - 0x0940 => rec_bit_blt(p, body, &mut r)?, - 0x061D => { - let rop = r.u32()?; - let (h, w, y, x) = (f64::from(r.i16()?), f64::from(r.i16()?), f64::from(r.i16()?), f64::from(r.i16()?)); - p.pattern_blit(Rect::new(x, y, x + w, y + h), rop); - } - f if IGNORED.contains(&f) => {} - _ => return None, - } - Some(()) -} diff --git a/crates/metafile/src/lib.rs b/crates/metafile/src/lib.rs index 0e699236d7..86d268cee1 100644 --- a/crates/metafile/src/lib.rs +++ b/crates/metafile/src/lib.rs @@ -13,13 +13,14 @@ //! lines or gradients, so clipped art is written whole, images over white, dashes as separate //! lines and gradients and patterns as one colour (each loss comes back as a warning). //! -//! [`import`] reads either format back into a document of one artboard (the picture's frame) and -//! one layer: paths with fills and strokes, clipping, images and text. Records it doesn't read are -//! skipped, with one warning. [`import_pict`] reads QuickDraw pictures (PICT, versions 1 and 2) -//! into the same kind of document. +//! [`import`] reads either format (an EMF with its EMF+ records too, through `craft_metafile`) +//! into a document of one artboard (the picture's frame) and one layer: paths with fills and +//! strokes, clipping, images and text. Records it doesn't read are skipped, with one warning. +//! [`import_pict`] reads QuickDraw pictures (PICT, versions 1 and 2) into the same kind of +//! document. //! -//! - `bytes`: little-endian writing and bounds-checked reading. -//! - `dib`: device-independent bitmaps, both ways. +//! - `bytes`: little-endian writing. +//! - `dib`: device-independent bitmaps for the writers. //! - `scene`: the document walk both writers share. //! - `emf`, `wmf`: the writers. //! - `import`: the readers. diff --git a/crates/metafile/src/tests/import.rs b/crates/metafile/src/tests/import.rs index 1e0ec5671b..f5870c5f95 100644 --- a/crates/metafile/src/tests/import.rs +++ b/crates/metafile/src/tests/import.rs @@ -151,13 +151,14 @@ fn dashes_gradients_and_images_round_trip_through_emf() { // ---------- hand-built records ---------- /// An EMF of `records` (type, body) with a frame of `w` × `h` hundredths of a millimetre on a -/// device of 100 pixels a millimetre. +/// device of 100 pixels a millimetre. Bodies are padded to a multiple of 4 bytes. fn hand_emf(w: i32, h: i32, records: &[(u32, Vec)]) -> Vec { let mut o = Out::default(); let rec = |o: &mut Out, kind: u32, body: &[u8]| { o.u32(kind); - o.u32(8 + body.len() as u32); + o.u32(8 + body.len().next_multiple_of(4) as u32); o.bytes(body); + o.pad(4); }; let mut head = Out::default(); head.bytes(&[0; 16]); @@ -336,6 +337,129 @@ fn wmf_window_is_mapped_onto_the_placeable_box() { } } +#[test] +fn wmf_without_a_placeable_header_is_read_at_1440_units_an_inch() { + // The window is 2880 × 1440 units: 2 × 1 inches. The rectangle is its left half. + let records = vec![(0x020B, le16(&[0, 0])), (0x020C, le16(&[1440, 2880])), (0x041B, le16(&[1440, 1440, 0, 0]))]; + let plain = hand_wmf(2880, 1440, &records)[22..].to_vec(); + let back = import(&plain).unwrap(); + assert!(near(back.document.artboards[0].rect, Rect::new(0.0, 0.0, 144.0, 72.0), 1e-6), "{:?}", back.document.artboards[0].rect); + let p = paths(&back.document); + assert_eq!(p.len(), 1); + assert!(near(p[0].geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 72.0, 72.0), 1e-6), "{:?}", p[0].geometric_bounds()); +} + +#[test] +fn wmf_without_a_placeable_box_in_a_metric_map_mode_is_read_at_96_pixels_an_inch() { + // MM_TWIPS (y up) and a window of 1440 twips square: one inch. The rectangle is the whole window. + let records = vec![(0x0103, le16(&[6])), (0x020B, le16(&[0, 0])), (0x020C, le16(&[1440, 1440])), (0x041B, le16(&[1440, 1440, 0, 0]))]; + let boxed = hand_wmf(1440, 1440, &records); + let plain = boxed[22..].to_vec(); + // The box runs from right to left, so it gives no size. + let mut inverted = boxed; + inverted[6..8].copy_from_slice(&1440i16.to_le_bytes()); + inverted[10..12].copy_from_slice(&0i16.to_le_bytes()); + for bytes in [plain, inverted] { + let back = import(&bytes).unwrap(); + assert!(near(back.document.artboards[0].rect, Rect::new(0.0, 0.0, 72.0, 72.0), 1e-4), "{:?}", back.document.artboards[0].rect); + let p = paths(&back.document); + assert_eq!(p.len(), 1); + assert!(near(p[0].geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 72.0, 72.0), 1e-4), "{:?}", p[0].geometric_bounds()); + } +} + +#[test] +fn wmf_whose_metric_map_mode_is_restored_away_is_read_at_1440_units_an_inch() { + // SAVEDC, MM_TWIPS, then RESTOREDC back to MM_TEXT, by a count of levels and by a level; the + // drawing is then the one in `wmf_without_a_placeable_header_is_read_at_1440_units_an_inch`. + for restore in [-1i16, 1] { + let records = vec![ + (0x001E, Vec::new()), + (0x0103, le16(&[6])), + (0x0127, le16(&[restore])), + (0x020B, le16(&[0, 0])), + (0x020C, le16(&[1440, 2880])), + (0x041B, le16(&[1440, 1440, 0, 0])), + ]; + let plain = hand_wmf(2880, 1440, &records)[22..].to_vec(); + let back = import(&plain).unwrap(); + assert!(near(back.document.artboards[0].rect, Rect::new(0.0, 0.0, 144.0, 72.0), 1e-6), "{restore}: {:?}", back.document.artboards[0].rect); + let p = paths(&back.document); + assert_eq!(p.len(), 1); + assert!(near(p[0].geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 72.0, 72.0), 1e-6), "{restore}: {:?}", p[0].geometric_bounds()); + } +} + +#[test] +fn wmf_that_draws_in_a_metric_map_mode_and_restores_is_read_at_96_pixels_an_inch() { + // SAVEDC, MM_TWIPS, a one-inch rectangle, then RESTOREDC back to MM_TEXT with nothing more drawn. + let records = vec![ + (0x001E, Vec::new()), + (0x0103, le16(&[6])), + (0x020B, le16(&[0, 0])), + (0x020C, le16(&[1440, 1440])), + (0x041B, le16(&[1440, 1440, 0, 0])), + (0x0127, le16(&[-1])), + ]; + let plain = hand_wmf(1440, 1440, &records)[22..].to_vec(); + let back = import(&plain).unwrap(); + let p = paths(&back.document); + assert_eq!(p.len(), 1); + let b = p[0].geometric_bounds().unwrap(); + assert!((b.width() - 72.0).abs() < 1e-4 && (b.height() - 72.0).abs() < 1e-4, "{b:?}"); +} + +#[test] +fn wmf_records_the_mix_mode_keeps_from_drawing_do_not_set_its_scale() { + // A rectangle of 1440 units in MM_TEXT; then SAVEDC, MM_TWIPS, a mix mode and two records that + // draw nothing under it, and RESTOREDC. + let rect = (0x041B, le16(&[1440, 1440, 0, 0])); + let patblt = |rop: u32| (0x061D, [rop.to_le_bytes().to_vec(), le16(&[100, 100, 0, 0])].concat()); + let cases = [ + // R2_NOP and R2_XORPEN: rectangles draw nothing. + (11i16, [rect.clone(), rect.clone()]), + (7, [rect.clone(), rect.clone()]), + // R2_NOP: PATBLT with PATCOPY fills nothing. + (11, [patblt(0x00F0_0021), patblt(0x00F0_0021)]), + // R2_COPYPEN: PATBLT with DSTINVERT is not drawn. + (13, [patblt(0x0055_0009), patblt(0x0055_0009)]), + ]; + for (mix, hidden) in cases { + let mut records = vec![(0x020B, le16(&[0, 0])), (0x020C, le16(&[1440, 1440])), rect.clone()]; + records.extend([(0x001E, Vec::new()), (0x0103, le16(&[6])), (0x0104, le16(&[mix]))]); + records.extend(hidden); + records.push((0x0127, le16(&[-1]))); + let plain = hand_wmf(1440, 1440, &records)[22..].to_vec(); + let back = import(&plain).unwrap(); + let p = paths(&back.document); + assert_eq!(p.len(), 1, "mix {mix}: {p:?}"); + let b = p[0].geometric_bounds().unwrap(); + assert!((b.width() - 72.0).abs() < 1e-4 && (b.height() - 72.0).abs() < 1e-4, "mix {mix}: {b:?}"); + } + // R2_NOP, then SAVEDC, R2_COPYPEN and RESTOREDC bring R2_NOP back: the MM_TWIPS rectangle after + // them draws nothing. + let mut records = vec![(0x020B, le16(&[0, 0])), (0x020C, le16(&[1440, 1440])), rect.clone(), (0x0104, le16(&[11]))]; + records.extend([(0x001E, Vec::new()), (0x0104, le16(&[13])), (0x0127, le16(&[-1])), (0x0103, le16(&[6])), rect]); + let back = import(&hand_wmf(1440, 1440, &records)[22..]).unwrap(); + let p = paths(&back.document); + assert_eq!(p.len(), 1, "{p:?}"); + let b = p[0].geometric_bounds().unwrap(); + assert!((b.width() - 72.0).abs() < 1e-4 && (b.height() - 72.0).abs() < 1e-4, "restored: {b:?}"); +} + +#[test] +fn a_stroke_that_reaches_too_far_leaves_the_strokes_before_it() { + // The black pen draws from (0, 500) to (100, 500), then on to a point far outside the picture. + let records = vec![(37, le(&[0x8000_0007u32 as i32])), (27, le(&[0, 500])), (54, le(&[100, 500])), (54, le(&[100_000_000, 500]))]; + let back = import(&hand_emf(5000, 3000, &records)).unwrap(); + let p = paths(&back.document); + assert_eq!(p.len(), 1, "{p:?}"); + let mm = 72.0 / 25.4; + let b = p[0].geometric_bounds().unwrap(); + assert!((b.x0).abs() < 0.01 && (b.x1 - mm).abs() < 0.01 && (b.y0 - 5.0 * mm).abs() < 0.01, "{b:?}"); + assert!(back.warnings.iter().any(|w| w.contains("far outside")), "{:?}", back.warnings); +} + #[test] fn damaged_files_fail_or_import_partly() { let good = emf(&sample()).bytes; @@ -357,6 +481,18 @@ fn damaged_files_fail_or_import_partly() { assert!(import(&huge).is_ok()); } +#[test] +fn a_file_with_more_objects_than_are_read_says_so() { + // RECTANGLE records: 10 more than the reader keeps, then a few under that. + let rect = (43, le(&[0, 0, 100, 100])); + let many = hand_emf(5000, 3000, &vec![rect.clone(); 200_010]); + let back = import(&many).unwrap(); + assert_eq!(paths(&back.document).len(), 200_000); + assert!(back.warnings.iter().any(|w| w.contains("reached the most objects")), "{:?}", back.warnings); + let few = import(&hand_emf(5000, 3000, &vec![rect; 3])).unwrap(); + assert!(few.warnings.is_empty(), "{:?}", few.warnings); +} + /// An EMR_STRETCHDIBITS copying `png` (a BI_PNG bitmap) to a 10 × 10 box. fn png_stretch_dibits(png: &[u8]) -> Vec { // Bounds; destination, source and its size; the BITMAPINFO and the bits (from the record start); @@ -371,19 +507,29 @@ fn png_stretch_dibits(png: &[u8]) -> Vec { } #[test] -fn embedded_bitmaps_share_one_pixel_budget() { - // #3600: each bitmap was bounded but not their total, so many records of the largest one a record - // may hold cost minutes. Those past the file's budget are left out before they're decoded. +fn oversized_embedded_bitmaps_are_left_out_before_decoding() { + // #3600: many records of the largest bitmap a record may hold cost minutes. Each of these claims + // more pixels than one image may have, so the reader leaves it out from its header. (The reader's + // budget for all the images of one file is tested where the reader is.) let records = vec![(81, png_stretch_dibits(&png_claiming(1 << 13, 1 << 13))); 5]; let back = import(&hand_emf(5000, 3000, &records)).unwrap(); - assert!(back.warnings.iter().any(|w| w == "images past the most pixels one file may hold were left out"), "{:?}", back.warnings); + assert!(!all(&back.document).iter().any(|n| matches!(n.kind, NodeKind::Image(_)))); } #[test] fn clips_nest_only_so_deep() { - // Each clip inside the last one used to nest a clipping group one level deeper, past the stack. - let mut records = vec![(30, le(&[0, 0, 1500, 1500])); 200_000]; - records.push((43, le(&[100, 100, 200, 200]))); + // Each clip inside the last one nests a clipping group one level deeper; past the stack they + // are left out with a warning. + let mut records = vec![]; + // As many as the reader keeps: one more than the stack. + for i in 0..32 { + // BEGINPATH, a rectangle a little smaller each time, ENDPATH, SELECTCLIPPATH (RGN_AND). + records.push((59, vec![])); + records.push((43, le(&[100 + i, 100 + i, 2000 - i, 2000 - i]))); + records.push((60, vec![])); + records.push((67, le(&[1]))); + } + records.push((43, le(&[500, 500, 600, 600]))); let back = import(&hand_emf(5000, 3000, &records)).unwrap(); let mut depth = 0; let mut n = back.document.layers[0].children().unwrap()[0].clone(); @@ -393,4 +539,324 @@ fn clips_nest_only_so_deep() { } assert_eq!(depth, vectorcraft_doc::clipnest::MAX_NEST); assert!(back.warnings.iter().any(|w| w.contains("clips nested more than")), "{:?}", back.warnings); + // A hostile count of clip records: each one used to nest a clipping group one level deeper, + // past the stack. They make one clip. + let mut records = vec![(30, le(&[0, 0, 1500, 1500])); 200_000]; + records.push((43, le(&[100, 100, 200, 200]))); + let back = import(&hand_emf(5000, 3000, &records)).unwrap(); + let layer = back.document.layers[0].children().unwrap(); + assert_eq!(layer.len(), 1); + let NodeKind::Group { children, clip: true } = &layer[0].kind else { panic!("a clipping group: {:?}", layer[0].kind) }; + assert!(children.iter().all(|c| !matches!(c.kind, NodeKind::Group { .. })), "one level"); + assert_eq!(paths(&back.document).len(), 1); +} + +/// An EMR_COMMENT holding EMF+ `records` (type, flags, data). +fn emf_plus(records: &[(u16, u16, Vec)]) -> Vec { + let mut plus = Out::default(); + for (kind, flags, data) in records { + plus.u16(*kind); + plus.u16(*flags); + plus.u32(12 + data.len() as u32); + plus.u32(data.len() as u32); + plus.bytes(data); + } + let mut body = Out::default(); + body.u32(4 + plus.len() as u32); + // "EMF+" + body.u32(0x2B46_4D45); + body.bytes(&plus.0); + body.0 +} + +fn le_f32(values: &[f32]) -> Vec { + values.iter().flat_map(|v| v.to_le_bytes()).collect() +} + +#[test] +fn emf_plus_only_pictures_import_their_drawing() { + // An EMF+ only file: its EMF records draw nothing, so it was imported empty with a warning. + // EmfPlusHeader (version, flags, 96 dpi), FillRects with an inline green color (flag S) and one + // rectangle of 10 × 5 mm at (10, 10) mm in device pixels, EmfPlusEndOfFile. + let header = le(&[0xDBC0_1002u32 as i32, 0, 96, 96]); + let rects = [le(&[0xFF00_FF00u32 as i32, 1]), le_f32(&[1000.0, 1000.0, 1000.0, 500.0])].concat(); + let comment = emf_plus(&[(0x4001, 0, header), (0x400A, 0x8000, rects), (0x4002, 0, vec![])]); + let back = import(&hand_emf(5000, 3000, &[(70, comment)])).unwrap(); + assert!(back.warnings.is_empty(), "{:?}", back.warnings); + let p = paths(&back.document); + assert_eq!(p.len(), 1); + assert_eq!(fill_rgb(&p[0]), Some([0, 255, 0])); + let mm = 72.0 / 25.4; + let b = p[0].geometric_bounds().unwrap(); + assert!(near(b, Rect::new(10.0 * mm, 10.0 * mm, 20.0 * mm, 15.0 * mm), 0.01), "{b:?}"); +} + +#[test] +fn hatched_brushes_fill_with_their_average_color() { + // CREATEBRUSHINDIRECT: a hatched (style 2) blue brush, selected; a null pen; a rectangle. The + // hatch is drawn over the white background, so the average is a light blue. + let records = vec![(39, le(&[1, 2, 0x00ff_0000, 0])), (37, le(&[1])), (37, le(&[0x8000_0008u32 as i32])), (43, le(&[1000, 1000, 2000, 1500]))]; + let back = import(&hand_emf(5000, 3000, &records)).unwrap(); + assert_eq!(back.warnings, vec!["hatched and pattern brushes are filled with their average color".to_string()]); + let p = paths(&back.document); + assert_eq!(p.len(), 1); + let [r, g, b] = fill_rgb(&p[0]).unwrap(); + assert!(b == 255 && r == g && r > 0 && r < 255, "{:?}", [r, g, b]); + // With a transparent background (SETBKMODE 1) the hatch is blue with gaps: a translucent fill. + let mut records = records; + records.insert(0, (18, le(&[1]))); + let back = import(&hand_emf(5000, 3000, &records)).unwrap(); + let p = paths(&back.document); + assert_eq!(fill_rgb(&p[0]), Some([0, 0, 255])); + let AppearanceItem::Fill(f) = &p[0].appearance.items[0] else { panic!("a fill") }; + assert!(f.opacity > 0.0 && f.opacity < 1.0, "{}", f.opacity); +} + +#[test] +fn text_keeps_a_stretch_across() { + // A world transform twice as wide as it is high, a 10 mm font and "Hi". + let mut text = vec![0; 16]; + text.extend(le(&[1, 0, 0])); + text.extend(le(&[1000, 1500, 2, 76, 0, 0, 0, 0, 0, 0])); + text.extend("Hi".encode_utf16().flat_map(u16::to_le_bytes)); + let mut font = le(&[2, -1000, 0, 0, 0, 400]); + font.extend([0u8; 8]); + font.extend("Arial".encode_utf16().chain(std::iter::repeat_n(0, 27)).flat_map(u16::to_le_bytes)); + let world = [2.0f32, 0.0, 0.0, 1.0, 0.0, 0.0].iter().flat_map(|v| v.to_le_bytes()).collect(); + let records = vec![(35, world), (82, font), (37, le(&[2])), (84, text)]; + let back = import(&hand_emf(5000, 3000, &records)).unwrap(); + let t = all(&back.document) + .into_iter() + .find_map(|n| match n.kind { + NodeKind::Text(t) => Some(t), + _ => None, + }) + .unwrap(); + let mm = 72.0 / 25.4; + assert!((t.runs[0].style.size - 10.0 * mm).abs() < 0.01, "{}", t.runs[0].style.size); + let [a, b, c, d, ..] = t.xf.as_coeffs(); + assert!((a - 2.0).abs() < 1e-6 && b.abs() < 1e-6 && c.abs() < 1e-6 && (d - 1.0).abs() < 1e-6, "{:?}", t.xf); +} + +#[test] +fn a_clip_whose_box_holds_the_picture_still_clips() { + // A diamond around the middle of the picture, whose box holds the whole frame but which cuts + // off its corners: BEGINPATH, POLYGON, ENDPATH, SELECTCLIPPATH (RGN_COPY), then a rectangle. + let mut diamond = le(&[0, 0, 0, 0, 4]); + diamond.extend(le(&[2500, -500, 5500, 1500, 2500, 3500, -500, 1500])); + // A bow tie through the four corners of a box around the picture. + let mut bow_tie = le(&[0, 0, 0, 0, 4]); + bow_tie.extend(le(&[-500, -500, 5500, 3500, 5500, -500, -500, 3500])); + // Two open figures through the four corners, the top edge and the bottom edge, which enclose + // nothing: MOVETOEX, LINETO, MOVETOEX, LINETO. + let edges = vec![(27, le(&[-500, -500])), (54, le(&[5500, -500])), (27, le(&[5500, 3500])), (54, le(&[-500, 3500]))]; + // One figure through the four corners that runs back over its edges and encloses nothing: + // POLYLINE top-left, top-right, top-left, bottom-left, bottom-right, bottom-left. + let mut retraced = le(&[0, 0, 0, 0, 6]); + retraced.extend(le(&[-500, -500, 5500, -500, -500, -500, -500, 3500, 5500, 3500, -500, 3500])); + for clip in [vec![(3, diamond)], vec![(3, bow_tie)], edges, vec![(4, retraced)]] { + let records = [vec![(59, vec![])], clip, vec![(60, vec![]), (67, le(&[5])), (43, le(&[0, 0, 5000, 3000]))]].concat(); + let back = import(&hand_emf(5000, 3000, &records)).unwrap(); + let layer = back.document.layers[0].children().unwrap(); + assert_eq!(layer.len(), 1); + assert!(matches!(layer[0].kind, NodeKind::Group { clip: true, .. }), "{:?}", layer[0].kind); + } +} + +#[test] +fn dual_emf_plus_files_draw_their_emf_plus_records() { + // A dual file (header flag 1): a translucent red EMF+ fill, and a plain rectangle that is only + // the fallback for readers of plain records. + let header = le(&[0xDBC0_1002u32 as i32, 0, 96, 96]); + let rects = [le(&[0x80FF_0000u32 as i32, 1]), le_f32(&[1000.0, 1000.0, 1000.0, 500.0])].concat(); + let comment = emf_plus(&[(0x4001, 1, header), (0x400A, 0x8000, rects), (0x4002, 0, vec![])]); + let back = import(&hand_emf(5000, 3000, &[(70, comment), (43, le(&[3000, 1000, 4000, 2000]))])).unwrap(); + let p = paths(&back.document); + assert_eq!(p.len(), 1); + assert_eq!(fill_rgb(&p[0]), Some([255, 0, 0])); + let AppearanceItem::Fill(f) = &p[0].appearance.items[0] else { panic!("a fill") }; + assert!((f.opacity - 128.0 / 255.0).abs() < 1e-6, "{}", f.opacity); +} + +#[test] +fn translucent_strokes_drawn_one_after_another_stay_apart() { + // EmfPlusObject: pen 0, 1 pixel wide, with a solid brush of `argb`; then two EmfPlusDrawLines + // with it, from A to B and from B back to A. + let header = le(&[0xDBC0_1002u32 as i32, 0, 96, 96]); + let lines = |argb: u32| { + let pen = [le(&[0xDBC0_1002u32 as i32, 0, 0, 2]), le_f32(&[1.0]), le(&[0xDBC0_1002u32 as i32, 0, argb as i32])].concat(); + let a_to_b = [le(&[2]), le_f32(&[1000.0, 1000.0, 3000.0, 1000.0])].concat(); + let b_to_a = [le(&[2]), le_f32(&[3000.0, 1000.0, 1000.0, 1000.0])].concat(); + let comment = emf_plus(&[(0x4001, 0, header.clone()), (0x4008, 0x0200, pen), (0x400D, 0, a_to_b), (0x400D, 0, b_to_a), (0x4002, 0, vec![])]); + paths(&import(&hand_emf(5000, 3000, &[(70, comment)])).unwrap().document) + }; + // Each translucent stroke keeps its own opacity, so where they overlap both show. + let p = lines(0x80FF_0000); + assert_eq!(p.len(), 2, "{p:?}"); + for n in &p { + let AppearanceItem::Stroke(st) = &n.appearance.items[0] else { panic!("a stroke") }; + assert!((st.opacity - 128.0 / 255.0).abs() < 1e-6, "{}", st.opacity); + } + // Opaque strokes still join into one path. + assert_eq!(lines(0xFFFF_0000).len(), 1); +} + +#[test] +fn strokes_join_only_with_round_caps_round_joins_and_no_dashes() { + // CREATEPENINDIRECT: a 20-unit black pen of `style`, selected; then two lines one after the + // other that meet at a right angle. + let lines = |style: i16| { + let records = vec![ + (0x02FA, [le16(&[style, 20, 0]), 0u32.to_le_bytes().to_vec()].concat()), + (0x012D, le16(&[0])), + (0x0214, le16(&[100, 100])), + (0x0213, le16(&[100, 700])), + (0x0213, le16(&[700, 700])), + ]; + paths(&import(&hand_wmf(1440, 1440, &records)).unwrap().document) + }; + // Round caps and round joins, a solid line: one path, as a round join is the two round caps. + assert_eq!(lines(0).len(), 1); + // Flat caps and miter joins, flat caps alone and miter joins alone: each line keeps its caps. + for style in [0x2200, 0x0200, 0x2000] { + let p = lines(style); + assert_eq!(p.len(), 2, "style {style:#x}: {p:?}"); + } + // PS_DASH: each line's dashes start at its own start. + let p = lines(1); + assert_eq!(p.len(), 2, "{p:?}"); + assert!(p.iter().all(|n| n.appearance.stroke().is_some_and(|st| st.dash.is_some())), "{p:?}"); +} + +#[test] +fn pattern_brushes_fill_with_their_average_color() { + // CREATEDIBPATTERNBRUSHPT: a 2 × 2 tile of 24-bit pixels, two red and two blue (bottom-up rows + // padded to 4 bytes); selected, a null pen, a rectangle. + let mut brush = le(&[1, 0, 32, 40, 72, 16]); + brush.extend(le(&[40, 2, 2, 0x0018_0001, 0, 0, 0, 0, 0, 0])); + brush.extend([0, 0, 255, 255, 0, 0, 0, 0, 255, 0, 0, 0, 0, 255, 0, 0]); + let records = vec![(94, brush), (37, le(&[1])), (37, le(&[0x8000_0008u32 as i32])), (43, le(&[1000, 1000, 2000, 1500]))]; + let back = import(&hand_emf(5000, 3000, &records)).unwrap(); + assert_eq!(back.warnings, vec!["hatched and pattern brushes are filled with their average color".to_string()]); + let p = paths(&back.document); + assert_eq!(p.len(), 1); + let [r, g, b] = fill_rgb(&p[0]).unwrap(); + assert!((126..=128).contains(&r) && g == 0 && (126..=128).contains(&b), "{:?}", [r, g, b]); +} + +#[test] +fn clipped_text_is_clipped_to_its_rectangle() { + // EXTTEXTOUTW with ETO_CLIPPED and a rectangle of 9–12 × 10–16 mm, in an underlined and struck + // through font. + let mut text = vec![0; 16]; + text.extend(le(&[1, 0, 0])); + text.extend(le(&[1000, 1500, 2, 76, 4, 900, 1000, 1200, 1600, 0])); + text.extend("Hi".encode_utf16().flat_map(u16::to_le_bytes)); + let mut font = le(&[2, -1000, 0, 0, 0, 400]); + font.extend([0, 1, 1, 0, 0, 0, 0, 0]); + font.extend("Arial".encode_utf16().chain(std::iter::repeat_n(0, 27)).flat_map(u16::to_le_bytes)); + let mut records = vec![(82, font), (37, le(&[2])), (84, text)]; + let back = import(&hand_emf(5000, 3000, &records)).unwrap(); + let layer = back.document.layers[0].children().unwrap(); + assert_eq!(layer.len(), 1); + let NodeKind::Group { children, clip: true } = &layer[0].kind else { panic!("a clipping group: {:?}", layer[0].kind) }; + let mm = 72.0 / 25.4; + let own = Rect::new(9.0 * mm, 10.0 * mm, 12.0 * mm, 16.0 * mm); + assert!(near(children[0].geometric_bounds().unwrap(), own, 0.01)); + let NodeKind::Text(t) = &children[1].kind else { panic!("text") }; + assert!(t.runs[0].style.underline && t.runs[0].style.strikethrough); + // Under clip paths nested as deep as the stack, the text's own clip is still the innermost. + for i in 0..32 { + records.insert(0, (67, le(&[1]))); + records.insert(0, (60, vec![])); + records.insert(0, (43, le(&[100 + i, 100 + i, 4000 - i, 2500 - i]))); + records.insert(0, (59, vec![])); + } + let back = import(&hand_emf(5000, 3000, &records)).unwrap(); + let mut n = back.document.layers[0].children().unwrap()[0].clone(); + while let NodeKind::Group { children, clip: true } = &n.kind + && matches!(children.last().map(|c| &c.kind), Some(NodeKind::Group { .. })) + { + n = children.last().unwrap().clone(); + } + let NodeKind::Group { children, clip: true } = &n.kind else { panic!("a clipping group: {:?}", n.kind) }; + assert!(near(children[0].geometric_bounds().unwrap(), own, 0.01), "{:?}", children[0].geometric_bounds()); + assert!(matches!(children[1].kind, NodeKind::Text(_))); +} + +#[test] +fn excluded_clip_rectangles_clip() { + // EXCLUDECLIPRECT cuts the top-left of the picture out of the clip; the rectangle crosses it. + // The clip it cuts from is the picture's bounds (5000 × 3000 device pixels). + let records = vec![(29, le(&[0, 0, 1500, 1500])), (43, le(&[1000, 1000, 2000, 1500]))]; + let mut bytes = hand_emf(5000, 3000, &records); + for (i, v) in [0i32, 0, 5000, 3000].iter().enumerate() { + bytes[8 + i * 4..12 + i * 4].copy_from_slice(&v.to_le_bytes()); + } + let back = import(&bytes).unwrap(); + assert!(back.warnings.is_empty(), "{:?}", back.warnings); + let layer = back.document.layers[0].children().unwrap(); + assert_eq!(layer.len(), 1); + assert!(matches!(layer[0].kind, NodeKind::Group { clip: true, .. }), "{:?}", layer[0].kind); +} + +#[test] +fn shapes_under_the_same_clip_share_one_clipping_group() { + let records = vec![(30, le(&[0, 0, 1500, 1500])), (43, le(&[100, 100, 200, 200])), (43, le(&[300, 300, 400, 400]))]; + let back = import(&hand_emf(5000, 3000, &records)).unwrap(); + let layer = back.document.layers[0].children().unwrap(); + assert_eq!(layer.len(), 1); + let NodeKind::Group { children, clip: true } = &layer[0].kind else { panic!("a clipping group: {:?}", layer[0].kind) }; + assert_eq!(children.len(), 3, "the clip and both rectangles"); +} + +#[test] +fn a_record_whose_size_is_not_a_multiple_of_4_ends_the_file() { + let records = vec![(43, le(&[100, 100, 200, 200])), (43, le(&[300, 300, 400, 400])), (43, le(&[500, 500, 600, 600]))]; + let mut bytes = hand_emf(5000, 3000, &records); + // The second rectangle's size, after the header and the first rectangle. + let header = u32::from_le_bytes(bytes[4..8].try_into().unwrap()) as usize; + let first = u32::from_le_bytes(bytes[header + 4..header + 8].try_into().unwrap()) as usize; + let at = header + first + 4; + let size = u32::from_le_bytes(bytes[at..at + 4].try_into().unwrap()); + bytes[at..at + 4].copy_from_slice(&(size + 2).to_le_bytes()); + let back = import(&bytes).unwrap(); + assert_eq!(paths(&back.document).len(), 1); + assert_eq!(back.warnings, vec!["the file ends early: what it held was imported".to_string()]); +} + +#[test] +fn wmf_with_an_inverted_placeable_box_is_read_at_its_units_an_inch() { + // The box runs from right to left, so it gives no size: the window (1440 units square, one inch + // at the header's 1440 units an inch) does. The rectangle is its top-left quarter. + let records = vec![(0x020B, le16(&[0, 0])), (0x020C, le16(&[1440, 1440])), (0x041B, le16(&[720, 720, 0, 0]))]; + let mut bytes = hand_wmf(1440, 1440, &records); + bytes[6..8].copy_from_slice(&1440i16.to_le_bytes()); + bytes[10..12].copy_from_slice(&0i16.to_le_bytes()); + let back = import(&bytes).unwrap(); + assert!(near(back.document.artboards[0].rect, Rect::new(0.0, 0.0, 72.0, 72.0), 1e-6), "{:?}", back.document.artboards[0].rect); + let p = paths(&back.document); + assert_eq!(p.len(), 1); + assert!(near(p[0].geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 36.0, 36.0), 1e-6), "{:?}", p[0].geometric_bounds()); +} + +#[test] +fn emf_without_a_frame_is_read_at_its_device_resolution() { + // An empty frame, and bounds of 5000 × 3000 device pixels at 100 pixels a millimetre. + let mut bytes = hand_emf(0, 0, &[(43, le(&[1000, 1000, 2000, 1500]))]); + for (i, v) in [0i32, 0, 5000, 3000].iter().enumerate() { + bytes[8 + i * 4..12 + i * 4].copy_from_slice(&v.to_le_bytes()); + } + let back = import(&bytes).unwrap(); + let mm = 72.0 / 25.4; + assert!(near(back.document.artboards[0].rect, Rect::new(0.0, 0.0, 50.0 * mm, 30.0 * mm), 0.01), "{:?}", back.document.artboards[0].rect); + let p = paths(&back.document); + assert_eq!(p.len(), 1); + assert!(near(p[0].geometric_bounds().unwrap(), Rect::new(10.0 * mm, 10.0 * mm, 20.0 * mm, 15.0 * mm), 0.01), "{:?}", p[0].geometric_bounds()); + // A device 50 mm high: 200 pixels a millimetre down, so everything is half as tall. + bytes[84..88].copy_from_slice(&50i32.to_le_bytes()); + let back = import(&bytes).unwrap(); + assert!(near(back.document.artboards[0].rect, Rect::new(0.0, 0.0, 50.0 * mm, 15.0 * mm), 0.01), "{:?}", back.document.artboards[0].rect); + let p = paths(&back.document); + assert!(near(p[0].geometric_bounds().unwrap(), Rect::new(10.0 * mm, 5.0 * mm, 20.0 * mm, 7.5 * mm), 0.01), "{:?}", p[0].geometric_bounds()); } diff --git a/crates/pdf/src/export/entry.rs b/crates/pdf/src/export/entry.rs index eabba52d9e..00ac16a3fe 100644 --- a/crates/pdf/src/export/entry.rs +++ b/crates/pdf/src/export/entry.rs @@ -45,14 +45,23 @@ fn export_with_report_inner(doc: &Document, opts: &PdfOptions, left_out: &mut Ha let set = &opts.settings; set.check()?; vectorcraft_doc::cancel::check().map_err(|_| PdfError::Cancelled)?; - // Live geometry effects export as their result; raster effects are reported below. - let baked = vectorcraft_effects::bake_document(doc); - // Baking stops early when cancelled, leaving a half-baked copy that must not be written. - vectorcraft_doc::cancel::check().map_err(|_| PdfError::Cancelled)?; - let doc = baked.as_ref().unwrap_or(doc); + // The pages come from the artboards, which baking leaves as they are. The version a long page + // raises the file to decides whether the layers are written, so it is settled before baking. let pages = pages(doc, opts)?; let raised = for_long_pages(set, &pages)?; let set = raised.as_ref().unwrap_or(set); + // Live geometry effects export as their result, in symbols' art too; raster effects are + // reported below. + // Only the layers this export writes place their instances' art (see `ex.non_printing` and + // `ex.layers` below). + let layers = vectorcraft_effects::WrittenLayers { + hidden: set.writes_layers() && !doc.page_knockout, + non_printing: set.include_non_printing || set.create_layers, + }; + let baked = vectorcraft_effects::bake_document_placing_symbols(doc, true, layers); + // Baking stops early when cancelled, leaving a half-baked copy that must not be written. + vectorcraft_doc::cancel::check().map_err(|_| PdfError::Cancelled)?; + let doc = baked.as_ref().unwrap_or(doc); // The file's Title is File Info's; the page information names the document, as its tab does. let title = crate::pdfx::title(set.standard, opts.title.clone().unwrap_or_else(|| doc.info_title().to_owned())); diff --git a/crates/pdf/src/export/images.rs b/crates/pdf/src/export/images.rs index d0158d8cd2..af686e1857 100644 --- a/crates/pdf/src/export/images.rs +++ b/crates/pdf/src/export/images.rs @@ -138,20 +138,22 @@ impl Exporter<'_> { } let doc = self.doc; let out = self.out.clone(); + let profiles = !out.standard.cmyk_only(); let img = doc.image_blob(im).filter(|_| !self.left_out.contains(key)).and_then(|blob| { let cmyk_image = blob.is_cmyk(); if !cmyk_image && self.convert && doc.color_mode == vectorcraft_doc::ColorMode::Cmyk { self.rgb_in_cmyk.images.insert(key.to_string()); } let r = if cmyk_image { - crate::images::recode_cmyk(blob, size, c, interpolate, out.cmyk_pixels(), None) + let icc = out.cmyk_image_icc(blob); + crate::images::recode_cmyk(blob, size, c, interpolate, out.cmyk_pixels(), None, icc.as_deref()) } else { - crate::images::recode(&blob.bytes, size, c, interpolate, out.pixels()) + crate::images::recode(&blob.bytes, size, c, interpolate, out.pixels(), profiles) }; if let Some(w) = r.warning { self.warn(w); } - r.image.or_else(|| embed(blob, interpolate, self.sixteen_bit)) + r.image.or_else(|| embed(blob, interpolate, self.sixteen_bit, profiles)) }); if img.is_none() { self.warn(UNDECODED); @@ -191,7 +193,8 @@ impl Exporter<'_> { let doc = self.doc; let img = doc.image_blob(im).filter(|b| b.is_cmyk()).and_then(|blob| { let alpha = crate::images::mask_alpha(doc.image_blob(mi)?, im.width, im.height, m.clip)?; - let r = crate::images::recode_cmyk(blob, size, self.compression, interpolate, self.out.cmyk_pixels(), Some(alpha)); + let icc = self.out.cmyk_image_icc(blob); + let r = crate::images::recode_cmyk(blob, size, self.compression, interpolate, self.out.cmyk_pixels(), Some(alpha), icc.as_deref()); if let (Some(w), Some(_)) = (r.warning, &r.image) { self.warn(w); } @@ -313,22 +316,32 @@ pub(super) fn png_8_bit(bytes: &[u8]) -> Option> { Some(png) } -/// Most pixels an image may have to be embedded: twice what the app reads (64 million), so every image -/// it holds is still written. -const MAX_EMBED_PIXELS: u64 = 1 << 27; - /// Image `blob` as it is: PNG, JPEG, GIF and WebP through the PDF writer (JPEG data unchanged), -/// other formats decoded. Without `sixteen_bit` (a file before PDF 1.5), a PNG of 16 bits a -/// sample is written at 8 bits ([`png_8_bit`]). -pub(super) fn embed(blob: &vectorcraft_doc::ImageBlob, interpolate: bool, sixteen_bit: bool) -> Option { +/// other formats (a TIFF) decoded with their 16-bit samples and, when `profiles` allows it (not in +/// PDF/X-1a), the ICC profile they carry ([`crate::images::decoded_image`]). Without `profiles`, an +/// image that carries a gray or RGB profile is written without it, and so is one whose gray or RGB +/// profile is malformed ([`crate::images::valid_icc`]): a JPEG with its data unchanged, an image of +/// another format decoded. Without `sixteen_bit` (a file before PDF 1.5), a PNG or another image of +/// 16 bits a sample is written at 8 bits ([`png_8_bit`]). +pub(super) fn embed(blob: &vectorcraft_doc::ImageBlob, interpolate: bool, sixteen_bit: bool, profiles: bool) -> Option { // The header's size first: the writer's decoders allocate what it declares, and the encoded // bytes of an image that is far larger than any the app reads may be a few kilobytes. let size = image::ImageReader::new(std::io::Cursor::new(blob.bytes.as_slice())).with_guessed_format().ok()?.into_dimensions(); - if size.is_ok_and(|(w, h)| u64::from(w) * u64::from(h) > MAX_EMBED_PIXELS) { + if size.is_ok_and(|(w, h)| u64::from(w) * u64::from(h) > crate::images::MAX_EMBED_PIXELS) { return None; } let bytes = blob.bytes.as_ref().clone(); + // The PDF writer keeps a gray or RGB image's ICC profile: without `profiles`, or when the + // profile is malformed, such a JPEG is written without its profile, and an image of another + // format is decoded and written without it. The color space is read from the header's bytes + // 16..20 even in a profile cut short, as the PDF writer reads it. + let strip = crate::images::source_icc(&bytes).is_some_and(|icc| match icc.get(16..20) { + Some(space @ (b"GRAY" | b"RGB ")) => !profiles || <[u8; 4]>::try_from(space).is_ok_and(|s| !crate::images::valid_icc(&icc, s)), + _ => false, + }); let direct = match blob.mime.as_str() { + "image/jpeg" | "image/jpg" if strip => Image::from_jpeg_with_icc(bytes.clone().into(), None, interpolate).ok(), + _ if strip => None, "image/png" if !sixteen_bit && png_16_bit(&bytes) => png_8_bit(&bytes).and_then(|png| Image::from_png(png.into(), interpolate).ok()), "image/png" => Image::from_png(bytes.clone().into(), interpolate).ok(), "image/jpeg" | "image/jpg" => Image::from_jpeg(bytes.clone().into(), interpolate).ok(), @@ -336,11 +349,7 @@ pub(super) fn embed(blob: &vectorcraft_doc::ImageBlob, interpolate: bool, sixtee "image/webp" => Image::from_webp(bytes.clone().into(), interpolate).ok(), _ => None, }; - direct.or_else(|| { - let rgba = image::load_from_memory(&bytes).ok()?.to_rgba8(); - let (w, h) = rgba.dimensions(); - Some(Image::from_rgba8(rgba.into_raw(), w, h)) - }) + direct.or_else(|| crate::images::decoded_image(&bytes, interpolate, sixteen_bit, profiles)) } #[cfg(test)] @@ -359,7 +368,7 @@ mod tests { let crc = !png[12..29].iter().fold(!0u32, |c, b| (0..8).fold(c ^ u32::from(*b), |c, _| if c & 1 == 1 { 0xEDB8_8320 ^ (c >> 1) } else { c >> 1 })); png[29..33].copy_from_slice(&crc.to_be_bytes()); - assert!(super::embed(&ImageBlob::png(png), false, true).is_none()); + assert!(super::embed(&ImageBlob::png(png), false, true, true).is_none()); } #[test] diff --git a/crates/pdf/src/export/nodes.rs b/crates/pdf/src/export/nodes.rs index 78930c7500..403cbc5431 100644 --- a/crates/pdf/src/export/nodes.rs +++ b/crates/pdf/src/export/nodes.rs @@ -14,6 +14,11 @@ struct Measured { members: Vec, } +/// Box `b` grown by `reach`, the room brush art can paint past it; `b` itself when `reach` is 0. +fn brushed(b: Option, reach: f64) -> Option { + if reach > 0.0 { b.map(|b| b.inflate(reach, reach)) } else { b } +} + #[cfg(test)] std::thread_local! { /// The objects this thread has measured for the walk and for the links (tests). @@ -312,15 +317,17 @@ impl Exporter<'_> { krilla::mask::Mask::new(sb.finish(), krilla::mask::MaskType::Luminosity) } - /// The box of `n`, and of the members of a plain group or layer. + /// The box of `n`, and of the members of a plain group or layer. A box grows by the room brush + /// art can paint past the brushed strokes of `n` and of the objects in it + /// ([`vectorcraft_brush::reach_within`]), as the renderer culls it. fn measure(&self, n: &Node) -> Measured { if !matches!(n.kind, NodeKind::Layer { clip: false, .. } | NodeKind::Group { clip: false, .. }) { #[cfg(test)] MEASURES.with(|m| m.set(m.get() + 1)); - return Measured { bounds: n.visual_bounds_with(&self.symbols), members: vec![] }; + return Measured { bounds: brushed(n.visual_bounds_with(&self.symbols), vectorcraft_brush::reach_within(n)), members: vec![] }; } let members: Vec<_> = n.editing_children().iter().map(|c| self.measure(c)).collect(); - Measured { bounds: n.visual_of_members(members.iter().map(|m| m.bounds)), members } + Measured { bounds: brushed(n.visual_of_members(members.iter().map(|m| m.bounds)), vectorcraft_brush::reach(n)), members } } pub(super) fn node(&mut self, s: &mut Surface, n: &Node, page: Rect, force: bool) { diff --git a/crates/pdf/src/export/text.rs b/crates/pdf/src/export/text.rs index 4b0b3a047a..c9ef8203c7 100644 --- a/crates/pdf/src/export/text.rs +++ b/crates/pdf/src/export/text.rs @@ -325,7 +325,7 @@ impl Exporter<'_> { let img = match self.images.get(&cache) { Some(img) => img.clone(), None => { - let img = embed(&image.blob, self.interpolate, self.sixteen_bit); + let img = embed(&image.blob, self.interpolate, self.sixteen_bit, !self.out.standard.cmyk_only()); self.images.insert(cache, img.clone()); img } diff --git a/crates/pdf/src/export/writer.rs b/crates/pdf/src/export/writer.rs index 9f6d9d6906..ca70ef2695 100644 --- a/crates/pdf/src/export/writer.rs +++ b/crates/pdf/src/export/writer.rs @@ -271,7 +271,8 @@ impl Writer { PdfError::from(e) })?; if self.cmyk { - cmyk_blending(&mut bytes, self.out.tagged); + let profile = self.out.tagged.then(|| vectorcraft_color::cms::icc_bytes(self.out.cmyk_profile()).ok()).flatten(); + cmyk_blending(&mut bytes, self.out.tagged, profile.as_deref(), self.out.standard != Standard::PdfA2b); } let lab = !self.lab_spots.is_empty() && !self.out.standard.cmyk_only(); let bytes = if lab { crate::lab_spot::lab_alternates(bytes, &self.lab_spots) } else { bytes }; @@ -285,12 +286,21 @@ impl Writer { /// its blending space (DeviceRGB, or sRGB when colours are `tagged`), so the group dictionaries /// are rewritten in place to DeviceCMYK (or the CMYK profile's space), keeping their length so the /// cross-reference offsets stay valid. Luminosity masks' groups keep RGB: mask luminance is that -/// of screen colours, as on screen. -fn cmyk_blending(pdf: &mut [u8], tagged: bool) { +/// of screen colours, as on screen. Tagged groups blend in the space of CMYK profile `profile` +/// (the one that tags CMYK colours) when the file has one. When its only CMYK spaces are of other +/// profiles (images' own), they blend in DeviceCMYK where `device` allows it, else they keep RGB; +/// without `profile`, they blend in the first CMYK space. +fn cmyk_blending(pdf: &mut [u8], tagged: bool, profile: Option<&[u8]>, device: bool) { let masks = luminosity_mask_groups(pdf); let mut spaces = vec![("/CS/DeviceRGB".to_string(), "/CS/DeviceCMYK".to_string())]; if tagged { - spaces.extend(icc_spaces(pdf)); + let own = profile.and_then(|icc| crate::output::tagging_stream(pdf, &crate::patch::Xref::read(pdf)?, icc)); + let without = match (profile, device) { + (None, _) => Without::FirstCmyk, + (Some(_), true) => Without::DeviceCmyk, + (Some(_), false) => Without::Rgb, + }; + spaces.extend(icc_spaces(pdf, own, without)); } let mut from = 0; while let Some(at) = find(pdf, b"/Group<<", from).map(|i| i + b"/Group".len()) { @@ -303,11 +313,22 @@ fn cmyk_blending(pdf: &mut [u8], tagged: bool) { } } +/// What tagged groups blend in when the file holds no space of the document's CMYK profile. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Without { + /// The first ICC-based CMYK space of the file. + FirstCmyk, + DeviceCmyk, + /// The RGB space they have. + Rgb, +} + /// The ICC-based RGB colour spaces of `pdf`, each with the ICC-based CMYK one to blend in instead, -/// as group `/CS` entries (`/CS 3 0 R`); none without a CMYK one. -fn icc_spaces(pdf: &[u8]) -> Vec<(String, String)> { +/// as group `/CS` entries (`/CS 3 0 R`): the one whose profile is stream `own`, else as `without` +/// says; none without a CMYK one. +fn icc_spaces(pdf: &[u8], own: Option, without: Without) -> Vec<(String, String)> { const ICC: &[u8] = b"[/ICCBased "; - let (mut rgb, mut cmyk) = (vec![], None); + let (mut rgb, mut cmyk, mut own_cmyk) = (vec![], None, None); let mut from = 0; while let Some(at) = find(pdf, ICC, from) { from = at + ICC.len(); @@ -319,11 +340,19 @@ fn icc_spaces(pdf: &[u8]) -> Vec<(String, String)> { let Some(head) = find(pdf, format!("\n{stream} 0 obj").as_bytes(), 0) else { continue }; let dict = pdf.get(head..find(pdf, b"stream", head).unwrap_or(pdf.len())).unwrap_or_default(); if find(dict, b"/N 4", 0).is_some() { + if own == Some(stream) { + own_cmyk.get_or_insert(format!("/CS {array} 0 R")); + } cmyk.get_or_insert(format!("/CS {array} 0 R")); } else if find(dict, b"/N 3", 0).is_some() { rgb.push(format!("/CS {array} 0 R")); } } + let cmyk = own_cmyk.or_else(|| match without { + Without::FirstCmyk => cmyk, + Without::DeviceCmyk => cmyk.map(|_| "/CS/DeviceCMYK".to_string()), + Without::Rgb => None, + }); let Some(cmyk) = cmyk else { return vec![] }; rgb.into_iter().map(|r| (r, cmyk.clone())).collect() } @@ -385,3 +414,27 @@ pub(super) fn date_time(t: i64) -> krilla::metadata::DateTime { .utc_offset_hour(0) .utc_offset_minute(0) } + +#[cfg(test)] +mod tests { + use super::{Without, icc_spaces}; + + /// Objects 1 to 3: an RGB ICC-based space (profile 4), then two CMYK ones (profiles 5, 6). + const SPACES: &[u8] = b"%PDF-1.7\n1 0 obj\n[/ICCBased 4 0 R]\nendobj\n2 0 obj\n[/ICCBased 5 0 R]\nendobj\n3 0 obj\n[/ICCBased 6 0 R]\nendobj\n\ + 4 0 obj\n<>stream\n\nendstream\nendobj\n5 0 obj\n<>stream\n\nendstream\nendobj\n\ + 6 0 obj\n<>stream\n\nendstream\nendobj\n"; + + #[test] + fn groups_blend_in_the_documents_cmyk_space_else_device_cmyk() { + let rgb = "/CS 1 0 R".to_string(); + // The space of the document's profile, wherever it is. + for without in [Without::FirstCmyk, Without::DeviceCmyk, Without::Rgb] { + assert_eq!(icc_spaces(SPACES, Some(6), without), [(rgb.clone(), "/CS 3 0 R".to_string())], "{without:?}"); + } + // Without it, DeviceCMYK, or RGB where DeviceCMYK isn't allowed, rather than another + // profile's space; the first CMYK space when the document's profile isn't known. + assert_eq!(icc_spaces(SPACES, None, Without::DeviceCmyk), [(rgb.clone(), "/CS/DeviceCMYK".to_string())]); + assert_eq!(icc_spaces(SPACES, None, Without::Rgb), []); + assert_eq!(icc_spaces(SPACES, None, Without::FirstCmyk), [(rgb, "/CS 2 0 R".to_string())]); + } +} diff --git a/crates/pdf/src/images.rs b/crates/pdf/src/images.rs index 4139259583..5204e4f396 100644 --- a/crates/pdf/src/images.rs +++ b/crates/pdf/src/images.rs @@ -10,7 +10,9 @@ //! CMYK images ([`ImageBlob::cmyk`]) stay CMYK: a CMYK JPEG already as asked is embedded as it is //! when its numbers are kept; the others' ink amounts are resampled, converted when the Output //! settings convert CMYK colours ([`CmykPixels`]) and compressed again. CMYK JPEGs hold Adobe's -//! inverted samples, which the PDF writer's Decode array undoes. +//! inverted samples, which the PDF writer's Decode array undoes. A CMYK image whose numbers are +//! kept carries the CMYK profile it is given ([`cmyk_icc`]), whether it is embedded as it is or +//! written again; without one it is untagged, a JPEG's own `ICC_PROFILE` segments included. use std::io::Cursor; use std::sync::Arc; @@ -21,12 +23,14 @@ use image::{DynamicImage, ExtendedColorType, ImageDecoder, ImageFormat, ImageRea use krilla::image::{BitsPerComponent, CustomImage, Image, ImageColorspace}; use vectorcraft_doc::ImageBlob; -use vectorcraft_doc::cmyk::jpeg_components; +use vectorcraft_doc::cmyk::{Inks, jpeg_components}; +use vectorcraft_doc::resample::{Resample, premultiply, resized, unpremultiply}; use crate::output::{CmykPixels, Pixels}; use crate::{CompressionSettings, Downsample, ImageCodec, JpegQuality, MonoCodec}; -/// Raw 8-bit pixels: colour samples (RGB, grey or CMYK) and an optional alpha channel. +/// Raw pixels: colour samples (RGB, grey or CMYK) and an optional alpha channel, of 8 bits a +/// sample or of 16 (big-endian), with the ICC profile the colour samples are in, if any. #[derive(Clone, Hash)] struct Raw { color: Arc>, @@ -34,6 +38,8 @@ struct Raw { width: u32, height: u32, space: ImageColorspace, + bits: BitsPerComponent, + icc: Option>>, } impl CustomImage for Raw { @@ -46,7 +52,7 @@ impl CustomImage for Raw { } fn bits_per_component(&self) -> BitsPerComponent { - BitsPerComponent::Eight + self.bits } fn size(&self) -> (u32, u32) { @@ -54,7 +60,7 @@ impl CustomImage for Raw { } fn icc_profile(&self) -> Option<&[u8]> { - None + self.icc.as_deref().map(Vec::as_slice) } fn color_space(&self) -> ImageColorspace { @@ -62,24 +68,86 @@ impl CustomImage for Raw { } } +/// `icc` when it is a well-formed profile ([`valid_icc`]) of the colour space `space` names: `GRAY` +/// for grey samples, `RGB ` for RGB ones. `None` for other profiles and spaces. +fn icc_for(icc: Option>, space: ImageColorspace) -> Option>> { + let want = match space { + ImageColorspace::Luma => *b"GRAY", + ImageColorspace::Rgb => *b"RGB ", + ImageColorspace::Cmyk | ImageColorspace::DeviceN => return None, + }; + icc.filter(|icc| valid_icc(icc, want)).map(Arc::new) +} + +/// The ICC profile image `bytes` carries: a TIFF's tag 34675 (read by the TIFF decoder itself, +/// which reads tags of any size), another format's as its decoder reads it. `None` without one. +pub(crate) fn source_icc(bytes: &[u8]) -> Option> { + let reader = ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?; + if reader.format() == Some(ImageFormat::Tiff) { + return vectorcraft_doc::cmyk::tiff_icc_profile(bytes); + } + let mut decoder = reader.into_decoder().ok()?; + decoder.icc_profile().ok().flatten().filter(|icc| !icc.is_empty()) +} + /// A `width` × `height` image of straight (not premultiplied) RGBA pixels, written as RGB (as /// CMYK when `pixels` converts to CMYK), or as grey when every pixel is grey, with an alpha -/// channel only when some pixel isn't opaque. `interpolate` asks viewers to smooth it when -/// enlarged (PDF/A forbids it). `None` when `rgba` doesn't hold that many pixels. -fn from_rgba(rgba: &[u8], width: u32, height: u32, interpolate: bool, pixels: Option<&Pixels>) -> Option { +/// channel only when some pixel isn't opaque. With an RGB `icc` profile, pixels that `pixels` +/// doesn't convert stay RGB and carry it; a grey one tags grey pixels. `interpolate` asks viewers +/// to smooth it when enlarged (PDF/A forbids it). `None` when `rgba` doesn't hold that many pixels. +fn from_rgba(rgba: &[u8], width: u32, height: u32, interpolate: bool, pixels: Option<&Pixels>, icc: Option>) -> Option { let px = rgba.as_chunks::<4>().0; if px.len() as u64 != width as u64 * height as u64 || px.is_empty() { return None; } - let (color, space) = if neutral(rgba) { + let rgb_icc = pixels.is_none() && icc.as_deref().is_some_and(|icc| valid_icc(icc, *b"RGB ")); + let (color, space) = if neutral(rgba) && !rgb_icc { (px.iter().map(|p| p[0]).collect(), ImageColorspace::Luma) } else if let Some(cmyk) = pixels.and_then(|p| p.cmyk(rgba)) { (cmyk, ImageColorspace::Cmyk) } else { (px.iter().flat_map(|p| [p[0], p[1], p[2]]).collect(), ImageColorspace::Rgb) }; + let icc = icc_for(icc.filter(|_| pixels.is_none()), space); let alpha = px.iter().any(|p| p[3] < 255).then(|| Arc::new(px.iter().map(|p| p[3]).collect())); - Image::from_custom(Raw { color: Arc::new(color), alpha, width, height, space }, interpolate).ok() + Image::from_custom(Raw { color: Arc::new(color), alpha, width, height, space, bits: BitsPerComponent::Eight, icc }, interpolate).ok() +} + +/// Decoded image `img` written losslessly as it is: grey or RGB samples (other kinds as RGB), with +/// an alpha channel only when some pixel isn't opaque, at 16 bits a sample when it has more than 8 +/// and `sixteen_bit` allows it (PDF 1.5 and later), else at 8; tagged with ICC profile `icc` when +/// that is a profile of the samples' colour space (`GRAY` or `RGB `). `None` when it has no pixels. +pub(crate) fn from_decoded(img: DynamicImage, icc: Option>, interpolate: bool, sixteen_bit: bool) -> Option { + let (width, height) = (img.width(), img.height()); + if width == 0 || height == 0 { + return None; + } + let kind = img.color(); + let space = if kind.has_color() { ImageColorspace::Rgb } else { ImageColorspace::Luma }; + let n = if kind.has_color() { 3 } else { 1 }; + let deep = sixteen_bit && kind.bits_per_pixel() > 8 * u16::from(kind.channel_count()); + let (color, alpha, bits) = if deep { + let s = if kind.has_color() { img.into_rgba16().into_raw() } else { img.into_luma_alpha16().into_raw() }; + let px = s.chunks_exact(n + 1); + let color = px.clone().flat_map(|p| p[..n].iter().flat_map(|v| v.to_be_bytes())).collect(); + let alpha = (kind.has_alpha() && px.clone().any(|p| p[n] < u16::MAX)).then(|| px.flat_map(|p| p[n].to_be_bytes()).collect()); + (color, alpha, BitsPerComponent::Sixteen) + } else { + let s = if kind.has_color() { img.into_rgba8().into_raw() } else { img.into_luma_alpha8().into_raw() }; + let px = s.chunks_exact(n + 1); + let color = px.clone().flat_map(|p| p[..n].iter().copied()).collect(); + let alpha = (kind.has_alpha() && px.clone().any(|p| p[n] < u8::MAX)).then(|| px.map(|p| p[n]).collect()); + (color, alpha, BitsPerComponent::Eight) + }; + let raw = Raw { color: Arc::new(color), alpha: alpha.map(Arc::new), width, height, space, bits, icc: icc_for(icc, space) }; + Image::from_custom(raw, interpolate).ok() +} + +/// Image `bytes` decoded within [`limits`], with the ICC profile it carries ([`source_icc`]) when +/// `profiles` allows it (not in PDF/X-1a, which allows no ICC-based color spaces), as +/// [`from_decoded`] writes it. `None` when it can't be decoded. +pub(crate) fn decoded_image(bytes: &[u8], interpolate: bool, sixteen_bit: bool, profiles: bool) -> Option { + from_decoded(decoded(bytes)?, profiles.then(|| source_icc(bytes)).flatten(), interpolate, sixteen_bit) } /// Are all of the RGBA pixels `rgba` grey? @@ -88,9 +156,59 @@ fn neutral(rgba: &[u8]) -> bool { } /// Colour `samples` (grey, RGB, or CMYK ink amounts, as `space` says) with an optional `alpha` -/// channel, written losslessly. -fn lossless(samples: Vec, alpha: Option>, space: ImageColorspace, width: u32, height: u32, interpolate: bool) -> Option { - Image::from_custom(Raw { color: Arc::new(samples), alpha: alpha.map(Arc::new), width, height, space }, interpolate).ok() +/// channel, written losslessly, tagged with ICC profile `icc` when given. +fn lossless( + samples: Vec, + alpha: Option>, + space: ImageColorspace, + width: u32, + height: u32, + interpolate: bool, + icc: Option<&[u8]>, +) -> Option { + let icc = icc.map(|icc| Arc::new(icc.to_vec())); + let raw = Raw { color: Arc::new(samples), alpha: alpha.map(Arc::new), width, height, space, bits: BitsPerComponent::Eight, icc }; + Image::from_custom(raw, interpolate).ok() +} + +/// Most pixels an image may have to be embedded: twice what the app reads (64 million), so every image +/// it holds is still written. +pub(crate) const MAX_EMBED_PIXELS: u64 = 1 << 27; + +/// The most bytes an ICC profile carried by an image is written with (16 MiB). +const MAX_ICC: usize = 16 << 20; + +/// The CMYK ICC profile image `blob` carries ([`ImageBlob::cmyk_icc_profile`]), when it is one a +/// CMYK image can be tagged with ([`valid_icc`]). `None` for other images and other profiles. +pub(crate) fn cmyk_icc(blob: &ImageBlob) -> Option> { + blob.cmyk_icc_profile().filter(|icc| valid_icc(icc, *b"CMYK")) +} + +/// Is `icc` a profile an image of colour space `space` (`GRAY`, `RGB ` or `CMYK`) can be tagged +/// with: at most [`MAX_ICC`] bytes, the size its header declares, the `acsp` signature, an input, +/// display, output or colour space profile of `space` colours, and a tag table whose tags lie +/// within it? +pub(crate) fn valid_icc(icc: &[u8], space: [u8; 4]) -> bool { + let be = |at: usize| icc.get(at..at + 4).and_then(|b| b.try_into().ok()).map(u32::from_be_bytes); + let fits = |at: u32, len: u32| u64::from(at) + u64::from(len) <= icc.len() as u64; + if icc.len() > MAX_ICC || be(0).and_then(|n| usize::try_from(n).ok()) != Some(icc.len()) { + return false; + } + let class = icc.get(12..16); + if icc.get(36..40) != Some(b"acsp".as_slice()) + || icc.get(16..20) != Some(space.as_slice()) + || ![b"scnr", b"mntr", b"prtr", b"spac"].iter().any(|c| class == Some(c.as_slice())) + { + return false; + } + let Some(count) = be(128) else { return false }; + if !fits(132, count.saturating_mul(12)) { + return false; + } + (0..count as usize).all(|i| { + let at = 132 + i * 12; + matches!((be(at + 4), be(at + 8)), (Some(offset), Some(len)) if fits(offset, len)) + }) } /// [`from_rgba`] of pixels converted by `pixels` (when given). @@ -98,7 +216,7 @@ pub(crate) fn from_rgba_in(mut rgba: Vec, width: u32, height: u32, interpola if let Some(p) = pixels { p.rgb_in_place(&mut rgba); } - from_rgba(&rgba, width, height, interpolate, pixels) + from_rgba(&rgba, width, height, interpolate, pixels, None) } /// A `width` × `height` image of CMYK ink amounts `inks` (four bytes a pixel), converted by @@ -114,7 +232,7 @@ pub(crate) fn from_inks(inks: Vec, alpha: Vec, width: u32, height: u32, Some(p) => p.convert(&inks), None => (inks, ImageColorspace::Cmyk), }; - lossless(samples, alpha, space, width, height, interpolate) + lossless(samples, alpha, space, width, height, interpolate, None) } /// The kinds of images the Compression section has settings for. @@ -225,23 +343,45 @@ fn jpeg_quality(r: &Rule, jpeg: bool) -> Option { } } -/// `img` resampled to `w` × `h` pixels as `r` says. +/// How `r` resamples an image. +fn resampling(r: &Rule) -> Resample { + match r.downsample { + Downsample::Average => Resample::Average, + Downsample::Subsample => Resample::Filter(FilterType::Nearest), + Downsample::Bicubic | Downsample::None => Resample::Filter(FilterType::CatmullRom), + } +} + +/// `img` resampled to `w` × `h` pixels as `r` says, the colors of an image with alpha weighted by +/// it ([`resized`]). fn resample(img: DynamicImage, r: &Rule, (w, h): (u32, u32)) -> DynamicImage { + resized(img, w, h, resampling(r)) +} + +/// The four channels of `img` resampled to `w` × `h` pixels as `r` says, each on its own. +fn resample_channels(img: DynamicImage, r: &Rule, (w, h): (u32, u32)) -> DynamicImage { if (w, h) == (img.width(), img.height()) { return img; } - match r.downsample { - Downsample::Average => img.thumbnail_exact(w, h), - Downsample::Subsample => img.resize_exact(w, h, FilterType::Nearest), - Downsample::Bicubic | Downsample::None => img.resize_exact(w, h, FilterType::CatmullRom), + match resampling(r) { + Resample::Average => img.thumbnail_exact(w, h), + Resample::Filter(f) => img.resize_exact(w, h, f), } } /// Encoded image `bytes` placed `size` points wide and high, as the Compression settings `c` ask: /// resampled when its resolution is above the threshold, compressed with ZIP or JPEG, its colours -/// converted by `convert` (colour images). `interpolate` lets viewers smooth it. An image that -/// can't be decoded is kept as it is. -pub(crate) fn recode(bytes: &[u8], size: (f64, f64), c: &CompressionSettings, interpolate: bool, convert: Option<&Pixels>) -> Recoded { +/// converted by `convert` (colour images). Pixels that keep their colours keep the ICC profile +/// they carry when `profiles` allows it (not in PDF/X-1a, which allows no ICC-based color spaces). +/// `interpolate` lets viewers smooth it. An image that can't be decoded is kept as it is. +pub(crate) fn recode( + bytes: &[u8], + size: (f64, f64), + c: &CompressionSettings, + interpolate: bool, + convert: Option<&Pixels>, + profiles: bool, +) -> Recoded { let keep = Recoded { image: None, warning: None }; let Ok(reader) = ImageReader::new(Cursor::new(bytes)).with_guessed_format() else { return keep }; let jpeg = reader.format() == Some(ImageFormat::Jpeg); @@ -270,6 +410,11 @@ pub(crate) fn recode(bytes: &[u8], size: (f64, f64), c: &CompressionSettings, in return Recoded { image: None, warning: rule.instead }; } let Some(img) = pixels.or_else(|| decoded(bytes)) else { return keep }; + // Pixels that keep their colours keep the profile they are in; converted ones are in the + // destination's. + let want = if kind == Kind::Color { *b"RGB " } else { *b"GRAY" }; + let icc = (profiles && convert.is_none()).then(|| source_icc(bytes)).flatten().filter(|icc| valid_icc(icc, want)); + let rgb_icc = icc.is_some() && kind == Kind::Color; let mut rgba = resample(img, &rule, sized(&rule, dims, size)).into_rgba8(); if kind == Kind::Mono { // Resampling greys the edges: back to black and white. @@ -284,16 +429,18 @@ pub(crate) fn recode(bytes: &[u8], size: (f64, f64), c: &CompressionSettings, in let (width, height) = rgba.dimensions(); let opaque = rgba.pixels().all(|p| p[3] == 255); let jpeg = jpeg_quality(&rule, jpeg).filter(|_| opaque).and_then(|q| { - // Grey pixels stay grey; colour ones go to CMYK when the output converts to CMYK. - let grey = kind != Kind::Color || neutral(&rgba); + // Grey pixels stay grey, unless they keep an RGB profile; colour ones go to CMYK when the + // output converts to CMYK. + let grey = kind != Kind::Color || (neutral(&rgba) && !rgb_icc); let (samples, space) = match convert.filter(|_| !grey).and_then(|p| p.cmyk(&rgba)) { Some(cmyk) => (cmyk, ImageColorspace::Cmyk), None if grey => (rgba.pixels().map(|p| p[0]).collect(), ImageColorspace::Luma), None => (rgba.pixels().flat_map(|p| [p[0], p[1], p[2]]).collect(), ImageColorspace::Rgb), }; - to_jpeg(&samples, space, width, height, q, interpolate) + let icc = icc_for(icc.clone(), space); + to_jpeg(&samples, space, width, height, q, interpolate, icc.as_deref().map(Vec::as_slice)) }); - let image = jpeg.or_else(|| from_rgba(rgba.as_raw(), width, height, interpolate, convert)); + let image = jpeg.or_else(|| from_rgba(rgba.as_raw(), width, height, interpolate, convert, icc)); Recoded { image, warning: rule.instead } } @@ -323,7 +470,8 @@ pub(crate) fn coverage_sized(w: u32, h: u32, cover: Vec, size: (f64, f64), c /// is when its numbers are (`convert` is `None`); otherwise its ink amounts are resampled, /// converted by `convert` and compressed again. With `alpha` (one sample a pixel, see /// [`mask_alpha`]) the image is lossless and carries it as its soft mask; `None` then when its -/// inks can't be read. +/// inks can't be read. When its numbers are kept, the image is tagged with CMYK profile `icc` +/// (see [`cmyk_icc`]), and is untagged without one; converted pixels are never tagged with it. pub(crate) fn recode_cmyk( blob: &ImageBlob, size: (f64, f64), @@ -331,40 +479,70 @@ pub(crate) fn recode_cmyk( interpolate: bool, convert: Option<&CmykPixels>, alpha: Option>, + icc: Option<&[u8]>, ) -> Recoded { let rule = rule(c, Kind::Color); let jpeg = jpeg_components(&blob.bytes).is_some(); + let icc = icc.filter(|_| convert.is_none()); if jpeg && convert.is_none() && alpha.is_none() { let dims = ImageReader::new(Cursor::new(blob.bytes.as_slice())).with_guessed_format().ok().and_then(|r| r.into_dimensions().ok()); - if dims.is_some_and(|d| kept(&rule, d, size, true)) { - return Recoded { image: None, warning: rule.instead }; + if let Some((w, h)) = dims.filter(|d| kept(&rule, *d, size, true)) { + // The JPEG data as it is, tagged with `icc` rather than with its own segments; one + // larger than [`MAX_EMBED_PIXELS`] is not written. + let image = (u64::from(w) * u64::from(h) <= MAX_EMBED_PIXELS) + .then(|| Image::from_jpeg_with_icc(blob.bytes.as_ref().clone().into(), icc.map(|i| i.to_vec().into()), interpolate).ok()) + .flatten(); + return Recoded { image, warning: rule.instead }; } } let Some(inks) = blob.cmyk() else { return Recoded { image: None, warning: Some(if jpeg { CMYK_KEPT } else { CMYK_RGB }) }; }; - let dims = (inks.width, inks.height); - let (width, height) = sized(&rule, dims, size); - let alpha = match alpha.map(|a| image::GrayImage::from_raw(inks.width, inks.height, a)) { - Some(Some(a)) => Some(resample(DynamicImage::ImageLuma8(a), &rule, (width, height)).into_luma8().into_raw()), - Some(None) => return Recoded { image: None, warning: None }, - None => None, - }; - // The four inks resample as the four channels of an RGBA image do. - let inks = match image::RgbaImage::from_raw(inks.width, inks.height, inks.data) { - Some(img) => resample(DynamicImage::ImageRgba8(img), &rule, (width, height)).into_rgba8().into_raw(), - None => return Recoded { image: None, warning: Some(CMYK_RGB) }, + let (width, height) = sized(&rule, (inks.width, inks.height), size); + let (inks, alpha) = match resampled_inks(inks, alpha, &rule, (width, height)) { + Ok(r) => r, + Err(warning) => return Recoded { image: None, warning }, }; let (samples, space) = match convert { Some(p) => p.convert(&inks), None => (inks, ImageColorspace::Cmyk), }; // JPEG needs opaque pixels. - let image = jpeg_quality(&rule, jpeg).filter(|_| alpha.is_none()).and_then(|q| to_jpeg(&samples, space, width, height, q, interpolate)); - let image = image.or_else(|| lossless(samples, alpha, space, width, height, interpolate)); + let image = jpeg_quality(&rule, jpeg).filter(|_| alpha.is_none()).and_then(|q| to_jpeg(&samples, space, width, height, q, interpolate, icc)); + let image = image.or_else(|| lossless(samples, alpha, space, width, height, interpolate, icc)); Recoded { image, warning: rule.instead } } +/// Ink amounts (four bytes a pixel) and their alpha (one byte a pixel), if any. +type InksAndAlpha = (Vec, Option>); + +/// Ink amounts `inks` and their `alpha` (one sample a pixel) resampled to `to` as `r` says. The +/// inks under clear pixels don't count where neighbors blend: they are multiplied by the alpha +/// before resampling and divided by the resampled alpha after. `Err` with the warning when they +/// can't be read. +fn resampled_inks(inks: Inks, alpha: Option>, r: &Rule, to: (u32, u32)) -> Result> { + let dims = (inks.width, inks.height); + let weighted = to != dims && resampling(r) != Resample::Filter(FilterType::Nearest); + let mut data = inks.data; + let alpha = match alpha.map(|a| image::GrayImage::from_raw(dims.0, dims.1, a)) { + Some(Some(a)) => { + if weighted { + premultiply(&mut data, a.as_raw()); + } + Some(resample(DynamicImage::ImageLuma8(a), r, to).into_luma8().into_raw()) + } + Some(None) => return Err(None), + None => None, + }; + // The four inks resample as the four channels of an RGBA image do, each on its own. + let img = image::RgbaImage::from_raw(dims.0, dims.1, data).ok_or(Some(CMYK_RGB))?; + let mut inks = resample_channels(DynamicImage::ImageRgba8(img), r, to).into_rgba8().into_raw(); + if let Some(a) = alpha.as_deref().filter(|_| weighted) { + unpremultiply(&mut inks, a); + } + Ok((inks, alpha)) +} + /// The most one image read here may allocate (bytes), as the image reader allows by default. const MAX_DECODE: u64 = 512 << 20; @@ -405,9 +583,9 @@ pub(crate) fn mask_alpha(blob: &ImageBlob, width: u32, height: u32, clip: bool) } /// Opaque colour `samples` (grey, RGB, or CMYK ink amounts, as `space` says) as a JPEG at -/// `quality`. CMYK JPEGs hold Adobe's inverted samples, which the PDF writer's Decode array -/// undoes. -fn to_jpeg(samples: &[u8], space: ImageColorspace, width: u32, height: u32, quality: u8, interpolate: bool) -> Option { +/// `quality`, tagged with ICC profile `icc` when given. CMYK JPEGs hold Adobe's inverted samples, +/// which the PDF writer's Decode array undoes. +fn to_jpeg(samples: &[u8], space: ImageColorspace, width: u32, height: u32, quality: u8, interpolate: bool, icc: Option<&[u8]>) -> Option { let mut out = Vec::new(); match space { ImageColorspace::Cmyk => { @@ -416,9 +594,36 @@ fn to_jpeg(samples: &[u8], space: ImageColorspace, width: u32, height: u32, qual } ImageColorspace::Rgb | ImageColorspace::Luma => { let t = if space == ImageColorspace::Rgb { ExtendedColorType::Rgb8 } else { ExtendedColorType::L8 }; - image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, quality).encode(samples, width, height, t).ok()?; + let mut encoder = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, quality); + if let Some(icc) = icc { + image::ImageEncoder::set_icc_profile(&mut encoder, icc.to_vec()).ok()?; + } + encoder.encode(samples, width, height, t).ok()?; } ImageColorspace::DeviceN => return None, } - Image::from_jpeg(out.into(), interpolate).ok() + Image::from_jpeg_with_icc(out.into(), icc.map(|i| i.to_vec().into()), interpolate).ok() +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The inks of a CMYK image with alpha, resampled, keep the amounts of the opaque pixels: the + /// inks under the clear pixels beside them don't thin them out. + #[test] + fn resampled_inks_keep_the_amounts_beside_clear_pixels() { + let data = [[40, 80, 120, 160], [0, 0, 0, 0]].repeat(8).concat(); + let alpha = [255, 0].repeat(8); + for method in ["average", "bicubic"] { + let c: CompressionSettings = serde_json::from_value(serde_json::json!({"color": {"downsample": method}})).unwrap(); + let inks = Inks::new(16, 1, data.clone()).unwrap(); + let (inks, alpha) = resampled_inks(inks, Some(alpha.clone()), &rule(&c, Kind::Color), (4, 1)).unwrap(); + let alpha = alpha.unwrap(); + let m = |c: u8, a: u8| (u16::from(c) * u16::from(a) / 255) as u8; + for (p, &a) in inks.as_chunks::<4>().0.iter().zip(&alpha) { + assert!(a > 0 && p.iter().zip([40, 80, 120, 160]).all(|(&c, want)| m(c, a).abs_diff(m(want, a)) <= 1), "{method}: {p:?} at {a}"); + } + } + } } diff --git a/crates/pdf/src/output.rs b/crates/pdf/src/output.rs index 77bc7d1d66..8114931bc4 100644 --- a/crates/pdf/src/output.rs +++ b/crates/pdf/src/output.rs @@ -18,7 +18,9 @@ //! document's), RGB with sRGB (colours of another RGB space as their sRGB equivalents) and grey //! with the sRGB tone curve. Otherwise they are device colours. PDF/A, PDF/X-3 and PDF/X-4 //! always tag them, whatever `profiles` says; PDF/X-1a never does, and always converts to a -//! CMYK destination (see [`crate::pdfx`]). +//! CMYK destination (see [`crate::pdfx`]). A CMYK image that keeps its numbers is tagged with +//! the CMYK profile it carries, if any, with `all` and `taggedSource`, and in PDF/A, PDF/X-3 +//! and PDF/X-4 unless `profiles` is `destination` ([`ColorOut::cmyk_image_icc`]). //! - Output intent: the profile `outputIntent` names, embedded as the `/GTS_PDFX` output intent //! of the catalog with the condition, identifier and registry; Trapped goes in the document //! information (`/False` when an output intent is written untrapped). PDF/A files carry their @@ -59,6 +61,9 @@ pub(crate) struct ColorOut { dest: Option, /// Colours are written in ICC-based colour spaces. pub tagged: bool, + /// CMYK images that keep their numbers are tagged with the CMYK profile they carry + /// ([`Self::cmyk_image_icc`]). + image_icc: bool, /// The CMYK profile that tags CMYK colours. cmyk_profile: String, /// Tagged RGB colours are written as their sRGB equivalents: why (a warning), when their RGB @@ -105,6 +110,7 @@ impl Default for ColorOut { profile_notes: vec![], dest: None, tagged: false, + image_icc: false, cmyk_profile, srgb_note: None, pixels: OnceLock::new(), @@ -240,6 +246,14 @@ impl ColorOut { ProfileInclusion::All | ProfileInclusion::Destination => true, ProfileInclusion::TaggedSource => !doc.color_profiles.is_empty(), }); + // Source profiles: with `all` and `taggedSource`, and in the files that tag every colour + // unless only the destination profile is asked for; never in PDF/X-1a. + out.image_icc = !set.standard.cmyk_only() + && match set.output.profiles { + ProfileInclusion::All | ProfileInclusion::TaggedSource => true, + ProfileInclusion::None => matches!(set.standard, Standard::PdfA2b | Standard::PdfX3 | Standard::PdfX4), + ProfileInclusion::Destination => false, + }; let rgb = match &out.dest { Some(d) if d.model == Model::Rgb => (d.srgb, d.cms.settings().rgb.clone()), _ => (source.rgb_is_srgb(), st.rgb.clone()), @@ -324,6 +338,16 @@ impl ColorOut { .as_ref() } + /// The CMYK profile CMYK image `blob` is tagged with ([`crate::images::cmyk_icc`]): the one it + /// carries, when its numbers are kept and the Profiles setting or the standard includes source + /// profiles. `None` otherwise, and in PDF/X-1a, whose images are untagged CMYK. + pub(crate) fn cmyk_image_icc(&self, blob: &vectorcraft_doc::ImageBlob) -> Option> { + if !self.image_icc || self.cmyk_pixels().is_some() { + return None; + } + crate::images::cmyk_icc(blob) + } + /// How CMYK images' ink amounts are converted; `None` when they keep their numbers (no /// conversion, or to a CMYK destination that keeps them). pub(crate) fn cmyk_pixels(&self) -> Option<&CmykPixels> { @@ -477,7 +501,7 @@ fn catalog(set: &PdfSettings, cmyk_profile: &str) -> Option { /// The object number of the stream of an ICC-based colour space of `pdf` that holds profile `icc` /// (its data as it is, or Flate-compressed); `None` when no colour space uses that profile. -fn tagging_stream(pdf: &[u8], xref: &Xref, icc: &[u8]) -> Option { +pub(crate) fn tagging_stream(pdf: &[u8], xref: &Xref, icc: &[u8]) -> Option { use std::io::Read; const ICC: &[u8] = b"[/ICCBased "; let mut from = 0; diff --git a/crates/pdf/src/print.rs b/crates/pdf/src/print.rs index 12c71756c8..2a3cbf98af 100644 --- a/crates/pdf/src/print.rs +++ b/crates/pdf/src/print.rs @@ -183,11 +183,14 @@ pub fn keep_layers(nodes: &mut Vec>, which: PrintLayers) { /// only the layers that print, overprints in composite output as [`PrintAdvanced::overprints`] /// says. pub fn printed_document<'a>(doc: &'a Document, set: &PrintSettings) -> Cow<'a, Document> { - let mut doc = vectorcraft_effects::bake_document(doc).map_or(Cow::Borrowed(doc), Cow::Owned); - let d = doc.to_mut(); - keep_layers(&mut d.layers, set.print_layers); - composite_overprints(d, set); - doc + // The layers that do not print are left out first, so the art placed for symbols is only + // the art that prints; the layers kept are shown. + let mut kept = doc.clone(); + keep_layers(&mut kept.layers, set.print_layers); + let layers = vectorcraft_effects::WrittenLayers { hidden: false, non_printing: true }; + let mut d = vectorcraft_effects::bake_document_placing_symbols(&kept, true, layers).unwrap_or(kept); + composite_overprints(&mut d, set); + Cow::Owned(d) } /// Overprinting fills and strokes in composite output: discarded (they knock out) or simulated diff --git a/crates/pdf/src/print/layout.rs b/crates/pdf/src/print/layout.rs index a88dd89950..5d28e9e2b1 100644 --- a/crates/pdf/src/print/layout.rs +++ b/crates/pdf/src/print/layout.rs @@ -71,7 +71,9 @@ pub struct TileGrid { /// Calls `f` with the bounds of each object of `n` that prints: visible, not on a template /// layer and not a guide (layers are already picked by the Print Layers option). Symbol -/// instances are measured by their art from `symbols`. +/// instances are measured by their art from `symbols`. A box grows by the room brush art can +/// paint past the brushed strokes of the object and of the objects in it +/// ([`vectorcraft_brush::reach_within`]). fn printed(n: &Node, symbols: &SymbolBoxes, f: &mut impl FnMut(Rect)) { if !n.visible { return; @@ -85,7 +87,8 @@ fn printed(n: &Node, symbols: &SymbolBoxes, f: &mut impl FnMut(Rect)) { } _ => { if let Some(b) = n.visual_bounds_with(symbols) { - f(b); + let reach = vectorcraft_brush::reach_within(n); + f(if reach > 0.0 { b.inflate(reach, reach) } else { b }); } } } @@ -102,9 +105,10 @@ fn has_art(doc: &Document, r: Rect) -> bool { any } -/// The bounds of all the art that prints. +/// The bounds of all the art that prints, with the brush art it paints. The box of a symbol +/// instance whose art holds brushed strokes grows as in [`has_art`]. fn art_bounds(doc: &Document) -> Option { - let symbols = doc.symbol_boxes(); + let symbols = doc.symbol_boxes().with_brush_art(); let mut all: Option = None; for l in &doc.layers { printed(l, &symbols, &mut |b| all = Some(all.map_or(b, |a| a.union(b)))); diff --git a/crates/pdf/src/print/plates.rs b/crates/pdf/src/print/plates.rs index ce6c5b336e..8b0876d9f3 100644 --- a/crates/pdf/src/print/plates.rs +++ b/crates/pdf/src/print/plates.rs @@ -8,7 +8,7 @@ use std::sync::Arc; use vectorcraft_color::Color; use vectorcraft_color::cms::{self, Cms, Model, ProfileKind}; use vectorcraft_color::swatch::REGISTRATION; -use vectorcraft_doc::inks::{Link, inks, plates, visit_node_colors}; +use vectorcraft_doc::inks::{Link, StopPlates, inks, plates, spot_color, stop_inks, visit_node_colors}; use vectorcraft_doc::overprint::darken_overprints; use vectorcraft_doc::{ColorMode, Document, ImageBlob, Node, NodeKind}; @@ -101,12 +101,33 @@ impl<'a> Separator<'a> { inks(self.doc, &self.cms, c, link, color.intent).on_plate(plate) } - /// Recolour `n`'s subtree as plate `plate`: the grey of each colour's coverage, unlinked. + /// [`Self::ink`] of a colour that prints process plates `plates` with its spot tint + /// ([`stop_inks`]): the spot plate prints the tint and the process plates print `plates`. With + /// spots as process, each process plate prints `plates` layered with the spot tint's process + /// equivalent, as a separated image's plates layer ([`vectorcraft_doc::separated::Separated::coverage_as`]). + fn stop_ink(&self, plate: &str, c: &Color, link: Link, plates: StopPlates) -> f32 { + let own = stop_inks(self.doc, &self.cms, c, link, plates, self.set.color.intent); + let (Some(_), Some((name, tint))) = (plates, own.spot.as_ref()) else { + return self.ink(plate, c, link); + }; + if !self.set.output.spots_to_process { + return own.on_plate(plate); + } + let Some(i) = cms::PROCESS_PLATES.iter().position(|p| *p == plate) else { + return 0.0; + }; + let spot = spot_color(self.doc, name).map_or(0.0, |s| self.ink(plate, &s.tinted(*tint), None)); + 1.0 - (1.0 - own.cmyk[i]) * (1.0 - spot) + } + + /// Recolour `n`'s subtree as plate `plate`: the grey of each colour's coverage, unlinked and + /// without process plates. pub fn node(&self, plate: &str, n: &mut Node) { - visit_node_colors(n, &mut |c, swatch, tint| { - *c = Color::Gray { k: self.ink(plate, c, swatch.as_deref().map(|s| (s, *tint))) }; + visit_node_colors(n, &mut |c, swatch, tint, plates| { + *c = Color::Gray { k: self.stop_ink(plate, c, swatch.as_deref().map(|s| (s, *tint)), *plates) }; *swatch = None; *tint = 1.0; + *plates = None; }); } diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index bee80238bd..b49a033a23 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -246,6 +246,97 @@ fn an_instance_whose_brush_art_reaches_the_page_is_written() { assert!(close(l[0].geometric_bounds().unwrap(), Rect::new(-15.0, 30.0, 5.0, 70.0), 0.01), "{:?}", l[0].geometric_bounds()); } +/// A 200 × 100 pt document whose 3 pt. Round brush paints a 20 pt round nib. +fn doc_with_wide_nib() -> Document { + let mut d = doc(200.0, 100.0); + let mut lib = vectorcraft_brush::library(&d); + let Some(vectorcraft_brush::BrushKind::Calligraphic(c)) = lib.iter_mut().find(|b| b.name == "3 pt. Round").map(|b| &mut b.kind) else { + panic!("the 3 pt. Round brush") + }; + c.size = 20.0; + vectorcraft_brush::store(&mut d, &lib); + d +} + +/// A line from (`x`, 40) to (`x`, 60) with a 1 pt black stroke, painted by the 3 pt. Round brush +/// when `brushed`. +fn nib_line(x: f64, brushed: bool) -> Node { + let mut stroke = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0); + if brushed { + stroke.stroke_mut().unwrap().brush = Some("3 pt. Round".into()); + } + Node::path(NodeId(0), shapes::line((x, 40.0).into(), (x, 60.0).into()), stroke) +} + +#[test] +fn a_path_whose_brush_art_reaches_the_page_is_written() { + // The line at x = -5 lies left of the page, and the 20 pt nib paints 10 pt either side of it, + // onto the page: alone, in a group, in a knockout group and as a compound path. + let compound = |n: Node| { + let mut c = Node::new(NodeId(0), NodeKind::Compound { children: vec![Arc::new(nib_line(-5.0, false))], rule: FillRule::NonZero }); + c.appearance = n.appearance; + c + }; + let knockout = |n: Node| { + let mut g = Node::group(NodeId(0), vec![Arc::new(n), Arc::new(rect_node(Rect::new(150.0, 10.0, 170.0, 30.0), Color::rgb(0.0, 0.0, 1.0)))]); + g.knockout = vectorcraft_doc::Knockout::On; + g + }; + let group = |n: Node| Node::group(NodeId(0), vec![Arc::new(n)]); + let wraps: [(&str, &dyn Fn(Node) -> Node); 4] = + [("path", &|n| n), ("group", &group), ("knockout group", &knockout), ("compound path", &compound)]; + for (what, wrap) in wraps { + let mut d = doc_with_wide_nib(); + add(&mut d, wrap(nib_line(-5.0, true))); + let out = roundtrip(&d); + let nib: Vec = leaves(&out).iter().filter_map(|n| n.geometric_bounds()).filter(|b| b.x1 < 100.0).collect(); + assert_eq!(nib.len(), 1, "{what}: the nib's art, {nib:?}"); + assert!(close(nib[0], Rect::new(-15.0, 30.0, 5.0, 70.0), 0.01), "{what}: {nib:?}"); + } + // Without its brush, or 100 pt left of the page, where the nib does not reach it, the line is + // left out. + for line in [nib_line(-5.0, false), nib_line(-100.0, true)] { + let mut d = doc_with_wide_nib(); + add(&mut d, line); + assert!(leaves(&roundtrip(&d)).is_empty()); + } + // A clipping path left of the page keeps the nib's art off it. + let mut d = doc_with_wide_nib(); + let clip = Node::new( + NodeId(0), + NodeKind::Path { + path: shapes::rectangle(Rect::new(-30.0, 0.0, -2.0, 100.0)), + rule: FillRule::NonZero, + live: None, + clipping: true, + guide: false, + }, + ); + add(&mut d, Node::new(NodeId(0), NodeKind::Group { children: vec![Arc::new(clip), Arc::new(nib_line(-5.0, true))], clip: true })); + let out = roundtrip(&d); + assert!(leaves(&out).is_empty(), "{:?}", leaves(&out)); +} + +/// The live effects in a symbol's art apply where the instance places the art, as on the canvas: +/// the symbol's square at (10, 40), which a Transform effect moves 100 pt right, is written at +/// (110, 40). +#[test] +fn symbol_art_effects_are_written_where_they_draw() { + let mut d = doc(200.0, 100.0); + let mut square = rect_node(Rect::new(10.0, 40.0, 20.0, 50.0), Color::rgb(1.0, 0.0, 0.0)); + square.appearance.effects.push(vectorcraft_doc::Effect { + id: "distort.transform".into(), + params: serde_json::json!({"moveH": 100.0}), + visible: true, + }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Moved".into(), art: Arc::new(square) }); + add(&mut d, Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: "Moved".into(), xf: Affine::IDENTITY })); + let out = roundtrip(&d); + let l = leaves(&out); + assert_eq!(l.len(), 1); + assert!(close(l[0].geometric_bounds().unwrap(), Rect::new(110.0, 40.0, 120.0, 50.0), 0.01), "{:?}", l[0].geometric_bounds()); +} + /// An instance of a symbol with 9-slice guides, scaled to 200 × 150, is written as the canvas /// draws it: its 10 × 10 corner square stays 10 × 10 and its 10 × 10 center square becomes 30 × 20. #[test] @@ -336,6 +427,31 @@ fn a_stained_instance_keeps_its_stain() { } } +/// A stained instance of a symbol whose art has a live effect is written in its stained colors, +/// where the effect draws the art. +#[test] +fn a_stained_instance_keeps_its_stain_when_its_art_has_effects() { + let blue = Color::rgb8(30, 90, 220); + let square = rect_node(Rect::new(10.0, 40.0, 20.0, 50.0), blue); + let half = stained_instance("Moved", Affine::IDENTITY, 0.5, true); + let want = vectorcraft_brush::instance_art(&square, &half).appearance.fill_paint().color().unwrap().to_hex(); + assert_ne!(want, blue.to_hex(), "the stain changes the color"); + let mut art = square; + art.appearance.effects.push(vectorcraft_doc::Effect { + id: "distort.transform".into(), + params: serde_json::json!({"moveH": 100.0}), + visible: true, + }); + let mut d = doc(200.0, 100.0); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Moved".into(), art: Arc::new(art) }); + add(&mut d, half); + let out = roundtrip(&d); + let l = leaves(&out); + assert_eq!(l.len(), 1); + assert!(close(l[0].geometric_bounds().unwrap(), Rect::new(110.0, 40.0, 120.0, 50.0), 0.01), "{:?}", l[0].geometric_bounds()); + assert_eq!(leaf_fills(&out), [want]); +} + /// The placed art of all the 9-slice instances in one export holds at most `MAX_SYMBOL_NODES` /// objects, opacity-mask art included, as on the canvas: of two instances whose art placed through /// the guides holds about 9,009,000 objects each (a gradient square in all nine cells, each copy diff --git a/crates/pdf/src/tests/cmykimages.rs b/crates/pdf/src/tests/cmykimages.rs index 45222bb04d..4719beec70 100644 --- a/crates/pdf/src/tests/cmykimages.rs +++ b/crates/pdf/src/tests/cmykimages.rs @@ -75,16 +75,18 @@ fn cmyk_dict(w: u32, h: u32, more: &str) -> String { const INVERTED: &str = "/Decode [1 0 1 0 1 0 1 0]"; -/// An image XObject of a written PDF: its colour space and the components of its ICC profile, -/// its Decode array, its filter and its stream data. +/// An image XObject of a written PDF: its colour space and the components and bytes of its ICC +/// profile, its Decode array, its filter, its stream data and whether it has a soft mask. #[derive(Debug)] struct Written { space: String, icc_n: Option, + icc: Option>, decode: Vec, filter: Option, data: Vec, width: u32, + smask: bool, } fn written(pdf: &[u8]) -> Vec { @@ -96,22 +98,26 @@ fn written(pdf: &[u8]) -> Vec { if d.get::>(b"Subtype").is_none_or(|n| n.as_ref() != b"Image") { continue; } - let (space, icc_n) = match (d.get::>(b"ColorSpace"), d.get::>(b"ColorSpace")) { - (Some(n), _) => (n.as_str().to_string(), None), + let (space, icc_n, icc) = match (d.get::>(b"ColorSpace"), d.get::>(b"ColorSpace")) { + (Some(n), _) => (n.as_str().to_string(), None, None), (_, Some(a)) => { let mut it = a.flex_iter(); let name = it.next::>().unwrap().as_str().to_string(); - (name, it.next::>().and_then(|s| s.dict().get::(b"N"))) + let profile = it.next::>(); + let n = profile.as_ref().and_then(|s| s.dict().get::(b"N")); + (name, n, profile.map(|s| s.decoded().unwrap().into_owned())) } - _ => (String::new(), None), + _ => (String::new(), None, None), }; out.push(Written { space, icc_n, + icc, decode: d.get::>(b"Decode").map(|a| a.iter::().collect()).unwrap_or_default(), filter: d.get::>(b"Filter").map(|n| n.as_str().to_string()), data: s.raw_data().to_vec(), width: d.get::(b"Width").unwrap_or(0), + smask: d.get::>(b"SMask").is_some(), }); } out @@ -447,6 +453,222 @@ fn the_output_settings_convert_cmyk_images_and_compression_recompresses_them_in_ assert_eq!(blob.cmyk().unwrap().data, flat(ink, 16)); } +/// A version 2.1 output profile of CMYK colors with a one-tag table (`cprt`), its header and table +/// consistent with its size; `edit` changes it after it is made. +fn cmyk_profile(edit: impl FnOnce(&mut Vec)) -> Vec { + let mut icc = vec![0u8; 156]; + icc[0..4].copy_from_slice(&156u32.to_be_bytes()); + icc[8..12].copy_from_slice(&[2, 0x10, 0, 0]); + icc[12..16].copy_from_slice(b"prtr"); + icc[16..20].copy_from_slice(b"CMYK"); + icc[20..24].copy_from_slice(b"Lab "); + icc[36..40].copy_from_slice(b"acsp"); + icc[128..132].copy_from_slice(&1u32.to_be_bytes()); + icc[132..136].copy_from_slice(b"cprt"); + icc[136..140].copy_from_slice(&144u32.to_be_bytes()); + icc[140..144].copy_from_slice(&12u32.to_be_bytes()); + icc[144..156].copy_from_slice(b"text\0\0\0\0VC\0\0"); + edit(&mut icc); + icc +} + +/// `inks` (four bytes a pixel) as a CMYK JPEG carrying `icc` in its `ICC_PROFILE` segments. +fn cmyk_jpeg_with(inks: &[u8], w: u16, h: u16, icc: &[u8]) -> Vec { + let mut out = Vec::new(); + let mut e = jpeg_encoder::Encoder::new(&mut out, 100); + e.add_icc_profile(icc).unwrap(); + e.encode(inks, w, h, jpeg_encoder::ColorType::Cmyk).unwrap(); + out +} + +/// A CMYK TIFF of `w` × `h` pixels of `ink` carrying `icc` as its tag 34675 (written as Open +/// stores a CMYK JPEG that carries one). +fn cmyk_tiff_with(ink: [u8; 4], w: u16, h: u16, icc: &[u8]) -> ImageBlob { + let jpg = cmyk_jpeg_with(&flat(ink, usize::from(w) * usize::from(h)), w, h, icc); + let (tiff, _) = vectorcraft_doc::cmyk::turned_cmyk(&jpg, image::metadata::Orientation::NoTransforms, None).unwrap(); + let blob = ImageBlob::new("image/tiff", tiff); + assert_eq!(blob.cmyk_icc_profile().as_deref(), Some(icc), "the TIFF carries the profile"); + blob +} + +/// A CMYK image whose numbers are kept is written in an ICC-based space of the CMYK profile it +/// carries, byte for byte, when the Profiles setting or the standard includes source profiles: +/// a TIFF written again, a JPEG kept as it is or compressed again, and an image with its mask as +/// its soft mask. Its inks are those it had. Without source profiles it is DeviceCMYK, and a +/// converted image never carries the profile its old numbers were in. +#[test] +fn a_cmyk_image_that_keeps_its_numbers_carries_its_cmyk_profile() { + let ink = [0u8, 102, 255, 0]; + let icc = cmyk_profile(|_| {}); + let tiff = cmyk_tiff_with(ink, 4, 4, &icc); + let tiff_inks = tiff.cmyk().unwrap().data; + let d = image_doc(tiff, 4, 4); + let export = |d: &Document, s: serde_json::Value| { + let out = export_with_report(d, &opts(s.clone())).unwrap_or_else(|e| panic!("{s}: {e}")); + let w: Vec = written(&out.bytes).into_iter().filter(|w| w.space != "DeviceGray").collect(); + assert_eq!(w.len(), 1, "{s}: {w:?}"); + (w.into_iter().next().unwrap(), out.bytes) + }; + let tagged = |w: &Written, s: &serde_json::Value| { + assert_eq!((w.space.as_str(), w.icc_n), ("ICCBased", Some(4)), "{s}"); + assert!(w.icc.as_deref() == Some(icc.as_slice()), "{s}: the image's own profile, byte for byte"); + }; + for s in [ + json!({"output": {"profiles": "all"}}), + json!({"output": {"profiles": "taggedSource"}}), + json!({"standard": "pdfX4"}), + json!({"standard": "pdfX3"}), + json!({"output": {"profiles": "all", "conversion": "preserveNumbers", "destination": DEVICE_CMYK}}), + ] { + let (w, bytes) = export(&d, s.clone()); + tagged(&w, &s); + assert_eq!(blobs(&import(&bytes).unwrap())[0].cmyk().unwrap().data, tiff_inks, "{s}: the inks as they were"); + } + // Without source profiles, untagged; PDF/X-1a images are always DeviceCMYK. + for s in [json!({}), json!({"output": {"profiles": "destination"}}), json!({"standard": "pdfX1a", "output": {"profiles": "all"}})] { + let (w, _) = export(&d, s.clone()); + assert!(w.icc.as_deref() != Some(icc.as_slice()), "{s}: {w:?}"); + } + let (w, _) = export(&d, json!({"standard": "pdfX1a", "output": {"profiles": "all"}})); + assert_eq!(w.space, "DeviceCMYK"); + // Converted to another CMYK profile: its new numbers aren't in the old profile. + let (w, _) = export(&d, json!({"output": {"profiles": "all", "conversion": "destination", "destination": DEVICE_CMYK}})); + assert!(w.icc.as_deref() != Some(icc.as_slice()), "{w:?}"); + + // A CMYK JPEG kept as it is carries the profile only when source profiles are included, and + // PDF/X-1a writes it untagged. + let jpg = cmyk_jpeg_with(&flat(ink, 64 * 64), 64, 64, &icc); + let d = image_doc(ImageBlob::new("image/jpeg", jpg.clone()), 64, 64); + let s = json!({"output": {"profiles": "all"}}); + let (w, _) = export(&d, s.clone()); + tagged(&w, &s); + assert!(w.data == jpg, "the JPEG data unchanged"); + for s in [json!({"standard": "pdfX1a"}), json!({})] { + let (w, _) = export(&d, s.clone()); + assert_eq!((w.space.as_str(), w.filter.as_deref()), ("DeviceCMYK", Some("DCTDecode")), "{s}"); + assert!(w.data == jpg, "{s}: the JPEG data unchanged"); + } + // Resampled and compressed again, it keeps the profile. + let s = json!({"output": {"profiles": "all"}, "compression": {"color": {"downsample": "bicubic", "ppi": 72.0, "abovePpi": 100.0}}}); + let (w, bytes) = export(&d, s.clone()); + tagged(&w, &s); + assert_eq!((w.width, w.filter.as_deref()), (40, Some("DCTDecode")), "{s}"); + assert!(blobs(&import(&bytes).unwrap())[0].cmyk().unwrap().data.as_chunks::<4>().0.iter().all(|p| close(p, &ink, 3))); + + // With its mask as its soft mask. + let mut d = masked_doc(png(image::GrayImage::from_raw(2, 2, vec![255, 128, 0, 64]).unwrap()), true, false); + d.images.insert("img".into(), cmyk_tiff_with(ink, 2, 2, &icc)); + let s = json!({"output": {"profiles": "all"}}); + let (w, bytes) = export(&d, s.clone()); + tagged(&w, &s); + assert!(w.smask, "{w:?}"); + assert!(!String::from_utf8_lossy(&bytes).contains("/S/Luminosity"), "no luminosity soft mask"); +} + +/// A CMYK JPEG kept as it is whose header declares far more pixels than the app reads is left out +/// with a warning, as other images that large are. +#[test] +fn a_kept_cmyk_jpeg_declaring_too_many_pixels_is_left_out() { + let mut jpg = cmyk_jpeg_with(&flat([0, 102, 255, 0], 4), 2, 2, &cmyk_profile(|_| {})); + // Height and width of the SOF0 segment (after its marker, length and precision): 16384 × 16384. + let sof = jpg.windows(2).position(|w| w == [0xFF, 0xC0]).unwrap(); + jpg[sof + 5..sof + 9].copy_from_slice(&[0x40, 0, 0x40, 0]); + assert_eq!(ImageBlob::new("image/jpeg", jpg.clone()).header_size(), Some((16384, 16384))); + let d = image_doc(ImageBlob::new("image/jpeg", jpg), 2, 2); + for s in [ + json!({"compression": {"color": {"downsample": "none"}}}), + json!({"output": {"profiles": "all"}, "compression": {"color": {"downsample": "none"}}}), + ] { + let out = export_with_report(&d, &opts(s.clone())).unwrap(); + assert!(written(&out.bytes).is_empty(), "{s}"); + assert!(out.warnings.iter().any(|w| w.contains("couldn't be decoded")), "{s}: {:?}", out.warnings); + } +} + +/// The profile each transparency group of written PDF `bytes` blends in: its ICC-based space's +/// profile, or `None` for DeviceCMYK. +fn group_profiles(bytes: &[u8]) -> Vec>> { + let text = String::from_utf8_lossy(bytes); + let file = Pdf::new(Arc::new(bytes.to_vec())).unwrap(); + let groups: Vec<&str> = text.split("/Group<<").skip(1).filter(|g| g.contains("/S/Transparency")).collect(); + assert!(!groups.is_empty(), "{text}"); + groups + .into_iter() + .map(|group| { + let cs = group.split("/CS").nth(1).unwrap(); + if cs.starts_with("/DeviceCMYK") { + return None; + } + let cs: i32 = cs.trim_start().split(' ').next().unwrap().parse().unwrap(); + let space = text.split(&format!("\n{cs} 0 obj\n")).nth(1).unwrap(); + let stream: i32 = space.strip_prefix("[/ICCBased ").unwrap().split(' ').next().unwrap().parse().unwrap(); + let profile = file.xref().get::>(craft_pdf::syntax::object::ObjectIdentifier::new(stream, 0)).unwrap(); + Some(profile.decoded().unwrap().into_owned()) + }) + .collect() +} + +/// Transparency in a tagged CMYK document blends in the document's CMYK profile space, not in the +/// space of the profile a CMYK image carries, whichever the file holds first. +#[test] +fn tagged_cmyk_documents_blend_in_their_own_profile_beside_an_image_profile() { + let icc = cmyk_profile(|_| {}); + let document = cms::icc_bytes(&cms::active_settings().cmyk).unwrap().to_vec(); + // A transparent CMYK rectangle over the image, and the image itself transparent. + let mut d = image_doc(cmyk_tiff_with([0, 102, 255, 0], 4, 4, &icc), 4, 4); + let mut n = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(20.0, 20.0, 60.0, 60.0)), + Appearance::basic(Paint::solid(Color::cmyk(0.0, 1.0, 0.0, 0.0)), Paint::None, 0.0), + ); + n.opacity = 0.5; + let l = d.layers[0].id; + d.insert(Some(l), 1, n).unwrap(); + let mut alone = Document::new_with_mode(100.0, 100.0, ColorMode::Cmyk); + alone.images.insert("img".into(), cmyk_tiff_with([0, 102, 255, 0], 4, 4, &icc)); + let image = + ImageObject { key: "img".into(), width: 4, height: 4, xf: Affine::scale(10.0), link: None, placement: Default::default(), pixels: None }; + let mut n = Node::new(alone.alloc_id(), NodeKind::Image(Box::new(image))); + n.opacity = 0.5; + let l = alone.layers[0].id; + alone.insert(Some(l), 0, n).unwrap(); + for d in [d, alone] { + let out = export_with_report(&d, &opts(json!({"output": {"profiles": "all"}}))).unwrap(); + let w = written(&out.bytes); + assert!(w.iter().any(|w| w.icc.as_deref() == Some(icc.as_slice())), "the image's own profile: {w:?}"); + for profile in group_profiles(&out.bytes) { + assert!(profile.as_ref().is_none_or(|p| *p == document), "the group blends in the document's CMYK profile or DeviceCMYK"); + } + } +} + +/// Only a well-formed CMYK profile tags an image: one whose size, signature, class, colour space +/// or tag table is wrong leaves it untagged. +#[test] +fn a_cmyk_image_with_a_malformed_profile_is_written_untagged() { + let tag = |icc: Vec| crate::images::cmyk_icc(&ImageBlob::new("image/jpeg", cmyk_jpeg_with(&flat([0, 102, 255, 0], 4), 2, 2, &icc))); + let good = cmyk_profile(|_| {}); + assert_eq!(tag(good.clone()), Some(good)); + let bad: [(&str, Vec); 7] = [ + ("declared size", cmyk_profile(|i| i[0..4].copy_from_slice(&200u32.to_be_bytes()))), + ("signature", cmyk_profile(|i| i[36..40].copy_from_slice(b"xxxx"))), + ("device link class", cmyk_profile(|i| i[12..16].copy_from_slice(b"link"))), + ("RGB colour space", cmyk_profile(|i| i[16..20].copy_from_slice(b"RGB "))), + ("tag beyond the end", cmyk_profile(|i| i[136..140].copy_from_slice(&150u32.to_be_bytes()))), + ("table beyond the end", cmyk_profile(|i| i[128..132].copy_from_slice(&3u32.to_be_bytes()))), + ("header only", cmyk_profile(|i| i.truncate(100))), + ]; + for (what, icc) in bad { + assert_eq!(tag(icc), None, "{what}"); + } + // And the image is written untagged. + let icc = cmyk_profile(|i| i[36..40].copy_from_slice(b"xxxx")); + let d = image_doc(cmyk_tiff_with([0, 102, 255, 0], 4, 4, &icc), 4, 4); + let out = export_with_report(&d, &opts(json!({"output": {"profiles": "taggedSource"}}))).unwrap(); + let w = written(&out.bytes); + assert_eq!((w.len(), w[0].space.as_str()), (1, "DeviceCMYK"), "{w:?}"); +} + /// A Press Quality export of a 2 × 2 CMYK image masked by PNG `mask` on its own pixel grid /// (`clip`, `invert`): the file, and the decoded soft mask of each CMYK image (`None`: it has none). fn export_masked(mask: Vec, clip: bool, invert: bool) -> (Vec, Vec>>) { diff --git a/crates/pdf/src/tests/compression.rs b/crates/pdf/src/tests/compression.rs index c02f3f5e1c..400bc0b0a8 100644 --- a/crates/pdf/src/tests/compression.rs +++ b/crates/pdf/src/tests/compression.rs @@ -5,7 +5,7 @@ use std::io::Cursor; -use craft_pdf::syntax::object::{Name, Object}; +use craft_pdf::syntax::object::{Array, Name, Object, Stream}; use image::{DynamicImage, ImageFormat}; use serde_json::{Value, json}; use vectorcraft_doc::{Document, ImageBlob, ImageObject, Node, NodeKind}; @@ -73,6 +73,38 @@ fn images_above_the_threshold_are_resampled_to_the_target_resolution() { assert!(text.contains("/Width 100") && text.contains("/DeviceGray"), "grey at 100 ppi"); } +/// An image with clear pixels, resampled, keeps the color of its opaque pixels: the clear black +/// beside them does not darken them. +#[test] +fn resampled_images_keep_their_color_beside_clear_pixels() { + let striped = image::RgbaImage::from_fn(600, 600, |x, _| if x % 2 == 0 { image::Rgba([200, 30, 30, 255]) } else { image::Rgba([0, 0, 0, 0]) }); + let d = doc(encoded(striped.into(), ImageFormat::Png), "image/png"); + for method in ["average", "bicubic"] { + let mut settings: PdfSettings = + serde_json::from_value(json!({"compression": {"color": {"downsample": method, "ppi": 150, "abovePpi": 225, "compression": "zip"}}})) + .unwrap(); + settings.compression.compress_text = false; + let bytes = export_with_report(&d, &PdfOptions { settings, ..Default::default() }).unwrap().bytes; + let file = craft_pdf::syntax::Pdf::new(std::sync::Arc::new(bytes)).unwrap(); + let rgb = file + .objects() + .into_iter() + .find_map(|o| match o { + Object::Stream(s) + if s.dict().get::>(b"Subtype").is_some_and(|n| n.as_ref() == b"Image") && s.dict().contains_key(b"SMask") => + { + Some(s.decoded().unwrap().into_owned()) + } + _ => None, + }) + .unwrap_or_else(|| panic!("{method}: a color image with a soft mask")); + assert_eq!(rgb.len(), 150 * 150 * 3, "{method}"); + for p in rgb.as_chunks::<3>().0 { + assert!(p[0].abs_diff(200) <= 3 && p[1].abs_diff(30) <= 3 && p[2].abs_diff(30) <= 3, "{method}: {p:?}"); + } + } +} + /// The width and height of each image XObject in `pdf`. fn image_sizes(pdf: &[u8]) -> Vec<(u32, u32)> { let file = craft_pdf::syntax::Pdf::new(std::sync::Arc::new(pdf.to_vec())).unwrap(); @@ -234,6 +266,292 @@ fn images_declaring_more_than_the_allowance_are_not_decoded() { assert_eq!(crate::images::mask_alpha(&blob, 60_000, 60_000, false), None); assert_eq!(crate::images::mask_alpha(&blob, 2, 2, false), None, "another size is not decoded at all"); let c: CompressionSettings = serde_json::from_value(json!({"gray": {"downsample": "bicubic", "ppi": 72, "abovePpi": 100}})).unwrap(); - let r = crate::images::recode(&png, (10.0, 10.0), &c, false, None); + let r = crate::images::recode(&png, (10.0, 10.0), &c, false, None, true); assert!(r.image.is_none(), "kept as it is"); } + +/// A version 2.1 display ICC profile for colour space `space` (`RGB ` or `GRAY`), `len` bytes in +/// all, with an empty tag table, every byte after the tag count different from its neighbors. +fn icc_profile(space: &[u8; 4], len: usize) -> Vec { + let mut icc: Vec = (0..len).map(|i| (i % 251) as u8).collect(); + icc[..4].copy_from_slice(&u32::try_from(len).unwrap().to_be_bytes()); + icc[8..12].copy_from_slice(&[2, 0x10, 0, 0]); + icc[12..16].copy_from_slice(b"mntr"); + icc[16..20].copy_from_slice(space); + icc[36..40].copy_from_slice(b"acsp"); + icc[128..132].copy_from_slice(&0u32.to_be_bytes()); + icc +} + +/// `img` encoded as `format` carrying ICC profile `icc`. +fn tagged(img: &DynamicImage, icc: &[u8], format: ImageFormat) -> Vec { + use image::ImageEncoder as _; + let mut out = Vec::new(); + match format { + ImageFormat::Tiff => { + let mut enc = image::codecs::tiff::TiffEncoder::new(Cursor::new(&mut out)); + enc.set_icc_profile(icc.to_vec()).unwrap(); + img.write_with_encoder(enc).unwrap(); + } + ImageFormat::Jpeg => { + let mut enc = image::codecs::jpeg::JpegEncoder::new(&mut out); + enc.set_icc_profile(icc.to_vec()).unwrap(); + img.write_with_encoder(enc).unwrap(); + } + _ => { + let mut enc = image::codecs::png::PngEncoder::new(&mut out); + enc.set_icc_profile(icc.to_vec()).unwrap(); + img.write_with_encoder(enc).unwrap(); + } + } + out +} + +/// An image XObject as it is written. +#[derive(Debug, PartialEq)] +struct Written { + /// Its colour space's name: `ICCBased` for an ICC-based one. + space: String, + /// The profile an ICC-based colour space holds. + icc: Option>, + bits: u8, + filter: String, + smask: bool, +} + +/// Each image XObject of `pdf` other than soft masks. +fn image_spaces(pdf: &[u8]) -> Vec { + let file = craft_pdf::syntax::Pdf::new(std::sync::Arc::new(pdf.to_vec())).unwrap(); + let images: Vec> = file + .objects() + .into_iter() + .filter_map(|o| match o { + Object::Stream(s) if s.dict().get::>(b"Subtype").is_some_and(|n| n.as_ref() == b"Image") => Some(s), + _ => None, + }) + .collect(); + let masks: Vec> = images.iter().filter_map(|s| s.dict().get::>(b"SMask")).map(|m| m.raw_data().to_vec()).collect(); + let mut out = vec![]; + for s in images.iter().filter(|s| !masks.contains(&s.raw_data().to_vec())) { + let d = s.dict(); + let (space, icc) = match (d.get::>(b"ColorSpace"), d.get::>(b"ColorSpace")) { + (Some(n), _) => (n.as_str().to_string(), None), + (_, Some(a)) => { + let mut it = a.flex_iter(); + let name = it.next::>().unwrap().as_str().to_string(); + (name, it.next::>().map(|s| s.decoded().unwrap().into_owned())) + } + _ => (String::new(), None), + }; + let filter = d.get::>(b"Filter").map(|n| n.as_str().to_string()).unwrap_or_default(); + let (bits, smask) = (d.get::(b"BitsPerComponent").unwrap_or(0), d.get::>(b"SMask").is_some()); + out.push(Written { space, icc, bits, filter, smask }); + } + out +} + +/// The decoded samples of each image XObject of `pdf` other than soft masks. +fn image_samples(pdf: &[u8]) -> Vec> { + let file = craft_pdf::syntax::Pdf::new(std::sync::Arc::new(pdf.to_vec())).unwrap(); + let images: Vec> = file + .objects() + .into_iter() + .filter_map(|o| match o { + Object::Stream(s) if s.dict().get::>(b"Subtype").is_some_and(|n| n.as_ref() == b"Image") => Some(s), + _ => None, + }) + .collect(); + let masks: Vec> = images.iter().filter_map(|s| s.dict().get::>(b"SMask")).map(|m| m.raw_data().to_vec()).collect(); + images.iter().filter(|s| !masks.contains(&s.raw_data().to_vec())).map(|s| s.decoded().unwrap().into_owned()).collect() +} + +/// The raw (still encoded) data of each image XObject of `pdf`. +fn image_data(pdf: &[u8]) -> Vec> { + let file = craft_pdf::syntax::Pdf::new(std::sync::Arc::new(pdf.to_vec())).unwrap(); + file.objects() + .into_iter() + .filter_map(|o| match o { + Object::Stream(s) if s.dict().get::>(b"Subtype").is_some_and(|n| n.as_ref() == b"Image") => Some(s.raw_data().to_vec()), + _ => None, + }) + .collect() +} + +/// A PNG or JPEG embedded as it is whose gray or RGB profile is malformed is written without it, +/// the JPEG with its JPEG data unchanged: a profile whose header declares another size, one without +/// the `acsp` signature, one whose tag table runs past its end, and one cut short after 64 bytes. +#[test] +fn a_malformed_profile_is_left_out_of_a_png_or_jpeg_kept_as_it_is() { + for (space, img, device) in [(b"RGB ", colour(), "DeviceRGB"), (b"GRAY", colour().grayscale(), "DeviceGray")] { + let mut malformed = [icc_profile(space, 600), icc_profile(space, 600), icc_profile(space, 600), icc_profile(space, 600)]; + malformed[0][..4].copy_from_slice(&601u32.to_be_bytes()); + malformed[1][36..40].copy_from_slice(b"xxxx"); + malformed[2][128..132].copy_from_slice(&100u32.to_be_bytes()); + malformed[3].truncate(64); + malformed[3][..4].copy_from_slice(&64u32.to_be_bytes()); + for (i, icc) in malformed.iter().enumerate() { + for (format, mime, filter) in [(ImageFormat::Png, "image/png", "FlateDecode"), (ImageFormat::Jpeg, "image/jpeg", "DCTDecode")] { + let what = format!("{device}, {format:?}, malformed profile {i}"); + let bytes = tagged(&img, icc, format); + let mut settings = PdfSettings::default(); + settings.compression.compress_text = false; + let pdf = export_with_report(&doc(bytes.clone(), mime), &PdfOptions { settings, ..Default::default() }).unwrap().bytes; + let spaces = image_spaces(&pdf); + let plain = spaces.len() == 1 && spaces[0].space == device && spaces[0].icc.is_none() && spaces[0].filter == filter; + assert!(plain, "{what}: {spaces:?}"); + if format == ImageFormat::Jpeg { + assert!(image_data(&pdf) == [bytes], "{what}: the JPEG data unchanged"); + } + } + } + } +} + +/// In PDF/X-1a a tagged gray JPEG kept as JPEG is written with its JPEG data, without its profile. +#[test] +fn pdf_x1a_keeps_a_tagged_gray_jpeg_as_jpeg() { + let jpeg = tagged(&colour().grayscale(), &icc_profile(b"GRAY", 300), ImageFormat::Jpeg); + let d = doc(jpeg.clone(), "image/jpeg"); + for compression in [json!({}), json!({"gray": {"compression": "jpeg"}})] { + let mut settings: PdfSettings = + serde_json::from_value(json!({"standard": "pdfX1a", "compatibility": "1.3", "compression": compression.clone()})).unwrap(); + settings.compression.compress_text = false; + let bytes = export_with_report(&d, &PdfOptions { settings, ..Default::default() }).unwrap().bytes; + crate::pdfx::verify(&bytes, Standard::PdfX1a).unwrap_or_else(|e| panic!("{compression}: {e}")); + let spaces = image_spaces(&bytes); + let dct = spaces.len() == 1 && spaces[0].space == "DeviceGray" && spaces[0].icc.is_none() && spaces[0].filter == "DCTDecode"; + assert!(dct, "{compression}: {spaces:?}"); + assert!(image_data(&bytes) == [jpeg.clone()], "{compression}: the JPEG data unchanged"); + } +} + +/// A gray or RGB TIFF that carries an ICC profile of its colour space is written in an ICC-based +/// colour space holding the same profile, at 16 bits a sample from PDF 1.5 on, with its alpha as +/// a soft mask; and so is a tagged TIFF or PNG that is resampled or compressed with JPEG. Pixels +/// the Output settings convert, and a profile of another colour space, are written without it. +#[test] +fn tagged_tiffs_keep_their_icc_profile() { + let (rgb, gray) = (icc_profile(b"RGB ", 600), icc_profile(b"GRAY", 300)); + let mut clear = colour().to_rgba8(); + clear.put_pixel(0, 0, image::Rgba([10, 20, 30, 0])); + let tiff = |img: &DynamicImage, icc: &[u8]| doc(tagged(img, icc, ImageFormat::Tiff), "image/tiff"); + let export = |d: &Document, settings: Value| { + let mut settings: PdfSettings = serde_json::from_value(settings).unwrap(); + settings.compression.compress_text = false; + let r = export_with_report(d, &PdfOptions { settings, ..Default::default() }).unwrap(); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + image_spaces(&r.bytes) + }; + let icc_based = |icc: &[u8], bits: u8, filter: &str, smask: bool| { + vec![Written { space: "ICCBased".into(), icc: Some(icc.to_vec()), bits, filter: filter.into(), smask }] + }; + let flate = "FlateDecode"; + let cases = [ + ("RGB", tiff(&colour(), &rgb), json!({}), icc_based(&rgb, 8, flate, false)), + ("gray", tiff(&colour().grayscale(), &gray), json!({}), icc_based(&gray, 8, flate, false)), + ( + "RGB, 16 bits", + tiff(&DynamicImage::ImageRgb16(colour().to_rgb16()), &rgb), + json!({"compatibility": "1.7"}), + icc_based(&rgb, 16, flate, false), + ), + ( + "RGB, 16 bits, PDF 1.4", + tiff(&DynamicImage::ImageRgb16(colour().to_rgb16()), &rgb), + json!({"compatibility": "1.4"}), + icc_based(&rgb, 8, flate, false), + ), + ("RGBA", tiff(&clear.clone().into(), &rgb), json!({}), icc_based(&rgb, 8, flate, true)), + ( + "RGB, resampled", + tiff(&colour(), &rgb), + json!({"compression": {"color": {"downsample": "bicubic", "ppi": 150, "abovePpi": 225}}}), + icc_based(&rgb, 8, flate, false), + ), + ( + "gray, resampled", + tiff(&colour().grayscale(), &gray), + json!({"compression": {"gray": {"downsample": "bicubic", "ppi": 150, "abovePpi": 225}}}), + icc_based(&gray, 8, flate, false), + ), + ("RGB, JPEG", tiff(&colour(), &rgb), json!({"compression": {"color": {"compression": "jpeg"}}}), icc_based(&rgb, 8, "DCTDecode", false)), + ( + "gray, JPEG", + tiff(&colour().grayscale(), &gray), + json!({"compression": {"gray": {"compression": "jpeg"}}}), + icc_based(&gray, 8, "DCTDecode", false), + ), + ( + "PNG, resampled", + doc(tagged(&colour(), &rgb, ImageFormat::Png), "image/png"), + json!({"compression": {"color": {"downsample": "bicubic", "ppi": 150, "abovePpi": 225}}}), + icc_based(&rgb, 8, flate, false), + ), + ]; + for (what, d, settings, want) in cases { + assert_eq!(export(&d, settings), want, "{what}"); + } + // 16-bit samples are written big-endian from PDF 1.5 on, and reduced to 8 bits before it. + // Their high and low bytes differ, so a swapped or truncated stream does not match. + let deep = DynamicImage::ImageRgb16(image::ImageBuffer::from_fn(600, 600, |x, y| { + image::Rgb([((x * 109 + y) % 65_521) as u16, ((y * 257 + 3) ^ 0x5a) as u16, ((x * y) % 65_521) as u16]) + })); + let sixteen: Vec = deep.to_rgb16().iter().flat_map(|v| v.to_be_bytes()).collect(); + for (compatibility, want) in [("1.7", sixteen), ("1.4", deep.to_rgb8().into_raw())] { + let mut settings: PdfSettings = serde_json::from_value(json!({ "compatibility": compatibility })).unwrap(); + settings.compression.compress_text = false; + let r = export_with_report(&tiff(&deep, &rgb), &PdfOptions { settings, ..Default::default() }).unwrap(); + assert!(image_samples(&r.bytes) == [want], "16-bit samples, PDF {compatibility}"); + } + // A gray image in an RGB profile stays RGB to keep it, resampled too. + let neutral = tiff(&DynamicImage::ImageRgb8(colour().grayscale().to_rgb8()), &rgb); + for settings in [json!({}), json!({"compression": {"color": {"downsample": "bicubic", "ppi": 150, "abovePpi": 225}}})] { + assert_eq!(export(&neutral, settings.clone()), icc_based(&rgb, 8, flate, false), "neutral RGB, {settings}"); + } + // A profile of another colour space is left out. + let spaces = export(&tiff(&colour(), &gray), json!({})); + assert!(spaces.len() == 1 && spaces[0].space == "DeviceRGB" && spaces[0].icc.is_none(), "RGB in a gray profile: {spaces:?}"); + // A malformed profile is left out, the image kept as it is, resampled or compressed with JPEG: + // one whose header declares another size, one without the `acsp` signature, and one whose tag + // table runs past its end. + let mut malformed = [rgb.clone(), rgb.clone(), rgb.clone()]; + malformed[0][..4].copy_from_slice(&601u32.to_be_bytes()); + malformed[1][36..40].copy_from_slice(b"xxxx"); + malformed[2][128..132].copy_from_slice(&100u32.to_be_bytes()); + let compressions = + [json!({}), json!({"color": {"downsample": "bicubic", "ppi": 150, "abovePpi": 225}}), json!({"color": {"compression": "jpeg"}})]; + for (i, icc) in malformed.iter().enumerate() { + for compression in &compressions { + let spaces = export(&tiff(&colour(), icc), json!({ "compression": compression })); + assert!( + spaces.len() == 1 && spaces[0].space == "DeviceRGB" && spaces[0].icc.is_none(), + "malformed profile {i}, {compression}: {spaces:?}" + ); + } + } + // Converted pixels are in the destination's colours, not the image's profile. + for destination in [vectorcraft_color::cms::DISPLAY_P3, vectorcraft_color::cms::GENERIC_CMYK] { + let spaces = export(&tiff(&colour(), &rgb), json!({"output": {"conversion": "destination", "destination": destination}})); + assert!(spaces.len() == 1 && spaces[0].icc.as_deref() != Some(rgb.as_slice()), "converted to {destination}: {spaces:?}"); + } + // PDF/X-1a allows no ICC-based color spaces: a tagged gray TIFF (8 or 16 bits), PNG or JPEG is + // written in DeviceGray, kept as it is, resampled or compressed with JPEG, and the file passes + // the PDF/X-1a check. + let compressions = [json!({}), json!({"gray": {"downsample": "bicubic", "ppi": 150, "abovePpi": 225}}), json!({"gray": {"compression": "jpeg"}})]; + let tiff16 = tiff(&DynamicImage::ImageLuma16(colour().to_luma16()), &gray); + let png = doc(tagged(&colour().grayscale(), &gray, ImageFormat::Png), "image/png"); + let jpeg = doc(tagged(&colour().grayscale(), &gray, ImageFormat::Jpeg), "image/jpeg"); + for (format, d) in [("TIFF", tiff(&colour().grayscale(), &gray)), ("TIFF, 16 bits", tiff16), ("PNG", png), ("JPEG", jpeg)] { + for compression in &compressions { + let mut settings: PdfSettings = + serde_json::from_value(json!({"standard": "pdfX1a", "compatibility": "1.3", "compression": compression.clone()})).unwrap(); + settings.compression.compress_text = false; + let r = export_with_report(&d, &PdfOptions { settings, ..Default::default() }); + let bytes = r.unwrap_or_else(|e| panic!("PDF/X-1a, {format}, {compression}: {e}")).bytes; + crate::pdfx::verify(&bytes, Standard::PdfX1a).unwrap_or_else(|e| panic!("PDF/X-1a, {format}, {compression}: {e}")); + let spaces = image_spaces(&bytes); + let gray = spaces.len() == 1 && spaces[0].space == "DeviceGray" && spaces[0].icc.is_none(); + assert!(gray, "PDF/X-1a, {format}, {compression}: {spaces:?}"); + } + } +} diff --git a/crates/pdf/src/tests/layers.rs b/crates/pdf/src/tests/layers.rs index 0650e3f0ef..b11cbc47d8 100644 --- a/crates/pdf/src/tests/layers.rs +++ b/crates/pdf/src/tests/layers.rs @@ -131,6 +131,37 @@ fn pdf_layers_import_back_as_layers() { } } +/// A hidden layer written as a PDF layer places the live effects of its instances' symbol art, +/// also in a PDF/A-2b file at PDF 1.4 whose 17,000 pt page has it written as PDF 1.6: the symbol's +/// square from x = 10 to 40, which a Transform effect moves 100 pt right, is written from x = 110 +/// to 140. +#[test] +fn a_hidden_layer_places_symbol_art_effects_when_a_long_page_raises_the_version() { + let mut d = Document::new(17_000.0, 300.0); + d.layers.clear(); + let mut square = rect(&mut d, 10.0, RED); + square.appearance.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params: json!({"moveH": 100.0}), visible: true }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Moved".into(), art: square.into() }); + let instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Moved".into(), xf: vectorcraft_geom::Affine::IDENTITY }); + let mut l = Node::layer(d.alloc_id(), "Hidden", LayerColor::Preset(0)); + l.visible = false; + if let NodeKind::Layer { children, .. } = &mut l.kind { + children.push(instance.into()); + } + d.layers.push(l.into()); + for compatibility in [Compatibility::Pdf14, Compatibility::Pdf16] { + let settings = PdfSettings { standard: Standard::PdfA2b, compatibility, create_layers: true, ..PdfSettings::default() }; + let r = export_with_report(&d, &PdfOptions { settings, created: Some(1_791_200_000), ..Default::default() }).unwrap(); + assert!(r.bytes.starts_with(b"%PDF-1.6"), "{compatibility:?}"); + let back = import_with_report(&r.bytes, &ImportOptions::default()).unwrap().document; + let hidden = back.layers.iter().find(|l| l.name.as_deref() == Some("Hidden")).expect("the hidden layer"); + let art = hidden.children().unwrap(); + assert_eq!(art.len(), 1, "{compatibility:?}"); + let b = art[0].geometric_bounds().unwrap(); + assert!((b.x0 - 110.0).abs() < 0.1 && (b.x1 - 140.0).abs() < 0.1, "{compatibility:?}: {b:?}"); + } +} + /// The rows of `nodes` in paint order, depth first: `depth name visible` for layers, `depth fill` /// for art. fn tree(nodes: &[std::sync::Arc], depth: usize, out: &mut Vec) { diff --git a/crates/pdf/src/tests/links.rs b/crates/pdf/src/tests/links.rs index c23854439f..f4792e7fa0 100644 --- a/crates/pdf/src/tests/links.rs +++ b/crates/pdf/src/tests/links.rs @@ -6,8 +6,8 @@ use std::sync::Arc; use craft_pdf::syntax::Pdf; use craft_pdf::syntax::object::{Array, Dict, Name}; use vectorcraft_color::Color; -use vectorcraft_doc::{Document, Node, NodeId}; -use vectorcraft_geom::{Rect, shapes}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; +use vectorcraft_geom::{Affine, Rect, shapes}; use super::{add, doc, rect_node}; use crate::*; @@ -89,6 +89,27 @@ fn hidden_and_unprinted_objects_have_no_links_and_clipping_trims_them() { assert_eq!(links(&export(&d, &PdfOptions::default()).unwrap()), vec![Vec::<(String, [f32; 4])>::new()]); } +/// A linked symbol instance whose art has a live effect links over the art where the effect draws it. +#[test] +fn a_linked_instance_keeps_its_link_when_its_art_has_effects() { + let mut art = rect_node(Rect::new(10.0, 40.0, 20.0, 50.0), Color::rgb(0.0, 0.0, 1.0)); + art.appearance.effects.push(vectorcraft_doc::Effect { + id: "distort.transform".into(), + params: serde_json::json!({"moveH": 100.0}), + visible: true, + }); + let mut d = doc(200.0, 100.0); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Moved".into(), art: Arc::new(art) }); + let mut instance = Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: "Moved".into(), xf: Affine::IDENTITY }); + instance.edit_attrs(|a| a.url = "https://example.com/symbol".into()); + add(&mut d, instance); + let pages = links(&export(&d, &PdfOptions::default()).unwrap()); + let [(uri, rect)] = pages[0].as_slice() else { panic!("one link: {pages:?}") }; + assert_eq!(uri, "https://example.com/symbol"); + // x 110…120 after the 100 pt move; y up: 100 − 50 to 100 − 40. + assert!(near(*rect, [110.0, 50.0, 120.0, 60.0]), "{rect:?}"); +} + #[test] fn each_page_links_its_own_artboard_objects() { let mut d = doc(200.0, 100.0); diff --git a/crates/pdf/src/tests/output.rs b/crates/pdf/src/tests/output.rs index a15c2aa429..e0f00dc0e7 100644 --- a/crates/pdf/src/tests/output.rs +++ b/crates/pdf/src/tests/output.rs @@ -161,6 +161,36 @@ fn spot_alternates_and_device_n_gradient_inks_are_written_as_the_document_holds_ assert!(text.contains("/C0[0 0 0.75]/C1[0.75 0.04 0]"), "the stops' C75, K4 and 75% Gold are written as they are"); } +#[test] +fn blend_steps_between_spot_gradients_with_process_plates_print_both_inks() { + let stop = |offset: f32, tint: f32, plates: Option<[f32; 4]>| { + let mut s = GradientStop::new(offset, Color::cmyk(0.0, 0.2, 0.8, 0.1).tinted(tint)); + s.swatch = Some("Gold".into()); + s.tint = tint; + s.plates = plates; + s + }; + let gradient = |tint: f32, plates: Option<[f32; 4]>| { + Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, vec![stop(0.0, tint, plates), stop(1.0, tint, plates)])))) + }; + let step_pdf = |a: &Paint, b: &Paint| { + let mut d = doc(ColorMode::Cmyk, &[]); + d.swatches.push(Swatch { name: "Gold".into(), paint: Paint::solid(Color::cmyk(0.0, 0.2, 0.8, 0.1)), global: true, spot: true }); + let step = vectorcraft_doc::blend::lerp_paint(a, b, 0.5); + let l = d.layers[0].id; + let n = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 110.0, 30.0)), Appearance::basic(step, Paint::None, 0.0)); + d.insert(Some(l), 0, n).unwrap(); + String::from_utf8_lossy(&export(&d, &PdfOptions::uncompressed()).unwrap()).into_owned() + }; + // The middle step prints 60% Gold over 30% Cyan, in one DeviceN shading of both inks. + let text = step_pdf(&gradient(0.2, Some([0.2, 0.0, 0.0, 0.0])), &gradient(1.0, Some([0.4, 0.0, 0.0, 0.0]))); + assert!(text.contains("[/DeviceN[/Cyan/Gold]"), "{text}"); + assert!(text.contains("/C0[0.3 0.6]/C1[0.3 0.6]"), "{text}"); + // Without plates the step is a Separation shading of Gold alone. + let text = step_pdf(&gradient(0.2, None), &gradient(1.0, None)); + assert!(!text.contains("/DeviceN") && text.contains("[/Separation/Gold/"), "{text}"); +} + /// A spot swatch's Separation space with alternate C0 M20 Y80 K10 under `colorant` (a PDF name). fn gold_separation(colorant: &str) -> String { format!("[/Separation{colorant}/DeviceCMYK<>]") diff --git a/crates/pdf/src/tests/print.rs b/crates/pdf/src/tests/print.rs index 5c5e1eb2c0..ecd1f25ce1 100644 --- a/crates/pdf/src/tests/print.rs +++ b/crates/pdf/src/tests/print.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use serde_json::json; -use vectorcraft_color::{Color, Paint, Swatch}; +use vectorcraft_color::{Color, Freeform, FreeformPoint, Gradient, GradientKind, GradientPaint, GradientStop, Paint, Swatch}; use vectorcraft_doc::{Appearance, Artboard, Document, LayerColor, Node, NodeKind}; use vectorcraft_geom::{Rect, shapes}; use vectorcraft_testkit::raster::render_region; @@ -451,6 +451,85 @@ fn a_symbol_instances_brush_art_keeps_its_artboard_printed() { assert!(p[0].1.iter().any(|(_, paint)| rgb8(paint) == [255, 0, 0]), "{p:?}"); } +#[test] +fn a_brushed_paths_brush_art_keeps_its_artboard_printed_and_framed() { + // A line from (-5, 40) to (-5, 60) with a 1 pt red stroke painted by a 20 pt round nib, alone, + // in a group or as the art of a symbol instance: the line lies left of the artboard, and the nib + // paints 10 pt either side of it, onto the artboard. + let line = || { + let mut stroke = Appearance::basic(Paint::None, rgb(1.0, 0.0, 0.0), 1.0); + stroke.stroke_mut().unwrap().brush = Some("3 pt. Round".into()); + Node::path(vectorcraft_doc::NodeId(0), shapes::line((-5.0, 40.0).into(), (-5.0, 60.0).into()), stroke) + }; + for what in ["path", "group", "symbol instance"] { + let mut d = doc(100.0, 100.0, &[]); + let mut lib = vectorcraft_brush::library(&d); + let Some(vectorcraft_brush::BrushKind::Calligraphic(c)) = lib.iter_mut().find(|b| b.name == "3 pt. Round").map(|b| &mut b.kind) else { + panic!("the 3 pt. Round brush") + }; + c.size = 20.0; + vectorcraft_brush::store(&mut d, &lib); + let mut n = match what { + "path" => line(), + "group" => Node::group(vectorcraft_doc::NodeId(0), vec![Arc::new(line())]), + _ => { + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Nib".into(), art: Arc::new(line()) }); + Node::new(vectorcraft_doc::NodeId(0), NodeKind::SymbolInstance { symbol: "Nib".into(), xf: vectorcraft_geom::Affine::IDENTITY }) + } + }; + n.id = d.alloc_id(); + let layer = d.default_layer().unwrap(); + d.insert(Some(layer), 0, n).unwrap(); + // Skip Blank Artboards keeps the artboard, and its page holds the nib's art. + let p = pages(&job(&d, json!({"skipBlank": true})).bytes); + assert_eq!(p.len(), 1, "{what}"); + assert!(p[0].1.iter().any(|(_, paint)| rgb8(paint) == [255, 0, 0]), "{what}: {p:?}"); + // Ignoring artboards, the page holds all the nib's art, 20 × 40 pt. + let pv = preview(&d, &settings(json!({"artboards": "ignore"}))).unwrap(); + let t = pv.sheets[0].trim; + assert!(t[2] - t[0] >= 20.0 && t[3] - t[1] >= 40.0, "{what}: {t:?}"); + } + // A compound path is painted with its own appearance: the brushed stroke left on its path + // paints nothing, and the artboard stays blank. + let mut d = doc(100.0, 100.0, &[]); + let kind = NodeKind::Compound { children: vec![Arc::new(line())], rule: vectorcraft_geom::FillRule::NonZero }; + let mut compound = Node::new(d.alloc_id(), kind); + compound.appearance = Appearance::basic(Paint::None, rgb(1.0, 0.0, 0.0), 1.0).into(); + let layer = d.default_layer().unwrap(); + d.insert(Some(layer), 0, compound).unwrap(); + assert!(preview(&d, &settings(json!({"skipBlank": true}))).is_err()); + // A brushed stroke without a paint draws no brush art: the artboard stays blank. + let mut d = doc(100.0, 100.0, &[]); + let mut unpainted = line(); + unpainted.id = d.alloc_id(); + unpainted.appearance.stroke_mut().unwrap().paint = Paint::None; + d.insert(Some(layer), 0, unpainted).unwrap(); + assert!(preview(&d, &settings(json!({"skipBlank": true}))).is_err()); +} + +#[test] +fn symbol_art_effects_print_where_they_draw() { + // A red square and the symbol's blue square, each moved 100 pt right by a Transform effect, + // print at the same distance from the page's left edge. + let moved = |mut n: Node| { + n.appearance.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params: json!({"moveH": 100.0}), visible: true }); + n + }; + let mut d = doc(200.0, 100.0, &[]); + let (layer, id) = (d.default_layer().unwrap(), d.alloc_id()); + let red = Node::path(id, shapes::rectangle(Rect::new(10.0, 10.0, 20.0, 20.0)), Appearance::basic(rgb(1.0, 0.0, 0.0), Paint::None, 0.0)); + d.insert(Some(layer), 0, moved(red)).unwrap(); + let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(10.0, 40.0, 20.0, 50.0)), Appearance::basic(rgb(0.0, 0.0, 1.0), Paint::None, 0.0)); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Moved".into(), art: Arc::new(moved(art)) }); + let id = d.alloc_id(); + d.insert(Some(layer), 0, Node::new(id, NodeKind::SymbolInstance { symbol: "Moved".into(), xf: vectorcraft_geom::Affine::IDENTITY })).unwrap(); + let p = pages(&job(&d, json!({})).bytes); + assert_eq!(p.len(), 1); + let left = |c: [u8; 3]| p[0].1.iter().find(|(_, paint)| rgb8(paint) == c).map(|(r, _)| r.x0); + let (red, blue) = (left([255, 0, 0]), left([0, 0, 255])); + assert!(red.zip(blue).is_some_and(|(r, b)| (r - b).abs() < 0.05), "{p:?}"); +} + #[test] fn copies_collate_and_reverse() { let mut d = @@ -536,6 +615,70 @@ fn cmyk_and_a_spot_separate_into_five_plates() { assert_eq!(inks(&p[2]), [0.0, 40.0], "the gold's yellow"); } +/// A 100 pt CMYK document with spot swatch `Gold` and a square filled with gradient `g`. +fn gold_gradient_doc(g: GradientPaint) -> Document { + let mut d = doc(100.0, 100.0, &[(Rect::new(0.0, 0.0, 50.0, 50.0), Paint::Gradient(Box::new(g)))]); + d.color_mode = vectorcraft_doc::ColorMode::Cmyk; + d.swatches.push(Swatch { name: "Gold".into(), paint: Paint::solid(Color::cmyk(0.0, 0.2, 0.8, 0.1)), global: true, spot: true }); + d +} + +/// The grey of each plate of a separation of `d` (job options `v`), in percent: of the first +/// gradient stop, and of the first freeform point when there is one. No plate keeps a link or +/// process plates. +fn gradient_plates(d: &Document, v: serde_json::Value) -> Vec<(f32, Option)> { + let opts = PrintOptions { settings: settings(v), ..Default::default() }; + let gray = |c: &Color| match c { + Color::Gray { k } => (k * 100.0).round(), + c => panic!("{c:?}"), + }; + let plan = plan(d, &opts).unwrap(); + plan.plates + .iter() + .map(|p| { + let mut found = vec![]; + p.walk(|n| { + if let Some(Paint::Gradient(g)) = n.appearance.fill().map(|f| &f.paint) { + let s = &g.gradient.stops[0]; + assert_eq!((s.swatch.as_deref(), s.tint, s.plates), (None, 1.0, None), "the stop is unlinked"); + found.push((gray(&s.color), g.freeform.as_ref().and_then(|f| f.points.first()).map(|q| gray(&q.color)))); + } + }); + assert_eq!(found.len(), 1); + found[0] + }) + .collect() +} + +#[test] +fn a_spot_gradient_stop_prints_its_process_plates() { + let mut mixed = GradientStop::new(0.0, Color::cmyk(0.25, 0.1, 0.8, 0.05)); + (mixed.swatch, mixed.tint, mixed.plates) = (Some("Gold".into()), 0.5, Some([0.25, 0.0, 0.4, 0.0])); + let g = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![mixed, GradientStop::new(1.0, Color::cmyk(0.0, 0.0, 0.0, 0.0))])); + let d = gold_gradient_doc(g); + let first = |v| gradient_plates(&d, v).into_iter().map(|(s, _)| s).collect::>(); + assert_eq!(first(json!({"output": {"mode": "separations"}})), [25.0, 0.0, 40.0, 0.0, 50.0], "Cyan, Magenta, Yellow, Black, Gold"); + // Spots as process: the plates layered with the gold tint's process inks (0, 10, 40, 5). + assert_eq!(first(json!({"output": {"mode": "separations", "spotsToProcess": true}})), [25.0, 10.0, 64.0, 5.0]); +} + +#[test] +fn a_freeform_gradients_points_separate_into_plates() { + let mut g = GradientPaint::new(Gradient::new(GradientKind::Freeform, vec![GradientStop::new(0.0, Color::cmyk(0.0, 0.0, 0.0, 1.0))])); + let point = FreeformPoint::new(vectorcraft_geom::Point::new(25.0, 25.0), Color::cmyk(0.0, 0.6, 0.0, 0.0)); + g.freeform = Some(Freeform { points: vec![point], ..Default::default() }); + let d = gold_gradient_doc(g); + let set = json!({"output": {"mode": "separations"}}); + let points = gradient_plates(&d, set.clone()).into_iter().map(|(_, p)| p).collect::>(); + assert_eq!(points, [Some(0.0), Some(60.0), Some(0.0), Some(0.0), Some(0.0)], "the point's magenta, on its plate only"); + // Each plate draws the square in the grey of the point's ink on it. + let plan = plan(&d, &PrintOptions { settings: settings(set), ..Default::default() }).unwrap(); + let drawn: Vec = plan.plates.iter().map(|p| render_region(p, Rect::new(0.0, 0.0, 50.0, 50.0), 1.0).over_white(25, 25)[0]).collect(); + for (plate, (v, ink)) in drawn.iter().zip([0.0, 0.6, 0.0, 0.0, 0.0]).enumerate() { + assert!((f32::from(*v) - 255.0 * (1.0 - ink)).abs() <= 3.0, "plate {plate}: {drawn:?}"); + } +} + #[test] fn trim_marks_surround_the_artboard_on_the_paper() { let d = doc(200.0, 100.0, &[(Rect::new(0.0, 0.0, 200.0, 100.0), rgb(1.0, 0.0, 0.0))]); diff --git a/crates/render/src/brush_fx.rs b/crates/render/src/brush_fx.rs index 3c6ea922d4..5844a2ef7f 100644 --- a/crates/render/src/brush_fx.rs +++ b/crates/render/src/brush_fx.rs @@ -155,19 +155,19 @@ pub(crate) fn path_cull_bounds(symbols: &SymbolBoxes, n: &Node, visual: impl FnO /// How far brush art can paint past `n`'s brushed strokes, or past the brushed strokes in the art /// of symbol instance `n`: `16 × w + 8`, where `w` is the widest stroke (at least 1) of `n` when it -/// has a visible brushed stroke and of the objects in that art that have one +/// has a visible brushed stroke with a paint and of the objects in that art that have one /// ([`SymbolBoxes::brush_width`]) or the pieces live-effect plug-ins paint for them -/// ([`crate::fx::painted_brush_width`]), and 0 when neither has one. +/// ([`crate::fx::painted_brush_width`]), and 0 when neither has one. The room for `n`'s own strokes +/// is [`vectorcraft_brush::reach`], which the exports leave too. pub(crate) fn pad(symbols: &SymbolBoxes, n: &Node) -> f64 { - let own = vectorcraft_brush::has_brush(n) - .then(|| n.appearance.items.iter().filter_map(|i| if let AppearanceItem::Stroke(s) = i { Some(s.width) } else { None }).fold(1.0, f64::max)); + let own = vectorcraft_brush::reach(n); let art = match &n.kind { NodeKind::SymbolInstance { symbol, .. } => { symbols.brush_width(symbol).into_iter().chain(crate::fx::painted_brush_width(symbols, symbol)).reduce(f64::max).map(|w| w.max(1.0)) } _ => None, }; - own.into_iter().chain(art).reduce(f64::max).map_or(0.0, |w| 16.0 * w + 8.0) + art.map_or(own, |w| own.max(16.0 * w + 8.0)) } pub use vectorcraft_brush::instance_art; diff --git a/crates/render/src/encode/png.rs b/crates/render/src/encode/png.rs index 6a62034e10..d393e23fa7 100644 --- a/crates/render/src/encode/png.rs +++ b/crates/render/src/encode/png.rs @@ -28,16 +28,12 @@ const ADAM7: [(u32, u32, u32, u32); 7] = [(0, 0, 8, 8), (4, 0, 8, 8), (0, 4, 4, /// Pixels per metre for a resolution in pixels per inch (the unit `pHYs` stores). pub fn pixels_per_metre(ppi: f64) -> u32 { - (ppi / 0.0254).round().clamp(1.0, u32::MAX as f64) as u32 + vectorcraft_doc::ppi::pixels_per_metre(ppi) } /// A whole `pHYs` chunk (length, type, data, CRC) declaring `x` × `y` pixels per inch. pub fn phys_chunk(x: f64, y: f64) -> Vec { - let [x, y] = [x, y].map(|v| pixels_per_metre(v).to_be_bytes()); - let mut out = Vec::with_capacity(21); - // x, y, unit 1 = metre. - chunk(&mut out, b"pHYs", &[x.as_slice(), y.as_slice(), &[1]].concat()); - out + vectorcraft_doc::ppi::phys_chunk(x, y) } /// Encode straight-alpha RGBA8 pixels (`width`×`height`, row-major) as a PNG file. diff --git a/crates/render/src/fx/bounds.rs b/crates/render/src/fx/bounds.rs index 65ce8a91fd..c79260e1c0 100644 --- a/crates/render/src/fx/bounds.rs +++ b/crates/render/src/fx/bounds.rs @@ -67,6 +67,13 @@ pub(crate) fn visual_bounds(symbols: &SymbolBoxes, n: &Node) -> Option { if let Some(art) = painted_art(symbols, n) { return art.visual_bounds_with(symbols).map(|r| with_raster_reach(symbols, n, r)); } + // Copies that each carry the raster effects listed before their Transform effect reach as far + // as each copy's raster effects paint, and the raster effects after it spread them all. + if effects::outer_effects(n).len() < n.appearance.effects.len() + && let Some(art) = effects::reshape(Some(symbols.document()), n, None) + { + return cull_bounds(symbols, &art); + } let bp = node_bezpath(n)?; let ctx = GeomContext { doc: Some(symbols.document()), ..GeomContext::of(n) }; let (g, carry) = effected_path_carrying(symbols.document(), n, &bp); diff --git a/crates/render/src/fx/entries.rs b/crates/render/src/fx/entries.rs index 7b80677e2c..1d9e21a64e 100644 --- a/crates/render/src/fx/entries.rs +++ b/crates/render/src/fx/entries.rs @@ -14,6 +14,9 @@ pub(super) struct Content<'a> { pub(super) cache: Option, /// Document-space bounds of the painted content. pub(super) reach: Rect, + /// `reach` before the effects of an earlier part of a split stack spread it: the bounds Radial + /// Blur's Blur Center is placed in, so the center stays put wherever the stack splits. + pub(super) object: Rect, /// Its silhouette: Feather and Inner Glow clip to it (without one, Feather only blurs and /// Inner Glow is skipped). pub(super) outline: Option<(&'a BezPath, FillRule)>, diff --git a/crates/render/src/fx/pixels.rs b/crates/render/src/fx/pixels.rs index cdf817f1e4..f4a441f3cb 100644 --- a/crates/render/src/fx/pixels.rs +++ b/crates/render/src/fx/pixels.rs @@ -241,7 +241,10 @@ impl Renderer { outline: feather_outline(&chain, content, content.reach.origin()), }); let (center, extent) = (content.reach.center(), 0.5 * content.reach.width().hypot(content.reach.height())); - let space = effects::PixelSpace { to_doc, px, center, channels, line, extent }; + // The Blur Center lies in the object's bounds; a split stack's later part spreads `reach` + // evenly, so the centre stays the same. + let size = content.object.size().to_vec2(); + let space = effects::PixelSpace { to_doc, px, center, size, channels, line, extent }; let (wz, hz) = (wu as usize, hu as usize); // What the content covers after the effects run so far: Rasterize makes its image over it. let mut bounds = content.bounds.unwrap_or(content.reach); @@ -708,6 +711,7 @@ impl Renderer { owner: None, cache: Some((j + 1) << 8), reach: ib.inflate(outset, outset), + object: ib.inflate(outset, outset), outline: Some((&outline, orule)), bounds, kept: None, diff --git a/crates/render/src/fx/renderer.rs b/crates/render/src/fx/renderer.rs index 190d433973..d1a8429fd6 100644 --- a/crates/render/src/fx/renderer.rs +++ b/crates/render/src/fx/renderer.rs @@ -389,7 +389,7 @@ impl Renderer { let bounds = rasterize_bounds(f.symbols, n, &rfx); // Under Rasterize the content reaches as far as its fills' and strokes' raster effects paint. let reach = bounds.map_or(reach, |b| reach.union(b)); - let content = Content { node: n, owner: None, cache: Some(0), reach, outline: Some((g, rule)), bounds, kept: None }; + let content = Content { node: n, owner: None, cache: Some(0), reach, object: reach, outline: Some((g, rule)), bounds, kept: None }; let mut items = items; self.raster_fx(ctx, f, &content, &rfx, &mut |r, c, fr| r.paint_items(c, fr, paints, g, rule, &gctx, items.as_deref_mut())); ctx.set_transform(Affine::IDENTITY); @@ -423,11 +423,12 @@ impl Renderer { let outer = self.made_again; self.made_again = outer || !kept; // With Crop Marks, the object inside the art paints its own raster effects; Vector - // Halftone samples them with the object. + // Halftone samples them with the object. The copies of a Transform effect that carry the + // raster effects listed before it paint those themselves. let rfx = if effects::has_crop_marks(a) || effects::addons::halftone::has_halftone(a) { vec![] } else { - effects::raster_effects(&a.appearance.effects) + effects::raster_effects(effects::outer_effects(a)) }; match cull_bounds(f.symbols, &art) { Some(reach) if !f.opts.outline && !rfx.is_empty() => { @@ -446,7 +447,16 @@ impl Renderer { None => rasterize_bounds(f.symbols, a, &rfx), }; let reach = bounds.map_or(reach, |b| reach.union(b)); - let content = Content { node: a, owner: Some(a), cache, reach, outline: region.as_deref().map(|r| (&r.0, r.1)), bounds, kept: None }; + let content = Content { + node: a, + owner: Some(a), + cache, + reach, + object: reach, + outline: region.as_deref().map(|r| (&r.0, r.1)), + bounds, + kept: None, + }; self.raster_fx(ctx, f, &content, &rfx, &mut |r, c, fr| r.draw_fx_art(c, fr, a, &art)); ctx.set_transform(Affine::IDENTITY); } @@ -770,6 +780,7 @@ impl Renderer { owner: content.owner, cache: None, reach: content.reach, + object: content.object, outline: content.outline, bounds: content.bounds, kept: kept.as_ref(), @@ -782,6 +793,7 @@ impl Renderer { owner: content.owner, cache: content.cache.filter(|_| !over), reach, + object: content.object, outline, bounds: spread, kept: content.kept.filter(|_| split == at), diff --git a/crates/render/src/ink.rs b/crates/render/src/ink.rs index 2d67db2073..7bcc117a23 100644 --- a/crates/render/src/ink.rs +++ b/crates/render/src/ink.rs @@ -239,19 +239,29 @@ fn inks(c: &Color) -> [f32; 4] { let key = c.key(); let cms = cms::active(); SEPARATED.with(|s| { - let (owner, seen) = &mut *s.borrow_mut(); + let kept = &mut *s.borrow_mut(); + let i = match kept.iter().position(|(owner, _)| Arc::ptr_eq(owner, &cms)) { + Some(i) => i, + None => { + if kept.len() >= KEPT_TABLES { + kept.remove(0); + } + kept.push((cms.clone(), HashMap::new())); + kept.len() - 1 + } + }; + let seen = &mut kept[i].1; // Large enough for the many colours of gradient meshes and blends, which otherwise cleared // it over and over and separated every colour through the profile again. - if !owner.as_ref().is_some_and(|o| Arc::ptr_eq(o, &cms)) || seen.len() >= 1 << 16 { + if seen.len() >= 1 << 16 { seen.clear(); - *owner = Some(cms.clone()); } *seen.entry(key).or_insert_with(|| cms.to_cmyk(c, cms.settings().intent)) }) } -/// Separated colours, for the colour settings they were separated with. -type Separated = (Option>, HashMap<[u32; 5], [f32; 4]>); +/// Separated colours, for each of the colour settings they were separated with, the newest last. +type Separated = Vec<(Arc, HashMap<[u32; 5], [f32; 4]>)>; thread_local! { static SEPARATED: RefCell = RefCell::default(); @@ -276,31 +286,37 @@ impl InkLut { } } -/// A table built for the colour settings it was built with, and its generation (see [`cached`]). -type Cached = Mutex, Arc, u64)>>; +/// Tables built for the colour settings they were built with, and their generations, the newest +/// last (see [`cached`]). +type Cached = Mutex, Arc, u64)>>; + +/// How many tables each [`Cached`] keeps: documents drawn side by side through their own profiles +/// don't make them again and again. +const KEPT_TABLES: usize = 4; /// The last table generation handed out: images made with a table are cached under its /// generation (see [`crate::images`]), and none is ever reused. static GENERATION: AtomicU64 = AtomicU64::new(0); -static DISPLAY: Cached = Mutex::new(None); +static DISPLAY: Cached = Mutex::new(Vec::new()); /// Screen colours → [`Ink::Cmy`] and [`Ink::K`] values (placed images). -static SEPARATE: Cached<[ProofLut; 2]> = Mutex::new(None); +static SEPARATE: Cached<[ProofLut; 2]> = Mutex::new(Vec::new()); -/// The table in `slot` for the active colour settings, built by `build` when they changed, and -/// its generation. +/// The table in `slot` for the active colour settings, built by `build` when none is kept for +/// them, and its generation. fn cached(slot: &Cached, build: impl FnOnce(&Cms) -> T) -> (Arc, u64) { let cms = cms::active(); let mut s = slot.lock().unwrap_or_else(|e| e.into_inner()); - match &*s { - Some((owner, t, g)) if Arc::ptr_eq(owner, &cms) => (t.clone(), *g), - _ => { - let t = Arc::new(build(&cms)); - let g = GENERATION.fetch_add(1, Ordering::Relaxed) + 1; - *s = Some((cms, t.clone(), g)); - (t, g) - } + if let Some((_, t, g)) = s.iter().find(|(owner, _, _)| Arc::ptr_eq(owner, &cms)) { + return (t.clone(), *g); } + let t = Arc::new(build(&cms)); + let g = GENERATION.fetch_add(1, Ordering::Relaxed) + 1; + if s.len() >= KEPT_TABLES { + s.remove(0); + } + s.push((cms, t.clone(), g)); + (t, g) } /// [`compose`] puts at least this many pixels in each band but the last. @@ -585,6 +601,18 @@ mod tests { assert_eq!(pm.data()[0].r, 204, "source pixels remain unchanged"); } + #[test] + fn tables_of_two_color_settings_are_kept_side_by_side() { + // Two documents drawn in turn through their own settings each keep their tables. + let settings = || Arc::new(Cms::new(&cms::ColorSettings::default()).unwrap()); + let (a, b) = (settings(), settings()); + let tables = |c: &Arc| cms::with_active(c.clone(), || (display_lut().1, separation().1)); + let (first_a, first_b) = (tables(&a), tables(&b)); + assert_ne!(first_a, first_b, "each settings get their own tables"); + assert_eq!(tables(&a), first_a, "the first settings' tables are not made again"); + assert_eq!(tables(&b), first_b, "the second settings' tables are not made again"); + } + #[test] fn the_ink_table_matches_the_profile() { let cms = cms::active(); diff --git a/crates/render/src/paint.rs b/crates/render/src/paint.rs index 1d39ece10c..c130fbe346 100644 --- a/crates/render/src/paint.rs +++ b/crates/render/src/paint.rs @@ -1,6 +1,7 @@ //! Paint conversion (solid, gradients, patterns) and image decoding. use vectorcraft_color::{GradientKind, Paint}; +use vectorcraft_doc::resample::{Resample, resized}; use vectorcraft_geom::{Rect, Vec2}; use vello_cpu::RenderContext; use vello_cpu::peniko::{self, ColorStop}; @@ -446,7 +447,7 @@ fn fit_pixmap(img: image::DynamicImage) -> image::DynamicImage { } let s = max as f64 / w.max(h) as f64; let (nw, nh) = (((w as f64 * s).round() as u32).clamp(1, max), ((h as f64 * s).round() as u32).clamp(1, max)); - img.resize_exact(nw, nh, image::imageops::FilterType::Triangle) + resized(img, nw, nh, Resample::Filter(image::imageops::FilterType::Triangle)) } /// [`decode_pixmap_or_why`]'s pixels. @@ -504,7 +505,7 @@ pub fn decode_pixmap_fit(bytes: &[u8], w: u16, h: u16) -> Option w as u32 || img.height() > h as u32 { - img.resize_exact(w as u32, h as u32, image::imageops::FilterType::Triangle) + resized(img, w as u32, h as u32, Resample::Filter(image::imageops::FilterType::Triangle)) } else { img }; @@ -587,4 +588,35 @@ mod tests { assert_eq!(room_for(MAX_DECODE_ALLOC, MAX_DECODE_ALLOC + 1), Err(Undecoded::NoRoom)); assert_eq!(room_for(MAX_DECODE_ALLOC, MAX_DECODE_ALLOC), Ok(())); } + + /// Opaque red beside clear black, every other column of a `w` × 1 image. + fn striped(w: u32) -> image::RgbaImage { + image::RgbaImage::from_fn(w, 1, |x, _| if x % 2 == 0 { image::Rgba([200, 30, 30, 255]) } else { image::Rgba([0, 0, 0, 0]) }) + } + + /// Does each pixel of `pm` hold red at its own coverage (premultiplied, within a step)? + fn red_at_its_coverage(pm: &vello_cpu::Pixmap) -> bool { + let m = |c: u8, a: u8| ((u16::from(c) * u16::from(a) + 127) / 255) as u8; + pm.data().iter().all(|p| p.r.abs_diff(m(200, p.a)) <= 1 && p.g.abs_diff(m(30, p.a)) <= 1 && p.b.abs_diff(m(30, p.a)) <= 1) + } + + /// A placed image drawn smaller keeps the color of its opaque pixels at its cut-out edges: the + /// clear pixels beside them do not darken them. + #[test] + fn an_image_drawn_smaller_keeps_its_color_beside_clear_pixels() { + let mut png = Vec::new(); + striped(8).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let pm = decode_pixmap_fit(&png, 2, 1).unwrap(); + assert_eq!((pm.width(), pm.height()), (2, 1)); + assert!(pm.data().iter().all(|p| p.a > 0)); + assert!(red_at_its_coverage(&pm), "{:?}", pm.data()); + } + + /// An image wider than a pixmap may be is shrunk to fit with its colors weighted by alpha the same way. + #[test] + fn an_image_shrunk_to_fit_a_pixmap_keeps_its_color_beside_clear_pixels() { + let pm = decoded_pixmap(image::DynamicImage::ImageRgba8(striped(u32::from(u16::MAX) + 4465))).unwrap(); + assert_eq!(pm.width(), u16::MAX); + assert!(red_at_its_coverage(&pm)); + } } diff --git a/crates/render/src/placed_document.rs b/crates/render/src/placed_document.rs index 6daf192fc4..7f9453fda5 100644 --- a/crates/render/src/placed_document.rs +++ b/crates/render/src/placed_document.rs @@ -425,8 +425,9 @@ impl Renderer { if !k.is_finite() || k <= 1e-12 { return; } - // The art in its own coordinates, with its own resources (its composite fonts included). - let _lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&e.doc.composite_fonts); + // The art in its own coordinates, with its own resources (its composite fonts included, and + // none of the host document's). + let _lent = vectorcraft_text::FontDb::global().lend_document_composite_fonts(&e.doc.composite_fonts); let symbols = e.doc.symbol_boxes().quick(); let visible = m.inverse().transform_rect_bbox(f.visible); let inner = Frame { doc: &e.doc, symbols: &symbols, view: f.view * m, visible, px: f.px / k, output: f.output * m, ..*f }; diff --git a/crates/render/src/proof.rs b/crates/render/src/proof.rs index a6736b022d..284ad8ce5d 100644 --- a/crates/render/src/proof.rs +++ b/crates/render/src/proof.rs @@ -4,7 +4,8 @@ //! space (CMYK press or RGB/colour-blindness simulation) → display, through a cached 17³ LUT. //! * **Separations Preview** recolours the *document* before rendering: each paint colour is split //! into process inks (colour-managed), or a spot ink at the colour's tint when it's linked to a -//! spot swatch (solid colours and gradient stops alike). With one plate visible the plate +//! spot swatch (solid colours and gradient stops alike), with the process plates a gradient stop +//! prints beside its spot ink ([`vectorcraft_color::GradientStop::plates`]). With one plate visible the plate //! renders as greyscale ink coverage (black = 100%); with several, the visible inks are //! composited through the proof profile, spots multiplied on top. Colours linked to the //! Registration swatch print their tint on every plate, spot plates included. @@ -29,6 +30,7 @@ use vectorcraft_color::cms::{self, Cms, CmykLut, PROCESS_PLATES, ProofLut, lab}; pub use vectorcraft_color::cms::{Intent, ProofSetup, ProofTarget}; use vectorcraft_color::{Color, Swatch, SwatchGroup}; pub use vectorcraft_doc::inks::{Inks, Link, Plate, inks, map_document_colors, map_node_colors, plates, spot_color}; +use vectorcraft_doc::inks::{StopPlates, map_node_inks, stop_inks}; use vectorcraft_doc::overprint::darken_overprints; use vectorcraft_doc::{Document, ImageBlob, Node, NodeId, Shared}; use vello_cpu::Pixmap; @@ -59,8 +61,8 @@ fn plate_rgb(c: &Cms, proof: &ProofSetup, visible: &[String], ink: &Inks) -> [f3 c.proof_cmyk_to_srgb(cmyk, proof) } -fn plate_color(doc: &Document, c: &Cms, proof: &ProofSetup, visible: &[String], color: &Color, link: Link) -> Color { - let ink = inks(doc, c, color, link, proof.intent); +fn plate_color(doc: &Document, c: &Cms, proof: &ProofSetup, visible: &[String], color: &Color, link: Link, plates: StopPlates) -> Color { + let ink = stop_inks(doc, c, color, link, plates, proof.intent); let mut rgb = plate_rgb(c, proof, visible, &ink); // Over several plates the visible spot inks print on top. for name in visible.iter().filter(|v| visible.len() != 1 && !PROCESS_PLATES.contains(&v.as_str())) { @@ -355,7 +357,7 @@ impl How<'_> { fn apply(&self, a: &mut Arc) { darken_overprints(a, self.discard_white); if let Some((c, proof, visible)) = self.plates { - map_node_colors(Arc::make_mut(a), &mut |col, sw| plate_color(self.doc, c, proof, visible, col, sw)); + map_node_inks(Arc::make_mut(a), &mut |col, sw, plates| plate_color(self.doc, c, proof, visible, col, sw, plates)); } } } diff --git a/crates/render/src/tests/colorize.rs b/crates/render/src/tests/colorize.rs index 721707502d..8a8891c7da 100644 --- a/crates/render/src/tests/colorize.rs +++ b/crates/render/src/tests/colorize.rs @@ -289,6 +289,35 @@ fn separations_preview_keeps_a_reduced_dcs_plates_coverage() { assert!(p[..3].iter().all(|v| (100..=160).contains(v)), "half the ink, got {p:?}"); } +/// A gradient stop linked to a spot ink that prints process plates with it shows them on those +/// plates, and its tint on the spot plate. +#[test] +fn separations_preview_shows_a_spot_gradient_stops_process_plates() { + use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let mut d = Document::new_with_mode(20.0, 20.0, vectorcraft_doc::ColorMode::Cmyk); + d.swatches.push(vectorcraft_color::Swatch { + name: "Gold".into(), + paint: Paint::solid(Color::cmyk(0.0, 0.2, 0.8, 0.1)), + global: true, + spot: true, + }); + let stop = |offset| { + let mut s = GradientStop::new(offset, Color::cmyk(0.25, 0.1, 0.8, 0.05)); + (s.swatch, s.tint, s.plates) = (Some("Gold".into()), 0.5, Some([0.25, 0.0, 0.4, 0.0])); + s + }; + let g = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, vec![stop(0.0), stop(1.0)])))); + let (layer, id) = (d.layers[0].id, d.alloc_id()); + let square = Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::basic(g, Paint::None, 0.0)); + d.insert(Some(layer), 0, square).unwrap(); + let gray = |plate: &str| Renderer::new().render(&d, 20, 20, Affine::IDENTITY, &separations(&[plate])).pixel(10, 10)[0]; + let near = |v: u8, ink: f32| (f32::from(v) - 255.0 * (1.0 - ink)).abs() <= 3.0; + for (plate, ink) in [("Cyan", 0.25), ("Magenta", 0.0), ("Yellow", 0.4), ("Black", 0.0), ("Gold", 0.5)] { + let v = gray(plate); + assert!(near(v, ink), "{plate}: {ink} of the ink, got {v}"); + } +} + /// Separations Preview showing `plates`, as the canvas draws it. fn separations(plates: &[&str]) -> RenderOptions { let proof = proof::ProofSetup { separations: Some(plates.iter().map(|p| p.to_string()).collect()), ..Default::default() }; diff --git a/crates/render/src/tests/fontchange.rs b/crates/render/src/tests/fontchange.rs index 15389cd805..27e1e7e1e9 100644 --- a/crates/render/src/tests/fontchange.rs +++ b/crates/render/src/tests/fontchange.rs @@ -209,7 +209,7 @@ fn a_documents_own_composite_font_draws_without_being_registered() { } /// A placed document draws its type in its own definition of a composite font that the document -/// placing it defines differently. +/// placing it defines differently, and as missing in one only the document placing it defines. #[test] fn a_placed_document_draws_its_own_definition_of_a_name_the_page_defines() { use vectorcraft_doc::{CompositeFont, CompositePart, CompositeParts, ImageBlob, LinkInfo, PlacedDocument}; @@ -260,6 +260,55 @@ fn a_placed_document_draws_its_own_definition_of_a_name_the_page_defines() { assert!(own == page(&plain, plain_id, "fontchange-placed-twice-plain", vec![]), "drawn in the placed document's definition"); assert!(own != page(&inter, inter_id, "fontchange-placed-twice-inter", vec![]), "not in the page's"); assert!(vectorcraft_text::FontDb::global().composite_font(NAME).is_none()); + // A placed document that defines no composite font draws type naming the page's as missing. + let (undefined, undefined_id) = typed(NAME); + let (missing, missing_id) = typed("CF Placed Nowhere"); + let borrowed = page(&undefined, undefined_id, "fontchange-placed-undefined", vec![definition("Inter")]); + assert!(borrowed == page(&missing, missing_id, "fontchange-placed-missing", vec![]), "drawn as in a missing font"); + assert!(borrowed != page(&inter, inter_id, "fontchange-placed-undefined-inter", vec![]), "not in the page's definition"); +} + +/// A document that defines no composite font, drawn while another document's composite font of +/// the name its type is set in is registered (that document in front), draws that type as in a +/// missing font: in a render, an ink render, a thumbnail and a node render. +#[test] +fn a_document_draws_type_in_another_documents_composite_font_as_missing() { + use vectorcraft_doc::{CompositeFont, CompositePart, CompositeParts}; + let _adding = adding_fonts(); + const NAME: &str = "CF Front Only"; + let db = vectorcraft_text::FontDb::global(); + let typed = |family: &str| { + let mut d = Document::new(300.0, 150.0); + let style = CharStyle { size: 60.0, font_family: family.into(), ..Default::default() }; + let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(TextObject::point(Point::new(10.0, 100.0), "Hamburg", style)))); + let l = d.layers[0].id; + let id = d.insert(Some(l), 0, n).unwrap(); + (d, id) + }; + let (back, id) = typed(NAME); + let (missing, missing_id) = typed("CF Front Nowhere"); + let (plain, plain_id) = typed("JetBrains Mono"); + let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let region = Rect::new(0.0, 0.0, 300.0, 150.0); + let draw = |d: &Document, id: NodeId| { + let n = d.node(id).unwrap().clone(); + ( + Renderer::new().render(d, 300, 150, Affine::IDENTITY, &opts).pixels, + Renderer::new().render_region_inks(d, region, 1.0, &opts), + Renderer::new().render_thumbnail(d, id, 64).map(|r| r.pixels), + Renderer::new().render_node(d, &std::sync::Arc::new(n), 300, 150, Affine::IDENTITY).map(|r| r.pixels), + ) + }; + let mut parts = CompositeParts::all(CompositePart::new("Source Sans 3", "Regular")); + parts.roman = CompositePart::new("JetBrains Mono", "Regular"); + db.set_composite_font(&CompositeFont { name: NAME.into(), parts }); + let (drawn, as_missing, in_front) = (draw(&back, id), draw(&missing, missing_id), draw(&plain, plain_id)); + db.remove_composite_font(NAME); + assert!(drawn.0 != in_front.0, "not in the front document's definition"); + assert!(drawn.0 == as_missing.0, "rendered"); + assert!(drawn.1 == as_missing.1, "rendered as ink amounts"); + assert!(drawn.2 == as_missing.2, "thumbnail"); + assert!(drawn.3 == as_missing.3, "node"); } /// Type at 80% opacity, in Multiply and with a drop shadow redraws in a font that becomes diff --git a/crates/render/src/tests/objectfx.rs b/crates/render/src/tests/objectfx.rs index c359f65219..f93124e1b9 100644 --- a/crates/render/src/tests/objectfx.rs +++ b/crates/render/src/tests/objectfx.rs @@ -1219,3 +1219,26 @@ fn a_shadow_before_a_skipped_transform_reaches_as_far_as_it_is_drawn() { assert!(within(b), "{what}: painted {b:?} for art {art:?}"); } } + +/// Each copy of a Transform effect draws the drop shadow listed before the effect under itself, +/// scaled with it: the red square (10..30) and its copy scaled 200 % and moved 60 pt down (0..40 +/// across, 60..100 down) each have a green shadow to their right, 20 pt for the square and 40 pt +/// for the copy. The bounds reach as far as the copy's shadow. +#[test] +fn each_copy_of_a_transform_effect_draws_its_own_shadow() { + let shadow = fx("stylize.dropShadow", json!({"x": 20, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"})); + let copies = fx("distort.transform", json!({"scaleH": 200, "scaleV": 200, "moveV": 60, "copies": 1})); + let red = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); + let mut n = Node::path(NodeId(0), shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0)), red); + n.appearance.effects = vec![shadow, copies]; + let d = doc_with(Document::new(100.0, 100.0), n); + let img = render(&d); + assert_eq!(img.pixel(20, 20), [255, 0, 0, 255], "the square"); + assert_eq!(img.pixel(45, 20), [0, 255, 0, 255], "the square's shadow"); + assert_eq!(img.pixel(20, 80), [255, 0, 0, 255], "the copy"); + assert_eq!(img.pixel(70, 80), [0, 255, 0, 255], "the copy's shadow, 40 pt to its right"); + assert_eq!(img.pixel(85, 80), [255, 255, 255, 255], "past the copy's shadow"); + let n = &d.layers[0].children().unwrap()[0]; + let b = crate::fx::visual_bounds(&d.symbol_boxes(), n).unwrap(); + assert!(b.x1 >= 80.0 - 1e-9, "{b:?}"); +} diff --git a/crates/svg/src/css.rs b/crates/svg/src/css.rs index f7e067aa30..5b0b921e32 100644 --- a/crates/svg/src/css.rs +++ b/crates/svg/src/css.rs @@ -194,6 +194,10 @@ pub(crate) fn type_props(st: &CharStyle, len: &dyn Fn(f64) -> String) -> Props { if st.proportional_metrics { v.push("\"palt\" 1".into()); } + // The East Asian glyph form: its one feature. + if let Some(tag) = st.glyph_form.feature().and_then(|t| std::str::from_utf8(t).ok()) { + v.push(format!("\"{tag}\" 1")); + } if !v.is_empty() { p.push(("font-feature-settings", v.join(", "))); } diff --git a/crates/svg/src/export/nodes.rs b/crates/svg/src/export/nodes.rs index 8716af7367..ea1d5ab95b 100644 --- a/crates/svg/src/export/nodes.rs +++ b/crates/svg/src/export/nodes.rs @@ -431,11 +431,75 @@ impl Writer<'_> { self.def(1, ""); self.line(&format!("")); self.depth += 1; + self.spanning_rect(&bare, ®ion); self.node_body(&bare); self.depth -= 1; self.line(""); } + /// Some readers draw a masked group only inside the bounding box of its shapes, which leaves + /// out a drop shadow, blur, glow or feather that paints past them. When `n`, written inside a + /// ``, holds one ([`Self::holds_raster`]), a hidden, unpainted rectangle over the + /// mask's `region` makes that box cover what it paints. + fn spanning_rect(&mut self, n: &Node, region: &str) { + if self.holds_raster(n) { + self.line(&format!("")); + } + } + + /// Do `n`, its fills and strokes, its members at any depth, its symbols' art or the art its + /// live objects are written as have a visible raster effect (shadow, glow, blur, feather)? + /// Objects that aren't written (hidden ones, unless the options keep them) are skipped, and so + /// are fills and strokes that [`Self::shape`] doesn't write (hidden, unpainted or zero-width). + /// An instance with overrides is looked at in the art it is written as + /// ([`vectorcraft_brush::instance_art`]). The walk keeps its own stack, and looks at each + /// symbol's art once, and at each instance's overridden art once. + fn holds_raster(&self, n: &Node) -> bool { + let mut stack: Vec> = vec![]; + let mut symbols: std::collections::HashSet<(String, Option)> = std::collections::HashSet::new(); + let paints = |i: &AppearanceItem| match i { + AppearanceItem::Fill(f) => f.visible && !f.paint.is_none(), + AppearanceItem::Stroke(s) => s.visible && !s.paint.is_none() && s.width > 0.0, + }; + // Whether `n` itself has one; else its members, symbol art or expanded art go on the stack. + let mut visit = |n: &Node, stack: &mut Vec>| { + if !(n.visible || self.opts.hidden_layers) { + return false; + } + if has_raster(&n.appearance.effects) || n.appearance.items.iter().any(|i| paints(i) && has_raster(i.effects())) { + return true; + } + // A live object is written as its expanded art ([`Self::node_body`]), which holds no + // live objects. + if vectorcraft_doc::live::is_live(n) { + let g = vectorcraft_effects::expand_live_deep(Some(self.doc), n); + if !vectorcraft_doc::live::is_live(&g) { + stack.push(std::sync::Arc::new(g)); + return false; + } + } + if let NodeKind::SymbolInstance { symbol, .. } = &n.kind { + let custom = !n.extras().symbol_overrides.is_empty(); + if symbols.insert((symbol.clone(), custom.then_some(n.id))) + && let Some(s) = self.doc.symbols.iter().find(|s| s.name == *symbol) + { + stack.push(if custom { std::sync::Arc::new(vectorcraft_brush::instance_art(&s.art, n)) } else { s.art.clone() }); + } + } + stack.extend(n.children().into_iter().flatten().cloned()); + false + }; + if visit(n, &mut stack) { + return true; + } + while let Some(c) = stack.pop() { + if visit(&c, &mut stack) { + return true; + } + } + false + } + /// What `write` writes to the body, taken out of it (written at `depth`, for ``). fn detached(&mut self, depth: usize, write: impl FnOnce(&mut Self)) -> String { let (body, saved) = (std::mem::take(&mut self.body), self.depth); @@ -664,7 +728,7 @@ impl Writer<'_> { } } self.symbol_nodes = after; - for (above, (_, body)) in above.iter().zip(written) { + for ((c, above), (_, body)) in elements.iter().zip(&above).zip(written) { if above.is_empty() { self.body.push_str(&body); continue; @@ -672,6 +736,11 @@ impl Writer<'_> { let ids: Vec<&str> = above.iter().filter_map(|&j| shapes[j].as_deref()).collect(); let mid = self.knockout_mask(&ids, ®ion); self.line(&format!("")); + // An element that paints past its shapes starts its mask group with a spanning + // rectangle (`Self::spanning_rect`). + self.depth += 1; + self.spanning_rect(c, ®ion); + self.depth -= 1; self.body.push_str(&body); self.line(""); } diff --git a/crates/svg/src/import.rs b/crates/svg/src/import.rs index 087512bf90..5267acd279 100644 --- a/crates/svg/src/import.rs +++ b/crates/svg/src/import.rs @@ -43,6 +43,7 @@ pub(super) use prepass::Edits; use prepass::{Extras, labels, prepass}; pub use prepass::{MAX_FOREIGN, MAX_FOREIGN_VALUE}; +mod budget; mod css; mod css_transform; mod depth; @@ -109,6 +110,8 @@ pub(crate) fn svg_filters(svg: &str, room: usize, taken: impl Fn(&str) -> bool) return Err(too_deep()); } let xml = parse(svg)?; + // Before the style cascade of `depth::height`, as `import` measures it. + budget::check(&xml, budget::Cost::LIMITS, depth::MAX_ELEMENT_DEPTH)?; if depth::height(&xml, depth::MAX_ELEMENT_DEPTH).is_none() { return Err(too_deep()); } @@ -136,10 +139,14 @@ pub(crate) fn import_finding( return Err(too_deep()); } let xml = parse(svg)?; + // Before the style cascade of `depth::height` and the prepass, which keeps the declarations of + // each element it reads; measured again below on the text usvg reads when that differs. + let spent = budget::check(&xml, budget::Cost::LIMITS, depth::MAX_ELEMENT_DEPTH)?; let Some(height) = depth::height(&xml, depth::MAX_ELEMENT_DEPTH) else { return Err(too_deep()); }; let (svg, found) = prepass(svg, &scan.markers, &xml, opts)?; + let rewritten = matches!(svg, Cow::Owned(_)); // The prepass's edits are in the text: the XML is read again only when it made any. let xml = match &svg { Cow::Borrowed(_) => xml, @@ -154,7 +161,14 @@ pub(crate) fn import_finding( let mut warnings = found.warnings; let text_xml = found.text_source.as_deref().map(parse).transpose()?; let (src, slots) = text::prepare(svg, &xml, text_xml.as_ref(), units.dpi, &mut warnings); + // Before usvg copies what ``s show and the style values of each copy: the text usvg reads. + let spent = match &src { + Cow::Borrowed(_) if !rewritten => spent, + Cow::Borrowed(_) => budget::check(&xml, budget::Cost::LIMITS, usize::MAX)?, + Cow::Owned(prepared) => budget::check(&parse(prepared)?, budget::Cost::LIMITS, usize::MAX)?, + }; let files = found.files; + files.spent_by_svg(spent); let tree = { let opt = usvg::Options { dpi: units.dpi as f32, @@ -164,6 +178,9 @@ pub(crate) fn import_finding( }; usvg::Tree::from_str(&src, &opt).map_err(|e| SvgError::Parse(e.to_string()))? }; + if let Some(err) = files.refused() { + return Err(err); + } let size = tree.size(); let k = units.k; let mut doc = Document::new(size.width() as f64 * k, size.height() as f64 * k); diff --git a/crates/svg/src/import/budget.rs b/crates/svg/src/import/budget.rs new file mode 100644 index 0000000000..2520a8932a --- /dev/null +++ b/crates/svg/src/import/budget.rs @@ -0,0 +1,746 @@ +//! What usvg makes of an SVG, measured in the XML before usvg runs: how many elements it makes, +//! and how many bytes of style values it copies into them. +//! +//! usvg makes an element of each SVG element, and of each element a `` shows a copy of, by +//! copying what the `` refers to. Each copy gets its own copy of every declaration the style +//! sheets and the `style` attribute give the element, so a long style on an element that ``s +//! copy, again and again in a chain, or that a style sheet rule gives to many elements, takes more +//! memory than the file holds many times over. usvg stops past 1,000,000 elements, but only after +//! it has made them and copied their styles. An SVG past [`MAX_SVG_ELEMENTS`] elements or +//! [`MAX_COPIED_STYLES`] bytes of copied styles is refused here instead. +//! +//! The copies are counted, never made: each element's count is worked out once and added up, so a +//! `` of an element costs one addition, however many elements its copy holds. References +//! follow usvg 0.48.1 (`parser/svgtree/parse.rs`): an id names the first element that has it, an +//! unprefixed `href` wins over `xlink:href`, and a `` of itself, of the `` its own copy +//! starts from, or of an element holding a `` of the element or of the ``, is left out. +//! Any other loop of references makes usvg copy without end, so an SVG with one is refused. usvg +//! looks for those ``s inside an element only in the SVG namespace: in an SVG without one, a +//! `` that leads back to the `` its copy starts from is refused here too, though usvg +//! would leave it out. +//! +//! The style sheets' rules are matched against each element once, as usvg matches them against +//! each copy. usvg tests a selector against an element without keeping what it found, so a +//! selector whose leftmost part matches nothing can test every set of ancestors in turn: the tests +//! usvg makes for each copy are counted, and an SVG past [`MAX_SELECTOR_TESTS`] of them is refused. +//! A look at an attribute counts one test for every 16 attributes of the element it scans, and one +//! for every 16 bytes of the value it compares. Matching stops once the tests pass what is left of +//! the limit. +//! +//! The import's own style cascade (`css::Styles`) keeps the declarations of the rules that match +//! each element, once per element, and reads selectors usvg drops (`:not()`). What it keeps and the +//! tests it makes count toward the same limits, measured before it runs. + +use std::cell::Cell; +use std::collections::{HashMap, HashSet}; + +use usvg::roxmltree; + +use super::{MAX_NODES, SVG_NS, XNode, css}; +use crate::{MAX_ELEMENT_DEPTH, SvgError}; + +/// Most elements usvg may make of an SVG: [`MAX_NODES`], and below the 1,000,000 elements past +/// which usvg stops (its count includes a root of its own). +pub(crate) const MAX_SVG_ELEMENTS: usize = if MAX_NODES < 999_999 { MAX_NODES } else { 999_999 }; + +/// Most bytes of style values usvg may copy into the elements of an SVG and the SVG images it +/// shows, all together: VectorCraft's own limit. +pub(crate) const MAX_COPIED_STYLES: u64 = 64 << 20; + +/// Most tests of a style sheet selector's parts against elements an SVG and the SVG images it +/// shows may take, all together: VectorCraft's own limit. +pub(crate) const MAX_SELECTOR_TESTS: u64 = 50_000_000; + +/// What usvg keeps for each value it copies besides its bytes (the count and length of a shared +/// string). +const COPY: u64 = 16; + +/// The longhands a `font` shorthand resets before setting the ones it gives, and the most bytes of +/// each reset value (`normal`). +const FONT_RESETS: u64 = 12; +const RESET_VALUE: u64 = 6; + +/// The longhands a `font` shorthand sets from its own text. +const FONT_PARTS: u64 = 6; + +const XLINK_NS: &str = "http://www.w3.org/1999/xlink"; + +/// The elements usvg reads (`EId` in usvg's `parser/svgtree/names.rs`); it skips the others with +/// everything inside them. +const ELEMENTS: [&str; 53] = [ + "a", + "circle", + "clipPath", + "defs", + "ellipse", + "feBlend", + "feColorMatrix", + "feComponentTransfer", + "feComposite", + "feConvolveMatrix", + "feDiffuseLighting", + "feDisplacementMap", + "feDistantLight", + "feDropShadow", + "feFlood", + "feFuncA", + "feFuncB", + "feFuncG", + "feFuncR", + "feGaussianBlur", + "feImage", + "feMerge", + "feMergeNode", + "feMorphology", + "feOffset", + "fePointLight", + "feSpecularLighting", + "feSpotLight", + "feTile", + "feTurbulence", + "filter", + "g", + "image", + "line", + "linearGradient", + "marker", + "mask", + "path", + "pattern", + "polygon", + "polyline", + "radialGradient", + "rect", + "stop", + "style", + "svg", + "switch", + "symbol", + "text", + "textPath", + "tref", + "tspan", + "use", +]; + +/// The name of element `n` when usvg reads it: in the SVG namespace or none, and one of +/// [`ELEMENTS`]. +fn svg_name<'a>(n: XNode<'a, '_>) -> Option<&'a str> { + let name = n.tag_name(); + (n.is_element() && matches!(name.namespace(), None | Some(SVG_NS)) && ELEMENTS.contains(&name.name())).then(|| name.name()) +} + +#[cfg(test)] +thread_local! { + /// The selector tests the last measurement on this thread made as usvg matches the style + /// sheets, as far as it got. + static USVG_TESTS: Cell = const { Cell::new(0) }; +} + +/// An element as the style sheets' selectors see it, as usvg matches them. Each look at it counts +/// as tests in `tests`; past `most` it has no parent or sibling and matches nothing, so the +/// matching ends. +struct Element<'a, 'i, 't> { + node: XNode<'a, 'i>, + tests: &'t Cell, + most: u64, +} + +impl<'a, 'i, 't> Element<'a, 'i, 't> { + /// Counts `n` tests: false past `most`. + fn test(&self, n: u64) -> bool { + let tests = self.tests.get().saturating_add(n); + self.tests.set(tests); + #[cfg(test)] + USVG_TESTS.set(tests); + tests <= self.most + } + + fn of(&self, node: Option>) -> Option { + node.filter(|_| self.test(1)).map(|node| Element { node, tests: self.tests, most: self.most }) + } +} + +impl simplecss::Element for Element<'_, '_, '_> { + fn parent_element(&self) -> Option { + self.of(self.node.parent_element()) + } + + fn prev_sibling_element(&self) -> Option { + self.of(self.node.prev_sibling_element()) + } + + fn has_local_name(&self, name: &str) -> bool { + self.test(1) && self.node.tag_name().name() == name + } + + fn attribute_matches(&self, name: &str, operator: simplecss::AttributeOperator<'_>) -> bool { + // The lookup scans the element's attributes, and the match the value. + let value = self.node.attribute(name); + let scanned = css::scan_tests(self.node.attributes().len()).saturating_add(value.map_or(0, |v| css::scan_tests(v.len()))); + self.test(scanned) && value.is_some_and(|value| operator.matches(value)) + } + + fn pseudo_class_matches(&self, class: simplecss::PseudoClass<'_>) -> bool { + self.test(1) && matches!(class, simplecss::PseudoClass::FirstChild) && self.node.prev_sibling_element().is_none() + } +} + +/// The bytes usvg copies for one declaration: three markers for `marker`, the resets and longhands +/// for `font`, its value for any other. Counted for every declaration, the ones usvg then drops (a +/// property it doesn't read, a value an earlier one overrides) too. +fn copied(declaration: &simplecss::Declaration) -> u64 { + let len = declaration.value.len() as u64; + match declaration.name { + "marker" => 3 * (COPY + len), + "font" => (FONT_RESETS + FONT_PARTS) * COPY + FONT_RESETS * RESET_VALUE + len, + _ => COPY + len, + } +} + +/// What usvg makes of an element or an SVG: elements (text nodes included), bytes of copied +/// styles and selector tests. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub(crate) struct Cost { + pub(crate) elements: u64, + pub(crate) bytes: u64, + pub(crate) tests: u64, +} + +impl Cost { + /// The most an SVG and the SVG images it shows may cost together. + pub(crate) const LIMITS: Cost = Cost { elements: MAX_SVG_ELEMENTS as u64, bytes: MAX_COPIED_STYLES, tests: MAX_SELECTOR_TESTS }; + + pub(crate) fn add(self, other: Cost) -> Cost { + Cost { + elements: self.elements.saturating_add(other.elements), + bytes: self.bytes.saturating_add(other.bytes), + tests: self.tests.saturating_add(other.tests), + } + } + + /// What is left of `self` after `spent`. + pub(crate) fn less(self, spent: Cost) -> Cost { + Cost { + elements: self.elements.saturating_sub(spent.elements), + bytes: self.bytes.saturating_sub(spent.bytes), + tests: self.tests.saturating_sub(spent.tests), + } + } +} + +/// What a `` shows: nothing, the element it refers to with all it holds, or only that +/// element (a `` whose own reference leads back to the `` showing it). +enum Shows<'a, 'i> { + Nothing, + All(XNode<'a, 'i>), + Bare(XNode<'a, 'i>), +} + +struct Measure<'a, 'i> { + /// The first element of each id. + ids: HashMap<&'a str, XNode<'a, 'i>>, + sheet: simplecss::StyleSheet<'a>, + /// The selector tests made of `sheet` so far, each element once. + tests: Cell, + /// The most selector tests of `sheet` that are left: matching stops past them. + most_tests: u64, + /// The selector tests the import's own cascade made ([`Measure::cascade`]). + cascade_tests: Cell, + /// The import's own style cascade of the same style sheets. + cascade: css::Styles, + /// The elements that hold a `` of themselves. + holds_use_of_itself: HashSet, + /// The ``s of each element, by the element. + used_by: HashMap>>, + /// The bytes of text in each element a `` shows. + tref_text: HashMap, +} + +impl<'a, 'i> Measure<'a, 'i> { + fn new(xml: &'a roxmltree::Document<'i>) -> Self { + let mut ids = HashMap::new(); + for n in xml.descendants() { + if let Some(id) = n.attribute("id") { + ids.entry(id).or_insert(n); + } + } + // The style sheets usvg reads: `{groups}"))); + assert_eq!(bytes, 4 * 19 + 20 + 4 * 23 + 24); + // usvg drops a `:not()` rule; the cascade keeps it for each group it matches. + assert_eq!(cost(&svg(&format!("{groups}"))).1, 4 * 23); + // A style sheet of another type is not read; the style element itself makes nothing. + assert_eq!(cost(&svg(&format!("{groups}"))), (5, 0)); + // `marker` sets three properties; `font` resets twelve and sets six from its text. + let (_, marker) = cost(&svg("")); + let (_, font) = cost(&svg("")); + assert_eq!((marker, font), (3 * (16 + 7), 18 * 16 + 12 * 6 + 6)); + } + + #[test] + fn references_usvg_leaves_out_copy_nothing() { + // A use of itself, of a group holding it, of what isn't there or isn't SVG. + let (n, _) = cost(&svg("")); + assert_eq!(n, 1 + 1 + 3 + 1 + 1); + // Two uses of each other: each shows the other alone. + assert_eq!(cost(&svg("")).0, 1 + 2 + 2); + // A group holding a use of the use that shows it: that use shows nothing, and the one the + // group holds shows it alone. + let back = svg(""); + assert_eq!(cost(&back).0, 1 + 3 + 1); + // The unprefixed href wins, and an id names its first element. + let first = svg(""); + assert_eq!(cost(&first).0, 1 + 3 + 1 + 1 + 2 + 4); + } + + #[test] + fn a_loop_usvg_copies_without_end_is_refused_as_usvg_refuses_it() { + let looped = svg(""); + assert_eq!(past(&looped, u64::MAX, u64::MAX), Some(Past::Depth)); + assert!(usvg::Tree::from_str(&looped, &usvg::Options::default()).is_err()); + // Without the loop, usvg reads it. + let open = svg(""); + assert!(past(&open, u64::MAX, u64::MAX).is_none() && usvg::Tree::from_str(&open, &usvg::Options::default()).is_ok()); + } + + /// A chain of ``s nested past the depth is too deep, as `depth::height` finds it, before + /// what the chain makes is added up; one within the depth `depth::height` gives is not. + #[test] + fn copies_nested_past_the_depth_are_too_deep() { + let links: String = (0..3000).map(|i| format!("", i + 1)).collect(); + let deep = svg(&format!("{links}")); + let xml = roxmltree::Document::parse(&deep).unwrap(); + assert_eq!(measure(&xml, NO_LIMITS, MAX_ELEMENT_DEPTH).err(), Some(Past::Depth)); + assert!(super::super::depth::height(&xml, MAX_ELEMENT_DEPTH).is_none()); + assert!(matches!(check(&xml, Cost::LIMITS, MAX_ELEMENT_DEPTH), Err(SvgError::TooDeep(_)))); + for text in [chain(5, ""), svg("")] { + let xml = roxmltree::Document::parse(&text).unwrap(); + let height = super::super::depth::height(&xml, usize::MAX).unwrap_or(0); + assert!(measure(&xml, NO_LIMITS, height).is_ok(), "{height} {text}"); + } + } + + #[test] + fn text_counts_its_runs_and_what_trefs_show() { + let (n, bytes) = cost(&svg("abcdxyz")); + // svg, g (its text is not counted outside a text), text, its runs "xy" and "z", tspan, tref and its text. + assert_eq!(n, 1 + 1 + 1 + 2 + 1 + 1 + 1); + assert_eq!(bytes, (16 + 2) + (16 + 1) + (16 + 4)); + } + + /// A long style sheet rule that matches many elements is refused before the import's own style + /// cascade (which keeps the declarations of each element) reads them, in an SVG and in an SVG + /// image it shows. + #[test] + fn a_long_rule_on_many_elements_is_refused_before_the_cascade_reads_it() { + let groups = svg(&format!("{}", "a".repeat(100_000), "".repeat(1000))); + let image = svg(&format!(r#""#, crate::base64_encode(groups.as_bytes()))); + // usvg drops a `:not()` rule, which the import's own cascade reads. + let not = svg(&format!("{}", "a".repeat(100_000), "".repeat(1000))); + for text in [groups, image, not] { + let before = super::super::css::selector_tests(); + let err = super::super::import(&text, &crate::ImportOptions::default(), MAX_NODES).err(); + assert!(matches!(err, Some(SvgError::StylesTooLarge(64))), "{err:?}"); + assert_eq!(super::super::css::selector_tests(), before); + } + } + + /// A linked SVG file with such a rule, and an `` of its own whose link the import reads, + /// is refused before the cascade reads it too. + #[test] + fn a_linked_svg_with_a_long_rule_is_refused_before_the_cascade_reads_it() { + let linked = + svg(&format!("{}", "a".repeat(100_000), "".repeat(1000))); + let read = |path: &str| path.ends_with("a.svg").then(|| (linked.clone().into_bytes(), vectorcraft_doc::LinkInfo::new(path))); + let folder = std::env::temp_dir().join("vectorcraft-svg-budget"); + let folder = folder.to_string_lossy(); + let opts = crate::ImportOptions { folder: Some(&folder), read: Some(&read) }; + let before = super::super::css::selector_tests(); + let err = super::super::import(&svg(""), &opts, MAX_NODES).err(); + assert!(matches!(err, Some(SvgError::StylesTooLarge(64))), "{err:?}"); + assert_eq!(super::super::css::selector_tests(), before); + } + + /// `depth` groups in one another, each of class `a`, around a rectangle, with `sheet`. + fn nested(depth: usize, sheet: &str) -> String { + svg(&format!("{}{}", "".repeat(depth), "".repeat(depth))) + } + + /// A selector whose leftmost part matches nothing makes usvg test every set of ancestors in + /// turn: the tests stop at the limit and the SVG is refused, before usvg or the cascade runs. + #[test] + fn a_selector_that_never_matches_stops_at_the_test_limit() { + let never = nested(60, &format!(".missing{} {{fill:red}}", " g".repeat(20))); + let xml = roxmltree::Document::parse(&never).unwrap(); + assert_eq!(measure(&xml, Cost::LIMITS, usize::MAX).err(), Some(Past::Tests)); + let before = super::super::css::selector_tests(); + let err = super::super::import(&never, &crate::ImportOptions::default(), MAX_NODES).err(); + assert!(matches!(err, Some(SvgError::StylesTooComplex)), "{err:?}"); + assert_eq!(super::super::css::selector_tests(), before); + // The same selector without its leftmost part matches at once, and imports. + let matching = nested(60, &format!("g{} {{fill:red}}", " g".repeat(19))); + assert!(super::super::import(&matching, &crate::ImportOptions::default(), MAX_NODES).is_ok()); + } + + /// usvg tests the rules against each copy a `` shows: the tests add up as the copies do, + /// and the cascade's tests count once for each element. + #[test] + fn selector_tests_count_for_each_copy() { + let tests = |levels: usize| { + let text = chain(levels, "").replacen("", "", 1); + let xml = roxmltree::Document::parse(&text).unwrap(); + measure(&xml, NO_LIMITS, usize::MAX).unwrap_or_else(|p| panic!("{p:?}")).tests + }; + let (ten, eleven) = (tests(10), tests(11)); + assert!(eleven > 2 * ten - 100, "{ten} {eleven}"); + let text = chain(11, "").replacen("", "", 1); + let xml = roxmltree::Document::parse(&text).unwrap(); + assert_eq!(measure(&xml, Cost { tests: eleven - 1, ..NO_LIMITS }, usize::MAX).err(), Some(Past::Tests)); + assert!(measure(&xml, Cost { tests: eleven, ..NO_LIMITS }, usize::MAX).is_ok()); + } + + /// Each alternative of a `:not()` counts as a test of the cascade, for each element. + #[test] + fn not_alternatives_count_as_tests() { + let alternatives: Vec = (0..1000).map(|i| format!(".m{i}")).collect(); + let text = svg(&format!("{}", alternatives.join(","), "".repeat(1000))); + let xml = roxmltree::Document::parse(&text).unwrap(); + let tests = measure(&xml, NO_LIMITS, usize::MAX).unwrap_or_else(|p| panic!("{p:?}")).tests; + assert!(tests > 1000 * 1000, "{tests}"); + assert_eq!(measure(&xml, Cost { tests: 1000 * 1000, ..NO_LIMITS }, usize::MAX).err(), Some(Past::Tests)); + } + + /// Matching as usvg matches stops once its tests pass what the limits have left, as when an + /// SVG image gets what the SVG showing it left. + #[test] + fn usvg_matching_stops_at_what_is_left() { + let never = nested(60, &format!(".missing{} {{fill:red}}", " g".repeat(20))); + let xml = roxmltree::Document::parse(&never).unwrap(); + let cascade = Measure::new(&xml).cascade(&xml, NO_LIMITS).unwrap_or_else(|p| panic!("{p:?}")).tests; + assert_eq!(measure(&xml, Cost { tests: cascade + 1000, ..NO_LIMITS }, usize::MAX).err(), Some(Past::Tests)); + let made = USVG_TESTS.get(); + assert!((1000..1100).contains(&made), "{made}"); + } + + /// Each class of a compound is looked for in the element's class list, so the tests grow with + /// the list's length: in the import's own cascade (a `:not()` rule, which usvg drops) and as + /// usvg matches. + #[test] + fn class_tests_grow_with_the_class_list() { + let list = (0..1000).map(|i| format!("c{i}")).collect::>().join(" "); + let classes: String = (0..100).map(|i| format!(".c{i}")).collect(); + let scans = 100 * css::scan_tests(list.len()); + let tests = |rule: &str| { + let text = svg(&format!("")); + let xml = roxmltree::Document::parse(&text).unwrap(); + measure(&xml, NO_LIMITS, usize::MAX).unwrap_or_else(|p| panic!("{p:?}")).tests + }; + let cascade = tests(&format!("g:not(.x{classes})")); + assert!(cascade >= scans, "{cascade} {scans}"); + tests(&format!("g{classes}")); + let usvg = USVG_TESTS.get(); + assert!(usvg >= scans, "{usvg} {scans}"); + } +} diff --git a/crates/svg/src/import/css.rs b/crates/svg/src/import/css.rs index fd864a547e..b5f1d80320 100644 --- a/crates/svg/src/import/css.rs +++ b/crates/svg/src/import/css.rs @@ -103,6 +103,24 @@ impl Compound { && self.attrs.iter().all(|(a, v)| n.attribute(a.as_str()).is_some_and(|x| v.as_deref().is_none_or(|v| x == v))) && !self.nots.iter().any(|c| c.matches(n)) } + + /// The tests [`Compound::matches`] makes of `n` at most, its `:not()`s' included: one for the + /// compound, [`scan_tests`] of `n`'s attributes for each attribute it looks up, and for each + /// of its classes, [`scan_tests`] of `n`'s class list. + fn tests(&self, n: XNode) -> u64 { + let lookups = u64::from(self.id.is_some()) + u64::from(!self.classes.is_empty()) + self.attrs.len() as u64; + let mut tests = lookups.saturating_mul(scan_tests(n.attributes().len())).saturating_add(1); + if !self.classes.is_empty() { + let list = scan_tests(n.attribute("class").map_or(0, str::len)); + tests = tests.saturating_add((self.classes.len() as u64).saturating_mul(list)); + } + self.nots.iter().map(|c| c.tests(n)).fold(tests, u64::saturating_add) + } +} + +/// The tests a scan of `len` attributes or bytes counts as: one, and one more for every 16. +pub(super) fn scan_tests(len: usize) -> u64 { + 1 + len as u64 / 16 } /// A complex selector, rightmost compound first; each compound's flag says whether it must be the @@ -129,7 +147,7 @@ thread_local! { /// [`SELECTOR_TESTS`] of this thread. #[cfg(test)] -fn selector_tests() -> u64 { +pub(super) fn selector_tests() -> u64 { SELECTOR_TESTS.get() } @@ -260,14 +278,35 @@ impl Selector { } fn matches(&self, n: XNode) -> bool { + #[cfg(test)] + SELECTOR_TESTS.set(SELECTOR_TESTS.get().saturating_add(1)); + self.matches_counting(n, &mut 0, None) + } + + /// [`Self::matches`], counting the tests of each compound tested against an element in + /// `steps` ([`Compound::tests`]), those of its `:not()`s included. Once `steps` passes `most`, + /// no compound matches any more. + fn matches_within(&self, n: XNode, steps: &mut u64, most: u64) -> bool { + self.matches_counting(n, steps, Some(most)) + } + + /// [`Self::matches_within`] when `most` is given; [`Self::matches`], counting nothing, when not. + fn matches_counting(&self, n: XNode, steps: &mut u64, most: Option) -> bool { // The result of matching a selector suffix from a node depends only on the suffix and // the node, so memoize it: without this, every descendant step retries every matching // ancestor and a selector whose leftmost compound never matches makes the search // enumerate ancestor combinations (#1703). A suffix of `parts` is identified by its // length, so (suffix length, node id) is a complete key and the visited states are // bounded by parts × ancestors. - fn go(parts: &[(Compound, bool)], n: XNode, memo: &mut HashMap<(usize, roxmltree::NodeId), bool>) -> bool { + type Memo = HashMap<(usize, roxmltree::NodeId), bool>; + fn go(parts: &[(Compound, bool)], n: XNode, memo: &mut Memo, steps: &mut u64, most: Option) -> bool { let Some(((c, child), rest)) = parts.split_first() else { return true }; + if let Some(most) = most { + *steps = steps.saturating_add(c.tests(n)); + if *steps > most { + return false; + } + } if !c.matches(n) { return false; } @@ -279,16 +318,14 @@ impl Selector { return hit; } let hit = if *child { - n.parent_element().is_some_and(|p| go(rest, p, memo)) + n.parent_element().is_some_and(|p| go(rest, p, memo, steps, most)) } else { - n.ancestors().skip(1).filter(|a| a.is_element()).any(|a| go(rest, a, memo)) + n.ancestors().skip(1).filter(|a| a.is_element()).any(|a| go(rest, a, memo, steps, most)) }; memo.insert(key, hit); hit } - #[cfg(test)] - SELECTOR_TESTS.set(SELECTOR_TESTS.get().saturating_add(1)); - go(&self.parts, n, &mut HashMap::new()) + go(&self.parts, n, &mut HashMap::new(), steps, most) } } @@ -495,6 +532,24 @@ impl Styles { m } + /// The bytes the declarations of the rules that match `n` take, names and values, each with + /// `per_declaration` more: at least what [`Styles::declared`] keeps of them for `n`. Nothing + /// is kept. `steps` counts the rules and compounds tested; `None` once it passes `most`. + pub(super) fn matched_bytes(&self, n: XNode, per_declaration: u64, steps: &mut u64, most: u64) -> Option { + let mut bytes = 0u64; + for r in self.index.candidates(n).into_iter().filter_map(|i| self.rules.get(i)) { + *steps = steps.saturating_add(1); + if r.selector.matches_within(n, steps, most) { + let size = |(k, v, _): &(String, String, bool)| per_declaration.saturating_add((k.len() + v.len()) as u64); + bytes = r.decls.iter().map(size).fold(bytes, u64::saturating_add); + } + if *steps > most { + return None; + } + } + Some(bytes) + } + /// Are there rules with a `:not()` (which usvg's style sheets drop)? pub(super) fn has_not_rules(&self) -> bool { self.rules.iter().any(|r| r.selector.has_not()) diff --git a/crates/svg/src/import/files.rs b/crates/svg/src/import/files.rs index bab4246270..fe3335fb4e 100644 --- a/crates/svg/src/import/files.rs +++ b/crates/svg/src/import/files.rs @@ -4,6 +4,10 @@ //! (missing, remote, not an image) becomes a placeholder that keeps the link and its place, so it //! can be relinked, and a warning. //! +//! A linked SVG file's own `` links are read the same way, relative paths from that file's +//! folder, within the same limits; an href that leads back to an SVG file showing it gets the +//! placeholder and a warning. +//! //! A raster image, linked or a data URL, whose orientation (EXIF, or a TIFF's Orientation tag) //! turns or flips its pixels is turned before usvg gets it, so it is sized, fitted and stored as //! it is shown. @@ -17,7 +21,7 @@ use usvg::{ImageHrefResolver, ImageKind, roxmltree}; use vectorcraft_doc::LinkInfo; use vectorcraft_doc::links::missing_placeholder; -use super::{Edits, depth, href}; +use super::{Edits, budget, depth, href}; use crate::{ImportOptions, MAX_ELEMENT_DEPTH, MAX_SVGZ, SvgError}; /// Most nested SVG images an imported SVG may decode (#3564). @@ -35,6 +39,9 @@ pub const MAX_NESTED_SVG_TEXT: u64 = 512 << 20; pub(in crate::import) struct Files { /// What usvg gets for each linked href. sources: HashMap, + /// The SVG images usvg is reading, innermost last: a linked SVG file, whose own links an href + /// inside it is looked up in, or `None` for a data URL. + within: Mutex>>>, /// The link of each linked raster or placeholder, by the address of the bytes usvg got. links: HashMap, /// An SVG image had text (which isn't imported). @@ -61,9 +68,18 @@ pub(in crate::import) struct Files { svg_text: AtomicU64, /// SVG images were left out for exceeding [`MAX_NESTED_SVG_READS`] or [`MAX_NESTED_SVG_TEXT`]. too_much_svg_read: AtomicBool, + /// Images linked from linked SVG files were left out, their files not read, past the same + /// limits for the files read for links. + too_much_linked: AtomicBool, /// The CMYK TIFF stored in place of a turned CMYK image, by the address of the PNG usvg got /// (kept here too, so the address stays its own). cmyk: Mutex>, + /// What usvg makes of the SVG and of the SVG images read so far, all together ([`budget`]): + /// elements, bytes of copied style values and selector tests. + spent: Mutex, + /// Why an SVG image refused the whole SVG: what usvg would make of it is past [`budget`]'s + /// limits. The first one. + refused: Mutex>, } /// Encoded image bytes, shared. @@ -84,8 +100,85 @@ type RasterKind = fn(Arc>) -> ImageKind; enum Source { /// A raster file of the kind usvg reads it as. Raster(RasterKind, Arc>), - /// An SVG file's text (unpacked when it is SVGZ), parsed by usvg as an image. - Svg(Arc), + /// An SVG file, parsed by usvg as an image. + Svg(Arc), +} + +/// A linked SVG file as usvg reads it. +struct SvgFile { + /// Its text (unpacked when it is SVGZ), placeholders stretched to their boxes. + text: Arc, + /// What usvg gets for each href its own `` elements link to. + sources: HashMap, +} + +/// The state of [`Files::read`] across the SVG files it reads the links of. +struct Reading<'a, 'w> { + opts: &'a ImportOptions<'a>, + warnings: &'w mut Vec, + /// The placeholder's bytes, made once. + placeholder: Option>>, + /// What each file read gave, by the file: hrefs spelled differently (`a.png`, `./a.png`, + /// `%61.png`), and in different SVG files, share one read and one copy of its bytes. Only an + /// SVG file whose art depends on where it is shown ([`Reading::placed`]) isn't kept, and a + /// raster read past the limits, which is left out. + by_file: HashMap, + /// The SVG files whose links are being read, innermost last, by [`identity`]. + active: Vec, + /// What the file being read gives depends on where it is shown: a link inside it led back to + /// an SVG file around it, or an SVG file inside it nests too deep there for its links to be + /// read. + placed: bool, + /// How many linked SVG files were read for their links, and the bytes of every linked SVG + /// file read and of every file read for the links of a linked SVG file. Rasters the imported + /// SVG links to aren't counted. + svg_reads: usize, + svg_text: u64, + /// What the linked SVG files measured for their links make, all together ([`budget`]); of one + /// past what is left, the selector tests it made. + measured: budget::Cost, +} + +impl Reading<'_, '_> { + /// The files read for links passed [`MAX_NESTED_SVG_READS`] or [`MAX_NESTED_SVG_TEXT`]. + fn spent(&self) -> bool { + self.svg_reads > MAX_NESTED_SVG_READS || self.svg_text > MAX_NESTED_SVG_TEXT + } +} + +/// What reading a linked file gave: what usvg gets, or why it can't be read. +#[derive(Clone)] +struct Outcome { + source: Result, + /// An SVG file whose own links weren't read, past [`Reading::spent`]: inside a linked SVG + /// file it is left out, and where the imported SVG links to it, it is shown without them. + capped: bool, +} + +impl Outcome { + fn not_read(why: &'static str) -> Self { + Outcome { source: Err(why), capped: false } + } + + fn shown(source: Source) -> Self { + Outcome { source: Ok(source), capped: false } + } +} + +/// Does SVG text `text` have an `` that links to a file (not a data URL)? +fn links_files(text: &str) -> bool { + super::parse(text).is_ok_and(|xml| xml.descendants().any(|n| n.is_element() && n.tag_name().name() == "image" && file_href(n).is_some())) +} + +/// The href of `` element `n`, unless it is a data URL. +fn file_href<'a>(n: roxmltree::Node<'a, '_>) -> Option<&'a str> { + href(n).filter(|h| !h.trim_start().starts_with("data:")) +} + +/// What the link to an SVG file being read is compared by, to find a link back to it: its path +/// with links and `..` resolved, or the path as given when that can't be found. +fn identity(file: &str) -> String { + std::fs::canonicalize(file).map_or_else(|_| file.to_string(), |p| p.to_string_lossy().into_owned()) } /// A linked raster image (or the placeholder of a missing one). @@ -164,54 +257,178 @@ impl Files { /// relinked. pub(in crate::import) fn read(svg: &str, xml: &roxmltree::Document, opts: &ImportOptions, edits: &mut Edits, warnings: &mut Vec) -> Self { let mut files = Files::default(); - let mut placeholder = None; - // What each file read gave, by the file: hrefs spelled differently (`a.png`, `./a.png`, - // `%61.png`) share one read and one copy of its bytes. - let mut by_file: HashMap> = HashMap::new(); - for n in xml.descendants().filter(|n| n.is_element() && n.tag_name().name() == "image") { - let Some(h) = href(n).filter(|h| !h.trim_start().starts_with("data:")) else { continue }; - if !files.sources.contains_key(h) { - let (path, file) = target(h, opts.folder); - // A failed read is cached too, but each href gets its own placeholder: its own link - // path (an Arc shared between hrefs would share the first href's link) and warning. - let cached = file.as_ref().and_then(|f| by_file.get(f)).cloned(); - let source = match cached { - Some(source) => source, - None => { - let read = file.clone().and_then(|file| opts.read.and_then(|read| read(&file))); - let source = match read { - Some((bytes, link)) => files.source(bytes, link).ok_or("is not an image VectorCraft reads"), - None => Err("not found"), - }; - if let Some(file) = file { - by_file.insert(file, source.clone()); - } - source - } - }; - let source = source.or_else(|why| { - warnings.push(format!("linked image '{h}' {why}: a placeholder keeps its place until it is relinked")); - let bytes = Arc::new(placeholder.get_or_insert_with(missing_placeholder).clone().ok_or(why)?); - files.links.insert(key(&bytes), Linked { link: LinkInfo::new(path), missing: true }); - Ok::<_, &str>(Source::Raster(ImageKind::PNG, bytes)) - }); - let Ok(source) = source else { continue }; - files.sources.insert(h.to_string(), source); - } - if files.placeholder(h) { - edits.set(svg, n, "preserveAspectRatio", "none"); - } - } + let mut reading = Reading { + opts, + warnings, + placeholder: None, + by_file: HashMap::new(), + active: vec![], + placed: false, + svg_reads: 0, + svg_text: 0, + measured: budget::Cost::default(), + }; + files.sources = files.links_of(svg, xml, opts.folder, None, edits, &mut reading); files } + /// What usvg gets for each href the `` elements of `xml` (the text `svg`) link to, + /// relative paths taken from `folder`. `inside` is how deep the SVG images `xml` shows nest in + /// it and the SVGs around it, measured when an SVG file is read (`None` for `xml` itself). + fn links_of( + &mut self, + svg: &str, + xml: &roxmltree::Document, + folder: Option<&str>, + mut inside: Option, + edits: &mut Edits, + reading: &mut Reading<'_, '_>, + ) -> HashMap { + let mut sources: HashMap = HashMap::new(); + let nested = !reading.active.is_empty(); + for n in xml.descendants().filter(|n| n.is_element() && n.tag_name().name() == "image") { + let Some(h) = file_href(n) else { continue }; + if !sources.contains_key(h) { + let (path, file) = target(h, folder); + // A failed read is cached too, but each href gets its own placeholder: its own link + // path (an Arc shared between hrefs would share the first href's link) and warning. + let back = nested && file.as_deref().is_some_and(|f| reading.active.contains(&identity(f))); + let cached = file.as_ref().and_then(|f| reading.by_file.get(f)).cloned(); + let outcome = match cached { + _ if back => { + reading.placed = true; + Some(Outcome::not_read("leads back to an SVG file that shows it")) + } + Some(outcome) => Some(outcome), + None => { + let around = std::mem::replace(&mut reading.placed, false); + let outcome = self.file(file.as_deref(), xml, &mut inside, reading); + // Kept unless what it shows depends on where it is. + let placed = reading.placed; + reading.placed |= around; + if let (Some(file), Some(outcome)) = (file, &outcome) + && !placed + { + reading.by_file.insert(file, outcome.clone()); + } + outcome + } + }; + // Inside a linked SVG file, past what may be read, the image is left out (noted). + let source = match outcome { + None => continue, + Some(Outcome { capped: true, .. }) if nested => { + self.too_much_svg_read.store(true, Ordering::Relaxed); + continue; + } + Some(outcome) => outcome.source, + }; + let source = source.or_else(|why| { + reading.warnings.push(format!("linked image '{h}' {why}: a placeholder keeps its place until it is relinked")); + let bytes = Arc::new(reading.placeholder.get_or_insert_with(missing_placeholder).clone().ok_or(why)?); + self.links.insert(key(&bytes), Linked { link: LinkInfo::new(path), missing: true }); + Ok::<_, &str>(Source::Raster(ImageKind::PNG, bytes)) + }); + let Ok(source) = source else { continue }; + sources.insert(h.to_string(), source); + } + if sources.get(h).is_some_and(|s| self.missing(s)) { + edits.set(svg, n, "preserveAspectRatio", "none"); + } + } + sources + } + + /// What reading linked file `file` gives, linked from `xml`, whose SVG images nest `inside` + /// deep (measured here when an SVG file is read); `None` for an image left out, noted. Inside + /// a linked SVG file each file read counts toward [`MAX_NESTED_SVG_TEXT`] before it is looked + /// at, and once the files read for links pass [`MAX_NESTED_SVG_READS`] or + /// [`MAX_NESTED_SVG_TEXT`] no file is read there; a raster whose read passes them is left out + /// undecoded. Every file the imported SVG links to is read. + fn file(&mut self, file: Option<&str>, xml: &roxmltree::Document, inside: &mut Option, reading: &mut Reading<'_, '_>) -> Option { + let (Some(file), Some(read)) = (file, reading.opts.read) else { return Some(Outcome::not_read("not found")) }; + let nested = !reading.active.is_empty(); + if nested && reading.spent() { + self.too_much_linked.store(true, Ordering::Relaxed); + return None; + } + let Some((bytes, link)) = read(file) else { return Some(Outcome::not_read("not found")) }; + let counted = if nested { bytes.len() as u64 } else { 0 }; + reading.svg_text = reading.svg_text.saturating_add(counted); + if nested && reading.spent() && image::guess_format(&bytes).is_ok() { + self.too_much_linked.store(true, Ordering::Relaxed); + return None; + } + match self.source(bytes, link) { + Some(Source::Svg(svg)) => { + let inside = *inside.get_or_insert_with(|| depth::height(xml, MAX_ELEMENT_DEPTH).unwrap_or(MAX_ELEMENT_DEPTH)); + Some(self.svg_file(svg, file, inside, counted, reading)) + } + source => Some(source.map_or_else(|| Outcome::not_read("is not an image VectorCraft reads"), Outcome::shown)), + } + } + + /// Linked SVG file `file`, read as `svg`, with the files its own `` elements link to + /// read from its folder; `inside` is how deep it nests in the SVGs around it, and `counted` the + /// bytes of it already counted toward [`MAX_NESTED_SVG_TEXT`]. Its text counts toward + /// [`MAX_NESTED_SVG_TEXT`], and reading its links toward [`MAX_NESTED_SVG_READS`]; once they + /// are passed, its links aren't read ([`Outcome::capped`], noted when it links to files). Its + /// links aren't read either when it nests too deep to be shown, or when it isn't XML. + fn svg_file(&mut self, svg: Arc, file: &str, inside: usize, counted: u64, reading: &mut Reading<'_, '_>) -> Outcome { + reading.svg_text = reading.svg_text.saturating_add((svg.text.len() as u64).saturating_sub(counted)); + let links = svg.text.contains("image"); + reading.svg_reads += usize::from(links); + if reading.spent() { + if links && links_files(&svg.text) { + self.too_much_linked.store(true, Ordering::Relaxed); + } + return Outcome { source: Ok(Source::Svg(svg)), capped: true }; + } + let left = MAX_ELEMENT_DEPTH.saturating_sub(inside); + if !links { + return Outcome::shown(Source::Svg(svg)); + } + if depth::xml_deeper_than(&svg.text, left) { + reading.placed = true; + return Outcome::shown(Source::Svg(svg)); + } + // Read from its own handle: the text stays borrowed while `svg` may be given back. + let text = svg.text.clone(); + let Ok(xml) = super::parse(&text) else { return Outcome::shown(Source::Svg(svg)) }; + // Measured before the style cascade of `depth::height`, as an SVG image is when usvg + // reads it ([`Files::svg_tree`]), which then refuses one past the limits, within what the + // linked SVG files measured before it left: past it, its links aren't read, and the + // selector tests it made still count. + let (result, tests) = budget::check_spending(&xml, budget::Cost::LIMITS.less(reading.measured), left); + match result { + Ok(cost) => reading.measured = reading.measured.add(cost), + Err(e) => { + reading.measured.tests = reading.measured.tests.saturating_add(tests); + reading.placed |= matches!(e, SvgError::TooDeep(_)); + return Outcome::shown(Source::Svg(svg)); + } + } + let Some(height) = depth::height(&xml, left) else { + reading.placed = true; + return Outcome::shown(Source::Svg(svg)); + }; + let folder = Path::new(file).parent().map(|p| p.to_string_lossy().into_owned()); + let mut edits = Edits::default(); + reading.active.push(identity(file)); + let sources = self.links_of(&text, &xml, folder.as_deref(), Some(inside + height), &mut edits, reading); + reading.active.pop(); + let text = Arc::from(edits.apply(&text).as_ref()); + Outcome::shown(Source::Svg(Arc::new(SvgFile { text, sources }))) + } + /// What usvg gets for a file read (`bytes`, linked by `link`): a raster as [`shown`] gives it - /// (formats usvg doesn't read are stored as PNG) or an SVG; `None` for anything else. + /// (formats usvg doesn't read are stored as PNG) or an SVG, its own links not read yet; `None` + /// for anything else. fn source(&mut self, bytes: Vec, link: LinkInfo) -> Option { let Ok(format) = image::guess_format(&bytes) else { // Unpacked once, here, within what the SVGZ images may unpack to. let text = crate::text_within(&bytes, &self.unpacked).ok()?; - return text.contains(" bool { - matches!(self.sources.get(h), Some(Source::Raster(_, b)) if self.links.get(&key(b)).is_some_and(|l| l.missing)) + /// Is `source` a placeholder? + fn missing(&self, source: &Source) -> bool { + matches!(source, Source::Raster(_, b) if self.links.get(&key(b)).is_some_and(|l| l.missing)) + } + + /// What usvg gets for href `h` where it is read: inside a linked SVG file, from that file's + /// own links; outside any SVG image, from the imported SVG's. Inside an SVG data URL, which + /// has no folder of its own, nothing. + fn find(&self, h: &str) -> Option { + let within = self.within.lock().ok()?; + let sources = match within.last() { + None => &self.sources, + Some(file) => &file.as_ref()?.sources, + }; + sources.get(h).or_else(|| sources.get(h.trim())).cloned() } /// The link of the image whose data usvg got as `kind`. @@ -272,9 +501,36 @@ impl Files { MAX_NESTED_SVG_TEXT >> 20 )); } + if self.too_much_linked.load(Ordering::Relaxed) { + notes.push(format!( + "images linked from linked SVG files were left out: once {MAX_NESTED_SVG_READS} SVG files or {} MB have been read for their links, the files they link to aren't read", + MAX_NESTED_SVG_TEXT >> 20 + )); + } notes } + /// What usvg makes of the SVG holding the images ([`budget::check`]): its images make at most + /// what is left of [`budget::Cost::LIMITS`]. + pub(in crate::import) fn spent_by_svg(&self, spent: budget::Cost) { + self.set_spent(spent); + } + + fn spent(&self) -> budget::Cost { + self.spent.lock().map(|s| *s).unwrap_or(budget::Cost::LIMITS) + } + + fn set_spent(&self, spent: budget::Cost) { + if let Ok(mut s) = self.spent.lock() { + *s = spent; + } + } + + /// The error of the first SVG image past [`budget`]'s limits, which refuses the SVG holding it. + pub(in crate::import) fn refused(&self) -> Option { + self.refused.lock().ok().and_then(|r| r.clone()) + } + fn note_text(&self, svg: &str) { if svg.contains(" Some(kind(bytes.clone())), - Source::Svg(text) => self.svg(text, opts), + resolve_string: Box::new(move |h, opts| match self.find(h)? { + Source::Raster(kind, bytes) => Some(kind(bytes)), + Source::Svg(file) => self.svg(&file.text.clone(), Some(file), opts), }), } } @@ -320,7 +576,7 @@ impl Files { /// noted. fn svg_data(&self, bytes: &[u8], opts: &usvg::Options) -> Option { match crate::text_within(bytes, &self.unpacked) { - Ok(text) => self.svg(&text, opts), + Ok(text) => self.svg(&text, None, opts), Err(e) => leave_out(&self.too_big, matches!(e, SvgError::TooBig(_))), } } @@ -329,8 +585,9 @@ impl Files { /// can't read, when it isn't SVG or when its elements nest deeper than the SVGs around it /// leave: usvg reads it while it reads them, on the same stack. Only a decoded image, with the /// images decoded inside it, counts toward [`MAX_NESTED_SVG_IMAGES`]; every image read counts - /// toward [`MAX_NESTED_SVG_READS`] and [`MAX_NESTED_SVG_TEXT`]. - fn svg(&self, text: &str, opts: &usvg::Options) -> Option { + /// toward [`MAX_NESTED_SVG_READS`] and [`MAX_NESTED_SVG_TEXT`]. `file` is the linked SVG file + /// the text is, whose own links the hrefs in it are looked up in. + fn svg(&self, text: &str, file: Option>, opts: &usvg::Options) -> Option { let decoded = self.svg_images.load(Ordering::Relaxed); if decoded >= MAX_NESTED_SVG_IMAGES { return leave_out(&self.too_many_svg_images, true); @@ -345,7 +602,7 @@ impl Files { // The image's place is taken while usvg reads it, so the images inside it get what is left. // usvg reads them all on this thread, so no other read comes between these steps. self.svg_images.store(decoded + 1, Ordering::Relaxed); - let tree = self.svg_tree(text, opts); + let tree = self.svg_tree(text, file, opts); if tree.is_none() { self.svg_images.store(decoded, Ordering::Relaxed); } @@ -353,7 +610,11 @@ impl Files { } /// [`Files::svg`]'s image once it is counted. - fn svg_tree(&self, text: &str, opts: &usvg::Options) -> Option { + fn svg_tree(&self, text: &str, file: Option>, opts: &usvg::Options) -> Option { + // The SVG holding it is refused already: no more images are read. + if self.refused().is_some() { + return None; + } // Measured as the SVG holding it is (`import`): the text before the XML reader. let used = self.depth.load(Ordering::Relaxed); let left = MAX_ELEMENT_DEPTH.saturating_sub(used); @@ -361,13 +622,53 @@ impl Files { return leave_out(&self.too_deep, true); } let xml = super::parse(text).ok()?; + // What usvg would make of it, measured as the SVG holding it is (`import`), before the + // style cascade of `depth::height`; its elements, copied styles and selector tests count + // with theirs while usvg reads it, and only when it decodes. Too deep, it is left out; + // past the other limits, the whole SVG is refused. + let spent = self.spent(); + let cost = match budget::check(&xml, budget::Cost::LIMITS.less(spent), left) { + Ok(cost) => cost, + Err(SvgError::TooDeep(_)) => return leave_out(&self.too_deep, true), + Err(e) => { + if let Ok(mut refused) = self.refused.lock() { + refused.get_or_insert(e); + } + return None; + } + }; let Some(height) = depth::height(&xml, left) else { return leave_out(&self.too_deep, true) }; // usvg's parser would overflow on it, as on the SVG holding it (`import`). super::convolve_matrices_ok(&xml).ok()?; + self.set_spent(spent.add(cost)); self.depth.store(used + height, Ordering::Relaxed); - let tree = usvg::Tree::from_data_nested(text.as_bytes(), opts); + let within = self.within.lock().ok().map(|mut w| w.push(file)).is_some(); + // usvg's `Tree::from_data_nested`, except that hrefs to files go to the resolver. + let nested = usvg::Options { + resources_dir: None, + dpi: opts.dpi, + font_size: opts.font_size, + languages: opts.languages.clone(), + shape_rendering: opts.shape_rendering, + text_rendering: opts.text_rendering, + image_rendering: opts.image_rendering, + default_size: opts.default_size, + image_href_resolver: ImageHrefResolver { + resolve_data: Box::new(|mime, bytes, o| (opts.image_href_resolver.resolve_data)(mime, bytes, o)), + resolve_string: Box::new(|h, o| (opts.image_href_resolver.resolve_string)(h, o)), + }, + ..usvg::Options::default() + }; + let tree = usvg::Tree::from_str(text, &nested); + if within && let Ok(mut w) = self.within.lock() { + w.pop(); + } self.depth.store(used, Ordering::Relaxed); - let tree = tree.ok()?; + let Ok(tree) = tree else { + // Left out: neither it nor the images inside it count. + self.set_spent(spent); + return None; + }; self.note_text(text); Some(ImageKind::SVG(tree)) } @@ -390,10 +691,11 @@ fn raster(format: image::ImageFormat) -> Option { /// orientation ([`vectorcraft_doc::cmyk::exif_orientation`], read for PNG, JPEG, GIF, WebP and /// TIFF) leaves the pixels as stored. Otherwise the pixels are read ([`decoded`], /// [`tiff_pixels`]), turned or flipped as the orientation says, and written as PNG, so usvg sizes -/// and fits the image as it is shown. A CMYK TIFF also keeps its inks as a CMYK TIFF -/// ([`vectorcraft_doc::cmyk::stored_cmyk_tiff`]), and a CMYK JPEG or TIFF that is turned keeps them -/// turned ([`vectorcraft_doc::cmyk::turned_cmyk`]). `None` when the pixels can't be read, and for -/// a TIFF with more strips or tiles than the decoder can count +/// and fits the image as it is shown, with the resolution the file declares +/// ([`vectorcraft_doc::ppi::resolution`]), its axes swapped by a quarter turn. A CMYK TIFF also +/// keeps its inks as a CMYK TIFF ([`vectorcraft_doc::cmyk::stored_cmyk_tiff`]), and a CMYK JPEG +/// or TIFF that is turned keeps them turned ([`vectorcraft_doc::cmyk::turned_cmyk`]). `None` when +/// the pixels can't be read, and for a TIFF with more strips or tiles than the decoder can count /// ([`vectorcraft_doc::cmyk::oversized_tiff`]), before any decoder opens it. fn shown(bytes: Arc>, format: image::ImageFormat) -> Option { use image::ImageFormat as F; @@ -409,9 +711,13 @@ fn shown(bytes: Arc>, format: image::ImageFormat) -> Option { } let tiff = image::guess_format(&bytes).ok() == Some(F::Tiff); let mut img = if tiff { tiff_pixels(&bytes)? } else { decoded(&bytes, format)? }; + let ppi = vectorcraft_doc::ppi::resolution(&bytes); + // The resolution describes the stored pixels; a quarter turn swaps its axes. + let quarter = orientation.is_some_and(|o| o.to_exif() >= 5); + let shown_ppi = ppi.map(|(x, y)| if quarter { (y, x) } else { (x, y) }); let cmyk = match orientation { - Some(o) if matches!(format, F::Jpeg | F::Tiff) => vectorcraft_doc::cmyk::turned_cmyk(&bytes, o, None).map(|(tiff, _)| tiff), - None if tiff => vectorcraft_doc::cmyk::stored_cmyk_tiff(&bytes, None), + Some(o) if matches!(format, F::Jpeg | F::Tiff) => vectorcraft_doc::cmyk::turned_cmyk(&bytes, o, shown_ppi).map(|(tiff, _)| tiff), + None if tiff => vectorcraft_doc::cmyk::stored_cmyk_tiff(&bytes, ppi), _ => None, }; if let Some(orientation) = orientation { @@ -419,6 +725,9 @@ fn shown(bytes: Arc>, format: image::ImageFormat) -> Option { } let mut png = Vec::new(); img.write_to(&mut std::io::Cursor::new(&mut png), F::Png).ok()?; + if let Some(ppi) = shown_ppi { + png = vectorcraft_doc::ppi::with_png_resolution(&png, ppi); + } Some(Shown { kind: ImageKind::PNG, bytes: Arc::new(png), cmyk }) } @@ -630,6 +939,163 @@ mod tests { assert!(read("1")); } + /// An SVG file of 2 × 2 showing `hrefs`. + fn linking(hrefs: &[&str]) -> Vec { + let images: String = hrefs.iter().map(|h| format!(r#""#)).collect(); + format!(r#"{images}"#).into_bytes() + } + + /// The links of the SVG showing `hrefs` read as [`Files::read`] reads them, the files `served` + /// by name, with the SVG files and bytes read for links starting at `reads` and `text`: the + /// names of the files read, in order, and the files. + fn read_links(hrefs: &[&str], served: &[(&str, Vec)], reads: usize, text: u64) -> (Vec, Files) { + let log = Mutex::new(vec![]); + let read = |path: &str| { + let name = Path::new(path).file_name()?.to_string_lossy().into_owned(); + log.lock().ok()?.push(name.clone()); + served.iter().find(|(n, _)| *n == name).map(|(_, bytes)| (bytes.clone(), LinkInfo::new(path))) + }; + let folder = std::env::temp_dir().join("vectorcraft-svg-limits"); + let folder = folder.to_string_lossy(); + let opts = ImportOptions { folder: Some(&folder), read: Some(&read) }; + let svg = String::from_utf8(linking(hrefs)).unwrap(); + let xml = super::super::parse(&svg).unwrap(); + let mut warnings = vec![]; + let mut reading = Reading { + opts: &opts, + warnings: &mut warnings, + placeholder: None, + by_file: HashMap::new(), + active: vec![], + placed: false, + svg_reads: reads, + svg_text: text, + measured: budget::Cost::default(), + }; + let mut files = Files::default(); + files.sources = files.links_of(&svg, &xml, opts.folder, None, &mut Edits::default(), &mut reading); + (log.into_inner().unwrap(), files) + } + + /// The linked SVG files measured for their links share the limits: each of these keeps about + /// 40 MB of declarations in the import's own cascade (its `:not()` rule), so the second one is + /// shown without its links, and neither it nor the cascade reads them. + #[test] + fn linked_svg_files_share_the_limits_for_their_links() { + let file = |png: &str| { + let groups = "".repeat(400); + let rule = format!("g:not(.x){{font-family:{}}}", "a".repeat(100_000)); + format!(r#"{groups}"#) + .into_bytes() + }; + let served = [("a.svg", file("a.png")), ("b.svg", file("b.png")), ("a.png", png()), ("b.png", png())]; + let (log, _) = read_links(&["a.svg"], &served, 0, 0); + assert_eq!(log, ["a.svg", "a.png"]); + let (log, _) = read_links(&["a.svg", "b.svg"], &served, 0, 0); + assert_eq!(log, ["a.svg", "a.png", "b.svg"]); + } + + /// A linked SVG file past the limits alone (a `` chain past the element limit) is shown + /// without its links, and the linked SVG files after it still get what it left. + #[test] + fn a_linked_svg_file_past_the_limits_leaves_the_others_their_links() { + let links: String = (1..=20).map(|i| format!(r##""##, i - 1)).collect(); + let chain = format!( + r##"{links}"## + ); + let served = [("a.svg", chain.into_bytes()), ("b.svg", linking(&["b.png"])), ("a.png", png()), ("b.png", png())]; + let (log, _) = read_links(&["a.svg", "b.svg"], &served, 0, 0); + assert_eq!(log, ["a.svg", "b.svg", "b.png"]); + } + + fn png() -> Vec { + let mut out = vec![]; + image::RgbaImage::new(1, 1).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + out + } + + fn linked_note() -> String { + format!( + "images linked from linked SVG files were left out: once {MAX_NESTED_SVG_READS} SVG files or {} MB have been read for their links, the files they link to aren't read", + MAX_NESTED_SVG_TEXT >> 20 + ) + } + + /// Every file read for a linked SVG file's links counts toward [`MAX_NESTED_SVG_TEXT`], a + /// raster too, after the linked SVG file's own text: the file that passes it is left out, and + /// no file after it is read. + #[test] + fn linked_files_past_the_text_limit_are_not_read() { + let a = linking(&["one.png", "two.png", "three.png"]); + let served = [("a.svg", a.clone()), ("one.png", png()), ("two.png", png()), ("three.png", png())]; + let (log, files) = read_links(&["a.svg"], &served, 0, MAX_NESTED_SVG_TEXT - (png().len() + a.len()) as u64); + assert_eq!(log, ["a.svg", "one.png", "two.png"]); + let Some(Source::Svg(a)) = files.sources.get("a.svg") else { panic!("a.svg is shown") }; + assert!(a.sources.contains_key("one.png") && a.sources.len() == 1, "{:?}", a.sources.keys()); + assert_eq!(files.left_out(), [linked_note()]); + } + + /// Once more than [`MAX_NESTED_SVG_READS`] SVG files are read for their links, the SVG file + /// past it is left out inside a linked SVG file, and no file a linked SVG file links to is + /// read (a nested link past the limit); rasters the imported SVG links to still are. + #[test] + fn linked_files_past_the_read_limit_are_not_read() { + let served = [("a.svg", linking(&["b.svg", "two.png"])), ("b.svg", linking(&["one.png"])), ("one.png", png()), ("two.png", png())]; + let (log, files) = read_links(&["a.svg", "two.png"], &served, MAX_NESTED_SVG_READS - 1, 0); + assert_eq!(log, ["a.svg", "b.svg", "two.png"]); + let Some(Source::Svg(a)) = files.sources.get("a.svg") else { panic!("a.svg is shown") }; + assert!(a.sources.is_empty(), "{:?}", a.sources.keys()); + assert!(matches!(files.sources.get("two.png"), Some(Source::Raster(..)))); + assert_eq!(files.left_out().len(), 2, "{:?}", files.left_out()); + assert!(files.left_out().contains(&linked_note())); + } + + /// Reading the SVG files the imported SVG links to, and their links, counts toward the + /// limits: past them, such a file is still shown, but the files it links to aren't read. + #[test] + fn svg_files_the_imported_svg_links_to_are_shown_without_their_links_past_the_limits() { + let served = [("a.svg", linking(&["one.png"])), ("one.png", png())]; + for (reads, text) in [(MAX_NESTED_SVG_READS, 0), (0, MAX_NESTED_SVG_TEXT)] { + let (log, files) = read_links(&["a.svg"], &served, reads, text); + assert_eq!(log, ["a.svg"], "one.png isn't read"); + let Some(Source::Svg(a)) = files.sources.get("a.svg") else { panic!("a.svg is shown") }; + assert!(a.sources.is_empty(), "{:?}", a.sources.keys()); + assert_eq!(files.left_out(), [linked_note()]); + } + // More of them than the limit: those past it are shown without their links. + let names: Vec = (0..MAX_NESTED_SVG_READS + 2).map(|i| format!("s{i}.svg")).collect(); + let hrefs: Vec<&str> = names.iter().map(String::as_str).collect(); + let mut served: Vec<(&str, Vec)> = hrefs.iter().map(|h| (*h, linking(&["one.png"]))).collect(); + served.push(("one.png", png())); + let (log, files) = read_links(&hrefs, &served, 0, 0); + assert_eq!(log.len(), hrefs.len() + 1, "one.png is read once"); + let with_links = hrefs.iter().filter(|h| matches!(files.sources.get(**h), Some(Source::Svg(s)) if s.sources.contains_key("one.png"))); + assert_eq!(with_links.count(), MAX_NESTED_SVG_READS); + assert!(hrefs.iter().all(|h| matches!(files.sources.get(*h), Some(Source::Svg(_)))), "all shown"); + assert_eq!(files.left_out(), [linked_note()]); + } + + /// An SVG file read once is kept by its file wherever it was read: another spelling of its + /// href doesn't read it again, past the limits too. + #[test] + fn an_svg_file_is_read_once_past_the_limits() { + let served = [("a.svg", linking(&["one.png"])), ("one.png", png())]; + let (log, files) = read_links(&["a.svg", "./a.svg", "%61.svg"], &served, MAX_NESTED_SVG_READS, 0); + assert_eq!(log, ["a.svg"]); + assert!(["a.svg", "./a.svg", "%61.svg"].iter().all(|h| matches!(files.sources.get(*h), Some(Source::Svg(_))))); + // Read inside a linked SVG file, where its read passes the text limit: left out there, + // and shown, not read again, where the imported SVG links to it. + let x = linking(&["a.svg"]); + let served = [("x.svg", x.clone()), ("a.svg", linking(&["one.png"])), ("one.png", png())]; + let (log, files) = read_links(&["x.svg", "./a.svg"], &served, 0, MAX_NESTED_SVG_TEXT - x.len() as u64); + assert_eq!(log, ["x.svg", "a.svg"]); + let Some(Source::Svg(x)) = files.sources.get("x.svg") else { panic!("x.svg is shown") }; + assert!(x.sources.is_empty(), "{:?}", x.sources.keys()); + let Some(Source::Svg(a)) = files.sources.get("./a.svg") else { panic!("a.svg is shown") }; + assert!(a.sources.is_empty(), "{:?}", a.sources.keys()); + assert_eq!(files.left_out().len(), 2, "{:?}", files.left_out()); + } + /// The nested SVG images read, decoded or not, take at most [`MAX_NESTED_SVG_TEXT`] bytes of /// text together: an image whose text goes past it is left out and noted. A broken image's /// text counts too, and its decoded place is given back. diff --git a/crates/svg/src/import/prepass.rs b/crates/svg/src/import/prepass.rs index 95c0d57203..3d1b04ad60 100644 --- a/crates/svg/src/import/prepass.rs +++ b/crates/svg/src/import/prepass.rs @@ -109,7 +109,7 @@ impl Edits { /// `svg` with the edits made; overlapping ones and ranges off character boundaries are /// skipped. - fn apply(mut self, svg: &str) -> Cow<'_, str> { + pub(super) fn apply(mut self, svg: &str) -> Cow<'_, str> { self.list.append(&mut self.id_edits); for (at, has_style, decls) in std::mem::take(&mut self.styles).into_values() { self.insert(at, if has_style { decls } else { format!(" style=\"{}\"", decls.strip_prefix(';').unwrap_or(&decls)) }); diff --git a/crates/svg/src/import/text.rs b/crates/svg/src/import/text.rs index f7ba77cea2..4bb79d6d78 100644 --- a/crates/svg/src/import/text.rs +++ b/crates/svg/src/import/text.rs @@ -40,7 +40,7 @@ use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{CharStyle, Dash, Justify, LineCap, LineJoin, ParaDirection, ParaStyle, StrokeLayer, TextKind, TextObject, TextRun}; use vectorcraft_geom::kurbo::ParamCurveArclen; use vectorcraft_geom::{Affine, BezPath, PathData, Point, Rect}; -use vectorcraft_text::{FontDb, TextLayout}; +use vectorcraft_text::{FontDb, PositionedGlyph, TextLayout, spacing_scale}; use super::css::{Styles, XNode}; use super::{DEFAULT_FONT_SIZE, PT_PER_IN, href, vector_effect}; @@ -378,24 +378,29 @@ fn clip_uses( Some(s) => own_transform(&cx.css, s), None => t.attribute("transform").unwrap_or("").to_string(), }; - // One element can carry one clip path. The text's own clip path is in the text's user space - // and wins; a clip path of the `` is in the ``'s, so the text's transform moves - // to the importer instead. - let clipped = |n: XNode| cx.css.own(n, "clip-path").is_some_and(|v| v.trim() != "none"); + // One element can carry one clip path. The text's own clip path is in the text's user space; + // a clip path of the `` is in the ``'s. With only the ``'s, the text's + // transform moves to the importer. With both, the placeholder's clip path is one that + // holds both ([`both_clips`]). + let clipped = |n: XNode| cx.css.own(n, "clip-path").filter(|v| v.trim() != "none"); let id = format!("{}{i}-{k}", slots.prefix); - let transform = if style_t.is_some_and(clipped) { - if clipped(style_u) { - let label = u.attribute("id").map_or_else(|| "a use of a text".to_string(), |id| format!("'{id}'")); - warnings.push(format!("clip path of {label} in a clip path ignored: the text's own applies")); - } - format!("{placed} {text_xf}") - } else { - slots.inner.insert(id.clone(), parse_transform(Some(&text_xf))); - placed - }; let props = clip_props(&cx.css, style_t, Some(style_u)); let mut out = String::new(); - clip_placeholder(&mut out, q, &id, &transform, &props, u, marker); + match (style_t.and_then(clipped), clipped(style_u)) { + (Some(text_clip), Some(use_clip)) => { + let both = both_clips(&mut out, q, &id, &text_clip, &use_clip, parse_transform(Some(&text_xf)), marker); + let props = match (both, props.split_once(';')) { + (Some(both), Some((_, rest))) => format!("clip-path:url(#{both});{rest}"), + _ => props, + }; + clip_placeholder(&mut out, q, &id, &format!("{placed} {text_xf}"), &props, u, marker); + } + (Some(_), None) => clip_placeholder(&mut out, q, &id, &format!("{placed} {text_xf}"), &props, u, marker), + (None, _) => { + slots.inner.insert(id.clone(), parse_transform(Some(&text_xf))); + clip_placeholder(&mut out, q, &id, &placed, &props, u, marker); + } + } // Another `` can still show this one by its id: a copy of it stays in a ``, which // the clip path leaves out, with the properties style rules gave it written out. if u.attribute("id").is_some() { @@ -654,6 +659,42 @@ fn clip_placeholder(out: &mut String, q: &str, id: &str, transform: &str, props: let _ = write!(out, " d=\"M{} {}H{}V{}H{}Z\"/>", b.x0, b.y0, b.x1, b.y1, b.x0); } +/// Write, in a `` (which a clip path leaves out), a clip path for the placeholder `id` of a +/// text with bounds `b` and transform `text_xf` shown by a ``, when both have a clip path: +/// it clips by the text's clip path `text_clip` in the text's user space and by the ``'s +/// `use_clip` in the ``'s, each on a rectangle over the text's bounds there, so a clip path in +/// bounding box units measures the text. Its id, or `None` when `text_xf` can't be inverted (the +/// text then draws nothing). +fn both_clips(out: &mut String, q: &str, id: &str, text_clip: &str, use_clip: &str, text_xf: Affine, b: Rect) -> Option { + let det = text_xf.determinant(); + if !det.is_finite() || det == 0.0 { + return None; + } + let [a, b2, c, d, e, f] = text_xf.inverse().as_coeffs(); + let ub = text_xf.transform_rect_bbox(b); + let (id_u, id_t) = (format!("{id}-u"), format!("{id}-t")); + let rect = |out: &mut String, clip: &str, r: Rect| { + let _ = write!( + out, + "<{q}path style=\"transform:{IDENTITY};clip-path:{};display:inline\" d=\"M{} {}H{}V{}H{}Z\"/>", + xml_escape(clip), + r.x0, + r.y0, + r.x1, + r.y1, + r.x0 + ); + }; + // The ``'s clip path, moved back by the inverse of the text's transform from the + // placeholder's user space to the ``'s. + let _ = write!(out, "<{q}defs><{q}clipPath id=\"{}\" style=\"transform:matrix({a} {b2} {c} {d} {e} {f})\">", xml_escape(&id_u)); + rect(out, use_clip, ub); + let _ = write!(out, "<{q}clipPath id=\"{}\" style=\"clip-path:url(#{})\">", xml_escape(&id_t), xml_escape(&id_u)); + rect(out, text_clip, b); + let _ = write!(out, ""); + Some(id_t) +} + /// Write the placeholder group for text `t` (namespace prefix `q`), slot `index`, with the text's /// id when `with_id`. #[allow(clippy::too_many_arguments)] @@ -965,6 +1006,12 @@ impl Ctx { "normal".into() } + /// Whether the computed `direction` of element `n` is `rtl`, in any letter case (CSS keywords + /// are ASCII case-insensitive, https://www.w3.org/TR/css-values-3/#keywords). + fn is_rtl(&self, n: XNode) -> bool { + self.prop(n, "direction").is_some_and(|d| d.trim().eq_ignore_ascii_case("rtl")) + } + /// The Character Direction of the characters of element `n` inside a ``, and what it /// leaves out (SVG 1.1 §10.7.4, /// https://www.w3.org/TR/SVG11/text.html#RelationshipWithBi-directionality, and CSS Writing @@ -987,7 +1034,7 @@ impl Ctx { let inherited = parent.as_ref().and_then(|p| p.style.char_direction); let mut notes = parent.map_or_else(Vec::new, |p| p.bidi_notes.clone()); let rtl = |rtl: bool| Some(if rtl { ParaDirection::RightToLeft } else { ParaDirection::LeftToRight }); - let own = || rtl(self.prop(n, "direction").is_some_and(|d| d.trim() == "rtl")); + let own = || rtl(self.is_rtl(n)); let (dir, note) = match bidi.as_str() { "embed" => (own(), None), "bidi-override" => (own(), Some(BIDI_OVERRIDE)), @@ -1376,7 +1423,7 @@ impl Ctx { // With `unicode-bidi: plaintext`, the text runs in the direction of its first strong // character, and each paragraph in that of its own ([`pin_first_strong`]). let plaintext = self.unicode_bidi(t) == "plaintext"; - let rtl = if plaintext { self.first_strong_rtl(t) == Some(true) } else { self.prop(t, "direction").is_some_and(|d| d.trim() == "rtl") }; + let rtl = if plaintext { self.first_strong_rtl(t) == Some(true) } else { self.is_rtl(t) }; let pin = |obj: &mut TextObject| { pin_direction(obj, rtl); if plaintext { @@ -1403,7 +1450,7 @@ impl Ctx { let chunk: String = cs.chars[i..end].iter().map(|c| c.0).collect(); text_first_strong_rtl(&chunk) == Some(true) }; - let rtl = if plaintext { chunk_rtl() } else { self.prop(el, "direction").is_some_and(|d| d.trim() == "rtl") }; + let rtl = if plaintext { chunk_rtl() } else { self.is_rtl(el) }; if !vertical && rtl { 1.0 - a } else { a } }; let anchor = anchor_of(0); @@ -1460,7 +1507,12 @@ impl Ctx { obj.xf = Affine::IDENTITY; } else { let origin = Point::new(x[0].unwrap_or(0.0) + dx[0], y[0].unwrap_or(0.0) + dy[0]); - let (justify, left, starts) = lines(&mut cells, &x, &y, &dx, &dy, &anchor_of, &pin, origin.x, &mut breaks); + let (justify, left, starts, unplaced) = lines(&mut cells, &x, &y, &dx, &dy, &anchor_of, &pin, origin.x, &mut breaks); + if unplaced > 0 { + warnings.push(format!( + "{label}: {unplaced} absolutely placed character(s) between characters of the other direction keep their place in the line" + )); + } obj.para.justify = justify; obj.xf = Affine::translate((finite(left), finite(origin.y))); // Lines anchored differently or at different x (paragraphs aligned or indented @@ -1593,7 +1645,8 @@ fn leading_tolerance(spacing: f64) -> f64 { /// character, alignment (as for [`justify_of`]) and anchor x. `anchor_of` gives where the chunk /// starting at a character sits on its anchor, and `pin` sets the paragraph directions of the /// text ([`pin_direction`]). When characters are placed on their own, every line is left-aligned -/// and its anchor x is its left edge. +/// and its anchor x is its left edge. Also returns how many absolutely placed characters kerning +/// cannot put on their x. #[allow(clippy::too_many_arguments)] fn lines( cells: &mut [Cell], @@ -1605,7 +1658,7 @@ fn lines( pin: &dyn Fn(&mut TextObject), x0: f64, breaks: &mut Vec, -) -> (Justify, f64, Vec<(usize, f64, f64)>) { +) -> (Justify, f64, Vec<(usize, f64, f64)>, usize) { let n = cells.len(); let y0 = y[0].unwrap_or(0.0) + dy[0]; let (mut base, mut cur) = (y0, y0); @@ -1648,7 +1701,7 @@ fn lines( } if targets.is_empty() { let starts = lines.iter().map(|&(s, lx)| (s, anchor_of(s), lx)).collect(); - return (justify_of(anchor_of(0)), x0, starts); + return (justify_of(anchor_of(0)), x0, starts, 0); } // Absolutely placed characters: lay the text out left-aligned and kern each one onto its x. // SVG anchors every absolutely placed chunk on its own, so a chunk not anchored at its left @@ -1658,59 +1711,122 @@ fn lines( // Chunk starts in order: line starts and absolutely placed characters. let mut starts: Vec = lines.iter().map(|l| l.0).chain(targets.iter().map(|t| t.0)).collect(); starts.sort_unstable(); - // The left and right edges of the chunk starting at character `s`, from each character's pen and end. - let edges = |s: usize, pens: &[Option], ends: &[Option]| { + // The left and right edges of the chunk starting at character `s`, and the character drawn at its left. + let edges = |s: usize, pens: &[Option]| { let e = starts.get(starts.partition_point(|&c| c <= s)).copied().unwrap_or(n); - let left = (s..e).filter_map(|j| pens[j]).fold(f64::INFINITY, f64::min); - let right = (s..e).filter_map(|j| ends[j]).fold(f64::NEG_INFINITY, f64::max); - (left.is_finite() && right.is_finite()).then_some((left, right)) + let (mut left, mut right, mut at) = (f64::INFINITY, f64::NEG_INFINITY, s); + for (j, p) in pens.iter().enumerate().take(e).skip(s) { + let Some(p) = p else { continue }; + if p.start < left { + (left, at) = (p.start, j); + } + right = right.max(p.end); + } + (left.is_finite() && right.is_finite()).then_some((left, right, at)) }; let mut line_left: Vec = lines.iter().map(|l| l.1).collect(); + // Where each line's first chunk's left edge goes. + let mut first_left: Vec = vec![]; // Where each absolutely placed character's pen goes, from the left edge of its line's first chunk. let mut wants: Vec<(usize, f64)> = vec![]; + // Absolutely placed characters drawn right next to a placed neighbor with no kerning between + // them (a left-to-right character between right-to-left ones): they stay where the layout puts them. + let mut unplaced = 0; // Kerning changes shaping (pair kerning is off for manually kerned characters): repeat until // every character sits on its x. for round in 0..4 { let (runs, bytes) = assemble(cells, breaks); let mut text = with_runs(runs.0); pin(&mut text); - let (pens, ends) = pens(&measure(&text), &bytes); + let pens = pens(&measure(&text), &bytes, cells); // The edges of each line's first chunk, found once a round. - let first: Vec> = lines.iter().map(|&(s, _)| edges(s, &pens, &ends)).collect(); + let first: Vec> = lines.iter().map(|&(s, _)| edges(s, &pens)).collect(); if round == 0 { // The chunks as they lie before any is moved: each one's left edge on its anchor. - let left_at = |s: usize, x: f64, chunk: Option<(f64, f64)>| chunk.map_or(x, |(left, right)| x - anchor_of(s) * (right - left)); - let first_left: Vec = lines.iter().zip(&first).map(|(&(s, lx), &chunk)| left_at(s, lx, chunk)).collect(); + let left_at = |s: usize, x: f64, chunk: Option<(f64, f64, usize)>| chunk.map_or(x, |(left, right, _)| x - anchor_of(s) * (right - left)); + first_left = lines.iter().zip(&first).map(|(&(s, lx), &chunk)| left_at(s, lx, chunk)).collect(); wants = targets .iter() .map(|&(i, x)| { - let chunk = edges(i, &pens, &ends); + let chunk = edges(i, &pens); // The pen of a right-to-left chunk's first character is right of the chunk's left edge. - let pen = pens[i].zip(chunk).map_or(0.0, |(p, (left, _))| p - left); + let pen = pens[i].zip(chunk).map_or(0.0, |(p, (left, ..))| p.start - left); (i, left_at(i, x, chunk) + pen - first_left[line_of(i)]) }) .collect(); - // A line's layout starts at the line's left edge, and its first chunk's left edge is `left` from there. - line_left = first_left.iter().zip(&first).map(|(&x, chunk)| x - chunk.map_or(0.0, |(left, _)| left)).collect(); } - let (mut line, mut moved, mut worst) = (usize::MAX, 0.0, 0.0f64); - for &(i, want) in &wants { - let l = line_of(i); - if l != line { - (line, moved) = (l, 0.0); + // A line's layout starts at the line's left edge, and its first chunk's left edge is `left` + // from there (right-to-left kerning can move that chunk). + line_left = first_left.iter().zip(&first).map(|(&x, chunk)| x - chunk.map_or(0.0, |(left, ..)| left)).collect(); + // Kerning a character widens its advance to the right: the glyphs drawn right of it move + // right, and so does a right-to-left glyph's own left edge (its kerning is at its left). In + // drawing order the kerning before an absolutely placed character is a cut after the + // character before it (before that character when it runs right to left), and what is drawn + // after the cut moves. Places in drawing order are doubled (from 2) to put cuts between them. + // Each gap between two placed characters drawn one after the other takes the kerning of one + // cut in it, so placing a character moves none placed before it. Kerning is drawn at the + // character's horizontal scale, so each correction is divided by it. + let mut worst = 0.0f64; + let mut from = 0; + unplaced = 0; + while from < wants.len() { + let l = line_of(wants[from].0); + let to = from + wants[from..].partition_point(|&(i, _)| line_of(i) == l); + let on_line = &wants[from..to]; + from = to; + let Some((p0, _, at)) = first[l] else { continue }; + let Some(home) = pens[at].map(|p| 2 * p.rank + 2) else { continue }; + // A character drawn as part of the glyph before it (a mark) is kerned where that glyph is. + // The kerning stays on the character just before the placed one: a mark whose kerning + // differs from its base's is drawn as a glyph of its own, and kerning the base would put + // the space between the base and its mark. + // Each search stops at the nearest earlier character with a glyph, at the latest the + // placed character before it, so the searches of a line read each character once. + let mut cuts: Vec<(usize, usize)> = on_line + .iter() + .filter(|&&(i, _)| pens[i].is_some()) + .filter_map(|&(i, _)| (lines[l].0..i).rev().find_map(|j| pens[j]).map(|k| (2 * k.rank + if k.rtl { 1 } else { 3 }, i - 1))) + .collect(); + cuts.sort_unstable(); + let mut points: Vec<(usize, f64, f64)> = + on_line.iter().filter_map(|&(i, want)| pens[i].map(|p| (2 * p.rank + 2, p.start, want))).collect(); + points.sort_by_key(|p| p.0); + // The character kerned at the first cut between places `a` and `b`. + let cut = |a: usize, b: usize| cuts.get(cuts.partition_point(|c| c.0 <= a)).filter(|c| c.0 < b).map(|c| c.1); + let split = points.partition_point(|p| p.0 < home); + // Drawn right of the line's first chunk: kerning moves the character away from it. + let (mut prev, mut moved) = (home, 0.0); + for &(place, start, want) in &points[split..] { + if let Some(k) = cut(prev, place) { + let d = want - (start - p0 + moved); + cells[k].kern += d / spacing_scale(&cells[k].style, false); + moved += d; + worst = worst.max(d.abs()); + } else { + unplaced += 1; + } + prev = place; + } + // Drawn left of it: kerning moves the chunk (and what lies between) away from the character. + (prev, moved) = (home, 0.0); + for &(place, start, want) in points[..split].iter().rev() { + if let Some(k) = cut(place, prev) { + let d = start - p0 - moved - want; + cells[k].kern += d / spacing_scale(&cells[k].style, false); + moved += d; + worst = worst.max(d.abs()); + } else { + unplaced += 1; + } + prev = place; } - let (Some(p), Some((p0, _))) = (pens[i], first[l]) else { continue }; - let d = want - (p - p0 + moved); - cells[i - 1].kern += d; - moved += d; - worst = worst.max(d.abs()); } if worst < 0.01 { break; } } let starts = lines.iter().zip(&line_left).map(|(&(s, _), &lx)| (s, 0.0, lx)).collect(); - (Justify::Left, line_left[0], starts) + (Justify::Left, line_left[0], starts, unplaced) } /// Centred and right-aligned lines of point type `obj` where a reader draws them. `text-anchor` @@ -1869,13 +1985,40 @@ fn advance(t: &TextObject) -> f64 { measure(t).glyphs.iter().map(|g| g.advance).sum() } -/// Pen x (start) and end x of the glyph that starts at each character's byte offset. -fn pens(lay: &TextLayout, bytes: &[usize]) -> (Vec>, Vec>) { - let mut at: HashMap = HashMap::with_capacity(lay.glyphs.len()); - for g in &lay.glyphs { - at.entry(g.byte).or_insert((g.origin.x, g.origin.x + g.advance)); +/// Where the glyph that starts a character is drawn on a line of point type. +#[derive(Clone, Copy)] +struct Pen { + /// Its left edge. Manual kerning on a right-to-left glyph is at its left, and the glyph is + /// drawn right of it: its left edge is past that kerning. + start: f64, + /// The right edge of its advance. + end: f64, + /// Its place in the order its line is drawn in, from the left. + rank: usize, + rtl: bool, +} + +/// The [`Pen`] of the glyph that starts at each character's byte offset (`bytes`, parallel to `cells`). +fn pens(lay: &TextLayout, bytes: &[usize], cells: &[Cell]) -> Vec> { + // A line's glyphs are laid out in the order they are drawn. + let mut at: HashMap = HashMap::with_capacity(lay.glyphs.len()); + for (rank, g) in lay.glyphs.iter().enumerate() { + at.entry(g.byte).or_insert((rank, g)); } - bytes.iter().map(|b| at.get(b).map_or((None, None), |&(s, e)| (Some(s), Some(e)))).unzip() + bytes + .iter() + .zip(cells) + .map(|(b, c)| { + let &(rank, g) = at.get(b)?; + let mut start = g.origin.x; + if g.rtl { + let st = c.final_style(); + let kern = st.kerning.unwrap_or(0.0) / 1000.0 * st.size * spacing_scale(&st, false); + start += finite(kern); + } + Some(Pen { start, end: g.origin.x + g.advance, rank, rtl: g.rtl }) + }) + .collect() } type Key = (Option, Option); diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index b035e6cd10..3272c999fc 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -366,6 +366,14 @@ pub enum SvgError { /// nested-image expansion bombs, #3564). #[error("the SVG expands to more than {0} nested SVG images")] TooManyImages(usize), + /// The style values the reader would copy into the elements the SVG expands to, `` + /// copies and SVG images included, add up to more than this many megabytes. + #[error("the SVG's styles expand to more than {0} MB")] + StylesTooLarge(usize), + /// Matching the style sheets' selectors against the elements the SVG expands to, `` + /// copies and SVG images included, takes more tests than the reader allows. + #[error("the SVG's style sheets take too long to match")] + StylesTooComplex, } /// Export a document as an SVG string (linked images are not returned: see [`export_full`]). diff --git a/crates/svg/tests/it/blend_export.rs b/crates/svg/tests/it/blend_export.rs index dd86f318f5..ec947041b0 100644 --- a/crates/svg/tests/it/blend_export.rs +++ b/crates/svg/tests/it/blend_export.rs @@ -202,6 +202,212 @@ fn a_mask_region_keeps_the_shadows_of_the_masked_art() { } } +fn drop_shadow() -> vectorcraft_doc::Effect { + vectorcraft_doc::Effect { + id: "stylize.dropShadow".into(), + params: serde_json::json!({"x": 15, "y": 15, "blur": 0, "opacity": 100}), + visible: true, + } +} + +/// Whether every `` in `svg` starts with a hidden, unpainted rectangle over its mask's region, +/// and whether any does. +fn spanning_rects(svg: &str) -> (bool, bool) { + let spans = masked_group_spans(svg); + (spans.iter().all(|s| *s), spans.iter().any(|s| *s)) +} + +/// For each `` in `svg`, in document order, whether it starts with a hidden, unpainted +/// rectangle over its mask's region. +fn masked_group_spans(svg: &str) -> Vec { + let xml = roxmltree::Document::parse_with_options(svg, roxmltree::ParsingOptions { allow_dtd: true, ..Default::default() }).unwrap(); + let spans: Vec = xml + .descendants() + .filter(|n| n.has_tag_name("g") && n.has_attribute("mask")) + .map(|group| { + let id = group.attribute("mask").unwrap().trim_start_matches("url(#").trim_end_matches(')'); + let mask = xml.descendants().find(|n| n.has_tag_name("mask") && n.attribute("id") == Some(id)).unwrap(); + let first = group.children().find(|n| n.is_element()).unwrap(); + first.has_tag_name("rect") + && first.attribute("fill") == Some("none") + && first.attribute("visibility") == Some("hidden") + && ["x", "y", "width", "height"].iter().all(|a| first.attribute(*a).is_some() && first.attribute(*a) == mask.attribute(*a)) + }) + .collect(); + assert!(!spans.is_empty(), "no masked group in {svg}"); + spans +} + +/// The number of paths `svg` imports as. +fn imported_paths(svg: &str) -> usize { + let (back, warnings) = vectorcraft_svg::import_with_report(svg).unwrap(); + assert!(warnings.is_empty(), "{warnings:?}"); + let mut paths = 0; + back.walk(|n| paths += usize::from(n.path_data().is_some())); + paths +} + +/// A masked group whose content holds a raster effect (a drop shadow, blur, glow or feather, which +/// paint past the shapes) starts with a hidden, unpainted rectangle over the mask's region, so that +/// a reader that draws a masked group only inside the box of its shapes still draws it. Art without +/// one gets none, brushed strokes (written as shapes) included, nor does an object whose own shadow +/// is drawn outside the mask. Import leaves the rectangle out. +#[test] +fn a_masked_group_spans_its_region_when_its_art_paints_past_its_shapes() { + // How the red square sits under the mask. + #[derive(Debug, Clone, Copy)] + enum Case { + Alone, + InGroup, + InNestedGroup, + FillEffect, + HiddenFill, + UnpaintedStroke, + HiddenInGroup, + Brushed, + InSymbol, + OverriddenSymbol, + InBlend, + } + use Case::*; + for (case, shadowed, want) in [ + (InGroup, true, true), + (InGroup, false, false), + (Alone, true, false), + (Alone, false, false), + (InNestedGroup, true, true), + (FillEffect, true, true), + (FillEffect, false, false), + // A fill or stroke that isn't written doesn't count. + (HiddenFill, true, false), + (UnpaintedStroke, true, false), + (HiddenInGroup, true, false), + (Brushed, false, false), + (Brushed, true, true), + (InSymbol, true, true), + (InSymbol, false, false), + // An unpainted fill in a dynamic symbol's art that the instance paints counts. + (OverriddenSymbol, true, true), + (OverriddenSymbol, false, false), + (InBlend, true, true), + (InBlend, false, false), + ] { + let mut d = Document::new(100.0, 60.0); + let mut red = rect(&mut d, Rect::new(10.0, 10.0, 30.0, 30.0), [255, 0, 0]); + if matches!(case, Brushed) { + let mut stroke = vectorcraft_doc::StrokeLayer::new(Paint::solid(Color::rgb8(0, 0, 200)), 8.0); + stroke.brush = Some("Bristle Round".into()); + red.appearance.items.push(vectorcraft_doc::AppearanceItem::Stroke(stroke)); + } + if matches!(case, UnpaintedStroke) { + red.appearance.items.push(vectorcraft_doc::AppearanceItem::Stroke(vectorcraft_doc::StrokeLayer::new(Paint::None, 8.0))); + } + if shadowed { + match case { + FillEffect | HiddenFill | OverriddenSymbol => red.appearance.items[0].effects_mut().push(drop_shadow()), + UnpaintedStroke => red.appearance.items.last_mut().unwrap().effects_mut().push(drop_shadow()), + _ => red.appearance.effects.push(drop_shadow()), + } + } + if matches!(case, HiddenFill) + && let vectorcraft_doc::AppearanceItem::Fill(f) = &mut red.appearance.items[0] + { + f.visible = false; + } + if matches!(case, OverriddenSymbol) { + red.appearance.set_fill(Paint::None); + } + let group = |d: &mut Document, n: Node| Node::group(d.alloc_id(), vec![n.into()]); + let mut masked = match case { + Alone | FillEffect => red, + HiddenFill | UnpaintedStroke => group(&mut d, red), + InGroup | Brushed => group(&mut d, red), + InNestedGroup => { + let inner = group(&mut d, red); + group(&mut d, inner) + } + HiddenInGroup => { + red.visible = false; + group(&mut d, red) + } + InSymbol => { + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Square".into(), art: std::sync::Arc::new(red) }); + let instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Square".into(), xf: vectorcraft_geom::Affine::IDENTITY }); + group(&mut d, instance) + } + OverriddenSymbol => { + d.symbols.push(vectorcraft_doc::Symbol { dynamic: true, name: "Square".into(), art: std::sync::Arc::new(red) }); + let mut instance = + Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Square".into(), xf: vectorcraft_geom::Affine::IDENTITY }); + let fill = Some(Paint::solid(Color::rgb8(255, 0, 0))); + instance.extras_mut().symbol_overrides.push(vectorcraft_doc::symbol_overrides::SymbolOverride { fill, ..Default::default() }); + group(&mut d, instance) + } + InBlend => { + let mut blue = rect(&mut d, Rect::new(60.0, 10.0, 80.0, 30.0), [0, 0, 255]); + blue.appearance.effects = red.appearance.effects.clone(); + let blend = Node::new(d.alloc_id(), NodeKind::Blend { children: vec![red.into(), blue.into()], spec: Default::default() }); + group(&mut d, blend) + } + }; + let art = rect(&mut d, Rect::new(10.0, 10.0, 20.0, 30.0), [255, 255, 255]); + masked.extras_mut().mask = Some(Box::new(OpacityMask::new(art, false))); + add(&mut d, masked); + let svg = export(&d, &ExportOptions::default()); + assert_eq!(spanning_rects(&svg).0, want, "{case:?}, shadowed {shadowed}:\n{svg}"); + if matches!(case, Alone | InGroup | InNestedGroup | FillEffect) { + // The red square alone: no rectangle of the region's size comes back. + assert_eq!(imported_paths(&svg), 1, "{case:?}, shadowed {shadowed}:\n{svg}"); + } + } + // Type can't be measured, so its mask's region covers any artwork: a group of type gets the + // rectangle only when it holds a raster effect, on the type or on a path beside it. + for (shadowed, path_shadowed) in [(false, false), (true, false), (false, true)] { + let mut d = Document::new(80.0, 40.0); + let style = CharStyle { size: 24.0, fill: Paint::solid(Color::BLACK), ..CharStyle::default() }; + let mut t = Node::new(d.alloc_id(), NodeKind::Text(Box::new(TextObject::point(Point::new(5.0, 30.0), "Wide", style)))); + if shadowed { + t.appearance.effects.push(drop_shadow()); + } + let mut red = rect(&mut d, Rect::new(50.0, 5.0, 60.0, 15.0), [255, 0, 0]); + if path_shadowed { + red.appearance.effects.push(drop_shadow()); + } + let mut group = Node::group(d.alloc_id(), vec![t.into(), red.into()]); + let art = rect(&mut d, Rect::new(0.0, 0.0, 40.0, 40.0), [255, 255, 255]); + group.extras_mut().mask = Some(Box::new(OpacityMask::new(art, false))); + add(&mut d, group); + let svg = export(&d, &ExportOptions::default()); + let want = shadowed || path_shadowed; + assert_eq!(svg.contains("visibility=\"hidden\""), want, "type {shadowed}, path {path_shadowed}:\n{svg}"); + } +} + +/// In a knockout group, each element is drawn inside one mask of the elements above it. When the +/// element inside a mask's group has a drop shadow, that group starts with the same hidden, +/// unpainted rectangle over the region, the other groups don't, and import leaves it out. +#[test] +fn a_knockout_group_spans_its_masks_when_an_element_paints_past_its_shapes() { + for shadowed in [false, true] { + let mut d = Document::new(60.0, 60.0); + let mut below = rect(&mut d, Rect::new(5.0, 5.0, 25.0, 25.0), [200, 0, 0]); + if shadowed { + below.appearance.effects.push(drop_shadow()); + } + let mut middle = rect(&mut d, Rect::new(15.0, 15.0, 35.0, 35.0), [0, 200, 0]); + middle.opacity = 0.5; + let mut top = rect(&mut d, Rect::new(20.0, 5.0, 30.0, 40.0), [0, 0, 200]); + top.opacity = 0.5; + let mut group = Node::group(d.alloc_id(), vec![below.into(), middle.into(), top.into()]); + group.knockout = vectorcraft_doc::Knockout::On; + add(&mut d, group); + let svg = export(&d, &ExportOptions::default()); + // The bottom and middle elements are masked, in paint order; the top one isn't. + assert_eq!(masked_group_spans(&svg), [shadowed, false], "shadowed {shadowed}:\n{svg}"); + assert_eq!(imported_paths(&svg), 3, "shadowed {shadowed}:\n{svg}"); + } +} + /// Type is measured by its layout or its path, and a reader sets live type in its own font, so a /// mask or knockout over type keeps the region that covers any artwork. #[test] diff --git a/crates/svg/tests/it/clip_text.rs b/crates/svg/tests/it/clip_text.rs index a2dcb46156..bb92802e60 100644 --- a/crates/svg/tests/it/clip_text.rs +++ b/crates/svg/tests/it/clip_text.rs @@ -221,6 +221,27 @@ fn a_clip_path_on_a_use_of_a_text_is_in_the_use_s_user_space() { assert!(t.xf.translation().to_point().distance(Point::new(200.0, 160.0)) < 1e-9, "{:?}", t.xf); } +#[test] +fn a_use_and_the_text_it_shows_in_a_clip_path_both_clip() { + // The text's own clip keeps y < 120 of its user space; the ``'s keeps x < 250 of the + // ``'s, which the text's transform doesn't move. The glyphs keep only what both keep. + let body = r##" + + HI + + "##; + let (d, warnings) = import_with_report(&svg(body)).unwrap(); + let (clip, _) = clip_group(&top(&d)[0]); + let b = clip_bounds(clip); + assert!(b.x0 >= 200.0 - 1e-6 && near(b.x1, 250.0, 1e-6), "{b:?}"); + assert!(near(b.y1, 130.0, 1e-6) && b.y0 > 50.0, "{b:?}"); + // It clips by the glyphs, not their box: nothing between the stems of the H. + let (bp, _) = vectorcraft_effects::clip_outline(clip).unwrap(); + assert!(bp.contains(Point::new(b.x0 + 2.0, 110.0)), "on a stem"); + assert!(!bp.contains(Point::new(225.0, 100.0)), "between the stems"); + assert!(!warnings.iter().any(|w| w.contains("ignored")), "{warnings:?}"); +} + #[test] fn a_css_transform_places_a_text_in_a_clip_path() { let d = open( diff --git a/crates/svg/tests/it/image_orientation.rs b/crates/svg/tests/it/image_orientation.rs index fbf412a0bb..d9de61290b 100644 --- a/crates/svg/tests/it/image_orientation.rs +++ b/crates/svg/tests/it/image_orientation.rs @@ -69,13 +69,21 @@ fn jpeg(orientation: Option) -> Vec { /// an Orientation tag (274) of `orientation`. Its RowsPerStrip (278) value is at byte [`ROWS_AT`] /// and its PlanarConfiguration (284, 1) value at [`PLANAR_AT`]. fn tiff(w: u32, h: u32, samples: u16, data: &[u8], orientation: u16) -> Vec { - let entries: u32 = if samples == 2 { 12 } else { 11 }; + tiff_at(w, h, samples, data, orientation, None) +} + +/// [`tiff`], declaring `ppi` (horizontal, vertical pixels per inch) when given, with XResolution +/// (282), YResolution (283) and ResolutionUnit (296, inches). +fn tiff_at(w: u32, h: u32, samples: u16, data: &[u8], orientation: u16, ppi: Option<(u32, u32)>) -> Vec { + let entries = 11 + u32::from(samples == 2) + 3 * u32::from(ppi.is_some()); let ifd_end = 8 + 2 + entries * 12 + 4; let bits_at = ifd_end; - let data_at = bits_at + if samples > 2 { 2 * u32::from(samples) } else { 0 }; + let ppi_at = bits_at + if samples > 2 { 2 * u32::from(samples) } else { 0 }; + let data_at = ppi_at + if ppi.is_some() { 16 } else { 0 }; let entry = |tag: u16, kind: u16, count: u32, value: u32| { [&tag.to_le_bytes()[..], &kind.to_le_bytes(), &count.to_le_bytes(), &value.to_le_bytes()].concat() }; + let resolution = |tags: [(u16, u16, u32); 2]| ppi.map(|_| tags.map(|(tag, kind, value)| entry(tag, kind, 1, value))).into_iter().flatten(); // Two SHORTs fit in the entry; more are written after the directory. let bits = match samples { 1 => 8, @@ -97,9 +105,11 @@ fn tiff(w: u32, h: u32, samples: u16, data: &[u8], orientation: u16) -> Vec entry(277, 3, 1, u32::from(samples)), entry(278, 4, 1, h), entry(279, 4, 1, u32::try_from(data.len()).unwrap()), - entry(284, 3, 1, 1), ] .into_iter() + .chain(resolution([(282, 5, ppi_at), (283, 5, ppi_at + 8)])) + .chain([entry(284, 3, 1, 1)]) + .chain(ppi.map(|_| entry(296, 3, 1, 2))) .chain(extra) { out.extend(e); @@ -110,6 +120,11 @@ fn tiff(w: u32, h: u32, samples: u16, data: &[u8], orientation: u16) -> Vec out.extend(8u16.to_le_bytes()); } } + if let Some((x, y)) = ppi { + for v in [x, 1, y, 1] { + out.extend(v.to_le_bytes()); + } + } assert_eq!(out.len(), data_at as usize); out.extend(data); out @@ -276,3 +291,88 @@ fn a_turned_jpeg_in_an_svg_image_imports_upright() { let px = pixels(&d, &im); assert!(red(px.get_pixel(4, 3)) && !red(px.get_pixel(4, 12))); } + +/// [`jpeg`] with its JFIF segment declaring `x` × `y` pixels per inch. +fn jpeg_at(orientation: Option, (x, y): (u16, u16)) -> Vec { + let mut jpg = jpeg(orientation); + let jfif = jpg.windows(5).position(|w| w == b"JFIF\0").unwrap(); + jpg[jfif + 7] = 1; + jpg[jfif + 8..jfif + 10].copy_from_slice(&x.to_be_bytes()); + jpg[jfif + 10..jfif + 12].copy_from_slice(&y.to_be_bytes()); + jpg +} + +/// The resolution the stored image of `im` declares. +fn stored_ppi(d: &Document, im: &ImageObject) -> Option<(f64, f64)> { + vectorcraft_doc::ppi::resolution(&d.images[&im.key].bytes) +} + +/// A raster that import writes again as PNG keeps the resolution its file declares, linked, as a +/// data URL and inside an SVG shown as an image: its axes swapped when the image turns a quarter, +/// in their order when it turns a half or is flipped. +#[test] +fn a_turned_raster_keeps_its_resolution() { + let dir = folder("ppi"); + for (orientation, ppi) in [(6, (150.0, 300.0)), (8, (150.0, 300.0)), (3, (300.0, 150.0)), (2, (300.0, 150.0))] { + let jpg = jpeg_at(Some(orientation), (300, 150)); + std::fs::write(dir.join("photo.jpg"), &jpg).unwrap(); + let data = format!("data:image/jpeg;base64,{}", base64_encode(&jpg)); + let inner = format!(r#""#); + let nested = format!("data:image/svg+xml;base64,{}", base64_encode(inner.as_bytes())); + for href in ["photo.jpg", data.as_str(), nested.as_str()] { + let (d, im) = import_one(&format!(r#""#), Some(&dir)); + let what = format!("orientation {orientation}, {}", &href[..href.len().min(20)]); + assert_eq!(d.images[&im.key].mime, "image/png", "{what}"); + assert_eq!(stored_ppi(&d, &im), Some(ppi), "{what}"); + } + } + let href = format!("data:image/tiff;base64,{}", base64_encode(&tiff_at(4, 2, 1, &[0, 0, 255, 255, 0, 0, 255, 255], 6, Some((300, 150))))); + let (d, im) = import_one(&format!(r#""#), None); + assert_eq!((im.width, im.height), (2, 4)); + assert_eq!(stored_ppi(&d, &im), Some((150.0, 300.0)), "a turned TIFF"); +} + +/// A TIFF that is not turned is written as PNG with the resolution it declares; a raster that +/// declares none is stored without one. +#[test] +fn an_upright_tiff_keeps_its_resolution() { + let gray = [0, 0, 255, 255, 0, 0, 255, 255]; + let href = format!("data:image/tiff;base64,{}", base64_encode(&tiff_at(4, 2, 1, &gray, 1, Some((300, 150))))); + let (d, im) = import_one(&format!(r#""#), None); + assert_eq!(d.images[&im.key].mime, "image/png"); + assert_eq!(stored_ppi(&d, &im), Some((300.0, 150.0))); + for bytes in [tiff(4, 2, 1, &gray, 1), jpeg(Some(6))] { + let href = format!("data:;base64,{}", base64_encode(&bytes)); + let (d, im) = import_one(&format!(r#""#), None); + assert_eq!(stored_ppi(&d, &im), None, "no resolution is made up"); + } +} + +/// A CMYK TIFF stored with its inks keeps its resolution, swapped when it turns a quarter. +#[test] +fn a_cmyk_tiff_keeps_its_resolution_turned_or_not() { + let (c, none) = ([255u8, 0, 0, 0], [0u8; 4]); + let data: Vec = [c, c, none, none, c, c, none, none].concat(); + for (orientation, ppi) in [(1, (300.0, 150.0)), (6, (150.0, 300.0))] { + let href = format!("data:image/tiff;base64,{}", base64_encode(&tiff_at(4, 2, 4, &data, orientation, Some((300, 150))))); + let (d, im) = import_one(&format!(r#""#), None); + assert_eq!(d.images[&im.key].mime, "image/tiff", "orientation {orientation}"); + assert!(d.images[&im.key].cmyk().is_some(), "orientation {orientation}: CMYK inks"); + assert_eq!(stored_ppi(&d, &im), Some(ppi), "orientation {orientation}"); + } +} + +/// A turned JPEG that a linked SVG file links to is turned too. +#[test] +fn a_turned_jpeg_linked_from_a_linked_svg_file_imports_upright() { + let dir = folder("nested-file"); + std::fs::create_dir_all(dir.join("sub")).unwrap(); + std::fs::write(dir.join("sub").join("photo.jpg"), jpeg(Some(6))).unwrap(); + let inner = r#""#; + std::fs::write(dir.join("sub").join("inner.svg"), inner).unwrap(); + let (d, im) = import_one(r#""#, Some(&dir)); + assert_eq!((im.width, im.height), (8, 16)); + assert!(near(placed(&im), Rect::new(20.0, 0.0, 60.0, 80.0)), "{:?}", placed(&im)); + let px = pixels(&d, &im); + assert!(red(px.get_pixel(4, 3)) && !red(px.get_pixel(4, 12))); +} diff --git a/crates/svg/tests/it/import_details.rs b/crates/svg/tests/it/import_details.rs index b043e4d985..4d6606eaa5 100644 --- a/crates/svg/tests/it/import_details.rs +++ b/crates/svg/tests/it/import_details.rs @@ -216,6 +216,185 @@ fn svgz_images_import_as_vector_art() { assert!((boxes[1].x0 - 100.0).abs() < 1e-6 && (boxes[1].height() - 20.0).abs() < 1e-6, "{boxes:?}"); } +/// An SVG file of 20 × 20 holding a 5 × 5 rectangle and `images`. +fn svg_file(images: &str) -> String { + format!(r#"{images}"#) +} + +/// Reads as [`read`] does, counting the reads of each file name. +fn counting(reads: &std::sync::Mutex>) -> impl Fn(&str) -> Option<(Vec, LinkInfo)> + Sync + '_ { + move |path: &str| { + if let Ok(mut reads) = reads.lock() { + reads.push(Path::new(path).file_name().unwrap().to_string_lossy().into_owned()); + } + read(path) + } +} + +/// A raster an SVG file links to is read from that file's folder and stays linked, in its place in +/// the SVG file's art. +#[test] +fn a_raster_linked_from_a_linked_svg_file_is_read_from_its_folder() { + let dir = folder("nested-link"); + let bytes = png(40, 20); + std::fs::write(dir.join("img").join("photo.png"), &bytes).unwrap(); + std::fs::write(dir.join("img").join("inner.svg"), svg_file(r#""#)).unwrap(); + let (d, w) = open_in(&dir, r#""#); + assert!(w.is_empty(), "{w:?}"); + assert_eq!(rects(&d), 1, "the SVG file's art"); + let [(_, im)] = images(&d)[..] else { panic!("{:?}", art(&d)) }; + let link = im.link.as_ref().unwrap(); + assert_eq!(Path::new(&link.path), dir.join("img").join("photo.png")); + assert_eq!(*d.images[&im.key].bytes, bytes, "the file's pixels"); + let b = im.xf.transform_rect_bbox(Rect::new(0.0, 0.0, 40.0, 20.0)); + assert!((b.x0 - 12.0).abs() < 1e-6 && (b.y0 - 14.0).abs() < 1e-6 && (b.width() - 10.0).abs() < 1e-6, "{b:?}"); +} + +/// One href in two SVG files of different folders names two files: each shows its own. +#[test] +fn one_href_in_svg_files_of_different_folders_shows_each_folders_file() { + let dir = folder("nested-same-href"); + let (outer, inner) = (png(4, 4), png(6, 6)); + std::fs::write(dir.join("photo.png"), &outer).unwrap(); + std::fs::write(dir.join("img").join("photo.png"), &inner).unwrap(); + std::fs::write(dir.join("img").join("inner.svg"), svg_file(r#""#)).unwrap(); + let (d, w) = open_in(&dir, r#""#); + assert!(w.is_empty(), "{w:?}"); + let [(_, a), (_, b)] = images(&d)[..] else { panic!("{:?}", art(&d)) }; + assert_eq!(Path::new(&a.link.as_ref().unwrap().path), dir.join("photo.png")); + assert_eq!(*d.images[&a.key].bytes, outer); + assert_eq!(Path::new(&b.link.as_ref().unwrap().path), dir.join("img").join("photo.png")); + assert_eq!(*d.images[&b.key].bytes, inner); +} + +/// A raster an SVG file links to that can't be read (missing, or refused by the reader) gets the +/// placeholder, stretched to its box, its link and a warning, as one the imported SVG links to. +#[test] +fn a_missing_raster_linked_from_a_linked_svg_file_keeps_a_placeholder() { + let dir = folder("nested-missing"); + std::fs::write(dir.join("img").join("secret.png"), png(4, 4)).unwrap(); + let links = r#""#; + std::fs::write(dir.join("img").join("inner.svg"), svg_file(links)).unwrap(); + let refusing = |path: &str| if path.ends_with("secret.png") { None } else { read(path) }; + let folder = dir.to_string_lossy(); + let body = r#""#; + let (d, w) = import_with(&svg(body), &ImportOptions { folder: Some(&folder), read: Some(&refusing) }).unwrap(); + for name in ["gone.png", "secret.png"] { + assert!(w.iter().any(|w| w.contains(&format!("'{name}' not found"))), "{name}: {w:?}"); + } + let [(_, gone), (_, secret)] = images(&d)[..] else { panic!("{:?}", art(&d)) }; + assert_eq!(Path::new(&gone.link.as_ref().unwrap().path), dir.join("img").join("gone.png")); + assert_eq!(Path::new(&secret.link.as_ref().unwrap().path), dir.join("img").join("secret.png")); + assert!(d.images[&gone.key].is_proxy() && d.images[&secret.key].is_proxy(), "placeholders, not the files"); + let b = gone.xf.transform_rect_bbox(Rect::new(0.0, 0.0, gone.width as f64, gone.height as f64)); + assert!((b.x0 - 12.0).abs() < 1e-6 && (b.width() - 10.0).abs() < 1e-6 && (b.height() - 5.0).abs() < 1e-6, "{b:?}"); +} + +/// An SVG file that links to itself, or to an SVG file that links back to it, is read once each +/// time it is shown: the link back gets the placeholder and a warning. +#[test] +fn svg_files_that_link_back_keep_a_placeholder_where_they_lead_back() { + let dir = folder("nested-cycle"); + std::fs::write(dir.join("img").join("self.svg"), svg_file(r#""#)).unwrap(); + std::fs::write(dir.join("img").join("a.svg"), svg_file(r#""#)).unwrap(); + std::fs::write(dir.join("img").join("b.svg"), svg_file(r#""#)).unwrap(); + let folder = dir.to_string_lossy(); + for (body, files, back) in [("img/self.svg", vec!["self.svg"], "self.svg"), ("img/a.svg", vec!["a.svg", "b.svg"], "./a.svg")] { + let reads = std::sync::Mutex::new(vec![]); + let counted = counting(&reads); + let body = format!(r#""#); + let (d, w) = import_with(&svg(&body), &ImportOptions { folder: Some(&folder), read: Some(&counted) }).unwrap(); + assert_eq!(*reads.lock().unwrap(), [files.clone(), files.clone()].concat()); + let warning = format!("linked image '{back}' leads back to an SVG file that shows it: a placeholder keeps its place until it is relinked"); + assert_eq!(w, [warning.clone(), warning]); + assert_eq!(rects(&d), 2 * files.len(), "each file's art once in each place"); + let found = images(&d); + assert_eq!(found.len(), 2); + for (_, im) in found { + assert!(d.images[&im.key].is_proxy()); + assert_eq!(Path::new(&im.link.as_ref().unwrap().path), dir.join("img").join(back.trim_start_matches("./"))); + } + } +} + +/// Two SVG files that link to each other, each shown by the imported SVG, each show the other +/// once, then the placeholder of the link back to themselves. +#[test] +fn svg_files_that_link_to_each_other_each_lead_back_to_themselves() { + let dir = folder("nested-cycle-both"); + std::fs::write(dir.join("img").join("a.svg"), svg_file(r#""#)).unwrap(); + std::fs::write(dir.join("img").join("b.svg"), svg_file(r#""#)).unwrap(); + let (d, w) = open_in(&dir, r#""#); + assert_eq!(w.len(), 2, "{w:?}"); + assert_eq!(rects(&d), 4, "each file's art once in each place"); + let [(_, a), (_, b)] = images(&d)[..] else { panic!("{:?}", art(&d)) }; + assert_eq!(Path::new(&a.link.as_ref().unwrap().path), dir.join("img").join("a.svg")); + assert_eq!(Path::new(&b.link.as_ref().unwrap().path), dir.join("img").join("b.svg")); +} + +/// An SVG file shown twice, and a raster that two SVG files link to, are read once. +#[test] +fn a_repeated_linked_svg_file_is_read_once() { + let dir = folder("nested-repeat"); + std::fs::write(dir.join("img").join("photo.png"), png(4, 4)).unwrap(); + std::fs::write(dir.join("img").join("a.svg"), svg_file(r#""#)).unwrap(); + std::fs::write( + dir.join("img").join("b.svg"), + svg_file(r#""#), + ) + .unwrap(); + let reads = std::sync::Mutex::new(vec![]); + let counted = counting(&reads); + let folder = dir.to_string_lossy(); + let body = r#""#; + let (d, w) = import_with(&svg(body), &ImportOptions { folder: Some(&folder), read: Some(&counted) }).unwrap(); + assert!(w.is_empty(), "{w:?}"); + let mut reads = reads.lock().unwrap().clone(); + reads.sort(); + assert_eq!(reads, ["a.svg", "b.svg", "photo.png"]); + let found = images(&d); + assert_eq!(found.len(), 4); + assert!(found.iter().all(|(_, im)| Path::new(&im.link.as_ref().unwrap().path) == dir.join("img").join("photo.png"))); +} + +/// A chain of SVG files, each linking to the next, is read only as deep as SVG images may nest: +/// past it the images are left out, with a warning. +#[test] +fn a_chain_of_linked_svg_files_stops_at_the_depth_cap() { + let dir = folder("nested-chain"); + let levels = vectorcraft_svg::MAX_ELEMENT_DEPTH; + for i in 0..levels { + std::fs::write(dir.join("img").join(format!("{i}.svg")), svg_file(&format!(r#""#, i + 1))) + .unwrap(); + } + let reads = std::sync::Mutex::new(vec![]); + let counted = counting(&reads); + let folder = dir.to_string_lossy(); + let (d, w) = + import_with(&svg(r#""#), &ImportOptions { folder: Some(&folder), read: Some(&counted) }) + .unwrap(); + let reads = reads.lock().unwrap().len(); + assert!(reads <= levels / 2 + 4, "{reads} reads"); + assert!(rects(&d) < levels / 2, "{}", rects(&d)); + assert!(w.iter().any(|w| w.contains("nest more than")), "{w:?}"); +} + +/// An SVG file reached first inside an SVG file where it nests too deep to be shown, then from the +/// imported SVG, shows the raster it links to where it fits. +#[test] +fn an_svg_file_too_deep_in_one_place_shows_its_links_in_another() { + let dir = folder("nested-deep-then-shallow"); + let depth = vectorcraft_svg::MAX_ELEMENT_DEPTH; + let nest = |n: usize, inner: &str| format!("{}{inner}{}", "".repeat(n), "".repeat(n)); + std::fs::write(dir.join("img").join("photo.png"), png(4, 4)).unwrap(); + std::fs::write(dir.join("img").join("deep.svg"), svg_file(&nest(depth * 2 / 3, r#""#))).unwrap(); + std::fs::write(dir.join("img").join("a.svg"), svg_file(&nest(depth / 2, r#""#))).unwrap(); + let (d, w) = open_in(&dir, r#""#); + assert!(w.iter().any(|w| w.contains("nest more than")), "{w:?}"); + let [(_, im)] = images(&d)[..] else { panic!("{:?} {w:?}", art(&d)) }; + assert_eq!(Path::new(&im.link.as_ref().unwrap().path), dir.join("img").join("photo.png")); +} + const SVG_NS: &str = r#"xmlns="http://www.w3.org/2000/svg""#; /// An image showing `svg`, from a base64 data URL of type `mime` (none when empty). @@ -672,6 +851,93 @@ fn nested_image_within_budget_imports_and_use_fan_out_is_refused() { assert!(matches!(err, SvgError::TooLarge(15)), "{err:?}"); } +/// Groups `g0` to `g{levels}`: `g0` a rectangle styled `style`, each other two ``s of the +/// one before; one `` of the last shown. +fn use_chain(levels: usize, style: &str) -> String { + let links: String = (1..=levels).map(|i| format!(r##""##, i - 1)).collect(); + svg(&format!(r##"{links}"##)) +} + +/// A style value of 100,000 bytes. +fn long_style() -> String { + format!("font-family:{}", "a".repeat(100_000)) +} + +/// A long style that a chain of ``s copies, or that a style sheet rule gives to many +/// elements, is refused before usvg copies it; short styles import, a rule that matches nothing +/// costing nothing. +#[test] +fn styles_that_expand_past_the_limit_are_refused() { + let err = import_with(&use_chain(10, &long_style()), &ImportOptions::default()).unwrap_err(); + assert!(matches!(err, SvgError::StylesTooLarge(64)), "{err:?}"); + assert_eq!(err.to_string(), "the SVG's styles expand to more than 64 MB"); + // 1,000 groups that one rule gives the long style, without any ``. + let sheet = svg(&format!("{}", long_style(), "".repeat(1000))); + let err = import_with(&sheet, &ImportOptions::default()).unwrap_err(); + assert!(matches!(err, SvgError::StylesTooLarge(64)), "{err:?}"); + + // The chain with a short style shows its 1,024 rectangles. + let (d, _) = import_with(&use_chain(10, "fill:red"), &ImportOptions::default()).unwrap(); + assert_eq!(art(&d).iter().filter(|n| n.children().is_none()).count(), 1024); + // 5,000 rectangles of a class with short rules, beside a long rule that matches none of them. + let rules = format!(".a{{fill:#123456;stroke:#654321;stroke-width:2;opacity:.5}} .b{{{}}}", long_style()); + let classed = svg(&format!("{}", r#""#.repeat(5000))); + let (d, _) = import_with(&classed, &ImportOptions::default()).unwrap(); + assert_eq!(art(&d).len(), 5000); +} + +/// A chain of ``s that makes more elements than usvg reads is refused before usvg makes them. +#[test] +fn a_use_chain_past_the_elements_usvg_reads_is_refused() { + let err = import_with(&use_chain(20, ""), &ImportOptions::default()).unwrap_err(); + assert!(matches!(err, SvgError::TooLarge(n) if n == vectorcraft_svg::MAX_NODES.min(999_999)), "{err:?}"); +} + +/// An SVG image whose styles expand past the limit refuses the SVG showing it, and the SVG images +/// share the limit with the SVG showing them. +#[test] +fn svg_images_whose_styles_expand_past_the_limit_refuse_the_svg() { + let err = import_with(&svg(&image_of("image/svg+xml", &use_chain(10, &long_style()))), &ImportOptions::default()).unwrap_err(); + assert!(matches!(err, SvgError::StylesTooLarge(64)), "{err:?}"); + // Each image copies its long style 383 times (about 38 MB): one imports, two together don't. + let image = image_of("image/svg+xml", &use_chain(7, &long_style())); + let (d, _) = import_with(&svg(&image), &ImportOptions::default()).unwrap(); + assert!(!art(&d).is_empty()); + let err = import_with(&svg(&image.repeat(2)), &ImportOptions::default()).unwrap_err(); + assert!(matches!(err, SvgError::StylesTooLarge(64)), "{err:?}"); + // An image that doesn't decode (no size) is left out, and what it would copy doesn't count. + let sizeless = use_chain(7, &long_style()).replacen(r#"width="200" height="120""#, r#"width="0" height="0""#, 1); + let (d, _) = import_with(&svg(&format!("{}{image}", image_of("image/svg+xml", &sizeless).repeat(2))), &ImportOptions::default()).unwrap(); + assert!(!art(&d).is_empty()); +} + +/// The SVG images share the element limit with the SVG showing them: each image's `` chain +/// makes 655,356 elements, so one imports and two together are refused before usvg makes the +/// second. +#[test] +fn svg_images_share_the_element_limit() { + let chain = use_chain(16, ""); + let unshown = chain.replacen(r##""##, "", 1); + assert_ne!(chain, unshown); + let image = image_of("image/svg+xml", &unshown); + let rect = r#""#; + assert!(import_with(&svg(&format!("{rect}{image}")), &ImportOptions::default()).is_ok()); + let err = import_with(&svg(&format!("{rect}{}", image.repeat(2))), &ImportOptions::default()).unwrap_err(); + assert!(matches!(err, SvgError::TooLarge(n) if n == vectorcraft_svg::MAX_NODES.min(999_999)), "{err:?}"); +} + +/// A `:not()` rule, which only the import's own style cascade reads, counts toward the style limit +/// the SVG images share: each image's rule gives 400 groups the long style (about 40 MB), so one +/// imports and two together are refused. +#[test] +fn svg_images_share_the_style_limit_with_not_rules() { + let groups = svg(&format!(r#"{}"#, long_style(), "".repeat(400))); + let image = image_of("image/svg+xml", &groups); + assert!(import_with(&svg(&image), &ImportOptions::default()).is_ok()); + let err = import_with(&svg(&image.repeat(2)), &ImportOptions::default()).unwrap_err(); + assert!(matches!(err, SvgError::StylesTooLarge(64)), "{err:?}"); +} + /// Nested SVG images exceeding `MAX_NESTED_SVG_IMAGES` are left out with a warning note (#3564). #[test] fn nested_svg_images_past_count_cap_are_left_out() { diff --git a/crates/svg/tests/it/import_text.rs b/crates/svg/tests/it/import_text.rs index 084c3172f3..816e17f15d 100644 --- a/crates/svg/tests/it/import_text.rs +++ b/crates/svg/tests/it/import_text.rs @@ -5,7 +5,7 @@ use vectorcraft_color::{GradientKind, Paint}; use vectorcraft_doc::{CharStyle, Document, Justify, Node, NodeKind, TextKind, TextObject}; use vectorcraft_geom::{Point, Rect}; use vectorcraft_svg::{import, import_with_report}; -use vectorcraft_text::{FontDb, layout}; +use vectorcraft_text::{FontDb, layout, spacing_scale}; fn svg(body: &str) -> String { format!(r#"{body}"#) @@ -469,6 +469,9 @@ fn rtl_point_text_start_and_end_use_directional_edges() { (r#"Wave"#, 0.0), (r#"Wave"#, 0.0), (r#"Wave"#, 1.0), + // CSS keywords are case-insensitive. + (r#"Wave"#, 1.0), + (r#"Wave"#, 0.0), // With `unicode-bidi: plaintext`, the direction of the chunk's first strong character. (r#"אבג"#, 1.0), (r#"12 אב"#, 0.0), @@ -572,6 +575,8 @@ fn a_tspan_bidi_embedding_becomes_its_character_direction() { ("ltr", "rtl", "normal", None, false), ("rtl", "ltr", "normal", None, false), ("ltr", "rtl", "EMBED", Some(Rtl), false), + ("ltr", "RTL", "embed", Some(Rtl), false), + ("RTL", "ltr", "embed", Some(Ltr), false), ("ltr", "rtl", "sideways", None, false), ] { let (t, w) = read(&format!( @@ -581,7 +586,7 @@ fn a_tspan_bidi_embedding_becomes_its_character_direction() { assert_eq!(t.plain_text(), "ab 1 2 cd", "{case}: the characters stay in logical order"); assert_eq!(char_direction_of(&t, "1 2"), want, "{case}: {:?}", t.runs); assert_eq!(char_direction_of(&t, "ab"), None, "{case}"); - assert_eq!(t.para_at(0).direction == Some(Rtl), outer == "rtl", "{case}: the paragraph keeps the text's direction"); + assert_eq!(t.para_at(0).direction == Some(Rtl), outer.eq_ignore_ascii_case("rtl"), "{case}: the paragraph keeps the text's direction"); assert_eq!(w.iter().any(|w| w.contains("bidi-override") && w.contains("not supported")), warns, "{case}: {w:?}"); if !warns { assert!(w.is_empty(), "{case}: {w:?}"); @@ -803,6 +808,114 @@ fn absolutely_placed_rtl_chunks_of_several_characters_anchor_by_their_visual_edg } } +/// Document-space left and right edges of the natural advance of the characters in `bytes` (the +/// manual kerning that places the next chunk left out: it is at a glyph's right when the glyph runs +/// left to right and at its left when it runs right to left). +fn chunk_edges(t: &TextObject, bytes: std::ops::Range) -> (f64, f64) { + let lay = layout(FontDb::global(), t); + let mut starts = vec![]; + let mut at = 0; + for r in &t.runs { + starts.push((at, &r.style)); + at += r.text.len(); + } + let style = |byte: usize| starts.iter().rev().find(|(s, _)| *s <= byte).map(|(_, st)| *st).unwrap(); + let (mut left, mut right) = (f64::INFINITY, f64::NEG_INFINITY); + for g in lay.glyphs.iter().filter(|g| bytes.contains(&g.byte)) { + let st = style(g.byte); + let kern = st.kerning.unwrap_or(0.0) / 1000.0 * st.size * spacing_scale(st, false); + let x = (t.xf * g.origin).x; + let (l, r) = if g.rtl { (x + kern, x + g.advance) } else { (x, x + g.advance - kern) }; + (left, right) = (left.min(l), right.max(r)); + } + assert!(left.is_finite(), "no glyph in {bytes:?}"); + (left, right) +} + +/// SVG 1.1 §10.4 and SVG 2 §11.10.1.1 (https://www.w3.org/TR/SVG2/text.html#TextAnchoringProperties): +/// every absolutely placed character starts a chunk anchored on its own x, also in right-to-left +/// text whose characters run right to left, on any line. +#[test] +fn absolutely_placed_right_to_left_characters_sit_on_their_own_x() { + // (markup, share of each chunk's advance left of its x, each chunk's bytes and x) + let two_lines = |anchor: &str| { + format!( + r#"abאב"# + ) + }; + type Chunks = Vec<(std::ops::Range, f64)>; + let cases: Vec<(String, f64, Chunks)> = vec![ + (two_lines("start"), 1.0, vec![(0..2, 20.0), (3..5, 100.0), (5..7, 160.0)]), + (two_lines("middle"), 0.5, vec![(0..2, 20.0), (3..5, 100.0), (5..7, 160.0)]), + (two_lines("end"), 0.0, vec![(0..2, 20.0), (3..5, 100.0), (5..7, 160.0)]), + (r#"אב"#.into(), 1.0, vec![(0..2, 100.0), (2..4, 160.0)]), + (r#"אב"#.into(), 0.0, vec![(0..2, 100.0), (2..4, 160.0)]), + // Three lines, the characters of the last out of order and overlapping. + ( + r#"אבגדהוז"#.into(), + 1.0, + vec![(0..4, 300.0), (5..7, 60.0), (7..9, 120.0), (10..12, 200.0), (12..14, 90.0), (14..16, 205.0)], + ), + // Left-to-right characters among right-to-left ones on the same line. + (r#"אbc"#.into(), 1.0, vec![(0..2, 100.0), (2..3, 160.0), (3..4, 220.0)]), + // Chunks of several characters. + ( + r#"abאבגד"#.into(), + 1.0, + vec![(0..2, 20.0), (3..7, 100.0), (7..11, 250.0)], + ), + ( + r#"abאבגד"#.into(), + 0.5, + vec![(0..2, 20.0), (3..7, 100.0), (7..11, 250.0)], + ), + // A placed character after a letter with a combining mark. + ( + r#"אָב"#.into(), + 1.0, + vec![(4..6, 160.0)], + ), + (r#"éb"#.into(), 0.0, vec![(3..4, 160.0)]), + // Characters stretched by `lengthAdjust`, whose kerning is drawn at their scale. + ( + r#"abאב"#.into(), + 1.0, + vec![(0..2, 20.0), (3..5, 100.0), (5..7, 160.0)], + ), + // Left to right, the right-to-left characters still each start at their own x. + ( + r#"abאב"#.into(), + 0.0, + vec![(0..2, 20.0), (3..5, 100.0), (5..7, 160.0)], + ), + ( + r#"abcd"#.into(), + 0.0, + vec![(0..2, 20.0), (3..4, 100.0), (4..5, 160.0)], + ), + ]; + let unplaced = |w: &[String]| w.iter().any(|w| w.contains("absolutely placed")); + for (body, share, chunks) in cases { + let (d, w) = import_with_report(&svg(&body)).unwrap(); + assert!(!unplaced(&w), "{body}: {w:?}"); + let t = only_text(&d); + if body.contains("lengthAdjust") { + assert!(t.runs.iter().any(|r| r.style.h_scale < 99.0), "{body}: {:?}", t.runs); + } + for (bytes, x) in chunks { + let (left, right) = chunk_edges(t, bytes.clone()); + let want = x - share * (right - left); + assert!(close(left, want, 0.05), "{body}: the chunk {bytes:?} spans {left}..{right}, so it does not start at {want}"); + } + } + // A left-to-right character between right-to-left ones is drawn right next to the one after + // it, with no kerning between them: that one keeps its place in the line, and a warning says so. + let (d, w) = import_with_report(&svg(r#"אbג"#)).unwrap(); + assert!(unplaced(&w), "{w:?}"); + let (left, right) = chunk_edges(only_text(&d), 2..3); + assert!(close(right, 160.0, 0.05), "b spans {left}..{right}"); +} + #[test] fn a_small_line_gap_in_tiny_type_keeps_its_leading() { // 0.0085 against an auto leading of 0.006 differs by less than 0.01 but is not a whole multiple of it. diff --git a/crates/testkit/src/strategies.rs b/crates/testkit/src/strategies.rs index 153ede8f02..c2543d4374 100644 --- a/crates/testkit/src/strategies.rs +++ b/crates/testkit/src/strategies.rs @@ -2,7 +2,7 @@ use proptest::prelude::*; use serde_json::{Value, json}; -use vectorcraft_engine::cmd::{Location, key_location, location_in, location_keys}; +use vectorcraft_engine::cmd::{Location, ParamsPlace, key_location, location_keys}; use vectorcraft_engine::{CommandSpec, Session, command_specs}; use vectorcraft_geom::{Anchor, PathData, Point, Rect, SubPath}; @@ -518,20 +518,8 @@ pub fn command_param_keys(spec: &CommandSpec) -> Vec { keys } -/// Parameter-name keys that name a file or folder in some command ([`key_location`]): fuzzing these -/// with arbitrary strings could write files anywhere, so callers substitute a temp path. -pub fn is_path_key(k: &str) -> bool { - key_location(k).is_some() -} - -/// Path keys that name a folder a command reads, creates or writes files into ([`key_location`]): -/// `folder`, `folders`, `dir`, `directory`, `destinationFolder` and `sourceFolder`. -pub fn is_folder_key(k: &str) -> bool { - key_location(k) == Some(Location::Folder) -} - -/// The location to send under the path key `k`: `safe_path` for a file, a folder next to it (in -/// the same temp folder) for a folder key. +/// The location to send under the path key `k` ([`key_location`]): `safe_path` for a file, a folder +/// next to it (in the same temp folder) for a folder key. pub fn safe_location(k: &str, safe_path: &str) -> String { location(key_location(k).unwrap_or(Location::File), safe_path) } @@ -542,55 +530,74 @@ fn location(l: Location, safe_path: &str) -> String { if l == Location::Folder { format!("{safe_path}-folder") } else { safe_path.to_string() } } -/// `v` with every string in it that can name a place on disk sent to the temp location: `v` -/// itself and the members of arrays in it, at any depth, when `kind` is `Some`, and in an object -/// at any depth, the strings under a path key ([`is_path_key`]). Other values keep their junk -/// shape. -fn redirect(kind: Option, v: &Value, safe_path: &str) -> Value { +/// `v`, found at `place` in a command's params, with every string in it that can name a place on +/// disk sent to the temp location: `v` itself and the members of arrays in it, at any depth, when +/// `kind` is `Some`, and in an object at any depth, the strings under a key that names a file or a +/// folder there ([`ParamsPlace::member`]: a call or a recorded step inside `v` keeps its command's +/// meaning). Other values keep their junk shape. +fn redirect(place: ParamsPlace, kind: Option, v: &Value, safe_path: &str) -> Value { match v { Value::String(_) => kind.map_or_else(|| v.clone(), |l| json!(location(l, safe_path))), - Value::Array(a) => Value::Array(a.iter().map(|x| redirect(kind, x, safe_path)).collect()), - Value::Object(o) => Value::Object(o.iter().map(|(k, x)| (k.clone(), redirect(key_location(k), x, safe_path))).collect()), + Value::Array(a) => { + let step = ParamsPlace::step(a); + Value::Array(a.iter().enumerate().map(|(i, x)| redirect(place.item(i, step), kind, x, safe_path)).collect()) + } + Value::Object(o) => { + let carried = ParamsPlace::carried(o); + let member = |k: &String, x: &Value| { + let (below, l) = place.member(k, carried); + (k.clone(), redirect(below, l, x, safe_path)) + }; + Value::Object(o.iter().map(|(k, x)| member(k, x)).collect()) + } _ => v.clone(), } } -/// `v`, with its strings sent to the temp location when `k` is a path key in any command -/// ([`is_path_key`]), and the strings under path keys in objects inside it too. -pub fn safe_value(k: &str, v: &Value, safe_path: &str) -> Value { - redirect(key_location(k), v, safe_path) +/// `v`, sent under key `k` at `place`, as [`redirect`] makes it. +fn redirect_under(place: ParamsPlace, k: &str, v: &Value, safe_path: &str) -> Value { + let (below, kind) = place.member(k, None); + redirect(below, kind, v, safe_path) } -/// `v` as [`safe_value`] makes it for command `spec` ([`location_in`]): a key that names part of -/// the document in it keeps its strings. +/// `v`, with its strings sent to the temp location when `k` is a path key in a command that gives it +/// no other meaning ([`key_location`]), and the strings under path keys in objects inside it too. +pub fn safe_value(k: &str, v: &Value, safe_path: &str) -> Value { + redirect_under(ParamsPlace::top(None), k, v, safe_path) +} + +/// `v` as [`safe_value`] makes it for command `spec` ([`vectorcraft_engine::cmd::location_in`]): a key that names part of +/// the document in it keeps its strings, at the top level and below. pub fn safe_value_for_command(spec: &CommandSpec, k: &str, v: &Value, safe_path: &str) -> Value { - redirect(location_in(spec, k), v, safe_path) + redirect_under(ParamsPlace::top(Some(spec)), k, v, safe_path) } /// A deterministic list of junk param objects for `doc` (the command's params doc): each /// documented key set to each junk value, all keys junk at once, wrong top-level types. A string -/// under a key that names a file or folder in any command ([`is_path_key`]) is a temp location. +/// under a key that names a file or folder in a command that gives it no other meaning +/// ([`key_location`]) is a temp location. pub fn junk_params(doc: &str, safe_path: &str) -> Vec { - junk_params_with(¶m_keys(doc), |k, v| safe_value(k, v, safe_path), key_location, safe_path) + junk_params_with(¶m_keys(doc), ParamsPlace::top(None), safe_path) } /// [`junk_params`] for command `spec`, with the keys of its schema and its file and folder keys too /// ([`command_param_keys`]), and a string under each key that names a file or folder in it -/// ([`location_in`]) a temp location, as are the strings in an array of them and under the path +/// ([`vectorcraft_engine::cmd::location_in`]) a temp location, as are the strings in an array of them and under the path /// keys of objects in one (`paths: [{ids, path}]`), which it also sends. pub fn junk_params_for_command(spec: &CommandSpec, safe_path: &str) -> Vec { - junk_params_with(&command_param_keys(spec), |k, v| safe_value_for_command(spec, k, v, safe_path), |k| location_in(spec, k), safe_path) + junk_params_with(&command_param_keys(spec), ParamsPlace::top(Some(spec)), safe_path) } -/// The junk cases for `keys`: `safe(k, v)` is what is sent for junk value `v` under `k`, and -/// `kind(k)` what `k` names on disk, if anything, whose keys also get a list of locations and a -/// list of objects with a `path`. -fn junk_params_with(keys: &[String], safe: impl Fn(&str, &Value) -> Value, kind: impl Fn(&str) -> Option, safe_path: &str) -> Vec { +/// The junk cases for `keys` at `place`, the top of a command's params: what is sent for a junk value +/// under a key is [`redirect_under`] it, and a key that names a file or a folder there also gets a +/// list of locations and a list of objects with a `path`. +fn junk_params_with(keys: &[String], place: ParamsPlace, safe_path: &str) -> Vec { let junk = junk_values(); let mut out = vec![Value::Null, json!([]), json!("str"), json!(42), json!({"unknownKey": 1})]; for k in keys { + let (below, kind) = place.member(k, None); for (i, v) in junk.iter().enumerate() { - let v = safe(k, v); + let v = redirect(below, kind, v, safe_path); // Sparse: one key at a time with every junk value, plus a few combos. let mut o = serde_json::Map::new(); o.insert(k.clone(), v.clone()); @@ -598,17 +605,62 @@ fn junk_params_with(keys: &[String], safe: impl Fn(&str, &Value) -> Value, kind: if i % 5 == 0 { let mut all = serde_json::Map::new(); for k2 in keys { - let v2 = kind(k2).map_or_else(|| v.clone(), |l| json!(location(l, safe_path))); + let v2 = place.member(k2, None).1.map_or_else(|| v.clone(), |l| json!(location(l, safe_path))); all.insert(k2.clone(), v2); } out.push(Value::Object(all)); } } - if let Some(l) = kind(k) { + if let Some(l) = kind { for v in [json!(["junk", "", 1]), json!([{"ids": [1], "path": "junk"}, {"path": null}])] { - out.push(json!({ k.as_str(): redirect(Some(l), &v, safe_path) })); + out.push(json!({ k.as_str(): redirect(below, Some(l), &v, safe_path) })); } } } out } + +#[cfg(test)] +mod tests { + use super::*; + + /// The strings the sweeps send keep the meaning the command gives their key, at every depth: an + /// export's folder grouping and a web link stay as sent, also inside a `command.batch` step and + /// a recorded step, and a real file or folder key there goes to the temp location. A key that names + /// part of the document in a recorded step's command stays, and the same key in a command that + /// doesn't take it as a param names a file. + #[test] + fn nested_locations_keep_command_meaning() { + let spec = |id: &str| command_specs().iter().find(|c| c.id == id).unwrap_or_else(|| panic!("no command {id}")); + let safe = "/tmp/sweep/out.bin"; + let settings = json!({"folders": "rows", "formats": [{"format": "png", "folder": "junk"}]}); + assert_eq!( + safe_value_for_command(spec("document.exportPresets.save"), "settings", &settings, safe), + json!({"folders": "rows", "formats": [{"format": "png", "folder": "/tmp/sweep/out.bin-folder"}]}) + ); + let steps = json!([ + {"command": "attributes.set", "params": {"url": "https://example.com/a"}}, + {"command": "document.save", "params": {"path": "junk"}}, + {"command": "object.path.simplify", "params": {"wholePaths": "junk"}}, + ]); + assert_eq!( + safe_value_for_command(spec("command.batch"), "commands", &steps, safe), + json!([ + {"command": "attributes.set", "params": {"url": "https://example.com/a"}}, + {"command": "document.save", "params": {"path": safe}}, + {"command": "object.path.simplify", "params": {"wholePaths": "junk"}}, + ]) + ); + let recorded = json!([ + ["text.createInPath", {"path": "junk"}], + ["object.setLiveShape", {"path": "junk"}], + ["document.compare", {"diffPath": "junk"}], + ]); + assert_eq!( + safe_value("steps", &recorded, safe), + json!([["text.createInPath", {"path": "junk"}], ["object.setLiveShape", {"path": safe}], ["document.compare", {"diffPath": safe}]]) + ); + assert_eq!(safe_value("url", &json!("https://example.com/a"), safe), json!("https://example.com/a")); + assert_eq!(safe_value("destinationFolder", &json!("junk"), safe), json!("/tmp/sweep/out.bin-folder")); + } +} diff --git a/crates/text/src/colr.rs b/crates/text/src/colr.rs index 66281f70f0..637dd9c243 100644 --- a/crates/text/src/colr.rs +++ b/crates/text/src/colr.rs @@ -148,6 +148,9 @@ struct Tree<'a> { painted: Option, /// It paints with the foreground colour (palette index 0xFFFF). foreground_used: bool, + /// A fill draws nothing (a radial gradient none of whose circles has a positive radius), so a + /// glyph with nothing else is colour art that draws nothing, not its outline. + drew_nothing: bool, } impl<'a> Tree<'a> { @@ -166,6 +169,7 @@ impl<'a> Tree<'a> { too_large: false, painted: None, foreground_used: false, + drew_nothing: false, } } @@ -254,7 +258,7 @@ impl<'a> Tree<'a> { self.close(); } let root = self.groups.pop()?; - if root.children.is_empty() { + if root.children.is_empty() && !self.drew_nothing { return None; } Some(Arc::new(Node::group(NO_ID, root.children))) @@ -308,22 +312,27 @@ impl<'a> Tree<'a> { } Brush::RadialGradient { c0, r0, c1, r1, color_stops, extend } => { let spread = spread(*extend); - let (c0, c1, r0, r1) = (point(*c0), point(*c1), f64::from(*r0), f64::from(*r1)); + let line = stops(color_stops, self); + // Without a stop, the others would repeat over a different interval. + if !spread.is_pad() && line.len() < color_stops.len() { + self.unsupported.get_or_insert("a repeating or reflecting gradient with a stop missing from the palette"); + return None; + } + let Some((c0, r0, c1, r1, mut stops)) = non_negative_radii(point(*c0), f64::from(*r0), point(*c1), f64::from(*r1), line, *extend) + else { + self.drew_nothing = true; + return None; + }; let concentric = (c0 - c1).hypot() < 1e-6; if (r0 > 1e-6 && !concentric) || r1 <= r0 || (c0 - c1).hypot() >= r1 { self.unsupported.get_or_insert("a radial gradient from a circle"); return None; } - let mut stops = stops(color_stops, self); if stops.iter().any(|s| !(0.0..=1.0).contains(&s.offset)) { self.unsupported.get_or_insert("a radial gradient with stops past its circles"); return None; } if !spread.is_pad() { - if stops.len() < color_stops.len() { - self.unsupported.get_or_insert("a repeating or reflecting gradient with a stop missing from the palette"); - return None; - } // A run of the stops is the whole way from the center to the circle: one that // starts at a circle (a first stop past the center comes as one) repeats over // less of it. The normalized ends can be a rounding error off 0 and 1. @@ -383,6 +392,87 @@ fn normalized(mut stops: Vec) -> Option<(Vec, f32, f Some((stops, first, if span > 0.0 { last } else { first + 1.0 })) } +/// A radial gradient's circles (`c0`, `r0`) and (`c1`, `r1`) and color line `stops` (0 and 1 at +/// the circles) recast so that neither circle has a negative radius, as normalizing a color line +/// to 0..1 can give. Circles of a negative radius are not drawn, only those on the side of the +/// circle of radius 0 (the tip of the cone) where the radius is positive. With pad, the stops on +/// the other side become one stop at the tip with the color there; with repeat and reflect, the +/// circles move along by whole periods of the color line to the drawn side +/// (https://learn.microsoft.com/en-us/typography/opentype/spec/colr, Radial gradients). `None` +/// when no circle is drawn. +fn non_negative_radii( + c0: Point, + r0: f64, + c1: Point, + r1: f64, + mut stops: Vec, + extend: Extend, +) -> Option<(Point, f64, Point, f64, Vec)> { + if (r0 >= 0.0 && r1 >= 0.0) || stops.is_empty() { + return Some((c0, r0, c1, r1, stops)); + } + if r0 == r1 { + return None; + } + stops.sort_by(|a, b| a.offset.total_cmp(&b.offset)); + let tip = r0 / (r0 - r1); + let grows = r1 > r0; + let (from, to, stops) = match extend { + Extend::Repeat | Extend::Reflect => { + // A reflected color line repeats every 2: once forward, then back. + let (period, stops) = if extend == Extend::Reflect { + let forward = stops.iter().map(|s| GradientStop { offset: s.offset / 2.0, ..s.clone() }); + let back = stops.iter().rev().map(|s| GradientStop { offset: 1.0 - s.offset / 2.0, ..s.clone() }); + (2.0, forward.chain(back).collect()) + } else { + (1.0, stops) + }; + let from = if grows { (tip / period).ceil() * period } else { (tip / period).floor() * period - period }; + (from, from + period, stops) + } + _ => { + // The color line runs from 0 to 1, and further where its stops do. + let first = stops.first().map_or(0.0, |s| f64::from(s.offset).min(0.0)); + let last = stops.last().map_or(1.0, |s| f64::from(s.offset).max(1.0)); + let (from, to) = match (grows, tip) { + (true, t) if t < last => (t, last), + (true, t) => (t, t + 1.0), + (false, t) if t > first => (first, t), + (false, t) => (t - 1.0, t), + }; + let line = Gradient { stops, ..Gradient::default() }; + // The color at `w`, as a stop at `offset` of the new line. + let at = |w: f64, offset: f32| { + let (color, opacity) = line.sample(w as f32); + GradientStop { opacity, ..GradientStop::new(offset, color) } + }; + // Stops at the tip stay on the drawn side of its stop, so a sharp change of color there + // keeps the color on that side. + let mut kept: Vec = line + .stops + .iter() + .filter(|s| (from - 1e-6..=to + 1e-6).contains(&f64::from(s.offset))) + .map(|s| GradientStop { offset: ((f64::from(s.offset) - from) / (to - from)).clamp(0.0, 1.0) as f32, ..s.clone() }) + .collect(); + if grows { + kept.insert(0, at(tip, 0.0)); + if kept.last().is_none_or(|s| s.offset < 1.0) { + kept.push(at(to, 1.0)); + } + } else { + kept.push(at(tip, 1.0)); + if kept.first().is_none_or(|s| s.offset > 0.0) { + kept.insert(0, at(from, 0.0)); + } + } + (from, to, kept) + } + }; + let circle = |w: f64| (c0.lerp(c1, w), (r0 + w * (r1 - r0)).max(0.0)); + let ((c0, r0), (c1, r1)) = (circle(from), circle(to)); + Some((c0, r0, c1, r1, stops)) +} + impl ColorPainter for Tree<'_> { fn push_transform(&mut self, transform: Transform) { let t = self.transform() * affine(&transform); @@ -418,12 +508,17 @@ impl ColorPainter for Tree<'_> { return; }; let Some(clip) = self.groups.get(at).and_then(|g| g.clip.clone()) else { return }; - if at + 1 == self.groups.len() - && let Some(g) = self.groups.last_mut() - { - g.flooded = g.children.is_empty(); - } + let innermost = at + 1 == self.groups.len(); + let before = self.groups.last().map_or(0, |g| g.children.len()); self.fill_path(&clip, &brush); + // Flooded only when this fill added the group's first child. A fill that paints nothing + // adds none and leaves the flag as it was, so the clip stays around what comes after it. + if innermost + && let Some(g) = self.groups.last_mut() + && g.children.len() > before + { + g.flooded = before == 0; + } } /// The glyph's outline filled, the brush moved by `brush_transform` (the glyph stays). @@ -575,10 +670,24 @@ impl ColorPainter for Pixels<'_, '_> { Brush::LinearGradient { p0, p1, color_stops, extend: e } => { peniko::Gradient::new_linear(point(p0), point(p1)).with_stops(stops(color_stops).as_slice()).with_extend(extend(e)).into() } - Brush::RadialGradient { c0, r0, c1, r1, color_stops, extend: e } => peniko::Gradient::new_two_point_radial(point(c0), r0, point(c1), r1) - .with_stops(stops(color_stops).as_slice()) - .with_extend(extend(e)) - .into(), + Brush::RadialGradient { c0, r0, c1, r1, color_stops, extend: e } => { + let line = color_stops + .iter() + .map(|s| { + let (c, a) = colour(&self.palette, self.foreground, s.palette_index, s.alpha).unwrap_or((Color::BLACK, 0.0)); + GradientStop { opacity: a, ..GradientStop::new(s.offset, c) } + }) + .collect(); + let Some((c0, r0, c1, r1, line)) = non_negative_radii(point(c0), f64::from(r0), point(c1), f64::from(r1), line, e) else { return }; + let stops: Vec = line + .iter() + .map(|s| { + let [r, g, b, a] = s.color.to_rgba8(s.opacity); + peniko::ColorStop::from((s.offset, peniko::Color::from_rgba8(r, g, b, a))) + }) + .collect(); + peniko::Gradient::new_two_point_radial(c0, r0 as f32, c1, r1 as f32).with_stops(stops.as_slice()).with_extend(extend(e)).into() + } Brush::SweepGradient { c0, start_angle, end_angle, color_stops, extend: e } => { peniko::Gradient::new_sweep(point(c0), start_angle.to_radians(), end_angle.to_radians()) .with_stops(stops(color_stops).as_slice()) diff --git a/crates/text/src/features.rs b/crates/text/src/features.rs index 9f2b555e23..112573104d 100644 --- a/crates/text/src/features.rs +++ b/crates/text/src/features.rs @@ -319,6 +319,9 @@ impl OtFeatures { v.push(f(&t, u32::from(s.extra_values.get(i).copied().unwrap_or(0).max(1)))); } } + if let Some(tag) = st.glyph_form.feature() { + v.push(f(tag, true)); + } if self.vertical { // Not `vrt2`: its glyphs are already turned on their side, and the layout turns Latin // and digits itself (they would lie upside down, and tate-chu-yoko break). diff --git a/crates/text/src/fontdb/composite.rs b/crates/text/src/fontdb/composite.rs index 16e98038fa..79a608788b 100644 --- a/crates/text/src/fontdb/composite.rs +++ b/crates/text/src/fontdb/composite.rs @@ -19,7 +19,7 @@ type Resolved = Option<(Arc, FontMatch)>; thread_local! { /// The composite fonts the guards of this thread lend ([`FontDb::lend_composite_fonts`]), the - /// latest loan last. + /// latest loan last. Only the latest loan of a database is looked in. static LENT: RefCell> = const { RefCell::new(Vec::new()) }; } @@ -34,8 +34,8 @@ struct Loan { number: u64, /// The fonts, by lowercased name. fonts: HashMap>, - /// The database's generation when they were lent, when each was then the font the database - /// holds by its name. + /// The database's generation when they were lent, when they were then exactly the fonts the + /// database holds: each the font it holds by its name, and none it holds left out. same_at: Option, /// A number for the definitions lent: loans of the same definitions have the same one. print: u64, @@ -67,8 +67,8 @@ pub struct CompositeCoverage { impl FontDb { /// Make `font` available by its name, in place of a composite font of that name (any case). /// The font menus and anything else that lists fonts change only when the definition does. - /// Whether it did. A font of that name a guard lends ([`FontDb::lend_composite_fonts`]) stays - /// in use on the guard's thread. + /// Whether it did. While a guard lends composite fonts ([`FontDb::lend_composite_fonts`]), the + /// guard's thread uses the fonts it lends and not this one. pub fn set_composite_font(&self, font: &CompositeFont) -> bool { let key = font.name.to_lowercase(); { @@ -91,15 +91,13 @@ impl FontDb { removed } - /// The composite font named `name` (any case): the one the latest guard of this thread that - /// lends that name lends ([`FontDb::lend_composite_fonts`]), else the one the database holds. + /// The composite font named `name` (any case). While a guard of this thread lends a document's + /// composite fonts ([`FontDb::lend_composite_fonts`]), the one the latest such guard lends, and + /// `None` when that document does not define the name, also when the database or an earlier + /// guard holds one of that name. Otherwise the one the database holds. pub fn composite_font(&self, name: &str) -> Option> { if self.lends() { - let key = name.to_lowercase(); - if let Some(f) = self.lent_font(&key) { - return Some(f); - } - return self.composites.read().unwrap_or_else(|e| e.into_inner()).get(&key).cloned(); + return self.lent_font(&name.to_lowercase()); } let map = self.composites.read().unwrap_or_else(|e| e.into_inner()); if map.is_empty() { @@ -113,30 +111,27 @@ impl FontDb { LENT.try_with(|l| l.borrow().iter().any(|loan| loan.db == self.id)).unwrap_or(false) } - /// The composite font named `key` (lowercased) that the latest guard of this thread lending that - /// name lends. + /// The composite font named `key` (lowercased) that the latest guard of this thread lending + /// composite fonts of this database lends. fn lent_font(&self, key: &str) -> Option> { - LENT.try_with(|l| l.borrow().iter().rev().filter(|loan| loan.db == self.id).find_map(|loan| loan.fonts.get(key).cloned())).ok().flatten() + LENT.try_with(|l| l.borrow().iter().rev().find(|loan| loan.db == self.id).and_then(|loan| loan.fonts.get(key).cloned())).ok().flatten() } - /// [`FontDb::generation`] on this thread, from the database's own generation `g`: `g` while each - /// font the guards of this thread lend is the one the database held by its name when it was lent - /// and the database has not changed since, else a number made from `g` and the definitions - /// lent, so what was laid out in one document's definitions is not taken for another's. + /// [`FontDb::generation`] on this thread, from the database's own generation `g`: `g` while no + /// guard of this thread lends composite fonts of this database, or while the latest one lends + /// exactly the fonts the database held when it was lent and the database has not changed since, + /// else a number made from `g` and the definitions lent, so what was laid out in one document's + /// definitions is not taken for another's. pub(super) fn lent_generation(&self, g: u64) -> u64 { - LENT.try_with(|l| { - let l = l.borrow(); - let loans = l.iter().filter(|loan| loan.db == self.id); - if loans.clone().all(|loan| loan.same_at == Some(g)) { - return g; - } - let mut h = DefaultHasher::new(); - g.hash(&mut h); - for loan in loans { + LENT.try_with(|l| match l.borrow().iter().rev().find(|loan| loan.db == self.id) { + Some(loan) if loan.same_at != Some(g) => { + let mut h = DefaultHasher::new(); + g.hash(&mut h); loan.print.hash(&mut h); + // The database's generations count up from 0 and never reach the top bit. + h.finish() | 1 << 63 } - // The database's generations count up from 0 and never reach the top bit. - h.finish() | 1 << 63 + _ => g, }) .unwrap_or(g) } @@ -245,20 +240,41 @@ impl FontDb { } } - /// Make each of the composite fonts `fonts` (a document's) available on this thread while the - /// returned guard lives, in place of a composite font of the same name that the database holds - /// or that an earlier guard of this thread lends. An app's session registers the composite fonts - /// of its front document; with the guard, a document exported without a session, one that is not - /// in front, or one placed in another document draws its type in its own, also while another - /// thread draws another document that defines the same name differently, or the session - /// registers another document's. Of fonts that share a name (in any case), the first is lent. + /// Make the composite fonts `fonts` (a document's) the only ones available on this thread while + /// the returned guard lives: type naming a composite font they do not define is set as in a + /// missing font, also when the database or an earlier guard of this thread holds one of that + /// name. An app's session registers the composite fonts of its front document; with the guard, a + /// document exported without a session, one that is not in front, or one placed in another + /// document draws its type in its own, also while another thread draws another document that + /// defines the same name differently, or the session registers another document's. Of fonts + /// that share a name (in any case), the first is lent. When none of `fonts` is usable and no + /// guard of this thread lends composite fonts of the database, the guard lends none: type naming + /// any composite font is set as in a missing font while it lives. When none is usable inside + /// another guard (a temporary document drawn while a document draws), nothing is lent and that + /// guard's fonts stay in use; [`FontDb::lend_document_composite_fonts`] lends none there too. /// Other threads, and the fonts the database holds and lists, are left as they are. The guard - /// stays on its thread and ends its loan when it drops, also when the thread unwinds. + /// stays on its thread and ends its loan when it drops, also when the thread unwinds. With no + /// guard (type laid out on its own), the fonts the database holds are used. pub fn lend_composite_fonts(&self, fonts: &[CompositeFont]) -> LentCompositeFonts<'_> { + self.lend(fonts, false) + } + + /// [`FontDb::lend_composite_fonts`] for a document that is drawn or measured as itself, also + /// inside another document's guard (a document placed in another): when it defines no usable + /// composite font, type naming any composite font is set as in a missing font while the guard + /// lives. + pub fn lend_document_composite_fonts(&self, fonts: &[CompositeFont]) -> LentCompositeFonts<'_> { + self.lend(fonts, true) + } + + /// Lend the usable fonts of `fonts`. With none, lend an empty set when `always` or when no + /// guard of this thread lends fonts of this database (and the database holds some), else + /// nothing. + fn lend(&self, fonts: &[CompositeFont], always: bool) -> LentCompositeFonts<'_> { // A font a document can't use (its name an installed family's, or a value out of range) // is not lent: an app leaves it out when it opens the document. let usable: Vec<&CompositeFont> = fonts.iter().filter(|f| f.check().is_ok() && !self.has_installed_family(&f.name)).collect(); - if usable.is_empty() { + if usable.is_empty() && !always && (self.lends() || self.composites.read().unwrap_or_else(|e| e.into_inner()).is_empty()) { return LentCompositeFonts { number: None, thread: PhantomData }; } let mut lent: HashMap> = HashMap::with_capacity(usable.len()); @@ -281,6 +297,8 @@ impl FontDb { }; lent.insert(key, font); } + // Each lent font is the database's; with as many, none it holds is left out. + same &= lent.len() == map.len(); self.generation.load(Ordering::Relaxed) }; let number = NEXT_LOAN.fetch_add(1, Ordering::Relaxed); diff --git a/crates/text/src/fontdb/gsub.rs b/crates/text/src/fontdb/gsub.rs index 888c89ab09..bcc19f74b0 100644 --- a/crates/text/src/fontdb/gsub.rs +++ b/crates/text/src/fontdb/gsub.rs @@ -304,6 +304,20 @@ impl FontFace { self.gsub.get_or_init(|| GsubIndex::read(self)) } + /// Does the face's `GSUB` table have feature `tag` with at least one lookup? At most + /// [`MAX_FEATURES`] feature records are read; false when the face has no `GSUB` table or it + /// cannot be read. + pub fn has_substitution_feature(&self, tag: [u8; 4]) -> bool { + let Some(font) = self.skrifa() else { return false }; + let Some(features) = font.gsub().ok().and_then(|g| g.feature_list().ok()) else { return false }; + features + .feature_records() + .iter() + .take(MAX_FEATURES) + .filter(|r| r.feature_tag().to_be_bytes() == tag) + .any(|r| r.feature(features.offset_data()).is_ok_and(|f| !f.lookup_list_indices().is_empty())) + } + /// What the features `aalt`, `salt`, `ss01` to `ss20`, `swsh`, `cv01` to `cv99`, `hist`, /// `jalt`, `nalt`, `ornm` and `titl` of the face's `GSUB` table substitute for glyph `gid`, in /// that order of features and within a feature in lookup order: the glyph of each single diff --git a/crates/text/src/harakat.rs b/crates/text/src/harakat.rs index 0f8ce4facd..ab5aa593bd 100644 --- a/crates/text/src/harakat.rs +++ b/crates/text/src/harakat.rs @@ -86,6 +86,7 @@ pub(crate) fn paint_only(a: &CharStyle, b: &CharStyle) -> bool { no_break, language, glyph_alternate, + glyph_form: _, fill, stroke, stroke_width, diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs index a7d7d1d3f3..d7669f2fe2 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -336,6 +336,8 @@ impl Ctx<'_> { tab.kern_shift = 0.0; tab.aki_shift = 0.0; tab.aki = 0.0; + tab.tsume_shift = 0.0; + tab.tsume = 0.0; tab.tcy = None; tab.wari = None; tab.vpal = None; @@ -653,6 +655,8 @@ impl Ctx<'_> { k.kern_shift = 0.0; k.aki_shift = 0.0; k.aki = 0.0; + k.tsume_shift = 0.0; + k.tsume = 0.0; k.len = 0; k.lead = 0.0; k.ch = kashida::TATWEEL; @@ -713,6 +717,8 @@ mod emit_kashida_mark_last { kern_shift: 0.0, aki_shift: 0.0, aki: 0.0, + tsume_shift: 0.0, + tsume: 0.0, sx: face.upem.recip() * 48.0, sy: face.upem.recip() * 48.0, bshift: 0.0, @@ -779,6 +785,8 @@ mod emit_kashida_mark_last { kern_shift: 0.0, aki_shift: 0.0, aki: 0.0, + tsume_shift: 0.0, + tsume: 0.0, sx: face.upem.recip() * 48.0, sy: face.upem.recip() * 48.0, bshift: 0.0, diff --git a/crates/text/src/layout/breaking.rs b/crates/text/src/layout/breaking.rs index 671ebee7a1..fadb0165d5 100644 --- a/crates/text/src/layout/breaking.rs +++ b/crates/text/src/layout/breaking.rs @@ -53,6 +53,15 @@ impl Metrics { } } +/// What a line band was placed below: the baseline of the line above it and the em box top that +/// line left for the next one (both `None` for a cell's first band), and the space pending between. +#[derive(Clone, Copy, Default)] +pub(super) struct Above { + pub(super) prev: Option, + pub(super) next_top: Option, + pub(super) pending: f64, +} + /// Where the next line goes: the region being filled and the previous baseline in it. #[derive(Clone)] pub(super) struct Pen<'r> { @@ -64,6 +73,8 @@ pub(super) struct Pen<'r> { pub(super) fb_min: f64, /// Further spans at the current baseline (text wrapping on both sides of an object). pub(super) queued: Vec<(f64, f64, f64)>, + /// What the line band at the current baseline was placed below (see [`Above`]). + pub(super) above: Above, /// Leading measured from em box top to em box top: where the next line's em box top goes. pub(super) model: LeadingModel, pub(super) next_top: Option, @@ -108,16 +119,21 @@ impl Pen<'_> { /// [`Pen::place`], skipping lines of a non-rectangular frame narrower than `min`. fn place_at_least(&mut self, est: Metrics, ind_l: f64, ind_r: f64, min: f64) -> Option<(f64, f64, f64, bool)> { let Some(regions) = self.regions else { - let b = self.prev.map_or(0.0, |b| self.next_baseline(b, est)); + let b = self.prev.map_or(0.0, |b| self.next_baseline(b, self.next_top, self.pending, est)); return Some((b, f64::NEG_INFINITY, f64::INFINITY, false)); }; // A further span was measured across the height of the line set before it on its baseline. // This line gets the part of it that is free across its own height: a taller line can // reach a wrap object the line before it stayed clear of. A span with no such part is - // left empty, and so is a part the line's height made narrower than `min`. + // left empty, and so is a part the line's height made narrower than `min`. A span on a + // baseline nearer the line above the band than this line's own leading sets it is left + // empty too: a taller line would reach into that line. while !self.queued.is_empty() { let (b, x0, x1) = self.queued.remove(0); let Some(r) = regions.get(self.ri) else { return Some((b, x0, x1, true)) }; + if b + EPS < self.band_baseline(r, est) { + continue; + } let mut free = r.spans(b - est.asc, b + est.desc).into_iter().filter_map(|(s, e)| { let (s, e) = (s.max(x0), e.min(x1)); let room = e - s - ind_l - ind_r; @@ -132,11 +148,8 @@ impl Pen<'_> { } loop { let r = regions.get(self.ri)?; - let mut baseline = match self.prev { - None if self.model == LeadingModel::EmBoxTop => r.top() + r.shift + est.top.max(self.fb_min), - None => r.top() + r.shift + est.first_baseline(self.fb, self.fb_min), - Some(b) => self.next_baseline(b, est) + r.gap, - }; + self.above = Above { prev: self.prev, next_top: self.next_top, pending: self.pending }; + let mut baseline = self.band_baseline(r, est); // The baseline moves down the cell a lead at a time, or a `MAX_STEPS`th of the cell's // height when that is more, in at most `MAX_STEPS` steps. let step = est.lead.max(1.0).max(r.cell.height() / MAX_STEPS as f64); @@ -188,13 +201,30 @@ impl Pen<'_> { pub(super) fn bottom(&self) -> f64 { self.regions.and_then(|r| r.get(self.ri)).map_or(f64::INFINITY, |r| r.bottom()) } - /// The baseline of the line after the one at `prev`, for a line of metrics `est`. - fn next_baseline(&self, prev: f64, est: Metrics) -> f64 { - match (self.model, self.next_top) { - (LeadingModel::EmBoxTop, Some(top)) => top + est.top + self.pending, - _ => prev + est.lead + self.pending, + /// The baseline of the line after the one at `prev`, which left the next em box top at + /// `next_top`, for a line of metrics `est` with `pending` space between them. + fn next_baseline(&self, prev: f64, next_top: Option, pending: f64, est: Metrics) -> f64 { + match (self.model, next_top) { + (LeadingModel::EmBoxTop, Some(top)) => top + est.top + pending, + _ => prev + est.lead + pending, } } + /// The highest baseline in cell `r` for a line of metrics `est` in the current line band: as + /// far below the line above the band ([`Pen::above`]) as its own leading sets it, or at the + /// cell's first baseline. + fn band_baseline(&self, r: &Region, est: Metrics) -> f64 { + let Above { prev, next_top, pending } = self.above; + match prev { + None if self.model == LeadingModel::EmBoxTop => r.top() + r.shift + est.top.max(self.fb_min), + None => r.top() + r.shift + est.first_baseline(self.fb, self.fb_min), + Some(b) => self.next_baseline(b, next_top, pending, est) + r.gap, + } + } + /// A line of metrics `m` set in a further span at baseline `b` is no nearer the line above + /// the band than its own leading sets it. + pub(super) fn clears_above(&self, b: f64, m: Metrics) -> bool { + self.regions.and_then(|r| r.get(self.ri)).is_none_or(|r| b + EPS >= self.band_baseline(r, m)) + } /// A line was set at `baseline` with metrics `m`: where the next one goes from. pub(super) fn settled(&mut self, baseline: f64, m: Metrics) { self.prev = Some(baseline); @@ -214,18 +244,30 @@ pub(super) fn tab_advance<'t, 'g>( ) -> (f64, &'t str) { use vectorcraft_doc::TabAlign; let rel = x - origin; - let seg: Vec<&SGlyph> = rest.into_iter().take_while(|g| g.ch != '\t' && g.ch != '\u{2028}').collect(); - let width: f64 = seg.iter().map(|g| g.adv).sum(); - let target = |pos: f64, align: TabAlign, on: char| match align { - TabAlign::Left => pos, - TabAlign::Right => pos - width, - TabAlign::Center => pos - width / 2.0, - TabAlign::Decimal => pos - seg.iter().take_while(|g| g.ch != on).map(|g| g.adv).sum::(), - }; - let explicit = tabs.iter().find_map(|t| { - let at = target(t.position, t.align, t.align_on); - (at > rel + 1e-6).then_some((at, t.leader.as_str())) - }); + // The text after the tab is read only when a right, center or decimal stop is reached, since + // only those align it. A tab to a default or left stop reads none of it. + let mut rest = Some(rest); + let mut seg: Vec<&SGlyph> = Vec::new(); + let mut width = 0.0; + let mut explicit = None; + for t in tabs { + if t.align != TabAlign::Left + && let Some(r) = rest.take() + { + seg = r.into_iter().take_while(|g| g.ch != '\t' && g.ch != '\u{2028}').collect(); + width = seg.iter().map(|g| g.adv).sum(); + } + let at = match t.align { + TabAlign::Left => t.position, + TabAlign::Right => t.position - width, + TabAlign::Center => t.position - width / 2.0, + TabAlign::Decimal => t.position - seg.iter().take_while(|g| g.ch != t.align_on).map(|g| g.adv).sum::(), + }; + if at > rel + 1e-6 { + explicit = Some((at, t.leader.as_str())); + break; + } + } let (at, leader) = explicit.unwrap_or_else(|| { let last = tabs.iter().map(|t| t.position).fold(0.0, f64::max).max(0.0); let base = rel.max(last); @@ -243,11 +285,16 @@ pub(super) fn drawn_after_tab<'g>(sg: &'g [SGlyph], drawn: &'g [usize], k: usize /// them) set on a line whose content starts `x_start` from the tab origin: tabs of the text take /// what [`tab_advance`] gives them from where the glyphs drawn before them end, aligning the glyphs /// drawn after them, not the width of their glyph. The tab of a list marker (length 0) keeps its -/// own width. -pub(super) fn drawn_width(sg: &[SGlyph], drawn: &[usize], tabs: &[vectorcraft_doc::TabStop], x_start: f64) -> f64 { +/// own width. With `end_trim` (a glyph index and an amount), that glyph is set that much narrower +/// where it is drawn (a line's end trim), before the tabs drawn after it take their stops. +pub(super) fn drawn_width(sg: &[SGlyph], drawn: &[usize], tabs: &[vectorcraft_doc::TabStop], x_start: f64, end_trim: Option<(usize, f64)>) -> f64 { let mut x = x_start; - for (k, g) in drawn.iter().enumerate().filter_map(|(k, &j)| sg.get(j).map(|g| (k, g))) { - x += if g.ch == '\t' && g.len > 0 { tab_advance(tabs, 0.0, x, drawn_after_tab(sg, drawn, k)).0 } else { g.adv }; + for (k, j, g) in drawn.iter().enumerate().filter_map(|(k, &j)| sg.get(j).map(|g| (k, j, g))) { + x += if g.ch == '\t' && g.len > 0 { + tab_advance(tabs, 0.0, x, drawn_after_tab(sg, drawn, k)).0 + } else { + g.adv - end_trim.filter(|&(at, _)| at == j).map_or(0.0, |(_, trim)| trim) + }; } x - x_start } @@ -256,6 +303,12 @@ pub(super) fn drawn_width(sg: &[SGlyph], drawn: &[usize], tabs: &[vectorcraft_do /// back before bisecting the earlier ones. const MAX_DRAWN_CHECKS: usize = 256; +/// Most breaks, or hyphenation points, [`break_line`] measures as drawn one by one when a glyph of +/// the line has a negative advance: a later break can then be drawn narrower than an earlier one, +/// and bisecting can miss the latest break that fits. It is also the most legal breaks such a line +/// reads past where it first overflows in the order of its text. +const MAX_DRAWN_CHECKS_STEPPING_BACK: usize = 1024; + /// Most copies of a leader drawn in one tab: a tiny type size and a far stop must not make /// millions of outlines. const MAX_LEADER_COPIES: f64 = 4096.0; @@ -357,8 +410,13 @@ pub(super) fn word_width(g: &[SGlyph], i: usize, line_end: &[f64], kinsoku: Kins /// from `i` ending before glyph `end` (with a hyphen when `hyphenated`) fits `width` as it is drawn: /// once the line holds a tab, whose width depends on what is drawn before it, the line reads on /// while the least it can be drawn at fits `width`, then ends at the latest legal break where it -/// fits as drawn (past [`MAX_DRAWN_CHECKS`] breaks back from the latest, the earlier ones without a -/// hyphen are bisected); hyphenation points are measured the same way. +/// fits as drawn (past [`MAX_DRAWN_CHECKS`] breaks back from the latest, or +/// [`MAX_DRAWN_CHECKS_STEPPING_BACK`] when a glyph of the line has a negative advance, the earlier +/// ones without a hyphen are bisected); hyphenation points are measured the same way. Once such a +/// line holds a glyph with a negative advance and has been wider than `width` in the order of its +/// text, it reads at most [`MAX_DRAWN_CHECKS_STEPPING_BACK`] legal breaks further, and a forced +/// line break right after the last of them, and ends at the latest of the breaks read that fits as +/// drawn. #[allow(clippy::too_many_arguments)] pub(super) fn break_line( text: &str, @@ -377,24 +435,26 @@ pub(super) fn break_line( fits: Option<&dyn Fn(usize, bool) -> bool>, ) -> (usize, bool) { // The line ending at `chosen`, once it holds a tab, when it fits as drawn; otherwise the latest - // of the legal `breaks` before it that fits as drawn, measuring at most MAX_DRAWN_CHECKS of - // them from the latest back and bisecting the earlier ones without a hyphen; the first of them - // when none of those measured fits. - let settle = |tabbed: bool, chosen: (usize, bool), breaks: &[(usize, bool)]| -> (usize, bool) { + // of the legal `breaks` before it that fits as drawn, measuring at most `checks` of them from + // the latest back and bisecting the earlier ones without a hyphen; the first of them when none + // of those measured fits. + let settle = |tabbed: bool, checks: usize, chosen: (usize, bool), breaks: &[(usize, bool)]| -> (usize, bool) { let Some(fits) = fits.filter(|_| tabbed) else { return chosen }; if fits(chosen.0, chosen.1) { return chosen; } let earlier = breaks.get(breaks.partition_point(|b| b.0 <= i)..breaks.partition_point(|b| b.0 < chosen.0)).unwrap_or_default(); - if let Some(&b) = earlier.iter().rev().take(MAX_DRAWN_CHECKS).find(|b| fits(b.0, b.1)) { + if let Some(&b) = earlier.iter().rev().take(checks).find(|b| fits(b.0, b.1)) { return b; } // Without a hyphen, a line that ends later is drawn no narrower, so those breaks bisect. - let rest = earlier.get(..earlier.len().saturating_sub(MAX_DRAWN_CHECKS)).unwrap_or_default(); + let rest = earlier.get(..earlier.len().saturating_sub(checks)).unwrap_or_default(); let plain: Vec<&(usize, bool)> = rest.iter().filter(|b| !b.1).collect(); let fitting = plain.partition_point(|b| fits(b.0, b.1)); fitting.checked_sub(1).and_then(|k| plain.get(k).copied()).or(earlier.first()).copied().unwrap_or(chosen) }; + // How many breaks a line measures as drawn one by one. + let checks = |back: f64| if back > 0.0 { MAX_DRAWN_CHECKS_STEPPING_BACK } else { MAX_DRAWN_CHECKS }; let mut breaks: Vec<(usize, bool)> = Vec::new(); let mut tabbed = false; if !width.is_finite() { @@ -426,6 +486,11 @@ pub(super) fn break_line( } }; let mut last_break: Option<(usize, bool)> = None; + // Whether the line, once it holds a tab and is measured as drawn, has been wider in the order of + // its text than `width`, and how many legal breaks it has read since then with a glyph stepping + // back: past MAX_DRAWN_CHECKS_STEPPING_BACK of them the line stops reading. + let mut overflowed = false; + let mut breaks_past_overflow = 0usize; // A list marker (length 0) is a cluster of its own; the line holds it and at least the first // cluster after it. let first = i + g.get(i..).unwrap_or_default().iter().take_while(|h| h.len == 0).count(); @@ -462,7 +527,7 @@ pub(super) fn break_line( let cluster_ink = if is_tab { 0.0 } else { cluster_width }; let cluster_back: f64 = if is_tab { 0.0 } else { g[j..cluster_end].iter().map(|glyph| (-glyph.adv).max(0.0)).sum() }; if gl.ch == '\u{2028}' { - return settle(tabbed, (cluster_end, false), &breaks); + return settle(tabbed, checks(back), (cluster_end, false), &breaks); } // Measured as the line is set when it ends with this cluster: only the cluster's last glyph // is narrowed, and only where the line may end. @@ -476,6 +541,7 @@ pub(super) fn break_line( // there are tabs. let stops_reached = if back + cluster_back > 0.0 { f64::NEG_INFINITY } else { nth_stop(tabs_read) - x_start }; let measured = if tabbed && fits.is_some() { (ink + cluster_ink).max(stops_reached) } else { x + cluster_width }; + overflowed |= tabbed && fits.is_some() && j > first && !gl.is_space() && x + cluster_width - end_credit > width + EPS; if j > first && !gl.is_space() && measured - end_credit > width + EPS { // It ends the line with the spaces after it. if burasagari != Burasagari::None && hangs(gl) && kinsoku_allows(g, cluster_end - 1, kinsoku) { @@ -504,12 +570,21 @@ pub(super) fn break_line( if fits.is_some() { breaks.push((cluster_end, hyphenated)); } + // A line with a glyph stepping back stops reading MAX_DRAWN_CHECKS_STEPPING_BACK + // breaks past where it first overflowed in the order of its text, and ends at the + // latest break read that fits as drawn: each of those breaks is measured one by one. + // A soft hyphen ending the text draws no hyphen there, as at the end of the text below. + // A break right before a forced line break reads on to it: the line ends there. + breaks_past_overflow += usize::from(overflowed && back > 0.0); + if breaks_past_overflow >= MAX_DRAWN_CHECKS_STEPPING_BACK && g.get(cluster_end).is_none_or(|n| n.ch != '\u{2028}') { + return settle(tabbed, checks(back), (cluster_end, hyphenated && cluster_end < g.len()), &breaks); + } } } j = cluster_end; } if j >= g.len() { - return settle(tabbed, (g.len(), false), &breaks); + return settle(tabbed, checks(back), (g.len(), false), &breaks); } // Hyphenate the word that overflows. A list marker starting the line is not part of a word. let word_start = last_break.map_or(first, |b| b.0); @@ -534,18 +609,19 @@ pub(super) fn break_line( .filter(|&k| k > 0 && kinsoku_allows(g, k - 1, kinsoku) && !splits_no_break(g, k)) .collect(); // The points the line may end at, the latest first. Measured as drawn, at most - // MAX_DRAWN_CHECKS of them are measured one by one, and the earlier ones are bisected: + // `checks(back)` of them are measured one by one, and the earlier ones are bisected: // each ends with a hyphen, so a later one is drawn no narrower. let points: Vec = pts.iter().rev().copied().filter(|&k| k <= j && k > i).collect(); let drawn = fits.filter(|_| tabbed); - for &k in points.iter().take(if drawn.is_some() { MAX_DRAWN_CHECKS } else { usize::MAX }) { + let one_by_one = checks(back); + for &k in points.iter().take(if drawn.is_some() { one_by_one } else { usize::MAX }) { let w = x_ws + g[word_start..k].iter().map(|g| g.adv).sum::() + hyphen_glyph(&g[k - 1]).adv; if drawn.map_or(w <= width + EPS, |fits| fits(k, true)) { return (k, true); } } if let Some(fits) = drawn { - let earlier: Vec = points.iter().skip(MAX_DRAWN_CHECKS).rev().copied().collect(); + let earlier: Vec = points.iter().skip(one_by_one).rev().copied().collect(); let fitting = earlier.partition_point(|&k| fits(k, true)); if let Some(&k) = fitting.checked_sub(1).and_then(|n| earlier.get(n)) { return (k, true); @@ -555,7 +631,7 @@ pub(super) fn break_line( // Break candidates and greedy overflow are cluster boundaries; hyphenation also returns only // cluster starts, so the resulting end always keeps each source cluster together. match last_break { - Some(b) if b.0 > i => settle(tabbed, b, &breaks), + Some(b) if b.0 > i => settle(tabbed, checks(back), b, &breaks), _ => (j, false), } } @@ -953,6 +1029,7 @@ fn a_pen_out_of_baseline_steps_finds_no_room() { fb: FirstBaseline::Ascent, fb_min: 0.0, queued: vec![], + above: Default::default(), model: LeadingModel::default(), next_top: None, no_room_for: f64::INFINITY, diff --git a/crates/text/src/layout/flow.rs b/crates/text/src/layout/flow.rs index 1ee9a3fe50..30b615c5fc 100644 --- a/crates/text/src/layout/flow.rs +++ b/crates/text/src/layout/flow.rs @@ -24,6 +24,10 @@ fn pushes_in(para: &ParaStyle) -> bool { /// Paragraphs longer than this (glyphs) are always broken line by line. const MAX_COMPOSE_GLYPHS: usize = 200_000; +/// The widths tried, halving the difference each time, for the longest break of a line placed again +/// at its own metrics in more room than it was broken in ([`place_flow_line`]). +const REFIT_STEPS: usize = 24; + /// Whether every line of area type in `regions` is as wide however tall it is and wherever it is set: /// rectangular cells without text wrap. fn constant_width(regions: Option<&[Region]>) -> bool { @@ -173,6 +177,7 @@ pub(super) fn flow(cx: &mut Ctx<'_>, paras: &[Range], t: &TextObject, reg fb: cx.opts.first_baseline, fb_min: cx.opts.first_baseline_min, queued: vec![], + above: Default::default(), model: t.para_at(0).leading_model, next_top: None, no_room_for: f64::INFINITY, @@ -415,25 +420,31 @@ fn place_flow_line(cx: &mut Ctx<'_>, pen: &mut Pen<'_>, context: &mut PlacementC let word = word_width(sg, *i, line_end, para.kinsoku); // A composed line in a frame whose lines are not all as wide is placed at its own tallest // metrics, as the composer placed it (`shaped::Shaped`): its room is the room across its height. - let est = match composed.as_ref().and_then(|lines| lines.get(*para_line)) { + let composed_line = composed.as_ref().and_then(|lines| lines.get(*para_line)).is_some_and(|&(end, _)| end > *i); + let mut est = match composed.as_ref().and_then(|lines| lines.get(*para_line)) { Some(&(end, _)) if end > *i && !constant_width(pen.regions) => sg.get(*i..end).and_then(Metrics::max).unwrap_or(est), _ => est, }; + // A line broken here in such a frame is placed again when it turns out taller than it was + // placed: its room is the room across its own height. + let refit = !composed_line && pen.regions.is_some() && !constant_width(pen.regions); // Place, break, then settle the baseline on the line's real metrics (moving on to the // next row/column if it no longer fits). loop { + let before = refit.then(|| pen.clone()); let first_in_region = pen.prev.is_none(); - let Some((mut baseline, x0, x1, same_baseline)) = pen.place(est, ind_l, ind_r, word) else { + let Some((mut baseline, mut x0, mut x1, same_baseline)) = pen.place(est, ind_l, ind_r, word) else { cx.out.overflow = cx.text.len() > if *i < n { sg[*i].byte } else { pr.start }; return None; }; - let width = x1 - x0 - ind_l - ind_r; let hyphenate = (para.hyphenate && (*hyphen_limit == 0 || *hyphen_run < *hyphen_limit)).then_some((¶.hyphenation, *zone)); - let (end, hyph, pushed_in) = match composed.as_ref().and_then(|lines| lines.get(*para_line)) { + let glyphs: &[SGlyph] = sg; + // The line broken in room `width` wide: its end, whether it ends with a hyphen, and whether + // it pushed characters in. + let break_in = |width: f64| match composed.as_ref().and_then(|lines| lines.get(*para_line)) { Some(&(end, hyph)) if end > *i => (end, hyph, false), _ if *i < n => { let start = *i; - let glyphs: &[SGlyph] = sg; // A horizontal line with right-to-left text is drawn in another order than its // text's, and its tabs take their stops in the order they are drawn: whether the line // ending before glyph `end` fits is measured as it is drawn ([`drawn_width`]). @@ -449,8 +460,9 @@ fn place_flow_line(cx: &mut Ctx<'_>, pen: &mut Pen<'_>, context: &mut PlacementC .filter(|&j| j < trimmed) .collect(); let hyphen = if hyphenated { end.checked_sub(1).and_then(|k| glyphs.get(k)).map_or(0.0, |g| hyphen_glyph(g).adv) } else { 0.0 }; - let credit = trimmed.checked_sub(1).filter(|&k| k >= start).and_then(|k| line_end.get(k)).copied().unwrap_or(0.0); - drawn_width(glyphs, &drawn, ¶.tabs, ind_l) + hyphen - credit <= width + EPS + // The last glyph's end trim comes off where it is drawn, before the tabs after it. + let credit = trimmed.checked_sub(1).filter(|&k| k >= start).and_then(|k| line_end.get(k).map(|&trim| (k, trim))); + drawn_width(glyphs, &drawn, ¶.tabs, ind_l, credit) + hyphen <= width + EPS }; let fits: Option<&dyn Fn(usize, bool) -> bool> = (!cx.vertical && bidi.is_some_and(|b| b.has_rtl())).then_some(&drawn_fits); let line = |ty| { @@ -478,8 +490,61 @@ fn place_flow_line(cx: &mut Ctx<'_>, pen: &mut Pen<'_>, context: &mut PlacementC } _ => (n, false, false), }; - let m = Metrics::max(&sg[*i..end]).unwrap_or(*pm); - baseline += if same_baseline || (pen.regions.is_none() && first_in_region) { + let (mut end, mut hyph, mut pushed_in) = break_in(x1 - x0 - ind_l - ind_r); + let metrics = |end: usize| glyphs.get(*i..end).and_then(Metrics::max).unwrap_or(*pm); + let m = metrics(end); + // The baseline moves from where `est` placed it to where the line's metrics set it, unless + // the line was placed at metrics of its own (below). + let mut settle = true; + if let Some(before) = before + && m != est + { + if m.union(est) != est { + // Taller than it was placed: place it again at metrics that hold both, and break it + // again in the room there. + *pen = before; + est = est.union(m); + continue; + } + // Broken again in the room of a taller line, it no longer holds what made that line + // taller. It goes where its own metrics place it when the room there holds the room it + // was broken in, and otherwise stays where it was placed, inside the room measured. + settle = false; + let mut own = before; + if let Some((b, a, z, _)) = own.place(m, ind_l, ind_r, word) + && a <= x0 + EPS + && z >= x1 - EPS + { + // The room there may hold more of the line, up to what would make it taller than + // `m`: the longest break that does not is between the two widths (a line breaks no + // earlier in more room). + let (mut lo, mut hi) = (x1 - x0 - ind_l - ind_r, z - a - ind_l - ind_r); + let wider = break_in(hi); + if metrics(wider.0).union(m) == m { + (end, hyph, pushed_in) = wider; + } else { + for _ in 0..REFIT_STEPS { + let mid = (lo + hi) / 2.0; + let line = break_in(mid); + if metrics(line.0).union(m) == m { + (end, hyph, pushed_in) = line; + lo = mid; + } else { + hi = mid; + } + } + } + *pen = own; + (baseline, x0, x1) = (b, a, z); + } + } + let m = metrics(end); + if same_baseline && !pen.clears_above(baseline, m) { + // A glyph taller than the first one sets the line lower than the span's baseline: the + // span is left empty, and the line goes in the next span or on the next baseline. + continue; + } + baseline += if !settle || same_baseline || (pen.regions.is_none() && first_in_region) { 0.0 } else if pen.model == LeadingModel::EmBoxTop { // The em box top is fixed (the frame's top, or the line above's): the baseline @@ -544,6 +609,9 @@ struct LineJustification { fit: LineFit, start_x: f64, after: Vec>, + /// The warichu glyphs drawn inside a block already started, by offset from the line's first + /// glyph ([`blocks_begun`]). + begun: Vec, kashidas: Vec<(usize, f64)>, /// Right-aligned area type: the line's last tab, which takes the text after it to the right /// edge (the text before it sits at its stops, from the left edge). @@ -649,9 +717,11 @@ fn prepare_line_geometry(cx: &Ctx<'_>, t: &TextObject, paragraph: &ParagraphData let line_end = sg.get(position.end).map_or(paragraph.pr.end, |g| g.byte); let order = visual_order(paragraph.bidi.as_ref().filter(|_| !cx.vertical), paragraph.pr.start, line_start..line_end, &sg[index..position.end]); // The line is as wide as it is drawn: its glyphs before its trailing spaces in drawing order, - // each tab up to its stop from where the glyphs drawn before it end. + // each tab up to its stop from where the glyphs drawn before it end, with the last glyph's end + // trim taken off where it is drawn. let measured: Vec = order.iter().map(|&offset| index + offset).filter(|&j| j < trimmed).collect(); - let measured_width = drawn_width(sg, &measured, ¶.tabs, position.ind_l) + hyphen.as_ref().map_or(0.0, |g| g.adv) - end_trim; + let trim_at = trimmed.checked_sub(1).filter(|&k| k >= index).map(|k| (k, end_trim)); + let measured_width = drawn_width(sg, &measured, ¶.tabs, position.ind_l, trim_at) + hyphen.as_ref().map_or(0.0, |g| g.adv); // The glyphs before `stop` in visual order, each with the advance it is set with. A list // marker does not hang: it is counted with no width. let visible = |stop: usize| -> (Vec, Vec<(&SGlyph, f64)>) { @@ -805,14 +875,14 @@ fn visible_after(index: usize, glyph: usize, after: &[Option], sg: &[SGly next } -// The glyph after which a gap between drawn glyphs opens, and the visible glyph that follows it: -// not a held glyph, and never a zero-width format control on either side. -fn gap_pair<'a>(glyph: usize, held: &[usize], after: &[Option], index: usize, sg: &'a [SGlyph]) -> Option<(&'a SGlyph, &'a SGlyph)> { +// The glyph after which a gap between drawn glyphs opens, and the visible glyph that follows it +// with its index: not a held glyph, and never a zero-width format control on either side. +fn gap_pair<'a>(glyph: usize, held: &[usize], after: &[Option], index: usize, sg: &'a [SGlyph]) -> Option<(&'a SGlyph, &'a SGlyph, usize)> { if held.contains(&glyph) { return None; } let a = sg.get(glyph).filter(|a| !is_format_control(a.ch))?; - visible_after(index, glyph, after, sg).and_then(|next| sg.get(next)).map(|b| (a, b)) + visible_after(index, glyph, after, sg).and_then(|next| sg.get(next).map(|b| (a, b, next))) } // Are `a` and `b` glyphs of the same warichu block? Right to left, the bidi order can draw a @@ -821,18 +891,61 @@ fn same_warichu_block(a: &SGlyph, b: &SGlyph) -> bool { a.wari.zip(b.wari).is_some_and(|(first, second)| first.start == second.start) } +// Is glyph `next` drawn inside a block the line has already started: a tate-chu-yoko glyph after +// its block's first, or a warichu glyph drawn after another glyph of its block (`begun`, by offset +// from the line's first glyph, from [`blocks_begun`])? A warichu block starts at the first of its +// glyphs drawn on the line, which right to left is not the block's first glyph. +fn continues_drawn_block(next: usize, index: usize, begun: &[bool], sg: &[SGlyph]) -> bool { + let Some(b) = sg.get(next) else { return false }; + match (b.wari, next.checked_sub(index).and_then(|k| begun.get(k))) { + (Some(_), Some(&begun)) => begun, + _ => b.continues_block(), + } +} + +// The warichu glyphs of `line` drawn after another glyph of their block, by offset from the line's +// first glyph. A block the bidi order interleaves with another keeps its start. +fn blocks_begun(line: &LineGeometry, sg: &[SGlyph]) -> Vec { + let len = line.body.saturating_sub(line.index); + // Each glyph's block, as the offset of the block's first glyph: a block's glyphs are neighbors + // in `sg`, and a block stays on one line. + let mut first: Vec = Vec::with_capacity(len); + for k in 0..len { + let pair = k.checked_sub(1).and_then(|p| sg.get(line.index + p)).zip(sg.get(line.index + k)); + let block = match first.last() { + Some(&f) if pair.is_some_and(|(a, b)| same_warichu_block(a, b)) => f, + _ => k, + }; + first.push(block); + } + let mut started = vec![false; len]; + let mut begun = vec![false; len]; + for &j in &line.drawn { + let Some(k) = j.checked_sub(line.index).filter(|_| sg.get(j).is_some_and(|g| g.wari.is_some())) else { continue }; + let Some(&f) = first.get(k) else { continue }; + if let (Some(seen), Some(slot)) = (started.get(f).copied(), begun.get_mut(k)) { + *slot = seen; + } + if let Some(seen) = started.get_mut(f) { + *seen = true; + } + } + begun +} + // Japanese (and Chinese) lines are justified between their characters (JLREQ 3.8): the // gaps next to a CJK character, not inside a Latin word, a tate-chu-yoko or warichu block or a -// shaped cluster. -pub(super) fn is_cjk_gap(glyph: usize, held: &[usize], after: &[Option], index: usize, sg: &[SGlyph]) -> bool { - gap_pair(glyph, held, after, index, sg).is_some_and(|(a, b)| { +// shaped cluster. `begun` holds the warichu glyphs drawn inside a block already started +// ([`blocks_begun`]). +pub(super) fn is_cjk_gap(glyph: usize, held: &[usize], (after, begun): (&[Option], &[bool]), index: usize, sg: &[SGlyph]) -> bool { + gap_pair(glyph, held, after, index, sg).is_some_and(|(a, b, next)| { a.byte != b.byte && !a.is_space() && !b.is_space() - && !b.continues_block() && !same_warichu_block(a, b) && a.ch != '\t' && (is_cjk(a.ch) || is_cjk(b.ch)) + && !continues_drawn_block(next, index, begun, sg) }) && !in_pair(glyph, index, after, sg) } @@ -861,13 +974,20 @@ fn in_pair(glyph: usize, index: usize, after: &[Option], sg: &[SGlyph]) - // its drawn glyphs: not after a held glyph, nor inside a tate-chu-yoko block (one cell) or a // warichu block (set as one piece), a shaped cluster, whose glyphs (a letter and its combining marks, a conjunct and its matra) stay // together, or an inseparable pair. On a line that ends in a drawn hyphen, the gap before the -// hyphen counts too: it follows the line's last visible glyph. -pub(super) fn is_letter_gap(glyph: usize, held: &[usize], after: &[Option], index: usize, sg: &[SGlyph], hyphen: bool) -> bool { +// hyphen counts too: it follows the line's last visible glyph. `begun` is as for [`is_cjk_gap`]. +pub(super) fn is_letter_gap( + glyph: usize, + held: &[usize], + (after, begun): (&[Option], &[bool]), + index: usize, + sg: &[SGlyph], + hyphen: bool, +) -> bool { if held.contains(&glyph) || sg.get(glyph).is_none_or(|a| is_format_control(a.ch)) || in_pair(glyph, index, after, sg) { return false; } match gap_pair(glyph, held, after, index, sg) { - Some((a, b)) => a.byte != b.byte && !b.continues_block() && !same_warichu_block(a, b), + Some((a, b, next)) => a.byte != b.byte && !same_warichu_block(a, b) && !continues_drawn_block(next, index, begun, sg), None => hyphen, } } @@ -974,7 +1094,8 @@ fn justify_flow_line(cx: &Ctx<'_>, paragraph: &ParagraphData<'_, '_>, line: &Lin *slot = Some(b); } } - let cjk_gaps = (line.index..line.body).filter(|&j| free(j) && is_cjk_gap(j, held, &after, line.index, sg)).count(); + let begun = blocks_begun(line, sg); + let cjk_gaps = (line.index..line.body).filter(|&j| free(j) && is_cjk_gap(j, held, (&after, &begun), line.index, sg)).count(); // Single Word Justification: a justified line holding one word (no word space) is // spread between its letters (Full Justify) or aligned. A tab separates two words. let single_word = justify && fixed.is_empty() && spaces == 0 && cjk_gaps == 0; @@ -1013,7 +1134,7 @@ fn justify_flow_line(cx: &Ctx<'_>, paragraph: &ParagraphData<'_, '_>, line: &Lin let pushed_in = line.position.pushed_in && paragraph.regions.is_some() && cjk_gaps > 0 && width > room + EPS; if pushed_in { let ems: f64 = (line.index..line.body) - .filter(|&j| free(j) && is_cjk_gap(j, held, &after, line.index, sg) && may_squeeze(&sg[j])) + .filter(|&j| free(j) && is_cjk_gap(j, held, (&after, &begun), line.index, sg) && may_squeeze(&sg[j])) .map(|j| squeeze_em(&sg[j], cx.vertical)) .sum(); if ems > EPS { @@ -1044,7 +1165,7 @@ fn justify_flow_line(cx: &Ctx<'_>, paragraph: &ParagraphData<'_, '_>, line: &Lin let used: f64 = flex.iter().map(|f| fit.letter(f) + fit.glyph(f)).sum(); let rest = room - width - used; let hyphen = line.hyphen.is_some(); - let gaps = (line.index..line.body).filter(|&j| free(j) && is_letter_gap(j, held, &after, line.index, sg, hyphen)).count(); + let gaps = (line.index..line.body).filter(|&j| free(j) && is_letter_gap(j, held, (&after, &begun), line.index, sg, hyphen)).count(); if gaps > 0 && rest > EPS { per_gap = rest / gaps as f64; } @@ -1076,7 +1197,7 @@ fn justify_flow_line(cx: &Ctx<'_>, paragraph: &ParagraphData<'_, '_>, line: &Lin _ => line.ax1 + line.opt_r - width, } }; - LineJustification { per_space, per_gap, per_cjk, squeeze, fit, start_x, after, kashidas, last_tab, trailing, fixed } + LineJustification { per_space, per_gap, per_cjk, squeeze, fit, start_x, after, begun, kashidas, last_tab, trailing, fixed } } /// The advance and leader of tab `glyph_index` of `line`, drawn at `order_index` of @@ -1203,10 +1324,10 @@ fn emit_flow_line(cx: &mut Ctx<'_>, pen: &mut Pen<'_>, paragraph: &ParagraphData advance += justification.fit.letter(&flex) + justification.fit.glyph(&flex); scale = justification.fit.glyph_scale(&flex); if justification.per_cjk != 0.0 || justification.squeeze != 0.0 { - if is_cjk_gap(glyph_index, &line.held, &justification.after, index, sg) { + if is_cjk_gap(glyph_index, &line.held, (&justification.after, &justification.begun), index, sg) { advance += justification.per_cjk + squeeze_after(glyph, justification.squeeze, cx.vertical); } - } else if is_letter_gap(glyph_index, &line.held, &justification.after, index, sg, line.hyphen.is_some()) { + } else if is_letter_gap(glyph_index, &line.held, (&justification.after, &justification.begun), index, sg, line.hyphen.is_some()) { advance += justification.per_gap; } } diff --git a/crates/text/src/layout/region.rs b/crates/text/src/layout/region.rs index 34c48942d5..f2a0f1bbfe 100644 --- a/crates/text/src/layout/region.rs +++ b/crates/text/src/layout/region.rs @@ -120,7 +120,8 @@ fn near_segment_in_band(a: Point, b: Point, top: f64, bottom: f64, r: f64) -> Op } /// [`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. +/// `inset` to an edge of `polys` (holes included), measured from the edge itself. A stretch of an +/// edge that contours meet along bounds no part of the shape, so the inset does not apply beside it. 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() { @@ -130,10 +131,68 @@ fn band_inset_intervals(polys: &[Vec], top: f64, bottom: f64, inset: f64) return vec![]; } 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))); + let edges = boundary_segments(polys, |lo, hi| hi > top - inset && lo < bottom + inset); + let near = edges.into_iter().filter_map(|(a, b)| near_segment_in_band(a, b, top, bottom, inset)); subtract_intervals(&iv, &union_intervals(near.collect())) } +/// The stretches of the edges of `polys` that bound the shape (even-odd), among the edges whose y +/// range `lo..hi` `keep` accepts. Edges that lie exactly along one line and overlap there (contours +/// that meet along an edge, however each one divides it) count by parity, as in +/// [`slant_boundaries`]: a stretch that an even number of them cover has the shape on both sides +/// and is left out. Edges of no length are left out. At most [`MAX_EDGE_PAIRS`] pairs are compared; +/// edges left unpaired count whole. +fn boundary_segments(polys: &[Vec], keep: impl Fn(f64, f64) -> bool) -> Vec<(Point, Point)> { + fn root(parent: &mut [usize], mut i: usize) -> usize { + while parent[i] != i { + parent[i] = parent[parent[i]]; + i = parent[i]; + } + i + } + let mut edges: Vec<(Point, Point)> = polys + .iter() + .flat_map(|p| (0..p.len()).map(move |i| (p[i], p[(i + 1) % p.len()]))) + .filter(|&(a, b)| a != b && keep(a.y.min(b.y), a.y.max(b.y))) + .collect(); + // Edges along one line overlap in x, so only edges whose x ranges overlap are compared. + edges.sort_by(|u, v| u.0.x.min(u.1.x).total_cmp(&v.0.x.min(v.1.x))); + let mut parent: Vec = (0..edges.len()).collect(); + let mut pairs = 0; + 'edges: for (i, &(p, q)) in edges.iter().enumerate() { + // The x ranges of edges along one line can differ by rounding, as in `slant_boundaries`. + let scale = p.x.abs().max(p.y.abs()).max(q.x.abs()).max(q.y.abs()).max(1.0); + let x1 = p.x.max(q.x) + 4.0 * f64::EPSILON * scale; + for (j, &(r, s)) in edges.iter().enumerate().skip(i + 1).take_while(|(_, o)| o.0.x.min(o.1.x) <= x1) { + pairs += 1; + if pairs > MAX_EDGE_PAIRS { + break 'edges; + } + if on_line_exactly(p, q, r) && on_line_exactly(p, q, s) { + let (a, b) = (root(&mut parent, i), root(&mut parent, j)); + parent[a] = b; + } + } + } + let mut groups: Vec<(usize, usize)> = (0..edges.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(edges[*i]); + continue; + } + // The stretches an odd number of the edges cover: pairs of their ends, sorted along the + // line by whichever coordinate changes more along it. + let (p, q) = edges[run[0].1]; + let by_x = (q.x - p.x).abs() >= (q.y - p.y).abs(); + let mut ends: Vec = run.iter().flat_map(|&(_, i)| [edges[i].0, edges[i].1]).collect(); + ends.sort_by(|a, b| if by_x { a.x.total_cmp(&b.x) } else { a.y.total_cmp(&b.y) }); + out.extend(ends.as_chunks::<2>().0.iter().filter(|c| c[0] != c[1]).map(|c| (c[0], c[1]))); + } + out +} + /// Union of sorted-or-not intervals. fn union_intervals(mut v: Vec<(f64, f64)>) -> Vec<(f64, f64)> { v.sort_by(|a, b| a.0.total_cmp(&b.0)); @@ -206,6 +265,10 @@ type Slant = (Point, Point, (f64, f64), (f64, f64)); /// The line through two points. type Line = (Point, Point); +/// The x at which an edge crosses a height, and the line it was found along (`None` when it is +/// the edge's end). +type Crossing = (f64, Option); + /// 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) @@ -327,7 +390,7 @@ fn slant_boundaries(slants: &mut [Slant]) -> (Vec<(f64, f64)>, bool, Vec) } /// The most pieces a line's band is cut into to keep it inside an Invert Wrap shape grown by its -/// offset. +/// offset, when [`grown_band`] gives up, or out of a wrap shape shrunk 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 @@ -367,20 +430,36 @@ fn band_intervals(polys: &[Vec], top: f64, bottom: f64) -> Vec<(f64, f64) let (edges, _, mut xs) = band_boundaries(polys, top, bottom); // The edges of contours that meet along an edge cross the middle of the band at the same x, // since each is crossed on the line through the same two points: the intervals on either side - // join there (an edge that bounds the shape there is still subtracted). Intervals with any gap + // join there (an edge that bounds the shape there is still subtracted). Crossings of other edges + // that round to the same x join only when both lie exactly at that x. Intervals with any gap // between them stay apart. - xs.sort_by(f64::total_cmp); - let mut mid: Vec<(f64, f64)> = xs.as_chunks::<2>().0.iter().map(|c| (c[0], c[1])).collect(); - mid.dedup_by(|next, prev| { - let seam = next.0 <= prev.1; - if seam { - prev.1 = prev.1.max(next.1); + let y = (top + bottom) * 0.5; + xs.sort_by(|a, b| a.0.total_cmp(&b.0).then_with(|| line_order(a.1, b.1))); + let mut mid: Vec<(f64, f64)> = Vec::new(); + let mut last: Option = None; + for &[(s, ks), (t, kt)] in xs.as_chunks::<2>().0 { + match mid.last_mut() { + Some(prev) if s <= prev.1 && ((ks.is_some() && last == ks) || (exactly_at(last, s, y) && exactly_at(ks, s, y))) => prev.1 = prev.1.max(t), + _ => mid.push((s, t)), } - seam - }); + last = kt; + } subtract_intervals(&mid, &edges) } +/// An order of the lines crossings of the band's middle were found along, which keeps crossings +/// along one line next to each other; a crossing at an edge's end (`None`) comes first. +fn line_order(a: Option, b: Option) -> std::cmp::Ordering { + let key = |l: Option| l.map_or([f64::NEG_INFINITY; 4], |(p, q)| [p.x, p.y, q.x, q.y]); + key(a).iter().zip(key(b)).fold(std::cmp::Ordering::Equal, |o, (u, v)| o.then(u.total_cmp(&v))) +} + +/// Does a crossing of the height `y` at `x`, found along `line` (or at an edge's end when `None`), +/// lie exactly at `x`? +fn exactly_at(line: Option, x: f64, y: f64) -> bool { + line.is_none_or(|(p, q)| on_line_exactly(p, q, Point::new(x, y))) +} + /// 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 @@ -423,17 +502,19 @@ fn band_cover_closed(polys: &[Vec], top: f64, bottom: f64) -> Vec<(f64, f /// 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. Last, the x /// at which the edges cross the middle of the band (even-odd, as [`poly_intervals`] finds them), -/// unsorted, each found along the line [`slant_boundaries`] gives its edge. -fn band_boundaries(polys: &[Vec], top: f64, bottom: f64) -> (Vec<(f64, f64)>, bool, Vec) { +/// unsorted, each found along the line [`slant_boundaries`] gives its edge, with that line (`None` +/// for a crossing at an edge's end). +fn band_boundaries(polys: &[Vec], top: f64, bottom: f64) -> (Vec<(f64, f64)>, bool, Vec) { let (mut flats, mut slants) = band_edges(polys, top, bottom); let (mut edges, paired, lines) = slant_boundaries(&mut slants); let y = (top + bottom) * 0.5; - let mut xs: Vec = slants.iter().zip(&lines).filter(|((p, q, ..), _)| p.y <= y && y < q.y).map(|(_, &(p, q))| line_x(p, q, y)).collect(); + let mut xs: Vec = + slants.iter().zip(&lines).filter(|((p, q, ..), _)| p.y <= y && y < q.y).map(|(_, &(p, q))| (line_x(p, q, y), Some((p, q)))).collect(); // When the middle is the band's bottom (a band of no height), the edges that start there cross // it but are not in the band: they cross it at their lower end. if y == bottom { let starts = polys.iter().flat_map(|poly| poly.iter().zip(poly.iter().cycle().skip(1))); - xs.extend(starts.filter(|(a, b)| a.y != b.y && a.y.min(b.y) == y).map(|(a, b)| if a.y < b.y { a.x } else { b.x })); + xs.extend(starts.filter(|(a, b)| a.y != b.y && a.y.min(b.y) == y).map(|(a, b)| (if a.y < b.y { a.x } else { b.x }, None))); } // The x covered by an odd number of the horizontal edges at one height: pairs of their // sorted ends. @@ -500,6 +581,9 @@ fn eroded_cover(polys: &[Vec], top: f64, bottom: f64, d: f64) -> Vec<(f64 cuts.dedup(); } } + // A stretch of an edge that contours meet along bounds no part of the shape, so the shape is + // not shrunk beside it. + let edges = boundary_segments(polys, |lo, hi| hi > top - r && lo < bottom + r); let mut out = Vec::new(); // A band of no height keeps its two equal cuts: one piece of no height, measured at its y. for w in cuts.windows(2) { @@ -510,19 +594,307 @@ fn eroded_cover(polys: &[Vec], top: f64, bottom: f64, d: f64) -> Vec<(f64 } // The points closer than `d` to an edge make a convex shape, so a vertical line within // the piece lies in it when both its ends do. - let near = polys.iter().flat_map(|p| { - (0..p.len()).filter_map(move |i| { - let (s, t) = (p[i], p[(i + 1) % p.len()]); - let (u, v) = (near_segment(s, t, a, r)?, near_segment(s, t, b, r)?); - let (x, y) = (u.0.max(v.0), u.1.min(v.1)); - (y > x).then_some((x, y)) - }) + let near = edges.iter().filter_map(|&(s, t)| { + let (u, v) = (near_segment(s, t, a, r)?, near_segment(s, t, b, r)?); + let (x, y) = (u.0.max(v.0), u.1.min(v.1)); + (y > x).then_some((x, y)) }); out.extend(subtract_intervals(&cover, &union_intervals(near.collect()))); } union_intervals(out) } +/// The most steps [`grown_band`] takes for one band and one wrap shape: edges, pairs of edges and +/// pairs of grown pieces looked at, and pieces looked at for each x it tests. +const MAX_INVERT_WRAP_WORK: usize = 1 << 20; + +#[cfg(test)] +thread_local! { + /// How many steps [`grown_band`] took on this thread. + static GROWN_BAND_WORK: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Adds `n` to `work`; false when that passes [`MAX_INVERT_WRAP_WORK`]. +fn spend(work: &mut usize, n: usize) -> bool { + *work = work.saturating_add(n); + #[cfg(test)] + GROWN_BAND_WORK.set(GROWN_BAND_WORK.get().saturating_add(n)); + *work <= MAX_INVERT_WRAP_WORK +} + +/// The x of the edge `p`–`q` (not horizontal) at `y`: the x of its end at that end's height. +fn edge_x(p: Point, q: Point, y: f64) -> f64 { + if y == p.y { + p.x + } else if y == q.y { + q.x + } else { + line_x(p, q, y) + } +} + +/// A trapezoid with a horizontal top and bottom: its top and bottom heights, then the x of its left +/// edge at each of them, then the x of its right edge at each of them. +type Trapezoid = (f64, f64, f64, f64, f64, f64); + +/// The shape `polys` (even-odd) between the heights `y0..y1` (`y0 < y1`) as trapezoids with +/// horizontal tops and bottoms, cut at each anchor's height and wherever two edges cross, whose union +/// (each trapezoid with its outline) is the shape with its outline there. Edges that lie along one +/// another give trapezoids that touch, and contours that cancel each other give none. `None` when +/// [`MAX_INVERT_WRAP_WORK`] runs out. +fn trapezoids(polys: &[Vec], y0: f64, y1: f64, work: &mut usize) -> Option> { + let mut edges: Vec<(Point, Point)> = polys + .iter() + .flat_map(|p| (0..p.len()).map(move |i| (p[i], p[(i + 1) % p.len()]))) + .filter(|(a, b)| a.y != b.y && a.y.max(b.y) > y0 && a.y.min(b.y) < y1) + .map(|(a, b)| if a.y < b.y { (a, b) } else { (b, a) }) + .collect(); + if !spend(work, edges.len()) { + return None; + } + edges.sort_by(|u, v| u.0.y.total_cmp(&v.0.y)); + let mut ys: Vec = edges.iter().flat_map(|(p, q)| [p.y, q.y]).filter(|&y| y > y0 && y < y1).chain([y0, y1]).collect(); + ys.sort_by(f64::total_cmp); + ys.dedup(); + let mut out = Vec::new(); + let (mut next, mut active) = (0, Vec::new()); + for w in ys.windows(2) { + let (a, b) = (w[0], w[1]); + // The edges that span the slab `a..b`: every anchor's height is a cut, so an edge that + // starts at or above `a` and ends below it reaches `b`. + while let Some(&e) = edges.get(next).filter(|e| e.0.y <= a) { + active.push(e); + next += 1; + } + active.retain(|e: &(Point, Point)| e.1.y >= b); + if !spend(work, active.len()) { + return None; + } + // The heights within the slab at which two edges cross: their order left to right differs + // at its top and bottom. + let mut cuts = vec![a, b]; + let ends: Vec<(f64, f64)> = active.iter().map(|&(p, q)| (edge_x(p, q, a), edge_x(p, q, b))).collect(); + let mut order: Vec = (0..ends.len()).collect(); + order.sort_by(|&i, &j| ends[i].0.total_cmp(&ends[j].0).then(ends[i].1.total_cmp(&ends[j].1))); + if order.windows(2).any(|w| ends[w[0]].1 > ends[w[1]].1) { + if !spend(work, ends.len() * ends.len()) { + return None; + } + for (i, &(sa, sb)) in ends.iter().enumerate() { + for &(ta, tb) in &ends[i + 1..] { + let (da, db) = (sa - ta, sb - tb); + if da * db < 0.0 { + let y = a + (b - a) * (da / (da - db)); + if y > a && y < b { + cuts.push(y); + } + } + } + } + cuts.sort_by(f64::total_cmp); + cuts.dedup(); + } + for c in cuts.windows(2) { + let (c, d) = (c[0], c[1]); + // No two edges cross within `c..d`, so their order at its middle holds throughout, and + // the shape (even-odd) lies between the first and second, the third and fourth, and so on. + let mid = (c + d) * 0.5; + let mut xs: Vec<(f64, f64, f64)> = active.iter().map(|&(p, q)| (line_x(p, q, mid), edge_x(p, q, c), edge_x(p, q, d))).collect(); + if !spend(work, xs.len()) { + return None; + } + xs.sort_by(|u, v| u.0.total_cmp(&v.0)); + for pair in xs.as_chunks::<2>().0 { + let ((_, l0, l1), (_, r0, r1)) = (pair[0], pair[1]); + if r0 > l0 || r1 > l1 { + out.push((c, d, l0, l1, r0, r1)); + } + } + } + } + Some(out) +} + +/// A convex polygon as its lower and upper outlines (the least and the greatest y at each x), each +/// left to right from its least x to its greatest, with its x range and y range. +struct Convex { + lower: Vec, + upper: Vec, + xs: (f64, f64), + ys: (f64, f64), +} + +impl Convex { + /// The convex hull of `pts`. + fn hull(mut pts: Vec) -> Convex { + let cross = |o: Point, a: Point, b: Point| (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x); + let chain = |pts: &[Point], turns: fn(f64) -> bool| { + let mut out: Vec = Vec::with_capacity(pts.len()); + for &p in pts { + while let [.., o, a] = out[..] { + if turns(cross(o, a, p)) { + break; + } + out.pop(); + } + out.push(p); + } + // The points at the greatest x after the first are on the other outline. + while let [.., a, b] = out[..] { + if a.x != b.x { + break; + } + out.pop(); + } + out + }; + pts.sort_by(|p, q| p.x.total_cmp(&q.x).then(p.y.total_cmp(&q.y))); + let lower = chain(&pts, |c| c > 0.0); + pts.sort_by(|p, q| p.x.total_cmp(&q.x).then(q.y.total_cmp(&p.y))); + let upper = chain(&pts, |c| c < 0.0); + let xs = (lower.first().map_or(f64::NAN, |p| p.x), lower.last().map_or(f64::NAN, |p| p.x)); + let ys = (lower.iter().fold(f64::INFINITY, |m, p| m.min(p.y)), upper.iter().fold(f64::NEG_INFINITY, |m, p| m.max(p.y))); + Convex { lower, upper, xs, ys } + } + + /// The y range of the polygon at `x`, within its x range. + fn at(&self, x: f64) -> (f64, f64) { + (chain_y(&self.lower, x), chain_y(&self.upper, x)) + } +} + +/// The y of the outline `chain` (left to right, no two points at one x) at `x`, within its x range. +fn chain_y(chain: &[Point], x: f64) -> f64 { + let i = chain.partition_point(|p| p.x < x); + match (i.checked_sub(1).and_then(|h| chain.get(h)), chain.get(i)) { + (Some(p), Some(q)) => p.y + (x - p.x) / (q.x - p.x) * (q.y - p.y), + (None, Some(q)) => q.y, + (Some(p), None) => p.y, + (None, None) => f64::NAN, + } +} + +/// The x at which some segment of `a` and some segment of `b` (outlines left to right) are at the +/// same y, strictly between the ends of the x range they share. +fn chain_crossings(a: &[Point], b: &[Point], out: &mut Vec, work: &mut usize) -> bool { + for s in a.windows(2) { + let first = b.partition_point(|q| q.x <= s[0].x).saturating_sub(1); + for t in b[first..].windows(2).take_while(|t| t[0].x < s[1].x) { + if !spend(work, 1) { + return false; + } + let (x0, x1) = (s[0].x.max(t[0].x), s[1].x.min(t[1].x)); + if x1 <= x0 { + continue; + } + let (d0, d1) = (chain_y(s, x0) - chain_y(t, x0), chain_y(s, x1) - chain_y(t, x1)); + if d0 * d1 < 0.0 { + out.push(x0 + (x1 - x0) * (d0 / (d0 - d1))); + } + } + } + true +} + +/// The x within `lo..hi` at which the shape `polys` (even-odd) grown by `off` (> 0) across and +/// along holds every height of the band `top..bottom` (`top <= bottom`): the x whose vertical line +/// across the band has each of its points within `off`, across and along, of the shape or its +/// outline. The shape from `off` above the band to `off` below it, and on to the nearest anchors +/// past those heights, is cut into [`trapezoids`]; each +/// grown by `off` is a convex polygon, and the line at an x lies in their union when the y ranges +/// they give at that x join up across the band. Those ranges change only at the polygons' corners +/// and where their outlines cross each other or the band's top or bottom, so the line is tested +/// once between each two of those x. `None` when that takes more than [`MAX_INVERT_WRAP_WORK`] +/// steps. +fn grown_band(polys: &[Vec], off: f64, top: f64, bottom: f64, (lo, hi): (f64, f64)) -> Option> { + let mut work = 0; + // The trapezoids reach on to the nearest anchor past `off` above and below the band, so that + // the shape's outline exactly `off` from the band counts. + let (y0, y1) = (top - off, bottom + off); + let ys = || polys.iter().flatten().map(|p| p.y); + let below = ys().filter(|&y| y < y0).fold(f64::NEG_INFINITY, f64::max); + let above = ys().filter(|&y| y > y1).fold(f64::INFINITY, f64::min); + let traps = trapezoids(polys, if below.is_finite() { below } else { y0 }, if above.is_finite() { above } else { y1 }, &mut work)?; + let mut grown: Vec = traps + .into_iter() + .filter(|&(_, _, l0, l1, r0, r1)| l0.min(l1) - off < hi && r0.max(r1) + off > lo) + .map(|(y0, y1, l0, l1, r0, r1)| { + let corners = [(l0, y0), (r0, y0), (l1, y1), (r1, y1)]; + let pts = corners + .into_iter() + .flat_map(|(x, y)| [(-off, -off), (off, -off), (-off, off), (off, off)].map(|(dx, dy)| Point::new(x + dx, y + dy))); + Convex::hull(pts.collect()) + }) + .collect(); + grown.sort_by(|p, q| p.xs.0.total_cmp(&q.xs.0)); + // The x at which the line's place among the polygons can change. + let mut xs = vec![lo, hi]; + for (j, p) in grown.iter().enumerate() { + xs.extend(p.lower.iter().chain(&p.upper).map(|v| v.x)); + for chain in [&p.lower, &p.upper] { + for s in chain.windows(2) { + for y in [top, bottom] { + let (d0, d1) = (s[0].y - y, s[1].y - y); + if d0 * d1 < 0.0 { + xs.push(s[0].x + (s[1].x - s[0].x) * (d0 / (d0 - d1))); + } + } + } + } + let ((_, x1), (y0, y1)) = (p.xs, p.ys); + for q in grown[j + 1..].iter().take_while(|q| q.xs.0 < x1) { + if !spend(&mut work, 1) { + return None; + } + let (v0, v1) = q.ys; + if v0 <= y1 + && y0 <= v1 + && !(chain_crossings(&p.upper, &q.lower, &mut xs, &mut work) && chain_crossings(&q.upper, &p.lower, &mut xs, &mut work)) + { + return None; + } + } + } + xs.retain(|&x| x >= lo && x <= hi); + xs.sort_by(f64::total_cmp); + xs.dedup(); + // Test the line between each two of those x, walking left to right with the polygons whose x + // range holds it. + let mut out: Vec<(f64, f64)> = Vec::new(); + let (mut next, mut active, mut ranges): (usize, Vec<&Convex>, Vec<(f64, f64)>) = (0, Vec::new(), Vec::new()); + for w in xs.windows(2) { + let x = (w[0] + w[1]) * 0.5; + while let Some(p) = grown.get(next).filter(|p| p.xs.0 <= x) { + active.push(p); + next += 1; + } + active.retain(|p| p.xs.1 >= x); + if !spend(&mut work, active.len()) { + return None; + } + ranges.clear(); + ranges.extend(active.iter().map(|p| p.at(x))); + ranges.sort_by(|u, v| u.0.total_cmp(&v.0)); + // The line is held from the band's top to `reach`, up to the first range that starts past + // it; a band of no height is held when a range reaches it. + let (mut reach, mut met) = (top, false); + for &(a, b) in &ranges { + if a > reach { + break; + } + reach = reach.max(b); + met |= b >= top; + } + if met && reach >= bottom { + match out.last_mut() { + Some(l) if l.1 >= w[0] => l.1 = w[1], + _ => out.push((w[0], w[1])), + } + } + } + Some(out) +} + 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. @@ -595,10 +967,20 @@ impl Region { } else { subtract_intervals(&iv, &pad(eroded_cover(polys, top, bottom, -off))) } + } else if let Some(held) = (*invert && *off > 0.0) + .then(|| iv.first().zip(iv.last()).and_then(|(f, l)| grown_band(polys, *off, top, bottom, (f.0 - inset, l.1 + inset)))) + .flatten() + { + // The x at which the shape grown by the offset holds the whole band. + intersect_intervals(&iv, &shrink(held)) } else if *invert { - // 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 + // With no offset, or when measuring the grown shape exactly takes more than + // [`MAX_INVERT_WRAP_WORK`] steps, the band is cut into pieces, which can leave a line + // shorter than the grown shape allows, never longer. + // + // 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 @@ -1004,6 +1386,29 @@ fn shared_slanted_edge_still_joins_near_canvas_limit() { assert_spans(&cells[0].spans(top, bottom), &[(-100.0 + 3.0 * bottom / 7.0, 100.0 + 3.0 * top / 7.0)]); } +/// A slanted edge and a vertical edge of two contours less than one unit in the last place apart +/// near the edge of the canvas, whose crossings of the band's middle round to the same x, are not +/// one edge: the line stops at the gap, drawn either way around. +#[cfg(test)] +#[test] +fn contours_whose_crossings_round_together_stay_apart() { + let x = 3_999_000.0; + let u = 2f64.powi(-31); + assert_eq!((x + u).to_bits(), x.to_bits() + 1); + let left: &[(f64, f64)] = &[(x - 100.0, 0.0), (x, 0.0), (x + u, 10.0), (x - 100.0, 10.0)]; + let right: &[(f64, f64)] = &[(x + u, 0.0), (x + 100.0, 0.0), (x + 100.0, 10.0), (x + u, 10.0)]; + let mirror = |c: &[(f64, f64)]| -> Vec<(f64, f64)> { c.iter().map(|&(px, py)| (px, 10.0 - py)).collect() }; + let (left_m, right_m) = (mirror(left), mirror(right)); + for frame in [closed(&[left, right]), closed(&[&right_m, &left_m])] { + let cells = Region::cells(&frame, &LayoutOptions::default(), &[]); + for (top, bottom) in [(8.0, 9.0), (1.0, 2.0)] { + let spans = cells[0].spans(top, bottom); + assert_eq!(spans.len(), 2, "{top}..{bottom}: {spans:?}"); + assert_spans(&spans, &[(x - 100.0, x + u), (x + u, x + 100.0)]); + } + } +} + /// Area type in two slanted contours four units in the last place apart near the edge of the canvas /// sets no line across the gap between them. #[cfg(test)] @@ -1090,6 +1495,36 @@ fn inset_keeps_text_clear_of_a_hole_s_sloped_edges() { assert_spans(&spans[0], &[(5.0, 36.0 - clear), (64.0 + clear, 95.0)]); } +/// The inset is not kept beside an edge two contours share, vertical, horizontal or slanted with an +/// extra anchor on one side, and is still kept beside the part of an edge only one contour covers. +#[cfg(test)] +#[test] +fn inset_is_not_kept_beside_an_edge_two_contours_share() { + let opts = LayoutOptions { inset: 5.0, ..LayoutOptions::default() }; + 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)]]); + assert_spans(&cell_spans(&side, &opts, &[], 40.0, 44.0)[0], &[(5.0, 95.0)]); + 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)]]); + assert_spans(&cell_spans(&seam, &opts, &[], 46.0, 54.0)[0], &[(5.0, 95.0)]); + 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)]]); + assert_spans(&cell_spans(&slanted, &opts, &[], 40.0, 44.0)[0], &[(5.0, 95.0)]); + // The lower contour covers only the left half of the upper one's bottom edge: the right half + // and the corner where they meet still keep the inset. + 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)]]); + assert_spans(&cell_spans(&step, &opts, &[], 46.0, 48.0)[0], &[(5.0, 50.0 - 21f64.sqrt())]); +} + +/// A negative wrap offset does not shrink a wrap object beside an edge two of its contours share, +/// with or without Invert Wrap. +#[cfg(test)] +#[test] +fn negative_wrap_offset_does_not_shrink_beside_an_edge_two_contours_share() { + let left: &[(f64, f64)] = &[(40.0, 40.0), (50.0, 40.0), (50.0, 60.0), (40.0, 60.0)]; + let right: &[(f64, f64)] = &[(50.0, 40.0), (60.0, 40.0), (60.0, 60.0), (50.0, 60.0)]; + assert_spans(&wrap_spans(&[left, right], -5.0, false, 44.0, 50.0), &[(0.0, 45.0), (55.0, 100.0)]); + assert_spans(&wrap_spans(&[left, right], -5.0, true, 46.0, 54.0), &[(45.0, 55.0)]); +} + /// In a frame of columns, the inset is kept once from a column's inner edge and once from the /// frame's sloped edge. #[cfg(test)] @@ -1166,8 +1601,8 @@ fn intersecting_intervals_looks_at_each_interval_once() { } /// A line in area type with an Invert Wrap comb of 500 teeth and an offset keeps a span inside -/// each tooth, left to right, through every piece of its band, and intersecting the spans with each -/// piece looks at each span once. +/// each tooth, left to right, and measuring the grown comb takes a few dozen steps for each tooth, +/// not one for each pair of teeth. #[cfg(test)] #[test] fn a_line_inside_an_invert_wrap_comb_keeps_a_span_in_each_tooth() { @@ -1179,11 +1614,92 @@ fn a_line_inside_an_invert_wrap_comb_keeps_a_span_in_each_tooth() { let wrap = vectorcraft_doc::WrapShape { path, wrap: vectorcraft_doc::TextWrap { offset: 0.25, invert: true } }; let cells = Region::cells(&frame, &LayoutOptions::default(), &[wrap]); INTERSECT_PAIRS.set(0); + GROWN_BAND_WORK.set(0); let got = cells[0].spans(40.0, 60.0); let want: Vec<(f64, f64)> = (0..500).map(|k| f64::from(k) * 2.0).map(|x| ((x - 0.25).max(0.0), x + 1.25)).collect(); assert_spans(&got, &want); - // At most 64 pieces, each looking at no more than the spans so far and the tooth spans. - assert!(INTERSECT_PAIRS.get() <= 64 * (500 + 500), "{} pairs", INTERSECT_PAIRS.get()); + // The line's one span is intersected once with the 500 spans the grown comb holds. + assert!(INTERSECT_PAIRS.get() <= 1 + 500, "{} pairs", INTERSECT_PAIRS.get()); + assert!(GROWN_BAND_WORK.get() <= 40 * 500, "{} steps", GROWN_BAND_WORK.get()); +} + +/// The spans of a 120 pt wide, 100 pt tall frame over the band `top..bottom` with one Invert Wrap +/// object through `contour` and `offset`. +#[cfg(test)] +fn invert_wrap_spans(contour: &[(f64, f64)], offset: f64, top: f64, bottom: f64) -> Vec<(f64, f64)> { + let frame = Rect::new(0.0, 0.0, 120.0, 100.0).to_path(0.1); + let path = PathData::from_bezpath(&closed(&[contour])); + let wrap = vectorcraft_doc::WrapShape { path, wrap: vectorcraft_doc::TextWrap { offset, invert: true } }; + Region::cells(&frame, &LayoutOptions::default(), &[wrap])[0].spans(top, bottom) +} + +/// The 100 pt square whose right edge steps in to x = 80 from `y0` to `y1`, with 79 more anchors +/// along its left edge, which leave its shape as it is. +#[cfg(test)] +fn notched_square(y0: f64, y1: f64) -> Vec<(f64, f64)> { + let mut contour = vec![(0.0, 0.0), (100.0, 0.0), (100.0, y0), (80.0, y0), (80.0, y1), (100.0, y1), (100.0, 100.0), (0.0, 100.0)]; + contour.extend((1..80).rev().map(|i| (0.0, 1.25 * f64::from(i)))); + contour +} + +/// With Invert Wrap and an offset, a line beside a notch the offset fills reaches as far as the +/// grown shape does at every height of its band, however tall the band and however many anchors +/// the shape has: a notch 0.5625 pt tall with an offset of 1, and one 0.4 pt tall with an offset +/// of 0.25 over a band of 100 pt. +#[cfg(test)] +#[test] +fn invert_wrap_with_an_offset_lets_a_line_beside_a_notch_reach_the_grown_shape() { + assert_spans(&invert_wrap_spans(¬ched_square(50.5, 51.0625), 1.0, 0.0, 100.0), &[(0.0, 101.0)]); + assert_spans(&invert_wrap_spans(¬ched_square(50.6, 51.0), 0.25, 0.0, 100.0), &[(0.0, 100.25)]); + // A band of no height in the notch, and one in a notch the offset does not fill. + assert_spans(&invert_wrap_spans(¬ched_square(50.5, 51.0625), 1.0, 50.7, 50.7), &[(0.0, 101.0)]); + assert_spans(&invert_wrap_spans(¬ched_square(50.0, 53.0), 1.0, 0.0, 100.0), &[(0.0, 81.0)]); + assert_spans(&invert_wrap_spans(¬ched_square(50.0, 53.0), 1.0, 51.5, 51.5), &[(0.0, 81.0)]); +} + +/// With Invert Wrap and an offset, a line beside a notch with sloped sides reaches as far as the +/// grown shape does at the notch's tip: 1 pt above and below the tip, each side is 8 pt from it. +#[cfg(test)] +#[test] +fn invert_wrap_with_an_offset_lets_a_line_beside_a_sloped_notch_reach_the_grown_shape() { + let notch = [(0.0, 0.0), (100.0, 0.0), (100.0, 45.15), (60.0, 50.15), (100.0, 55.15), (100.0, 100.0), (0.0, 100.0)]; + assert_spans(&invert_wrap_spans(¬ch, 1.0, 40.0, 60.0), &[(0.0, 69.0)]); + assert_spans(&invert_wrap_spans(¬ch, 5.0, 40.0, 60.0), &[(0.0, 105.0)]); +} + +/// With Invert Wrap and an offset, a band of no height exactly the offset past a wrap shape's +/// bottom edge or its tip still holds a line as wide as the grown edge or tip. +#[cfg(test)] +#[test] +fn invert_wrap_with_an_offset_holds_a_band_exactly_the_offset_past_the_shape() { + let bar = [(20.0, 0.0), (60.0, 0.0), (60.0, 10.0), (20.0, 10.0)]; + assert_spans(&invert_wrap_spans(&bar, 1.0, 11.0, 11.0), &[(19.0, 61.0)]); + assert!(invert_wrap_spans(&bar, 1.0, 11.5, 11.5).is_empty()); + let tip = [(20.0, 0.0), (80.0, 0.0), (50.0, 10.0)]; + assert_spans(&invert_wrap_spans(&tip, 1.0, 11.0, 11.0), &[(49.0, 51.0)]); + let tip = [(20.0, 20.0), (50.0, 10.0), (80.0, 20.0)]; + assert_spans(&invert_wrap_spans(&tip, 1.0, 9.0, 9.0), &[(49.0, 51.0)]); +} + +/// A wrap shape whose edges cross one another tens of thousands of times takes no more than +/// [`MAX_INVERT_WRAP_WORK`] steps to measure exactly; it is then cut into pieces, and the line +/// still stays inside the shape grown by the offset. An offset that is not a number is 0. +#[cfg(test)] +#[test] +fn invert_wrap_with_an_offset_bounds_its_work_on_a_tangled_shape() { + let star: Vec = (0..301) + .map(|k| f64::from(k * 150) * std::f64::consts::TAU / 301.0) + .map(|a| Point::new(50.0 + 45.0 * a.cos(), 50.0 + 45.0 * a.sin())) + .collect(); + GROWN_BAND_WORK.set(0); + assert!(grown_band(std::slice::from_ref(&star), 1.0, 10.0, 90.0, (0.0, 120.0)).is_none()); + assert!(GROWN_BAND_WORK.get() <= 2 * MAX_INVERT_WRAP_WORK, "{} steps", GROWN_BAND_WORK.get()); + let contour: Vec<(f64, f64)> = star.iter().map(|p| (p.x, p.y)).collect(); + let spans = invert_wrap_spans(&contour, 1.0, 10.0, 90.0); + assert!(spans.iter().all(|&(a, b)| a >= 4.0 && b <= 96.0), "{spans:?}"); + let square = [(40.0, 40.0), (60.0, 40.0), (60.0, 60.0), (40.0, 60.0)]; + assert_spans(&invert_wrap_spans(&square, f64::NAN, 45.0, 55.0), &invert_wrap_spans(&square, 0.0, 45.0, 55.0)); + assert_spans(&invert_wrap_spans(&square, 0.0, 45.0, 55.0), &[(40.0, 60.0)]); } /// Along the line, text keeps the inset beside a wrap object, around it and, with Invert Wrap, diff --git a/crates/text/src/layout/shaped.rs b/crates/text/src/layout/shaped.rs index 63005364fb..61c28b1465 100644 --- a/crates/text/src/layout/shaped.rs +++ b/crates/text/src/layout/shaped.rs @@ -91,8 +91,9 @@ struct Placed<'r> { /// What a line's placement depends on: its first glyph, whether it is the paragraph's first line, /// the pen's cell, baselines, pending space, narrowest word without room and further spans, the -/// span of the line above and whether the line is past the frame's end. -type Key = (usize, bool, usize, Option, Option, u64, u64, Vec<[u64; 3]>, Option, bool); +/// span of the line above, whether the line is past the frame's end, and what the further spans' +/// band was placed below. +type Key = (usize, bool, usize, Option, Option, u64, u64, Vec<[u64; 3]>, Option, bool, (Option, Option, u64)); fn key(pos: usize, first: bool, pen: &Pen<'_>, span: Option, past: bool) -> Key { ( @@ -106,6 +107,7 @@ fn key(pos: usize, first: bool, pen: &Pen<'_>, span: Option, past: bool) -> pen.queued.iter().map(|&(b, x0, x1)| [b.to_bits(), x0.to_bits(), x1.to_bits()]).collect(), span.map(f64::to_bits), past, + (pen.above.prev.map(f64::to_bits), pen.above.next_top.map(f64::to_bits), pen.above.pending.to_bits()), ) } diff --git a/crates/text/src/layout/warichu.rs b/crates/text/src/layout/warichu.rs index dd816599c6..b68b69efd9 100644 --- a/crates/text/src/layout/warichu.rs +++ b/crates/text/src/layout/warichu.rs @@ -287,6 +287,10 @@ fn place_block(g: &mut [SGlyph], s: &WariStyle, (vertical, whole): (bool, bool)) let rtl = !vertical && g.first().is_some_and(|gl| gl.level.is_rtl()); let (inset, outset) = if rtl { (after, before) } else { (before, after) }; let length = inset + block + outset; + // How far the glyphs reach above and below the line's baseline, each from its block line's + // baseline. + let above = g.iter().zip(&places).map(|(gl, p)| gl.ascent - p.1).fold(0.0, f64::max); + let below = g.iter().zip(&places).map(|(gl, p)| gl.descent + p.1).fold(0.0, f64::max); let glyphs = g.len(); for (i, (gl, (along, across, advance))) in g.iter_mut().zip(places).enumerate() { let em = gl.face.units_per_em() * gl.sy / r; @@ -300,9 +304,10 @@ fn place_block(g: &mut [SGlyph], s: &WariStyle, (vertical, whole): (bool, bool)) if i + 1 < glyphs { gl.keeps_next = true; } - // The line keeps the height of the block's own size, and holds the whole stack. - gl.ascent = (ascent / r).max(-top); - gl.descent = (descent / r).max(bottom); + // The line keeps the height of the block's own size, and holds the whole stack with each + // block line's glyphs. + gl.ascent = (ascent / r).max(-top).max(above); + gl.descent = (descent / r).max(bottom).max(below); if s.auto_leading { gl.leading /= r; } diff --git a/crates/text/src/layout/wrapping_tests.rs b/crates/text/src/layout/wrapping_tests.rs index eae22bab8a..a0a09956bc 100644 --- a/crates/text/src/layout/wrapping_tests.rs +++ b/crates/text/src/layout/wrapping_tests.rs @@ -22,6 +22,8 @@ fn synthetic_glyphs(specs: &[(usize, usize, f64, char)]) -> Vec { kern_shift: 0.0, aki_shift: 0.0, aki: 0.0, + tsume_shift: 0.0, + tsume: 0.0, sx: 1.0, sy: 1.0, bshift: 0.0, @@ -646,6 +648,198 @@ fn a_negative_advance_after_a_tab_keeps_a_fitting_line_whole() { assert_eq!(ended, (5, false)); } +/// A tabbed line of glyphs with negative advances, past the frame in the order of its text: `a`, +/// a tab to the default stop at 36 pt, `y` stepping back 1 pt, then `n` times `b` (1 pt), `z` +/// (−1 pt) and a space, so its glyphs other than the tab never fill the frame. Its breaks end the +/// line before glyph 2 and before 6 + 3u for each u. +fn stepping_back_tabbed_line(n: usize) -> (String, Vec) { + let text = format!("a\ty{}", "bz ".repeat(n)); + let specs: Vec<_> = text + .char_indices() + .map(|(byte, ch)| { + let adv = match ch { + 'y' | 'z' => -1.0, + ' ' => 0.0, + _ => 1.0, + }; + (byte, ch.len_utf8(), adv, ch) + }) + .collect(); + let glyphs = synthetic_glyphs(&specs); + (text, glyphs) +} + +/// A tabbed line with glyphs stepping back stops reading a bounded number of breaks past where it +/// overflows in the order of its text: a long paragraph is not read to its end to set one line. +#[test] +fn a_tabbed_line_stepping_back_stops_reading_past_its_overflow() { + let (text, glyphs) = stepping_back_tabbed_line(2000); + // The latest break the line reads is the first it measures as drawn. + let furthest = std::cell::Cell::new(0); + let measured = std::cell::Cell::new(0usize); + let drawn_fits = |end: usize, _hyphenated: bool| { + furthest.set(furthest.get().max(end)); + measured.set(measured.get() + 1); + end <= 10 + }; + let fits: Option<&dyn Fn(usize, bool) -> bool> = Some(&drawn_fits); + let ended = + break_line(&text, &glyphs, 0, 30.0, &[], 0.0, None, Burasagari::None, Kinsoku::None, KinsokuShoriType::PushOutOnly, false, false, &[], fits); + assert_eq!(ended, (9, false)); + // 1,024 breaks past the overflow at `y`: the break before glyph 6 + 3 × 1,023. + assert_eq!(furthest.get(), 3075, "read up to glyph {} of {}", furthest.get(), glyphs.len()); + assert!(measured.get() <= 1100, "measured {} breaks as drawn", measured.get()); +} + +/// Where a tabbed line with glyphs stepping back stops reading, it ends at the latest break read +/// that fits as drawn, even when a break past those fits too. +#[test] +fn a_tabbed_line_stepping_back_ends_at_the_latest_break_read_that_fits() { + let (text, glyphs) = stepping_back_tabbed_line(1500); + let end = |drawn_fits: &dyn Fn(usize, bool) -> bool| { + break_line( + &text, + &glyphs, + 0, + 30.0, + &[], + 0.0, + None, + Burasagari::None, + Kinsoku::None, + KinsokuShoriType::PushOutOnly, + false, + false, + &[], + Some(drawn_fits), + ) + }; + // The break before glyph 4002 is past the 1,024 breaks read after the overflow (up to 3075). + assert_eq!(end(&|end: usize, _: bool| end <= 10 || end == 4002), (9, false)); + // A break among those read keeps its place. + assert_eq!(end(&|end: usize, _: bool| end <= 10 || end == 600), (600, false)); + assert_eq!(end(&|end: usize, _: bool| end <= 10 || end == 3075), (3075, false)); +} + +/// A tabbed line with glyphs stepping back that stops reading at a soft hyphen ending the text ends +/// there without a hyphen, as a line that reads to the end of the text does. +#[test] +fn a_tabbed_line_stepping_back_ends_at_a_final_soft_hyphen_without_a_hyphen() { + // The 1,023 spaces and the soft hyphen are the 1,024 breaks the line reads past its overflow. + let text = format!("a\ty{}b\u{00AD}", "bz ".repeat(1023)); + let specs: Vec<_> = text + .char_indices() + .map(|(byte, ch)| { + let adv = match ch { + 'y' | 'z' => -1.0, + ' ' | '\u{00AD}' => 0.0, + _ => 1.0, + }; + (byte, ch.len_utf8(), adv, ch) + }) + .collect(); + let glyphs = synthetic_glyphs(&specs); + let len = glyphs.len(); + let drawn_fits = |end: usize, _hyphenated: bool| end <= 10 || end == len; + let fits: Option<&dyn Fn(usize, bool) -> bool> = Some(&drawn_fits); + let ended = + break_line(&text, &glyphs, 0, 30.0, &[], 0.0, None, Burasagari::None, Kinsoku::None, KinsokuShoriType::PushOutOnly, false, false, &[], fits); + assert_eq!(ended, (len, false)); +} + +/// A tabbed line with glyphs stepping back whose last break read comes right before a forced line +/// break ends after the forced break, so the next line does not start with it and draw empty. +#[test] +fn a_tabbed_line_stepping_back_keeps_a_forced_break_after_its_last_break_read() { + // The 1,024th space is the 1,024th break past the overflow, and glyph 3075 after it is U+2028. + let text = format!("a\ty{}\u{2028}bbb", "bz ".repeat(1024)); + let specs: Vec<_> = text + .char_indices() + .map(|(byte, ch)| { + let adv = match ch { + 'y' | 'z' => -1.0, + ' ' | '\u{2028}' => 0.0, + _ => 1.0, + }; + (byte, ch.len_utf8(), adv, ch) + }) + .collect(); + let glyphs = synthetic_glyphs(&specs); + assert_eq!(glyphs[3075].ch, '\u{2028}'); + let drawn_fits = |end: usize, _hyphenated: bool| end <= 10 || end >= 3075; + let fits: Option<&dyn Fn(usize, bool) -> bool> = Some(&drawn_fits); + let ended = + break_line(&text, &glyphs, 0, 30.0, &[], 0.0, None, Burasagari::None, Kinsoku::None, KinsokuShoriType::PushOutOnly, false, false, &[], fits); + assert_eq!(ended, (3076, false)); +} + +/// A tab to a default or left stop does not read the text after it, which only right, center and +/// decimal stops align: the first tab of a long paragraph does not read the paragraph to its end. +#[test] +fn a_tab_to_a_default_or_left_stop_reads_no_text_after_it() { + use vectorcraft_doc::{TabAlign, TabStop}; + let (_, glyphs) = stepping_back_tabbed_line(2000); + let read = std::cell::Cell::new(0usize); + let rest = || glyphs[2..].iter().inspect(|_| read.set(read.get() + 1)); + let left = [TabStop { position: 100.0, align: TabAlign::Left, leader: String::new(), align_on: '.' }]; + assert_eq!(tab_advance(&[], 0.0, 1.0, rest()).0, 35.0); + assert_eq!(tab_advance(&left, 0.0, 1.0, rest()).0, 99.0); + assert_eq!(read.get(), 0, "read {} glyphs after the tab", read.get()); + // A right stop reads up to the next tab and aligns that text on the stop. + let right = [TabStop { position: 100.0, align: TabAlign::Right, leader: String::new(), align_on: '.' }]; + let short = synthetic_glyphs(&[(0, 1, 2.0, 'b'), (1, 1, 3.0, 'b'), (2, 1, 0.0, '\t'), (3, 1, 7.0, 'b')]); + assert_eq!(tab_advance(&right, 0.0, 1.0, short.iter()).0, 94.0); +} + +/// A long tabbed line with a glyph that steps back ends at the latest break that fits as drawn, even +/// where a later break than one that does not fit fits again. +#[test] +fn a_long_tabbed_line_that_steps_back_ends_at_the_latest_break_that_fits_as_drawn() { + // a (0), tab (1), then b and a space for each u: breaks before 4 + 2u. + let text = format!("a\t{}", "b ".repeat(400)); + let specs: Vec<_> = text.char_indices().map(|(byte, ch)| (byte, ch.len_utf8(), if byte == 2 { -0.5 } else { 1.0 }, ch)).collect(); + let glyphs = synthetic_glyphs(&specs); + let drawn_fits = |end: usize, _hyphenated: bool| end <= 10 || end == 200; + let fits: Option<&dyn Fn(usize, bool) -> bool> = Some(&drawn_fits); + let ended = + break_line(&text, &glyphs, 0, 1e6, &[], 0.0, None, Burasagari::None, Kinsoku::None, KinsokuShoriType::PushOutOnly, false, false, &[], fits); + assert_eq!(ended, (200, false)); +} + +/// A tabbed line with a glyph that steps back, ending in a word with more hyphenation points than +/// are measured one by one, ends at the latest point that fits as drawn. +#[test] +fn a_tabbed_line_that_steps_back_ends_at_the_latest_hyphenation_point_that_fits_as_drawn() { + let opts = HyphenationOptions { words_longer_than: 0, after_first: 1, before_last: 1, ..Default::default() }; + // a (0), tab (1), then a word of 400 syllables of two glyphs from glyph 2: points before 4, 6, ... + let text = format!("a\t{}", "कि".repeat(400)); + let specs: Vec<_> = text.char_indices().map(|(byte, ch)| (byte, ch.len_utf8(), if byte == 2 { -1.0 } else { 1.0 }, ch)).collect(); + let mut glyphs = synthetic_glyphs(&specs); + for glyph in &mut glyphs { + glyph.hyphen_language = crate::hyphen::Language::from_tag(Some("hi")); + glyph.sx = 0.001; + } + let drawn_fits = |end: usize, _hyphenated: bool| end <= 20 || end == 50; + let fits: Option<&dyn Fn(usize, bool) -> bool> = Some(&drawn_fits); + let ended = break_line( + &text, + &glyphs, + 0, + 600.0, + &[], + 0.0, + Some((&opts, 0.0)), + Burasagari::None, + Kinsoku::None, + KinsokuShoriType::PushOutOnly, + false, + false, + &[], + fits, + ); + assert_eq!(ended, (50, true)); +} + /// Mojikumi: the greedy breaker measures a line as it is set, with its last character narrowed /// (`line_end`): 」 set half width ends a measure of three and a half characters. Only the last /// glyph of the last cluster counts, and only where the line may end. @@ -862,7 +1056,8 @@ fn a_further_span_is_measured_across_the_height_of_its_line() { wrap: vectorcraft_doc::TextWrap { offset: 0.0, invert: false }, }; let small = breaking::Metrics { asc: 10.0, desc: 3.0, lead: 14.0, cap: 7.0, xh: 5.0, top: 10.0 }; - let tall = breaking::Metrics { asc: 30.0, desc: 9.0, lead: 42.0, cap: 21.0, xh: 15.0, top: 30.0 }; + // The tall line is set at the small line's leading, so it may share the small line's baseline. + let tall = breaking::Metrics { asc: 30.0, desc: 9.0, lead: 14.0, cap: 21.0, xh: 15.0, top: 30.0 }; // An object down the middle of the frame splits every line in two, and `above` lies right of // it over y 20 to 40. A small line after a baseline of 50 is set at 64, over y 54 to 67, clear // of `above`; a tall line in the span right of it on that baseline covers y 34 to 73. @@ -877,6 +1072,7 @@ fn a_further_span_is_measured_across_the_height_of_its_line() { fb: FirstBaseline::Ascent, fb_min: 0.0, queued: vec![], + above: Default::default(), model: LeadingModel::RomanBaseline, next_top: None, no_room_for: f64::INFINITY, @@ -897,17 +1093,72 @@ fn a_further_span_is_measured_across_the_height_of_its_line() { assert!(near(right, (64.0, 220.0, 300.0, true)), "{right:?}"); // That part is 80 wide: a tall line that starts with a wider word goes on the next baseline. let (_, right) = set(Rect::new(300.0, 20.0, 400.0, 40.0), 100.0); - assert!(near(right, (106.0, 0.0, 180.0, false)), "{right:?}"); + assert!(near(right, (78.0, 0.0, 180.0, false)), "{right:?}"); // `above` covers the whole span: the tall line goes on the next baseline, left of the object. let (left, right) = set(Rect::new(220.0, 20.0, 400.0, 40.0), 0.0); assert!(near(left, (64.0, 0.0, 180.0, false)), "{left:?}"); - assert!(near(right, (106.0, 0.0, 180.0, false)), "{right:?}"); + assert!(near(right, (78.0, 0.0, 180.0, false)), "{right:?}"); // `above` lies below the tall line: the span is as wide for it as for the small line, and it // takes the span whatever its first word, as a further span always did. let (_, right) = set(Rect::new(300.0, 300.0, 400.0, 320.0), 200.0); assert!(near(right, (64.0, 220.0, 400.0, true)), "{right:?}"); } +/// A further span goes only to a line whose own leading sets it no higher than the span's +/// baseline: a taller line leaves the span empty and goes on the next baseline, so its ascent does +/// not reach into the line above the band. In a cell's first band, a taller line leaves a span +/// whose baseline is above its own first baseline in the cell. +#[test] +fn a_further_span_is_left_to_a_line_its_leading_sets_there() { + use std::cell::Cell; + use std::rc::Rc; + let frame = Rect::new(0.0, 0.0, 400.0, 400.0).to_path(0.1); + let wraps = [vectorcraft_doc::WrapShape { + path: PathData::from_bezpath(&Rect::new(180.0, 0.0, 220.0, 400.0).to_path(0.1)), + wrap: vectorcraft_doc::TextWrap { offset: 0.0, invert: false }, + }]; + let regions = region::Region::cells(&frame, &LayoutOptions::default(), &wraps); + let small = breaking::Metrics { asc: 10.0, desc: 3.0, lead: 14.0, cap: 7.0, xh: 5.0, top: 10.0 }; + let tall = breaking::Metrics { asc: 30.0, desc: 9.0, lead: 42.0, cap: 21.0, xh: 15.0, top: 30.0 }; + let set = |prev: Option, model: LeadingModel, next: breaking::Metrics| { + let mut pen = breaking::Pen { + regions: Some(®ions), + ri: 0, + prev, + pending: 0.0, + fb: FirstBaseline::Ascent, + fb_min: 0.0, + queued: vec![], + above: Default::default(), + model, + next_top: prev.map(|b| b - small.top + small.lead), + no_room_for: f64::INFINITY, + steps_left: Rc::new(Cell::new(breaking::MAX_TOTAL_STEPS)), + search: Default::default(), + }; + let left = pen.place(small, 0.0, 0.0, 0.0); + let at = left.map_or(f64::NAN, |l| l.0); + pen.settled(at, small); + let ok = pen.clears_above(at, next); + (left, pen.place(next, 0.0, 0.0, 0.0), ok) + }; + let near = |got: Option<(f64, f64, f64, bool)>, want: (f64, f64, f64, bool)| { + got.is_some_and(|g| (g.0 - want.0).abs() < 0.01 && (g.1 - want.1).abs() < 0.01 && (g.2 - want.2).abs() < 0.01 && g.3 == want.3) + }; + // The next baseline for the tall line after the small one at 64, and after the small one at 10. + for (model, after_64, after_10) in [(LeadingModel::RomanBaseline, 106.0, 52.0), (LeadingModel::EmBoxTop, 98.0, 44.0)] { + // After a line at 50, the small line is set at 64. A small line takes the span right of the + // object on that baseline; a tall line, which its leading sets lower, goes on the next one. + let (left, right, ok) = set(Some(50.0), model, small); + assert!(near(left, (64.0, 0.0, 180.0, false)) && near(right, (64.0, 220.0, 400.0, true)) && ok, "{model:?}: {left:?} {right:?}"); + let (_, right, ok) = set(Some(50.0), model, tall); + assert!(near(right, (after_64, 0.0, 180.0, false)) && !ok, "{model:?}: {right:?}"); + // The cell's first band: the small line at 10, the tall line on the next baseline. + let (left, right, ok) = set(None, model, tall); + assert!(near(left, (10.0, 0.0, 180.0, false)) && near(right, (after_10, 0.0, 180.0, false)) && !ok, "{model:?}: {left:?} {right:?}"); + } +} + /// The every-line composer's searches for the paragraphs of one frame share one budget: each takes /// the lines it tried and the baseline steps it spent from it, the layout's own steps stay as they /// were, and once the budget runs out the next paragraph's search stops (it is broken line by line). @@ -941,6 +1192,7 @@ fn shaped_composition_searches_share_the_frame_budget() { fb: FirstBaseline::Ascent, fb_min: 0.0, queued: vec![], + above: Default::default(), model: LeadingModel::default(), next_top: None, no_room_for: f64::INFINITY, @@ -1173,11 +1425,14 @@ fn justification_adds_no_gap_inside_a_warichu_block_drawn_right_to_left() { let mut glyphs = synthetic_glyphs(&[(0, 2, 10.0, first), (2, 2, 0.0, second)]); block(&mut glyphs[0], 0, 0.0); block(&mut glyphs[1], 0, 10.0); - assert!(!flow::is_letter_gap(1, &[], &after, 0, &glyphs, false), "{first}{second}"); - assert!(!flow::is_cjk_gap(1, &[], &after, 0, &glyphs), "{first}{second}"); + // Glyph 0 is drawn after glyph 1 of its block. + let begun = [true, false]; + assert!(!flow::is_letter_gap(1, &[], (&after, &begun), 0, &glyphs, false), "{first}{second}"); + assert!(!flow::is_cjk_gap(1, &[], (&after, &begun), 0, &glyphs), "{first}{second}"); // The same two glyphs as the first glyphs of two blocks. block(&mut glyphs[1], 2, 0.0); - assert!(flow::is_letter_gap(1, &[], &after, 0, &glyphs, false), "{first}{second}"); - assert_eq!(flow::is_cjk_gap(1, &[], &after, 0, &glyphs), first == '漢', "{first}{second}"); + let begun = [false, false]; + assert!(flow::is_letter_gap(1, &[], (&after, &begun), 0, &glyphs, false), "{first}{second}"); + assert_eq!(flow::is_cjk_gap(1, &[], (&after, &begun), 0, &glyphs), first == '漢', "{first}{second}"); } } diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 6ae85931ca..362a1c2408 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -556,25 +556,32 @@ fn cluster_extent(layout: &TextLayout, glyphs: &[PositionedGlyph], i: usize) -> /// Caret for byte offset `byte`, as a (top, bottom) segment in text space. In horizontal type, a /// cluster drawn with several glyphs is measured whole ([`cluster_extent`]). Inside a ligature the -/// caret stands at its caret stops ([`PositionedGlyph::carets`]). +/// caret stands at its caret stops ([`PositionedGlyph::carets`]). Next to a character of a warichu +/// block the caret spans the band of its block line, as its highlight does. pub fn caret_position(layout: &TextLayout, byte: usize) -> (Point, Point) { let Some(line) = layout.lines.get(layout.line_of(byte)) else { return (Point::ZERO, Point::ZERO); }; let glyphs = &layout.glyphs[line.glyph_start..line.glyph_end]; - let (pos, angle) = if let Some(i) = glyphs.iter().position(|g| g.byte <= byte && g.byte + g.len > byte) { + let (pos, angle, glyph) = if let Some(i) = glyphs.iter().position(|g| g.byte <= byte && g.byte + g.len > byte) { let g = &glyphs[i]; let (origin, advance) = match cluster_extent(layout, glyphs, i) { Some((left, right)) => (Point::new(left, g.origin.y), right - left), None => (g.origin, g.advance), }; let off = g.caret_offset(byte, advance); - (origin + dir(g.angle) * if g.rtl { advance - off } else { off }, g.angle) + (origin + dir(g.angle) * if g.rtl { advance - off } else { off }, g.angle, Some(g)) } else if let Some(g) = glyphs.iter().max_by_key(|g| g.byte + g.len) { - (g.origin + dir(g.angle) * if g.rtl { 0.0 } else { g.advance }, g.angle) + (g.origin + dir(g.angle) * if g.rtl { 0.0 } else { g.advance }, g.angle, Some(g)) } else { - (layout.physical_point(Point::new(line.x0, line.baseline)), if layout.vertical { std::f64::consts::FRAC_PI_2 } else { 0.0 }) + (layout.physical_point(Point::new(line.x0, line.baseline)), if layout.vertical { std::f64::consts::FRAC_PI_2 } else { 0.0 }, None) }; + if let Some((_, top, bottom)) = + glyph.filter(|g| g.warichu.is_some() && !layout.on_path).and_then(|g| block_band(&warichu_rows(layout, line), line, g)) + { + let x = layout.logical_point(pos).x; + return (layout.physical_point(Point::new(x, top)), layout.physical_point(Point::new(x, bottom))); + } // Up vector in y-down space, rotated with the baseline. let d = dir(angle); let up = Vec2::new(d.y, -d.x); @@ -786,6 +793,20 @@ fn warichu_rows(layout: &TextLayout, l: &LineInfo) -> Vec<(usize, f64, f64)> { rows } +/// The band across line `l` (text space, from the top) of the block line that warichu glyph `g` is +/// on, with that block line's index in its block: out to halfway to the block lines next to it, +/// and to the line's top or bottom past the block's outer lines. `rows` are the line's +/// [`warichu_rows`]. None for a glyph of no block. +fn block_band(rows: &[(usize, f64, f64)], l: &LineInfo, g: &PositionedGlyph) -> Option<(usize, f64, f64)> { + let block = g.warichu?; + let lines = rows.get(rows.partition_point(|r| r.0 < block)..rows.partition_point(|r| r.0 <= block)).unwrap_or_default(); + let row = lines.partition_point(|r| r.1 < g.warichu_line - 1e-9); + let own = lines.get(row).filter(|r| (r.1 - g.warichu_line).abs() < 1e-9)?; + let top = row.checked_sub(1).and_then(|k| lines.get(k)).map_or(l.baseline - l.ascent, |above| (above.2 + own.2) * 0.5); + let bottom = lines.get(row + 1).map_or(l.baseline + l.descent, |below| (below.2 + own.2) * 0.5); + Some((row, top, bottom)) +} + /// A glyph of a warichu block line, for [`selection_quads`]: its block and block line, its extent /// along the line and its band across it (text space), and whether the selection covers it. struct BlockPiece { @@ -829,11 +850,7 @@ pub fn selection_quads(layout: &TextLayout, a: usize, b: usize) -> Vec<[Point; 4 let mut pieces: Vec = Vec::new(); for (i, g) in layout.glyphs.iter().enumerate().take(l.glyph_end).skip(l.glyph_start) { let Some(block) = g.warichu else { continue }; - let lines = rows.get(rows.partition_point(|r| r.0 < block)..rows.partition_point(|r| r.0 <= block)).unwrap_or_default(); - let row = lines.partition_point(|r| r.1 < g.warichu_line - 1e-9); - let Some(own) = lines.get(row).filter(|r| (r.1 - g.warichu_line).abs() < 1e-9) else { continue }; - let top = row.checked_sub(1).and_then(|k| lines.get(k)).map_or(l.baseline - l.ascent, |above| (above.2 + own.2) * 0.5); - let bottom = lines.get(row + 1).map_or(l.baseline + l.descent, |below| (below.2 + own.2) * 0.5); + let Some((row, top, bottom)) = block_band(&rows, l, g) else { continue }; let x = layout.logical_point(g.origin).x; let selected = selected(i, g); let (f0, f1) = if selected { covered(g) } else { (0.0, g.advance) }; diff --git a/crates/text/src/shape.rs b/crates/text/src/shape.rs index befcbed41f..9d36eed28b 100644 --- a/crates/text/src/shape.rs +++ b/crates/text/src/shape.rs @@ -49,6 +49,12 @@ pub(crate) struct SGlyph { /// The Insert Aki Left and Right `adv` holds, in points: on the last glyph of its cluster, 0 /// on the others. Justification does not stretch or narrow it. pub aki: f64, + /// The space Tsume ([`tighten`]) took before the cluster's ink, in points, on every glyph of + /// its cluster: `dx` is that much smaller. + pub tsume_shift: f64, + /// The space Tsume took out of `adv`, in points: on the last glyph of its cluster, 0 on the + /// others. + pub tsume: f64, /// Outline scale (font units -> points). pub sx: f64, pub sy: f64, @@ -232,6 +238,8 @@ pub(crate) fn hyphen_glyph(g: &SGlyph) -> SGlyph { h.kern_shift = 0.0; h.aki_shift = 0.0; h.aki = 0.0; + h.tsume_shift = 0.0; + h.tsume = 0.0; h.byte = g.byte + g.len; h.len = 0; h.ch = '-'; @@ -838,8 +846,8 @@ fn optical_pairs(db: &FontDb, text: &str, glyphs: &mut [SGlyph], runs: &[(Range< let mut cache = HashMap::new(); let mut corrections: HashMap<[u64; 15], Option> = HashMap::new(); let mut references: HashMap> = HashMap::new(); - // The Insert Aki a cluster's last glyph holds does not make a mark its base. - let shaped_advances: Vec = glyphs.iter().map(|g| g.adv - g.aki).collect(); + // The Insert Aki and Tsume a cluster's last glyph holds do not make a mark its base. + let shaped_advances: Vec = glyphs.iter().map(|g| g.adv - g.aki + g.tsume).collect(); for i in 0..glyphs.len().saturating_sub(1) { let Some((a, b)) = glyphs.get(i).zip(glyphs.get(i + 1)) else { continue }; if a.level != b.level { @@ -897,10 +905,10 @@ fn optical_pairs(db: &FontDb, text: &str, glyphs: &mut [SGlyph], runs: &[(Range< continue; } // Neither glyph is rotated, so a right-to-left manual kerning shift adds to the offset. - // Insert Aki is measured as no space: the pair is spaced as it would be without it, and - // the Aki stays on top of that. - let left_x = left.dx + left.kern_shift - left.aki_shift; - let right_x = right.dx + right.kern_shift - right.aki_shift; + // Insert Aki is measured as no space, and Tsume as taking none: the pair is spaced as it + // would be without them, and they stay on top of that. + let left_x = left.dx + left.kern_shift - left.aki_shift + left.tsume_shift; + let right_x = right.dx + right.kern_shift - right.aki_shift + right.tsume_shift; let left_y = left.dy - left.bshift; let right_y = right.dy - right.bshift; let Some(left_style) = runs.get(left.run).map(|(_, s)| *s) else { continue }; @@ -909,7 +917,7 @@ fn optical_pairs(db: &FontDb, text: &str, glyphs: &mut [SGlyph], runs: &[(Range< let tracking = left_style.tracking / 1000.0 * em * spacing_scale(left_style, false); // A manual kerning value on the left glyph is part of its advance and, right to left, of // its offset too (it spaces the left glyph from its left neighbor): it is not taken off. - let advance = glyphs[cluster_start..=cluster_end].iter().map(|g| g.adv - g.aki).sum::() - tracking; + let advance = glyphs[cluster_start..=cluster_end].iter().map(|g| g.adv - g.aki + g.tsume).sum::() - tracking; let key = [ u64::from(left.face.id()), u64::from(left.gid), @@ -1028,6 +1036,8 @@ fn drawn_alike(a: &CharStyle, b: &CharStyle, vertical: bool) -> bool { no_break, language, glyph_alternate, + // An OpenType feature over its own characters, like `features`. + glyph_form: _, } = a; // Keep PartialEq's non-reflexive behavior for ignored numeric fields, without cloning styles. let offsets = (standard_vertical_roman, tcy_up_down, tcy_left_right); @@ -1096,7 +1106,7 @@ pub(crate) fn warichu_alike(a: &CharStyle, b: &CharStyle) -> bool { /// character style's name, leading, baseline shift, rotation, Character Alignment, Character /// Direction (text is shaped apart where its bidi level changes), Kashidas, the kerning (each glyph takes its /// run's, see [`shape_segment`]), the space before a line's first character ([`space_before`]), -/// Insert Aki ([`aki`]), Tsume ([`tighten`]), the OpenType features (each run's apply to its own characters, as features +/// Insert Aki ([`aki`]), Tsume ([`tighten`]), the OpenType features and the East Asian glyph form (each run's apply to its own characters, as features /// over a range of the one buffer) and the tracking, as long as the tracking keeps or drops /// standard ligatures alike ([`crate::features::ligatures_suppressed_by`]). fn shapes_alike(a: &CharStyle, b: &CharStyle) -> bool { @@ -1159,6 +1169,8 @@ fn shapes_alike(a: &CharStyle, b: &CharStyle) -> bool { no_break, language, glyph_alternate, + // Applied as a feature over its run's own characters, with `features`. + glyph_form: _, } = a; *font_family == b.font_family && warichu_alike(a, b) @@ -1276,6 +1288,8 @@ fn inline_glyph( kern_shift: if level.is_rtl() && !vertical { manual_kern } else { before } + aki_shift, aki_shift, aki: if adv.is_finite() { aki_left + aki_right } else { 0.0 }, + tsume_shift: 0.0, + tsume: 0.0, // Not used to draw (the art has its own transform), but they make the glyph's em box // its run's em: Character Alignment and Top-to-Top leading treat an inline graphic as a // character of its run's size, whatever its scale (see `layout::glyph_em`). @@ -1442,8 +1456,8 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe let mut ranged = Vec::new(); for (r, run_style) in runs.get(source_runs.clone()).unwrap_or_default() { let (a, b) = (r.start.max(range.start), r.end.min(range.end)); - if run_style.features != base_style.features && a < b { - let own = variant(&CharStyle { features: run_style.features.clone(), ..base_style.clone() }); + if (run_style.features != base_style.features || run_style.glyph_form != base_style.glyph_form) && a < b { + let own = variant(&CharStyle { features: run_style.features.clone(), glyph_form: run_style.glyph_form, ..base_style.clone() }); ranged_features(base, &own, a..b, &mut ranged); } } @@ -1784,6 +1798,8 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe kern_shift, aki_shift, aki: aki_in_adv, + tsume_shift: 0.0, + tsume: 0.0, sx: k * hs, sy: k * vs, bshift: gst.baseline_shift + pos_shift, @@ -1822,8 +1838,9 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe /// drawn along the line, the last one with `own` as its width before the tracking, kerning and /// Insert Aki its advance holds. `tsume` percent of the blank space between the cluster's own width /// and its ink, on each side, comes out of the cluster's advance, and its glyphs are drawn the -/// left side's share earlier. A cluster without ink, such as a space, or with a width that is not -/// positive, keeps its place and width. +/// left side's share earlier ([`SGlyph::tsume`] and [`SGlyph::tsume_shift`] hold both, for Optical +/// kerning to measure the pair without them). A cluster without ink, such as a space, or with a +/// width that is not positive, keeps its place and width. fn tighten(glyphs: &mut [SGlyph], own: f64, tsume: f64) { let Some(last) = glyphs.len().checked_sub(1) else { return }; let share = if tsume.is_nan() { 0.0 } else { tsume.clamp(0.0, MAX_TSUME) / 100.0 }; @@ -1844,9 +1861,11 @@ fn tighten(glyphs: &mut [SGlyph], own: f64, tsume: f64) { let right = (pen - hi).clamp(0.0, pen) * share; for g in glyphs.iter_mut() { g.dx -= left; + g.tsume_shift = left; } if let Some(g) = glyphs.get_mut(last) { g.adv -= left + right; + g.tsume = left + right; } } diff --git a/crates/text/src/test_fonts.rs b/crates/text/src/test_fonts.rs index bdb818d3f3..7abae3f0eb 100644 --- a/crates/text/src/test_fonts.rs +++ b/crates/text/src/test_fonts.rs @@ -1939,6 +1939,12 @@ pub fn colr_variable_font() -> Option> { with_colr(&variable_font()?, family_names(COLR_VARIABLE_FAMILY, &axis_names)?, &colr) } +/// [`variable_font`] (one weight axis, 400 to 700) as `family` with `colr` and [`colr_font`]'s +/// palette. `None` when it can't be built. +pub fn colr_variable_font_with(family: &str, colr: &write_fonts::tables::colr::Colr) -> Option> { + with_colr(&variable_font()?, family_names(family, &[])?, colr) +} + /// A `name` table for Regular of `family`, with `more` records. fn family_names(family: &str, more: &[(u16, &str)]) -> Option> { let ps = family.replace(' ', ""); diff --git a/crates/text/src/tests/colr.rs b/crates/text/src/tests/colr.rs index c3a0499af6..e59fb390c9 100644 --- a/crates/text/src/tests/colr.rs +++ b/crates/text/src/tests/colr.rs @@ -25,7 +25,7 @@ use vectorcraft_doc::color::{BlendMode, Color, GradientKind, Paint}; use vectorcraft_doc::{Node, NodeKind}; use crate::colr::{ColourContent, colour_glyph}; -use crate::test_fonts::{COLR_GREEN, COLR_RED}; +use crate::test_fonts::{COLR_BLUE, COLR_GREEN, COLR_RED}; const FOREGROUND: Color = Color::Rgb { r: 0.25, g: 0.5, b: 0.75 }; @@ -288,6 +288,49 @@ fn a_glyph_filled_with_one_colour_is_one_path() { assert_eq!(fill(only), Paint::solid(rgb(COLR_RED))); } +/// A fill that paints nothing (a palette index past the palette) followed by another glyph +/// inside the same glyph's clip keeps the clip: the second glyph is drawn clipped to the first, +/// not on its own. +#[test] +fn a_fill_that_paints_nothing_keeps_the_clip_around_the_glyph_after_it() { + use write_fonts::tables::colr::{BaseGlyphList, BaseGlyphPaint, Colr, LayerList}; + use write_fonts::types::GlyphId16; + let bytes = colr_font(false).unwrap(); + let read = skrifa::FontRef::new(&bytes).unwrap(); + let gid = |ch| GlyphId16::new(u16::try_from(read.charmap().map(ch).unwrap().to_u32()).unwrap()); + let mut colr = Colr::new(0, None, None, 0); + let paint = ColrPaint::glyph(ColrPaint::colr_layers(2, 0), gid('O')); + colr.base_glyph_list = Some(BaseGlyphList::new(1, vec![BaseGlyphPaint::new(gid(COLOUR_CHAR), paint)])).into(); + colr.layer_list = Some(LayerList::new(2, vec![solid(99), ColrPaint::glyph(solid(0), gid('I'))])).into(); + let font = crate::test_fonts::colr_font_with("Colrtest Empty Fill", &colr).unwrap(); + let root = art(&font, COLOUR_CHAR); + let [clipped] = children(&root) else { panic!("{:?}", children(&root).iter().map(|c| c.kind_label()).collect::>()) }; + assert!(matches!(clipped.kind, NodeKind::Group { clip: true, .. }), "the `O` still clips: {}", clipped.kind_label()); + let [clip, inner] = children(clipped) else { panic!("{:?}", children(clipped).iter().map(|c| c.kind_label()).collect::>()) }; + assert!(matches!(clip.kind, NodeKind::Path { clipping: true, .. }), "{}", clip.kind_label()); + assert_eq!(fill(inner), Paint::solid(rgb(COLR_RED))); +} + +/// A fill that paints nothing after a colour flooding the glyph leaves it that glyph filled: +/// one path, as without the empty fill. +#[test] +fn a_fill_that_paints_nothing_after_a_flood_keeps_one_path() { + use write_fonts::tables::colr::{BaseGlyphList, BaseGlyphPaint, Colr, LayerList}; + use write_fonts::types::GlyphId16; + let bytes = colr_font(false).unwrap(); + let read = skrifa::FontRef::new(&bytes).unwrap(); + let gid = |ch| GlyphId16::new(u16::try_from(read.charmap().map(ch).unwrap().to_u32()).unwrap()); + let mut colr = Colr::new(0, None, None, 0); + let paint = ColrPaint::glyph(ColrPaint::colr_layers(2, 0), gid('O')); + colr.base_glyph_list = Some(BaseGlyphList::new(1, vec![BaseGlyphPaint::new(gid(COLOUR_CHAR), paint)])).into(); + colr.layer_list = Some(LayerList::new(2, vec![solid(0), solid(99)])).into(); + let font = crate::test_fonts::colr_font_with("Colrtest Flood Then Empty", &colr).unwrap(); + let root = art(&font, COLOUR_CHAR); + let [only] = children(&root) else { panic!("{:?}", children(&root).iter().map(|c| c.kind_label()).collect::>()) }; + assert!(matches!(only.kind, NodeKind::Path { .. }), "{}", only.kind_label()); + assert_eq!(fill(only), Paint::solid(rgb(COLR_RED))); +} + /// A sweep glyph in a font without clip boxes, its base glyph without an outline (the space's, /// as COLRv1 fonts make them): its image is as large as what it paints. #[test] @@ -358,6 +401,147 @@ fn a_radial_gradient_from_a_circle_around_its_centre_is_vector_art() { assert_eq!(offsets, [0.25, 1.0], "the stops start a quarter of the way out"); } +/// A padded radial gradient whose color line starts before 0 starts at the circle of radius 0: +/// circles of a negative radius are not drawn, so the stops before that circle become one stop +/// there with the color between them +/// (https://learn.microsoft.com/en-us/typography/opentype/spec/colr, Radial gradients). With its +/// centers apart, the gradient is focused on the tip of its cone; with its centers together, it +/// is centered there with no stop below 0. +#[test] +fn a_radial_gradient_with_a_stop_before_0_starts_at_its_circle_of_radius_0() { + use vectorcraft_doc::color::{Gradient, GradientStop}; + use write_fonts::tables::colr::{ColorLine, ColorStop, Extend}; + use write_fonts::types::{F2Dot14, FWord, UfWord}; + let one = F2Dot14::from_f32(1.0); + let half = F2Dot14::from_f32(0.5); + let line = ColorLine::new(Extend::Pad, 2, vec![ColorStop::new(F2Dot14::from_f32(-0.5), 0, half), ColorStop::new(one, 1, one)]); + let w = FWord::new; + // Half-opaque red at -0.5 and blue at 1: at 0, a third of the way from red to blue, in color + // and opacity. + let red = GradientStop { opacity: 0.5, ..GradientStop::new(0.0, rgb(COLR_RED)) }; + let tip = Gradient { stops: vec![red, GradientStop::new(1.0, rgb(COLR_BLUE))], ..Gradient::default() }.sample(1.0 / 3.0); + assert!((tip.1 - 2.0 / 3.0).abs() < 1e-6, "{tip:?}"); + for (family, c1_x, focal) in [("Colrtest Tip", 250, Some(300.0)), ("Colrtest Dot", 300, None)] { + let font = v1_font(family, COLOUR_CHAR, |o| { + ColrPaint::glyph(ColrPaint::radial_gradient(line.clone(), w(300), w(300), UfWord::new(0), w(c1_x), w(300), UfWord::new(400)), o) + }); + let root = art(&font, COLOUR_CHAR); + let Paint::Gradient(g) = fill(&children(&root)[0]) else { panic!("{family}: a gradient") }; + let offsets: Vec = g.gradient.stops.iter().map(|s| s.offset).collect(); + assert_eq!(offsets, [0.0, 1.0], "{family}"); + let first = &g.gradient.stops[0]; + assert_eq!((first.color, first.opacity), tip, "{family}: the color at the circle of radius 0"); + assert_eq!(g.gradient.stops[1].color, rgb(COLR_BLUE), "{family}"); + let geom = g.geom.unwrap(); + assert!((geom.start.x - f64::from(c1_x)).abs() < 1e-3 && (geom.start.y + 300.0).abs() < 1e-3, "{family}: {geom:?}"); + assert!(((geom.end - geom.start).hypot() - 400.0).abs() < 1e-3, "{family}: {geom:?}"); + assert_eq!(geom.focal.map(|f| ((f.x * 1e3).round() / 1e3, (f.y * 1e3).round() / 1e3)), focal.map(|x| (x, -300.0)), "{family}"); + } +} + +/// A sharp change of color at the circle of radius 0 of a gradient whose color line starts +/// before 0 keeps the color beyond it: red up to 0, then green fading to blue. +#[test] +fn a_sharp_change_of_color_at_the_circle_of_radius_0_keeps_the_color_beyond_it() { + use write_fonts::tables::colr::{ColorLine, ColorStop, Extend}; + use write_fonts::types::{F2Dot14, FWord, UfWord}; + let (one, zero) = (F2Dot14::from_f32(1.0), F2Dot14::from_f32(0.0)); + let stops = vec![ + ColorStop::new(F2Dot14::from_f32(-1.0), 0, one), + ColorStop::new(zero, 0, one), + ColorStop::new(zero, 2, one), + ColorStop::new(one, 1, one), + ]; + let line = ColorLine::new(Extend::Pad, 4, stops); + let w = FWord::new; + let font = v1_font("Colrtest Edge", COLOUR_CHAR, |o| { + ColrPaint::glyph(ColrPaint::radial_gradient(line.clone(), w(300), w(300), UfWord::new(0), w(250), w(300), UfWord::new(400)), o) + }); + let root = art(&font, COLOUR_CHAR); + let Paint::Gradient(g) = fill(&children(&root)[0]) else { panic!("a gradient") }; + let stops = &g.gradient.stops; + let colors: Vec = stops.iter().map(|s| s.color).collect(); + assert_eq!(colors, [rgb(COLR_RED), rgb(COLR_RED), rgb(COLR_GREEN), rgb(COLR_BLUE)], "{stops:?}"); + assert!(stops[..3].iter().all(|s| s.offset.abs() < 1e-5) && stops[3].offset == 1.0, "{stops:?}"); +} + +/// A glyph drawn into an image draws a radial gradient with a circle of a negative radius from the +/// circle of radius 0, as vector art does: with pad, the color at the tip of the cone and the +/// colors on its drawn side, not one solid color. A composite that keeps only its backdrop makes +/// the glyph an image. Red runs to blue; the circles are around the `O`'s middle and larger than it. +#[test] +fn an_image_of_a_radial_gradient_with_a_stop_past_its_circle_of_radius_0_draws_from_that_circle() { + use write_fonts::tables::colr::{ColorLine, ColorStop, CompositeMode, Extend}; + use write_fonts::types::{F2Dot14, FWord, UfWord}; + let one = F2Dot14::from_f32(1.0); + let w = FWord::new; + type Check = fn([u8; 3]) -> bool; + // Red at -0.5 (a start circle of radius -250 once normalized): the colors run from a third of + // the way to blue at the tip to blue. Blue at 1.5 (an end circle of radius -250): they run + // from red at the outer circle, which lies outside the `O`, to two thirds of the way to blue + // at the tip. Either way every opaque pixel holds some blue. + let cases: [(&str, f32, f32, u16, u16, Check); 2] = + [("Colrtest Tip Image", -0.5, 1.0, 0, 500, |[r, _, b]| b > 20 && r < 240), ("Colrtest Rim Image", 0.0, 1.5, 500, 0, |[_, _, b]| b > 20)]; + for (family, first, last, r0, r1, check) in cases { + let line = + ColorLine::new(Extend::Pad, 2, vec![ColorStop::new(F2Dot14::from_f32(first), 0, one), ColorStop::new(F2Dot14::from_f32(last), 1, one)]); + let font = v1_font(family, COLOUR_CHAR, |o| { + let radial = ColrPaint::radial_gradient(line.clone(), w(290), w(330), UfWord::new(r0), w(290), w(330), UfWord::new(r1)); + ColrPaint::composite(ColrPaint::glyph(solid(2), o), CompositeMode::Dest, ColrPaint::glyph(radial, o)) + }); + let Some(ColourContent::Image(image)) = content(&font, COLOUR_CHAR) else { panic!("{family}: an image") }; + let pixmap = vello_cpu::Pixmap::from_png(std::io::Cursor::new(image.blob.bytes.as_slice())).unwrap(); + let pixels: Vec<[u8; 3]> = pixmap.take_unpremultiplied().into_iter().filter(|p| p.a == 255).map(|p| [p.r, p.g, p.b]).collect(); + assert!(pixels.len() > 100, "{family}: the `O` is drawn"); + let wrong: Vec<_> = pixels.iter().filter(|p| !check(**p)).take(5).collect(); + assert!(wrong.is_empty(), "{family}: {wrong:?}"); + } + // Repeat and reflect draw their bands, not one color. + for (family, extend) in [("Colrtest Repeat Image", Extend::Repeat), ("Colrtest Reflect Image", Extend::Reflect)] { + let line = ColorLine::new(extend, 2, vec![ColorStop::new(F2Dot14::from_f32(-0.5), 0, one), ColorStop::new(one, 1, one)]); + let font = v1_font(family, COLOUR_CHAR, |o| { + ColrPaint::glyph(ColrPaint::radial_gradient(line.clone(), w(290), w(330), UfWord::new(0), w(290), w(330), UfWord::new(100)), o) + }); + let Some(ColourContent::Image(image)) = content(&font, COLOUR_CHAR) else { panic!("{family}: an image") }; + let pixmap = vello_cpu::Pixmap::from_png(std::io::Cursor::new(image.blob.bytes.as_slice())).unwrap(); + let colors: std::collections::HashSet<[u8; 3]> = + pixmap.take_unpremultiplied().into_iter().filter(|p| p.a == 255).map(|p| [p.r, p.g, p.b]).collect(); + assert!(colors.len() > 10, "{family}: {colors:?}"); + } +} + +/// A radial gradient whose circles both have the same negative radius at a variable font's +/// instance draws no circle, so a glyph painted with only that gradient is colour art that draws +/// nothing, not its outline. The radii are 10 at the default weight and -10 at 700. +#[test] +fn a_radial_gradient_with_no_circle_drawn_leaves_the_glyph_empty() { + use write_fonts::tables::colr::{BaseGlyphList, BaseGlyphPaint, Colr, Extend, VarColorLine, VarColorStop}; + use write_fonts::tables::variations::{ItemVariationData, ItemVariationStore, RegionAxisCoordinates, VariationRegion, VariationRegionList}; + use write_fonts::types::{F2Dot14, FWord, GlyphId16, UfWord}; + let bytes = colr_font(false).unwrap(); + let read = skrifa::FontRef::new(&bytes).unwrap(); + let gid = |ch| GlyphId16::new(u16::try_from(read.charmap().map(ch).unwrap().to_u32()).unwrap()); + let (one, fixed) = (F2Dot14::from_f32(1.0), 0xFFFF_FFFF); + let line = + VarColorLine::new(Extend::Pad, 2, vec![VarColorStop::new(F2Dot14::from_f32(0.0), 0, one, fixed), VarColorStop::new(one, 1, one, fixed)]); + let w = FWord::new; + let radial = ColrPaint::var_radial_gradient(line, w(290), w(330), UfWord::new(10), w(290), w(330), UfWord::new(10), 0); + let mut colr = Colr::new(0, None, None, 0); + colr.base_glyph_list = Some(BaseGlyphList::new(1, vec![BaseGlyphPaint::new(gid(COLOUR_CHAR), ColrPaint::glyph(radial, gid('O')))])).into(); + // One 16-bit delta for each of x0, y0, r0, x1, y1 and r1, at full weight. + let deltas: Vec = [0i16, 0, -20, 0, 0, -20].iter().flat_map(|d| d.to_be_bytes()).collect(); + let region = VariationRegion::new(vec![RegionAxisCoordinates::new(F2Dot14::from_f32(0.0), one, one)]); + let data = ItemVariationData::new(6, 1, vec![0], deltas); + colr.item_variation_store = Some(ItemVariationStore::new(VariationRegionList::new(1, vec![region]), vec![Some(data)])).into(); + let font = crate::test_fonts::colr_variable_font_with("Colrtest No Circle", &colr).unwrap(); + let font = skrifa::FontRef::new(&font).unwrap(); + let bold = font.axes().location([("wght", 700.0)]); + let Some(ColourContent::Art(root)) = colour_glyph(&font, (&bold).into(), 1000.0, u32::from(gid(COLOUR_CHAR).to_u16()), FOREGROUND).0 else { + panic!("colour art") + }; + assert!(children(&root).is_empty(), "{:?}", children(&root).iter().map(|c| c.kind_label()).collect::>()); +} + /// A COLRv1 color line through `stops` (offset, palette index) that extends by `extend`. fn color_line(extend: write_fonts::tables::colr::Extend, stops: &[(f32, u16)]) -> write_fonts::tables::colr::ColorLine { use write_fonts::tables::colr::{ColorLine, ColorStop}; diff --git a/crates/text/src/tests/combos.rs b/crates/text/src/tests/combos.rs index 4f57aa6972..a2d837e286 100644 --- a/crates/text/src/tests/combos.rs +++ b/crates/text/src/tests/combos.rs @@ -378,8 +378,8 @@ fn x_width() -> f64 { fn composer_x_mixed_sizes_in_a_stepped_frame() { // A frame as wide as the first line down to 40 pt and half as wide below. A 36 pt word makes // the line it is on reach below the step, where the frame is narrow: the every-line composer - // breaks the paragraph with each line's measure where its height sets it, not as the - // single-line composer does, and every line keeps within its room. + // breaks the paragraph with each line's measure where its height sets it, and every line keeps + // within its room. let w = x_width(); let set = |x: CharStyle, composer: Composer| { let mut t = stepped(w, w * 0.5, 40.0, 300.0); @@ -394,8 +394,10 @@ fn composer_x_mixed_sizes_in_a_stepped_frame() { // The 36 pt line reaches below the step and is set at the narrow measure. let tall = &l.lines[1]; assert!(tall.ascent > 30.0 && tall.baseline + tall.descent > 40.0 && tall.avail.1 < w * 0.5 + 0.01, "{:?}", l.lines); + // The single-line composer measures each line across its height too, and breaks this + // paragraph the same way. let (greedy, _) = set(sans(36.0), Composer::SingleLine); - assert_ne!(every, greedy); + assert_eq!(every, greedy); // Uniform sizes keep the breaks they had. let (uniform, _) = set(sans(12.0), Composer::EveryLine); assert_eq!(uniform, ["Destroy all creatures with toughness X or", "less. Then draw a card for each creature", "destroyed this way."]); @@ -435,8 +437,40 @@ fn composer_x_mixed_sizes_around_text_wrap() { across && !text[g.byte..].starts_with(char::is_whitespace) && g.origin.x < object.x1 && g.origin.x + g.advance > object.x0 }); assert_eq!(hits.count(), 0, "{:?}", l.lines); + // The single-line composer measures each line across its height too, and breaks this + // paragraph the same way. let (greedy, _, _) = set(Composer::SingleLine); - assert_ne!(every, greedy); + assert_eq!(every, greedy); +} + +#[test] +fn composer_x_taller_line_in_a_further_span() { + // A wrap object down the middle of the frame splits every line in two. The 36 pt word falls in + // the span right of it on the second baseline, after a 12 pt line left of it: the line that + // holds it is set as far below the line above it as its own leading sets it, and its ascent + // stays clear of that line, with either composer. + let w = x_width(); + let object = Rect::new(w, -10.0, w + 40.0, 310.0); + for composer in [Composer::SingleLine, Composer::EveryLine] { + let mut runs = vec![run(&format!("{RAG} Then draw a card for each creature destroyed this way. "), sans(12.0))]; + runs.extend(with_x(sans(36.0))); + let mut t = area(runs, Rect::new(0.0, 0.0, 2.0 * w + 40.0, 300.0)); + t.wrap = vec![vectorcraft_doc::WrapShape { path: PathData::from_bezpath(&object.to_path(0.1)), wrap: Default::default() }]; + t.para.composer = composer; + let l = layout(db(), &t); + assert!(!l.overflow, "{composer:?}: {:?}", l.lines); + let tall: Vec<_> = l.lines.iter().filter(|line| line.ascent > 30.0).collect(); + assert_eq!(tall.len(), 1, "{composer:?}: {:?}", l.lines); + for line in tall { + for above in l.lines.iter().filter(|a| a.baseline < line.baseline - 0.01) { + let beside = above.avail.0 < line.avail.1 && line.avail.0 < above.avail.1; + assert!( + !beside || line.baseline - line.ascent >= above.baseline + above.descent - 0.01, + "{composer:?}: {line:?} reaches into {above:?}" + ); + } + } + } } #[test] @@ -463,13 +497,42 @@ fn composer_x_mixed_sizes_in_a_frame_that_widens() { assert_eq!(greedy, ["Destroy all", "creatures", "with toughness X or less. Then draw", "a card for each creature destroyed this", "way."]); } +#[test] +fn single_line_composer_measures_a_line_across_its_tallest_glyph() { + // A frame wide enough for "Destroy all creatures X" down to 20 pt and as wide as "Destroy all" + // below, and a rectangle as wide with an object (6 pt wrap offset) beside that part. The first + // line starts with 12 pt words and takes in a 36 pt word, which sets it lower and reaches below + // 20 pt: the single-line composer measures its room across that height, every line that + // reaches the narrow part is set in it, and the first line keeps the 12 pt words that fit + // above it. + let w = natural_width("Destroy all creatures X", 12.0) + 30.0; + let narrow = natural_width("Destroy all", 12.0) + 2.0; + let runs = vec![run("Destroy all creatures ", sans(12.0)), run("X", sans(36.0)), run(" or less. Then draw a card.", sans(12.0))]; + let object = Rect::new(narrow + 6.0, 26.0, w + 10.0, 300.0); + let mut beside = area(runs.clone(), Rect::new(0.0, 0.0, w, 300.0)); + beside.wrap = vec![vectorcraft_doc::WrapShape { path: PathData::from_bezpath(&object.to_path(0.1)), wrap: Default::default() }]; + let mut shaped = stepped(w, narrow, 20.0, 300.0); + shaped.runs = runs; + for (name, mut t) in [("stepped frame", shaped), ("text wrap", beside)] { + t.para.composer = Composer::SingleLine; + let l = layout(db(), &t); + assert!(past_their_room(&t, &l).is_empty() && !l.overflow, "{name}: {:?}", l.lines); + let low = l.lines.iter().filter(|li| li.baseline + li.descent > 20.01); + assert!(low.clone().all(|li| li.avail.1 <= narrow + 0.01), "{name}: {:?}", l.lines); + // The 36 pt word is set, on a line in the narrow part. + assert!(low.clone().any(|li| li.ascent > 30.0), "{name}: {:?}", l.lines); + assert_eq!(line_texts(&t, &l)[0], "Destroy all creatures", "{name}: {:?}", l.lines); + assert!(l.lines[0].baseline < 20.0 && l.lines[0].avail.1 > w - 0.01, "{name}: {:?}", l.lines); + } +} + #[test] fn composer_x_mixed_sizes_overflow_a_shaped_frame() { // A stepped frame too short for the paragraph: the every-line composer still breaks the lines // that fit as one paragraph, with the lines past the frame's end measured as wide as the last // line the frame holds. Here that is the narrow part, so the lines that fit break as in a frame - // tall enough for the whole paragraph, and not as the single-line composer breaks them. They - // are set in order, each once and within its room, and the frame overflows. + // tall enough for the whole paragraph. They are set in order, each once and within its room, + // and the frame overflows. let w = x_width(); let set = |bottom: f64, composer: Composer| { let mut t = stepped(w, w * 0.5, 40.0, bottom); @@ -487,8 +550,10 @@ fn composer_x_mixed_sizes_overflow_a_shaped_frame() { assert_eq!(every, ["Destroy all creatures with toughness", "X or less. Then", "draw a card for each"]); let (whole, ..) = set(300.0, Composer::EveryLine); assert_eq!(every, whole[..every.len()]); + // The single-line composer measures each line across its height too, and breaks the lines + // that fit the same way. let (greedy, ..) = set(75.0, Composer::SingleLine); - assert_ne!(every, greedy); + assert_eq!(every, greedy); // A frame with no room for a line sets none. for composer in [Composer::EveryLine, Composer::SingleLine] { let mut t = stepped(w, w * 0.5, 4.0, 8.0); @@ -529,8 +594,10 @@ fn composer_x_mixed_sizes_overflow_around_text_wrap() { assert_eq!(hits.count(), 0, "{:?}", l.lines); // The lines that fit break as in `composer_x_mixed_sizes_around_text_wrap`'s taller frame. assert_eq!(every, ["Destroy all creatures with", "toughness\u{a0}X", "or less. Then", "draw a card for", "each creature"]); + // The single-line composer measures each line across its height too, and breaks the lines + // that fit the same way. let (greedy, ..) = set(Composer::SingleLine); - assert_ne!(every, greedy); + assert_eq!(every, greedy); } #[test] diff --git a/crates/text/src/tests/composite.rs b/crates/text/src/tests/composite.rs index 4158d89330..0765b88aaf 100644 --- a/crates/text/src/tests/composite.rs +++ b/crates/text/src/tests/composite.rs @@ -192,6 +192,72 @@ fn nested_loans_of_one_name_use_each_documents_definition() { assert_eq!(db.generation(), plain); } +/// While one document's composite fonts are lent, a name only another document defines (the one +/// the database holds, or one an outer guard lends) is no composite font: type set in it lays out +/// as in a missing font, also after it was laid out in that definition with nothing lent. +#[test] +fn a_lent_document_does_not_use_another_documents_composite_font() { + let db = FontDb::with_font_dirs(vec![]); + let (a, b) = (roman_at("CF Only A", 50.0), roman_at("CF Only B", 50.0)); + // The session registered B's font, and A's (the same definition) as well. + db.set_composite_font(&a); + db.set_composite_font(&b); + let half = advance(&db, "JetBrains Mono", 10.0); + assert!((advance(&db, "CF Only B", 20.0) - half).abs() < 1e-9); + let missing = advance(&db, "CF Nowhere", 20.0); + assert!((missing - half).abs() > 1e-6, "the missing font draws otherwise"); + // Lending looks the name up among the installed families, which catalogs them the first time. + assert!(!db.has_installed_family("CF Only A")); + let plain = db.generation(); + { + let _a = db.lend_composite_fonts(std::slice::from_ref(&a)); + assert!(db.composite_font("CF Only A").is_some()); + assert!(db.composite_font("cf only b").is_none()); + assert!(db.composite_fonts_for("CF Only B", "A").is_none()); + assert_ne!(db.generation(), plain, "type laid out with B's font is not reused"); + assert!((advance(&db, "CF Only B", 20.0) - missing).abs() < 1e-9); + assert!((advance(&db, "CF Only A", 20.0) - half).abs() < 1e-9); + // A document placed in A that defines B's font sees only its own. + let _b = db.lend_composite_fonts(std::slice::from_ref(&b)); + assert!(db.composite_font("CF Only A").is_none()); + assert!((advance(&db, "CF Only B", 20.0) - half).abs() < 1e-9); + } + assert_eq!(db.generation(), plain); + assert!((advance(&db, "CF Only B", 20.0) - half).abs() < 1e-9); +} + +/// A document that defines no composite font, drawn or lent as a document, uses none of the +/// database's. A temporary document that defines none, drawn inside another document's guard, +/// keeps that guard's fonts; with no guard at all, the database's stay in use. +#[test] +fn a_document_without_composite_fonts_uses_none_and_a_preview_is_unchanged() { + let db = FontDb::with_font_dirs(vec![]); + let (a, b) = (roman_at("CF Held A", 50.0), roman_at("CF Held B", 50.0)); + db.set_composite_font(&b); + let half = advance(&db, "JetBrains Mono", 10.0); + let missing = advance(&db, "CF Nowhere Else", 20.0); + let plain = db.generation(); + for lend in [FontDb::lend_composite_fonts, FontDb::lend_document_composite_fonts] { + let _none = lend(&db, &[]); + assert!(db.composite_font("CF Held B").is_none()); + assert_ne!(db.generation(), plain); + assert!((advance(&db, "CF Held B", 20.0) - missing).abs() < 1e-9); + } + { + let _a = db.lend_composite_fonts(std::slice::from_ref(&a)); + // A temporary document drawn inside it lends nothing and keeps A's fonts. + let _preview = db.lend_composite_fonts(&[]); + assert!(db.composite_font("CF Held A").is_some()); + assert!(db.composite_font("CF Held B").is_none()); + // A document placed in it that defines none uses none of A's. + let _placed = db.lend_document_composite_fonts(&[]); + assert!(db.composite_font("CF Held A").is_none()); + } + assert_eq!(db.generation(), plain); + assert!(db.composite_font("CF Held B").is_some()); + assert!((advance(&db, "CF Held B", 20.0) - half).abs() < 1e-9); +} + /// Two threads that lend different definitions of one name at once each lay out in their own. #[test] fn threads_lending_one_name_at_once_use_their_own_definitions() { diff --git a/crates/text/src/tests/harakat.rs b/crates/text/src/tests/harakat.rs index ea84bcf346..c8d93d451f 100644 --- a/crates/text/src/tests/harakat.rs +++ b/crates/text/src/tests/harakat.rs @@ -381,6 +381,44 @@ fn check_spaced_harakat(db: &FontDb, family: &str) { assert!((length(&b) - length(&a) - 12.0).abs() < 1e-6, "{family}: {} → {}", length(&a), length(&b)); } +/// Right to left, with harakat coloured apart, Optical kerning keeps the Tsume of each letter's +/// cluster as it does in "HOH": the glyphs move as far with Optical kerning as without it. +#[test] +fn optical_kerning_keeps_the_tsume_of_a_letter_with_coloured_harakat() { + let db = FontDb::with_font_dirs(vec![]); + assert_eq!(db.add_font(crate::test_fonts::lam_alef_font(b"rlig").unwrap()), 1); + check_optical_tsume(&db, crate::test_fonts::lam_alef_family(b"rlig")); + if let Some(face) = arabic_face("optical_kerning_keeps_the_tsume_of_a_letter_with_coloured_harakat") { + check_optical_tsume(FontDb::global(), &face.family); + } +} + +fn check_optical_tsume(db: &FontDb, family: &str) { + const WORD: &str = "بَبَ"; // ب 0, fatha 2, ب 4, fatha 6 + let set = |optical: bool, letter: Option| { + let mut t = text_with_harakat(WORD, family, Some(red())); + crate::edit::style_range(&mut t.runs, 0, WORD.len(), |st| st.optical_kerning = optical); + if let Some(at) = letter { + crate::edit::style_range(&mut t.runs, at, at + 2, |st| st.tsume = 100.0); + } + t + }; + // Each glyph's place and advance: where a mark's ink leaves no blank space on the left, the + // Tsume of the line's first cluster only narrows its advance and moves no glyph. + let xs = |t: &TextObject| layout(db, t).glyphs.iter().flat_map(|g| [g.xf.as_coeffs()[4], g.advance]).collect::>(); + assert!(xs(&set(true, None)).iter().zip(xs(&set(false, None))).any(|(a, b)| (a - b).abs() > 1e-6), "{family}: Optical moves the pair"); + // Each letter in turn: the first one's cluster ends the pair, the second one's starts it. + for letter in [0, 4] { + let moved = |optical: bool| xs(&set(optical, Some(letter))).iter().zip(xs(&set(optical, None))).map(|(a, b)| a - b).collect::>(); + let (without, with_optical) = (moved(false), moved(true)); + assert!(without.iter().any(|m| m.abs() > 1e-3), "{family} {letter}: Tsume moves or narrows the glyphs: {without:?}"); + assert!( + without.len() == with_optical.len() && without.iter().zip(&with_optical).all(|(a, b)| (a - b).abs() < 1e-6), + "{family} {letter}: {without:?} {with_optical:?}" + ); + } +} + #[test] fn own_chars_need_the_same_setting_and_each_character_in_its_cluster() { // بَبَب right to left: final beh (cluster 8), fatha and medial beh (cluster 4), fatha and diff --git a/crates/text/src/tests/justify.rs b/crates/text/src/tests/justify.rs index bc1e5b1b13..5c82700cde 100644 --- a/crates/text/src/tests/justify.rs +++ b/crates/text/src/tests/justify.rs @@ -668,6 +668,36 @@ fn a_right_to_left_line_with_a_tab_and_many_breaks_wraps_when_it_does_not_fit_as } } +/// A right-to-left line with a tab whose last character loses its Japanese–Latin space at the +/// line's end is measured with that space taken off where the character is drawn, before the tab: +/// right aligned, it ends on the frame's right edge, and it wraps when it does not fit as drawn. +#[test] +fn a_right_to_left_tabbed_line_is_measured_without_its_line_end_space() { + use vectorcraft_doc::Mojikumi; + // א (0), ב (2), tab (4), ג (5), 漢 (7), then a Hebrew word too long for the frame: the first + // line ends after 漢, which loses the quarter em it had before the Hebrew word. + let text = format!("אב\tג漢{}", "ד".repeat(40)); + let lay = |width: f64| { + let mut t = area(&text, width, Justify::Right, no_ranges()); + t.para.mojikumi = Mojikumi::GyomatsuYakumonoZenkaku; + t.para.tabs = vec![TabStop { position: 150.0, align: TabAlign::Left, leader: String::new(), align_on: '.' }]; + layout(db(), &t) + }; + let l = lay(300.0); + assert!(l.lines.len() >= 2, "wraps: {} line(s)", l.lines.len()); + assert!(l.glyphs.iter().filter(|g| g.line == 0).all(|g| g.byte < 10), "the first line ends after 漢"); + let (_, right) = drawn_extent(&l, &text, 0); + assert!((right - 300.0).abs() < 1e-6, "ends on the right edge: {right}"); + assert!((l.lines[0].x1 - right).abs() < 1e-6, "the line's record ends where it is drawn: {}", l.lines[0].x1); + // Drawn, that line is as wide as the stop and the text after the tab (אב). In a frame a point + // narrower, less than the quarter em, it does not fit and the first line stays in the frame. + let after_tab: f64 = l.glyphs.iter().filter(|g| g.byte < 4).map(|g| g.advance).sum(); + let width = 150.0 + after_tab - 1.0; + let l = lay(width); + let (left, right) = drawn_extent(&l, &text, 0); + assert!(left >= -1e-6 && right <= width + 1e-6, "the first line stays in the frame: {left} {right} (frame {width})"); +} + /// Point type has no measure to fill: a justified line with a tab keeps its natural width. #[test] fn justified_point_type_with_a_tab_keeps_its_width() { diff --git a/crates/text/src/tests/tsume.rs b/crates/text/src/tests/tsume.rs index 72f0d69f19..bd2d7d9ccc 100644 --- a/crates/text/src/tests/tsume.rs +++ b/crates/text/src/tests/tsume.rs @@ -112,6 +112,25 @@ fn the_font_kerning_is_added_after_the_tsume() { assert!(near(&before_kerned, &before_h) && before_h[0] < -10.0, "{before_kerned:?} {before_h:?}"); } +#[test] +fn optical_kerning_keeps_the_tsume() { + // Optical kerning spaces each pair as without the Tsume, and the Tsume stays on top: the + // characters move back as far with Optical kerning as without it. + let plain = point("HOH", style(100.0)); + let optical = point("HOH", CharStyle { optical_kerning: true, ..style(100.0) }); + let xs = |t: &TextObject| { + let l = layout(db(), t); + [0, 1, 2].map(|i| drawn_x(&l, i)) + }; + // The test font's Optical spacing differs from its own for these pairs. + assert!(!near(&xs(&optical), &xs(&plain)), "{:?} {:?}", xs(&optical), xs(&plain)); + for at in [0, 1, 2] { + let without = moves(&plain, &with(&plain, at, |s| s.tsume = 100.0), &[0, 1, 2]); + let with_optical = moves(&optical, &with(&optical, at, |s| s.tsume = 100.0), &[0, 1, 2]); + assert!(without.iter().any(|m| *m < -1.0) && near(&with_optical, &without), "{at}: {without:?} {with_optical:?}"); + } +} + #[test] fn a_letter_with_its_mark_takes_the_tsume_of_the_letter() { let plain = point("H\u{301}O", style(100.0)); diff --git a/crates/text/src/tests/typo.rs b/crates/text/src/tests/typo.rs index 4790b642af..351c698451 100644 --- a/crates/text/src/tests/typo.rs +++ b/crates/text/src/tests/typo.rs @@ -2041,3 +2041,40 @@ fn soft_return_breaks_line_even_inside_no_break() { let lay = layout(db(), &t); assert_eq!(lay.lines.len(), 2, "soft return honors line break despite no_break"); } + +/// An East Asian glyph form (the Glyphs panel menu's Traditional Forms, JIS 78 Forms, …) draws +/// the characters with the font's glyphs of that form, and Default with its default glyphs. Needs +/// craft-fonts' BIZ UDMincho, which has traditional, expert, JIS 78, 83 and 90, full-width and +/// half-width forms and no JIS 04 forms (skipped without it). A form on one character of a run +/// changes that character only. +#[test] +fn glyph_forms_draw_the_fonts_east_asian_forms() { + use vectorcraft_doc::GlyphForm; + const FAMILY: &str = "BIZ UDMincho"; + if db().face(FAMILY, "Regular").is_none_or(|f| f.family != FAMILY) { + eprintln!("skipped: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout to run it)"); + return; + } + let st = |form| CharStyle { size: 20.0, font_family: FAMILY.into(), glyph_form: form, ..CharStyle::default() }; + let glyphs = |text: &str, form| layout(db(), &TextObject::point(Point::ZERO, text, st(form))).glyphs; + let gids = |text: &str, form| glyphs(text, form).iter().map(|g| g.gid).collect::>(); + for (form, text) in + [(GlyphForm::Traditional, "亜"), (GlyphForm::Expert, "唖"), (GlyphForm::Jis78, "唖"), (GlyphForm::Jis83, "芦"), (GlyphForm::Jis90, "芦")] + { + assert_ne!(gids(text, form), gids(text, GlyphForm::Default), "{form:?} {text}"); + } + // The font has no JIS 04 forms, so the characters keep their glyphs. + assert_eq!(gids("亜唖芦", GlyphForm::Jis04), gids("亜唖芦", GlyphForm::Default)); + // Full-width Latin takes a whole em, half-width punctuation half of one. + let advance = |text: &str, form| glyphs(text, form).first().map_or(0.0, |g| g.advance); + assert!(advance("A", GlyphForm::Default) < 15.0, "{}", advance("A", GlyphForm::Default)); + assert!((advance("A", GlyphForm::FullWidth) - 20.0).abs() < 0.01, "{}", advance("A", GlyphForm::FullWidth)); + assert!((advance("、", GlyphForm::Default) - 20.0).abs() < 0.01, "{}", advance("、", GlyphForm::Default)); + assert!((advance("、", GlyphForm::HalfWidth) - 10.0).abs() < 0.01, "{}", advance("、", GlyphForm::HalfWidth)); + // Traditional Forms on the middle character only. + let mut t = TextObject::point(Point::ZERO, "亜亜亜", st(GlyphForm::Default)); + edit::style_range(&mut t.runs, 3, 6, |s| s.glyph_form = GlyphForm::Traditional); + let ids: Vec = layout(db(), &t).glyphs.iter().map(|g| g.gid).collect(); + let (plain, traditional) = (gids("亜", GlyphForm::Default), gids("亜", GlyphForm::Traditional)); + assert_eq!(ids, [plain[0], traditional[0], plain[0]]); +} diff --git a/crates/text/src/tests/warichu.rs b/crates/text/src/tests/warichu.rs index d68cb8fccc..cbefb86bb5 100644 --- a/crates/text/src/tests/warichu.rs +++ b/crates/text/src/tests/warichu.rs @@ -433,6 +433,51 @@ fn blocks_the_bidi_order_interleaves_keep_their_places() { assert!(c.x < bet.x && bet.x < z.x, "{c:?} {bet:?} {z:?}"); } +/// A justified line spreads its letters with the same gap before a right-to-left block as before a +/// left-to-right one: the block starts at the first of its glyphs the line draws. +#[test] +fn justification_opens_the_same_gap_before_a_right_to_left_block() { + for inside in ["cd", "אב"] { + let at = |justify: Justify| { + let mut t = area("", style(20.0), Rect::new(0.0, 0.0, 200.0, 400.0), justify); + t.runs = vec![TextRun::new("ab", style(20.0)), TextRun::new(inside, marked(20.0)), TextRun::new("z", style(20.0))]; + let l = layout(db(), &t); + let x = |byte: usize| l.glyphs.iter().filter(|g| g.byte == byte).map(|g| g.origin.x).fold(f64::INFINITY, f64::min); + let block = l.glyphs.iter().filter(|g| g.warichu.is_some()).map(|g| g.origin.x).fold(f64::INFINITY, f64::min); + (x(0), x(1), block, x(2 + inside.len())) + }; + let (a, b, block, z) = at(Justify::Left); + let (a2, b2, block2, z2) = at(Justify::JustifyAll); + let gap = (b2 - a2) - (b - a); + assert!(gap > 1.0, "{inside}: the line is spread: {gap}"); + assert!(((block2 - b2) - (block - b) - gap).abs() < 1e-6, "{inside}: the gap before the block: {} {gap}", (block2 - b2) - (block - b)); + assert!(((z2 - block2) - (z - block) - gap).abs() < 1e-6, "{inside}: the gap after the block: {} {gap}", (z2 - block2) - (z - block)); + } +} + +/// The caret next to a character of a block spans the band of the character's block line, not +/// the whole line. +#[test] +fn the_caret_in_a_block_spans_its_block_line() { + let l = layout(db(), &with_block("cdef", marked(20.0))); + let (c, e) = (&l.glyphs[2], &l.glyphs[4]); + let middle = (c.origin.y + e.origin.y) * 0.5; + let line = &l.lines[0]; + // "c" and "d", on the upper line. + for byte in [2, 3] { + let (top, bottom) = caret_position(&l, byte); + assert!((top.y - (line.baseline - line.ascent)).abs() < 1e-6 && (bottom.y - middle).abs() < 1e-6, "{byte}: {top:?} {bottom:?} {middle}"); + } + // "e" and "f", on the lower line. + for byte in [4, 5] { + let (top, bottom) = caret_position(&l, byte); + assert!((top.y - middle).abs() < 1e-6 && (bottom.y - (line.baseline + line.descent)).abs() < 1e-6, "{byte}: {top:?} {bottom:?} {middle}"); + } + // Outside the block the caret spans the line. + let (top, bottom) = caret_position(&l, 0); + assert!((top.y - (line.baseline - line.ascent)).abs() < 1e-6 && (bottom.y - (line.baseline + line.descent)).abs() < 1e-6); +} + /// A click on a block's lower line goes to that line's characters, not to the character of the /// upper line at the same place along the block. #[test] @@ -581,6 +626,24 @@ fn a_block_of_several_fonts_keeps_the_tallest_of_them() { assert!(first_short.0 >= plain[pair.0].0 - 1e-6 && first_short.1 >= deepest - 1e-6, "{first_short:?} {plain:?}"); } +/// The line holds each block line's characters at their own height: with a wide Line Gap, the +/// ascent of the top block line's characters and the descent of the bottom one's stay inside the +/// line. +#[test] +fn a_wide_line_gap_keeps_the_outer_block_lines_inside_the_line() { + let small = layout(db(), &point("x", style(10.0))); + let (ascent, descent) = (small.lines[0].ascent, small.lines[0].descent); + for lines in [2, 3] { + let l = layout(db(), &with_block("cdefgh", CharStyle { warichu_lines: lines, warichu_gap: 20.0, ..marked(20.0) })); + let line = &l.lines[0]; + let block = &l.glyphs[2..8]; + let top = block.iter().map(|g| g.origin.y).fold(f64::INFINITY, f64::min); + let bottom = block.iter().map(|g| g.origin.y).fold(f64::NEG_INFINITY, f64::max); + assert!(line.baseline - line.ascent <= top - ascent + 1e-6, "{lines}: {} {} {top} {ascent}", line.baseline, line.ascent); + assert!(line.baseline + line.descent >= bottom + descent - 1e-6, "{lines}: {} {} {bottom} {descent}", line.baseline, line.descent); + } +} + /// Warichu Settings on characters not marked Warichu leave their shaping alone: "fi" keeps its /// ligature when only the f has other settings. #[test] diff --git a/crates/text/src/thread/tests.rs b/crates/text/src/thread/tests.rs index adbf3b2c70..4ea7696aae 100644 --- a/crates/text/src/thread/tests.rs +++ b/crates/text/src/thread/tests.rs @@ -415,8 +415,7 @@ fn stepped_frame(w: f64, narrow: f64, y: f64, bottom: f64) -> TextObject { /// A paragraph of mixed type sizes that a stepped frame cannot hold goes on in the next frame. The /// every-line composer breaks the lines the first frame holds as one paragraph, as in a frame tall -/// enough for all of it and not as the single-line composer breaks them, and the first frame -/// takes the text of those lines. The next frame sets the rest at its own width, without the +/// enough for all of it, and the first frame takes the text of those lines. The next frame sets the rest at its own width, without the /// first-line indent, and no character is lost or repeated. The frames take the same shares as /// when each is measured with the whole rest of the story. #[test] @@ -460,8 +459,10 @@ fn a_mixed_size_paragraph_continued_from_a_shaped_frame_is_composed_in_both() { assert_eq!(every, whole[..every.len()], "indent {indent}"); if indent == 0.0 { assert_eq!(every, ["Destroy all creatures with toughness", "X or less. Then", "draw a card for each"]); + // The single-line composer measures each line across its height too, and breaks the + // first frame's lines the same way. let (greedy, ..) = shares(Composer::SingleLine, indent); - assert_eq!(greedy, ["Destroy all creatures with toughness X", "or less. Then draw a", "card for each", "creature destroyed"]); + assert_eq!(greedy, every); } // The next frame starts at its left edge, and its lines keep within it. assert!((line_start(&lays[1], 0) - 200.0).abs() < 1e-6, "{}", line_start(&lays[1], 0)); diff --git a/crates/three-d/src/lib.rs b/crates/three-d/src/lib.rs index bb066c0e8a..4290bc1c75 100644 --- a/crates/three-d/src/lib.rs +++ b/crates/three-d/src/lib.rs @@ -21,7 +21,10 @@ mod caps; mod mesh; pub use mesh::{Mesh, MeshedSolid, extrude_mesh, extrude_meshed, inflate_meshed, inflate_meshes, plane_mesh, revolve_mesh}; mod shadow; -pub use shadow::{MAX_SHADOW_FACES, Shadow, ShadowCaster, ShadowPlane, ShadowPosition, TOO_COMPLEX_SHADOW}; +pub use shadow::{ + MAX_SHADOW_FACES, Shadow, ShadowCaster, ShadowPlane, ShadowPosition, SolidFaces, TOO_COMPLEX_SHADOW, extrude_shadowed, inflate_shadowed, + plane_shadowed, revolve_facets_shadowed, revolve_shadowed, +}; use vectorcraft_geom::kurbo::{ParamCurveArclen, ParamCurveDeriv}; use vectorcraft_geom::{BezPath, FillRule, ParamCurve, PathData, Point, Rect, Shape, Vec2}; @@ -961,21 +964,136 @@ fn revolve_face_limit(o: Revolve) -> usize { /// [`revolve`], or with `mesh` the surface's faces before projection, kept there instead of drawn, /// each turned out of the region `rule` fills. -fn revolve_faces( +fn revolve_faces(path: &PathData, rule: FillRule, bounds: Rect, options: Revolve, mesh: Option<&mut Vec>) -> Result, String> { + let draw = mesh.is_none(); + revolve_sweep(path, rule, bounds, options, draw, mesh).map(|(faces, _)| faces) +} + +#[cfg(test)] +thread_local! { + /// How many Revolve surfaces this thread has swept, for the tests. + pub(crate) static REVOLVED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// One contour's profile as a sweep takes it: its points, the tangents at the ends of each edge, +/// and whether each edge walls a hole. +#[derive(Default)] +struct Swept { + points: Vec, + tangents: Vec<[Vec2; 2]>, + holes: Vec, +} + +/// Where a sweep places a profile: about the axis at `axis` and the middle height `center_y`, +/// turned through `sweep` radians in `steps` steps, with the sanitized options `o`. +struct Sweeping { + o: Revolve, + axis: f64, + center_y: f64, + sweep: f64, + steps: usize, +} + +impl Sweeping { + /// Profile point `p` turned to the end of step `step`, in view space. + fn vertex(&self, p: Point, step: usize) -> V3 { + let (s, c) = (self.sweep * step as f64 / self.steps as f64).sin_cos(); + self.o.rotate(V3((p.x - self.axis) * c, p.y - self.center_y, (p.x - self.axis) * s)) + } +} + +/// The end `index` (0 the first, 1 the last) of `profile` and the way its cap faces along the axis: +/// the sign of the end's y less its neighbor's, or with the two level, -1 for an end above the +/// middle height `center_y` and 1 otherwise. +fn cap_outward(profile: &[Point], index: usize, center_y: f64) -> Option<(Point, f64)> { + let neighbours = if index == 0 { profile.first().zip(profile.get(1)) } else { profile.last().zip(profile.get(profile.len().saturating_sub(2))) }; + neighbours.map(|(end, neighbour)| { + let dy = end.y - neighbour.y; + let outward = if dy.abs() > 1e-10 { + dy.signum() + } else if end.y < center_y { + -1.0 + } else { + 1.0 + }; + (*end, outward) + }) +} + +/// Keep for a mesh the faces of one contour's profile `s`, which runs round the region it sweeps as +/// `turn` says (its holes' walls turned the other way): a quad for each edge at each step, then for +/// each end in `caps` (0 the first, 1 the last) the disk, or for a sweep of less than a full turn +/// the sector with its center on the axis. `keep` keeps one face with its outward normal; its +/// error, or an edge with invalid coordinates, stops the faces. +fn keep_profile(at: &Sweeping, s: &Swept, turn: f64, caps: &[usize], mut keep: impl FnMut(Vec, V3) -> Result<(), String>) -> Result<(), String> { + let (o, steps) = (at.o, at.steps); + for (pair, hole) in s.points.windows(2).zip(&s.holes) { + let [a, b] = pair else { continue }; + let turn = if *hole { -turn } else { turn }; + if ![a.x, a.y, b.x, b.y].iter().all(|v| v.is_finite() && v.abs() <= 1e8) { + return Err("Revolve profile contains invalid coordinates".into()); + } + for j in 0..steps { + let [v0, v1, v2, v3] = [at.vertex(*a, j), at.vertex(*b, j), at.vertex(*b, j + 1), at.vertex(*a, j + 1)]; + // The edge's outward normal in the profile's plane (distance from the axis, height), + // swept to the middle of the step. + let (dr, dy) = ((b.x - a.x) * turn, (b.y - a.y) * turn); + let (sin, cos) = (at.sweep * (j as f64 + 0.5) / steps as f64).sin_cos(); + keep(vec![v0, v1, v2, v3], o.rotate(V3(dy * cos, -dr, dy * sin)))?; + } + } + for &index in caps { + let Some((end, outward)) = cap_outward(&s.points, index, at.center_y) else { continue }; + let mut cap: Vec = (0..=steps).map(|j| at.vertex(end, j)).collect(); + if o.angle >= 360.0 { + cap.pop(); + } else { + cap.insert(0, o.rotate(V3(0.0, end.y - at.center_y, 0.0))); + } + keep(cap, o.rotate(V3(0.0, outward, 0.0)))?; + } + Ok(()) +} + +/// Keep no more faces for a mesh after error `e`, which is the result when no face is drawn. +fn lose_mesh(draw: bool, mesh: &mut Option<&mut Vec>, lost: &mut Option, e: String) -> Result<(), String> { + if !draw { + return Err(e); + } + *mesh = None; + lost.get_or_insert(e); + Ok(()) +} + +/// [`revolve`]'s faces when `draw`, and with `mesh` the surface's faces before projection kept +/// there from the same sweep, each turned out of the region `rule` fills. While faces are drawn, an +/// error keeping faces for the mesh stops only the mesh: the error comes back beside the faces +/// drawn, and `mesh` keeps no more faces. Without `draw` that error is the result. +fn revolve_sweep( path: &PathData, rule: FillRule, bounds: Rect, options: Revolve, + draw: bool, mut mesh: Option<&mut Vec>, -) -> Result, String> { +) -> Result<(Vec, Option), String> { + #[cfg(test)] + REVOLVED.with(|n| n.set(n.get() + 1)); let o = options.sanitized(); let curve_samples = match o.curve_samples { Some(samples) => samples.clamp(1, CURVE_SAMPLES), None => revolve_curve_samples([path], o)?, }; + let mut lost = None; // For a mesh, each piece of a closed contour's edge is cut where it crosses another contour, so // each part's normal turns toward a hole only where it walls one. - let mut search = if mesh.is_some() { Some(HoleSearch::new(path, rule)?) } else { None }; + let mut search = None; + if mesh.is_some() { + match HoleSearch::new(path, rule) { + Ok(s) => search = Some(s), + Err(e) => lose_mesh(draw, &mut mesh, &mut lost, e)?, + } + } let face_limit = revolve_face_limit(o); // A face kept for a mesh: its normal follows from its corners. let keep = |mesh: &mut Vec, face: Vec, normal: V3| { @@ -1013,10 +1131,8 @@ fn revolve_faces( // Only the longest contour of a compound profile carries the graphics. let surface_contour = o.map_surface.then(|| longest_contour(path, axis)).flatten(); let mut faces = Vec::new(); - let vertex = |p: Point, step: usize| { - let (s, c) = (sweep * step as f64 / steps as f64).sin_cos(); - o.rotate(V3((p.x - axis) * c, p.y - center_y, (p.x - axis) * s)) - }; + let at = Sweeping { o, axis, center_y, sweep, steps }; + let vertex = |p: Point, step: usize| at.vertex(p, step); let normal = |tangent: Vec2, step: usize| { let (s, c) = (sweep * step as f64 / steps as f64).sin_cos(); o.rotate(V3(tangent.y * c, -tangent.x, tangent.y * s).unit()) @@ -1032,17 +1148,26 @@ fn revolve_faces( } Ok(()) }; - let mut count = 0; + // The points of the profile drawn, and of the profile kept for the mesh, which takes the parts + // its edges are cut into. + let (mut count, mut kept_count) = (0, 0); let mut curve_budget = 0; for (contour, sp) in path.subpaths.iter().enumerate() { - let mut profile = Vec::new(); - let mut tangents = Vec::new(); - let mut hole_edges = Vec::new(); + let (mut drawn, mut kept) = (Swept::default(), Swept::default()); if let Some(first) = sp.anchors.first() { - profile.push(first.p); - count += 1; - if count > MAX_PROFILE_POINTS { - return Err(TOO_COMPLEX_PROFILE.into()); + if draw { + drawn.points.push(first.p); + count += 1; + if count > MAX_PROFILE_POINTS { + return Err(TOO_COMPLEX_PROFILE.into()); + } + } + if mesh.is_some() { + kept.points.push(first.p); + kept_count += 1; + if kept_count > MAX_PROFILE_POINTS { + lose_mesh(draw, &mut mesh, &mut lost, TOO_COMPLEX_PROFILE.into())?; + } } } let segments = if sp.closed { sp.anchors.len() } else { sp.anchors.len().saturating_sub(1) }; @@ -1074,22 +1199,40 @@ fn revolve_faces( let v = d.eval(t.clamp(1e-7, 1.0 - 1e-7)).to_vec2(); if v.hypot2() > 1e-20 { v } else { b - a } }; - let a = profile.last().copied().unwrap_or(b); - let parts = match search.as_mut() { - Some(search) => search.parts(contour, a, b)?, - None => vec![(b, false)], - }; - for (end, hole) in parts { - tangents.push([tangent(t0), tangent(t1)]); - hole_edges.push(hole); - profile.push(end); + let ends = [tangent(t0), tangent(t1)]; + if draw { + drawn.tangents.push(ends); + drawn.holes.push(false); + drawn.points.push(b); count += 1; if count > MAX_PROFILE_POINTS { return Err(TOO_COMPLEX_PROFILE.into()); } } + let Some(search) = search.as_mut().filter(|_| mesh.is_some()) else { continue }; + let a = kept.points.last().copied().unwrap_or(b); + let parts = match search.parts(contour, a, b) { + Ok(parts) => parts, + Err(e) => { + lose_mesh(draw, &mut mesh, &mut lost, e)?; + continue; + } + }; + for (end, hole) in parts { + kept.tangents.push(ends); + kept.holes.push(hole); + kept.points.push(end); + kept_count += 1; + if kept_count > MAX_PROFILE_POINTS { + lose_mesh(draw, &mut mesh, &mut lost, TOO_COMPLEX_PROFILE.into())?; + break; + } + } } } + // The two profiles start and end at the same points: the parts of the last edge end where + // it does. + let profile = if draw { &drawn.points } else { &kept.points }; let ends = o.cap_ends && !sp.closed && profile.len() >= 2 && profile.first().zip(profile.last()).is_some_and(|(a, b)| a.distance(*b) > 1e-10); let mut rings = [None, None]; if ends { @@ -1101,33 +1244,49 @@ fn revolve_faces( } } } - // For a mesh: which way the profile runs round the region it sweeps (closed against the - // axis at its ends when it is open), so the faces' normals point out of the solid. - let turn = { - let mut ring: Vec<(f64, f64)> = profile.iter().map(|p| (p.x - axis, p.y)).collect(); - if let (false, Some(first), Some(last)) = (sp.closed, profile.first(), profile.last()) { - ring.extend([(0.0, last.y), (0.0, first.y)]); + // Which way a profile runs round the region it sweeps (closed against the axis at its ends + // when it is open), so the faces' normals point out of the solid. A closed contour that does + // not touch the axis has its side cut opposite the middle of its outer side; an anchor goes + // there, so no face runs across the cut. That one anchor is not counted against the limit + // on the profile's points. + let prepare = |s: &mut Swept| { + let turn = { + let mut ring: Vec<(f64, f64)> = s.points.iter().map(|p| (p.x - axis, p.y)).collect(); + if let (false, Some(first), Some(last)) = (sp.closed, s.points.first(), s.points.last()) { + ring.extend([(0.0, last.y), (0.0, first.y)]); + } + let area: f64 = ring.iter().zip(ring.iter().cycle().skip(1)).take(ring.len()).map(|(p, q)| p.0 * q.1 - q.0 * p.1).sum(); + if area < 0.0 { -1.0 } else { 1.0 } + }; + if sp.closed + && surface_contour == Some(contour) + && let Some((k, t)) = ring_cut(&s.points, axis) + && let (Some(a), Some(b), Some([ta, tb]), Some(hole)) = + (s.points.get(k), s.points.get(k + 1), s.tangents.get(k).copied(), s.holes.get(k).copied()) + { + let point = *a + (*b - *a) * t; + let middle = ta + (tb - ta) * t; + s.points.insert(k + 1, point); + s.tangents.splice(k..=k, [[ta, middle], [middle, tb]]); + s.holes.insert(k + 1, hole); } - let area: f64 = ring.iter().zip(ring.iter().cycle().skip(1)).take(ring.len()).map(|(p, q)| p.0 * q.1 - q.0 * p.1).sum(); - if area < 0.0 { -1.0 } else { 1.0 } + turn }; - // A closed contour that does not touch the axis has its side cut opposite the middle of its - // outer side; an anchor goes there, so no face runs across the cut. That one anchor is not - // counted against the limit on the profile's points. - if sp.closed - && surface_contour == Some(contour) - && let Some((k, t)) = ring_cut(&profile, axis) - && let (Some(a), Some(b), Some([ta, tb]), Some(hole)) = - (profile.get(k), profile.get(k + 1), tangents.get(k).copied(), hole_edges.get(k).copied()) - { - let point = *a + (*b - *a) * t; - let middle = ta + (tb - ta) * t; - profile.insert(k + 1, point); - tangents.splice(k..=k, [[ta, middle], [middle, tb]]); - hole_edges.insert(k + 1, hole); + if let Some(m) = mesh.as_deref_mut() { + let turn = prepare(&mut kept); + let caps: Vec = rings.iter().enumerate().filter_map(|(i, r)| r.as_ref().map(|_| i)).collect(); + let kept = keep_profile(&at, &kept, turn, &caps, |face, normal| keep(m, face, normal)); + if let Err(e) = kept { + lose_mesh(draw, &mut mesh, &mut lost, e)?; + } } - let along = along_profile(&profile, axis, sp.closed); - for (i, ((pair, [ta, tb]), hole)) in profile.windows(2).zip(tangents).zip(hole_edges).enumerate() { + if !draw { + continue; + } + let turn = prepare(&mut drawn); + let profile = &drawn.points; + let along = along_profile(profile, axis, sp.closed); + for (i, ((pair, [ta, tb]), hole)) in profile.windows(2).zip(drawn.tangents.iter().copied()).zip(drawn.holes.iter().copied()).enumerate() { let [a, b] = pair else { continue }; let turn = if hole { -turn } else { turn }; let [va, vb] = along.get(i).copied().unwrap_or_default(); @@ -1136,14 +1295,6 @@ fn revolve_faces( } for j in 0..steps { let [v0, v1, v2, v3] = [vertex(*a, j), vertex(*b, j), vertex(*b, j + 1), vertex(*a, j + 1)]; - if let Some(mesh) = mesh.as_deref_mut() { - // The edge's outward normal in the profile's plane (distance from the axis, - // height), swept to the middle of the step. - let (dr, dy) = ((b.x - a.x) * turn, (b.y - a.y) * turn); - let (s, c) = (sweep * (j as f64 + 0.5) / steps as f64).sin_cos(); - keep(mesh, vec![v0, v1, v2, v3], o.rotate(V3(dy * c, -dr, dy * s)))?; - continue; - } let first = (i == 0).then(|| rings.first().and_then(Option::as_ref).and_then(|r| r.arcs.get(j))).flatten(); let last = (i + 2 == profile.len()).then(|| rings.last().and_then(Option::as_ref).and_then(|r| r.arcs.get(j))).flatten(); // Where the corners lie on the unrolled side surface, and whether the face shows @@ -1186,28 +1337,7 @@ fn revolve_faces( } } for (index, ring) in rings.iter().enumerate().filter_map(|(i, r)| r.as_ref().map(|r| (i, r))) { - let neighbours = - if index == 0 { profile.first().zip(profile.get(1)) } else { profile.last().zip(profile.get(profile.len().saturating_sub(2))) }; - if let Some((end, neighbour)) = neighbours { - let dy = end.y - neighbour.y; - let outward = if dy.abs() > 1e-10 { - dy.signum() - } else if end.y < center_y { - -1.0 - } else { - 1.0 - }; - if let Some(mesh) = mesh.as_deref_mut() { - // The disk, or for a partial sweep the sector with its centre on the axis. - let mut cap: Vec = (0..=steps).map(|j| vertex(*end, j)).collect(); - if o.angle >= 360.0 { - cap.pop(); - } else { - cap.insert(0, o.rotate(V3(0.0, end.y - center_y, 0.0))); - } - keep(mesh, cap, o.rotate(V3(0.0, outward, 0.0)))?; - continue; - } + if let Some((_, outward)) = cap_outward(profile, index, center_y) { // Keep the original tessellation work budget, even though each cap // now produces only one curved vector face. emit(ring.face(bounds, o, light, outward)?, steps)?; @@ -1215,7 +1345,7 @@ fn revolve_faces( } } faces.sort_by(|a, b| a.depth.total_cmp(&b.depth)); - Ok(faces) + Ok((faces, lost)) } #[cfg(test)] diff --git a/crates/three-d/src/shadow.rs b/crates/three-d/src/shadow.rs index 66842abad2..b580ddcd5f 100644 --- a/crates/three-d/src/shadow.rs +++ b/crates/three-d/src/shadow.rs @@ -12,7 +12,7 @@ use std::ops::Range; use vectorcraft_geom::{BezPath, FillRule, PathData, Point, Rect}; use crate::solid::{Face3, Keep, extrude_faces, inflate_faces, plane_faces}; -use crate::{Extrude, Inflate, MAX_SOLID_FACES, Revolve, V3, View, finite, perspective_scale}; +use crate::{Extrude, Face, Facet, Inflate, MAX_SOLID_FACES, Revolve, V3, View, finite, perspective_scale}; /// Where the shadow falls. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] @@ -172,8 +172,8 @@ impl ShadowCaster { /// Add Inflate's solids for several shapes of one object ([`crate::inflate_together`]), each /// shape whose entry in `casts` is true: the eye is placed for every shape, as for the solids - /// drawn, but the faces of the others are not kept (their range is empty). A shape that does - /// not inflate is left out, as its solid is; the result says which, in order. + /// drawn, but the solids of the others are not built (their range is empty). A casting shape + /// that does not inflate is left out, as its solid is; the result says which, in order. pub fn inflate( &mut self, shapes: &[(&PathData, FillRule)], @@ -182,11 +182,15 @@ impl ShadowCaster { options: Inflate, view: View, ) -> Vec, String>> { - inflate_faces(shapes, bounds, options, view, Keep::Faces) - .enumerate() - .map(|(i, r)| { - let (_, faces, projection) = r?; - if casts.get(i).copied().unwrap_or(true) { self.add(faces?, projection) } else { Ok(self.faces.len()..self.faces.len()) } + let mut solids = inflate_faces(shapes, bounds, options, view, Keep::Faces); + (0..shapes.len()) + .map(|i| { + if !casts.get(i).copied().unwrap_or(true) { + solids.pass(); + return Ok(self.faces.len()..self.faces.len()); + } + let (_, faces, projection) = solids.next().unwrap_or_else(|| Ok((vec![], Ok(vec![]), None)))?; + self.add(faces?, projection) }) .collect() } @@ -199,6 +203,14 @@ impl ShadowCaster { self.add(faces, Some(crate::revolve_projection(bounds, o))) } + /// Add the faces of a solid kept by the build that drew it ([`extrude_shadowed`], + /// [`plane_shadowed`], [`inflate_shadowed`], [`revolve_shadowed`]): the faces + /// [`ShadowCaster::extrude`], [`ShadowCaster::plane`], [`ShadowCaster::inflate`] or + /// [`ShadowCaster::revolve`] adds for that solid, or the error it gives. + pub fn add_solid(&mut self, solid: SolidFaces) -> Result, String> { + self.add(solid.faces?, solid.projection) + } + /// The shadow of the faces gathered, on the page, filled with the nonzero rule: `None` when /// there are none, when the first light lights nothing (Shading is off or its intensity is 0) /// or does not reach the plane (it is behind the object for a shadow behind it, or below the @@ -287,6 +299,56 @@ impl ShadowCaster { } } +/// A solid's faces before projection, kept by the build that drew it, for its shadow +/// ([`ShadowCaster::add_solid`]): the faces, or the error keeping them gave, and the projection the +/// solid was drawn with. +#[derive(Clone, Debug)] +pub struct SolidFaces { + faces: Result, String>, + projection: Option, +} + +/// Extrude & Bevel's solid ([`crate::extrude`]) and, from the same build, the faces +/// [`ShadowCaster::extrude`] adds for it. An error where [`crate::extrude`] gives one. +pub fn extrude_shadowed(path: &PathData, rule: FillRule, bounds: Rect, options: Extrude, view: View) -> Result<(Vec, SolidFaces), String> { + let (facets, faces, projection) = extrude_faces(path, rule, bounds, options, view, Keep::Both)?; + Ok((facets, SolidFaces { faces, projection })) +} + +/// Rotate's plane ([`crate::plane`]) and, from the same build, the face [`ShadowCaster::plane`] +/// adds for it. An error where [`crate::plane`] gives one. +pub fn plane_shadowed(path: &PathData, rule: FillRule, bounds: Rect, view: View) -> Result<(Vec, SolidFaces), String> { + let (facets, faces, projection) = plane_faces(path, rule, bounds, view, Keep::Both)?; + Ok((facets, SolidFaces { faces, projection })) +} + +/// Inflate's solids for several shapes of one object ([`crate::inflate_each`]) and, from the same +/// builds, the faces [`ShadowCaster::inflate`] adds for each, each solid built as the iterator +/// reaches it. An error where [`crate::inflate_each`] gives one. +pub fn inflate_shadowed( + shapes: &[(&PathData, FillRule)], + bounds: Rect, + options: Inflate, + view: View, +) -> impl Iterator, SolidFaces), String>> + use<> { + inflate_faces(shapes, bounds, options, view, Keep::Both).map(|r| r.map(|(facets, faces, projection)| (facets, SolidFaces { faces, projection }))) +} + +/// Revolve's surface ([`crate::revolve`]) and, from the same sweep, the faces +/// [`ShadowCaster::revolve`] adds for it with the nonzero fill rule. An error where +/// [`crate::revolve`] gives one. +pub fn revolve_shadowed(path: &PathData, bounds: Rect, options: Revolve) -> Result<(Vec, SolidFaces), String> { + let mut kept = vec![]; + let (faces, lost) = crate::revolve_sweep(path, FillRule::NonZero, bounds, options, true, Some(&mut kept))?; + let projection = Some(crate::revolve_projection(bounds, options.sanitized())); + Ok((faces, SolidFaces { faces: lost.map_or(Ok(kept), Err), projection })) +} + +/// [`revolve_shadowed`] with the faces as facets, as [`crate::revolve_facets`] gives them. +pub fn revolve_facets_shadowed(path: &PathData, bounds: Rect, options: Revolve) -> Result<(Vec, SolidFaces), String> { + revolve_shadowed(path, bounds, options).map(|(faces, kept)| (faces.into_iter().map(Facet::of_face).collect(), kept)) +} + /// Whether `area`, the signed area of a polygon with corners `points`, is within rounding of /// nothing for its size (the square of its bounds' diagonal), or not a number, so the polygon draws /// nothing. A long, narrow polygon keeps an area well above that. diff --git a/crates/three-d/src/shadow/tests.rs b/crates/three-d/src/shadow/tests.rs index 3fb3767177..1e3f5c437b 100644 --- a/crates/three-d/src/shadow/tests.rs +++ b/crates/three-d/src/shadow/tests.rs @@ -185,3 +185,276 @@ fn every_effect_casts_a_shadow() { // The surface turns about the square's left edge, reaching 100 to either side of it. assert!(b.x1 > 100.0 && b.x0 < 100.0 + 1e-6, "{b:?}"); } + +/// The faces `caster` gathered and the projection it keeps, every number to the bit. +fn gathered(caster: &ShadowCaster) -> String { + format!("{:?} {:?}", caster.faces, caster.projection) +} + +/// What a solid kept for its shadow casts ([`casts`]). +fn cast_from(solid: SolidFaces) -> Result<(String, Option, Option), String> { + let mut caster = ShadowCaster::new(); + caster.add_solid(solid)?; + Ok(casts(&caster)) +} + +/// The faces `caster` gathered, and the shadows they cast behind and below. +fn casts(caster: &ShadowCaster) -> (String, Option, Option) { + let below = Shadow { position: ShadowPosition::Below, distance: 0.3, ..Shadow::default() }; + (gathered(caster), caster.path(Shadow::default()), caster.path(below)) +} + +/// A star of `points` points about (100, 100), its edges curved, with a square hole. +fn star(points: usize) -> PathData { + let mut b = BezPath::new(); + for k in 0..2 * points { + let (s, c) = (k as f64 * std::f64::consts::PI / points as f64).sin_cos(); + let r = if k % 2 == 0 { 90.0 } else { 45.0 }; + let p = (100.0 + r * c, 100.0 + r * s); + if k == 0 { b.move_to(p) } else { b.curve_to((p.0 + 3.0, p.1), (p.0, p.1 + 3.0), p) } + } + b.close_path(); + rect(&mut b, 90.0, 90.0, 20.0, 20.0); + PathData::from_bezpath(&b) +} + +/// A closed rectangle from (`x`, `y`), `w` wide and `h` high. +fn rect(b: &mut BezPath, x: f64, y: f64, w: f64, h: f64) { + b.move_to((x, y)); + b.line_to((x + w, y)); + b.line_to((x + w, y + h)); + b.line_to((x, y + h)); + b.close_path(); +} + +/// The views the solids are compared in: straight on, turned, with perspective, and with colored +/// lights. +fn views() -> Vec { + let turned = View { rotation_x: -25.0, rotation_y: 35.0, rotation_z: 10.0, ..View::default() }; + vec![front(), turned, View { perspective: 60.0, ..turned }, View { light_color: [1.0, 0.5, 0.25], ..turned }] +} + +/// Extrude & Bevel built once for its facets and its shadow gives the facets [`crate::extrude`] +/// gives and casts what [`ShadowCaster::extrude`] casts, to the bit, errors included. +#[test] +fn an_extruded_solid_and_its_shadow_match_the_two_built_apart() { + use crate::{Bevel, BevelShape}; + let bevel = Bevel { shape: BevelShape::Rounded, width: 6.0, height: 5.0, ..Bevel::default() }; + let options = [ + Extrude::default(), + Extrude { depth: 0.0, ..Extrude::default() }, + Extrude { cap: false, ..Extrude::default() }, + Extrude { hidden: true, ..Extrude::default() }, + Extrude { twist: 90.0, taper: 0.6, ..Extrude::default() }, + Extrude { bevel: Some(bevel), ..Extrude::default() }, + Extrude { bevel: Some(Bevel { both_sides: true, inside: true, ..bevel }), twist: 45.0, ..Extrude::default() }, + ]; + let path = star(7); + let r = path.bounds().unwrap(); + for view in views() { + for o in options { + let (facets, faces) = extrude_shadowed(&path, FillRule::NonZero, r, o, view).unwrap(); + let apart = crate::extrude(&path, FillRule::NonZero, r, o, view).unwrap(); + assert_eq!(format!("{facets:?}"), format!("{apart:?}"), "{o:?} {view:?}"); + let mut caster = ShadowCaster::new(); + caster.extrude(&path, FillRule::NonZero, r, o, view).unwrap(); + assert!(!caster.is_empty()); + assert_eq!(cast_from(faces), Ok(casts(&caster)), "{o:?} {view:?}"); + } + } + let flat = Rect::new(0.0, 0.0, f64::INFINITY, 10.0); + let error = crate::extrude(&path, FillRule::NonZero, flat, Extrude::default(), front()).err(); + assert!(error.is_some()); + assert_eq!(extrude_shadowed(&path, FillRule::NonZero, flat, Extrude::default(), front()).err(), error); +} + +/// Rotate's plane built once for its facet and its shadow matches the two built apart. +#[test] +fn a_rotated_plane_and_its_shadow_match_the_two_built_apart() { + let path = star(5); + let r = path.bounds().unwrap(); + for view in views() { + for rule in [FillRule::NonZero, FillRule::EvenOdd] { + let (facets, faces) = plane_shadowed(&path, rule, r, view).unwrap(); + assert_eq!(format!("{facets:?}"), format!("{:?}", crate::plane(&path, rule, r, view).unwrap()), "{view:?}"); + let mut caster = ShadowCaster::new(); + caster.plane(&path, rule, r, view).unwrap(); + assert_eq!(cast_from(faces), Ok(casts(&caster)), "{view:?}"); + } + } +} + +/// Inflate's solids built once for their facets and shadows match the two built apart: several +/// puffs under one eye, both sides, open backs, and twisted sides cut finer than room is left for. +#[test] +fn inflated_solids_and_their_shadows_match_the_two_built_apart() { + let star = star(5); + let box_ = square(200.0, 20.0, 60.0); + let ring: Vec = (0..600) + .map(|k| { + let (s, c) = (k as f64 * std::f64::consts::TAU / 600.0).sin_cos(); + Point::new(100.0 + 90.0 * c, 100.0 + 90.0 * s) + }) + .collect(); + let ring = PathData::single(vectorcraft_geom::SubPath::polyline(&ring, true)); + let sets = [vec![(&star, FillRule::NonZero), (&box_, FillRule::NonZero), (&star, FillRule::EvenOdd)], vec![(&ring, FillRule::NonZero)]]; + let bounds = Rect::new(0.0, 0.0, 280.0, 200.0); + let options = [ + Inflate::default(), + Inflate { depth: 30.0, both_sides: true, ..Inflate::default() }, + Inflate { depth: 20.0, cap: false, volume: 80.0, ..Inflate::default() }, + Inflate { depth: 40.0, twist: 360.0, taper: 0.7, both_sides: true, ..Inflate::default() }, + // Thin and barely twisted: the star's sides want more pieces than room is left after its + // front and back, and the shadow, which keeps the faces turned away, has less room left. + Inflate { depth: 0.1, twist: 0.1, both_sides: true, ..Inflate::default() }, + ]; + for shapes in &sets { + for view in views() { + for o in options { + let built: Vec<_> = inflate_shadowed(shapes, bounds, o, view).collect(); + let facets: Vec<_> = crate::inflate_each(shapes, bounds, o, view).collect(); + let mut caster = ShadowCaster::new(); + let added = caster.inflate(shapes, &vec![true; shapes.len()], bounds, o, view); + assert!(added.iter().all(Result::is_ok)); + assert_eq!(built.len(), shapes.len()); + let mut one = ShadowCaster::new(); + for (b, f) in built.into_iter().zip(&facets) { + let ((facets, faces), f) = (b.unwrap(), f.as_ref().unwrap()); + assert_eq!(format!("{facets:?}"), format!("{f:?}"), "{o:?} {view:?}"); + one.add_solid(faces).unwrap(); + } + assert_eq!(casts(&one), casts(&caster), "{o:?} {view:?}"); + } + } + } +} + +/// Revolve's surface swept once for its faces and its shadow gives the faces [`crate::revolve`] +/// gives and casts what [`ShadowCaster::revolve`] casts, to the bit: an open profile with caps, +/// closed contours that cross (their walls cut where they do), a hole, partial sweeps, smooth and +/// flat shading, and the cut side that graphics take. +#[test] +fn a_revolved_surface_and_its_shadow_match_the_two_swept_apart() { + let mut open = BezPath::new(); + open.move_to((120.0, 0.0)); + open.curve_to((160.0, 20.0), (100.0, 60.0), (140.0, 90.0)); + open.line_to((125.0, 120.0)); + let mut crossing = BezPath::new(); + rect(&mut crossing, 110.0, 0.0, 60.0, 80.0); + rect(&mut crossing, 150.0, 40.0, 40.0, 80.0); + let mut holed = BezPath::new(); + holed.move_to((110.0, 0.0)); + holed.curve_to((200.0, 0.0), (200.0, 120.0), (110.0, 120.0)); + holed.close_path(); + rect(&mut holed, 130.0, 40.0, 20.0, 30.0); + let paths = [open, crossing, holed].map(|b| PathData::from_bezpath(&b)); + let turned = Revolve { rotation_x: -20.0, rotation_y: 30.0, ..Revolve::default() }; + let options = [ + Revolve::default(), + turned, + Revolve { angle: 200.0, perspective: 40.0, ..turned }, + Revolve { smooth_shading: false, segments: 12, ..turned }, + Revolve { cap_ends: false, offset: 15.0, ..turned }, + Revolve { map_surface: true, edge: crate::Edge::Right, ..turned }, + Revolve { map_surface: true, angle: 300.0, curve_samples: Some(5), ..turned }, + ]; + for path in &paths { + let bounds = path.bounds().unwrap(); + for o in options { + let (faces, kept) = revolve_shadowed(path, bounds, o).unwrap(); + assert_eq!(format!("{faces:?}"), format!("{:?}", crate::revolve(path, bounds, o).unwrap()), "{o:?}"); + let (facets, also) = revolve_facets_shadowed(path, bounds, o).unwrap(); + assert_eq!(format!("{facets:?}"), format!("{:?}", crate::revolve_facets(path, bounds, o).unwrap()), "{o:?}"); + assert_eq!(cast_from(also), cast_from(kept.clone()), "{o:?}"); + let mut caster = ShadowCaster::new(); + caster.revolve(path, FillRule::NonZero, bounds, o).unwrap(); + assert!(!caster.is_empty()); + assert_eq!(cast_from(kept), Ok(casts(&caster)), "{o:?}"); + } + } +} + +/// A surface whose shadow is past the limit on the profile's points (its walls cut where they +/// cross another contour) still draws every face, and its shadow gives the error the shadow swept +/// alone gives. +#[test] +fn a_surface_whose_shadow_is_too_complex_still_draws() { + let mut b = BezPath::new(); + b.move_to((110.0, 0.0)); + for i in 1..6000 { + b.line_to((110.0 + f64::from(i) * 0.02, if i % 2 == 0 { 0.0 } else { 10.0 })); + } + b.line_to((110.0, 20.0)); + b.close_path(); + rect(&mut b, 100.0, 4.0, 140.0, 2.0); + let path = PathData::from_bezpath(&b); + let bounds = path.bounds().unwrap(); + let o = Revolve { segments: 4, smooth_shading: false, ..Revolve::default() }; + let (faces, kept) = revolve_shadowed(&path, bounds, o).unwrap(); + let drawn = crate::revolve(&path, bounds, o).unwrap(); + assert!(!drawn.is_empty()); + assert!(faces == drawn); + let alone = ShadowCaster::new().revolve(&path, FillRule::NonZero, bounds, o).unwrap_err(); + assert!(alone.contains("too complex"), "{alone}"); + assert_eq!(cast_from(kept).unwrap_err(), alone); +} + +/// One build gives the facets and the faces of the shadow: each solid is built once. +#[test] +fn a_solid_and_its_shadow_are_built_once() { + let path = star(5); + let r = path.bounds().unwrap(); + let count = |n: &'static std::thread::LocalKey>| n.with(std::cell::Cell::get); + let start = count(&crate::solid::EXTRUDED); + let (facets, faces) = extrude_shadowed(&path, FillRule::NonZero, r, Extrude::default(), front()).unwrap(); + assert!(!facets.is_empty() && cast_from(faces).is_ok_and(|c| c.1.is_some())); + assert_eq!(count(&crate::solid::EXTRUDED), start + 1); + let start = count(&crate::solid::PLANES); + let (facets, faces) = plane_shadowed(&path, FillRule::NonZero, r, front()).unwrap(); + assert!(!facets.is_empty() && cast_from(faces).is_ok_and(|c| c.1.is_some())); + assert_eq!(count(&crate::solid::PLANES), start + 1); + let start = count(&crate::solid::INFLATED); + let box_ = square(200.0, 20.0, 60.0); + let shapes = [(&path, FillRule::NonZero), (&box_, FillRule::NonZero)]; + for solid in inflate_shadowed(&shapes, Rect::new(0.0, 0.0, 280.0, 200.0), Inflate::default(), front()) { + let (facets, faces) = solid.unwrap(); + assert!(!facets.is_empty() && cast_from(faces).is_ok_and(|c| c.1.is_some())); + } + assert_eq!(count(&crate::solid::INFLATED), start + 2); + let start = count(&crate::REVOLVED); + let (drawn, faces) = revolve_shadowed(&path, r, Revolve::default()).unwrap(); + assert!(!drawn.is_empty() && cast_from(faces).is_ok_and(|c| c.1.is_some())); + assert_eq!(count(&crate::REVOLVED), start + 1); +} + +/// An Inflate shape that casts nothing still places the eye with its puff, but its solid is not +/// built (nor, with no volume, its puff solved); the shapes that cast keep the very faces and +/// projection they have when every shape casts. +#[test] +fn an_inflate_shape_that_casts_nothing_builds_no_solid() { + let (a, b) = (square(100.0, 100.0, 100.0), square(150.0, 150.0, 30.0)); + let shapes = [(&a, FillRule::NonZero), (&b, FillRule::NonZero)]; + let bounds = Rect::new(100.0, 100.0, 200.0, 200.0); + let view = View { perspective: 60.0, rotation_y: 30.0, ..front() }; + let built = || crate::solid::INFLATED.with(std::cell::Cell::get); + let puffed = || crate::solid::PUFFED.with(std::cell::Cell::get); + for o in [Inflate::default(), Inflate { volume: 0.0, depth: 20.0, ..Inflate::default() }] { + let mut all = ShadowCaster::new(); + let every = all.inflate(&shapes, &[true, true], bounds, o, view); + let (start, solved) = (built(), puffed()); + let mut some = ShadowCaster::new(); + let kept = some.inflate(&shapes, &[false, true], bounds, o, view); + assert_eq!(built(), start + 1, "{o:?}: only the casting shape's solid is built"); + if o.volume == 0.0 { + assert_eq!(puffed(), solved + 1, "{o:?}: only the casting shape's puff is solved"); + } + let (Ok(first), Ok(second)) = (&every[0], &every[1]) else { panic!("{every:?}") }; + assert!(!first.is_empty() && !second.is_empty()); + assert_eq!(kept, vec![Ok(0..0), Ok(0..second.len())]); + assert_eq!(format!("{:?}", some.faces), format!("{:?}", &all.faces[second.clone()])); + assert_eq!(some.projection, all.projection); + let mut none = ShadowCaster::new(); + assert_eq!(none.inflate(&shapes, &[false, false], bounds, o, view), vec![Ok(0..0), Ok(0..0)]); + assert!(none.is_empty() && none.projection.is_none()); + } +} diff --git a/crates/three-d/src/solid.rs b/crates/three-d/src/solid.rs index 55d270f97d..18ef7d6d1b 100644 --- a/crates/three-d/src/solid.rs +++ b/crates/three-d/src/solid.rs @@ -23,15 +23,17 @@ mod rings; #[cfg(test)] pub(crate) use build::EXTRUDED; #[cfg(test)] +pub(crate) use build::PLANES; +#[cfg(test)] use build::{Camera, cuts, edge_distance, newell, section}; pub(crate) use build::{Face3, Keep, extrude_faces, plane_faces}; pub use build::{extrude, plane}; pub use face_map::{FaceMap, extrude_face_map, plane_face_map}; #[cfg(test)] use inflate::GRID_WORK; -#[cfg(test)] -pub(crate) use inflate::INFLATED; pub(crate) use inflate::inflate_faces; +#[cfg(test)] +pub(crate) use inflate::{INFLATED, PUFFED, SOLVE_FIRST}; pub use inflate::{inflate, inflate_each, inflate_together}; #[cfg(test)] use membrane::{Edges, GRID_BUDGET, MAX_EDGE_ENTRIES, MAX_GRID_WORK, Membrane, cell_triangles}; diff --git a/crates/three-d/src/solid/build.rs b/crates/three-d/src/solid/build.rs index 2aa218e558..d734161343 100644 --- a/crates/three-d/src/solid/build.rs +++ b/crates/three-d/src/solid/build.rs @@ -3,7 +3,7 @@ use vectorcraft_geom::kurbo::ParamCurveDeriv; use super::outline::{self, Along, Budget, CURVE_TOLERANCE}; use super::rings::{ CURVE_PIECES, MAX_PIECES, MAX_PLANE_POINTS, MAX_SOLID_POINTS, Ring, Span, TOO_COMPLEX_SURFACE, curve_pieces, inset, left, signed_area, - solid_rings_traced, + solid_rings_traced, square_corners, }; use super::{ Bevel, DepthPlane, Extrude, Facet, FillRule, MAX_FACES, MAX_SOLID_FACES, ParamCurve, PathData, PlanarFace, Point, Rect, Revolve, V3, View, @@ -458,10 +458,15 @@ pub(super) fn check_bounds(b: Rect) -> Result<(), String> { } /// The art's outward direction at edge `i` of `ring` (before rotation), tilted towards the face -/// it borders by `z` (+1 front, -1 back, 0 a side wall). +/// it borders by `z` (+1 front, -1 back, 0 a side wall). An edge of no length (a corner cut +/// square, see [`square_corners`]) faces out between the edges on either side of it. pub(super) fn outward(ring: &[Point], i: usize, z: f64) -> V3 { let n = ring.len(); - let (lx, ly) = left(ring[i], ring[(i + 1) % n]); + let (mut lx, mut ly) = left(ring[i], ring[(i + 1) % n]); + if lx == 0.0 && ly == 0.0 && n > 2 { + let (a, b) = (left(ring[(i + n - 1) % n], ring[i]), left(ring[(i + 1) % n], ring[(i + 2) % n])); + (lx, ly) = (a.0 + b.0, a.1 + b.1); + } V3(-lx, -ly, z) } @@ -607,7 +612,10 @@ pub(crate) fn extrude_faces(path: &PathData, rule: FillRule, bounds: Rect, optio let (bands, caps) = (steps.len().saturating_sub(1), if o.cap { 2 } else { 0 }); let size = bounds.width().max(bounds.height()); let most = curve_pieces(path, size, bands, caps)?; - let traced = solid_rings_traced(path, rule, size, MAX_SOLID_POINTS, most)?; + // Every inset of one extrusion goes the same way: into the shape for a bevel inside, out of it + // for one outside. The corners that way opens are cut square past the miter limit. + let side = steps.iter().map(|s| s.inset).find(|w| *w != 0.0).unwrap_or(0.0); + let traced: Vec = solid_rings_traced(path, rule, size, MAX_SOLID_POINTS, most)?.iter().map(|r| square_corners(r, side)).collect(); let rings: Vec<&[Point]> = traced.iter().map(|r| r.points.as_slice()).collect(); let edges = rings.iter().map(|r| r.len()).fold(0usize, usize::saturating_add); if edges.saturating_mul(bands).saturating_add(caps) > MAX_SOLID_FACES { @@ -697,6 +705,13 @@ pub(crate) fn extrude_faces(path: &PathData, rule: FillRule, bounds: Rect, optio Ok(b.finish()) } +#[cfg(test)] +thread_local! { + /// How many Rotate planes (and Extrude & Bevel solids with no depth) this thread has built, for + /// the tests. + pub(crate) static PLANES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// Rotate: the flat art turned in 3D about the centre of `bounds` (which may be larger than the /// shape's own, so that every part of one object turns about the same point). pub fn plane(path: &PathData, rule: FillRule, bounds: Rect, view: View) -> Result, String> { @@ -705,6 +720,8 @@ pub fn plane(path: &PathData, rule: FillRule, bounds: Rect, view: View) -> Resul /// [`plane`], keeping its facet, its face before projection, or both, as `keep` asks. pub(crate) fn plane_faces(path: &PathData, rule: FillRule, bounds: Rect, view: View, keep: Keep) -> Result { + #[cfg(test)] + PLANES.with(|n| n.set(n.get() + 1)); check_bounds(bounds)?; let rings = solid_rings_traced(path, rule, bounds.width().max(bounds.height()), MAX_PLANE_POINTS, CURVE_PIECES)?; let camera = Camera::new(view, bounds, 0.0); diff --git a/crates/three-d/src/solid/inflate.rs b/crates/three-d/src/solid/inflate.rs index 677e9cc8bc..5edf57a894 100644 --- a/crates/three-d/src/solid/inflate.rs +++ b/crates/three-d/src/solid/inflate.rs @@ -21,12 +21,35 @@ struct Puff { height: f64, } -/// The rings of `path` and its membrane on the grid of `bounds`; `None` for a shape with no area. -fn puff(path: &PathData, rule: FillRule, bounds: Rect, o: &Inflate) -> Result, String> { +/// The pieces each curve of `path` is sampled in for Inflate's solid ([`curve_pieces`]); an error +/// when its outline does not fit the solid's limits. +fn outline_pieces(path: &PathData, bounds: Rect, o: &Inflate) -> Result { // The sides take one face for each edge of the outline in each slice; the grid's faces are // counted as they are built. + curve_pieces(path, bounds.width().max(bounds.height()), if o.depth > 0.0 { slices(o) } else { 0 }, 0) +} + +/// Whether `path` has few enough anchors that [`curve_pieces`] might take it: fewer than +/// [`MAX_SOLID_POINTS`] contours, and at most three times as many anchors (a contour of one anchor +/// adds one, and every other takes at most two anchors for each segment it adds). Counts the +/// contours' anchors without reading them. +pub(super) fn might_fit(path: &PathData) -> bool { + let mut anchors = 0usize; + for (contours, sp) in path.subpaths.iter().enumerate() { + anchors = anchors.saturating_add(sp.anchors.len()); + if contours >= MAX_SOLID_POINTS || anchors > MAX_SOLID_POINTS.saturating_mul(3) { + return false; + } + } + true +} + +/// The rings of `path` and its membrane on the grid of `bounds`; `None` for a shape with no area. +fn puff(path: &PathData, rule: FillRule, bounds: Rect, o: &Inflate) -> Result, String> { + #[cfg(test)] + PUFFED.with(|n| n.set(n.get() + 1)); let size = bounds.width().max(bounds.height()); - let most = curve_pieces(path, size, if o.depth > 0.0 { slices(o) } else { 0 }, 0)?; + let most = outline_pieces(path, bounds, o)?; let rings = solid_rings(path, rule, size, MAX_SOLID_POINTS, most)?; if rings.is_empty() { return Ok(None); @@ -66,7 +89,7 @@ pub fn inflate_together(shapes: &[(&PathData, FillRule)], bounds: Rect, options: } /// [`inflate_together`], each solid built only as the iterator reaches it: a caller that stops early -/// builds none of the solids after. +/// builds none of the solids after (and with no volume, solves none of their puffs). pub fn inflate_each( shapes: &[(&PathData, FillRule)], bounds: Rect, @@ -77,28 +100,98 @@ pub fn inflate_each( } /// [`inflate_together`], keeping each solid's facets, its faces before projection, or both, as -/// `keep` asks. Every shape's membrane is solved at once (the eye depends on the highest puff); -/// each solid is built as the iterator reaches it. -pub(crate) fn inflate_faces( - shapes: &[(&PathData, FillRule)], - bounds: Rect, - options: Inflate, - view: View, - keep: Keep, -) -> impl Iterator> + use<> { +/// `keep` asks. Every shape's membrane is solved at once (the eye depends on the highest puff), +/// except with no volume: nothing puffs then, and each shape's membrane is solved when its solid +/// is taken. Each solid is built as the iterator reaches it. +pub(crate) fn inflate_faces(shapes: &[(&PathData, FillRule)], bounds: Rect, options: Inflate, view: View, keep: Keep) -> Solids { let o = options.sanitized(); + let later = o.volume == 0.0; + #[cfg(test)] + let later = later && !SOLVE_FIRST.with(std::cell::Cell::get); + if later { + // A shape is copied to be solved later only when its anchors are few enough for the + // solid's point limit; a larger one is refused now, with the error its puff gives. + let shapes: Vec> = shapes + .iter() + .map(|(path, rule)| { + check_bounds(bounds)?; + if !might_fit(path) { + outline_pieces(path, bounds, &o)?; + } + Ok(((*path).clone(), *rule)) + }) + .collect(); + return Solids { pending: Pending::Later(shapes.into_iter()), bounds, o, view, reach: 0.0, keep }; + } let puffs: Vec, String>> = shapes.iter().map(|(path, rule)| check_bounds(bounds).and_then(|()| puff(path, *rule, bounds, &o))).collect(); let reach = puffs.iter().flatten().flatten().map(|p| p.height).fold(0.0, f64::max); - puffs.into_iter().map(move |p| match p { - Ok(Some(p)) => inflated(p, bounds, o, view, reach, keep), - Ok(None) => Ok((vec![], Ok(vec![]), None)), - Err(e) => Err(e), - }) + Solids { pending: Pending::Solved(puffs.into_iter()), bounds, o, view, reach, keep } +} + +/// The shapes' puffs still to take: every one solved when the shapes were laid out, or each +/// shape's path and fill rule (or the error its bounds or outline already gives), its puff solved +/// when its solid is taken. +enum Pending { + Solved(std::vec::IntoIter, String>>), + Later(std::vec::IntoIter>), +} + +/// The solids of [`inflate_faces`], one result for each shape in order, each built as it is taken. +pub(crate) struct Solids { + pending: Pending, + bounds: Rect, + o: Inflate, + view: View, + /// The highest puff of the shapes drawn together. + reach: f64, + keep: Keep, +} + +impl Solids { + /// Pass over the next shape without building its solid, or solving its puff if that waits. + pub(crate) fn pass(&mut self) { + match &mut self.pending { + Pending::Solved(puffs) => { + puffs.next(); + } + Pending::Later(shapes) => { + shapes.next(); + } + } + } +} + +impl Iterator for Solids { + type Item = Result; + + fn next(&mut self) -> Option { + let p = match &mut self.pending { + Pending::Solved(puffs) => puffs.next()?, + Pending::Later(shapes) => shapes.next()?.and_then(|(path, rule)| puff(&path, rule, self.bounds, &self.o)), + }; + Some(match p { + Ok(Some(p)) => inflated(p, self.bounds, self.o, self.view, self.reach, self.keep), + Ok(None) => Ok((vec![], Ok(vec![]), None)), + Err(e) => Err(e), + }) + } + + fn size_hint(&self) -> (usize, Option) { + match &self.pending { + Pending::Solved(puffs) => puffs.size_hint(), + Pending::Later(shapes) => shapes.size_hint(), + } + } } #[cfg(test)] thread_local! { + /// How many puffs this thread has solved, for the tests. + pub(crate) static PUFFED: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Solve every shape's puff before the first solid is taken even with no volume, as with + /// volume, for the tests that compare the two. + pub(crate) static SOLVE_FIRST: std::cell::Cell = const { std::cell::Cell::new(false) }; /// How many inflated solids this thread has built, for the tests. pub(crate) static INFLATED: std::cell::Cell = const { std::cell::Cell::new(0) }; /// The grid work of the last solid this thread inflated in full, for the tests. diff --git a/crates/three-d/src/solid/outline.rs b/crates/three-d/src/solid/outline.rs index 07fb0ce58b..93d9d70340 100644 --- a/crates/three-d/src/solid/outline.rs +++ b/crates/three-d/src/solid/outline.rs @@ -123,7 +123,8 @@ fn contour(path: &mut BezPath, ring: &Ring, points: &[Point], step: &Along, budg while i < n { let end = |k: usize| points.get((k + 1) % n).copied().unwrap_or(first); let Some(span) = ring.spans.get(i).copied().flatten() else { - if i + 1 < n { + // A corner cut square (see `square_corners`) whose two copies did not move apart. + if i + 1 < n && points.get(i).copied() != Some(end(i)) { path.line_to(end(i)); } i += 1; diff --git a/crates/three-d/src/solid/rings.rs b/crates/three-d/src/solid/rings.rs index 80dc66407c..882bd245af 100644 --- a/crates/three-d/src/solid/rings.rs +++ b/crates/three-d/src/solid/rings.rs @@ -16,6 +16,10 @@ pub(super) const CURVE_PIECES: u32 = 32; /// for fewer takes fewer. pub(super) const MIN_CURVE_PIECES: u32 = 4; +/// How far an inset corner's miter reaches at most, as a multiple of the inset. [`square_corners`] +/// cuts a corner whose miter would reach further square across instead. +const MITER_LIMIT: f64 = 4.0; + const TOO_COMPLEX_SHAPE: &str = "The shape is too complex for a 3D effect"; /// The error a solid past its limits returns, and a 3D effect whose solids together pass /// [`crate::MAX_OBJECT_FACES`]. @@ -472,8 +476,10 @@ pub(super) fn left(a: Point, b: Point) -> (f64, f64) { } /// `ring` moved `w` points towards its filled side (negative: away from it), each corner along -/// its bisector, its mitre limited to four times `w` so sharp corners don't shoot off. Each point -/// stays the partner of its source point, so rings at different insets join face to face. +/// its bisector, its miter limited to [`MITER_LIMIT`] times `w` so sharp corners don't shoot off. +/// A point given twice (a corner [`square_corners`] cut) moves each copy along its one edge's +/// normal. Each point stays the partner of its source point, so rings at different insets join +/// face to face. pub(super) fn inset(ring: &[Point], w: f64) -> Vec { if w == 0.0 { return ring.to_vec(); @@ -486,6 +492,12 @@ pub(super) fn inset(ring: &[Point], w: f64) -> Vec { let next = ring[(i + 1) % n]; let (ax, ay) = left(prev, p); let (bx, by) = left(p, next); + if ax == 0.0 && ay == 0.0 { + return Point::new(p.x + bx * w, p.y + by * w); + } + if bx == 0.0 && by == 0.0 { + return Point::new(p.x + ax * w, p.y + ay * w); + } let (mut mx, mut my) = (ax + bx, ay + by); let ml = mx.hypot(my); if ml < 1e-9 { @@ -493,8 +505,43 @@ pub(super) fn inset(ring: &[Point], w: f64) -> Vec { } else { (mx, my) = (mx / ml, my / ml); } - let cos = (mx * ax + my * ay).max(0.25); + let cos = (mx * ax + my * ay).max(1.0 / MITER_LIMIT); Point::new(p.x + mx * w / cos, p.y + my * w / cos) }) .collect() } + +/// `ring` with each corner whose miter an inset towards `side` (positive: the filled side, +/// negative: away from it) would reach past [`MITER_LIMIT`] given twice, joined by an edge of no +/// length that follows no curve. [`inset`] moves the two copies apart along their own edges' +/// normals, so the inset ring cuts the corner square, as a bevel join does, instead of running out +/// to a point along the bisector. Corners on the other side of the turn, whose inset edges meet +/// before the corner, keep one point. +pub(super) fn square_corners(ring: &Ring, side: f64) -> Ring { + let n = ring.points.len(); + if side == 0.0 || n < 3 || ring.spans.len() != n { + return ring.clone(); + } + let mut out = Ring { points: Vec::with_capacity(n), spans: Vec::with_capacity(n) }; + for (i, (&p, span)) in ring.points.iter().zip(&ring.spans).enumerate() { + let prev = ring.points[(i + n - 1) % n]; + let next = ring.points[(i + 1) % n]; + let (a, b) = (left(prev, p), left(p, next)); + let (mx, my) = (a.0 + b.0, a.1 + b.1); + let ml = mx.hypot(my); + // The cosine of the half angle between the bisector and each edge's normal: the miter + // reaches 1 / cos times the inset. + let cos = if ml < 1e-9 { 0.0 } else { (mx * a.0 + my * a.1) / ml }; + // Which way the outline turns at `p`: an inset towards `side` opens the corner when the + // turn is against it. + let turn = (p - prev).cross(next - p); + let edges = (a.0 != 0.0 || a.1 != 0.0) && (b.0 != 0.0 || b.1 != 0.0); + out.points.push(p); + if edges && cos < 1.0 / MITER_LIMIT && turn * side < 0.0 { + out.spans.push(None); + out.points.push(p); + } + out.spans.push(*span); + } + out +} diff --git a/crates/three-d/src/solid/tests.rs b/crates/three-d/src/solid/tests.rs index 335f434419..a75821e696 100644 --- a/crates/three-d/src/solid/tests.rs +++ b/crates/three-d/src/solid/tests.rs @@ -255,6 +255,78 @@ fn a_bevel_inside_shrinks_the_cap_and_outside_grows_the_walls() { assert!(inside.iter().any(|f| !close(f.brightness, inside[inside.len() - 1].brightness, 1e-3))); } +/// A bevel past a sharp corner is cut square, as a bevel join cuts a stroke, instead of running +/// out to a spike along the corner's bisector: seen straight on, no point of the solid lies further +/// from the art than the miters of its corners of about 90° (14.6 pt for a 10 pt bevel), where the +/// sharp corner's spike reached 40 pt. The bevel opens the corner of a thin spike (with its +/// neighbor in the same compound path) when it is outside, and of a narrow notch when it is inside; +/// the other two cases, where the inset edges meet, keep their limited miters and are checked too. +#[test] +fn a_bevel_cuts_sharp_corners_square() { + let poly = |pts: &[(f64, f64)]| { + let mut b = BezPath::new(); + b.move_to(pts[0]); + pts[1..].iter().for_each(|p| b.line_to(*p)); + b.close_path(); + b + }; + let spike = [(50.0, 0.0), (56.0, 100.0), (44.0, 100.0)]; + let block = [(80.0, 40.0), (120.0, 40.0), (120.0, 100.0), (80.0, 100.0)]; + let notched = [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (52.0, 100.0), (50.0, 20.0), (48.0, 100.0), (0.0, 100.0)]; + let mut both = poly(&spike); + both.extend(poly(&block).elements().iter().copied()); + let bevel = Bevel { width: 10.0, height: 10.0, ..Bevel::default() }; + let mut far_cases = vec![]; + for (name, art, outline) in [("spike", both, vec![spike.to_vec(), block.to_vec()]), ("notch", poly(¬ched), vec![notched.to_vec()])] { + let (p, b) = shape(&art); + let outline: Vec> = outline.iter().map(|r| r.iter().map(|q| Point::new(q.0, q.1)).collect()).collect(); + for inside in [false, true] { + for shape in [BevelShape::Classic, BevelShape::Rounded] { + let o = Extrude { bevel: Some(Bevel { inside, shape, ..bevel }), ..Extrude::default() }; + let f = extrude(&p, FillRule::NonZero, b, o, front()).unwrap(); + let far = f.iter().flat_map(|f| f.contours.iter().flatten()).map(|q| edge_distance(&outline, *q)).fold(0.0, f64::max); + if far > 15.0 { + far_cases.push(format!("{name} inside {inside} {shape:?}: a point {far} pt from the art")); + } + assert!(f.iter().all(|f| f.normal.iter().all(|v| v.is_finite())), "{name} inside {inside} {shape:?}"); + } + // Turned, every face still has a normal it can be lit and sorted by. + let o = Extrude { bevel: Some(Bevel { inside, ..bevel }), ..Extrude::default() }; + let f = extrude(&p, FillRule::NonZero, b, o, View::default()).unwrap(); + assert!(f.iter().all(|f| f.normal.iter().all(|v| v.is_finite()) && f.brightness.is_finite()), "{name} inside {inside}"); + } + } + assert!(far_cases.is_empty(), "{far_cases:#?}"); +} + +/// With the bevel outside, the cap is the outline itself, so a corner cut square keeps its two +/// points together there: the cap's outline draws no straight segment of no length at that corner. +#[test] +fn a_cap_draws_no_empty_segment_at_a_corner_cut_square() { + use vectorcraft_geom::kurbo::PathEl; + let mut art = BezPath::new(); + art.move_to((50.0, 0.0)); + art.line_to((56.0, 100.0)); + art.curve_to((56.0, 120.0), (44.0, 120.0), (44.0, 100.0)); + art.close_path(); + let (p, b) = shape(&art); + let o = Extrude { bevel: Some(Bevel { width: 10.0, height: 10.0, ..Bevel::default() }), ..Extrude::default() }; + let f = extrude(&p, FillRule::NonZero, b, o, front()).unwrap(); + let cap = f.iter().find(|f| f.depth == f64::MAX && f.outline.is_some()).unwrap(); + let mut at = None; + for el in cap.path().to_bezpath().elements() { + match *el { + PathEl::MoveTo(q) => at = Some(q), + PathEl::LineTo(q) => { + assert_ne!(at, Some(q), "a segment of no length at {q:?}"); + at = Some(q); + } + PathEl::QuadTo(_, q) | PathEl::CurveTo(_, _, q) => at = Some(q), + PathEl::ClosePath => {} + } + } +} + #[test] fn bevel_shapes_repeats_and_both_sides_change_the_surface() { let (p, b) = shape(&square(0.0, 0.0, 100.0)); @@ -1030,6 +1102,105 @@ fn a_flat_twisted_inflate_matches_the_extrusion() { } } +/// With no volume nothing puffs, so each shape's membrane is solved only when its solid is taken: +/// a caller that stops early (past the object's face limit) solves none after. With volume, the +/// eye waits on the highest puff, so every membrane is solved first. +#[test] +fn a_flat_inflate_solves_each_puff_as_its_solid_is_taken() { + let shapes: Vec = (0..3).map(|i| shape(&square(120.0 * i as f64, 0.0, 100.0)).0).collect(); + let shapes: Vec<(&PathData, FillRule)> = shapes.iter().map(|p| (p, FillRule::NonZero)).collect(); + let b = Rect::new(0.0, 0.0, 340.0, 100.0); + let puffed = || PUFFED.with(std::cell::Cell::get); + let start = puffed(); + let mut each = inflate_each(&shapes, b, Inflate { depth: 20.0, volume: 0.0, ..Inflate::default() }, front()); + assert_eq!(puffed(), start, "no puff is solved before the first solid is taken"); + assert!(each.next().is_some_and(|f| f.is_ok_and(|f| !f.is_empty()))); + assert_eq!(puffed(), start + 1, "the later puffs wait until their solids are taken"); + drop(each); + assert_eq!(puffed(), start + 1); + let start = puffed(); + let each = inflate_each(&shapes, b, Inflate { depth: 20.0, ..Inflate::default() }, front()); + assert_eq!(puffed(), start + 3, "with volume, every puff places the eye"); + assert_eq!(each.count(), 3); +} + +/// With no volume, solving each puff as its solid is taken gives the very solids that solving +/// every puff first gives: their facets, their faces before projection and their projection, bit +/// for bit, with an empty shape and one that cannot be inflated among them. +#[test] +fn a_flat_inflate_solved_as_taken_matches_one_solved_first() { + let mut frame = square(-10.0, -10.0, 260.0); + frame.extend(square(-8.0, -8.0, 256.0)); + let mut circle = BezPath::new(); + circle.extend(vectorcraft_geom::kurbo::Shape::path_elements(&vectorcraft_geom::kurbo::Circle::new((180.0, 60.0), 50.0), 0.01)); + let mut bad = vectorcraft_geom::SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0)], true); + bad.anchors[1].h_out = Point::new(f64::NAN, 0.0); + let paths = [shape(&square(0.0, 0.0, 100.0)).0, shape(&frame).0, PathData::new(vec![]), PathData::new(vec![bad]), shape(&circle).0]; + let shapes: Vec<(&PathData, FillRule)> = paths.iter().map(|p| (p, FillRule::EvenOdd)).collect(); + let b = Rect::new(-10.0, -10.0, 250.0, 250.0); + let turned = View { rotation_x: -20.0, rotation_y: 30.0, ..front() }; + let options = [ + Inflate { volume: 0.0, ..Inflate::default() }, + Inflate { volume: 0.0, depth: 40.0, twist: 90.0, taper: 0.5, ..Inflate::default() }, + Inflate { volume: 0.0, depth: 10.0, both_sides: true, cap: false, ..Inflate::default() }, + ]; + for view in [front(), turned, View { perspective: 60.0, ..turned }, View { perspective: 100.0, rotation_y: 150.0, ..turned }] { + for o in options { + for (keep, facets, mesh) in [(build::Keep::Facets, true, false), (build::Keep::Faces, false, true), (build::Keep::Both, true, true)] { + let solids = |first: bool| { + SOLVE_FIRST.with(|s| s.set(first)); + let out: Vec> = inflate_faces(&shapes, b, o, view, keep).collect(); + SOLVE_FIRST.with(|s| s.set(false)); + out + }; + let (taken, first) = (solids(false), solids(true)); + assert_eq!(taken.len(), 5); + // The solid keeps its facets, its faces before projection, or both, as asked. + let built = |r: &Result| { + r.as_ref().is_ok_and(|(f, m, _)| (!facets || !f.is_empty()) && (!mesh || m.as_ref().is_ok_and(|m| !m.is_empty()))) + }; + assert!(built(&taken[0]) && built(&taken[1]) && built(&taken[4]), "{o:?} {view:?} facets {facets} mesh {mesh}"); + assert!( + taken[2].as_ref().is_ok_and(|(f, m, p)| f.is_empty() && m.as_ref().is_ok_and(Vec::is_empty) && p.is_none()) && taken[3].is_err() + ); + assert_eq!(format!("{taken:?}"), format!("{first:?}"), "{o:?} {view:?} facets {facets} mesh {mesh}"); + } + } + } +} + +/// With no volume, a shape with too many anchors or contours for the solid is refused before it +/// is kept for later, with the error that solving every puff first gives it. +#[test] +fn a_flat_inflate_refuses_a_shape_past_the_point_limit_as_one_solved_first() { + use super::inflate::might_fit; + let many = MAX_SOLID_POINTS * 3 + 10; + let anchors: Vec = (0..many).map(|i| Point::new((i % 200) as f64, (i / 200) as f64 / 10.0)).collect(); + let long = PathData::new(vec![vectorcraft_geom::SubPath::polyline(&anchors, true)]); + let mut nan = anchors.clone(); + if let Some(last) = nan.last_mut() { + *last = Point::new(f64::NAN, 0.0); + } + let invalid = PathData::new(vec![vectorcraft_geom::SubPath::polyline(&nan, true)]); + let dots = PathData::new((0..=MAX_SOLID_POINTS).map(|i| vectorcraft_geom::SubPath::polyline(&[Point::new(i as f64, 0.0)], false)).collect()); + let square = shape(&square(0.0, 0.0, 100.0)).0; + assert!(might_fit(&square) && !might_fit(&long) && !might_fit(&invalid) && !might_fit(&dots)); + let paths = [square, long, invalid, dots]; + let shapes: Vec<(&PathData, FillRule)> = paths.iter().map(|p| (p, FillRule::EvenOdd)).collect(); + let b = Rect::new(-10.0, -10.0, 250.0, 250.0); + let o = Inflate { volume: 0.0, ..Inflate::default() }; + let solids = |first: bool| { + SOLVE_FIRST.with(|s| s.set(first)); + let out: Vec> = inflate_faces(&shapes, b, o, front(), build::Keep::Facets).collect(); + SOLVE_FIRST.with(|s| s.set(false)); + out + }; + let (taken, first) = (solids(false), solids(true)); + assert!(taken[0].as_ref().is_ok_and(|(f, ..)| !f.is_empty())); + assert!(taken[1..].iter().all(Result::is_err), "{:?}", taken[1..].iter().map(|r| r.as_ref().err()).collect::>()); + assert_eq!(format!("{taken:?}"), format!("{first:?}")); +} + /// #1724: under the nonzero rule a contour inside another that runs the same way cuts no hole /// (the middle is filled, as the art is drawn); one running the other way does, and so does /// either under the even-odd rule. diff --git a/crates/tools/Cargo.toml b/crates/tools/Cargo.toml index 042a6f5174..269b7365d1 100644 --- a/crates/tools/Cargo.toml +++ b/crates/tools/Cargo.toml @@ -24,3 +24,5 @@ serde_json = { workspace = true } image = { workspace = true } # The tests lay type out in the bundled fonts (the workspace leaves turning them on to the engine). vectorcraft-text = { workspace = true, features = ["test-fonts", "bundled-fonts"] } +# How many times a path is flattened. +vectorcraft-doc = { workspace = true, features = ["spine-count"] } diff --git a/crates/tools/src/addons/corner_tool.rs b/crates/tools/src/addons/corner_tool.rs index 177926837e..470795579e 100644 --- a/crates/tools/src/addons/corner_tool.rs +++ b/crates/tools/src/addons/corner_tool.rs @@ -311,6 +311,7 @@ impl Tool for CornerTool { None => vec![], } } + PointerKind::TripleClick => vec![], } } diff --git a/crates/tools/src/addons/enclosing_lasso.rs b/crates/tools/src/addons/enclosing_lasso.rs index 9b92f0833d..0f674aead9 100644 --- a/crates/tools/src/addons/enclosing_lasso.rs +++ b/crates/tools/src/addons/enclosing_lasso.rs @@ -134,7 +134,7 @@ impl Tool for EnclosingLassoTool { let symbols = cx.doc.symbol_boxes(); let region = (points.len() >= 3).then(|| Region::new(polygon(&points, true))).flatten(); let mut ids = if let Some(region) = region { - enclosure_candidates(cx.doc, region.path.bounding_box(), cx.isolation) + enclosure_candidates(cx.doc, region.path.bounding_box(), cx.isolation, cx.outline) .into_iter() .filter(|id| cx.doc.node(*id).is_some_and(|n| node_inside(n, &symbols, ®ion))) .collect() diff --git a/crates/tools/src/addons/enclosing_lasso/tests.rs b/crates/tools/src/addons/enclosing_lasso/tests.rs index 836e640306..a8ba79aac7 100644 --- a/crates/tools/src/addons/enclosing_lasso/tests.rs +++ b/crates/tools/src/addons/enclosing_lasso/tests.rs @@ -367,3 +367,25 @@ fn enclosing_lasso_considers_the_geometry_a_visible_compound_paints() { ); } } + +/// A loop around clipped art that the clipping path's own shape holds, but not the region a live +/// effect moved it to, selects the art in Outline view only, which draws the clipping path without +/// its effects. +#[test] +fn outline_view_loops_measure_clipped_art_by_the_plain_clipping_path() { + let (d, _, art) = doc_with_moved_clip_region(); + let s = Selection::default(); + let p = paint(); + let around = [(410.0, 410.0), (490.0, 410.0), (490.0, 490.0), (410.0, 490.0)]; + let gesture = |outline: bool| { + let cx = ToolContext { outline, ..cx(&d, &s, &p) }; + let mut tool = crate::create(ID); + tool.pointer(&cx, &PointerEvent::new(PointerKind::Down, 410.0, 410.0)); + for &(x, y) in &around[1..] { + tool.pointer(&cx, &PointerEvent::new(PointerKind::Drag, x, y)); + } + tool.pointer(&cx, &PointerEvent::new(PointerKind::Up, 410.0, 490.0)) + }; + assert_eq!(gesture(true), vec![Action::Exec("select.set".into(), json!({"ids": [art.0]}))]); + assert_eq!(gesture(false), vec![Action::Exec("select.set".into(), json!({"ids": []}))]); +} diff --git a/crates/tools/src/addons/extend_path.rs b/crates/tools/src/addons/extend_path.rs index d1f54861ca..2269396f90 100644 --- a/crates/tools/src/addons/extend_path.rs +++ b/crates/tools/src/addons/extend_path.rs @@ -131,7 +131,7 @@ impl Tool for ExtendPathTool { // Back where it started: nothing to keep. if length == 0.0 { vec![Action::Cancel] } else { vec![preview, Action::Commit] } } - PointerKind::DoubleClick => vec![], + PointerKind::DoubleClick | PointerKind::TripleClick => vec![], } } diff --git a/crates/tools/src/addons/parametric_shape.rs b/crates/tools/src/addons/parametric_shape.rs index 68a42a665f..33700073c7 100644 --- a/crates/tools/src/addons/parametric_shape.rs +++ b/crates/tools/src/addons/parametric_shape.rs @@ -326,7 +326,7 @@ impl Tool for ParametricShapeTool { self.hover(cx, ev.pos); } match ev.kind { - PointerKind::Move => vec![], + PointerKind::Move | PointerKind::TripleClick => vec![], PointerKind::Down => { let tol = cx.point_tol(); let grip = selected(cx).and_then(|(id, s)| { diff --git a/crates/tools/src/addons/slide_anchor.rs b/crates/tools/src/addons/slide_anchor.rs index e24db4c50d..0bec99cf35 100644 --- a/crates/tools/src/addons/slide_anchor.rs +++ b/crates/tools/src/addons/slide_anchor.rs @@ -96,7 +96,7 @@ impl Tool for SlideAnchorTool { // Back where it started: nothing to keep. if t == 0.0 { vec![Action::Cancel] } else { vec![preview, Action::Commit] } } - PointerKind::DoubleClick => vec![], + PointerKind::DoubleClick | PointerKind::TripleClick => vec![], } } diff --git a/crates/tools/src/addons/smart_pen.rs b/crates/tools/src/addons/smart_pen.rs index cd72f1dd40..c25ab8f670 100644 --- a/crates/tools/src/addons/smart_pen.rs +++ b/crates/tools/src/addons/smart_pen.rs @@ -527,6 +527,7 @@ impl Tool for SmartPenTool { } _ => vec![], }, + PointerKind::TripleClick => vec![], } } diff --git a/crates/tools/src/builder.rs b/crates/tools/src/builder.rs index f5be7ac4c5..00005e3c21 100644 --- a/crates/tools/src/builder.rs +++ b/crates/tools/src/builder.rs @@ -41,9 +41,9 @@ pub use live_paint::{ }; use live_paint::{check_live_paint_options, lp_color, lp_rgb_color}; pub use lookup::{ - EDGE_NAME, FACE_NAME, Face, LIVE_PAINT_NAME, LIVE_PAINT_PREFIX, SOURCES_NAME, builder_members, drawn_outlines, edge_near, edges, face_at, faces, - is_live_paint, leaf_shapes, live_paint_at, live_paint_takes, node_outline, outline_snap, path_contains, shape_builder_shapes, shapes_for, - sources, visible_edge_near, visible_face_at, + EDGE_NAME, FACE_NAME, Face, LIVE_PAINT_NAME, LIVE_PAINT_PREFIX, LP_JOIN_TOL, SOURCES_NAME, builder_members, connected_edges, drawn_outlines, + edge_near, edges, face_at, faces, flood_faces, is_live_paint, leaf_shapes, live_paint_at, live_paint_takes, lp_stroke_paint, node_outline, + outline_snap, path_contains, shape_builder_shapes, shapes_for, sources, visible_edge_near, visible_face_at, }; pub use map::{ BuilderMap, HATCH, HIGHLIGHT_RED, Hit, MergeGeometry, MergeInput, PreparedMerge, Rest, Touched, hatch, maps_built, merge_geometry, merge_inputs, diff --git a/crates/tools/src/builder/live_paint.rs b/crates/tools/src/builder/live_paint.rs index e5f696a5a7..235715a0b6 100644 --- a/crates/tools/src/builder/live_paint.rs +++ b/crates/tools/src/builder/live_paint.rs @@ -1,10 +1,14 @@ use super::cache::RegionCache; -use super::lookup::{is_live_paint, live_paint_at, live_paint_at_where, visible_edge_near, visible_face_at}; +use super::lookup::{ + connected_edges, flood_faces, is_live_paint, leaf_shapes, live_paint_at, live_paint_at_where, lp_stroke_paint, node_outline, visible_edge_near, + visible_face_at, +}; use super::map::{HIGHLIGHT_RED, sorted_roots}; use super::{ Action, Arc, BezPath, CLICK_TOL_PX, Cursor, Document, EDGE_NAME, FACE_NAME, FillRule, Mods, Node, NodeId, Overlay, Point, PointerEvent, PointerKind, Rect, Tool, ToolContext, ToolKey, Value, color_swatches, json, json_ids, path_contains, pick_swatch, plain, swatch_chips, }; +use vectorcraft_color::Paint; // ---------- Live Paint Bucket ---------- @@ -172,6 +176,17 @@ enum LpPaint { /// highlighted. The cursor is a filled bucket where a click fills a face, a brush where it paints /// an edge and an empty bucket where it paints nothing; with Alt it is the Eyedropper. /// +/// A double-click on a face fills it and the faces reached from it across edges that draw no +/// stroke (`scope: "connected"`); on an edge it paints the edges joined to it that have its stroke. +/// A triple-click on a face fills every face of the group with the face's fill, and on an edge it +/// paints every edge of the group with the edge's stroke (`scope: "samePaint"`). Each click of a +/// double-click or triple-click paints as it arrives, as its own undo step, and the paint compared +/// is the one the face or edge had before the first of its clicks that painted it. A first click +/// that made the Live Paint group counts when the face it filled is the clicked face. Shift and the +/// options choose a face or an edge as for a click; with Alt or Cmd/Ctrl held a double-click or +/// triple-click paints nothing. With Space held for the view tools, a click, double-click or triple-click paints +/// nothing and no face or edge is highlighted. +/// /// The Left and Right arrow keys without Shift, Alt or Cmd/Ctrl set the active paint (the fill, /// or the stroke when the Stroke proxy is in front) to the color swatch before or after it in the /// Swatches panel, wrapping around; from a color that is no swatch, Right picks the first swatch @@ -182,10 +197,13 @@ enum LpPaint { pub struct LivePaintBucketTool { pub(super) cache: RegionCache, pub(super) hover: LpHover, - /// Where the pointer last moved, and whether Shift and Alt were held. - at: Option<(Point, bool, bool)>, + /// Where the pointer last moved, and the modifiers held there. + at: Option<(Point, Mods)>, /// The fill command and polyline previewed from the press's snapshot. fill_drag: Option<(Value, Vec>)>, + /// The last [`LP_PRESSES`] presses, oldest first: the face or edge each one painted, with its + /// paint before that press, or None for a press that painted no face or edge. + presses: Vec>, fills: bool, strokes: bool, highlight: bool, @@ -198,6 +216,40 @@ pub struct LivePaintBucketTool { picked: [Option; 2], } +/// The face or edge a Live Paint Bucket press paints. +#[derive(Clone, Debug, PartialEq)] +struct LpPress { + /// The face or edge; None for the face of the Live Paint group the press makes. + part: Option, + /// Where the press was. + at: Point, + /// Its fill (a face), or the stroke paint it draws with ([`lp_stroke_paint`], an edge), before + /// the press. + before: Paint, + /// The other faces or edges the double-click that followed the press reached, each with its + /// fill or drawn stroke paint before the double-click. + also: Vec<(NodeId, Paint)>, +} + +/// The fill of the face under `p` in the Live Paint group that `roots` make: the fill of the +/// front-most of their paths whose closed subpaths hold `p`, else none. Open subpaths bound no face. +fn made_face_fill(doc: &Document, roots: &[NodeId], p: Point) -> Paint { + let mut leaves = vec![]; + for n in roots.iter().filter_map(|id| doc.node(*id)) { + leaf_shapes(n, &mut leaves); + } + let holds = |l: &Node| { + node_outline(l).is_some_and(|(path, rule)| { + let closed = vectorcraft_geom::PathData::new(path.subpaths.into_iter().filter(|sp| sp.closed && sp.anchors.len() >= 2).collect()); + !closed.is_empty() && path_contains(&closed, rule, p) + }) + }; + leaves.iter().rev().find(|l| holds(l)).map_or(Paint::None, |l| l.appearance.fill_paint()) +} + +/// How many presses the Live Paint Bucket keeps: the three of a triple-click. +const LP_PRESSES: usize = 3; + /// Maximum points in one Live Paint fill path chunk. pub const LP_FILL_CHUNK_POINTS: usize = 4096; @@ -208,6 +260,7 @@ impl Default for LivePaintBucketTool { hover: LpHover::None, at: None, fill_drag: None, + presses: Vec::new(), fills: true, strokes: false, highlight: true, @@ -272,14 +325,109 @@ impl LivePaintBucketTool { } } - /// The highlight at `p` for a pointer with Shift and Alt held as given: none with Alt or with - /// Highlight off, else the face or edge a click there paints. With Highlight off the selection's - /// map is still made, for the cursor ([`Self::paints_at`]). - fn hover_at(&mut self, cx: &ToolContext, p: Point, shift: bool, alt: bool) -> LpHover { - if alt { + /// Note a press: what it paints, None when it paints no face or edge. + fn note_press(&mut self, press: Option) { + if self.presses.len() == LP_PRESSES { + self.presses.remove(0); + } + self.presses.push(press); + } + + /// Note a press at `at` that paints face or edge (`edge`) `n`. + fn note_part(&mut self, n: &Node, edge: bool, at: Point) { + let before = if edge { lp_stroke_paint(n) } else { n.appearance.fill_paint() }; + self.note_press(Some(LpPress { part: Some(n.id), at, before, also: vec![] })); + } + + /// Note that the double-click after the last press also reaches `parts` of group `group`, with + /// the paint each has now (a face's fill, or an edge's drawn stroke paint with `edge`). + fn note_reached(&mut self, group: &Node, parts: Vec, edge: bool) { + let Some(Some(last)) = self.presses.last_mut() else { return }; + let reached: std::collections::HashSet = parts.into_iter().filter(|id| last.part != Some(*id)).collect(); + last.also = group + .children() + .into_iter() + .flatten() + .filter(|c| reached.contains(&c.id)) + .map(|n| (n.id, if edge { lp_stroke_paint(n) } else { n.appearance.fill_paint() })) + .collect(); + } + + /// The paint `part` had before the first press of a click sequence of `clicks` presses that + /// painted `part`, or before the double-click after a press when that double-click reached it + /// (the sequence's first press counts when it made the group `part` is in and the face it + /// filled there is `part`); `now` when the last press did not paint it. + fn before(&self, cx: &ToolContext, part: NodeId, clicks: usize, now: Paint) -> Paint { + let Some(run) = self.presses.len().checked_sub(clicks).and_then(|from| self.presses.get(from..)) else { return now }; + let made_part = |q: &LpPress| live_paint_at(cx.doc, q.at).and_then(|g| visible_face_at(cx.doc.node(g)?, q.at)).is_some_and(|f| f.id == part); + let on_part = |i: usize, q: &LpPress| q.part == Some(part) || (i == 0 && q.part.is_none() && made_part(q)); + if !run.last().and_then(Option::as_ref).is_some_and(|q| on_part(run.len() - 1, q)) { + return now; + } + for (i, q) in run.iter().enumerate() { + let Some(q) = q else { continue }; + if on_part(i, q) { + return q.before.clone(); + } + if let Some((_, paint)) = q.also.iter().find(|(id, _)| *id == part) { + return paint.clone(); + } + } + now + } + + /// What a double-click (`scope` "connected", 2 `clicks`) or a triple-click ("samePaint", 3) at + /// `p` runs: the command a click there runs, with `scope`, and the paint it compares as `match`. + /// A double-click notes the other faces or edges it reaches, for the triple-click's `match`. + fn multi_click(&mut self, cx: &ToolContext, p: Point, mods: Mods, scope: &str, clicks: usize) -> Vec { + // With Alt held, with Space held for the view tools, or with Cmd/Ctrl held (its presses went + // to the selection tool Cmd lends), a double-click or triple-click paints nothing. + if mods.alt || mods.space || mods.cmd { + return vec![]; + } + let point = json!([p.x, p.y]); + let paint = self.paints(mods.shift); + if matches!(paint, LpPaint::Strokes | LpPaint::Both) + && let Some((g, Some(e))) = lp_part_at(cx.doc, p, cx.tol(4.0), true, &|id| lp_visible(cx, id)) + { + let mut v = json!({ "group": g.0, "point": point, "tolerance": cx.tol(4.0), "scope": scope }); + let like = self.before(cx, e.id, clicks, lp_stroke_paint(e)); + if clicks == 2 + && let Some(group) = cx.doc.node(g) + { + self.note_reached(group, connected_edges(group, e.id, &like), true); + } + if let Ok(like) = serde_json::to_value(like) { + v["match"] = like; + } + return vec![Action::Exec("livePaint.strokeEdge".into(), v)]; + } + if !matches!(paint, LpPaint::Fills | LpPaint::Both) { + return vec![]; + } + let Some((g, f)) = live_paint_at(cx.doc, p).and_then(|g| Some((g, visible_face_at(cx.doc.node(g)?, p)?))) else { return vec![] }; + let mut v = json!({ "group": g.0, "point": point, "scope": scope }); + if clicks == 2 + && let Some(group) = cx.doc.node(g) + { + self.note_reached(group, flood_faces(group, f.id), false); + } + if scope == "samePaint" + && let Ok(like) = serde_json::to_value(self.before(cx, f.id, clicks, f.appearance.fill_paint())) + { + v["match"] = like; + } + vec![Action::Exec("livePaint.fill".into(), v)] + } + + /// The highlight at `p` for a pointer with the modifiers `mods`: none with Alt, with Space held + /// for the view tools or with Highlight off, else the face or edge a click there paints. With + /// Highlight off the selection's map is still made, for the cursor ([`Self::paints_at`]). + fn hover_at(&mut self, cx: &ToolContext, p: Point, mods: Mods) -> LpHover { + if mods.alt || mods.space { return LpHover::None; } - let target = self.target_at(cx, p, shift); + let target = self.target_at(cx, p, mods.shift); if self.highlight { target } else { LpHover::None } } @@ -354,13 +502,19 @@ impl Tool for LivePaintBucketTool { } match ev.kind { PointerKind::Move => { - self.at = Some((p, ev.mods.shift, ev.mods.alt)); - self.hover = self.hover_at(cx, p, ev.mods.shift, ev.mods.alt); + self.at = Some((p, ev.mods)); + self.hover = self.hover_at(cx, p, ev.mods); vec![] } PointerKind::Down => { self.hover = LpHover::None; + // With Space held for the view tools, a press paints nothing. + if ev.mods.space { + self.note_press(None); + return vec![]; + } if ev.mods.alt { + self.note_press(None); if ev.mods.shift { return crate::xform::eyedropper::sample_color_at(cx, p).map_or_else(Vec::new, |color| { vec![Action::Exec("paint.sampleColor".into(), json!({ "color": crate::params::color_json(&color), "ids": [] }))] @@ -385,36 +539,49 @@ impl Tool for LivePaintBucketTool { let point = json!([p.x, p.y]); let paint = self.paints(ev.mods.shift); if matches!(paint, LpPaint::Strokes | LpPaint::Both) - && let Some((g, Some(_))) = lp_part_at(cx.doc, p, cx.tol(4.0), true, &|id| lp_visible(cx, id)) + && let Some((g, Some(e))) = lp_part_at(cx.doc, p, cx.tol(4.0), true, &|id| lp_visible(cx, id)) { + self.note_part(e, true, p); return vec![Action::Exec("livePaint.strokeEdge".into(), json!({ "group": g.0, "point": point, "tolerance": cx.tol(4.0) }))]; } if !matches!(paint, LpPaint::Fills | LpPaint::Both) { + self.note_press(None); return vec![]; } if let Some(g) = live_paint_at(cx.doc, p) { + match cx.doc.node(g).and_then(|n| visible_face_at(n, p)) { + Some(f) => self.note_part(f, false, p), + None => self.note_press(None), + } return self.begin_fill(json!({ "group": g.0, "point": point }), p); } if self.cache.at(cx, p).is_some() { let roots = sorted_roots(cx.doc, &cx.selection.objects); + self.note_press(Some(LpPress { part: None, at: p, before: made_face_fill(cx.doc, &roots, p), also: vec![] })); return self.begin_fill(json!({ "ids": json_ids(&roots), "point": point }), p); } + self.note_press(None); vec![] } PointerKind::Drag => self.drag_fill(p), PointerKind::Up => { // The swatch preview shows again at the release point. - self.at = Some((p, ev.mods.shift, ev.mods.alt)); + self.at = Some((p, ev.mods)); let mut acts = self.drag_fill(p); if self.fill_drag.take().is_some() { acts.push(Action::Commit); } acts } - _ => vec![], + PointerKind::DoubleClick => self.multi_click(cx, p, ev.mods, "connected", 2), + PointerKind::TripleClick => self.multi_click(cx, p, ev.mods, "samePaint", 3), } } + fn history_moved(&mut self) { + self.presses.clear(); + } + /// Escape during a fill drag cancels it. Left and Right pick the color swatch before or after /// the active paint, while no drag is on. fn key(&mut self, cx: &ToolContext, key: ToolKey, mods: Mods) -> Vec { @@ -453,6 +620,7 @@ impl Tool for LivePaintBucketTool { } fn deactivate(&mut self, _cx: &ToolContext) -> Vec { + self.presses.clear(); if self.fill_drag.take().is_some() { vec![Action::Commit] } else { vec![] } } @@ -467,7 +635,8 @@ impl Tool for LivePaintBucketTool { // No chips during a fill drag, or while Alt makes the tool sample with the eyedropper. if self.preview && !self.busy() - && let Some((at, _, false)) = self.at + && let Some((at, mods)) = self.at + && !mods.alt { out.extend(swatch_chips(cx, at, Self::active_paint(cx), self.picked[Self::picked_slot(cx)], true)); } @@ -518,8 +687,8 @@ impl Tool for LivePaintBucketTool { // of a Live Paint group the hover takes no map. loop { self.cache.settle(wait); - if let Some((p, shift, alt)) = self.at { - self.hover = self.hover_at(cx, p, shift, alt); + if let Some((p, mods)) = self.at { + self.hover = self.hover_at(cx, p, mods); } if !wait || !self.cache.waiting() { break; @@ -540,7 +709,11 @@ pub const LP_SELECT_WIDTH_RANGE: (f64, f64) = (1.0, 20.0); /// Live Paint Selection: click selects a face (Shift adds); Alt-click selects an edge. A drag draws /// a marquee, and on release the faces and edges it touches ([`lp_parts_in`]) become the selection; /// with Shift held at the press, each of them leaves the selection if it is selected and joins it -/// otherwise. A click and a marquee change the selection on release, so Escape between the press +/// otherwise. A double-click on a face selects it and the faces of its group that are not parted +/// from it by a stroked edge; on an edge, it selects the edge and the edges joined to it end to end +/// that have its stroke paint ([`LivePaintSelectionTool::reach_at`]). With Shift held, each of them +/// leaves the selection if it is selected and joins it otherwise. +/// A click and a marquee change the selection on release, so Escape between the press /// and the release (which removes the marquee) leaves the selection as it was. 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. Its Tool Options @@ -627,6 +800,18 @@ impl LivePaintSelectionTool { }; (hit, cursor) } + + /// What a double-click at `p` selects, Alt held or not: on the face a click there picks + /// ([`LivePaintSelectionTool::picks_edge`]), that face and the faces of its group a flood from it + /// reaches across edges that are hidden or draw no stroke ([`flood_faces`]); on the edge a click + /// picks, that edge and the edges of its group joined to it end to end through edges that draw + /// with the stroke paint it draws with ([`connected_edges`], [`lp_stroke_paint`]). Empty where a click selects no face or edge. + fn reach_at(&self, cx: &ToolContext, p: Point, alt: bool) -> Vec { + let Some(edge) = self.picks_edge(alt) else { return vec![] }; + let Some((gid, Some(part))) = lp_part_at(cx.doc, p, cx.tol(4.0), edge, &|id| lp_selectable(cx, id)) else { return vec![] }; + let Some(group) = cx.doc.node(gid) else { return vec![] }; + if edge { connected_edges(group, part.id, &lp_stroke_paint(part)) } else { flood_faces(group, part.id) } + } } /// The faces (with `faces`) and edges (with `edges`) that marquee `r` touches, among the faces and @@ -748,7 +933,19 @@ impl Tool for LivePaintSelectionTool { (false, false) => vec![Action::Exec("select.set".into(), json!({ "ids": json_ids(&ids) }))], } } - _ => vec![], + PointerKind::DoubleClick => { + // The two clicks before it already selected the part under the pointer (or, with + // Shift, toggled it twice); the double-click selects the part with what it reaches. + let ids = self.reach_at(cx, p, ev.mods.alt); + match (ids.is_empty(), ev.mods.shift) { + (true, _) => vec![], + (false, true) => vec![Action::Exec("select.toggle".into(), json!({ "ids": json_ids(&ids) }))], + (false, false) => vec![Action::Exec("select.set".into(), json!({ "ids": json_ids(&ids) }))], + } + } + // The tool takes no action on a triple-click; its third press and release select as a + // click does. + PointerKind::TripleClick => vec![], } } diff --git a/crates/tools/src/builder/lookup.rs b/crates/tools/src/builder/lookup.rs index 5e85d9339d..daa9a34f82 100644 --- a/crates/tools/src/builder/lookup.rs +++ b/crates/tools/src/builder/lookup.rs @@ -104,6 +104,349 @@ fn nearest_edge<'a>(edges: impl IntoIterator>, p: Point, to best.map(|b| b.1) } +/// The greatest distance (pt) between the ends of two Live Paint edges that the Live Paint tools take +/// as one point. Every edge comes from one planar map, so their ends meet this closely. +pub const LP_JOIN_TOL: f64 = 1e-4; + +/// The greatest distance (pt) between the middle of a Live Paint face's outline segment and an edge +/// it runs along. The planar map refits outlines to [`vectorcraft_pathops::DEFAULT_PRECISION`], +/// keeping each refit segment's ends, and with Gap Detection on, the faces and the edges come from +/// two maps, so an outline can lie that far off its edges between its ends. +const LP_FACE_EDGE_TOL: f64 = vectorcraft_pathops::DEFAULT_PRECISION; + +/// The cell [`LP_JOIN_TOL`] wide that holds `p`, for finding the points near it; two points within +/// [`LP_JOIN_TOL`] of each other lie in the same or neighboring cells. The cast saturates, so a +/// coordinate too large or not finite does not overflow. +fn lp_cell(p: Point) -> (i64, i64) { + ((p.x / LP_JOIN_TOL).round() as i64, (p.y / LP_JOIN_TOL).round() as i64) +} + +/// The cell that holds `p` ([`lp_cell`]) and the eight cells around it. +fn lp_cells_around(p: Point) -> impl Iterator { + let (x, y) = lp_cell(p); + (-1..=1).flat_map(move |dx: i64| (-1..=1).map(move |dy: i64| (x.saturating_add(dx), y.saturating_add(dy)))) +} + +/// The stroke paint Live Paint edge `edge` draws with: the paint of its topmost stroke that is shown +/// with a paint, a weight above 0 and an opacity above 0, or [`Paint::None`] when the edge is fully +/// transparent or has no such stroke. +pub fn lp_stroke_paint(edge: &Node) -> Paint { + if edge.opacity <= 0.0 { + return Paint::None; + } + edge.appearance + .items + .iter() + .rev() + .find_map(|i| match i { + vectorcraft_doc::appearance::AppearanceItem::Stroke(s) if s.visible && !s.paint.is_none() && s.width > 0.0 && s.opacity > 0.0 => { + Some(s.paint.clone()) + } + _ => None, + }) + .unwrap_or(Paint::None) +} + +/// Whether Live Paint edge `edge` draws no stroke ([`lp_stroke_paint`] is [`Paint::None`]). +fn unstroked(edge: &Node) -> bool { + lp_stroke_paint(edge).is_none() +} + +/// The segments of `pd`. +fn lp_segments(pd: &PathData) -> Vec { + pd.subpaths.iter().flat_map(|sp| (0..sp.segment_count()).map(|i| sp.segment(i))).collect() +} + +/// The faces of Live Paint group `group` that a flood from face `start` reaches, `start` first: +/// `start`, and each face that shares with a face already reached an edge that is hidden or draws +/// no stroke. Hidden faces are not reached and do not pass the flood on. A face runs along the parts +/// of the edge segments its outline segments lie on ([`lp_lies_on`]) or overlap ([`lp_overlap`]). +/// Two faces share an edge where those parts overlap along more than [`LP_FACE_EDGE_TOL`], or, where +/// both outlines lie within [`LP_JOIN_TOL`] of the edge, along more than half the shorter part. So +/// two faces that a Gap Detection gap parts on the same side of an edge, whose parts only touch, do +/// not share it, and two faces whose shared edge is shorter than [`LP_FACE_EDGE_TOL`] do. Empty when +/// `start` is not a face of `group` that is not hidden. +pub fn flood_faces(group: &Node, start: NodeId) -> Vec { + use kurbo::{ParamCurve, ParamCurveArclen}; + use std::collections::{HashMap, HashSet}; + let shown: Vec<&Arc> = faces(group).into_iter().filter(|f| f.visible).collect(); + if !shown.iter().any(|f| f.id == start) { + return vec![]; + } + // Each edge segment, and whether a flood crosses it. + let edge_segs: Vec<(kurbo::CubicBez, bool)> = edges(group) + .into_iter() + .flat_map(|e| { + let cross = !e.visible || unstroked(e); + e.path_data().map(lp_segments).unwrap_or_default().into_iter().map(move |s| (s, cross)) + }) + .collect(); + // The faces along each edge segment a flood crosses, each with the part of the segment it runs + // along (from and to, in the segment's own parameter). A face outline segment usually lies on + // one edge segment, stroked or not ([`lp_lies_on`]); one that does not (a piece of an edge + // segment where a Gap Detection line meets it, the line itself, or an outline segment that spans + // several edge segments) is measured against the edge segments a flood crosses that its bounds + // meet ([`lp_overlap`]). Each part also records whether its outline segment lies within + // [`LP_JOIN_TOL`] of it ([`lp_close`]). + let all: Vec<(kurbo::CubicBez, bool)> = edge_segs.iter().map(|&(s, _)| (s, true)).collect(); + let all_grid = LpEdgeGrid::new(&all); + let mut along: HashMap> = HashMap::new(); + let mut pieces: Vec<(kurbo::CubicBez, NodeId)> = vec![]; + for f in &shown { + for piece in f.path_data().map(lp_segments).unwrap_or_default() { + let m = piece.eval(0.5); + let bounds = kurbo::ParamCurveExtrema::bounding_box(&piece).inflate(LP_FACE_EDGE_TOL, LP_FACE_EDGE_TOL); + // The edge segment the outline segment lies on whose middle is nearest its own. + let on = all_grid + .near_box(bounds) + .into_iter() + .filter_map(|k| edge_segs.get(k).and_then(|(s, cross)| lp_lies_on(s, &piece).map(|part| (k, s, *cross, part)))) + .min_by(|x, y| (x.1.eval(0.5) - m).hypot().total_cmp(&(y.1.eval(0.5) - m).hypot())); + match on { + Some((k, s, cross, (from, to))) => { + if cross { + along.entry(k).or_default().push((f.id, from, to, lp_close(s, from, to, &piece))); + } + } + None => pieces.push((piece, f.id)), + } + } + } + if !pieces.is_empty() { + let grid = LpEdgeGrid::new(&edge_segs); + for (piece, id) in pieces { + let bounds = kurbo::ParamCurveExtrema::bounding_box(&piece).inflate(LP_FACE_EDGE_TOL, LP_FACE_EDGE_TOL); + for k in grid.near_box(bounds) { + if let Some((s, true)) = edge_segs.get(k) + && let Some((a, c)) = lp_overlap(s, &piece) + { + along.entry(k).or_default().push((id, a, c, lp_close(s, a, c, &piece))); + } + } + } + } + let mut next: HashMap> = HashMap::new(); + // Sorted by where each part starts, a part is compared only with the parts after it that start + // before it ends. Two parts that overlap along [`LP_FACE_EDGE_TOL`] or less join only when both + // lie within [`LP_JOIN_TOL`] of the edge and the overlap is more than half the shorter part: an + // edge that short is shared, while an outline that only crosses it lies off it. + for (k, on) in &mut along { + let Some((s, _)) = edge_segs.get(*k) else { continue }; + on.sort_by(|x, y| x.1.total_cmp(&y.1)); + for (i, &(a, a0, a1, a_close)) in on.iter().enumerate() { + for &(c, c0, c1, c_close) in on.iter().skip(i + 1).take_while(|x| x.1 < a1) { + let (from, to) = (a0.max(c0), a1.min(c1)); + let len = |x: f64, y: f64| s.subsegment(x..y).arclen(1e-6); + let shared = if a != c && from < to { len(from, to) } else { 0.0 }; + let short_shared = a_close && c_close && shared > 0.5 * len(a0, a1).min(len(c0, c1)); + if shared > 0.0 && (shared > LP_FACE_EDGE_TOL || short_shared) { + next.entry(a).or_default().push(c); + next.entry(c).or_default().push(a); + } + } + } + } + let mut reached = vec![start]; + let mut seen = HashSet::from([start]); + let mut i = 0; + while let Some(&f) = reached.get(i) { + i += 1; + for &n in next.get(&f).map(Vec::as_slice).unwrap_or_default() { + if seen.insert(n) { + reached.push(n); + } + } + } + reached +} + +/// The part of edge segment `s` that outline segment `piece` runs along, as (from, to) in `s`'s +/// own parameter, or None when they share no length. The part runs between the ends of `s` that lie +/// within [`LP_FACE_EDGE_TOL`] of `piece` and the ends of `piece` that lie within [`LP_JOIN_TOL`] of +/// `s` (the map keeps the ends of an outline segment it refits), and its middle lies within +/// [`LP_FACE_EDGE_TOL`] of `piece`, where the two run along each other ([`lp_runs_along`]). When no +/// end of `piece` lies on `s`, `piece` must lie within [`LP_JOIN_TOL`] of the part ([`lp_close`]). So +/// two segments that only cross or touch, or that only lie near each other, share nothing. +fn lp_overlap(s: &kurbo::CubicBez, piece: &kurbo::CubicBez) -> Option<(f64, f64)> { + use kurbo::{ParamCurve, ParamCurveNearest}; + let on_piece = |p: Point| piece.nearest(p, 1e-9).distance_sq.sqrt() <= LP_FACE_EDGE_TOL; + let mut ts: Vec = [(s.p0, 0.0), (s.p3, 1.0)].into_iter().filter(|(p, _)| on_piece(*p)).map(|(_, t)| t).collect(); + let mut piece_end_on = false; + for p in [piece.p0, piece.p3] { + let n = s.nearest(p, 1e-9); + if n.distance_sq.sqrt() <= LP_JOIN_TOL { + ts.push(n.t); + piece_end_on = true; + } + } + let from = ts.iter().copied().fold(f64::INFINITY, f64::min); + let to = ts.iter().copied().fold(f64::NEG_INFINITY, f64::max); + if from >= to { + return None; + } + let mid = (from + to) / 2.0; + let n = piece.nearest(s.eval(mid), 1e-9); + let along = if piece_end_on { lp_runs_along(s, from, to, piece, mid, n.t) } else { lp_close(s, from, to, piece) }; + (n.distance_sq.sqrt() <= LP_FACE_EDGE_TOL && along).then_some((from, to)) +} + +/// The part of edge segment `s` that outline segment `piece` lies on as a whole, as (from, to) in +/// `s`'s own parameter: both ends of `piece` lie within [`LP_JOIN_TOL`] of `s`, its middle lies +/// within [`LP_FACE_EDGE_TOL`] of `s`, and the two run along each other ([`lp_runs_along`]). +fn lp_lies_on(s: &kurbo::CubicBez, piece: &kurbo::CubicBez) -> Option<(f64, f64)> { + use kurbo::{ParamCurve, ParamCurveNearest}; + let (a, c, m) = (s.nearest(piece.p0, 1e-9), s.nearest(piece.p3, 1e-9), s.nearest(piece.eval(0.5), 1e-9)); + let (from, to) = (a.t.min(c.t), a.t.max(c.t)); + let near = a.distance_sq.sqrt() <= LP_JOIN_TOL && c.distance_sq.sqrt() <= LP_JOIN_TOL && m.distance_sq.sqrt() <= LP_FACE_EDGE_TOL; + (near && lp_runs_along(s, from, to, piece, m.t, 0.5)).then_some((from, to)) +} + +/// Whether outline segment `piece` runs along the part of edge segment `s` from `from` to `to` +/// rather than crossing it: it lies within [`LP_JOIN_TOL`] of that part ([`lp_close`]), or the two +/// run the same way or opposite ways at `ts` on `s` and `tp` on `piece` ([`lp_parallel`]). +fn lp_runs_along(s: &kurbo::CubicBez, from: f64, to: f64, piece: &kurbo::CubicBez, ts: f64, tp: f64) -> bool { + lp_close(s, from, to, piece) || lp_parallel(s, ts, piece, tp) +} + +/// Whether outline segment `piece` lies within [`LP_JOIN_TOL`] of edge segment `s` at the ends and +/// the middle of the part of `s` from `from` to `to`. +fn lp_close(s: &kurbo::CubicBez, from: f64, to: f64, piece: &kurbo::CubicBez) -> bool { + use kurbo::{ParamCurve, ParamCurveNearest}; + [from, (from + to) / 2.0, to].into_iter().all(|t| piece.nearest(s.eval(t), 1e-9).distance_sq.sqrt() <= LP_JOIN_TOL) +} + +/// Whether segment `s` at parameter `ts` and segment `piece` at parameter `tp` run the same way or +/// opposite ways: the sine of the angle between their directions there is at most 0.2. False where +/// either has no direction. +fn lp_parallel(s: &kurbo::CubicBez, ts: f64, piece: &kurbo::CubicBez, tp: f64) -> bool { + use kurbo::{ParamCurve, ParamCurveDeriv}; + let (u, v) = (s.deriv().eval(ts).to_vec2(), piece.deriv().eval(tp).to_vec2()); + let n = u.hypot() * v.hypot(); + n > 0.0 && u.cross(v).abs() <= 0.2 * n +} + +/// Most grid cells one edge segment is listed in by [`LpEdgeGrid`]; a longer one is tried for +/// every point. +const LP_GRID_SPAN: i64 = 1024; + +/// The farthest cell from the grid's origin, on each axis, that [`LpEdgeGrid`] numbers a point in. +const LP_GRID_LIMIT: f64 = 1_048_576.0; + +/// The edge segments a flood crosses, by the cells of a square grid (about one cell per segment) +/// that their bounds, widened by [`LP_FACE_EDGE_TOL`], cover. +struct LpEdgeGrid { + origin: Point, + cell: f64, + /// Segment indices by cell. + cells: std::collections::HashMap<(i64, i64), Vec>, + /// Segments whose bounds cover more than [`LP_GRID_SPAN`] cells, near every point. + wide: Vec, +} + +impl LpEdgeGrid { + /// The grid of the segments of `edges` that a flood crosses (those marked true). + fn new(edges: &[(kurbo::CubicBez, bool)]) -> Self { + let boxes: Vec<(usize, Rect)> = edges + .iter() + .enumerate() + .filter(|(_, e)| e.1) + .map(|(k, (s, _))| (k, kurbo::ParamCurveExtrema::bounding_box(s).inflate(LP_FACE_EDGE_TOL, LP_FACE_EDGE_TOL))) + .collect(); + let all = boxes.iter().map(|b| b.1).reduce(|a, c| a.union(c)).unwrap_or_default(); + let side = (boxes.len() as f64).sqrt().ceil().max(1.0); + let cell = all.width().max(all.height()) / side; + let cell = if cell.is_finite() && cell > LP_FACE_EDGE_TOL { cell } else { LP_FACE_EDGE_TOL }; + let mut grid = Self { origin: all.origin(), cell, cells: std::collections::HashMap::new(), wide: vec![] }; + for (k, b) in boxes { + let ((x0, y0), (x1, y1)) = (grid.cell_of(Point::new(b.x0, b.y0)), grid.cell_of(Point::new(b.x1, b.y1))); + if (x1 - x0 + 1).saturating_mul(y1 - y0 + 1) > LP_GRID_SPAN { + grid.wide.push(k); + continue; + } + for x in x0..=x1 { + for y in y0..=y1 { + grid.cells.entry((x, y)).or_default().push(k); + } + } + } + grid + } + + /// The cell `p` is in, counted from the origin (at most [`LP_GRID_LIMIT`] cells away on each + /// axis). + fn cell_of(&self, p: Point) -> (i64, i64) { + let at = |v: f64, o: f64| ((v - o) / self.cell).floor().clamp(-LP_GRID_LIMIT, LP_GRID_LIMIT) as i64; + (at(p.x, self.origin.x), at(p.y, self.origin.y)) + } + + /// The segments whose widened bounds may meet `r`, each once, in ascending order. When `r` + /// covers more than [`LP_GRID_SPAN`] cells, every listed segment is returned. + fn near_box(&self, r: Rect) -> Vec { + let ((x0, y0), (x1, y1)) = (self.cell_of(Point::new(r.x0, r.y0)), self.cell_of(Point::new(r.x1, r.y1))); + let mut out: Vec = self.wide.clone(); + if (x1 - x0 + 1).saturating_mul(y1 - y0 + 1) > LP_GRID_SPAN { + out.extend(self.cells.values().flatten()); + } else { + for x in x0..=x1 { + for y in y0..=y1 { + out.extend(self.cells.get(&(x, y)).into_iter().flatten()); + } + } + } + out.sort_unstable(); + out.dedup(); + out + } +} + +/// The edges of Live Paint group `group` that are not hidden and are joined to edge `start` through +/// edges that draw with stroke paint `paint` ([`lp_stroke_paint`]), `start` first: `start`, and each +/// edge that draws with that stroke paint and has an end (the first or last point of one of its subpaths) within [`LP_JOIN_TOL`] of an +/// end of an edge already reached. +/// Empty when `start` is not an edge of `group` that is not hidden. +pub fn connected_edges(group: &Node, start: NodeId, paint: &Paint) -> Vec { + use std::collections::{HashMap, HashSet}; + let es: Vec<&Arc> = edges(group).into_iter().filter(|e| e.visible && (e.id == start || lp_stroke_paint(e) == *paint)).collect(); + // The first and last points of each subpath of each edge. + let ends: Vec> = es + .iter() + .map(|e| { + let Some(pd) = e.path_data() else { return vec![] }; + pd.subpaths + .iter() + .filter_map(|sp| { + let n = sp.segment_count(); + (n > 0).then(|| [sp.segment(0).p0, sp.segment(n - 1).p3]) + }) + .flatten() + .collect() + }) + .collect(); + let mut at: HashMap<(i64, i64), Vec<(Point, usize)>> = HashMap::new(); + for (i, pts) in ends.iter().enumerate() { + for &p in pts { + at.entry(lp_cell(p)).or_default().push((p, i)); + } + } + let Some(first) = es.iter().position(|e| e.id == start) else { return vec![] }; + let mut reached = vec![first]; + let mut seen = HashSet::from([first]); + let mut k = 0; + while let Some(&i) = reached.get(k) { + k += 1; + for &p in ends.get(i).map(Vec::as_slice).unwrap_or_default() { + for c in lp_cells_around(p) { + for &(q, j) in at.get(&c).map(Vec::as_slice).unwrap_or_default() { + if (q - p).hypot() <= LP_JOIN_TOL && seen.insert(j) { + reached.push(j); + } + } + } + } + } + reached.into_iter().filter_map(|i| es.get(i).map(|e| e.id)).collect() +} + /// The visible Live Paint group with a face under `p` that is not hidden (front-most in paint order). pub fn live_paint_at(doc: &Document, p: Point) -> Option { live_paint_at_where(doc, p, |id| doc.is_visible(id)) @@ -162,8 +505,8 @@ fn collect_members<'a>(n: &'a Node, builder: bool, out: &mut Vec<&'a Node>) { NodeKind::Path { guide: true, .. } | NodeKind::Path { clipping: true, .. } => {} NodeKind::Path { .. } | NodeKind::Compound { .. } => out.push(n), NodeKind::Group { .. } if builder && is_live_paint(n) => { - out.extend(faces(n).into_iter().filter(|f| !f.visible || f.locked || !f.appearance.fill_paint().is_none()).map(|f| &**f)); - out.extend(edges(n).into_iter().filter(|e| !e.visible || e.locked || !e.appearance.stroke_paint().is_none()).map(|e| &**e)); + out.extend(faces(n).into_iter().filter(|f| !f.visible || f.locked || (f.opacity > 0.0 && f.appearance.has_drawn_fill())).map(|f| &**f)); + out.extend(edges(n).into_iter().filter(|e| !e.visible || e.locked || (e.opacity > 0.0 && e.appearance.has_drawn_stroke())).map(|e| &**e)); } NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => { for c in children { @@ -244,9 +587,12 @@ fn shapes_of<'a>(doc: &'a Document, roots: &[NodeId], builder: bool) -> (Vec(doc: &'a Document, roots: &[NodeId], open_filled_as_closed: bool) -> (Vec, Vec<&'a Node>) { let (mut shapes, leaves) = shapes_of(doc, roots, true); @@ -257,7 +603,7 @@ pub fn shape_builder_shapes<'a>(doc: &'a Document, roots: &[NodeId], open_filled s.path.subpaths = s.path.subpaths.iter().flat_map(|sp| sp.cut_at(&start)).collect(); continue; } - if !open_filled_as_closed || l.appearance.fill_paint().is_none() { + if !open_filled_as_closed || !l.appearance.has_drawn_fill() { continue; } for sp in s.path.subpaths.iter_mut().filter(|sp| !sp.closed) { diff --git a/crates/tools/src/builder/map.rs b/crates/tools/src/builder/map.rs index 74ec31f69a..6b524e9af9 100644 --- a/crates/tools/src/builder/map.rs +++ b/crates/tools/src/builder/map.rs @@ -364,7 +364,8 @@ impl BuilderMap { } /// What a merge needs of each input besides the map: its outline as drawn ([`node_outline`]) and -/// whether its fill closes its open subpaths (Consider Open Filled Paths as Closed, and a fill). +/// whether its fill closes its open subpaths (Consider Open Filled Paths as Closed, and a fill row +/// that draws). #[derive(Clone, Debug, PartialEq)] pub struct MergeInput { pub outline: Option, @@ -375,7 +376,7 @@ pub struct MergeInput { pub fn merge_inputs(leaves: &[&Node], open_filled_as_closed: bool) -> Vec { leaves .iter() - .map(|l| MergeInput { outline: node_outline(l).map(|o| o.0), fill_closes: open_filled_as_closed && !l.appearance.fill_paint().is_none() }) + .map(|l| MergeInput { outline: node_outline(l).map(|o| o.0), fill_closes: open_filled_as_closed && l.appearance.has_drawn_fill() }) .collect() } diff --git a/crates/tools/src/builder/tests.rs b/crates/tools/src/builder/tests.rs index 90e4832771..66db1e550c 100644 --- a/crates/tools/src/builder/tests.rs +++ b/crates/tools/src/builder/tests.rs @@ -1124,6 +1124,287 @@ fn bucket_click_fills_face_and_shift_click_strokes_edge() { assert_eq!(id, "livePaint.strokeEdge"); } +/// A double-click runs a click's command with `scope: "connected"` and a triple-click with +/// `"samePaint"`, matching the paint the face or edge had before the first click there. +#[test] +fn bucket_double_and_triple_click_widen_what_a_click_paints() { + let (d, gid, f2, e) = live_group_doc(); + let red = vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)); + let mut painted = d.clone(); + painted.node_mut(f2).unwrap().appearance.set_fill(red.clone()); + painted.node_mut(e).unwrap().appearance.set_stroke(red.clone()); + let s = Selection::default(); + let p = paint(); + let (cx, later) = (cx(&d, &s, &p), cx(&painted, &s, &p)); + let face_before = serde_json::to_value(d.node(f2).unwrap().appearance.fill_paint()).unwrap(); + let edge_before = serde_json::to_value(d.node(e).unwrap().appearance.stroke_paint()).unwrap(); + let red_json = serde_json::to_value(&red).unwrap(); + assert_ne!(face_before, red_json); + assert_ne!(edge_before, red_json); + let fill = |scope: &str, like: Option<&Value>| { + let mut v = json!({ "group": gid.0, "point": [75.0, 25.0], "scope": scope }); + if let Some(like) = like { + v["match"] = like.clone(); + } + vec![Action::Exec("livePaint.fill".into(), v)] + }; + let click = |t: &mut LivePaintBucketTool, cx: &ToolContext, x: f64, m: Mods| { + t.pointer(cx, &ev(PointerKind::Down, x, 25.0).with_mods(m)); + t.pointer(cx, &ev(PointerKind::Up, x, 25.0).with_mods(m)); + }; + let mut t = LivePaintBucketTool::default(); + // The clicks paint the face as they arrive; the triple-click matches the fill from before them. + click(&mut t, &cx, 75.0, Mods::default()); + click(&mut t, &later, 75.0, Mods::default()); + assert_eq!(t.pointer(&later, &ev(PointerKind::DoubleClick, 75.0, 25.0)), fill("connected", None)); + click(&mut t, &later, 75.0, Mods::default()); + assert_eq!(t.pointer(&later, &ev(PointerKind::TripleClick, 75.0, 25.0)), fill("samePaint", Some(&face_before))); + // A new click there starts again from the fill it finds. + click(&mut t, &later, 75.0, Mods::default()); + assert_eq!(t.pointer(&later, &ev(PointerKind::TripleClick, 75.0, 25.0)), fill("samePaint", Some(&red_json))); + // A click before the triple-click's own three is not part of it. + let mut t = LivePaintBucketTool::default(); + click(&mut t, &cx, 75.0, Mods::default()); + for _ in 0..3 { + click(&mut t, &later, 75.0, Mods::default()); + } + assert_eq!(t.pointer(&later, &ev(PointerKind::TripleClick, 75.0, 25.0)), fill("samePaint", Some(&red_json))); + // Shift: the edge, matching its stroke from before the first click. + let shift = Mods { shift: true, ..Default::default() }; + let stroke = |scope: &str, like: &Value| { + vec![Action::Exec( + "livePaint.strokeEdge".into(), + json!({ "group": gid.0, "point": [51.0, 25.0], "tolerance": 4.0, "scope": scope, "match": like }), + )] + }; + click(&mut t, &cx, 51.0, shift); + click(&mut t, &later, 51.0, shift); + assert_eq!(t.pointer(&later, &ev(PointerKind::DoubleClick, 51.0, 25.0).with_mods(shift)), stroke("connected", &edge_before)); + click(&mut t, &later, 51.0, shift); + assert_eq!(t.pointer(&later, &ev(PointerKind::TripleClick, 51.0, 25.0).with_mods(shift)), stroke("samePaint", &edge_before)); + // With Alt or Space held, or with both options off, a double-click or triple-click paints nothing. + let alt = Mods { alt: true, ..Default::default() }; + let space = Mods { space: true, ..Default::default() }; + for k in [PointerKind::DoubleClick, PointerKind::TripleClick] { + assert!(t.pointer(&cx, &ev(k, 75.0, 25.0).with_mods(alt)).is_empty(), "{k:?}"); + assert!(t.pointer(&cx, &ev(k, 75.0, 25.0).with_mods(Mods { cmd: true, ..Default::default() })).is_empty(), "{k:?} with Cmd"); + assert!(t.pointer(&cx, &ev(k, 75.0, 25.0).with_mods(space)).is_empty(), "{k:?} with Space"); + assert!(t.pointer(&cx, &ev(k, 51.0, 25.0).with_mods(Mods { shift: true, ..space })).is_empty(), "{k:?} with Shift and Space"); + } + // A press with Space held paints nothing either. + for m in [space, Mods { shift: true, ..space }] { + for (k, x) in [(PointerKind::Down, 75.0), (PointerKind::Up, 75.0), (PointerKind::Down, 51.0), (PointerKind::Up, 51.0)] { + assert!(t.pointer(&cx, &ev(k, x, 25.0).with_mods(m)).is_empty(), "{k:?} at {x} with {m:?}"); + } + } + t.set_option("paintFills", &json!(false)); + for k in [PointerKind::DoubleClick, PointerKind::TripleClick] { + assert!(t.pointer(&cx, &ev(k, 75.0, 25.0)).is_empty(), "{k:?}"); + } + // Outside every face, nothing is painted. + t.set_option("paintFills", &json!(true)); + assert!(t.pointer(&cx, &ev(PointerKind::DoubleClick, 400.0, 400.0)).is_empty()); +} + +/// A triple-click whose third click lands on a face the double-click's flood filled matches that +/// face's fill from before the double-click. +#[test] +fn bucket_triple_click_on_a_face_the_double_click_flooded_matches_its_earlier_fill() { + let (mut d, gid, f2, _) = live_group_doc(); + let red = vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)); + let blue = vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0)); + let f1 = crate::builder::face_at(d.node(gid).unwrap(), Point::new(25.0, 25.0)).unwrap().id; + for f in [f1, f2] { + d.node_mut(f).unwrap().appearance.set_fill(red.clone()); + } + let mut first = d.clone(); + first.node_mut(f1).unwrap().appearance.set_fill(blue.clone()); + let mut flooded = first.clone(); + flooded.node_mut(f2).unwrap().appearance.set_fill(blue.clone()); + let s = Selection::default(); + let p = paint(); + let (start, first, flooded) = (cx(&d, &s, &p), cx(&first, &s, &p), cx(&flooded, &s, &p)); + let mut t = LivePaintBucketTool::default(); + let click = |t: &mut LivePaintBucketTool, cx: &ToolContext, x: f64| { + t.pointer(cx, &ev(PointerKind::Down, x, 25.0)); + t.pointer(cx, &ev(PointerKind::Up, x, 25.0)); + }; + click(&mut t, &start, 25.0); + click(&mut t, &first, 25.0); + t.pointer(&first, &ev(PointerKind::DoubleClick, 25.0, 25.0)); + click(&mut t, &flooded, 75.0); + let like = serde_json::to_value(&red).unwrap(); + assert_eq!( + t.pointer(&flooded, &ev(PointerKind::TripleClick, 75.0, 25.0)), + vec![Action::Exec("livePaint.fill".into(), json!({ "group": gid.0, "point": [75.0, 25.0], "scope": "samePaint", "match": like }))] + ); +} + +/// On an edge that stores a stroke paint but draws none (its stroke hidden, or the edge fully +/// transparent), a double-click or triple-click matches no paint, with or without the clicks +/// before it. +#[test] +fn bucket_multi_click_on_an_edge_matches_the_paint_it_draws() { + let (mut d, gid, _, e) = live_group_doc(); + d.node_mut(e).unwrap().appearance.set_stroke(vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 0.0))); + let mut hidden = d.clone(); + hidden.node_mut(e).unwrap().appearance.stroke_mut().unwrap().visible = false; + let mut clear = d.clone(); + clear.node_mut(e).unwrap().opacity = 0.0; + let none = serde_json::to_value(vectorcraft_color::Paint::None).unwrap(); + let s = Selection::default(); + let p = paint(); + let shift = Mods { shift: true, ..Default::default() }; + let stroke = |scope: &str| { + vec![Action::Exec( + "livePaint.strokeEdge".into(), + json!({ "group": gid.0, "point": [51.0, 25.0], "tolerance": 4.0, "scope": scope, "match": none }), + )] + }; + for doc in [&hidden, &clear] { + let cx = cx(doc, &s, &p); + let mut t = LivePaintBucketTool::default(); + assert_eq!(t.pointer(&cx, &ev(PointerKind::DoubleClick, 51.0, 25.0).with_mods(shift)), stroke("connected")); + for _ in 0..3 { + t.pointer(&cx, &ev(PointerKind::Down, 51.0, 25.0).with_mods(shift)); + t.pointer(&cx, &ev(PointerKind::Up, 51.0, 25.0).with_mods(shift)); + } + assert_eq!(t.pointer(&cx, &ev(PointerKind::TripleClick, 51.0, 25.0).with_mods(shift)), stroke("samePaint")); + } +} + +/// A triple-click whose first click makes the Live Paint group matches the fill of the face the +/// group makes there: an open path in front, whose outline bounds no face, does not give it. +#[test] +fn bucket_triple_click_on_a_made_group_skips_open_paths() { + use vectorcraft_color::{Color, Paint}; + use vectorcraft_geom::{PathData, SubPath}; + let (red, blue) = (Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 0.0, 1.0))); + let mut d = Document::new(500.0, 500.0); + let l = d.layers[0].id; + let back = d.alloc_id(); + let mut look = Appearance::default_art(); + look.set_fill(red.clone()); + d.insert(Some(l), 0, Node::path(back, shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), look)).unwrap(); + // An open U around (75, 25), filled blue. + let u = [Point::new(60.0, 5.0), Point::new(60.0, 45.0), Point::new(90.0, 45.0), Point::new(90.0, 5.0)]; + let front = d.alloc_id(); + let mut look = Appearance::default_art(); + look.set_fill(blue); + d.insert(Some(l), 1, Node::path(front, PathData::single(SubPath::polyline(&u, false)), look)).unwrap(); + // The face the planar map makes there takes its fill from the square, as the group's would. + let shapes: Vec = [back, front] + .iter() + .enumerate() + .filter_map(|(k, id)| node_outline(d.node(*id)?).map(|(path, rule)| vectorcraft_pathops::Shape::new(path, rule, k as u64))) + .collect(); + let (regions, _) = vectorcraft_pathops::live_paint(&shapes); + let face = regions.iter().find(|r| r.contains(Point::new(75.0, 25.0))).expect("a face at (75, 25)"); + assert_eq!(face.top(), Some(0), "the square is the face's top shape"); + let mut s = Selection::default(); + s.set([back, front]); + let p = paint(); + let (made, ..) = live_group_doc(); + let none = Selection::default(); + let (cx, later) = (cx(&d, &s, &p), cx(&made, &none, &p)); + let mut t = LivePaintBucketTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, 75.0, 25.0)); + t.pointer(&cx, &ev(PointerKind::Up, 75.0, 25.0)); + for _ in 0..2 { + t.pointer(&later, &ev(PointerKind::Down, 75.0, 25.0)); + t.pointer(&later, &ev(PointerKind::Up, 75.0, 25.0)); + } + let acts = t.pointer(&later, &ev(PointerKind::TripleClick, 75.0, 25.0)); + let [Action::Exec(id, v)] = acts.as_slice() else { panic!("{acts:?}") }; + assert_eq!(id, "livePaint.fill"); + assert_eq!(v["match"], serde_json::to_value(&red).unwrap()); +} + +/// A triple-click whose first click makes the Live Paint group on one face and whose other two +/// clicks fill another face matches the fill the second face had before the first click on it, +/// not the fill under the first click or the fill the clicks gave it. +#[test] +fn bucket_triple_click_after_making_the_group_on_another_face_matches_its_own_face() { + use vectorcraft_color::{Color, Paint}; + let (red, blue) = (Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 0.0, 1.0))); + let mut d = Document::new(500.0, 500.0); + let l = d.layers[0].id; + let square = d.alloc_id(); + let mut look = Appearance::default_art(); + look.set_fill(red.clone()); + d.insert(Some(l), 0, Node::path(square, shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 50.0)), look)).unwrap(); + let mut s = Selection::default(); + s.set([square]); + let p = paint(); + let (made, _, f2, _) = live_group_doc(); + let mut painted = made.clone(); + painted.node_mut(f2).unwrap().appearance.set_fill(blue.clone()); + let none = Selection::default(); + let (cx, later, after) = (cx(&d, &s, &p), cx(&made, &none, &p), cx(&painted, &none, &p)); + let mut t = LivePaintBucketTool::default(); + // The first click makes the group and fills the face at (25, 25); the next two fill (75, 25), + // the first of them painting it blue. + t.pointer(&cx, &ev(PointerKind::Down, 25.0, 25.0)); + t.pointer(&cx, &ev(PointerKind::Up, 25.0, 25.0)); + for ctx in [&later, &after] { + t.pointer(ctx, &ev(PointerKind::Down, 75.0, 25.0)); + t.pointer(ctx, &ev(PointerKind::Up, 75.0, 25.0)); + } + let acts = t.pointer(&after, &ev(PointerKind::TripleClick, 75.0, 25.0)); + let [Action::Exec(id, v)] = acts.as_slice() else { panic!("{acts:?}") }; + assert_eq!(id, "livePaint.fill"); + let own = serde_json::to_value(made.node(f2).unwrap().appearance.fill_paint()).unwrap(); + assert_ne!(own, serde_json::to_value(&red).unwrap()); + assert_ne!(own, serde_json::to_value(&blue).unwrap()); + assert_eq!(v["match"], own); +} + +/// A triple-click whose clicks land on one face, another face, then the first face again matches +/// the fill the first face had before the first click on it, not the fill that click gave it. +#[test] +fn bucket_triple_click_with_a_click_on_another_face_between_matches_the_first_fill() { + use vectorcraft_color::{Color, Paint}; + let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + let (d, gid, f2, _) = live_group_doc(); + let mut painted = d.clone(); + painted.node_mut(f2).unwrap().appearance.set_fill(red.clone()); + let s = Selection::default(); + let p = paint(); + let (cx, later) = (cx(&d, &s, &p), cx(&painted, &s, &p)); + let mut t = LivePaintBucketTool::default(); + // The first click paints the face at (75, 25) red; the second fills the face at (25, 25). + for (ctx, x) in [(&cx, 75.0), (&later, 25.0), (&later, 75.0)] { + t.pointer(ctx, &ev(PointerKind::Down, x, 25.0)); + t.pointer(ctx, &ev(PointerKind::Up, x, 25.0)); + } + let acts = t.pointer(&later, &ev(PointerKind::TripleClick, 75.0, 25.0)); + let own = serde_json::to_value(d.node(f2).unwrap().appearance.fill_paint()).unwrap(); + assert_ne!(own, serde_json::to_value(&red).unwrap()); + assert_eq!( + acts, + vec![Action::Exec("livePaint.fill".into(), json!({ "group": gid.0, "point": [75.0, 25.0], "scope": "samePaint", "match": own }))] + ); +} + +/// With Space held for the view tools, the pointer outlines no face or edge, as a press there +/// paints nothing. +#[test] +fn bucket_highlights_nothing_with_space_held() { + let (d, ..) = live_group_doc(); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = LivePaintBucketTool::default(); + let outlined = |t: &LivePaintBucketTool| t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Path { .. })); + let space = Mods { space: true, ..Default::default() }; + for (x, m) in [(75.0, space), (51.0, Mods { shift: true, ..space })] { + t.pointer(&cx, &ev(PointerKind::Move, x, 25.0).with_mods(m)); + assert!(!outlined(&t), "at {x} with {m:?}"); + } + t.pointer(&cx, &ev(PointerKind::Move, 75.0, 25.0)); + assert!(outlined(&t)); +} + /// After a fill drag, the cursor swatch preview shows at the release point, not where the pointer /// last moved before the press. #[test] @@ -1733,6 +2014,599 @@ 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!({}))]); } +/// A Live Paint group of three faces in a row, A (0..50), B (50..100) and C (100..150), 50 pt tall, +/// with these edges: AB between A and B, with no stroke; BC between B and C, stroked red; the tops +/// of A and B stroked black; the top of C stroked red; and one bottom edge under all three, +/// stroked black. Returns the group, the faces [A, B, C] and the edges [AB, BC, top A, top B, +/// top C, bottom]. +fn live_strip(d: &mut Document) -> (NodeId, [NodeId; 3], [NodeId; 6]) { + let l = d.layers[0].id; + let black = Paint::solid(vectorcraft_color::Color::BLACK); + let red = Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)); + let mut kids = vec![empty_sources(d)]; + let mut fs = [NodeId(0); 3]; + for (k, x) in [0.0, 50.0, 100.0].into_iter().enumerate() { + fs[k] = d.alloc_id(); + let mut face = Node::path(fs[k], shapes::rectangle(Rect::new(x, 0.0, x + 50.0, 50.0)), Appearance::default()); + face.name = Some(FACE_NAME.into()); + kids.push(Arc::new(face)); + } + let pt = Point::new; + let lines = [ + (pt(50.0, 0.0), pt(50.0, 50.0), None), + (pt(100.0, 0.0), pt(100.0, 50.0), Some(red.clone())), + (pt(0.0, 0.0), pt(50.0, 0.0), Some(black.clone())), + (pt(50.0, 0.0), pt(100.0, 0.0), Some(black.clone())), + (pt(100.0, 0.0), pt(150.0, 0.0), Some(red)), + (pt(0.0, 50.0), pt(150.0, 50.0), Some(black)), + ]; + let mut es = [NodeId(0); 6]; + for (k, (from, to, stroke)) in lines.into_iter().enumerate() { + es[k] = d.alloc_id(); + let mut a = Appearance::default(); + if let Some(s) = stroke { + a.set_stroke(s); + } + let mut edge = Node::path(es[k], shapes::line(from, to), a); + edge.name = Some(EDGE_NAME.into()); + kids.push(Arc::new(edge)); + } + let gid = d.alloc_id(); + let mut g = Node::group(gid, kids); + g.name = Some(LIVE_PAINT_NAME.into()); + let at = d.layers[0].children().map_or(0, |c| c.len()); + d.insert(Some(l), at, g).unwrap(); + (gid, fs, es) +} + +#[test] +fn live_paint_flood_crosses_unstroked_edges_and_stops_at_stroked_ones() { + let mut d = Document::new(500.0, 500.0); + let (g, [a, b, c], [ab, bc, ..]) = live_strip(&mut d); + let group = |d: &Document| d.node(g).unwrap().clone(); + assert_eq!(flood_faces(&group(&d), a), vec![a, b]); + assert_eq!(flood_faces(&group(&d), b), vec![b, a]); + assert_eq!(flood_faces(&group(&d), c), vec![c]); + // A hidden edge does not part the faces either; a hidden face is not reached and does not start + // a flood; an id that is not a face of the group reaches nothing. + let mut hidden = d.clone(); + hidden.node_mut(bc).unwrap().visible = false; + assert_eq!(flood_faces(&group(&hidden), a), vec![a, b, c]); + hidden.node_mut(b).unwrap().visible = false; + assert_eq!(flood_faces(&group(&hidden), a), vec![a]); + assert!(flood_faces(&group(&hidden), b).is_empty()); + assert!(flood_faces(&group(&d), ab).is_empty()); + // An edge whose stroke is hidden, 0 pt wide or fully transparent, or that is itself fully + // transparent, draws no stroke, so the flood crosses it. + use vectorcraft_doc::appearance::{AppearanceItem, StrokeLayer}; + let base = d.node(bc).unwrap().appearance.stroke().unwrap().clone(); + let changes: [fn(&mut StrokeLayer); 3] = [|s| s.visible = false, |s| s.width = 0.0, |s| s.opacity = 0.0]; + for change in changes { + let mut e = d.clone(); + let mut s = base.clone(); + change(&mut s); + e.node_mut(bc).unwrap().appearance.items.retain(|i| !matches!(i, AppearanceItem::Stroke(_))); + e.node_mut(bc).unwrap().appearance.items.push(AppearanceItem::Stroke(s)); + assert_eq!(flood_faces(&group(&e), a), vec![a, b, c]); + } + let mut e = d.clone(); + e.node_mut(bc).unwrap().opacity = 0.0; + assert_eq!(flood_faces(&group(&e), a), vec![a, b, c]); +} + +/// Faces P (0..50) and Q (50..100) above one edge from (0, 0) to (100, 0) and face R (0..100) below +/// it, with no edge between P and Q (as where a Gap Detection line parts them): P and Q each run +/// along part of the edge, and R along all of it. +#[test] +fn live_paint_flood_measures_faces_along_part_of_an_edge() { + let mut d = Document::new(500.0, 500.0); + let l = d.layers[0].id; + let mut kids = vec![empty_sources(&mut d)]; + let mut ids = [NodeId(0); 3]; + for (k, r) in [Rect::new(0.0, -50.0, 50.0, 0.0), Rect::new(50.0, -50.0, 100.0, 0.0), Rect::new(0.0, 0.0, 100.0, 50.0)].into_iter().enumerate() { + ids[k] = d.alloc_id(); + let mut face = Node::path(ids[k], shapes::rectangle(r), Appearance::default()); + face.name = Some(FACE_NAME.into()); + kids.push(Arc::new(face)); + } + let [p, q, r] = ids; + let mut edge = Node::path(d.alloc_id(), shapes::line(Point::new(0.0, 0.0), Point::new(100.0, 0.0)), Appearance::default()); + edge.name = Some(EDGE_NAME.into()); + kids.push(Arc::new(edge)); + let gid = d.alloc_id(); + let mut g = Node::group(gid, kids); + g.name = Some(LIVE_PAINT_NAME.into()); + d.insert(Some(l), 0, g).unwrap(); + let group = d.node(gid).unwrap().clone(); + // P reaches R across the edge, and Q through R; P and Q only touch at (50, 0). + assert_eq!(flood_faces(&group, p), vec![p, r, q]); + let mut without_r = d.clone(); + without_r.node_mut(r).unwrap().visible = false; + assert_eq!(flood_faces(without_r.node(gid).unwrap(), p), vec![p]); +} + +/// Face P (0..100) above unstroked edges along y = 0 split at `splits`, whose outline runs along +/// all of them with one segment, and below them one face between each two splits, the faces parted +/// from each other by stroked edges. A flood from any face below reaches P and, through it, the +/// others; this holds when the outline's middle is no edge's middle (30), is the end shared by two +/// edges (50), and is the middle of an edge shorter than the outline (25 and 75). +#[test] +fn live_paint_flood_crosses_an_outline_segment_that_spans_several_edges() { + for splits in [vec![30.0], vec![50.0], vec![25.0, 75.0]] { + let mut d = Document::new(500.0, 500.0); + let l = d.layers[0].id; + let mut kids = vec![empty_sources(&mut d)]; + let xs: Vec = std::iter::once(0.0).chain(splits.iter().copied()).chain(std::iter::once(100.0)).collect(); + let add_face = |d: &mut Document, kids: &mut Vec>, r: Rect| { + let id = d.alloc_id(); + let mut face = Node::path(id, shapes::rectangle(r), Appearance::default()); + face.name = Some(FACE_NAME.into()); + kids.push(Arc::new(face)); + id + }; + let p = add_face(&mut d, &mut kids, Rect::new(0.0, -50.0, 100.0, 0.0)); + let below: Vec = xs.windows(2).map(|w| add_face(&mut d, &mut kids, Rect::new(w[0], 0.0, w[1], 50.0))).collect(); + let pt = Point::new; + let lines = xs + .windows(2) + .map(|w| (pt(w[0], 0.0), pt(w[1], 0.0), false)) + .chain(splits.iter().map(|&x| (pt(x, 0.0), pt(x, 50.0), true))) + .collect::>(); + for (from, to, stroked) in lines { + let mut a = Appearance::default(); + if stroked { + a.set_stroke(Paint::solid(vectorcraft_color::Color::BLACK)); + } + let mut edge = Node::path(d.alloc_id(), shapes::line(from, to), a); + edge.name = Some(EDGE_NAME.into()); + kids.push(Arc::new(edge)); + } + let gid = d.alloc_id(); + let mut g = Node::group(gid, kids); + g.name = Some(LIVE_PAINT_NAME.into()); + d.insert(Some(l), 0, g).unwrap(); + let group = d.node(gid).unwrap().clone(); + let mut all = below.clone(); + all.push(p); + all.sort(); + for &f in &below { + let mut got = flood_faces(&group, f); + assert_eq!(got.first(), Some(&f), "{splits:?}"); + got.sort(); + assert_eq!(got, all, "{splits:?} from {f:?}"); + } + } +} + +/// A Live Paint group built from `paths` as `livePaint.make` builds one, with Gap Detection closing +/// gaps up to `gap` pt when given, and with no stroke on any edge. Returns the group and its faces. +fn live_from_paths(paths: Vec, gap: Option) -> (Node, Vec) { + let mut d = Document::new(500.0, 500.0); + let shapes: Vec = paths.into_iter().enumerate().map(|(k, p)| po::Shape::new(p, FillRule::NonZero, k as u64)).collect(); + let (regions, lines) = match gap { + Some(g) => { + let (r, e, _) = po::live_paint_with_gaps(&shapes, g); + (r, e) + } + None => po::live_paint(&shapes), + }; + let mut kids = vec![empty_sources(&mut d)]; + let mut ids = vec![]; + for r in regions { + let id = d.alloc_id(); + let mut face = Node::path(id, r.path, Appearance::default()); + face.name = Some(FACE_NAME.into()); + kids.push(Arc::new(face)); + ids.push(id); + } + for e in lines { + let mut edge = Node::path(d.alloc_id(), e.path, Appearance::default()); + edge.name = Some(EDGE_NAME.into()); + kids.push(Arc::new(edge)); + } + let mut g = Node::group(d.alloc_id(), kids); + g.name = Some(LIVE_PAINT_NAME.into()); + (g, ids) +} + +/// Live Paint groups built from curves, one with a T-junction where lines end inside an ellipse and +/// one with Gap Detection closing the gap between a curve's end and a circle: with no stroke on any +/// edge, a flood from any face reaches every face. +#[test] +fn live_paint_flood_crosses_unstroked_curves_in_built_groups() { + let pt = Point::new; + let frame = shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 200.0)); + let t_junction = vec![ + frame, + shapes::ellipse(Rect::new(50.0, 60.0, 150.0, 140.0)), + shapes::line(pt(113.0, 0.0), pt(113.0, 80.0)), + shapes::line(pt(113.0, 200.0), pt(113.0, 120.0)), + ]; + let a = |p: Point, h_in: Point, h_out: Point| vectorcraft_geom::Anchor { p, h_in, h_out, kind: vectorcraft_geom::AnchorKind::Smooth }; + let (start, end) = (pt(102.7, 20.0), pt(109.0, 100.0 + (2500.0f64 - 81.0).sqrt() - 2.0)); + let curve = PathData::single(SubPath::new( + vec![a(start, start, start + kurbo::Vec2::new(40.0, 40.0)), a(end, end + kurbo::Vec2::new(-30.0, -40.0), end)], + false, + )); + let gap = vec![shapes::ellipse(Rect::new(50.0, 50.0, 150.0, 150.0)), curve]; + for (name, paths, max_gap, count) in [("T-junction", t_junction, None, 3), ("Gap Detection", gap, Some(3.0), 2)] { + let (g, fs) = live_from_paths(paths, max_gap); + assert_eq!(fs.len(), count, "{name}"); + for &f in &fs { + let mut got = flood_faces(&g, f); + got.sort(); + assert_eq!(got, fs, "{name} from {f:?}"); + } + } +} + +/// A closed outline: `curve`, then straight lines through `rest` and back to the curve's start. +fn curve_then_lines(curve: kurbo::CubicBez, rest: &[Point]) -> PathData { + let a = |p: Point, h_in: Point, h_out: Point| vectorcraft_geom::Anchor { p, h_in, h_out, kind: vectorcraft_geom::AnchorKind::Corner }; + let mut anchors = vec![a(curve.p0, curve.p0, curve.p1), a(curve.p3, curve.p2, curve.p3)]; + anchors.extend(rest.iter().map(|&p| a(p, p, p))); + PathData::single(SubPath::new(anchors, true)) +} + +/// `c` with its two handles moved 0.006 pt along y: its ends stay put and its middle moves 0.0045 pt, +/// as a face outline refit within the planar map's precision can lie off its edge. +fn refit(c: kurbo::CubicBez) -> kurbo::CubicBez { + let up = kurbo::Vec2::new(0.0, 0.006); + kurbo::CubicBez::new(c.p0, c.p1 + up, c.p2 + up, c.p3) +} + +/// A Live Paint group of `faces` and of `lines`, each line with or without a stroke. Returns the +/// group and the ids of the faces. +fn live_of(faces: Vec, lines: Vec<(PathData, bool)>) -> (Node, Vec) { + let mut d = Document::new(500.0, 500.0); + let mut kids = vec![empty_sources(&mut d)]; + let mut ids = vec![]; + for pd in faces { + let id = d.alloc_id(); + let mut face = Node::path(id, pd, Appearance::default()); + face.name = Some(FACE_NAME.into()); + kids.push(Arc::new(face)); + ids.push(id); + } + for (pd, stroked) in lines { + let mut a = Appearance::default(); + if stroked { + a.set_stroke(Paint::solid(vectorcraft_color::Color::BLACK)); + } + let mut edge = Node::path(d.alloc_id(), pd, a); + edge.name = Some(EDGE_NAME.into()); + kids.push(Arc::new(edge)); + } + let mut g = Node::group(d.alloc_id(), kids); + g.name = Some(LIVE_PAINT_NAME.into()); + (g, ids) +} + +/// Faces whose outlines along an unstroked curved edge lie up to 0.0045 pt off it, as the planar map +/// can leave them when it refits an outline across a T-junction or, with Gap Detection on, builds the +/// faces and the edges from two maps: the flood still crosses the edge. Two faces that a gap parts +/// on the same side of the edge, which only touch, are still not joined. +#[test] +fn live_paint_flood_crosses_curved_edges_that_outlines_lie_slightly_off() { + use kurbo::ParamCurve; + let c = kurbo::CubicBez::new(Point::new(0.0, 0.0), Point::new(30.0, 40.0), Point::new(70.0, 40.0), Point::new(100.0, 0.0)); + let edge = |s: kurbo::CubicBez| { + let a = |p: Point, h_in: Point, h_out: Point| vectorcraft_geom::Anchor { p, h_in, h_out, kind: vectorcraft_geom::AnchorKind::Corner }; + PathData::single(SubPath::new(vec![a(s.p0, s.p0, s.p1), a(s.p3, s.p2, s.p3)], false)) + }; + // T-junction: a stroked line ends on the curve at t = 0.4 and parts the faces below it (L and R); + // the curve is two edges, and the face above (U) runs along both with one refit segment. + let j = c.eval(0.4); + let (left, right) = (c.subsegment(0.0..0.4), c.subsegment(0.4..1.0)); + let (g, ids) = live_of( + vec![ + curve_then_lines(left, &[Point::new(j.x, 80.0), Point::new(0.0, 80.0)]), + curve_then_lines(right, &[Point::new(100.0, 80.0), Point::new(j.x, 80.0)]), + curve_then_lines(refit(c), &[Point::new(100.0, -50.0), Point::new(0.0, -50.0)]), + ], + vec![(edge(left), false), (edge(right), false), (shapes::line(j, Point::new(j.x, 80.0)), true)], + ); + let [l, r, u] = [ids[0], ids[1], ids[2]]; + assert_eq!(flood_faces(&g, l), vec![l, u, r]); + let mut from_u = flood_faces(&g, u); + assert_eq!(from_u.first(), Some(&u)); + from_u.sort(); + assert_eq!(from_u, ids); + // Gap Detection: a gap line, which is no edge, parts P and Q above the curve at t = 0.5; the curve + // is one edge, and Q and the face below (B) run along it with refit segments. + let m = c.eval(0.5); + let (g, ids) = live_of( + vec![ + curve_then_lines(c.subsegment(0.0..0.5), &[Point::new(m.x, -50.0), Point::new(0.0, -50.0)]), + curve_then_lines(refit(c.subsegment(0.5..1.0)), &[Point::new(100.0, -50.0), Point::new(m.x, -50.0)]), + curve_then_lines(refit(c), &[Point::new(100.0, 80.0), Point::new(0.0, 80.0)]), + ], + vec![(edge(c), false)], + ); + let [p, q, b] = [ids[0], ids[1], ids[2]]; + assert_eq!(flood_faces(&g, p), vec![p, b, q]); + let mut without_b = g.clone(); + if let Some(kids) = without_b.children_mut() + && let Some(n) = kids.iter_mut().find(|n| n.id == b) + { + Arc::make_mut(n).visible = false; + } + assert_eq!(flood_faces(&without_b, p), vec![p]); +} + +/// Two large faces whose only shared edge, with no stroke, is 0.005 pt long: the flood crosses it. +#[test] +fn live_paint_flood_crosses_a_shared_edge_shorter_than_the_precision() { + let pt = Point::new; + let (a, b) = (pt(50.0, 0.0), pt(50.0, 0.005)); + let (g, ids) = live_of( + vec![ + PathData::single(SubPath::polyline(&[pt(0.0, -50.0), a, b, pt(0.0, 50.0)], true)), + PathData::single(SubPath::polyline(&[pt(100.0, -50.0), pt(100.0, 50.0), b, a], true)), + ], + vec![(shapes::line(a, b), false)], + ); + assert_eq!(flood_faces(&g, ids[0]), ids); +} + +/// A stroked edge along y = 0 and an edge with no stroke 0.008 pt below it, with a face above the +/// first whose outline ends on it and bows 0.005 pt off it in the middle, nearer the second, and a +/// face below the second: the stroked edge parts the two faces, so the flood does not join them. +#[test] +fn live_paint_flood_stops_where_a_stroked_edge_runs_along_an_unstroked_one() { + let pt = Point::new; + let bow = kurbo::CubicBez::new(pt(100.0, 0.0), pt(70.0, 0.02 / 3.0), pt(30.0, 0.02 / 3.0), pt(0.0, 0.0)); + let (g, ids) = live_of( + vec![ + curve_then_lines(bow, &[pt(0.0, -50.0), pt(100.0, -50.0)]), + PathData::single(SubPath::polyline(&[pt(0.0, 0.008), pt(0.0, 50.0), pt(100.0, 50.0), pt(100.0, 0.008)], true)), + ], + vec![(shapes::line(pt(0.0, 0.0), pt(100.0, 0.0)), true), (shapes::line(pt(0.0, 0.008), pt(100.0, 0.008)), false)], + ); + assert_eq!(flood_faces(&g, ids[0]), vec![ids[0]]); + assert_eq!(flood_faces(&g, ids[1]), vec![ids[1]]); +} + +/// An edge with no stroke from (10, 0) to (90, 0), and two faces that meet on a line 0.005 pt below +/// it from (0, 0.005) to (100, 0.005) (as a Gap Detection line): neither face runs along the edge, so +/// the flood does not join them. +#[test] +fn live_paint_flood_does_not_cross_an_edge_beside_a_line_two_faces_meet_on() { + let pt = Point::new; + let (a, b) = (pt(0.0, 0.005), pt(100.0, 0.005)); + let (g, ids) = live_of( + vec![ + PathData::single(SubPath::polyline(&[a, b, pt(100.0, -50.0), pt(0.0, -50.0)], true)), + PathData::single(SubPath::polyline(&[b, a, pt(0.0, 50.0), pt(100.0, 50.0)], true)), + ], + vec![(shapes::line(pt(10.0, 0.0), pt(90.0, 0.0)), false)], + ); + assert_eq!(flood_faces(&g, ids[0]), vec![ids[0]]); +} + +/// A stroked edge and an edge with no stroke that leave one point at a slope of 0.01, so they lie +/// within 0.01 pt of each other for their first point or so: the face between them and the face +/// beyond the edge with no stroke share that edge, so the flood joins them. +#[test] +fn live_paint_flood_crosses_an_unstroked_edge_beside_a_stroked_one() { + let pt = Point::new; + let (o, a, b) = (pt(0.0, 0.0), pt(100.0, 0.0), pt(100.0, 1.0)); + let (g, ids) = live_of( + vec![ + PathData::single(SubPath::polyline(&[o, a, b], true)), + PathData::single(SubPath::polyline(&[o, b, pt(100.0, 50.0), pt(0.0, 50.0)], true)), + ], + vec![(shapes::line(o, a), true), (shapes::line(o, b), false), (shapes::line(a, b), true)], + ); + assert_eq!(flood_faces(&g, ids[0]), ids); +} + +/// Two faces on either side of an edge with no stroke whose curve has a cusp at its middle (no +/// direction there): the flood crosses it. +#[test] +fn live_paint_flood_crosses_an_edge_with_a_cusp_at_its_middle() { + let c = kurbo::CubicBez::new(Point::new(0.0, 0.0), Point::new(100.0, 60.0), Point::new(0.0, 60.0), Point::new(100.0, 0.0)); + let a = |p: Point, h_in: Point, h_out: Point| vectorcraft_geom::Anchor { p, h_in, h_out, kind: vectorcraft_geom::AnchorKind::Corner }; + let edge = PathData::single(SubPath::new(vec![a(c.p0, c.p0, c.p1), a(c.p3, c.p2, c.p3)], false)); + let (g, ids) = live_of( + vec![ + curve_then_lines(c, &[Point::new(100.0, -50.0), Point::new(0.0, -50.0)]), + curve_then_lines(c, &[Point::new(100.0, 100.0), Point::new(0.0, 100.0)]), + ], + vec![(edge, false)], + ); + assert_eq!(flood_faces(&g, ids[0]), ids); +} + +/// Two faces parted by a line that is no edge (as a Gap Detection line), which crosses an edge with +/// no stroke: one 0.006 pt long, upright or at a slope of 0.1, and one 1 pt long at a slope of 0.09. +/// The faces only cross the edge and do not run along it, so the flood does not join them. +#[test] +fn live_paint_flood_does_not_cross_an_edge_an_outline_only_crosses() { + let pt = Point::new; + let short = pt(0.006, 0.0); + for (a, b, end) in + [(pt(0.003, -0.004), pt(0.003, 0.02), short), (pt(-0.037, -0.004), pt(0.043, 0.004), short), (pt(0.1, -0.009), pt(0.3, 0.009), pt(1.0, 0.0))] + { + let (g, ids) = live_of( + vec![ + PathData::single(SubPath::polyline(&[a, b, pt(-50.0, 50.0), pt(-50.0, -50.0)], true)), + PathData::single(SubPath::polyline(&[b, a, pt(50.0, -50.0), pt(50.0, 50.0)], true)), + ], + vec![(shapes::line(pt(0.0, 0.0), end), false)], + ); + assert_eq!(flood_faces(&g, ids[0]), vec![ids[0]], "{a:?} to {b:?}"); + } +} + +#[test] +fn live_paint_connected_edges_follow_the_same_stroke_paint() { + let mut d = Document::new(500.0, 500.0); + let (g, [a, ..], [ab, bc, top_a, top_b, top_c, bottom]) = live_strip(&mut d); + let group = d.node(g).unwrap().clone(); + let black = Paint::solid(vectorcraft_color::Color::BLACK); + let red = Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)); + // Top A and top B join end to end; top C joins them but is red, and the black bottom does not + // join them. + assert_eq!(connected_edges(&group, top_a, &black), vec![top_a, top_b]); + // BC and top C, both red, join at (100, 0). + assert_eq!(connected_edges(&group, bc, &red), vec![bc, top_c]); + assert_eq!(connected_edges(&group, bottom, &black), vec![bottom]); + // The edge started from is taken whatever its paint. + assert_eq!(connected_edges(&group, ab, &Paint::None), vec![ab]); + assert!(connected_edges(&group, a, &black).is_empty()); +} + +/// An edge from (0, 0) through (50, 0) to (100, 0) and a second edge with the same stroke from +/// (50, 0) to (50, 50): the second one ends at an anchor in the middle of the first, not at one of +/// its ends, so the two are not joined end to end. A third edge from (100, 0) is. +#[test] +fn live_paint_connected_edges_join_only_at_path_ends() { + let mut d = Document::new(500.0, 500.0); + let l = d.layers[0].id; + let black = Paint::solid(vectorcraft_color::Color::BLACK); + let mut kids = vec![empty_sources(&mut d)]; + let pt = Point::new; + let paths = [ + PathData::single(SubPath::polyline(&[pt(0.0, 0.0), pt(50.0, 0.0), pt(100.0, 0.0)], false)), + shapes::line(pt(50.0, 0.0), pt(50.0, 50.0)), + shapes::line(pt(100.0, 0.0), pt(100.0, 50.0)), + ]; + let mut ids = vec![]; + for pd in paths { + let mut a = Appearance::default(); + a.set_stroke(black.clone()); + let id = d.alloc_id(); + let mut edge = Node::path(id, pd, a); + edge.name = Some(EDGE_NAME.into()); + kids.push(Arc::new(edge)); + ids.push(id); + } + let gid = d.alloc_id(); + let mut g = Node::group(gid, kids); + g.name = Some(LIVE_PAINT_NAME.into()); + d.insert(Some(l), 0, g).unwrap(); + let group = d.node(gid).unwrap().clone(); + assert_eq!(connected_edges(&group, ids[0], &black), vec![ids[0], ids[2]]); + assert_eq!(connected_edges(&group, ids[1], &black), vec![ids[1]]); +} + +/// Three edges end to end along (0, 0) to (150, 0) under one face: a red one, one drawn red with a +/// hidden blue stroke over it, and one drawn blue with a hidden red stroke over it. Edges join by the +/// paint they draw with, not by a hidden stroke's paint, for `connected_edges` and a double-click. +#[test] +fn live_paint_connected_edges_follow_the_stroke_paint_they_draw_with() { + use vectorcraft_doc::appearance::{AppearanceItem, StrokeLayer}; + let mut d = Document::new(500.0, 500.0); + let l = d.layers[0].id; + let red = Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)); + let blue = Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0)); + let mut kids = vec![empty_sources(&mut d)]; + let fid = d.alloc_id(); + let mut face = Node::path(fid, shapes::rectangle(Rect::new(0.0, 0.0, 150.0, 50.0)), Appearance::default()); + face.name = Some(FACE_NAME.into()); + kids.push(Arc::new(face)); + let pt = Point::new; + let hidden = |p: &Paint| AppearanceItem::Stroke(StrokeLayer { visible: false, ..StrokeLayer::new(p.clone(), 1.0) }); + let shown = |p: &Paint| AppearanceItem::Stroke(StrokeLayer::new(p.clone(), 1.0)); + let edges = [(0.0, vec![shown(&red)]), (50.0, vec![shown(&red), hidden(&blue)]), (100.0, vec![shown(&blue), hidden(&red)])]; + let mut ids = vec![]; + for (x, items) in edges { + let id = d.alloc_id(); + let mut edge = Node::path(id, shapes::line(pt(x, 0.0), pt(x + 50.0, 0.0)), Appearance { items, ..Appearance::default() }); + edge.name = Some(EDGE_NAME.into()); + kids.push(Arc::new(edge)); + ids.push(id); + } + let gid = d.alloc_id(); + let mut g = Node::group(gid, kids); + g.name = Some(LIVE_PAINT_NAME.into()); + d.insert(Some(l), 0, g).unwrap(); + let group = d.node(gid).unwrap().clone(); + assert_eq!(connected_edges(&group, ids[0], &red), vec![ids[0], ids[1]]); + assert_eq!(connected_edges(&group, ids[2], &blue), vec![ids[2]]); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let set = |ids: &[NodeId]| vec![Action::Exec("select.set".into(), json!({ "ids": ids.iter().map(|i| i.0).collect::>() }))]; + let alt = Mods { alt: true, ..Default::default() }; + let mut t = LivePaintSelectionTool::default(); + let mut dbl = |x: f64| t.pointer(&cx, &ev(PointerKind::DoubleClick, x, 1.0).with_mods(alt)); + assert_eq!(dbl(75.0), set(&[ids[1], ids[0]])); + assert_eq!(dbl(125.0), set(&[ids[2]])); +} + +#[test] +fn live_paint_selection_double_click_selects_connected_faces_or_edges() { + let mut d = Document::new(500.0, 500.0); + let (_, [a, b, c], [_, _, top_a, top_b, ..]) = live_strip(&mut d); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let set = |ids: &[NodeId]| vec![Action::Exec("select.set".into(), json!({ "ids": ids.iter().map(|i| i.0).collect::>() }))]; + let toggle = |ids: &[NodeId]| vec![Action::Exec("select.toggle".into(), json!({ "ids": ids.iter().map(|i| i.0).collect::>() }))]; + let alt = Mods { alt: true, ..Default::default() }; + let shift = Mods { shift: true, ..Default::default() }; + let dbl = |t: &mut LivePaintSelectionTool, x: f64, y: f64, m: Mods| t.pointer(&cx, &ev(PointerKind::DoubleClick, x, y).with_mods(m)); + let mut t = LivePaintSelectionTool::default(); + // A face: the faces not parted from it by a stroked edge. + assert_eq!(dbl(&mut t, 25.0, 25.0, Mods::default()), set(&[a, b])); + assert_eq!(dbl(&mut t, 125.0, 25.0, Mods::default()), set(&[c])); + // An edge (Alt): the edges joined to it end to end with its stroke paint. + assert_eq!(dbl(&mut t, 25.0, 1.0, alt), set(&[top_a, top_b])); + // With Shift held, the parts reached leave the selection or join it. + assert_eq!(dbl(&mut t, 75.0, 25.0, shift), toggle(&[b, a])); + assert_eq!(dbl(&mut t, 75.0, 1.0, Mods { alt: true, shift: true, ..Default::default() }), toggle(&[top_b, top_a])); + // Away from the group, a double-click adds nothing to what its clicks did. + assert!(dbl(&mut t, 300.0, 300.0, Mods::default()).is_empty()); + // Select Fills off: the double-click picks the edge nearest the pointer as a click does. + t.set_option("selectFills", &json!(false)); + assert_eq!(dbl(&mut t, 25.0, 1.0, Mods::default()), set(&[top_a, top_b])); + assert!(dbl(&mut t, 25.0, 25.0, Mods::default()).is_empty()); + // Select Strokes off: Alt picks the face. + t.set_option("selectFills", &json!(true)); + t.set_option("selectStrokes", &json!(false)); + assert_eq!(dbl(&mut t, 25.0, 1.0, alt), set(&[a, b])); + // Both off: nothing. + t.set_option("selectFills", &json!(false)); + assert!(dbl(&mut t, 25.0, 25.0, Mods::default()).is_empty()); + assert!(dbl(&mut t, 25.0, 1.0, alt).is_empty()); +} + +#[test] +fn live_paint_selection_triple_click_adds_nothing_to_its_clicks() { + let mut d = Document::new(500.0, 500.0); + let (_, [a, ..], _) = live_strip(&mut d); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = LivePaintSelectionTool::default(); + // The third click's press and release select the face under the pointer, as a click does. + assert_eq!(lp_click(&mut t, &cx, ev(PointerKind::Down, 25.0, 25.0)), vec![Action::Exec("select.set".into(), json!({ "ids": [a.0] }))]); + for m in [Mods::default(), Mods { alt: true, ..Default::default() }, Mods { shift: true, ..Default::default() }] { + assert!(t.pointer(&cx, &ev(PointerKind::TripleClick, 25.0, 25.0).with_mods(m)).is_empty()); + assert!(t.pointer(&cx, &ev(PointerKind::TripleClick, 25.0, 1.0).with_mods(m)).is_empty()); + } +} + +#[test] +fn live_paint_selection_double_click_skips_locked_groups_and_art_outside_isolation() { + let mut d = Document::new(500.0, 500.0); + let (g, _, _) = live_strip(&mut d); + let (other, _) = live_square(&mut d, Rect::new(200.0, 0.0, 300.0, 100.0)); + let s = Selection::default(); + let p = paint(); + let dbl = |d: &Document, iso: Option, x: f64| { + let cx = ToolContext { isolation: iso, ..cx(d, &s, &p) }; + LivePaintSelectionTool::default().pointer(&cx, &ev(PointerKind::DoubleClick, x, 25.0)) + }; + assert!(!dbl(&d, None, 25.0).is_empty()); + assert!(dbl(&d, Some(other), 25.0).is_empty(), "outside the isolated art"); + d.node_mut(g).unwrap().locked = true; + assert!(dbl(&d, None, 25.0).is_empty(), "a locked group"); + assert!(!dbl(&d, None, 250.0).is_empty()); +} + /// 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 diff --git a/crates/tools/src/context.rs b/crates/tools/src/context.rs index e6db6069c7..1e8f57ffc9 100644 --- a/crates/tools/src/context.rs +++ b/crates/tools/src/context.rs @@ -329,6 +329,8 @@ pub struct ToolContext<'a> { pub screen: Option, /// Where the Plane Switching Widget sits (Perspective Grid Options); None while it's hidden. pub plane_widget: Option, + /// What Automatic Plane Positioning takes a point from (Perspective Grid Options). + pub plane_targets: distort::perspective::widget::PlaneTargets, /// General › Use Precise Cursors, or Caps Lock while it is on: the drawing tools' pointers are /// crosshairs ([`crate::Cursor::precise`]), and the Blob Brush and the Eraser show no tip outline. pub precise_cursors: bool, diff --git a/crates/tools/src/cropimage.rs b/crates/tools/src/cropimage.rs index ff716bf171..0245f75112 100644 --- a/crates/tools/src/cropimage.rs +++ b/crates/tools/src/cropimage.rs @@ -169,6 +169,7 @@ impl Tool for CropImageTool { PointerKind::Up => self.drag = None, PointerKind::DoubleClick => return self.apply(cx), PointerKind::Move => self.last = ev.pos, + PointerKind::TripleClick => {} } vec![] } diff --git a/crates/tools/src/cursor.rs b/crates/tools/src/cursor.rs index 584149da8f..85b9cf258e 100644 --- a/crates/tools/src/cursor.rs +++ b/crates/tools/src/cursor.rs @@ -110,14 +110,16 @@ pub enum Cursor { /// The Pencil tool with Alt pressed after the drag starts and Alt key toggles to Smooth Tool off: /// releasing the mouse button with Alt still held closes the path. A drag started with Shift or /// Alt held draws an open straight line instead. Also while a freehand stroke is drawn back near - /// its start, where releasing the mouse button closes the path. A crosshair with a ring. + /// its start, or a stroke continuing a selected path near that path's other end, where + /// releasing the mouse button closes the path. A crosshair with a ring. PencilClose, /// The Pencil tool before a press that draws a straight line (Shift or Alt held). A crosshair with a - /// short straight line. + /// short level line. PencilStraight, - /// The Pencil tool before a press that draws a straight line (Shift or Alt held), over an end of - /// a selected open path: the line continues the path from that end. A crosshair with a short - /// straight line leaving a square end point. + /// The Pencil tool before a press over an end of a selected open path: the stroke, freehand or a + /// straight line, continues the path from that end. Also while a continuing stroke ends near an + /// open end of another path selected at the press, where releasing the mouse button connects the + /// two. A crosshair with a short line rising to the right. PencilContinue, /// The Paintbrush tool. Paintbrush, diff --git a/crates/tools/src/cursors.toml b/crates/tools/src/cursors.toml index 674ecebf60..51756bf0fd 100644 --- a/crates/tools/src/cursors.toml +++ b/crates/tools/src/cursors.toml @@ -629,7 +629,9 @@ hotspot = "The lead tip." [[cursor]] id = "PencilNew" group = "Drawing and editing tools" -shown_when = ["The Pencil tool before a press that draws a new freehand path: the pointer is not within Edit Selected Paths of a selected path that the press would continue from an end or redraw. Over such a path, and while a stroke is drawn, the Pencil cursor has no star."] +shown_when = [ + "The Pencil tool before a press that draws a new freehand path: the pointer is not within Edit Selected Paths of a selected path that the press would continue from an end or redraw. Over such a path, and while a stroke is drawn, the Pencil cursor has no star.", +] hotspot = "The lead tip." look = "The Pencil cursor with a small star badge, where PencilClose has its ring." @@ -639,6 +641,7 @@ group = "Drawing and editing tools" shown_when = [ "The Pencil tool with Alt pressed after the drag starts, when Alt key toggles to Smooth Tool is off: releasing the mouse button with Alt still held closes the path. A drag started with Shift or Alt held draws an open straight line and does not show this cursor.", "The Pencil tool while a freehand stroke is drawn back to within Close Paths When Ends Are Within of its start: releasing the mouse button there closes the path.", + "The Pencil tool while a stroke continuing a selected open path, freehand or a straight line, is drawn to within Close Paths When Ends Are Within of that path's other end: releasing the mouse button there closes the path.", ] hotspot = "The lead tip." look = "The Pencil cursor with a ring badge (closing the loop), like PenClose." @@ -646,16 +649,21 @@ look = "The Pencil cursor with a ring badge (closing the loop), like PenClose." [[cursor]] id = "PencilStraight" group = "Drawing and editing tools" -shown_when = ["The Pencil tool with Shift or Alt held before a press, except with Alt held when Alt key toggles to Smooth Tool is on: the press draws a straight line, at 45° steps from the Constrain Angle when Shift is held and at any angle with Alt alone."] +shown_when = [ + "The Pencil tool with Shift or Alt held before a press, except with Alt held when Alt key toggles to Smooth Tool is on: the press draws a straight line, at 45° steps from the Constrain Angle when Shift is held and at any angle with Alt alone.", +] hotspot = "The lead tip." -look = "The Pencil cursor with a short straight-line badge, where PencilClose has its ring." +look = "The Pencil cursor with a short level-line badge, where PencilClose has its ring." [[cursor]] id = "PencilContinue" group = "Drawing and editing tools" -shown_when = ["The Pencil tool over an end of a selected open path, within Edit Selected Paths, with Shift or Alt held before a press, except with Alt held when Alt key toggles to Smooth Tool is on: the press draws a straight line that continues the path from that end."] +shown_when = [ + "The Pencil tool over an end of a selected open path, within Edit Selected Paths, before a press, except with Alt held when Alt key toggles to Smooth Tool is on: the press continues the path from that end, freehand, or with a straight line when Shift or Alt is held.", + "The Pencil tool while a stroke continuing a selected path ends within Edit Selected Paths of an open end of another path selected at the press: releasing the mouse button connects the two.", +] hotspot = "The lead tip." -look = "PencilStraight's badge with a small filled square at the line's lower end (the end point the line continues from)." +look = "The Pencil cursor with a short badge line rising to the right, where PencilClose has its ring (the stroke carries on from the path)." [[cursor]] id = "Paintbrush" diff --git a/crates/tools/src/dimension.rs b/crates/tools/src/dimension.rs index ff99091153..3f8da166e4 100644 --- a/crates/tools/src/dimension.rs +++ b/crates/tools/src/dimension.rs @@ -240,12 +240,18 @@ fn points_source(cx: &ToolContext, (a, ra): (Point, &Option), (b, rb): impl DimensionTool { /// Where a Linear pick at `p` lands: on the nearest anchor of any path, within reach (kept as /// a link to its path); else where Smart Guides put it (another object's anchor or centre, in - /// line with one, or for the second point on a construction guide through the first), its - /// guides showing; else on the closest point of the line under the pointer; else `p` itself. + /// line with one, or for the second point square to a segment or grazing a curve from the + /// first with Snap to Perpendicular or Snap to Tangent on, or on a construction guide through + /// a first point picked on an anchor), its guides showing; else on the closest point of the + /// line under the pointer; else `p` itself. A first point not on an anchor has no + /// construction guides through it. /// A point the guides leave where the pointer is (right on a guide line) stays there, and with /// Snap to Pixel or Snap to Grid on a point stays where they place it. fn snap_linear(&mut self, cx: &ToolContext, p: Point) -> (Point, Option) { - let leave = self.points.last().map(|(first, _)| crate::guides::Leave::segment(cx, *first, false)); + let leave = self.points.last().map(|(first, anchor)| match anchor { + Some(_) => crate::guides::Leave::segment(cx, *first, false), + None => crate::guides::Leave::contact(*first), + }); let guided = self.snap.hover(cx, p, &[], leave.as_ref()); if let Some((point, reference)) = anchor_under(cx, p) { self.snap.clear(); @@ -902,10 +908,11 @@ mod tests { } } - /// A point that Smart Guides leave where the pointer already is (the pointer right on a - /// construction guide or in line with a target) stays on the guide the overlays show. It - /// does not move to the nearest point of a segment within the pick's reach. Off the guides, - /// a point near a segment still lands on it. + /// A point that Smart Guides leave where the pointer already is (the pointer right in line + /// with a target) stays on the guide the overlays show. It does not move to the nearest point + /// of a segment within the pick's reach. Off the guides, a point near a segment still lands + /// on it, also straight below the first point: the second point has no construction guide + /// through a first point that is not on an anchor. #[test] fn a_point_on_a_guide_stays_on_the_guide() { let (d, _) = doc_with_rect(); @@ -923,17 +930,22 @@ mod tests { // Off the guides, beside the edge: the closest point of the edge. let (on_edge, reference) = t.snap_linear(&c, Point::new(206.0, 170.5)); assert!(on_edge.distance(Point::new(200.0, 170.5)) < 1e-4 && reference.is_none(), "{on_edge:?}"); - // The first point, above the rectangle, then straight down along the vertical - // construction guide through it, past the right edge. + // The first point, above the rectangle, then straight down past the right edge: no + // vertical guide through the first point holds the second, so beside the edge it lands + // on the edge, and in line with the center it stays in line. click(&mut t, 206.0, 50.0); assert_eq!(t.points, vec![(Point::new(206.0, 50.0), None)]); - for y in [150.0, 170.5, 190.0] { - assert_eq!(t.snap_linear(&c, Point::new(206.0, y)), (Point::new(206.0, y), None), "on the construction guide at y = {y}"); - assert!(!t.snap.guides().is_empty()); + for y in [170.5, 190.0] { + let (q, reference) = t.snap_linear(&c, Point::new(206.0, y)); + assert!(q.distance(Point::new(200.0, y)) < 1e-4 && reference.is_none(), "beside the edge at y = {y}: {q:?}"); } - click(&mut t, 206.0, 170.5); + assert_eq!(t.snap_linear(&c, Point::new(207.0, 300.0)), (Point::new(207.0, 300.0), None), "away from the art"); + assert!(t.snap.guides().is_empty()); + assert_eq!(t.snap_linear(&c, Point::new(206.0, 150.0)), (Point::new(206.0, 150.0), None)); + assert!(!t.snap.guides().is_empty()); + click(&mut t, 206.0, 150.0); let dim = t.pending.as_ref().expect("both points were picked"); - assert_eq!((dim.a, dim.b), (Point::new(206.0, 50.0), Point::new(206.0, 170.5))); + assert_eq!((dim.a, dim.b), (Point::new(206.0, 50.0), Point::new(206.0, 150.0))); // The second point, off the edge, is held against the rectangle's anchors. let Some(DimensionSource::Points { free_b: Some(free), .. }) = &dim.source else { panic!("{:?}", dim.source) }; assert!(matches!(free, FreePoint::Anchors { .. }), "{free:?}"); @@ -950,6 +962,82 @@ mod tests { assert_eq!(DimensionTool::default().snap_linear(&pixel, Point::new(206.0, 170.0)), (Point::new(206.0, 170.0), None)); } + /// After a first point that is not on an anchor, the second point still lands where the line + /// from the first point meets a slanted segment square or grazes a curve, with the + /// "perpendicular" or "tangent" label, at places no construction guide through the first + /// point reaches. With Snap to Perpendicular and Snap to Tangent off it stays at the pointer. + #[test] + fn the_second_point_lands_square_to_a_segment_or_grazing_a_curve() { + use vectorcraft_doc::Appearance; + use vectorcraft_geom::{Rect, shapes}; + let (mut d, _) = doc_with_rect(); + let l = d.layers[0].id; + let (line, circle) = (d.alloc_id(), d.alloc_id()); + let slanted = shapes::line(Point::new(300.0, 100.0), Point::new(400.0, 150.0)); + d.insert(Some(l), 0, Node::path(line, slanted, Appearance::default_art())).unwrap(); + let round = shapes::ellipse(Rect::new(420.0, 370.0, 480.0, 430.0)); + d.insert(Some(l), 0, Node::path(circle, round, Appearance::default_art())).unwrap(); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + let first = Point::new(300.0, 250.0); + let picked = |c: &ToolContext| { + let mut t = DimensionTool::default(); + for kind in [PointerKind::Move, PointerKind::Down, PointerKind::Up] { + t.pointer(c, &PointerEvent::new(kind, first.x, first.y)); + } + assert_eq!(t.points, vec![(first, None)]); + t + }; + let labeled = |t: &DimensionTool, label: &str| t.snap.guides().iter().any(|o| matches!(o, Overlay::Label { text, .. } if text == label)); + // The foot of the perpendicular from (300, 250) to the line is (360, 130), along no + // construction guide angle from the first point. + let mut t = picked(&c); + let (q, reference) = t.snap_linear(&c, Point::new(361.0, 132.0)); + assert!(q.distance(Point::new(360.0, 130.0)) < 1e-4 && reference.is_none(), "{q:?}"); + assert!(labeled(&t, "perpendicular"), "{:?}", t.snap.guides()); + // Where a line from the first point grazes the circle about (450, 400), radius 30. + let (center, radius) = (Point::new(450.0, 400.0), 30.0); + let away = first - center; + let angle = away.y.atan2(away.x) + (radius / away.hypot()).acos(); + let touch = center + Vec2::new(angle.cos(), angle.sin()) * radius; + let (q, _) = t.snap_linear(&c, touch + Vec2::new(0.5, 0.5)); + assert!((q.distance(center) - radius).abs() < 0.05, "{q:?} is on the circle"); + assert!(((q - first).normalize().dot((q - center).normalize())).abs() < 0.01, "{q:?} grazes the circle"); + assert!(labeled(&t, "tangent"), "{:?}", t.snap.guides()); + // With both options off, the pointer near the foot lands on the closest point of the line + // instead. + let off = ToolContext { snap_perpendicular: false, snap_tangent: false, ..cx(&d, &s, &p) }; + let mut t = picked(&off); + let (q, _) = t.snap_linear(&off, Point::new(361.0, 132.0)); + assert!(q.distance(Point::new(360.0, 130.0)) > 0.5 && !labeled(&t, "perpendicular"), "{q:?}"); + } + + /// After a first point picked on an anchor, the second point still lands on the construction + /// guides through it. + #[test] + fn the_second_point_after_an_anchor_lands_on_construction_guides() { + let (d, id) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + let mut t = DimensionTool::default(); + for kind in [PointerKind::Move, PointerKind::Down, PointerKind::Up] { + t.pointer(&c, &PointerEvent::new(kind, 200.0, 200.0)); + } + assert_eq!(t.points, vec![(Point::new(200.0, 200.0), Some(PointRef { node: id, subpath: 0, anchor: 2 }))]); + // 1.5 units right and below the 45° guide up and to the right of the anchor. + let (q, reference) = t.snap_linear(&c, Point::new(331.0, 72.0)); + assert!(q.distance(Point::new(329.5, 70.5)) < 1e-4 && reference.is_none(), "{q:?}"); + assert!(!t.snap.guides().is_empty()); + // The same offset from a first point off the anchors stays at the pointer. + let mut t = DimensionTool::default(); + for kind in [PointerKind::Move, PointerKind::Down, PointerKind::Up] { + t.pointer(&c, &PointerEvent::new(kind, 240.0, 240.0)); + } + assert_eq!(t.points, vec![(Point::new(240.0, 240.0), None)]); + assert_eq!(t.snap_linear(&c, Point::new(371.0, 112.0)), (Point::new(371.0, 112.0), None)); + assert!(t.snap.guides().is_empty()); + } + #[test] fn placement_press_previews_without_a_prior_move() { let (d, _) = doc_with_rect(); diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index 3030414b38..69230dc050 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -55,7 +55,7 @@ use std::borrow::Cow; use std::collections::{BTreeMap, BTreeSet}; use serde_json::{Value, json}; -use vectorcraft_doc::hit::{Hit, HitKind, compound_part_at, hit_test, selected_hidden_at, symbol_part_at, symbol_part_outline}; +use vectorcraft_doc::hit::{Hit, HitKind, compound_part_at, hit_test, selected_hidden_at, symbol_part_at, symbol_part_outline_in_view}; use vectorcraft_doc::{AnchorRef, Node, NodeId, NodeKind, Selection, symbol_overrides}; use vectorcraft_geom::{Anchor, PathData, PathSeg, Point, Rect, Vec2}; @@ -1029,7 +1029,7 @@ impl Tool for DirectSelectionTool { out.extend(self.mesh.overlays(cx, &|id| cx.selection.contains(id))); if !self.group { if let Some(sp) = &cx.selection.symbol_part - && let Some(path) = cx.doc.node(sp.instance).and_then(|n| symbol_part_outline(cx.doc, n, &sp.path)) + && let Some(path) = cx.doc.node(sp.instance).and_then(|n| symbol_part_outline_in_view(cx.doc, n, &sp.path, cx.hit_options())) { out.push(Overlay::Path { path, color: cx.doc.layer_color(sp.instance), width: 1.0, dashed: false }); } @@ -1608,7 +1608,7 @@ impl DirectSelectionTool { // (members of groups too), each whole, as a click selects one; with an Alt-marquee, every // object it touches, each whole. if enclosed || whole { - let mut touched = vectorcraft_doc::hit::marquee(cx.doc, r, cx.isolation, true); + let mut touched = vectorcraft_doc::hit::marquee_in_view(cx.doc, r, cx.isolation, true, cx.outline); let editable = cx.doc.editable(); touched.retain(|id| editable(*id)); let picked = if enclosed { crate::select::inside(cx, r, touched) } else { touched }; @@ -1680,7 +1680,7 @@ impl DirectSelectionTool { } // Objects without anchors to pick (type, images, symbols…) are selected whole when // the marquee touches them, as with the Selection tool (#927). - for id in vectorcraft_doc::hit::marquee(cx.doc, r, cx.isolation, true) { + for id in vectorcraft_doc::hit::marquee_in_view(cx.doc, r, cx.isolation, true, cx.outline) { let whole = cx.doc.node(id).is_some_and(|n| !matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })); if whole && !sel.iter().any(|(s, _)| *s == id) && !framed.iter().any(|(f, _)| *f == id) && !meshed.contains(&id) { sel.push((id, vec![])); diff --git a/crates/tools/src/direct/tests.rs b/crates/tools/src/direct/tests.rs index 7ce48bdc1e..32229158af 100644 --- a/crates/tools/src/direct/tests.rs +++ b/crates/tools/src/direct/tests.rs @@ -2396,3 +2396,26 @@ fn type_on_a_path_shows_and_drags_its_paths_handles() { assert!((v["x"].as_f64().unwrap() - 400.0).abs() < 1e-9, "Shift keeps it straight above its anchor: {v}"); assert!(handles(&ToolContext { handles_multiple: false, ..cx(&d, &s, &p) }).is_empty()); } + +/// An Alt-marquee across clipped art where the clipping path's own shape, but not the region a +/// live effect moved it to, lets it show selects the art in Outline view only, which draws the +/// clipping path without its effects. +#[test] +fn outline_view_marquees_measure_clipped_art_by_the_plain_clipping_path() { + let (d, _, art) = doc_with_moved_clip_region(); + let s = Selection::default(); + let p = paint(); + let alt = Mods { alt: true, ..Mods::default() }; + let marquee = |outline: bool| { + let c = ToolContext { outline, ..cx(&d, &s, &p) }; + let mut t = DirectSelectionTool::new(false); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 440.0, 410.0).with_mods(alt)); + t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 460.0, 430.0).with_mods(alt)); + t.pointer(&c, &PointerEvent::new(PointerKind::Up, 460.0, 430.0).with_mods(alt)) + }; + let selects = |a: &[Action]| a.iter().any(|a| matches!(a, Action::Exec(c, v) if c == "select.set" && v["ids"] == json!([art.0]))); + let a = marquee(true); + assert!(selects(&a), "outline: {a:?}"); + let a = marquee(false); + assert!(!selects(&a), "preview: {a:?}"); +} diff --git a/crates/tools/src/distort/perspective.rs b/crates/tools/src/distort/perspective.rs index 2e9ecb558b..72cb02b6db 100644 --- a/crates/tools/src/distort/perspective.rs +++ b/crates/tools/src/distort/perspective.rs @@ -26,6 +26,7 @@ use crate::bbox::{Handle as BoxHandle, scale_for_drag}; use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; pub mod define; +pub mod infer; pub mod view; pub mod widget; pub use define::{GridDefinition, Rgb, Station}; @@ -183,6 +184,11 @@ pub struct PerspectiveGrid { /// Horizontal extent of the right plane (points, plane units); None: `extent`, as the left. #[serde(default, skip_serializing_if = "Option::is_none")] pub extent_right: Option, + /// Automatic Plane Positioning: the point (x, y and z in the grid's frame, points, as + /// [`Axis`] names them) the active plane passes through for now, while the other planes hide + /// ([`infer`]). View state. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub inferred: Option<[f64; 3]>, } impl PerspectiveGrid { @@ -224,11 +230,18 @@ impl PerspectiveGrid { snap: true, rulers: false, extent_right: None, + inferred: None, } } - /// Where `plane` is along its normal (points; 0: its place in the grid's definition). + /// Where `plane` is along its normal (points; 0: its place in the grid's definition): for the + /// active plane held by Automatic Plane Positioning, where that holds it. pub fn offset(&self, plane: Plane) -> f64 { + self.inferred_offset(plane).unwrap_or_else(|| self.placed_offset(plane)) + } + + /// Where `plane` was moved along its normal, Automatic Plane Positioning aside. + pub fn placed_offset(&self, plane: Plane) -> f64 { match plane { Plane::Left => self.left_offset, Plane::Right => self.right_offset, @@ -325,7 +338,8 @@ impl PerspectiveGrid { let mut v = serde_json::to_value(self).map_err(|e| e.to_string())?; if let (Some(o), Some(p)) = (v.as_object_mut(), patch.as_object()) { for (k, val) in p { - if k == "ids" || k == "attached" { + // Automatic Plane Positioning's point is `perspective.plane.infer`'s to set. + if k == "ids" || k == "attached" || k == "inferred" { continue; } o.insert(k.clone(), val.clone()); @@ -333,6 +347,7 @@ impl PerspectiveGrid { } let mut g: Self = serde_json::from_value(v).map_err(|e| e.to_string())?; g.reconcile(self, patch); + g.keep_positioning_valid(); g.validate()?; Ok(g) } @@ -354,7 +369,7 @@ impl PerspectiveGrid { self.extent, self.height, ]; - if nums.iter().any(|v| !v.is_finite() || v.abs() > 4.0e6) { + if nums.iter().chain(self.inferred.iter().flatten()).any(|v| !v.is_finite() || v.abs() > 4.0e6) { return Err("grid values must be finite".into()); } if self.distance <= 0.0 || self.cell <= 0.0 || self.extent <= 0.0 || self.height <= 0.0 { @@ -563,10 +578,31 @@ impl PerspectiveGrid { let Some(h) = self.homography(plane) else { return vec![] }; let d = self.domain(plane); let mut out = vec![]; + let (w, h_len) = (d.width(), d.height()); + let Some(((su, nu), (sv, nv))) = self.line_steps(plane) else { return out }; + for i in 0..=nu { + let u = i as f64 * su; + if let (Some(a), Some(b)) = (h.apply(Point::new(u, 0.0)), h.apply(Point::new(u, h_len))) { + out.push((a, b)); + } + } + for i in 0..=nv { + let v = i as f64 * sv; + if let (Some(a), Some(b)) = (h.apply(Point::new(0.0, v)), h.apply(Point::new(w, v))) { + out.push((a, b)); + } + } + out + } + + /// How the gridlines of `plane` are spaced as drawn: (step, the number of the last line) along + /// its u and its v axis. `None` for a grid without lines. + pub(crate) fn line_steps(&self, plane: Plane) -> Option<((f64, usize), (f64, usize))> { + let d = self.domain(plane); // A stored grid is not checked: no spacing, or an extent that isn't a number, has no lines. let (w, h_len) = (d.width(), d.height()); if !(self.cell.is_finite() && self.cell > 0.0 && w.is_finite() && h_len.is_finite()) { - return out; + return None; } let step = |len: f64| { let mut s = self.cell; @@ -580,19 +616,7 @@ impl PerspectiveGrid { // tolerance can inflate the count when the whole domain is far smaller than it, so the // bound is capped on its own, before any loop runs. let count = |len: f64, s: f64| ((len + 1e-9) / s).floor().clamp(0.0, 120.0) as usize; - for i in 0..=count(w, su) { - let u = i as f64 * su; - if let (Some(a), Some(b)) = (h.apply(Point::new(u, 0.0)), h.apply(Point::new(u, h_len))) { - out.push((a, b)); - } - } - for i in 0..=count(h_len, sv) { - let v = i as f64 * sv; - if let (Some(a), Some(b)) = (h.apply(Point::new(0.0, v)), h.apply(Point::new(w, v))) { - out.push((a, b)); - } - } - out + Some(((su, count(w, su)), (sv, count(h_len, sv)))) } /// Plane Switching widget geometry in the first artboard's top-left corner (headless): (plane, @@ -611,10 +635,10 @@ impl PerspectiveGrid { } /// The left, right and horizontal plane widgets: where each sits (on its plane: the middle of a - /// wall's ground edge, the middle of the horizontal plane). + /// wall's ground edge, the middle of the horizontal plane). A hidden plane has none. pub fn plane_widgets(&self) -> Vec<(Plane, Point)> { let e = self.extent / 2.0; - Plane::ALL + self.shown_planes() .into_iter() .filter_map(|pl| { let q = if pl == Plane::Ground { Point::new(e, e) } else { Point::new(e, 0.0) }; @@ -793,7 +817,7 @@ pub fn grid_overlays_in(doc: &Document, tol: f64, place: Option &'static str { + match self { + Self::Anchor => "anchor", + Self::Gridline => "gridline", + } + } +} + +impl Axis { + /// Where the axis' coordinate is in a point of the grid's frame. + fn index(self) -> usize { + match self { + Self::X => 0, + Self::Y => 1, + Self::Z => 2, + } + } +} + +/// Call `f` with each shown object in perspective that isn't inside another one, its plane and +/// its depth: its own record, else the one grid `g` stored before attachments were kept on the +/// objects ([`PerspectiveGrid::attachment_of`]). +fn each_attached<'a>(g: &PerspectiveGrid, n: &'a Node, f: &mut dyn FnMut(&'a Node, Plane, f64)) { + if !n.visible { + return; + } + match attachment(n).or_else(|| g.attached_plane(n.id).map(|p| (p, 0.0))) { + Some((pl, depth)) => f(n, pl, depth), + None => n.children().into_iter().flatten().for_each(|c| each_attached(g, c, f)), + } +} + +/// Call `f` with `n` and each node inside it, leaving out hidden nodes and what they hold. +fn each_shown<'a>(n: &'a Node, f: &mut dyn FnMut(&'a Node)) { + if !n.visible { + return; + } + f(n); + n.children().into_iter().flatten().for_each(|c| each_shown(c, f)); +} + +impl PerspectiveGrid { + /// Where Automatic Plane Positioning holds `plane`: the active plane only. + pub(super) fn inferred_offset(&self, plane: Plane) -> Option { + let p = self.inferred?; + if plane != self.plane { + return None; + } + let [.., n] = self.axes(plane)?; + Some(p[n.index()]) + } + + /// The planes that show: all three, or only the active one while Automatic Plane Positioning + /// holds it. + pub fn shown_planes(&self) -> Vec { + match self.inferred { + Some(_) if self.plane != Plane::None => vec![self.plane], + _ => Plane::ALL.to_vec(), + } + } + + /// The point of the grid's frame at plane coordinates `q` on `plane` at `depth`. + fn frame_point(&self, plane: Plane, depth: f64, q: Point) -> Option<[f64; 3]> { + let [u, v, n] = self.axes(plane)?; + let mut out = [0.0; 3]; + out[u.index()] = q.x; + out[v.index()] = q.y; + out[n.index()] = depth; + Some(out) + } + + /// The anchor point of shown art in perspective nearest `p` within `tol`: (distance, frame point). + fn anchor_near(&self, doc: &Document, p: Point, tol: f64) -> Option<(f64, [f64; 3])> { + let mut best: Option<(f64, [f64; 3])> = None; + let mut visit = |n: &Node, plane: Plane, depth: f64| { + // The plane's inverse map, worked out only once an anchor is within reach. + let mut hi = None; + each_shown(n, &mut |c| { + let NodeKind::Path { path, .. } = &c.kind else { return }; + for a in path.subpaths.iter().flat_map(|sp| sp.anchors.iter()) { + let d = a.p.distance(p); + if !(d <= tol && best.is_none_or(|b| d < b.0)) { + continue; + } + let inv = hi.get_or_insert_with(|| self.homography_at(plane, depth).and_then(|h| h.inverse())); + if let Some(at) = inv.as_ref().and_then(|m| m.apply(a.p)).and_then(|q| self.frame_point(plane, depth, q)) { + best = Some((d, at)); + } + } + }); + }; + for l in &doc.layers { + each_attached(self, l, &mut visit); + } + best + } + + /// The gridline intersection of a shown plane nearest `p` within `tol`: (distance, frame point). + fn intersection_near(&self, p: Point, tol: f64) -> Option<(f64, [f64; 3])> { + let mut best: Option<(f64, [f64; 3])> = None; + for plane in self.shown_planes() { + let depth = self.offset(plane); + let Some(h) = self.homography_at(plane, depth) else { continue }; + let Some(q) = h.inverse().and_then(|hi| hi.apply(p)) else { continue }; + let Some(((su, nu), (sv, nv))) = self.line_steps(plane) else { continue }; + // The drawn lines nearest the pointer along each axis, and their neighbors: the + // projection skews and shrinks the cells, so the intersection nearest on the page can be + // one over from the nearest in the plane. + let near = |v: f64, step: f64, last: usize| { + let i = (v / step).round().clamp(0.0, last as f64) as i64; + (i - 2..=i + 2).filter(move |k| (0..=last as i64).contains(k)).map(move |k| k as f64 * step) + }; + for (u, v) in near(q.x, su, nu).flat_map(|u| near(q.y, sv, nv).map(move |v| (u, v))) { + let q = Point::new(u, v); + let Some(d) = h.apply(q).map(|at| at.distance(p)) else { continue }; + if d <= tol + && best.is_none_or(|b| d < b.0) + && let Some(at) = self.frame_point(plane, depth, q) + { + best = Some((d, at)); + } + } + } + best + } + + /// What Automatic Plane Positioning finds within `tol` of page point `p`: the nearest anchor + /// point of shown art in perspective, else the nearest gridline intersection of a shown plane, + /// as a point of the grid's frame. `None` while the grid is hidden or has no active plane. + pub fn infer_at(&self, doc: &Document, p: Point, tol: f64, targets: PlaneTargets) -> Option<(InferSource, [f64; 3])> { + if !self.visible || self.plane == Plane::None || !(tol.is_finite() && p.x.is_finite() && p.y.is_finite()) { + return None; + } + let anchor = if targets.anchors { self.anchor_near(doc, p, tol) } else { None }; + let found = match anchor { + Some((_, at)) => Some((InferSource::Anchor, at)), + None if targets.gridlines => self.intersection_near(p, tol).map(|(_, at)| (InferSource::Gridline, at)), + None => None, + }; + found.filter(|(_, at)| at.iter().all(|v| v.is_finite())) + } + + /// Put a plane that Automatic Plane Positioning holds in the grid stored in `doc` back in its + /// place. Returns whether one was held. + pub fn end_positioning(doc: &mut Document) -> bool { + if !Self::positioning(doc) { + return false; + } + doc.unknown.get_mut(DOC_KEY).and_then(|v| v.as_object_mut()).is_some_and(|o| o.remove("inferred").is_some()) + } + + /// Drop the point Automatic Plane Positioning holds when the grid no longer shows, has no + /// active plane, or would put the active plane behind the viewer through it. + pub fn keep_positioning_valid(&mut self) { + if self.inferred.is_some() && (!self.visible || self.plane == Plane::None || self.validate().is_err()) { + self.inferred = None; + } + } + + /// Whether Automatic Plane Positioning holds a plane of the grid stored in `doc`. + pub fn positioning(doc: &Document) -> bool { + doc.unknown.get(DOC_KEY).and_then(|v| v.get("inferred")).is_some_and(|v| !v.is_null()) + } +} + +/// The Perspective Selection tool's step for Shift held over `p` with no button down: the command +/// that moves the active plane through the anchor point or gridline intersection there, unless +/// the plane is held through that point already. +pub(super) fn hover_action(cx: &ToolContext, g: &PerspectiveGrid, p: Point) -> Option { + let tol = cx.tol(HIT_PX); + let (_, at) = g.infer_at(cx.doc, p, tol, cx.plane_targets)?; + if g.inferred.is_some_and(|held| held.iter().zip(&at).all(|(a, b)| (a - b).abs() <= 1e-9)) { + return None; + } + Some(Action::Exec("perspective.plane.infer".into(), json!({"at": [p.x, p.y], "tolerance": tol}))) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testutil::*; + use crate::{Mods, PointerEvent, PointerKind, Tool, ToolKey}; + use vectorcraft_doc::Selection; + use vectorcraft_geom::Rect; + + fn grid() -> PerspectiveGrid { + PerspectiveGrid::preset(2, Rect::new(0.0, 0.0, 800.0, 600.0)) + } + + #[test] + fn a_gridline_intersection_gives_the_frame_point_the_planes_pass_through() { + let mut g = grid(); + let (d, cell) = (Document::new(800.0, 600.0), g.cell); + // Three cells along and two up the left wall (two-point: u recedes along Z, v is Y). + let p = g.to_page(Plane::Left, Point::new(3.0 * cell, 2.0 * cell)).unwrap(); + let (source, at) = g.infer_at(&d, p, 1.0, PlaneTargets::ALL).unwrap(); + assert_eq!(source, InferSource::Gridline); + for (got, want) in at.iter().zip([0.0, 2.0 * cell, 3.0 * cell]) { + assert!((got - want).abs() < 1e-6, "{at:?}"); + } + // Held, the active plane lies at the point's coordinate along its normal, the other planes + // hide, and their own places stay. + g.inferred = Some(at); + g.plane = Plane::Ground; + assert!((g.offset(Plane::Ground) - 2.0 * cell).abs() < 1e-6); + assert_eq!((g.placed_offset(Plane::Ground), g.offset(Plane::Left)), (0.0, 0.0)); + assert_eq!(g.shown_planes(), vec![Plane::Ground]); + assert_eq!(g.plane_widgets().len(), 1); + // The plane drawn there passes through the point the pointer was over. + let back = g.to_page(Plane::Ground, Point::new(0.0, 3.0 * cell)).unwrap(); + assert!((back - p).hypot() < 1e-6, "{back:?} {p:?}"); + // Another plane made active passes through it too. + g.plane = Plane::Right; + assert!((g.offset(Plane::Right) - 3.0 * cell).abs() < 1e-6); + assert_eq!(g.offset(Plane::Ground), 0.0); + // With no active plane nothing is held. + g.plane = Plane::None; + assert_eq!(g.shown_planes(), Plane::ALL.to_vec()); + } + + #[test] + fn the_pointer_must_be_within_reach_of_a_target_that_is_on() { + // Only the right wall shows, in its own place: the other planes' lines are out of the way. + let g = PerspectiveGrid { plane: Plane::Right, inferred: Some([0.0; 3]), ..grid() }; + let (d, cell) = (Document::new(800.0, 600.0), g.cell); + let on = g.to_page(Plane::Right, Point::new(2.0 * cell, cell)).unwrap(); + let mid = g.to_page(Plane::Right, Point::new(2.5 * cell, 1.5 * cell)).unwrap(); + assert!(g.infer_at(&d, on + vectorcraft_geom::Vec2::new(2.0, 0.0), 3.0, PlaneTargets::ALL).is_some()); + assert!(g.infer_at(&d, mid, 3.0, PlaneTargets::ALL).is_none(), "the middle of a cell is no intersection"); + assert!(g.infer_at(&d, on, 3.0, PlaneTargets { anchors: true, gridlines: false }).is_none()); + assert!(g.infer_at(&d, on, f64::NAN, PlaneTargets::ALL).is_none()); + assert!(g.infer_at(&d, Point::new(f64::INFINITY, 0.0), 3.0, PlaneTargets::ALL).is_none()); + // Hidden, or without an active plane, the grid gives no point. + assert!(PerspectiveGrid { visible: false, ..g.clone() }.infer_at(&d, on, 3.0, PlaneTargets::ALL).is_none()); + assert!(PerspectiveGrid { plane: Plane::None, ..g.clone() }.infer_at(&d, on, 3.0, PlaneTargets::ALL).is_none()); + // Beyond the plane's last line there is no intersection. + let past = g.to_page(Plane::Right, Point::new(g.right_extent() + 5.0 * cell, cell)).unwrap(); + assert!(g.infer_at(&d, past, 3.0, PlaneTargets::ALL).is_none()); + } + + #[test] + fn a_hidden_path_inside_art_in_perspective_has_no_anchor_to_take() { + let g = PerspectiveGrid { plane: Plane::Right, ..grid() }; + let mut d = Document::new(800.0, 600.0); + g.store(&mut d); + // A group on the right wall holding one small square, a corner in the middle of a cell. + let at = g.to_page(Plane::Right, Point::new(2.5 * g.cell, 1.5 * g.cell)).unwrap(); + let (layer, group, square) = (d.layers[0].id, d.alloc_id(), d.alloc_id()); + let mut path = Node::path(square, vectorcraft_geom::shapes::rectangle(Rect::new(at.x, at.y, at.x + 2.0, at.y + 2.0)), Default::default()); + path.visible = false; + let mut art = Node::group(group, vec![std::sync::Arc::new(path)]); + super::super::set_attachment(&mut art, Plane::Right, 0.0); + d.insert(Some(layer), 0, art).unwrap(); + let anchors = PlaneTargets { anchors: true, gridlines: false }; + assert!(g.infer_at(&d, at, 0.5, anchors).is_none(), "the square is hidden"); + d.node_mut(square).unwrap().visible = true; + let (source, point) = g.infer_at(&d, at, 0.5, anchors).unwrap(); + assert_eq!(source, InferSource::Anchor); + for (got, want) in point.iter().zip([2.5 * g.cell, 1.5 * g.cell, 0.0]) { + assert!((got - want).abs() < 1e-6, "{point:?}"); + } + // A grid stored before attachments were kept on the objects lists them itself. + let mut d = Document::new(800.0, 600.0); + let (layer, square) = (d.layers[0].id, d.alloc_id()); + d.insert( + Some(layer), + 0, + Node::path(square, vectorcraft_geom::shapes::rectangle(Rect::new(at.x, at.y, at.x + 2.0, at.y + 2.0)), Default::default()), + ) + .unwrap(); + assert!(g.infer_at(&d, at, 0.5, anchors).is_none(), "not in perspective"); + let mut legacy = g.clone(); + legacy.attached.insert(square.0.to_string(), Plane::Right); + assert_eq!(legacy.infer_at(&d, at, 0.5, anchors).map(|f| f.0), Some(InferSource::Anchor)); + } + + #[test] + fn the_stored_point_ends_with_end_positioning() { + let mut d = Document::new(800.0, 600.0); + let mut g = grid(); + g.store(&mut d); + assert!(!PerspectiveGrid::positioning(&d)); + assert!(!PerspectiveGrid::end_positioning(&mut d)); + g.inferred = Some([1.0, 2.0, 3.0]); + g.store(&mut d); + assert!(PerspectiveGrid::positioning(&d)); + assert_eq!(PerspectiveGrid::current(&d).inferred, Some([1.0, 2.0, 3.0])); + // `perspective.grid.set` leaves the point as it is. + assert_eq!(g.merged(&json!({"inferred": [9, 9, 9], "cell": 25})).unwrap().inferred, Some([1.0, 2.0, 3.0])); + assert!(PerspectiveGrid { inferred: Some([f64::NAN, 0.0, 0.0]), ..g.clone() }.validate().is_err()); + assert!(PerspectiveGrid::end_positioning(&mut d)); + assert_eq!(PerspectiveGrid::current(&d), PerspectiveGrid { inferred: None, ..g }); + } + + #[test] + fn shift_over_an_intersection_asks_for_the_plane_once() { + let mut d = Document::new(800.0, 600.0); + let mut g = grid(); + g.store(&mut d); + let (s, p) = (Selection::default(), paint()); + let at = g.to_page(Plane::Left, Point::new(2.0 * g.cell, 3.0 * g.cell)).unwrap(); + let shift = Mods { shift: true, ..Default::default() }; + let hover = |d: &Document, mods: Mods| { + let c = cx(d, &s, &p); + let mut t = super::super::PerspectiveSelectionTool::default(); + t.pointer(&c, &PointerEvent { mods, ..PointerEvent::new(PointerKind::Move, at.x, at.y) }) + }; + assert!(hover(&d, Mods::default()).is_empty(), "without Shift the pointer only hovers"); + let acts = hover(&d, shift); + let [Action::Exec(cmd, v)] = acts.as_slice() else { panic!("{acts:?}") }; + assert_eq!((cmd.as_str(), &v["at"]), ("perspective.plane.infer", &json!([at.x, at.y]))); + // Held through that point already, the hover asks for nothing more. + g.inferred = g.infer_at(&d, at, 1.0, PlaneTargets::ALL).map(|f| f.1); + g.store(&mut d); + assert!(hover(&d, shift).is_empty()); + // Escape puts the plane back. + let c = cx(&d, &s, &p); + let mut t = super::super::PerspectiveSelectionTool::default(); + assert_eq!(t.key(&c, ToolKey::Escape, Mods::default()), vec![Action::Exec("perspective.plane.infer".into(), json!({"clear": true}))]); + } +} diff --git a/crates/tools/src/distort/perspective/tools.rs b/crates/tools/src/distort/perspective/tools.rs index 915e4a8835..1716a4593d 100644 --- a/crates/tools/src/distort/perspective/tools.rs +++ b/crates/tools/src/distort/perspective/tools.rs @@ -289,6 +289,9 @@ impl Tool for PerspectiveSelectionTool { _ => vec![], } } + // Automatic Plane Positioning: Shift held over an anchor point of art in perspective or + // over a gridline intersection, with no button down. During a drag Shift constrains. + (PointerKind::Move, SelDrag::Idle) if m.shift => super::infer::hover_action(cx, &g, p).into_iter().collect(), (_, d) => { self.drag = d; vec![] @@ -296,7 +299,8 @@ impl Tool for PerspectiveSelectionTool { } } /// Escape during a move, a resize or a plane widget drag cancels it: the objects and the plane - /// go back to the start of the drag. + /// go back to the start of the drag. With no drag, Escape puts a plane that Automatic Plane + /// Positioning holds back in its place. fn key(&mut self, cx: &ToolContext, key: ToolKey, mods: Mods) -> Vec { if key == ToolKey::Escape && self.busy() { self.measure = None; @@ -305,6 +309,9 @@ impl Tool for PerspectiveSelectionTool { _ => vec![Action::Cancel], }; } + if key == ToolKey::Escape && PerspectiveGrid::current(cx.doc).inferred.is_some() { + return vec![Action::Exec("perspective.plane.infer".into(), json!({"clear": true}))]; + } if let (ToolKey::Digit(5), SelDrag::Move { perp, began, shift, .. }) = (key, &mut self.drag) { *perp = !*perp; *shift = mods.shift; diff --git a/crates/tools/src/distort/perspective/widget.rs b/crates/tools/src/distort/perspective/widget.rs index 4af1173e83..c5bdf05542 100644 --- a/crates/tools/src/distort/perspective/widget.rs +++ b/crates/tools/src/distort/perspective/widget.rs @@ -50,17 +50,44 @@ impl WidgetCorner { } } -/// Perspective Grid Options: whether the Plane Switching Widget shows, and where. +/// Perspective Grid Options: whether the Plane Switching Widget shows, and where, and what +/// Automatic Plane Positioning takes a point from ([`super::infer`]). #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", default)] pub struct WidgetOptions { pub show: bool, pub position: WidgetCorner, + /// Automatic Plane Positioning › Anchor Point of Perspective Artwork. + pub anchor_point: bool, + /// Automatic Plane Positioning › Intersection of Gridlines. + pub gridline_intersection: bool, } impl Default for WidgetOptions { fn default() -> Self { - Self { show: true, position: WidgetCorner::TopLeft } + Self { show: true, position: WidgetCorner::TopLeft, anchor_point: true, gridline_intersection: true } + } +} + +impl WidgetOptions { + /// What Automatic Plane Positioning takes a point from. + pub fn targets(self) -> PlaneTargets { + PlaneTargets { anchors: self.anchor_point, gridlines: self.gridline_intersection } + } +} + +/// What Automatic Plane Positioning takes a point from: the anchor points of art in perspective, +/// the gridline intersections of the planes that show. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct PlaneTargets { + pub anchors: bool, + pub gridlines: bool, +} + +impl PlaneTargets { + pub const ALL: Self = Self { anchors: true, gridlines: true }; + pub fn any(self) -> bool { + self.anchors || self.gridlines } } diff --git a/crates/tools/src/distort/puppet.rs b/crates/tools/src/distort/puppet.rs index f141378382..2ca6ec0631 100644 --- a/crates/tools/src/distort/puppet.rs +++ b/crates/tools/src/distort/puppet.rs @@ -422,7 +422,7 @@ impl Tool for PuppetWarpTool { } None => vec![], }, - PointerKind::DoubleClick => vec![], + PointerKind::DoubleClick | PointerKind::TripleClick => vec![], } } /// Delete/Backspace remove the selected pins; with none selected they are the shortcut's diff --git a/crates/tools/src/distort/width.rs b/crates/tools/src/distort/width.rs index e7050d3a79..4ebbac4981 100644 --- a/crates/tools/src/distort/width.rs +++ b/crates/tools/src/distort/width.rs @@ -300,6 +300,7 @@ impl Tool for WidthTool { self.hover = Self::spot_at(cx, p); vec![] } + PointerKind::TripleClick => vec![], PointerKind::DoubleClick => { let Some(spot) = Self::spot_at(cx, p) else { return vec![] }; let Some((w, _)) = Self::hit(cx, &spot, p) else { diff --git a/crates/tools/src/draw2/curvature.rs b/crates/tools/src/draw2/curvature.rs index 02087d997a..06ad1c1230 100644 --- a/crates/tools/src/draw2/curvature.rs +++ b/crates/tools/src/draw2/curvature.rs @@ -653,6 +653,7 @@ impl Tool for CurvatureTool { self.pts[i].1 = !self.pts[i].1; vec![Action::Exec("path.curvature".into(), self.params())] } + PointerKind::TripleClick => vec![], } } fn notify(&mut self, cx: &ToolContext, what: &str) { diff --git a/crates/tools/src/draw2/family.rs b/crates/tools/src/draw2/family.rs index 8058101b1c..2e93888d02 100644 --- a/crates/tools/src/draw2/family.rs +++ b/crates/tools/src/draw2/family.rs @@ -477,7 +477,8 @@ impl Tool for FamilyTool { } "slope" => self.slope = v.as_f64().filter(|n| n.is_finite()).map_or(self.slope, |n| n.clamp(-100.0, 100.0)), "fillArc" => self.fill_arc = v.as_bool().unwrap_or(self.fill_arc), - "decay" => self.decay = v.as_f64().unwrap_or(self.decay).clamp(5.0, 150.0), + // Report and persist the decay that shapes::spiral can actually draw. + "decay" => self.decay = v.as_f64().unwrap_or(self.decay).clamp(5.0, 99.99), "segments" => self.segments = v.as_u64().unwrap_or(10).clamp(2, 1000) as u32, "clockwise" => self.clockwise = v.as_bool().unwrap_or(self.clockwise), "rows" | "concentric" => self.rows = v.as_u64().unwrap_or(5).min(999) as u32, @@ -534,6 +535,55 @@ mod tests { use crate::testutil::*; use vectorcraft_doc::Selection; + #[test] + fn spiral_reports_the_decay_its_command_draws() { + let mut t = FamilyTool::new("spiral"); + assert_eq!(t.options()["decay"], json!(80.0)); + for (requested, expected) in [(-10.0, 5.0), (5.0, 5.0), (80.0, 80.0), (99.99, 99.99), (100.0, 99.99), (150.0, 99.99), (200.0, 99.99)] { + t.set_option("decay", &json!(requested)); + assert_eq!(t.options()["decay"], json!(expected)); + let (id, params) = t.command(Point::ZERO, Point::new(100.0, 0.0), Mods::default()); + assert_eq!(id, "shape.spiral"); + assert_eq!(params["decay"], json!(expected)); + // Inspect the actual adjacent radii, not a second copy of the tool's clamp. Decay is per full + // wind and a segment is a quarter turn, so four segments give the decay. + let path = vectorcraft_geom::shapes::spiral(Point::ZERO, 100.0, params["decay"].as_f64().unwrap(), 2, true); + let anchors = &path.subpaths[0].anchors; + let outer = anchors[2].p.distance(Point::ZERO); + let next = anchors[1].p.distance(Point::ZERO); + assert!((100.0 * (next / outer).powi(4) - expected).abs() < 1e-9); + } + for invalid in [Value::Null, json!("80"), json!(false), json!({})] { + t.set_option("decay", &invalid); + assert_eq!(t.options()["decay"], json!(99.99)); + } + } + + #[test] + fn normalized_spiral_decay_preserves_existing_capped_paths_within_roundoff() { + for requested in [100.0, 150.0] { + let mut t = FamilyTool::new("spiral"); + t.set_option("decay", &json!(requested)); + for clockwise in [false, true] { + for segments in [2, 10, 1000] { + for radius in [1.0, 100.0, 1e6] { + let previous = vectorcraft_geom::shapes::spiral(Point::ZERO, radius, requested, segments, clockwise); + let normalized = vectorcraft_geom::shapes::spiral(Point::ZERO, radius, t.decay, segments, clockwise); + let old = &previous.subpaths[0].anchors; + let new = &normalized.subpaths[0].anchors; + assert_eq!(old.len(), new.len()); + for (a, b) in old.iter().zip(new) { + assert_eq!(a.kind, b.kind); + for (p, q) in [(a.p, b.p), (a.h_in, b.h_in), (a.h_out, b.h_out)] { + assert!(p.distance(q) <= 1e-10 * (1.0 + radius), "{requested}% / {segments} / {radius}: {p:?} != {q:?}"); + } + } + } + } + } + } + } + #[test] fn grid_drag_and_arrows() { let (d, _) = doc_with_rect(); diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index 61396e01d9..1bf6a9488b 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -6,9 +6,9 @@ //! points with straight segments and the release fits them; Alt on release (or ending near the start) closes the path, and starting //! near an end of a selected open path continues it. Shift held at the press draws a straight //! Pencil line at 45° steps from the Constrain Angle instead, and Alt held at the press (with Alt -//! key toggles to Smooth Tool off) draws a straight line at any angle. The Pencil's new path starts and ends on -//! Smart Guides ([`DrawSnap`]: an anchor, a path, in line with the art), hovering too; the points -//! between follow the hand. The Paintbrush records the pen pressure of each point (a stroke a pen +//! key toggles to Smooth Tool off) draws a straight line at any angle. The Pencil ignores Smart +//! Guides and Snap to Point: it shows no Smart Guides, hovering or drawing, and its ends follow the +//! hand. Snap to Grid and Snap to Pixel still move its ends (`grid_snaps`). The Paintbrush records the pen pressure of each point (a stroke a pen //! pressed less than fully on sends `[x, y, pressure]` points) for pressure-sensitive brushes, and //! the pen's tilt and barrel rotation where the pen reads them (`[x, y, pressure, tiltX, tiltY, //! rotation]` points, `null` for what a point lacks) for brushes that vary with them. The Blob @@ -98,8 +98,13 @@ pub struct GestureTool { /// A release where the pointer last dragged to would close the stroke because it ends near /// its start (Close Paths When Ends Are Within): the cursor shows the closing ring. near_start: bool, + /// A release where the pointer last dragged to would connect the continued path to another + /// selected path's open end (`finish`): the cursor shows the continuation cursor. + connects: bool, /// Pencil/Paintbrush continuing a selected open path: (path, continue from its start). extend: Option<(NodeId, bool)>, + /// The other end of the path `extend` continues: a release near it closes the path. + close_to: Option, /// A Pencil stroke continuing a selected open path: the other paths selected at the press, /// whose open ends it connects to. connect_to: Vec, @@ -817,7 +822,9 @@ impl GestureTool { active: false, began: false, near_start: false, + connects: false, extend: None, + close_to: None, connect_to: vec![], redraw: None, fidelity, @@ -853,27 +860,29 @@ impl GestureTool { } } - /// Do the ends of its strokes snap (the Pencil)? - fn snaps(&self) -> bool { - self.id == "pencil" - } - /// Does a straight Knife cut snap to anchors and paths? Only with Smart Guides on, which Snap to - /// Pixel (for drawing) and Snap to Grid turn off (`PointSnap::new`). Its ends snap as the - /// Pencil's straight line's do: the press, and the release unless Shift keeps it on a 45° step. + /// Pixel (for drawing) and Snap to Grid turn off (`PointSnap::new`). Its ends snap: the press, + /// and the release unless Shift keeps it on a 45° step. fn knife_snaps(&self, cx: &ToolContext) -> bool { self.id == "knife" && self.straight && cx.smart_guides && !cx.snaps_to_pixel(crate::PixelOp::Drawing) && !cx.snap_to_grid } - /// Does the end of a straight line snap: the Pencil's Alt line's, or a straight Knife cut's - /// without Shift? + /// Do the Pencil's ends snap? Only to the grid or to pixels, with View → Snap to Grid or Snap + /// to Pixel on: those are separate from Smart Guides (and turn them off), and the grid case is + /// its own question (#2958). Smart Guides and Snap to Point never move them. + fn grid_snaps(&self, cx: &ToolContext) -> bool { + self.id == "pencil" && (cx.snap_to_grid || cx.snaps_to_pixel(crate::PixelOp::Drawing)) + } + + /// Does the end of a straight line without Shift snap: the Pencil's Alt line's to the grid or + /// pixels, a straight Knife cut's to anchors and paths? fn line_end_snaps(&self, cx: &ToolContext) -> bool { - self.straight && self.unconstrained && (self.snaps() || self.knife_snaps(cx)) + self.straight && self.unconstrained && (self.grid_snaps(cx) || self.knife_snaps(cx)) } /// Where a stroke or straight line released at `p` ends: where it snaps when its end snaps. fn release_end(&mut self, cx: &ToolContext, p: Point) -> Point { - if (self.snaps() && !self.smoothing && !self.straight) || self.line_end_snaps(cx) { self.snap.drag(cx, p, None) } else { p } + if (self.grid_snaps(cx) && !self.smoothing && !self.straight) || self.line_end_snaps(cx) { self.snap.drag(cx, p, None) } else { p } } /// Is a straight line with its end at `end` back at its press point (within a pixel), so that @@ -1100,6 +1109,21 @@ impl GestureTool { self.find_end(cx, p, &cx.selection.objects) } + /// The other end of the open end `find_end` found: the opposite end of `id`'s last open + /// subpath. + fn other_end(cx: &ToolContext, id: NodeId, at_start: bool) -> Option { + let pd = cx.doc.node(id)?.path_data()?; + let sp = pd.subpaths.iter().rev().find(|s| !s.closed && !s.anchors.is_empty())?; + let a = if at_start { sp.anchors.last() } else { sp.anchors.first() }; + a.map(|a| a.p) + } + + /// Continues the path at the open end `find_extend` found, if any, noting its other end. + fn set_extend(&mut self, cx: &ToolContext, found: Option<(NodeId, bool, Point)>) { + self.extend = found.map(|(id, at_start, _)| (id, at_start)); + self.close_to = found.and_then(|(id, at_start, _)| Self::other_end(cx, id, at_start)); + } + /// [`Self::find_extend`] among `ids`. fn find_end(&self, cx: &ToolContext, p: Point, ids: &[NodeId]) -> Option<(NodeId, bool, Point)> { if self.edit_within <= 0.0 { @@ -1144,16 +1168,32 @@ impl GestureTool { } /// Does a stroke that ends at `end` end near its start (Close Paths When Ends Are Within, off - /// at 0 pixels)? + /// at 0 pixels)? A stroke continuing a selected path ends near that path's other end, a + /// straight line too; a new straight line never closes, as it would run back over itself. fn ends_near_start(&self, cx: &ToolContext, end: Point) -> bool { - self.close_within > 0.0 && self.points.len() > 2 && self.points[0].distance(end) <= cx.tol(self.close_within) + if self.close_within <= 0.0 { + return false; + } + let tol = cx.tol(self.close_within); + match (self.extend, self.close_to) { + (Some(_), Some(to)) => self.points.len() >= 2 && to.distance(end) <= tol, + (Some(_), None) => false, + (None, _) => !self.straight && self.points.len() > 2 && self.points.first().is_some_and(|s| s.distance(end) <= tol), + } } - /// Does a release now, with the stroke ending at `end`, close a freehand stroke because it ends - /// near its start (`finish`)? A stroke that redraws a selected path closes only when the engine - /// finds it does not end on that path, so it counts as not closing. + /// The open end of another path selected at the press that a continuing Pencil stroke ending + /// at `end` connects to (`finish`). + fn connects_at(&self, cx: &ToolContext, end: Point) -> Option<(NodeId, bool, Point)> { + self.extend.and_then(|_| self.find_end(cx, end, &self.connect_to)) + } + + /// Does a release now, with the stroke ending at `end`, close the stroke because it ends near + /// its start, or near the other end of the path it continues (`finish`)? A stroke that redraws + /// a selected path closes only when the engine finds it does not end on that path, so it counts + /// as not closing, and a stroke that connects to another path doesn't close. fn release_closes_near_start(&self, cx: &ToolContext, end: Point) -> bool { - self.draws_path() && !self.smoothing && !self.straight && self.extend.is_none() && self.redraw.is_none() && self.ends_near_start(cx, end) + self.draws_path() && !self.smoothing && self.redraw.is_none() && self.ends_near_start(cx, end) && self.connects_at(cx, end).is_none() } /// Parameters of `path.freehand` for the current stroke, fitted at Fidelity on screen. Only the @@ -1194,14 +1234,16 @@ impl GestureTool { if !self.began { return vec![]; } - // Close Paths When Ends Are Within is off at 0 pixels. + // Close Paths When Ends Are Within is off at 0 pixels. A stroke continuing a + // selected path closes it near its other end, a straight line too. let near = pts.last().is_some_and(|&end| self.ends_near_start(cx, end)); - // A straight line has two points: closing it would draw it back over itself. - let closed = !self.straight && ((m.alt && (self.id == "paintbrush" || !self.alt_smooth)) || (self.extend.is_none() && near)); - let mut params = self.freehand_params(cx, closed); + // Alt at the release closes a freehand stroke; a new straight line has two points: + // closing it would draw it back over itself. + let closed = (!self.straight && m.alt && (self.id == "paintbrush" || !self.alt_smooth)) || near; // A Pencil stroke that continues a selected path and ends on an open end of another - // path selected at the press connects the two. - let connect = pts.last().and_then(|&end| self.find_end(cx, end, &self.connect_to)); + // path selected at the press connects the two, and doesn't close. + let connect = pts.last().and_then(|&end| self.connects_at(cx, end)); + let mut params = self.freehand_params(cx, closed && connect.is_none()); if let Some((other, at_start, _)) = connect { params["connect"] = json!({"id": other.0, "end": if at_start { "start" } else { "end" }}); } @@ -1259,14 +1301,11 @@ impl Tool for GestureTool { self.tip_at = (!ev.mods.cmd && !self.blob_alt_smooths(ev.mods)).then_some(p); } match ev.kind { - PointerKind::Move if self.snaps() => { - self.snap.hover(cx, p, &[], None); - vec![] - } PointerKind::Down => { self.active = true; self.began = false; self.near_start = false; + self.connects = false; // Alt switches the Pencil when its toggle is on, the Blob Brush always, and the // Paintbrush when the press has a selected path. self.smoothing = ev.mods.alt @@ -1278,18 +1317,19 @@ impl Tool for GestureTool { self.straight = (self.id == "pencil" && !self.smoothing && (ev.mods.shift || ev.mods.alt)) || (self.id == "knife" && ev.mods.alt); self.unconstrained = self.straight && !ev.mods.shift; let extend = if self.draws_path() && !self.smoothing { self.find_extend(cx, p) } else { None }; - self.extend = extend.map(|(id, at_start, _)| (id, at_start)); + self.set_extend(cx, extend); // The stroke's previews select the path it continues, so the others are kept now. self.connect_to = match self.extend { Some((id, _)) if self.id == "pencil" => cx.selection.objects.iter().copied().filter(|o| *o != id).collect(), _ => vec![], }; self.redraw = if self.draws_path() && !self.smoothing && self.extend.is_none() { self.find_redraw(cx, p) } else { None }; - // A path continued starts at its end, one redrawn on it; a new one where it snaps. - // A straight line is constrained from the end it continues, so it starts there. + // A path continued starts at its end, one redrawn on it; a new one at the press, + // or on the grid or a pixel when they snap. A straight line is constrained from the + // end it continues, so it starts there. let start = if let Some((_, _, end)) = extend.filter(|_| self.straight) { end - } else if self.snaps() && !self.smoothing && self.extend.is_none() && self.redraw.is_none() { + } else if self.grid_snaps(cx) && !self.smoothing && self.extend.is_none() && self.redraw.is_none() { self.snap.press(cx, p, &[], None) } else if self.knife_snaps(cx) { // A straight Knife cut, its overlay and Shift's 45° steps start from the snapped point. @@ -1313,13 +1353,13 @@ impl Tool for GestureTool { self.moved |= self.points.first().is_some_and(|start| p.distance(*start) > vectorcraft_geom::EPS); let p = self.constrained(cx, p, ev.mods); let mut end = p; - if self.snaps() && !self.smoothing && !self.straight { - // Where the stroke would end: shown, taken on release. + if self.grid_snaps(cx) && !self.smoothing && !self.straight { + // Where the stroke would end on the grid or a pixel: taken on release. end = self.snap.drag(cx, p, None); } let p = if self.line_end_snaps(cx) { - // Alt's line ends where a stroke would, and a Knife cut's on the anchors and - // paths its press snaps to: shown, taken on release. + // Alt's line ends on the grid or a pixel when they snap, and a Knife cut on the + // anchors and paths its press snaps to: shown, taken on release. self.snap.drag(cx, p, None) } else { p @@ -1336,16 +1376,20 @@ impl Tool for GestureTool { return if std::mem::take(&mut self.began) { vec![Action::Cancel] } else { vec![] }; } self.points.truncate(1); + // The line ends at `p`, where its end snaps. + end = p; } else if self.points.last().is_some_and(|l| l.distance(p) < cx.tol(1.0)) || self.points.len() >= crate::MAX_STROKE_SAMPLES { // A release here keeps the last point unless it snaps (`Up`), so the ring // follows the point `finish` will test. - let kept = self.points.last().copied().filter(|l| l.distance(p) < cx.tol(1.0) && !self.snaps()); + let kept = self.points.last().copied().filter(|l| l.distance(p) < cx.tol(1.0) && !self.grid_snaps(cx)); let release_end = kept.unwrap_or(end); self.near_start = self.release_closes_near_start(cx, release_end); + self.connects = self.connects_at(cx, release_end).is_some(); return vec![]; } self.push(p, ev); self.near_start = self.release_closes_near_start(cx, end); + self.connects = self.connects_at(cx, end).is_some(); if !self.draws_path() || self.smoothing { return vec![]; } @@ -1394,7 +1438,7 @@ impl Tool for GestureTool { } } else if self.points.last().is_some_and(|l| l.distance(p) >= cx.tol(1.0)) { self.push(end, ev); - } else if self.snaps() + } else if self.grid_snaps(cx) && !self.smoothing && self.points.len() > 1 && let Some(last) = self.points.last_mut() @@ -1406,11 +1450,13 @@ impl Tool for GestureTool { self.active = false; self.began = false; self.near_start = false; + self.connects = false; self.smoothing = false; self.straight = false; self.unconstrained = false; self.clear(); self.extend = None; + self.close_to = None; self.connect_to.clear(); self.redraw = None; out @@ -1440,6 +1486,7 @@ impl Tool for GestureTool { self.active = false; self.began = false; self.near_start = false; + self.connects = false; self.smoothing = false; self.straight = false; self.unconstrained = false; @@ -1470,6 +1517,7 @@ impl Tool for GestureTool { self.snap.clear(); self.active = false; self.near_start = false; + self.connects = false; self.began = false; self.smoothing = false; self.straight = false; @@ -1557,6 +1605,11 @@ impl Tool for GestureTool { if !self.active && self.straight_at_press(m) { return if self.find_extend(cx, p).is_some() { Cursor::PencilContinue } else { Cursor::PencilStraight }; } + // A continuing Pencil stroke that a release would connect to another selected path's open + // end (`finish`) shows that it continues on; `connects` tests the point the release keeps. + if self.id == "pencil" && self.active && self.connects { + return Cursor::PencilContinue; + } // Alt held at the release closes the path (`finish`). // A straight line stays open, so its release has nothing to close, and before a press Alt // gives the Pencil a straight line. @@ -1576,9 +1629,12 @@ impl Tool for GestureTool { "smooth" => smooth_cursor(cx), "pathEraser" => Cursor::PathEraser, "join" => Cursor::Join, + // Before a press over an open end of a selected path the Pencil shows that the stroke + // continues it (`PointerKind::Down`). + _ if !self.active && self.find_extend(cx, p).is_some() => Cursor::PencilContinue, // Before a press that draws a new path the Pencil shows its star; over a selected path - // that the press continues from an end or redraws (`PointerKind::Down`), it does not. - _ if !self.active && self.find_extend(cx, p).is_none() && self.find_redraw(cx, p).is_none() => Cursor::PencilNew, + // that the press redraws (`PointerKind::Down`), it does not. + _ if !self.active && self.find_redraw(cx, p).is_none() => Cursor::PencilNew, _ => Cursor::Pencil, } } diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index ece7a369bb..b62226692a 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -22,25 +22,67 @@ fn drag_held(t: &mut GestureTool, cx: &ToolContext, pts: &[(f64, f64)], m: Mods) v } -/// The Pencil's new path starts and ends on Smart Guides (#506), the points between where -/// the hand went. +/// The Pencil follows the hand from the press to the release: it ignores Smart Guides and Snap to Point and shows no +/// Smart Guides, hovering or drawing over the art, with Smart Guides on or with only Snap to Point. #[test] -fn pencil_ends_snap_to_smart_guides() { +fn pencil_follows_the_hand_and_shows_no_smart_guides() { let (d, _) = doc_with_rect(); let s = Selection::default(); let p = paint(); - let cx = cx(&d, &s, &p); - let mut t = GestureTool::new("pencil"); - let acts = drag(&mut t, &cx, &[(102.0, 98.0), (151.0, 300.0), (250.0, 320.0), (198.0, 203.0)], Mods::default()); - let Some(Action::Preview(_, v)) = acts.last().and_then(|a| a.first()) else { panic!("{acts:?}") }; - assert_eq!(v["points"], json!([[100.0, 100.0], [151.0, 300.0], [250.0, 320.0], [200.0, 200.0]])); + let on = cx(&d, &s, &p); + let snap_to_point = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + // Near the corners at (100, 100) and (200, 200), within Snap to Point's 2 px of them. + let hand = [(101.0, 99.0), (151.0, 300.0), (250.0, 320.0), (199.0, 201.0)]; + for cx in [&on, &snap_to_point] { + let mut t = GestureTool::new("pencil"); + t.pointer(cx, &PointerEvent::new(PointerKind::Move, hand[0].0, hand[0].1)); + assert!(t.overlays(cx).is_empty(), "hovering: {:?}", t.overlays(cx)); + t.pointer(cx, &PointerEvent::new(PointerKind::Down, hand[0].0, hand[0].1)); + for &(x, y) in &hand[1..] { + t.pointer(cx, &PointerEvent::new(PointerKind::Drag, x, y)); + assert!(t.snap.guides().is_empty(), "drawing: {:?}", t.snap.guides()); + } + let last = hand[hand.len() - 1]; + let acts = t.pointer(cx, &PointerEvent::new(PointerKind::Up, last.0, last.1)); + let Some(Action::Preview(_, v)) = acts.first() else { panic!("{acts:?}") }; + assert_eq!(v["points"], json!(hand.map(|(x, y)| [x, y]))); + } // The Paintbrush follows the hand all the way. let mut t = GestureTool::new("paintbrush"); - let acts = drag(&mut t, &cx, &[(102.0, 98.0), (151.0, 300.0)], Mods::default()); + let acts = drag(&mut t, &on, &[(102.0, 98.0), (151.0, 300.0)], Mods::default()); let Some(Action::Preview(_, v)) = acts.last().and_then(|a| a.first()) else { panic!("{acts:?}") }; assert_eq!(v["points"][0], json!([102.0, 98.0])); } +/// Snap to Grid and Snap to Pixel are not Smart Guides: they still move the Pencil's ends (and an +/// Alt line's), while the points between follow the hand. +#[test] +fn pencil_ends_still_snap_to_the_grid_and_pixels() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let grid = ToolContext { snap_to_grid: true, ..cx(&d, &s, &p) }; + let pixel = ToolContext { snap_to_pixel: true, ..cx(&d, &s, &p) }; + let on = |cx: &ToolContext, q: (f64, f64)| match cx.snap_to_grid { + true => vectorcraft_geom::snap::snap_point_to_grid(Point::new(q.0, q.1), cx.grid_step()), + false => Point::new(q.0.round(), q.1.round()), + }; + let hand = [(301.3, 302.6), (351.4, 420.2), (447.7, 452.9)]; + for cx in [&grid, &pixel] { + let (first, last) = (on(cx, hand[0]), on(cx, hand[2])); + assert!(first != Point::new(hand[0].0, hand[0].1) && last != Point::new(hand[2].0, hand[2].1)); + let mut t = GestureTool::new("pencil"); + let acts = drag(&mut t, cx, &hand, Mods::default()); + let Some(Action::Preview(_, v)) = acts.last().and_then(|a| a.first()) else { panic!("{acts:?}") }; + assert_eq!(v["points"], json!([[first.x, first.y], [351.4, 420.2], [last.x, last.y]])); + // Alt's straight line ends on the grid or a pixel too. + let mut t = GestureTool::new("pencil"); + let acts = drag_held(&mut t, cx, &[hand[0], hand[2]], Mods { alt: true, ..Mods::default() }); + let Some(Action::Preview(_, v)) = acts.last().and_then(|a| a.first()) else { panic!("{acts:?}") }; + assert_eq!(v["points"][1], json!([last.x, last.y])); + } +} + /// #852: the Paintbrush sends each point's pen pressure; a mouse (always fully pressed) and /// the Pencil send plain points. #[test] @@ -693,10 +735,10 @@ fn pencil_shift_draws_a_straight_line_at_45_degree_steps() { } } -/// #3799: a Shift line leaves no Smart Guides of its press on screen while it is dragged -/// (its end doesn't snap), and Alt at its release leaves it open. +/// #3799: a Shift line shows no Smart Guides, at its press or while it is dragged, and Alt at its +/// release leaves it open. #[test] -fn pencil_shift_line_drops_the_press_guides_and_stays_open_with_alt() { +fn pencil_shift_line_shows_no_guides_and_stays_open_with_alt() { let (d, _) = doc_with_rect(); let s = Selection::default(); let p = paint(); @@ -704,7 +746,7 @@ fn pencil_shift_line_drops_the_press_guides_and_stays_open_with_alt() { let shift = Mods { shift: true, ..Default::default() }; let mut t = GestureTool::new("pencil"); t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 102.0, 98.0).with_mods(shift)); - assert!(!t.overlays(&cx).is_empty(), "the press snaps to the corner and shows it"); + assert!(t.snap.guides().is_empty(), "the press: {:?}", t.snap.guides()); t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 300.0, 140.0).with_mods(shift)); assert!(t.overlays(&cx).is_empty(), "{:?}", t.overlays(&cx)); let shift_alt = Mods { shift: true, alt: true, ..Default::default() }; @@ -793,7 +835,7 @@ fn pencil_shows_the_star_before_a_press_that_draws_a_new_path() { } } let mut t = GestureTool::new("pencil"); - assert_eq!(t.cursor(&cx, end, Mods::default()), Cursor::Pencil, "over an end the stroke continues"); + assert_eq!(t.cursor(&cx, end, Mods::default()), Cursor::PencilContinue, "over an end the stroke continues"); assert_eq!(t.cursor(&cx, middle, Mods::default()), Cursor::Pencil, "over the path the stroke redraws"); assert_eq!(t.cursor(&cx, away, Mods::default()), Cursor::PencilNew, "away from the path"); // While a stroke is drawn, the Pencil's own cursor. @@ -838,7 +880,7 @@ fn pencil_shift_line_continues_a_selected_path_from_its_end() { } /// Before a press over an end of a selected open path, the Pencil shows its continuation cursor -/// exactly when the press would draw a straight line that continues the path; away from the +/// exactly when the press continues the path, freehand or with a straight line; away from the /// ends, with nothing selected, with Edit Selected Paths off, once the press is down and with /// the Paintbrush, it does not. #[test] @@ -859,12 +901,9 @@ fn pencil_shows_the_continuation_cursor_over_an_end_a_line_continues() { let shift = Mods { shift: true, ..Default::default() }; let alt = Mods { alt: true, ..Default::default() }; let shift_alt = Mods { shift: true, alt: true, ..Default::default() }; - // The release's stroke: a straight line that continues the path. - let continues = |acts: &[Vec]| { - acts.last() - .and_then(|a| a.first()) - .is_some_and(|a| matches!(a, Action::Preview(_, v) if v.get("extend").is_some() && v["points"].as_array().is_some_and(|q| q.len() == 2))) - }; + // The release's stroke continues the path. + let continues = + |acts: &[Vec]| acts.last().and_then(|a| a.first()).is_some_and(|a| matches!(a, Action::Preview(_, v) if v.get("extend").is_some())); for alt_smooth in [false, true] { for m in [Mods::default(), shift, alt, shift_alt] { for (at, other_end) in [(Point::new(405.0, 303.0), (500.0, 296.0)), (Point::new(296.0, 302.0), (200.0, 310.0))] { @@ -880,7 +919,7 @@ fn pencil_shows_the_continuation_cursor_over_an_end_a_line_continues() { let end = Point::new(405.0, 303.0); assert_eq!(t.cursor(&cx, end, shift), Cursor::PencilContinue); assert_eq!(t.cursor(&cx, end, alt), Cursor::PencilContinue, "Alt alone continues at any angle"); - assert_eq!(t.cursor(&cx, end, Mods::default()), Cursor::Pencil, "without Shift or Alt the stroke is freehand"); + assert_eq!(t.cursor(&cx, end, Mods::default()), Cursor::PencilContinue, "a freehand stroke continues it too"); assert_eq!(t.cursor(&cx, Point::new(350.0, 360.0), shift), Cursor::PencilStraight, "away from the ends"); // While the line is drawn, the Pencil's own cursor. t.pointer(&cx, &PointerEvent::new(PointerKind::Down, end.x, end.y).with_mods(shift)); @@ -897,6 +936,105 @@ fn pencil_shows_the_continuation_cursor_over_an_end_a_line_continues() { assert_eq!(Cursor::PencilContinue.precise(), Cursor::Crosshair, "Use Precise Cursors"); } +/// A Pencil stroke continuing a selected path shows the continuation cursor while a release would +/// connect it to an open end of another path selected at the press, and the closing ring while a +/// release would close the path because the stroke ends within Close Paths When Ends Are Within +/// of the path's other end, a straight line too; the release does what the cursor showed. +#[test] +fn a_continued_stroke_shows_where_it_connects_or_closes() { + let (mut d, _) = doc_with_rect(); + let l = d.layers[0].id; + let add = |d: &mut vectorcraft_doc::Document, pts: &[(f64, f64)]| { + let id = d.alloc_id(); + let mut els = vec![vectorcraft_geom::PathEl::MoveTo(Point::new(pts[0].0, pts[0].1))]; + els.extend(pts[1..].iter().map(|&(x, y)| vectorcraft_geom::PathEl::LineTo(Point::new(x, y)))); + let pd = vectorcraft_geom::PathData::from_bezpath(&vectorcraft_geom::BezPath::from_vec(els)); + d.insert(Some(l), 1, vectorcraft_doc::Node::path(id, pd, vectorcraft_doc::Appearance::default_art())).unwrap(); + id + }; + let a = add(&mut d, &[(300.0, 300.0), (400.0, 300.0), (400.0, 400.0)]); + let b = add(&mut d, &[(500.0, 500.0), (600.0, 500.0)]); + let p = paint(); + let mut both = Selection::default(); + both.set([a, b]); + let mut cx = cx(&d, &both, &p); + cx.smart_guides = false; + cx.snap_to_point = false; + let none = Mods::default(); + let shift = Mods { shift: true, ..Default::default() }; + // Runs a stroke from `pts[0]`, giving the cursor at its last point before the release and the + // release's `path.freehand` parameters. + let run = |t: &mut GestureTool, pts: &[(f64, f64)], m: Mods| { + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, pts[0].0, pts[0].1).with_mods(m)); + for &(x, y) in &pts[1..] { + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, x, y).with_mods(m)); + } + let (x, y) = pts[pts.len() - 1]; + let shown = t.cursor(&cx, Point::new(x, y), m); + let acts = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, x, y).with_mods(m)); + let Some(Action::Preview(_, v)) = acts.first() else { panic!("{acts:?}") }; + (shown, v.clone()) + }; + let mut t = GestureTool::new("pencil"); + // To the other selected path's start: it connects, and doesn't close. + let (shown, v) = run(&mut t, &[(400.0, 400.0), (450.0, 450.0), (498.0, 502.0)], none); + assert_eq!(shown, Cursor::PencilContinue, "near the other path's end"); + assert_eq!( + (v["extend"].clone(), v["connect"].clone(), v["closed"].clone()), + (json!({"id": a.0, "end": "end"}), json!({"id": b.0, "end": "start"}), json!(false)) + ); + // Back near the path's own start (10 px from it): the ring, and the release closes it. + let (shown, v) = run(&mut t, &[(400.0, 400.0), (350.0, 420.0), (290.0, 380.0), (292.0, 306.0)], none); + assert_eq!(shown, Cursor::PencilClose, "near the path's other end"); + assert_eq!((v["extend"].clone(), v["closed"].clone()), (json!({"id": a.0, "end": "end"}), json!(true))); + assert!(v.get("connect").is_none(), "{v}"); + // Farther than Close Paths When Ends Are Within (15 px): no ring, and it stays open. + let (shown, v) = run(&mut t, &[(400.0, 400.0), (350.0, 420.0), (290.0, 380.0), (290.0, 330.0)], none); + assert_eq!((shown, v["closed"].clone()), (Cursor::Pencil, json!(false)), "away from the other end"); + // A straight line from the end to near the start: the ring, and it closes the path. + let (shown, v) = run(&mut t, &[(400.0, 400.0), (350.0, 350.0), (306.0, 306.0)], shift); + assert_eq!(shown, Cursor::PencilClose, "a straight line near the other end"); + assert_eq!((v["points"].as_array().map(Vec::len), v["closed"].clone()), (Some(2), json!(true))); + // Close Paths When Ends Are Within off: neither ring nor close. + t.set_option("closeWithin", &json!(0.0)); + let (shown, v) = run(&mut t, &[(400.0, 400.0), (350.0, 420.0), (290.0, 380.0), (292.0, 306.0)], none); + assert_eq!((shown, v["closed"].clone()), (Cursor::Pencil, json!(false)), "at 0 px"); +} + +/// The continuation cursor tests where the release ends, after snapping, not the pointer: here +/// Snap to Grid moves a stroke's end from 13 pt away from another selected path's end (outside Edit +/// Selected Paths' 12 px) to 9 pt away, so the release connects, and the cursor says so. +#[test] +fn the_continuation_cursor_follows_the_snapped_release() { + let (mut d, _) = doc_with_rect(); + let l = d.layers[0].id; + let add = |d: &mut vectorcraft_doc::Document, a: (f64, f64), b: (f64, f64)| { + let id = d.alloc_id(); + let els = vec![vectorcraft_geom::PathEl::MoveTo(Point::new(a.0, a.1)), vectorcraft_geom::PathEl::LineTo(Point::new(b.0, b.1))]; + let pd = vectorcraft_geom::PathData::from_bezpath(&vectorcraft_geom::BezPath::from_vec(els)); + d.insert(Some(l), 1, vectorcraft_doc::Node::path(id, pd, vectorcraft_doc::Appearance::default_art())).unwrap(); + id + }; + // On the 9 pt grid. + let a = add(&mut d, (306.0, 306.0), (405.0, 405.0)); + let b = add(&mut d, (504.0, 504.0), (603.0, 504.0)); + let p = paint(); + let mut both = Selection::default(); + both.set([a, b]); + let mut cx = cx(&d, &both, &p); + cx.smart_guides = false; + cx.snap_to_point = false; + cx.snap_to_grid = true; + let mut t = GestureTool::new("pencil"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 405.0, 405.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 460.0, 450.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 517.0, 504.0)); + assert_eq!(t.cursor(&cx, Point::new(517.0, 504.0), Mods::default()), Cursor::PencilContinue); + let acts = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 517.0, 504.0)); + let Some(Action::Preview(_, v)) = acts.first() else { panic!("{acts:?}") }; + assert_eq!(v["connect"], json!({"id": b.0, "end": "start"}), "{v}"); +} + /// #3846: Alt during a Shift line doesn't promise a close the release can't do, and with Alt /// Toggles to Smooth, Alt pressed after the press doesn't turn the line into a smoothing drag. #[test] @@ -1649,10 +1787,11 @@ fn paintbrush_alt_with_a_two_anchor_curve_selected_smooths() { } } -/// #3799: Alt's line starts and ends on Smart Guides as a stroke does, and pressed on an end of -/// a selected open path it continues the path from that end to the pointer. +/// #3799: Alt's line runs from the press to the pointer as a stroke does, snapping to nothing, +/// and pressed on an end of a selected open path it continues the path from that end to the +/// pointer. #[test] -fn pencil_alt_line_snaps_its_ends_and_continues_a_selected_path() { +fn pencil_alt_line_follows_the_hand_and_continues_a_selected_path() { let (mut d, _) = doc_with_rect(); let alt = Mods { alt: true, ..Default::default() }; let p = paint(); @@ -1662,7 +1801,7 @@ fn pencil_alt_line_snaps_its_ends_and_continues_a_selected_path() { let mut t = GestureTool::new("pencil"); let acts = drag_held(&mut t, &cx, &[(102.0, 98.0), (151.0, 300.0), (198.0, 203.0)], alt); let Some(Action::Preview(_, v)) = acts.last().and_then(|a| a.first()) else { panic!("{acts:?}") }; - assert_eq!(v["points"], json!([[100.0, 100.0], [200.0, 200.0]])); + assert_eq!(v["points"], json!([[102.0, 98.0], [198.0, 203.0]])); } let l = d.layers[0].id; let id = d.alloc_id(); diff --git a/crates/tools/src/guides/snap.rs b/crates/tools/src/guides/snap.rs index 006f498b6e..d7ee8ecdd8 100644 --- a/crates/tools/src/guides/snap.rs +++ b/crates/tools/src/guides/snap.rs @@ -257,10 +257,11 @@ impl Leave { self } - /// The straight segment from the anchor `at` to a point being dragged (an open path's end - /// moved with Direct Selection): the point may land square to a segment or grazing a curve, - /// but is not held to Shift's angles or the construction guides, which a moved anchor - /// does not follow. + /// The straight segment from the point `at` to a point being placed (an open path's end + /// moved with Direct Selection, or the Dimension tool's second Linear point after a first + /// point that is not on an anchor): the point may + /// land square to a segment or grazing a curve, but is not held to Shift's angles or the + /// construction guides through `at`. pub fn contact(at: Point) -> Self { Self { at, shift: None, angles: &[], contact: true } } diff --git a/crates/tools/src/input.rs b/crates/tools/src/input.rs index 9b53d2404c..5362147b97 100644 --- a/crates/tools/src/input.rs +++ b/crates/tools/src/input.rs @@ -29,6 +29,9 @@ pub enum PointerKind { /// Moved with no button (hover). Move, DoubleClick, + /// The third click of a triple-click, after its press and release (the second click's + /// release sends [`PointerKind::DoubleClick`]). + TripleClick, } #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 1119bb0764..93f71431c1 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -450,6 +450,36 @@ pub(crate) mod testutil { (d, g, clip, art) } + /// A document with the rectangle of [`doc_with_rect`] and a clip group whose clipping path, + /// (400, 400)–(500, 500), has a live effect that moves the region it clips to 100 pt right + /// (registered with [`vectorcraft_doc::hit::set_clip_region`]), over art at (420, 420)–(480, 480), + /// inside the clipping path's own shape and outside the moved region: the document, the clip + /// group and the art. + pub fn doc_with_moved_clip_region() -> (Document, NodeId, NodeId) { + fn moved(clip: &Node) -> Option> { + let mut moves = false; + clip.walk(&mut |n| moves |= n.appearance.effects.iter().any(|e| e.visible && e.id == "test.move")); + if !moves { + return None; + } + Some(vectorcraft_doc::hit::clip_regions(clip).into_iter().next().map(|(mut bp, rule)| { + bp.apply_affine(vectorcraft_geom::Affine::translate((100.0, 0.0))); + (bp, rule) + })) + } + vectorcraft_doc::hit::set_clip_region(moved); + let (mut d, _) = doc_with_rect(); + let l = d.layers[0].id; + let (g, clip, art) = (d.alloc_id(), d.alloc_id(), d.alloc_id()); + let mut path = Node::path(clip, shapes::rectangle(Rect::new(400.0, 400.0, 500.0, 500.0)), Default::default()); + path.appearance.effects.push(vectorcraft_doc::Effect { id: "test.move".into(), params: serde_json::json!({}), visible: true }); + let picture = Node::path(art, shapes::rectangle(Rect::new(420.0, 420.0, 480.0, 480.0)), Appearance::default_art()); + let group = + Node::new(g, vectorcraft_doc::NodeKind::Group { children: vec![std::sync::Arc::new(path), std::sync::Arc::new(picture)], clip: true }); + d.insert(Some(l), 1, group).unwrap(); + (d, g, art) + } + /// A new layer of `d`, above the others, with the unpainted rectangle `mask` as its clipping /// mask and `art` clipped by it: the layer and the clipping mask. pub fn add_masked_layer(d: &mut Document, mask: Rect, art: Node) -> (NodeId, NodeId) { @@ -604,6 +634,7 @@ pub(crate) mod testutil { construction_angles: guides::construction_angles(guides::DEFAULT_CONSTRUCTION_ANGLES), screen: None, plane_widget: Some(Default::default()), + plane_targets: distort::perspective::widget::PlaneTargets::ALL, precise_cursors: false, global_edit: &[], } @@ -673,7 +704,10 @@ mod cursor_tests { // Away from a selected path the Pencil shows its new-path cursor, drawn with a star; its // own cursor, for drawing and for a selected path under the pointer, borrows the crosshair. assert_eq!(cursor_at("pencil", &d, away), Cursor::PencilNew); - assert_eq!(Cursor::PencilNew.precise(), Cursor::Crosshair); + // Its badged cursors too: Use Precise Cursors shows the plain crosshair. + for c in [Cursor::PencilNew, Cursor::PencilClose, Cursor::PencilStraight, Cursor::PencilContinue, Cursor::PaintbrushClose] { + assert_eq!(c.precise(), Cursor::Crosshair, "{c:?}"); + } assert_eq!(Cursor::PencilNew.stand_in(), None); assert_eq!(Cursor::Pencil.precise(), Cursor::Crosshair); assert_eq!(Cursor::Pencil.stand_in(), Some(Cursor::Crosshair)); diff --git a/crates/tools/src/objects_on_path.rs b/crates/tools/src/objects_on_path.rs index 8f19259126..fe956691e1 100644 --- a/crates/tools/src/objects_on_path.rs +++ b/crates/tools/src/objects_on_path.rs @@ -42,13 +42,14 @@ //! Behavior: , //! . +use std::sync::Arc; + use serde_json::{Value, json}; -use vectorcraft_doc::blend::Spine; use vectorcraft_doc::objects_on_path::{ - CENTER, Member, ObjectsOnPath, attachable_path, is_objects_on_path, layout, nth_length, path_length, stop, stops, + CENTER, Measured, Member, ObjectsOnPath, attachable, attachable_path, is_objects_on_path, layout, nth_length, }; use vectorcraft_doc::{Document, Node, NodeId, Selection}; -use vectorcraft_geom::{BezPath, Point, Vec2}; +use vectorcraft_geom::{BezPath, PathData, Point, Vec2}; use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; @@ -85,14 +86,20 @@ pub const MEMBER_RADIUS_PX: f32 = 4.5; /// How near (screen px) the pointer must be to hit a Select/Move widget. const MEMBER_HIT_PX: f64 = 6.0; -/// The Objects on Path group the widgets show for at `zoom` (screen px per document point), with -/// its record, its children and its path: only when the selection is that one editable group, on -/// a path with length, and no anchors are Direct-Selected. -fn one_group<'a>( - doc: &'a Document, - selection: &Selection, - zoom: f64, -) -> Option<(NodeId, &'a ObjectsOnPath, &'a [std::sync::Arc], &'a vectorcraft_geom::PathData)> { +/// An Objects on Path group the widgets show for, with its record, its children, its path and the +/// path measured: one flattening serves every widget of the group. +struct Group<'a> { + id: NodeId, + rec: &'a ObjectsOnPath, + children: &'a [Arc], + path: &'a PathData, + measured: Arc, +} + +/// The Objects on Path group the widgets show for at `zoom` (screen px per document point): only +/// when the selection is that one editable group, on a path with length, and no anchors are +/// Direct-Selected. +fn one_group<'a>(doc: &'a Document, selection: &Selection, zoom: f64) -> Option> { if !selection.anchors.is_empty() || !zoom.is_finite() || zoom <= 0.0 { return None; } @@ -103,8 +110,39 @@ fn one_group<'a>( let n = doc.node(*group)?; let rec = n.extras().objects_on_path.as_deref()?; let children = n.children()?; - let path = attachable_path(children.iter().find(|c| c.id == rec.path)?)?; - Some((*group, rec, children.as_slice(), path)) + let (path, measured) = attachable(children.iter().find(|c| c.id == rec.path)?)?; + Some(Group { id: *group, rec, children: children.as_slice(), path, measured: Arc::new(measured) }) +} + +/// The path of an Objects on Path group as measured when a widget drag began, kept for the drag: +/// the previews change the group's record and its objects, not its path. +#[derive(Clone, Debug)] +struct Kept { + group: NodeId, + path: PathData, + measured: Arc, +} + +impl Kept { + fn of(g: &Group) -> Self { + Self { group: g.id, path: g.path.clone(), measured: Arc::clone(&g.measured) } + } + + /// The group's path in `doc` measured: the kept measurement while the path is as it was, else + /// the path measured again and kept. `None` when the group no longer has a path with length. + fn now(&mut self, doc: &Document) -> Option> { + let n = doc.node(self.group)?; + let rec = n.extras().objects_on_path.as_deref()?; + let node = n.children()?.iter().find(|c| c.id == rec.path)?; + if let vectorcraft_doc::NodeKind::Path { path, guide: false, .. } = &node.kind + && *path == self.path + { + return Some(Arc::clone(&self.measured)); + } + let (path, measured) = attachable(node)?; + *self = Self { group: self.group, path: path.clone(), measured: Arc::new(measured) }; + Some(Arc::clone(&self.measured)) + } } /// The direction the top of the object `m` faces: the -y direction of the frame it is drawn in @@ -148,22 +186,27 @@ impl RotateAllWidget { /// selection is one editable Objects on Path group with at least one object on a path with /// length, and no anchors are Direct-Selected. pub fn of(doc: &Document, selection: &Selection, zoom: f64) -> Option { - let (group, rec, children, path) = one_group(doc, selection, zoom)?; - let first = rec.members.first()?; - let (pivot, _) = stop(path, rec.members.len(), rec.spacing, rec.start, 0)?; - let at = beside(doc, children, first, pivot, top(first), ROTATE_ALL_OFFSET_PX / zoom)?; - Some(Self { group, pivot, at, rotate: rec.rotate }) + Self::in_group(doc, &one_group(doc, selection, zoom)?, zoom) } - /// The widget of `cx` when `p` is within reach of it. - fn at_point(cx: &ToolContext, p: Point) -> Option { - Self::of(cx.doc, cx.selection, cx.zoom).filter(|w| w.at.distance(p) <= cx.tol(ROTATE_ALL_HIT_PX)) + /// The widget of the group `g`. + fn in_group(doc: &Document, g: &Group, zoom: f64) -> Option { + let rec = g.rec; + let first = rec.members.first()?; + let (pivot, _) = g.measured.stop(rec.members.len(), rec.spacing, rec.start, 0)?; + let at = beside(doc, g.children, first, pivot, top(first), ROTATE_ALL_OFFSET_PX / zoom)?; + Some(Self { group: g.id, pivot, at, rotate: rec.rotate }) + } + + /// The widget of the group `g` of `cx` when `p` is within reach of it. + fn at_point(cx: &ToolContext, g: &Group, p: Point) -> Option { + Self::in_group(cx.doc, g, cx.zoom).filter(|w| w.at.distance(p) <= cx.tol(ROTATE_ALL_HIT_PX)) } } /// Is `p` over the Rotate All widget? pub fn over_rotate_all(cx: &ToolContext, p: Point) -> bool { - RotateAllWidget::at_point(cx, p).is_some() + one_group(cx.doc, cx.selection, cx.zoom).and_then(|g| RotateAllWidget::at_point(cx, &g, p)).is_some() } /// Dragging the Rotate All widget: the group's Rotate follows the angle the pointer turns about @@ -191,7 +234,12 @@ impl RotateAllDrag { /// Start a drag when the press `ev` is on the Rotate All widget. pub fn hit(cx: &ToolContext, ev: &PointerEvent) -> Option { - let widget = RotateAllWidget::at_point(cx, ev.pos)?; + Self::hit_in(cx, &one_group(cx.doc, cx.selection, cx.zoom)?, ev) + } + + /// [`RotateAllDrag::hit`] on the group `g` of `cx`. + fn hit_in(cx: &ToolContext, g: &Group, ev: &PointerEvent) -> Option { + let widget = RotateAllWidget::at_point(cx, g, ev.pos)?; let d = ev.pos - widget.pivot; let last = d.y.atan2(d.x); let last = if last.is_finite() { last } else { 0.0 }; @@ -272,17 +320,22 @@ impl SpaceWidget { /// length, and no anchors are Direct-Selected. It sits beyond the last object's bounds, ahead /// along the path's direction there. pub fn of(doc: &Document, selection: &Selection, zoom: f64) -> Option { - let (group, rec, children, path) = one_group(doc, selection, zoom)?; + Self::in_group(doc, &one_group(doc, selection, zoom)?, zoom) + } + + /// The widget of the group `g`. + fn in_group(doc: &Document, g: &Group, zoom: f64) -> Option { + let (group, rec) = (g.id, g.rec); let count = rec.members.len(); if count < 2 { return None; } - let (len, closed) = path_length(path)?; + let (len, closed) = (g.measured.length(), g.measured.closed()); let (start, gap) = layout(len, closed, count, rec.spacing, rec.start); - let (last, angle) = stop(path, count, rec.spacing, rec.start, count - 1)?; + let (last, angle) = g.measured.stop(count, rec.spacing, rec.start, count - 1)?; let dir = Vec2::new(angle.cos(), angle.sin()); let m = rec.members.last()?; - let b = children.iter().find(|c| c.id == m.id)?.geometric_bounds_with(&doc.symbol_boxes())?; + let b = g.children.iter().find(|c| c.id == m.id)?.geometric_bounds_with(&doc.symbol_boxes())?; let corners = [Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x0, b.y1), Point::new(b.x1, b.y1)]; let reach = corners.iter().map(|c| (*c - last).dot(dir)).fold(0.0, f64::max); let at = last + dir * (reach + SPACE_OFFSET_PX / zoom); @@ -291,29 +344,26 @@ impl SpaceWidget { finite.then_some(Self { group, last, last_length, at, dir, len, closed, count, start, gap, saved: (rec.spacing, rec.start) }) } - /// The widget of `cx` when `p` is within reach of it. - fn at_point(cx: &ToolContext, p: Point) -> Option { - Self::of(cx.doc, cx.selection, cx.zoom).filter(|w| w.at.distance(p) <= cx.tol(SPACE_HIT_PX)) + /// The widget of the group `g` of `cx` when `p` is within reach of it. + fn at_point(cx: &ToolContext, g: &Group, p: Point) -> Option { + Self::in_group(cx.doc, g, cx.zoom).filter(|w| w.at.distance(p) <= cx.tol(SPACE_HIT_PX)) } } /// Is `p` over the Space widget? pub fn over_space(cx: &ToolContext, p: Point) -> bool { - SpaceWidget::at_point(cx, p).is_some() + one_group(cx.doc, cx.selection, cx.zoom).and_then(|g| SpaceWidget::at_point(cx, &g, p)).is_some() } -/// The distance along the path of the Objects on Path group of `w` in `doc` to the point nearest -/// `p` ([`Spine::nearest`]: past the ends of an open path, along the lines of its end segments), -/// staying near `from` when the pointer is following the path from there. The line from the last -/// object's attachment point through the widget counts as the path too, as far as the pointer is -/// ahead of that object along it, so a widget beyond a corner measures from where it is. The flag -/// says whether the point is on that line, where the distance runs on past the end of a closed path -/// instead of round it. -fn length_near(doc: &Document, w: &SpaceWidget, p: Point, from: Option) -> Option<(f64, bool)> { - let n = doc.node(w.group)?; - let rec = n.extras().objects_on_path.as_deref()?; - let path = attachable_path(n.children()?.iter().find(|c| c.id == rec.path)?)?; - let spine = Spine::new(path)?; +/// The distance along the path of the Objects on Path group of `w`, `measured`, to the point nearest +/// `p` ([`vectorcraft_doc::blend::Spine::nearest`]: past the ends of an open path, along the lines +/// of its end segments), staying near `from` when the pointer is following the path from there. The +/// line from the last object's attachment point through the widget counts as the path too, as far +/// as the pointer is ahead of that object along it, so a widget beyond a corner measures from where +/// it is. The flag says whether the point is on that line, where the distance runs on past the end +/// of a closed path instead of round it. +fn length_near(measured: &Measured, w: &SpaceWidget, p: Point, from: Option) -> Option<(f64, bool)> { + let spine = measured.spine(); let bias = |s: f64| from.filter(|f| f.is_finite()).map_or(0.0, |f| spine.apart(s, f) / 2.0); let ahead = (p - w.last).dot(w.dir); let line = (ahead >= 0.0).then(|| { @@ -334,6 +384,8 @@ fn length_near(doc: &Document, w: &SpaceWidget, p: Point, from: Option) -> #[derive(Clone, Debug)] pub struct SpaceDrag { widget: SpaceWidget, + /// The group's path, measured. + path: Kept, start: Point, began: bool, /// The distance along the path to the point nearest the pointer at the last drag (points). @@ -353,17 +405,23 @@ impl SpaceDrag { /// Start a drag when the press `ev` is on the Space widget. pub fn hit(cx: &ToolContext, ev: &PointerEvent) -> Option { - let widget = SpaceWidget::at_point(cx, ev.pos)?; - let (last, _) = length_near(cx.doc, &widget, ev.pos, None)?; - Some(Self { widget, start: ev.pos, began: false, last, along: 0.0, gap: widget.gap, at: ev.pos }) + Self::hit_in(cx, &one_group(cx.doc, cx.selection, cx.zoom)?, ev) + } + + /// [`SpaceDrag::hit`] on the group `g` of `cx`. + fn hit_in(cx: &ToolContext, g: &Group, ev: &PointerEvent) -> Option { + let widget = SpaceWidget::at_point(cx, g, ev.pos)?; + let (last, _) = length_near(&g.measured, &widget, ev.pos, None)?; + Some(Self { widget, path: Kept::of(g), start: ev.pos, began: false, last, along: 0.0, gap: widget.gap, at: ev.pos }) } /// The pointer moved to `p` from `self.at`: add the distance it moved along the path. On the /// line through the widget, from a point ahead of the last object, that is how far it moved /// along the line; otherwise it takes the shorter way round a closed path. fn follow(&mut self, doc: &Document, p: Point) { + let Some(measured) = self.path.now(doc) else { return }; let w = &self.widget; - let Some((t, on_line)) = length_near(doc, w, p, Some(self.last)) else { return }; + let Some((t, on_line)) = length_near(&measured, w, p, Some(self.last)) else { return }; let before = (self.at - w.last).dot(w.dir); let step = if on_line && before >= 0.0 { (p - w.last).dot(w.dir) - before @@ -469,10 +527,15 @@ impl MoveAllWidget { /// the distance from the first object to the last is shorter than the path. It sits beyond the /// first object's bounds, on the side its bottom faces. pub fn of(doc: &Document, selection: &Selection, zoom: f64) -> Option { - let (group, rec, children, path) = one_group(doc, selection, zoom)?; + Self::in_group(doc, &one_group(doc, selection, zoom)?, zoom) + } + + /// The widget of the group `g`. + fn in_group(doc: &Document, g: &Group, zoom: f64) -> Option { + let (group, rec, children) = (g.id, g.rec, g.children); let count = rec.members.len(); let first = rec.members.first()?; - let (len, closed) = path_length(path)?; + let (len, closed) = (g.measured.length(), g.measured.closed()); let (start, gap) = layout(len, closed, count, rec.spacing, rec.start); let most = if closed { len } else { len - gap * count.saturating_sub(1) as f64 }; if !closed && (!most.is_finite() || most <= 1e-9) { @@ -481,21 +544,21 @@ impl MoveAllWidget { // On an open path, Auto and a Space value the path is too short for draw the objects apart // by what is left of the path after the start, so another start would change the distance. let keeps = closed || count < 2 || rec.spacing.is_some_and(|g| (g - gap).abs() < 1e-9); - let (at_first, _) = stop(path, count, rec.spacing, rec.start, 0)?; + let (at_first, _) = g.measured.stop(count, rec.spacing, rec.start, 0)?; let at = beside(doc, children, first, at_first, -top(first), MOVE_ALL_OFFSET_PX / zoom)?; let finite = [len, start, most, rec.start].iter().all(|v| v.is_finite()); finite.then_some(Self { group, first: at_first, at, len, closed, start, most, gap: (!keeps).then_some(gap), saved: rec.start }) } - /// The widget of `cx` when `p` is within reach of it. - fn at_point(cx: &ToolContext, p: Point) -> Option { - Self::of(cx.doc, cx.selection, cx.zoom).filter(|w| w.at.distance(p) <= cx.tol(MOVE_ALL_HIT_PX)) + /// The widget of the group `g` of `cx` when `p` is within reach of it. + fn at_point(cx: &ToolContext, g: &Group, p: Point) -> Option { + Self::in_group(cx.doc, g, cx.zoom).filter(|w| w.at.distance(p) <= cx.tol(MOVE_ALL_HIT_PX)) } } /// Is `p` over the Move All widget? pub fn over_move_all(cx: &ToolContext, p: Point) -> bool { - MoveAllWidget::at_point(cx, p).is_some() + one_group(cx.doc, cx.selection, cx.zoom).and_then(|g| MoveAllWidget::at_point(cx, &g, p)).is_some() } /// Dragging the Move All widget: the distance the pointer moves along the path moves every object @@ -504,6 +567,8 @@ pub fn over_move_all(cx: &ToolContext, p: Point) -> bool { #[derive(Clone, Debug)] pub struct MoveAllDrag { widget: MoveAllWidget, + /// The group's path, measured. + path: Kept, start: Point, began: bool, /// The distance along the path to the point nearest the pointer at the last drag (points). @@ -521,9 +586,14 @@ impl MoveAllDrag { /// Start a drag when the press `ev` is on the Move All widget. pub fn hit(cx: &ToolContext, ev: &PointerEvent) -> Option { - let widget = MoveAllWidget::at_point(cx, ev.pos)?; - let (_, last) = group_spine(cx.doc, widget.group)?.nearest(ev.pos, Some(widget.start))?; - last.is_finite().then_some(Self { widget, start: ev.pos, began: false, last, to: widget.start, at: ev.pos }) + Self::hit_in(cx, &one_group(cx.doc, cx.selection, cx.zoom)?, ev) + } + + /// [`MoveAllDrag::hit`] on the group `g` of `cx`. + fn hit_in(cx: &ToolContext, g: &Group, ev: &PointerEvent) -> Option { + let widget = MoveAllWidget::at_point(cx, g, ev.pos)?; + let (_, last) = g.measured.spine().nearest(ev.pos, Some(widget.start))?; + last.is_finite().then_some(Self { widget, path: Kept::of(g), start: ev.pos, began: false, last, to: widget.start, at: ev.pos }) } /// The pointer moved to `p`: move the first object as far along the path as the point nearest @@ -531,8 +601,8 @@ impl MoveAllDrag { /// the first anchor and [`MoveAllWidget::most`], so moving back from beyond an end moves the /// objects back at once. fn follow(&mut self, doc: &Document, p: Point) { + let Some((_, t)) = self.path.now(doc).and_then(|m| m.spine().nearest(p, Some(self.last))) else { return }; let w = &self.widget; - let Some((_, t)) = group_spine(doc, w.group).and_then(|s| s.nearest(p, Some(self.last))) else { return }; let step = if w.closed { (t - self.last + w.len / 2.0).rem_euclid(w.len) - w.len / 2.0 } else { t - self.last }; if !t.is_finite() || !step.is_finite() { return; @@ -604,8 +674,13 @@ impl MemberWidget { /// its order along the path that is neither hidden nor locked: only when the selection is one /// editable Objects on Path group on a path with length, and no anchors are Direct-Selected. pub fn all(doc: &Document, selection: &Selection, zoom: f64) -> Vec { - let Some((group, rec, _, path)) = one_group(doc, selection, zoom) else { return vec![] }; - let Some(at) = stops(path, rec.members.len(), rec.spacing, rec.start) else { return vec![] }; + one_group(doc, selection, zoom).map(|g| Self::in_group(doc, selection, &g)).unwrap_or_default() + } + + /// The widgets of the group `g`, the selection. + fn in_group(doc: &Document, selection: &Selection, g: &Group) -> Vec { + let (group, rec) = (g.id, g.rec); + let at = g.measured.stops(rec.members.len(), rec.spacing, rec.start); let editable = doc.editable(); rec.members .iter() @@ -616,17 +691,16 @@ impl MemberWidget { .collect() } - /// The widget of `cx` nearest `p`, when `p` is within reach of it; of widgets as near, the - /// chosen one, else the first along the path. - fn at_point(cx: &ToolContext, p: Point) -> Option { + /// The widget of the group `g` of `cx` nearest `p`, when `p` is within reach of it; of widgets + /// as near, the chosen one, else the first along the path. + fn at_point(cx: &ToolContext, g: &Group, p: Point) -> Option { let reach = cx.tol(MEMBER_HIT_PX); // Every attachment point lies on the path: a pointer beyond reach of its bounds is over none. - let (_, _, _, path) = one_group(cx.doc, cx.selection, cx.zoom)?; - if !path.control_bounds()?.inflate(reach, reach).contains(p) { + if !g.path.control_bounds()?.inflate(reach, reach).contains(p) { return None; } let mut best: Option<(f64, Self)> = None; - for w in Self::all(cx.doc, cx.selection, cx.zoom) { + for w in Self::in_group(cx.doc, cx.selection, g) { let d = w.at.distance(p); let nearer = best.is_none_or(|(b, bw)| d < b - 1e-9 || (d <= b + 1e-9 && w.chosen && !bw.chosen)); if d <= reach && nearer { @@ -639,17 +713,87 @@ impl MemberWidget { /// Is `p` over a Select/Move widget? pub fn over_member(cx: &ToolContext, p: Point) -> bool { - MemberWidget::at_point(cx, p).is_some() + one_group(cx.doc, cx.selection, cx.zoom).and_then(|g| MemberWidget::at_point(cx, &g, p)).is_some() } /// The highlight of the Select/Move widget under `p`, if any: a ring around it. pub fn member_hover(cx: &ToolContext, p: Point) -> Option { - let w = MemberWidget::at_point(cx, p)?; + let w = MemberWidget::at_point(cx, &one_group(cx.doc, cx.selection, cx.zoom)?, p)?; let r = cx.tol(f64::from(MEMBER_RADIUS_PX) + 2.0); let ring = vectorcraft_geom::shapes::ellipse(vectorcraft_geom::Rect::new(w.at.x - r, w.at.y - r, w.at.x + r, w.at.y + r)); Some(Overlay::Path { path: ring.to_bezpath(), color: HIGHLIGHT, width: 1.5, dashed: false }) } +/// The widgets of the selection at `zoom` (screen px per document point), each as its own `of` or +/// `all` gives it, from one measurement of the group's path: for drawing them together. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Widgets { + pub members: Vec, + pub rotate_all: Option, + pub space: Option, + pub move_all: Option, +} + +impl Widgets { + pub fn of(doc: &Document, selection: &Selection, zoom: f64) -> Self { + let Some(g) = one_group(doc, selection, zoom) else { return Self::default() }; + Self { + members: MemberWidget::in_group(doc, selection, &g), + rotate_all: RotateAllWidget::in_group(doc, &g, zoom), + space: SpaceWidget::in_group(doc, &g, zoom), + move_all: MoveAllWidget::in_group(doc, &g, zoom), + } + } +} + +/// A widget of a selected Objects on Path group. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum WidgetKind { + RotateAll, + Space, + MoveAll, + Member, +} + +/// The widget `p` is over, of the Rotate All, Space, Move All and Select/Move widgets in that +/// order, from one measurement of the group's path: as [`over_rotate_all`], [`over_space`], +/// [`over_move_all`] and [`over_member`] answer in turn. +pub fn widget_at(cx: &ToolContext, p: Point) -> Option { + let g = one_group(cx.doc, cx.selection, cx.zoom)?; + if RotateAllWidget::at_point(cx, &g, p).is_some() { + Some(WidgetKind::RotateAll) + } else if SpaceWidget::at_point(cx, &g, p).is_some() { + Some(WidgetKind::Space) + } else if MoveAllWidget::at_point(cx, &g, p).is_some() { + Some(WidgetKind::MoveAll) + } else { + MemberWidget::at_point(cx, &g, p).map(|_| WidgetKind::Member) + } +} + +/// A drag of a widget of a selected Objects on Path group. +#[derive(Clone, Debug)] +pub enum WidgetDrag { + RotateAll(RotateAllDrag), + Space(SpaceDrag), + MoveAll(MoveAllDrag), + Member(MemberDrag), +} + +impl WidgetDrag { + /// The drag the press `ev` starts, of the Rotate All, Space, Move All and Select/Move widgets + /// in that order, from one measurement of the group's path: as [`RotateAllDrag::hit`], + /// [`SpaceDrag::hit`], [`MoveAllDrag::hit`] and [`MemberDrag::hit`] answer in turn. + pub fn hit(cx: &ToolContext, ev: &PointerEvent) -> Option { + let g = one_group(cx.doc, cx.selection, cx.zoom)?; + RotateAllDrag::hit_in(cx, &g, ev) + .map(Self::RotateAll) + .or_else(|| SpaceDrag::hit_in(cx, &g, ev).map(Self::Space)) + .or_else(|| MoveAllDrag::hit_in(cx, &g, ev).map(Self::MoveAll)) + .or_else(|| MemberDrag::hit_in(cx, &g, ev).map(Self::Member)) + } +} + /// Dragging a Select/Move widget: the object goes to the place along the path nearest the /// pointer, and the objects between it and its place move one place toward where it was, except /// hidden and locked ones (`object.objectsOnPath.moveMember`). On an open path a pointer beyond @@ -661,6 +805,8 @@ pub fn member_hover(cx: &ToolContext, p: Point) -> Option { #[derive(Clone, Debug)] pub struct MemberDrag { widget: MemberWidget, + /// The group's path, measured. + path: Kept, /// The objects in their order along the path when the press began. order: Vec, /// The distance along the path to each place (points), in that order. @@ -687,10 +833,14 @@ impl MemberDrag { /// Start a drag when the press `ev` is on a Select/Move widget. pub fn hit(cx: &ToolContext, ev: &PointerEvent) -> Option { - let widget = MemberWidget::at_point(cx, ev.pos)?; - let n = cx.doc.node(widget.group)?; - let rec = n.extras().objects_on_path.as_deref()?; - let (len, closed) = path_length(attachable_path(n.children()?.iter().find(|c| c.id == rec.path)?)?)?; + Self::hit_in(cx, &one_group(cx.doc, cx.selection, cx.zoom)?, ev) + } + + /// [`MemberDrag::hit`] on the group `g` of `cx`. + fn hit_in(cx: &ToolContext, g: &Group, ev: &PointerEvent) -> Option { + let widget = MemberWidget::at_point(cx, g, ev.pos)?; + let rec = g.rec; + let (len, closed) = (g.measured.length(), g.measured.closed()); let count = rec.members.len(); let (s0, gap) = layout(len, closed, count, rec.spacing, rec.start); let places: Vec = (0..count).map(|i| nth_length(len, closed, s0, gap, i)).collect(); @@ -698,7 +848,7 @@ impl MemberDrag { let editable = cx.doc.editable(); let open = rec.members.iter().map(|m| editable(m.id)).collect(); let order = rec.members.iter().map(|m| m.id).collect(); - Some(Self { widget, order, places, open, len, closed, start: ev.pos, began: false, last, target: widget.index }) + Some(Self { widget, path: Kept::of(g), order, places, open, len, closed, start: ev.pos, began: false, last, target: widget.index }) } /// How far apart along the path the distances `a` and `b` are: the shorter way round a closed @@ -733,8 +883,8 @@ impl MemberDrag { self.began = true; out.push(Action::Begin("Move Object on Path".into())); } - let w = &self.widget; - let Some(spine) = group_spine(cx.doc, w.group) else { return out }; + let Some(measured) = self.path.now(cx.doc) else { return out }; + let (w, spine) = (&self.widget, measured.spine()); let Some((near, t)) = spine.nearest(p, None) else { return out }; // Where the path passes as near the pointer more than once, the point nearest along the path // to where the drag was counts. @@ -767,13 +917,6 @@ impl MemberDrag { } } -/// The path of the Objects on Path group `g` of `doc`, to measure along. -fn group_spine(doc: &Document, g: NodeId) -> Option { - let n = doc.node(g)?; - let rec = n.extras().objects_on_path.as_deref()?; - Spine::new(attachable_path(n.children()?.iter().find(|c| c.id == rec.path)?)?) -} - /// The path a click at `p` attaches the selected objects to: the path object hit there, when it can /// take objects, is in no Objects on Path group, is not a clipping path or part of a compound path, /// blend, envelope, repeat or Intertwine group ([`vectorcraft_doc::objects_on_path::held`]), and @@ -781,14 +924,13 @@ fn group_spine(doc: &Document, g: NodeId) -> Option { pub fn target(cx: &ToolContext, p: Point) -> Option<(NodeId, BezPath)> { let h = vectorcraft_doc::hit::hit_test(cx.doc, p, cx.hit_options())?; let n = cx.doc.node(h.leaf)?; - let path = attachable_path(n)?; if h.ancestry.iter().filter(|a| **a != h.leaf).any(|a| cx.doc.node(*a).is_some_and(is_objects_on_path)) { return None; } - if vectorcraft_doc::objects_on_path::held(cx.doc, h.leaf).is_some() { + if vectorcraft_doc::objects_on_path::held(cx.doc, h.leaf).is_some() || !cx.selection.objects.iter().any(|id| *id != h.leaf) { return None; } - cx.selection.objects.iter().any(|id| *id != h.leaf).then(|| (h.leaf, path.to_bezpath())) + attachable_path(n).map(|path| (h.leaf, path.to_bezpath())) } pub struct ObjectsOnPathTool { @@ -856,28 +998,17 @@ impl Tool for ObjectsOnPathTool { self.pointer = (ev.kind == PointerKind::Move).then_some(p); match ev.kind { PointerKind::Move => { - let widget = over_rotate_all(cx, p) || over_space(cx, p) || over_move_all(cx, p) || over_member(cx, p); - self.hover = if widget { None } else { target(cx, p) }; + self.hover = if widget_at(cx, p).is_some() { None } else { target(cx, p) }; vec![] } PointerKind::Down => { - if let Some(d) = RotateAllDrag::hit(cx, ev) { - self.rotating = Some(d); - self.hover = None; - return vec![]; - } - if let Some(d) = SpaceDrag::hit(cx, ev) { - self.spacing = Some(d); - self.hover = None; - return vec![]; - } - if let Some(d) = MoveAllDrag::hit(cx, ev) { - self.moving = Some(d); - self.hover = None; - return vec![]; - } - if let Some(d) = MemberDrag::hit(cx, ev) { - self.member = Some(d); + if let Some(d) = WidgetDrag::hit(cx, ev) { + match d { + WidgetDrag::RotateAll(d) => self.rotating = Some(d), + WidgetDrag::Space(d) => self.spacing = Some(d), + WidgetDrag::MoveAll(d) => self.moving = Some(d), + WidgetDrag::Member(d) => self.member = Some(d), + } self.hover = None; return vec![]; } @@ -917,17 +1048,21 @@ impl Tool for ObjectsOnPathTool { if self.member.is_some() { return Cursor::Move; } - let idle = self.spacing.is_none() && self.moving.is_none(); - if self.rotating.is_some() || (idle && over_rotate_all(cx, p)) { - Cursor::Rotate - } else if self.spacing.is_some() || (self.moving.is_none() && over_space(cx, p)) { - Cursor::ArrowHollow - } else if self.moving.is_some() || over_move_all(cx, p) || over_member(cx, p) { - Cursor::Move - } else if target(cx, p).is_some() { - Cursor::ObjectsOnPath - } else { - Cursor::Arrow + if self.rotating.is_some() { + return Cursor::Rotate; + } + if self.spacing.is_some() { + return Cursor::ArrowHollow; + } + if self.moving.is_some() { + return Cursor::Move; + } + match widget_at(cx, p) { + Some(WidgetKind::RotateAll) => Cursor::Rotate, + Some(WidgetKind::Space) => Cursor::ArrowHollow, + Some(WidgetKind::MoveAll | WidgetKind::Member) => Cursor::Move, + None if target(cx, p).is_some() => Cursor::ObjectsOnPath, + None => Cursor::Arrow, } } @@ -1405,7 +1540,10 @@ mod tests { gap: 100.0, saved: (None, 0.0), }; - let moved = |along| SpaceDrag { widget: w, start: Point::ZERO, began: true, last: 0.0, along, gap: w.gap, at: Point::ZERO }; + let line = shapes::line(Point::ZERO, Point::new(400.0, 0.0)); + let path = Kept { group: NodeId(1), measured: Arc::new(Measured::new(&line).unwrap()), path: line }; + let moved = + |along| SpaceDrag { widget: w, path: path.clone(), start: Point::ZERO, began: true, last: 0.0, along, gap: w.gap, at: Point::ZERO }; assert_eq!(moved(30.0).spacing_at(false), (100.0, 0.0), "a quarter of the way round at most"); assert_eq!(moved(-60.0).spacing_at(false), (80.0, 0.0)); assert_eq!(moved(-60.0).spacing_at(true), (60.0, 310.0), "the span of 180 centered on the first anchor"); @@ -1958,4 +2096,168 @@ mod tests { t.pointer(&c, &ev(PointerKind::Down, 0.0, 300.0)); assert_eq!(t.pointer(&c, &ev(PointerKind::Up, 0.0, 300.0)), vec![choose(ids[2])], "the chosen one"); } + + /// What `f` returns, and how many times it flattened a path. + fn flattenings(f: impl FnOnce() -> T) -> (T, usize) { + let before = vectorcraft_doc::blend::spines_built(); + let out = f(); + (out, vectorcraft_doc::blend::spines_built() - before) + } + + /// Space 100 from 50 on the line from (0, 300) to (400, 300): the objects attach at (50, 300) + /// and (150, 300). The Rotate All widget is at (50, 274), the Move All widget at (50, 326) and + /// the Space widget at (176, 300). + #[test] + fn each_widget_lookup_flattens_the_path_once() { + let (d, g, sel) = spaced_doc(Some(100.0), 50.0); + let paint = paint(); + let c = cx(&d, &sel, &paint); + // Points to 1/1,000 pt, as the path is measured along its flattening. + let close = |a: Point, b: Point| a.distance(b) < 1e-3; + let (w, n) = flattenings(|| RotateAllWidget::of(&d, &sel, 1.0)); + assert_eq!(n, 1, "Rotate All"); + let w = w.unwrap(); + assert!(w.group == g && w.rotate == 0.0, "{w:?}"); + assert!(close(w.pivot, Point::new(50.0, 300.0)) && close(w.at, Point::new(50.0, 274.0)), "{w:?}"); + let (w, n) = flattenings(|| SpaceWidget::of(&d, &sel, 1.0)); + assert_eq!(n, 1, "Space"); + let w = w.unwrap(); + assert!(close(w.last, Point::new(150.0, 300.0)) && close(w.at, Point::new(176.0, 300.0)), "{w:?}"); + assert!((w.last_length - 150.0).abs() < 1e-3 && (w.len - 400.0).abs() < 1e-3 && !w.closed && w.count == 2, "{w:?}"); + assert!((w.start - 50.0).abs() < 1e-3 && (w.gap - 100.0).abs() < 1e-3 && w.saved == (Some(100.0), 50.0), "{w:?}"); + let (w, n) = flattenings(|| MoveAllWidget::of(&d, &sel, 1.0)); + assert_eq!(n, 1, "Move All"); + let w = w.unwrap(); + assert!(close(w.first, Point::new(50.0, 300.0)) && close(w.at, Point::new(50.0, 326.0)), "{w:?}"); + assert!((w.len - 400.0).abs() < 1e-3 && (w.start - 50.0).abs() < 1e-3 && (w.most - 300.0).abs() < 1e-3, "{w:?}"); + assert!(w.gap.is_none() && w.saved == 50.0 && !w.closed, "{w:?}"); + let (ws, n) = flattenings(|| MemberWidget::all(&d, &sel, 1.0)); + assert_eq!(n, 1, "Select/Move"); + assert_eq!(ws.iter().map(|w| w.index).collect::>(), [0, 1]); + assert!(close(ws[0].at, Point::new(50.0, 300.0)) && close(ws[1].at, Point::new(150.0, 300.0)), "{ws:?}"); + // Each hit test, over its widget. + type Over = fn(&ToolContext, Point) -> bool; + let hits: [(&str, Over, Point); 4] = [ + ("Rotate All", over_rotate_all, Point::new(50.0, 274.0)), + ("Space", over_space, Point::new(176.0, 300.0)), + ("Move All", over_move_all, Point::new(50.0, 326.0)), + ("Select/Move", over_member, Point::new(150.0, 300.0)), + ]; + for (what, over, p) in hits { + assert_eq!(flattenings(|| over(&c, p)), (true, 1), "{what}"); + } + assert_eq!(flattenings(|| member_hover(&c, Point::new(150.0, 300.0)).is_some()), (true, 1)); + // A group of one object has no Space widget, and its objects no room to move on an open + // path: one flattening finds that. + let (d1, sel1) = single_doc(); + assert_eq!(flattenings(|| SpaceWidget::of(&d1, &sel1, 1.0)), (None, 1)); + let (d2, _, sel2) = group_doc(0.0); + assert_eq!(flattenings(|| MoveAllWidget::of(&d2, &sel2, 1.0)), (None, 1)); + // Nothing flattens for a selection the widgets do not show for. + assert_eq!(flattenings(|| Widgets::of(&d, &Selection::default(), 1.0)), (Widgets::default(), 0)); + } + + /// All four kinds of widget come from one flattening, as each one's own lookup gives it; and the + /// widget under the pointer, in the order a press takes them, from one flattening too. + #[test] + fn the_widgets_of_a_group_share_one_flattening() { + let (d, _, sel) = spaced_doc(Some(100.0), 50.0); + let paint = paint(); + let c = cx(&d, &sel, &paint); + let (all, n) = flattenings(|| Widgets::of(&d, &sel, 1.0)); + assert_eq!(n, 1); + assert_eq!(all.members, MemberWidget::all(&d, &sel, 1.0)); + assert_eq!(all.rotate_all, RotateAllWidget::of(&d, &sel, 1.0)); + assert_eq!(all.space, SpaceWidget::of(&d, &sel, 1.0)); + assert_eq!(all.move_all, MoveAllWidget::of(&d, &sel, 1.0)); + assert!(all.rotate_all.is_some() && all.space.is_some() && all.move_all.is_some() && all.members.len() == 2); + let cases = [ + (Point::new(50.0, 274.0), Some(WidgetKind::RotateAll)), + (Point::new(176.0, 300.0), Some(WidgetKind::Space)), + (Point::new(50.0, 326.0), Some(WidgetKind::MoveAll)), + (Point::new(150.0, 300.0), Some(WidgetKind::Member)), + // On the path between the objects: over none of them, after every one is tested. + (Point::new(250.0, 300.0), None), + ]; + for (p, kind) in cases { + assert_eq!(flattenings(|| widget_at(&c, p)), (kind, 1), "{p:?}"); + } + // A pointer move and the cursor of each tool look once. + for t in [Box::new(crate::select::SelectionTool::default()) as Box, Box::new(ObjectsOnPathTool::default())] { + for (p, cursor) in [(Point::new(50.0, 274.0), Cursor::Rotate), (Point::new(176.0, 300.0), Cursor::ArrowHollow)] { + assert_eq!(flattenings(|| t.cursor(&c, p, Mods::default())), (cursor, 1), "{}", t.id()); + } + } + let mut t = ObjectsOnPathTool::default(); + assert_eq!(flattenings(|| t.pointer(&c, &ev(PointerKind::Move, 250.0, 300.0))), (vec![], 1)); + } + + /// A press on each widget measures the path once, and the drag that follows measures it no more + /// while the path stays as it was. + #[test] + fn a_widget_drag_flattens_the_path_once() { + let (d, g, sel) = spaced_doc(Some(100.0), 50.0); + let paint = paint(); + let c = cx(&d, &sel, &paint); + let presses = [ + ("Rotate All", Point::new(50.0, 274.0), Point::new(24.0, 300.0)), + ("Space", Point::new(176.0, 300.0), Point::new(226.0, 300.0)), + ("Move All", Point::new(50.0, 326.0), Point::new(100.0, 326.0)), + ("Select/Move", Point::new(150.0, 300.0), Point::new(40.0, 300.0)), + ]; + let tools: [Box Box>; 2] = + [Box::new(|| Box::new(crate::select::SelectionTool::default())), Box::new(|| Box::new(ObjectsOnPathTool::default()))]; + for new in &tools { + for (what, at, to) in presses { + let mut t = new(); + assert_eq!(flattenings(|| t.pointer(&c, &ev(PointerKind::Down, at.x, at.y))), (vec![], 1), "{what} {}", t.id()); + assert!(t.busy(), "{what} {}", t.id()); + let (acts, n) = flattenings(|| t.pointer(&c, &ev(PointerKind::Drag, to.x, to.y))); + assert_eq!(n, 0, "{what} {}", t.id()); + assert!(matches!(acts.last(), Some(Action::Preview(..))), "{what} {}: {acts:?}", t.id()); + let (acts, n) = flattenings(|| t.pointer(&c, &ev(PointerKind::Drag, to.x + 1.0, to.y))); + assert_eq!(n, 0, "{what} {}: {acts:?}", t.id()); + } + } + // The drags as each one's own press starts it. + type Hit = fn(&ToolContext, &PointerEvent) -> bool; + let checks: [(&str, Hit, Point); 4] = [ + ("Rotate All", |c, e| RotateAllDrag::hit(c, e).is_some(), Point::new(50.0, 274.0)), + ("Space", |c, e| SpaceDrag::hit(c, e).is_some(), Point::new(176.0, 300.0)), + ("Move All", |c, e| MoveAllDrag::hit(c, e).is_some(), Point::new(50.0, 326.0)), + ("Select/Move", |c, e| MemberDrag::hit(c, e).is_some(), Point::new(150.0, 300.0)), + ]; + for (what, hit, p) in checks { + assert_eq!(flattenings(|| hit(&c, &ev(PointerKind::Down, p.x, p.y))), (true, 1), "{what}"); + } + // The Move All drag moves the objects by what the pointer moves along the path: 50 pt. + let mut d = MoveAllDrag::hit(&c, &ev(PointerKind::Down, 50.0, 326.0)).unwrap(); + let acts = d.drag(&c, Point::new(100.0, 326.0)); + assert!(matches!(acts.last(), Some(Action::Preview(_, p)) if p["ids"] == json!([g.0])), "{acts:?}"); + assert_eq!(moved(&acts), Some((100.0, None)), "{acts:?}"); + } + + /// A drag whose group's path changes while it goes on measures the new path, once. + #[test] + fn a_widget_drag_follows_a_path_that_changed() { + let (d, g, sel) = spaced_doc(Some(100.0), 50.0); + let paint = paint(); + let c = cx(&d, &sel, &paint); + let mut drag = MoveAllDrag::hit(&c, &ev(PointerKind::Down, 50.0, 326.0)).unwrap(); + // The path now runs from (100, 300) to (500, 300): the pointer at (200, 326) is 100 pt along + // it, 50 pt on from where the press was. + let mut longer = d.clone(); + let line = longer.node(g).and_then(|n| n.children()).unwrap()[0].id; + if let Some(NodeKind::Path { path, .. }) = longer.node_mut(line).map(|n| &mut n.kind) { + *path = shapes::line(Point::new(100.0, 300.0), Point::new(500.0, 300.0)); + } + let c = cx(&longer, &sel, &paint); + let (acts, n) = flattenings(|| drag.drag(&c, Point::new(200.0, 326.0))); + assert_eq!(n, 1); + assert!(matches!(acts.last(), Some(Action::Preview(_, p)) if p["ids"] == json!([g.0])), "{acts:?}"); + assert_eq!(moved(&acts), Some((100.0, None)), "{acts:?}"); + let (acts, n) = flattenings(|| drag.drag(&c, Point::new(300.0, 326.0))); + assert_eq!(n, 0); + assert_eq!(moved(&acts), Some((200.0, None)), "{acts:?}"); + } } diff --git a/crates/tools/src/pen.rs b/crates/tools/src/pen.rs index a0ab57ae87..24a21d08ca 100644 --- a/crates/tools/src/pen.rs +++ b/crates/tools/src/pen.rs @@ -449,7 +449,7 @@ impl Tool for PenTool { } vec![Action::Commit] } - PointerKind::DoubleClick => vec![], + PointerKind::DoubleClick | PointerKind::TripleClick => vec![], } } fn key(&mut self, cx: &ToolContext, key: ToolKey, _m: Mods) -> Vec { diff --git a/crates/tools/src/printtiling.rs b/crates/tools/src/printtiling.rs index b4e0e06d0c..a28382daf8 100644 --- a/crates/tools/src/printtiling.rs +++ b/crates/tools/src/printtiling.rs @@ -68,7 +68,7 @@ impl Tool for PrintTilingTool { self.drag = None; vec![Action::Exec("print.tiling.set".into(), json!({ "reset": true }))] } - PointerKind::Move => vec![], + PointerKind::Move | PointerKind::TripleClick => vec![], } } diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index 76e4a5c977..f63be1193e 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -40,7 +40,7 @@ use std::cell::RefCell; use std::collections::HashMap; use serde_json::{Value, json}; -use vectorcraft_doc::hit::{Hit, HitKind, hit_test, marquee, objects_at, selected_hidden_at}; +use vectorcraft_doc::hit::{Hit, HitKind, hit_test, marquee_in_view, objects_at, selected_hidden_at}; use vectorcraft_doc::{NodeId, OrientedBox}; use vectorcraft_geom::{Affine, Point, Rect, Vec2}; @@ -48,9 +48,7 @@ use crate::bbox::{Handle, hit_handle, in_rotate_zone, move_delta, rotate_for_dra use crate::blendwidget::{self, BlendWidgetDrag}; use crate::corners::{self, CornerDrag, over_widget}; use crate::guides::{PointSnap, Targets, distance_guides, hold_on_path}; -use crate::objects_on_path::{ - MemberDrag, MoveAllDrag, RotateAllDrag, SpaceDrag, member_hover, over_member, over_move_all, over_rotate_all, over_space, -}; +use crate::objects_on_path::{MemberDrag, MoveAllDrag, RotateAllDrag, SpaceDrag, WidgetDrag, WidgetKind, member_hover, widget_at}; use crate::pathtype::{self, BracketDrag, over_bracket}; use crate::pie::{self, PieDrag}; use crate::rulerguide::GuideEdit; @@ -1159,7 +1157,7 @@ impl Tool for SelectionTool { if r.width() < Self::drag_threshold(cx) && r.height() < Self::drag_threshold(cx) { return if toggle { vec![] } else { vec![Action::Exec("select.none".into(), json!({}))] }; } - let touched = marquee(cx.doc, r, cx.isolation, false); + let touched = marquee_in_view(cx.doc, r, cx.isolation, false, cx.outline); let enclosed = marquee_enclosed(cx, enclosed, marquee_direction(cx, start, p, directional_inside)); let ids = if enclosed { inside(cx, r, touched) } else { touched }; let art = Action::Exec(if toggle { "select.toggle" } else { "select.set" }.into(), json!({ "ids": json_ids(&ids) })); @@ -1269,14 +1267,11 @@ impl Tool for SelectionTool { if blendwidget::over_widget(cx, p) { return Cursor::ArrowHollow; } - if over_rotate_all(cx, p) { - return Cursor::Rotate; - } - if over_space(cx, p) { - return Cursor::ArrowHollow; - } - if over_move_all(cx, p) || over_member(cx, p) { - return Cursor::Move; + match widget_at(cx, p) { + Some(WidgetKind::RotateAll) => return Cursor::Rotate, + Some(WidgetKind::Space) => return Cursor::ArrowHollow, + Some(WidgetKind::MoveAll | WidgetKind::Member) => return Cursor::Move, + None => {} } if over_bracket(cx, p) { return Cursor::PathBracket; @@ -1651,20 +1646,13 @@ impl SelectionTool { self.state = State::BlendWidget(d); return Some(vec![]); } - if let Some(d) = RotateAllDrag::hit(cx, ev) { - self.state = State::RotateAll(d); - return Some(vec![]); - } - if let Some(d) = SpaceDrag::hit(cx, ev) { - self.state = State::Space(d); - return Some(vec![]); - } - if let Some(d) = MoveAllDrag::hit(cx, ev) { - self.state = State::MoveAll(d); - return Some(vec![]); - } - if let Some(d) = MemberDrag::hit(cx, ev) { - self.state = State::Member(d); + if let Some(d) = WidgetDrag::hit(cx, ev) { + self.state = match d { + WidgetDrag::RotateAll(d) => State::RotateAll(d), + WidgetDrag::Space(d) => State::Space(d), + WidgetDrag::MoveAll(d) => State::MoveAll(d), + WidgetDrag::Member(d) => State::Member(d), + }; return Some(vec![]); } if let Some(b) = BracketDrag::hit(cx, ev) { diff --git a/crates/tools/src/select/tests.rs b/crates/tools/src/select/tests.rs index b7af316571..3a47a9c85e 100644 --- a/crates/tools/src/select/tests.rs +++ b/crates/tools/src/select/tests.rs @@ -2646,3 +2646,22 @@ fn outline_view_click_through_an_image_selects_the_path_behind() { assert!(!selects(&a, back), "preview, {picked:?} selected: {a:?}"); } } + +/// A marquee across clipped art where the clipping path's own shape, but not the region a live +/// effect moved it to, lets it show reaches the clip group in Outline view only, which draws the +/// clipping path without its effects. +#[test] +fn outline_view_marquees_measure_a_clip_group_by_its_plain_clipping_path() { + let (d, g, _) = doc_with_moved_clip_region(); + let s = Selection::default(); + let p = paint(); + let marquee = |outline: bool| { + let cx = ToolContext { outline, ..cx(&d, &s, &p) }; + let mut t = SelectionTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, 440.0, 410.0)); + t.pointer(&cx, &ev(PointerKind::Drag, 460.0, 430.0)); + t.pointer(&cx, &ev(PointerKind::Up, 460.0, 430.0)) + }; + assert_eq!(marquee(true), vec![Action::Exec("select.set".into(), json!({"ids": [g.0]}))]); + assert_eq!(marquee(false), vec![Action::Exec("select.set".into(), json!({"ids": []}))]); +} diff --git a/crates/tools/src/symbolism.rs b/crates/tools/src/symbolism.rs index 1618d6e7d6..580e61d4fd 100644 --- a/crates/tools/src/symbolism.rs +++ b/crates/tools/src/symbolism.rs @@ -238,10 +238,15 @@ impl Default for BrushPaintTool { } impl BrushPaintTool { + /// The tool's brush, else the document's current brush, skipping a name the document's brush + /// library no longer has (a deleted brush), so the stroke is drawn without it. fn brush_name(&self, cx: &ToolContext) -> Option { - self.brush.clone().or_else(|| cx.doc.unknown.get("currentBrush").and_then(Value::as_str).map(str::to_string)) + [self.brush.clone(), vectorcraft_brush::current(cx.doc)].into_iter().flatten().find(|n| vectorcraft_brush::find(cx.doc, n).is_some()) } fn map(&self, cx: &ToolContext, acts: Vec) -> Vec { + if !acts.iter().any(|a| matches!(a, Action::Preview(c, _) if c == "path.freehand")) { + return acts; + } let Some(b) = self.brush_name(cx) else { return acts }; acts.into_iter() .map(|a| match a { @@ -403,4 +408,23 @@ mod tests { t.set_option("brush", &json!("Dots")); assert_eq!(t.options()["brush"], "Dots"); } + + #[test] + fn paintbrush_skips_a_brush_the_document_does_not_have() { + let (mut d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let drag = |d: &vectorcraft_doc::Document, t: &mut BrushPaintTool| { + let cx = cx(d, &s, &p); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 0.0, 0.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 30.0, 0.0)).swap_remove(1) + }; + d.unknown.insert("currentBrush".into(), json!("Charcoal")); + let mut t = BrushPaintTool::default(); + t.set_option("brush", &json!("Deleted")); + let a = drag(&d, &mut t); + assert!(matches!(&a, Action::Preview(c, v) if c == "brush.freehand" && v["brush"] == "Charcoal"), "the current brush: {a:?}"); + d.unknown.insert("currentBrush".into(), json!("Also deleted")); + let a = drag(&d, &mut BrushPaintTool::default()); + assert!(matches!(&a, Action::Preview(c, v) if c == "path.freehand" && v.get("brush").is_none()), "no brush: {a:?}"); + } } diff --git a/crates/tools/src/text/tool.rs b/crates/tools/src/text/tool.rs index dd561bc616..e18754f0ca 100644 --- a/crates/tools/src/text/tool.rs +++ b/crates/tools/src/text/tool.rs @@ -113,6 +113,7 @@ impl Tool for TypeTool { } vec![] } + PointerKind::TripleClick => vec![], PointerKind::Move => { // The type being edited is no target: its guides would only point at itself. self.snap.hover(cx, ev.pos, self.editing.as_slice(), None); diff --git a/crates/tools/src/touchtype.rs b/crates/tools/src/touchtype.rs index 018a65aefc..d195f276e4 100644 --- a/crates/tools/src/touchtype.rs +++ b/crates/tools/src/touchtype.rs @@ -387,7 +387,7 @@ impl Tool for TouchTypeTool { Some(d) if d.began => vec![Action::Commit], _ => vec![], }, - PointerKind::DoubleClick | PointerKind::Move => vec![], + PointerKind::DoubleClick | PointerKind::TripleClick | PointerKind::Move => vec![], } } diff --git a/crates/tools/src/xform/gradient.rs b/crates/tools/src/xform/gradient.rs index 9a61c98591..5a3565f3a9 100644 --- a/crates/tools/src/xform/gradient.rs +++ b/crates/tools/src/xform/gradient.rs @@ -582,7 +582,7 @@ impl Tool for GradientTool { let at = a.stop_point(cx, i).unwrap_or(ev.pos); vec![Self::select_stop(i), Action::Dialog("gradientStop".into(), json!({ "index": i, "x": at.x, "y": at.y }))] } - PointerKind::Move => vec![], + PointerKind::Move | PointerKind::TripleClick => vec![], } } diff --git a/crates/tools/src/xform/transform.rs b/crates/tools/src/xform/transform.rs index 263c0ea5e4..395b235e4a 100644 --- a/crates/tools/src/xform/transform.rs +++ b/crates/tools/src/xform/transform.rs @@ -272,6 +272,7 @@ impl Tool for TransformTool { None => vec![], } } + PointerKind::TripleClick => vec![], PointerKind::Move => { if self.drag.is_none() { self.hover = if cx.selection.is_empty() { vec![] } else { snap_pick(cx, p).1 }; diff --git a/crates/trace/src/logo/pipeline.rs b/crates/trace/src/logo/pipeline.rs index 766cf242dd..16bb1b3b08 100644 --- a/crates/trace/src/logo/pipeline.rs +++ b/crates/trace/src/logo/pipeline.rs @@ -6,7 +6,7 @@ use super::march::{area2, contours}; use super::outline::{Stats, Style, fit_outline}; use super::palette::{WHITE_MIN, auto_palette, flat_fraction, fold_tones, parse_hex, unexplained_colours}; use super::restore::RestoreParams; -use super::unmix::{Px, count_ambiguous, unmix}; +use super::unmix::{Px, Switched, count_ambiguous, unmix}; use crate::{Raster, TraceError, TraceParams, TraceResult, TracedPath}; use vectorcraft_geom::{Anchor, AnchorKind, PathData, Point, SubPath}; @@ -20,7 +20,7 @@ const FIELD_CELLS_MAX: usize = 6_000_000; const MIN_FLAT: f64 = 0.93; /// Most outlines of one colour (above the noise threshold) we will fit; more is refused, not truncated. const MAX_LOOPS_PER_CLASS: usize = if cfg!(test) { 500 } else { 20_000 }; -/// Most distinct pixel values `unmix` may have to work on (those that are not exactly one color). A busier image is +/// Most distinct pixel values `unmix` may have to work on (`count_ambiguous`). A busier image is /// averaged down further first, which bounds the time on pathological input. const EDGE_BUDGET: usize = 150_000; /// Palette colours closer than this (RGB distance) are one colour. @@ -320,27 +320,33 @@ fn keep_shape(s: &Shape, map: &ToSource, kept: &mut Vec, anchors_made: &mu /// A hard-edged source (a GIF, say) has no anti-aliasing to read an edge position from, and its /// outlines would follow the pixel staircase. Blurring the coverage by under a pixel gives the -/// outline a smooth edge to find. Sources with plenty of blended edge pixels are left alone. -fn soften_if_aliased(planes: &mut [Vec], w: usize, h: usize) -> bool { +/// outline a smooth edge to find. Sources with plenty of blended edge pixels are left alone. The +/// pixels that took another mix than their best one (`switched`) are judged by their best mix. +fn soften_if_aliased(planes: &mut [Vec], switched: &Switched, w: usize, h: usize) -> bool { let n = w * h; - let dominant: Vec = - (0..n).map(|i| (0..planes.len()).max_by(|&a, &b| plane_at(planes, a, i).total_cmp(&plane_at(planes, b, i))).unwrap_or(0)).collect(); - let (mut boundary, mut blended) = (0usize, 0usize); - for y in 0..h { - for x in 0..w { - let i = y * w + x; - let d = dominant.get(i).copied().unwrap_or(0); - let strongest = (0..planes.len()).map(|c| plane_at(planes, c, i)).fold(0.0f32, f32::max); - if strongest < 0.9 { - blended += 1; - } - let differs = |j: usize| dominant.get(j).is_some_and(|&o| o != d); - if (x + 1 < w && differs(i + 1)) || (y + 1 < h && differs(i + w)) { - boundary += 1; + let aliased = { + let at = |c: usize, i: usize| match switched.binary_search_by_key(&i, |&(j, _)| j) { + Ok(s) => switched.get(s).and_then(|(_, col)| col.get(c)).copied().unwrap_or(0.0), + Err(_) => plane_at(planes, c, i), + }; + let dominant: Vec = (0..n).map(|i| (0..planes.len()).max_by(|&a, &b| at(a, i).total_cmp(&at(b, i))).unwrap_or(0)).collect(); + let (mut boundary, mut blended) = (0usize, 0usize); + for y in 0..h { + for x in 0..w { + let i = y * w + x; + let d = dominant.get(i).copied().unwrap_or(0); + let strongest = (0..planes.len()).map(|c| at(c, i)).fold(0.0f32, f32::max); + if strongest < 0.9 { + blended += 1; + } + let differs = |j: usize| dominant.get(j).is_some_and(|&o| o != d); + if (x + 1 < w && differs(i + 1)) || (y + 1 < h && differs(i + w)) { + boundary += 1; + } } } - } - let aliased = boundary > 0 && blended * 4 < boundary; + boundary > 0 && blended * 4 < boundary + }; if aliased { for p in planes.iter_mut() { blur_plane(p, w, h, 0.8); @@ -437,26 +443,27 @@ pub(crate) fn trace_logo(img: &Raster, params: &TraceParams, max_anchors: usize) let mut classes = classes_for(&palette, own_white || merge_white.is_some()); // A very busy image is averaged down further until the unmixing work is bounded. for _ in 0..6 { - if count_ambiguous(&pix, &classes) <= EDGE_BUDGET || w * h <= 16_384 { + if count_ambiguous(&pix, w, h, &classes) <= EDGE_BUDGET || w * h <= 16_384 { break; } (pix, w, h, factor) = working_copy(img, factor * 2); } - let (mut planes, residual) = unmix(&pix, w, h, &classes); - let mut planes = if params.logo_colors.is_empty() && palette.len() < MAX_COLOURS { + let (mut planes, residual, switched) = unmix(&pix, w, h, &classes); + let (mut planes, mut switched) = if params.logo_colors.is_empty() && palette.len() < MAX_COLOURS { // Colours too small to be found at first show up as pixels nothing explains: add them. let extra = unexplained_colours(&pix, w, h, &residual, &palette); if extra.is_empty() { - planes + (planes, switched) } else { palette.extend(extra.into_iter().take(MAX_COLOURS - palette.len())); // (A colour nothing explained may be one more tone of a colour that is there.) palette = fold_tones(&pix, palette); classes = classes_for(&palette, own_white); - unmix(&pix, w, h, &classes).0 + let (planes, _, switched) = unmix(&pix, w, h, &classes); + (planes, switched) } } else { - std::mem::take(&mut planes) + (std::mem::take(&mut planes), switched) }; if let Some(to) = merge_white && palette.len() < planes.len() @@ -467,10 +474,18 @@ pub(crate) fn trace_logo(img: &Raster, params: &TraceParams, max_anchors: usize) *t += *v; } } + for (_, col) in &mut switched { + if palette.len() < col.len() { + let white_weight = col.remove(palette.len()); + if let Some(t) = col.get_mut(to) { + *t += white_weight; + } + } + } } // Without a white class, `white` is an index no class has. let (white, transparent) = if own_white { (palette.len(), palette.len() + 1) } else { (usize::MAX, palette.len()) }; - let aliased = soften_if_aliased(&mut planes, w, h); + let aliased = soften_if_aliased(&mut planes, &switched, w, h); if own_white { fill_knockouts(&mut planes, w, h, white, transparent); } diff --git a/crates/trace/src/logo/tests.rs b/crates/trace/src/logo/tests.rs index 168ba05d7f..33ab678a1f 100644 --- a/crates/trace/src/logo/tests.rs +++ b/crates/trace/src/logo/tests.rs @@ -919,3 +919,242 @@ fn an_outline_fitted_without_area_is_left_out() { } } } + +/// A black disc and a gray square on white, the gray lying on the line from black to white: the +/// disc's edge pixels are blends of black and white, so the gray is one shape (the square) and no +/// gray lines the disc. Colors found and named exactly, the darker gray also named 52 levels off; +/// sharp and soft edges. +#[test] +fn a_gray_between_black_and_white_is_one_shape() { + const INK: [u8; 3] = [4, 4, 3]; + for gray in [[230u8, 230, 230], [200, 200, 200]] { + for blur in [0.0, 0.6] { + let img = render(120, 60, blur, |x, y| { + Some(if (x - 30.0).hypot(y - 30.0) <= 20.0 { + INK + } else if (60.0..=110.0).contains(&x) && (10.0..=50.0).contains(&y) { + gray + } else { + WHITE + }) + }); + // (A gray of 230 named 52 levels darker lies nearer white than its name, and is traced as white.) + let offs: &[Option] = if gray[0] == 200 { &[None, Some(0), Some(52)] } else { &[None, Some(0)] }; + for &by in offs { + let (p, gray_name) = match by { + None => (logo_params(), gray), + Some(by) => { + // Each name moved `by` levels toward mid-gray: the black lighter, the gray darker. + let names = [INK.map(|v| v.saturating_add(by)), gray.map(|v| v.saturating_sub(by))]; + let logo_colors = names.iter().map(|c| format!("#{:02X}{:02X}{:02X}", c[0], c[1], c[2])).collect(); + (TraceParams { logo_colors, ..logo_params() }, names[1]) + } + }; + let what = format!("gray {gray:?}, blur {blur}, names moved {by:?}"); + let res = trace(&img, &p); + let grays = res.paths.iter().filter(|t| t.color == gray_name).count(); + let paths: Vec<_> = res.paths.iter().map(|t| (t.color, t.pixels)).collect(); + assert_eq!(grays, 1, "{what}: {grays} gray paths; {paths:?}"); + assert_eq!(top_color(&res, Point::new(85.0, 30.0)), Some(gray_name), "{what}: the square"); + for k in 0..16 { + let a = f64::from(k) * std::f64::consts::TAU / 16.0; + let at = Point::new(30.0 + 20.0 * a.cos(), 30.0 + 20.0 * a.sin()); + assert_ne!(top_color(&res, at), Some(gray_name), "{what}: the disc's edge at {at:?}"); + } + } + } + } +} + +/// A one-pixel gray line between flat black and flat white, with the three colors named, stays a +/// gray line along its whole length, beside a black disc whose edge pixels are as light as the gray. +#[test] +fn a_one_pixel_gray_line_between_black_and_white_stays_gray() { + const INK: [u8; 3] = [4, 4, 3]; + for gray in [[230u8, 230, 230], [200, 200, 200], [128, 128, 128]] { + let img = render(120, 80, 0.0, |x, y| { + Some(if x < 40.0 || (x - 90.0).hypot(y - 40.0) <= 15.0 { + INK + } else if x < 41.0 { + gray + } else { + WHITE + }) + }); + let logo_colors = vec!["#040403".into(), format!("#{:02X}{:02X}{:02X}", gray[0], gray[1], gray[2]), "#FFFFFF".into()]; + let res = trace(&img, &TraceParams { logo_colors, ..logo_params() }); + let paths: Vec<_> = res.paths.iter().map(|t| (t.color, t.pixels)).collect(); + for y in 2..78 { + let at = Point::new(40.5, f64::from(y) + 0.5); + assert_eq!(top_color(&res, at), Some(gray), "gray {gray:?}: the line at {at:?}; {paths:?}"); + } + for k in 0..16 { + let a = f64::from(k) * std::f64::consts::TAU / 16.0; + let at = Point::new(90.0 + 15.0 * a.cos(), 40.0 + 15.0 * a.sin()); + assert_ne!(top_color(&res, at), Some(gray), "gray {gray:?}: the disc's edge at {at:?}"); + } + } +} + +/// A gray stroke 12 pixels long touching a black disc on white, with the three colors named: the +/// stroke's pixels join the disc's edge pixels that are as light as the gray, but no gray lines the +/// rest of the disc's edge, and a sharp stroke stays gray. Strokes two and three pixels wide outside +/// the disc, on and off the pixel grid, sharp and soft. A soft stroke about two pixels wide that +/// touches black is traced as black and white, and one about three pixels wide in part, so the +/// stroke's own color is checked on sharp strokes. +#[test] +fn a_gray_stroke_touching_a_black_disc_leaves_its_edge_black_and_white() { + const INK: [u8; 3] = [4, 4, 3]; + for gray in [[230u8, 230, 230], [200, 200, 200], [128, 128, 128]] { + for blur in [0.0, 0.6] { + // The disc reaches x = 42 to 43 along the stroke's rows; each stroke starts inside it. + for (sx, wide) in [(41.0, 4.0), (41.5, 4.0), (41.0, 5.0)] { + let img = render(120, 60, blur, |x, y| { + Some(if (x - 25.0).hypot(y - 28.0) <= 18.0 { + INK + } else if (sx..sx + wide).contains(&x) && (22.0..34.0).contains(&y) { + gray + } else { + WHITE + }) + }); + let logo_colors = vec!["#040403".into(), format!("#{:02X}{:02X}{:02X}", gray[0], gray[1], gray[2]), "#FFFFFF".into()]; + let res = trace(&img, &TraceParams { logo_colors, ..logo_params() }); + let paths: Vec<_> = res.paths.iter().map(|t| (t.color, t.pixels)).collect(); + let what = format!("gray {gray:?}, blur {blur}, stroke at {sx} {wide} px wide"); + if blur == 0.0 { + for y in 24..32 { + let at = Point::new(sx + wide - 1.0, f64::from(y) + 0.5); + assert_eq!(top_color(&res, at), Some(gray), "{what}: the stroke at {at:?}; {paths:?}"); + } + } + // Points on the disc's edge more than 30 degrees from the stroke (which spans about 20). + for k in 6..=58 { + let a = f64::from(k) * std::f64::consts::TAU / 64.0; + let at = Point::new(25.0 + 18.0 * a.cos(), 28.0 + 18.0 * a.sin()); + assert_ne!(top_color(&res, at), Some(gray), "{what}: the disc's edge at {at:?}; {paths:?}"); + } + } + } + } +} + +/// Stripes on white (black, a dark gray with a black disc on it, a light gray), with the colors +/// named 52 levels off: each gray then lies on the line between two other names, and the dark +/// stripe's rows beside white keep the stripe's color above and below the disc. Sharp and soft edges, +/// with and without white named. +#[test] +fn a_gray_stripe_beside_white_keeps_its_color_beside_a_black_disc() { + const INK: [u8; 3] = [5, 5, 3]; + for blur in [0.0, 0.6] { + let img = render(300, 160, blur, |x, y| { + let inside = |x0: f64, y0: f64, x1: f64, y1: f64| (x0..x1).contains(&x) && (y0..y1).contains(&y); + Some(if (x - 150.0).hypot(y - 80.0) <= 12.0 || inside(20.0, 20.0, 280.0, 50.0) { + INK + } else if inside(20.0, 65.0, 280.0, 95.0) { + [100, 100, 100] + } else if inside(20.0, 110.0, 280.0, 140.0) { + [190, 190, 190] + } else { + WHITE + }) + }); + for white in [false, true] { + let mut logo_colors: Vec = ["#393937", "#989898", "#8A8A8A"].iter().map(|s| (*s).to_string()).collect(); + if white { + logo_colors.push("#FFFFFF".into()); + } + let res = trace(&img, &TraceParams { logo_colors, ..logo_params() }); + let what = format!("blur {blur}, white named {white}"); + let paths: Vec<_> = res.paths.iter().map(|t| (t.color, t.pixels)).collect(); + let stripe = top_color(&res, Point::new(60.0, 80.0)); + assert_ne!(stripe, Some([0x39, 0x39, 0x37]), "{what}: the stripe; {paths:?}"); + for x in [140.0, 145.0, 150.0, 155.0, 160.0] { + for y in [65.5, 94.5] { + assert_eq!(top_color(&res, Point::new(x, y)), stripe, "{what}: ({x}, {y}); {paths:?}"); + } + } + if blur == 0.0 { + let inks = res.paths.iter().filter(|t| t.color == [0x39, 0x39, 0x37]).count(); + assert_eq!(inks, 2, "{what}: {inks} paths in the black's name; {paths:?}"); + } + } + } +} + +/// Gray strokes two and three pixels wide on white (whole pixels of the gray), 3 and 4 px from a +/// black disc, and a two-pixel stroke six pixels long, fewer pixels than a line needs to keep its +/// class, 2 to 4.5 px from the disc: the strokes' pixels are blends of black and white too, but nothing +/// darker than the gray lies beside them, and they stay gray. +#[test] +fn thin_gray_strokes_beside_black_stay_gray() { + const INK: [u8; 3] = [4, 4, 3]; + for gray in [[230u8, 230, 230], [200, 200, 200]] { + for wide in [2.0, 3.0] { + let img = render(120, 60, 0.0, |x, y| { + Some(if (x - 25.0).hypot(y - 28.0) <= 18.0 { + INK + } else if ((47.0..47.0 + wide).contains(&x) && (8.0..50.0).contains(&y)) + || ((8.0..110.0).contains(&x) && (49.0..49.0 + wide).contains(&y)) + || ((44.0..46.0).contains(&x) && (16.0..22.0).contains(&y)) + { + gray + } else { + WHITE + }) + }); + let logo_colors = vec!["#040403".into(), format!("#{:02X}{:02X}{:02X}", gray[0], gray[1], gray[2])]; + let res = trace(&img, &TraceParams { logo_colors, ..logo_params() }); + let what = format!("gray {gray:?}, {wide} px strokes"); + let short = (17..21).map(|y| Point::new(45.0, f64::from(y) + 0.5)); + let long = [Point::new(47.0 + wide / 2.0, 20.0), Point::new(47.0 + wide / 2.0, 30.0), Point::new(25.0, 49.0 + wide / 2.0)]; + for at in long.into_iter().chain(short) { + let paths: Vec<_> = res.paths.iter().map(|t| (t.color, t.pixels)).collect(); + assert_eq!(top_color(&res, at), Some(gray), "{what}: {at:?}; {paths:?}"); + } + } + } +} + +/// A sharp black disc and a mid-gray square on white, with up to 2 levels of noise added to each +/// pixel: the edge pixels as light as the gray, read as blends of black and white, still count as +/// unblended when judging whether the source is aliased, so the trace is softened as without them +/// and no gray lines the disc. +#[test] +fn a_noisy_hard_edged_gray_between_black_and_white_is_one_shape() { + const GRAY: [u8; 3] = [128, 128, 128]; + let mut img = render(120, 60, 0.0, |x, y| { + Some(if (x - 30.0).hypot(y - 30.0) <= 20.0 { + [0, 0, 0] + } else if (60.0..=110.0).contains(&x) && (10.0..=50.0).contains(&y) { + GRAY + } else { + WHITE + }) + }); + for (i, px) in img.rgba.chunks_mut(4).enumerate() { + let mut h = (i as u64 ^ 0x9E37_79B9_7F4A_7C15).wrapping_mul(0x2545_F491_4F6C_DD1D); + h ^= h >> 29; + let d = (h % 5) as i32 - 2; + for c in px.iter_mut().take(3) { + *c = (i32::from(*c) + d).clamp(0, 255) as u8; + } + } + for named in [false, true] { + let p = if named { + TraceParams { logo_colors: vec!["#000000".into(), "#808080".into(), "#FFFFFF".into()], ..logo_params() } + } else { + logo_params() + }; + let res = trace(&img, &p); + let paths: Vec<_> = res.paths.iter().map(|t| (t.color, t.pixels)).collect(); + let grays = res.paths.iter().filter(|t| t.color == GRAY).count(); + assert_eq!(grays, 1, "named {named}: {grays} gray paths; {paths:?}"); + assert_eq!(top_color(&res, Point::new(85.0, 30.0)), Some(GRAY), "named {named}: the square"); + for k in 0..16 { + let a = f64::from(k) * std::f64::consts::TAU / 16.0; + let at = Point::new(30.0 + 20.0 * a.cos(), 30.0 + 20.0 * a.sin()); + assert_ne!(top_color(&res, at), Some(GRAY), "named {named}: the disc's edge at {at:?}; {paths:?}"); + } + } +} diff --git a/crates/trace/src/logo/unmix.rs b/crates/trace/src/logo/unmix.rs index cdfdfe52fd..3268c9c20a 100644 --- a/crates/trace/src/logo/unmix.rs +++ b/crates/trace/src/logo/unmix.rs @@ -3,7 +3,10 @@ //! An edge pixel of an anti-aliased logo is a blend of the colours that meet there. Reading it as //! "the nearest colour" throws away exactly the sub-pixel information that says where the edge //! runs, so each pixel is instead explained as a mix of at most three classes, whichever mix -//! reproduces the pixel best. +//! reproduces the pixel best. When another mix also reproduces it (with a gray between black and +//! white among the classes, a black-to-white edge pixel is a mix of black and gray as well as of +//! black and white), the pixel takes the mix whose classes lie nearest it in the flat areas around it, +//! when its neighbors show an edge between those classes. use std::collections::{HashMap, HashSet}; @@ -13,6 +16,20 @@ pub(crate) type Px = [f32; 4]; const LAMBDA: f64 = 30.0; /// Pixels this close (in 0..1 premultiplied RGBA) to a class are taken as exactly that class. const PURE: f64 = 4.0 / 255.0; +/// A mix whose squared error is at most this reproduces the pixel: it comes within [`PURE`] of it, +/// as a pixel taken as exactly one class does. +const REPRODUCES: f64 = PURE * PURE; +/// How far (in pixels, each way) a class is looked for around a pixel that two mixes reproduce. +const NEARBY: usize = 6; +/// A pixel whose neighbors are all this close to it (in 0..1 premultiplied RGBA) lies in a flat area. +const FLAT: f64 = 1.5 / 255.0; +/// How many joined pixels within [`PURE`] of one class are taken as art of that class, such as a +/// one-pixel line. The edge pixels of a curve that come within `PURE` of a class join in far fewer. +/// A straight edge whose anti-aliased pixels come within `PURE` of +/// a class gives the same pixels as a line of that class, and keeps the class too. A one-pixel line +/// between two classes that is shorter, falls between pixels or is blurred is read as a blend of +/// those two classes. +const LINE: usize = 2 * NEARBY + 1; struct Subset { idx: [usize; 3], @@ -90,21 +107,33 @@ fn subsets(classes: &[[f64; 4]]) -> Vec { out } -/// How many distinct pixel values are not (nearly) exactly one class: the ones `unmix` has to work -/// on. A flat area whose color is near but not exactly a class counts once, however large it is. -pub(crate) fn count_ambiguous(pix: &[Px], classes: &[[f64; 4]]) -> usize { +/// How many distinct pixel values `unmix` has to work on: the values not (nearly) exactly one class, +/// and the values that are, at pixels outside a flat area ([`in_flat_area`]). A flat area whose color +/// is near but not exactly a class counts once, however large it is. +pub(crate) fn count_ambiguous(pix: &[Px], width: usize, height: usize, classes: &[[f64; 4]]) -> usize { let mut seen = HashSet::new(); - for px in pix { + for (i, px) in pix.iter().take(width.saturating_mul(height)).enumerate() { let p = [f64::from(px[0]), f64::from(px[1]), f64::from(px[2]), f64::from(px[3])]; - if !classes.iter().any(|cv| (0..4).map(|j| (p[j] - cv[j]).powi(2)).sum::().sqrt() < PURE) { - seen.insert(px.map(f32::to_bits)); + let key = px.map(f32::to_bits); + if seen.contains(&key) { + continue; + } + if !classes.iter().any(|cv| (0..4).map(|j| (p[j] - cv[j]).powi(2)).sum::().sqrt() < PURE) + || !in_flat_area(pix, width, height, i % width, i / width) + { + seen.insert(key); } } seen.len() } -/// Coverage planes, one `width × height` plane per class (each pixel's weights sum to 1). -pub(crate) fn unmix(pix: &[Px], width: usize, height: usize, classes: &[[f64; 4]]) -> (Vec>, Vec) { +/// The pixels that took another mix than their best one, in pixel order, each with every class's +/// weight before it did. +pub(crate) type Switched = Vec<(usize, Vec)>; + +/// Coverage planes, one `width × height` plane per class (each pixel's weights sum to 1), the +/// squared error each pixel's best mix leaves, and the pixels that took another mix ([`Switched`]). +pub(crate) fn unmix(pix: &[Px], width: usize, height: usize, classes: &[[f64; 4]]) -> (Vec>, Vec, Switched) { let k = classes.len(); let n = width.saturating_mul(height); let mut planes = vec![vec![0.0f32; n]; k]; @@ -113,46 +142,384 @@ pub(crate) fn unmix(pix: &[Px], width: usize, height: usize, classes: &[[f64; 4] let subs = subsets(classes); // Each distinct pixel value is mixed once: a flat area that is near but not exactly a class // repeats one value. - let mut mixed: HashMap<[u32; 4], Mix> = HashMap::new(); + let mut mixed: HashMap<[u32; 4], Mixes> = HashMap::new(); + // The class each pixel stands for (the class nearest it, when every other class is at least + // twice as far). + let mut stands_for: Vec> = vec![None; n]; + // The class each pixel comes within `PURE` of, where it does. + let mut pure: Vec> = vec![None; n]; + // The pixels outside a flat area that another mix also reproduces, with their values. + let mut tied: Vec<(usize, [u32; 4])> = Vec::new(); for (i, px) in pix.iter().take(n).enumerate() { let p = [f64::from(px[0]), f64::from(px[1]), f64::from(px[2]), f64::from(px[3])]; // Fast path: a pixel that is (nearly) exactly one class. let mut near = (f64::MAX, 0usize); + let mut second = f64::MAX; for (c, cv) in classes.iter().enumerate() { let d: f64 = (0..4).map(|j| (p[j] - cv[j]).powi(2)).sum(); if d < near.0 { + second = near.0; near = (d, c); + } else if d < second { + second = d; } } + if let Some(q) = stands_for.get_mut(i) { + // (Squared distances: twice as far is four times the square.) + *q = (4.0 * near.0 <= second).then_some(near.1); + } + let key = px.map(f32::to_bits); if near.0.sqrt() < PURE { if let Some(v) = planes.get_mut(near.1).and_then(|pl| pl.get_mut(i)) { *v = 1.0; } + if let Some(q) = pure.get_mut(i) { + *q = Some(near.1); + } + // (An edge pixel can come within `PURE` of a class it holds none of: a black-to-white + // edge pixel as light as a gray class.) + if !in_flat_area(pix, width, height, i % width, i / width) + && !mixed.entry(key).or_insert_with(|| best_mixes(p, near, &subs)).tied.is_empty() + { + tied.push((i, key)); + } continue; } - let (res, weights) = mixed.entry(px.map(f32::to_bits)).or_insert_with(|| best_mix(p, near, &subs)); + let mixes = mixed.entry(key).or_insert_with(|| best_mixes(p, near, &subs)); if let Some(r) = residual.get_mut(i) { - *r = *res; + *r = mixes.residual; } - for &(c, wv) in weights.iter() { - if let Some(v) = planes.get_mut(c).and_then(|pl| pl.get_mut(i)) { - *v = wv; + set_weights(&mut planes, i, &mixes.best, 1.0); + // (A pixel in a flat area has no neighbor far enough from it for `across_edge`.) + if !mixes.tied.is_empty() && !in_flat_area(pix, width, height, i % width, i / width) { + tied.push((i, key)); + } + } + let mut switched = Vec::new(); + if tied.is_empty() { + return (planes, residual, switched); + } + // A pixel two mixes reproduce takes another mix of two classes whose farthest class lies nearer + // it than the best mix's does, in the flat areas around it ([`flat_classes`], [`RowDistances::around`]), + // when the pixel lies on an edge between that mix's classes ([`across_edge`]). For the best mix, + // the classes held by flat areas between two classes count as well ([`between_classes`]). A + // pixel within `PURE` of a class that is joined to at least [`LINE`] such pixels of that class + // (itself included) keeps it ([`pure_runs`]), as a one-pixel line of gray between black and white. + let flat = flat_classes(pix, &stands_for, width, height); + let between = between_classes(pix, &flat, &mixed, width, height); + let runs = pure_runs(&pure, width, height); + let mut flat_rows = RowDistances::new(|j| [flat.get(j).copied().flatten(), None], width, height, k); + let mut between_rows = (!between.is_empty()).then(|| RowDistances::new(|j| between.get(j).copied().unwrap_or([None; 2]), width, height, k)); + let mut dist = vec![NEARBY + 1; k]; + let mut kept = vec![NEARBY + 1; k]; + for (i, key) in tied { + if pure.get(i).copied().flatten().is_some() && runs.get(i).is_some_and(|&r| r >= LINE) { + continue; + } + let Some(mixes) = mixed.get(&key) else { continue }; + let edges: Vec<&Weights> = mixes.tied.iter().filter(|m| across_edge(pix, width, height, i, classes, &mixes.best, m)).collect(); + if edges.is_empty() { + continue; + } + flat_rows.around(i, &mut dist); + kept.copy_from_slice(&dist); + if let Some(rows) = &mut between_rows { + rows.around(i, &mut kept); + for (h, &d) in kept.iter_mut().zip(&dist) { + *h = (*h).min(d); + } + } + let now = farthest(&mixes.best, &kept); + let other = edges.into_iter().filter(|m| farthest(m, &dist) < now).min_by_key(|m| farthest(m, &dist)); + if let Some(other) = other { + switched.push((i, planes.iter().map(|pl| pl.get(i).copied().unwrap_or(0.0)).collect())); + // (`residual` keeps the best mix's error; the mix taken comes within `REPRODUCES` of the + // pixel as well.) + set_weights(&mut planes, i, &mixes.best, 0.0); + set_weights(&mut planes, i, other, 1.0); + } + } + (planes, residual, switched) +} + +/// Whether pixel `i` lies on an edge between the two classes of `other`, rather than in an area of +/// a class of `best` that `other` leaves out: for each such class, the pixel has a neighbor beyond +/// it toward each class of `other`, along the line between them. (A black-to-white edge pixel as +/// light as a gray has a darker neighbor and a lighter one; a gray stroke on white has no neighbor +/// darker than the gray.) +fn across_edge(pix: &[Px], width: usize, height: usize, i: usize, classes: &[[f64; 4]], best: &Weights, other: &Weights) -> bool { + let [(a, _), (b, _)] = other.as_slice() else { return false }; + let (Some(ca), Some(cb)) = (classes.get(*a), classes.get(*b)) else { return false }; + let ab: [f64; 4] = std::array::from_fn(|j| cb[j] - ca[j]); + let len2: f64 = ab.iter().map(|v| v * v).sum(); + if len2 <= 1e-12 { + return false; + } + let len = len2.sqrt(); + // Where `v` lies along the line from `a` to `b` (0 at `a`, 1 at `b`), and how far off it. + let place = |v: [f64; 4]| { + let t = (0..4).map(|j| (v[j] - ca[j]) * ab[j]).sum::() / len2; + let off = (0..4).map(|j| (v[j] - ca[j] - t * ab[j]).powi(2)).sum::().sqrt(); + (t, off) + }; + let (x, y) = (i % width.max(1), i / width.max(1)); + let neighbors: Vec = (y.saturating_sub(1)..(y + 2).min(height)) + .flat_map(|yy| (x.saturating_sub(1)..(x + 2).min(width)).map(move |xx| yy * width + xx)) + .filter(|&j| j != i) + .filter_map(|j| pix.get(j)) + .map(|q| place([f64::from(q[0]), f64::from(q[1]), f64::from(q[2]), f64::from(q[3])])) + .filter(|&(_, off)| off <= 2.0 * PURE) + .map(|(t, _)| t) + .collect(); + let left_out: Vec = best.iter().filter(|&&(c, w)| w > 0.0 && c != *a && c != *b).map(|&(c, _)| c).collect(); + !left_out.is_empty() + && left_out.iter().all(|&c| { + let Some(&cv) = classes.get(c) else { return false }; + let (tc, _) = place(cv); + neighbors.iter().any(|&t| (tc - t) * len > PURE) && neighbors.iter().any(|&t| (t - tc) * len > PURE) + }) +} + +/// How far the farthest class of `mix` lies, by the distances `dist` ([`RowDistances::around`]). +fn farthest(mix: &Weights, dist: &[usize]) -> usize { + mix.iter().filter(|&&(_, w)| w > 0.0).map(|&(c, _)| dist.get(c).copied().unwrap_or(NEARBY + 1)).max().unwrap_or(0) +} + +/// Sets pixel `i` of each class's plane in `weights` to the class's weight times `scale`. +fn set_weights(planes: &mut [Vec], i: usize, weights: &[(usize, f32)], scale: f32) { + for &(c, wv) in weights { + if let Some(v) = planes.get_mut(c).and_then(|pl| pl.get_mut(i)) { + *v = wv * scale; + } + } +} + +/// A class's weight in the mix of a flat area that stands for no class, from which the area +/// counts as holding that class. +const HOLDS: f32 = 0.25; + +/// The class each pixel stands for (`stands_for`) where the pixel lies in a flat area +/// ([`in_flat_area`]), and `None` elsewhere. +fn flat_classes(pix: &[Px], stands_for: &[Option], width: usize, height: usize) -> Vec> { + (0..width.saturating_mul(height)) + .map(|i| stands_for.get(i).copied().flatten().filter(|_| in_flat_area(pix, width, height, i % width, i / width))) + .collect() +} + +/// The classes held by flat areas that stand for no class (a flat color between two classes, as +/// with colors named some levels off): the classes of at least [`HOLDS`] weight in the area's mix +/// (at most two, the heaviest), held also by the pixels of exactly its color joined to it, flat or +/// not (its rows beside another color, where a soft edge or a shape close by leaves no flat pixel). +/// Empty when there is no such area. +fn between_classes(pix: &[Px], flat: &[Option], mixed: &HashMap<[u32; 4], Mixes>, width: usize, height: usize) -> Vec<[Option; 2]> { + let mut held = Vec::new(); + // Pixels holding classes, from which the pixels of their color are reached. + let mut reach: Vec = Vec::new(); + for (i, f) in flat.iter().enumerate() { + if f.is_some() || !in_flat_area(pix, width, height, i % width, i / width) { + continue; + } + let Some(mixes) = pix.get(i).and_then(|px| mixed.get(&px.map(f32::to_bits))) else { continue }; + let mut heavy: Vec<(usize, f32)> = mixes.best.iter().copied().filter(|&(_, w)| w >= HOLDS).collect(); + heavy.sort_by(|a, b| b.1.total_cmp(&a.1)); + if heavy.is_empty() { + continue; + } + if held.is_empty() { + held = vec![[None; 2]; width.saturating_mul(height)]; + } + if let Some(slot) = held.get_mut(i) { + *slot = [heavy.first().map(|&(c, _)| c), heavy.get(1).map(|&(c, _)| c)]; + reach.push(i); + } + } + while let Some(i) = reach.pop() { + let (Some(&classes), Some(key)) = (held.get(i), pix.get(i).map(|px| px.map(f32::to_bits))) else { continue }; + let (x, y) = (i % width, i / width); + for yy in y.saturating_sub(1)..(y + 2).min(height) { + for xx in x.saturating_sub(1)..(x + 2).min(width) { + let j = yy * width + xx; + if let (Some(slot @ [None, None]), Some(q)) = (held.get_mut(j), pix.get(j)) + && q.map(f32::to_bits) == key + { + *slot = classes; + reach.push(j); + } } } } - (planes, residual) + held } -/// A pixel's mix: the squared error it leaves and each class's weight. -type Mix = (f32, Vec<(usize, f32)>); +/// For each of `k` classes, how far along each row the nearest pixel holding that class (`at`, the +/// classes pixel `j` holds) lies from each pixel, up to `NEARBY + 1` when none lies within +/// [`NEARBY`]. A row is worked out when it is first asked for, so a few pixels cost a few rows. +struct RowDistances { + at: F, + width: usize, + k: usize, + /// Per row, once worked out: the distance for pixel `x` and class `c` at `x * k + c`. + rows: Vec>>, +} + +impl [Option; 2]> RowDistances { + const NONE: u8 = (NEARBY + 1) as u8; + + fn new(at: F, width: usize, height: usize, k: usize) -> Self { + Self { at, width, k, rows: vec![None; height] } + } + + fn row(&mut self, y: usize) -> &[u8] { + if self.rows.get(y).is_some_and(Option::is_none) { + let built = self.build(y); + if let Some(slot) = self.rows.get_mut(y) { + *slot = Some(built); + } + } + self.rows.get(y).and_then(Option::as_deref).unwrap_or(&[]) + } + + fn build(&self, y: usize) -> Vec { + let (width, k) = (self.width, self.k); + let mut row = vec![Self::NONE; width.saturating_mul(k)]; + // Toward the right, then toward the left, each from the last pixel holding the class. + let mut last = vec![Self::NONE; k]; + for x in 0..width { + let held = (self.at)(y * width + x); + for (c, d) in last.iter_mut().enumerate() { + *d = if held.contains(&Some(c)) { 0 } else { d.saturating_add(1).min(Self::NONE) }; + if let Some(r) = row.get_mut(x * k + c) { + *r = *d; + } + } + } + last.fill(Self::NONE); + for x in (0..width).rev() { + for (c, d) in last.iter_mut().enumerate() { + let Some(r) = row.get_mut(x * k + c) else { continue }; + *d = if *r == 0 { 0 } else { d.saturating_add(1).min(Self::NONE) }; + *r = (*r).min(*d); + } + } + row + } + + /// For each class, how far (in pixels, the larger of the two axes) the nearest pixel holding + /// that class lies from pixel `i`, into `dist` (one entry per class); `NEARBY + 1` when none + /// lies within [`NEARBY`]. + fn around(&mut self, i: usize, dist: &mut [usize]) { + let (width, k, height) = (self.width.max(1), self.k, self.rows.len()); + let (x, y) = (i % width, i / width); + dist.fill(NEARBY + 1); + for yy in y.saturating_sub(NEARBY)..(y + NEARBY + 1).min(height) { + let dy = yy.abs_diff(y); + let row = self.row(yy); + for (c, d) in dist.iter_mut().enumerate().take(k) { + if let Some(&r) = row.get(x * k + c) { + *d = (*d).min(usize::from(r).max(dy)); + } + } + } + } +} + +/// For each pixel within [`PURE`] of a class (`pure`), how many pixels within `PURE` of the same +/// class are joined to it (itself included, through the eight neighbors); 0 for other pixels. +fn pure_runs(pure: &[Option], width: usize, height: usize) -> Vec { + let n = width.saturating_mul(height); + let mut size = vec![0usize; n]; + let mut seen = vec![false; n]; + let mut stack = Vec::new(); + let mut members = Vec::new(); + for start in 0..n { + let Some(c) = pure.get(start).copied().flatten() else { continue }; + if seen.get(start).copied().unwrap_or(true) { + continue; + } + if let Some(s) = seen.get_mut(start) { + *s = true; + } + stack.push(start); + members.clear(); + while let Some(i) = stack.pop() { + members.push(i); + let (x, y) = (i % width, i / width); + for yy in y.saturating_sub(1)..(y + 2).min(height) { + for xx in x.saturating_sub(1)..(x + 2).min(width) { + let j = yy * width + xx; + if pure.get(j).copied().flatten() == Some(c) + && let Some(s) = seen.get_mut(j) + && !*s + { + *s = true; + stack.push(j); + } + } + } + } + for &i in &members { + if let Some(s) = size.get_mut(i) { + *s = members.len(); + } + } + } + size +} + +/// Whether every neighbor of the pixel at (`x`, `y`) inside the image lies within [`FLAT`] of it. +fn in_flat_area(pix: &[Px], width: usize, height: usize, x: usize, y: usize) -> bool { + let Some(p) = pix.get(y * width + x) else { return false }; + (y.saturating_sub(1)..(y + 2).min(height)).all(|yy| { + (x.saturating_sub(1)..(x + 2).min(width)).all(|xx| { + pix.get(yy * width + xx).is_some_and(|q| (0..4).map(|j| (f64::from(p[j]) - f64::from(q[j])).powi(2)).sum::().sqrt() <= FLAT) + }) + }) +} + +/// Each class's weight in a pixel's mix. +type Weights = Vec<(usize, f32)>; + +/// A mix tried for a pixel: its squared error with its penalty, the penalty, and its classes with +/// their weights (the first `n`). +#[derive(Clone, Copy)] +struct Candidate { + res: f64, + penalty: f64, + idx: [usize; 3], + w: [f64; 3], + n: usize, +} + +impl Candidate { + fn weights(&self) -> Weights { + self.idx.iter().zip(self.w).take(self.n).map(|(&c, w)| (c, w as f32)).collect() + } +} + +/// How a pixel value is mixed: the squared error the best mix leaves, each class's weight in it, +/// and the other mixes of two classes that reproduce the value ([`REPRODUCES`]). +struct Mixes { + residual: f32, + best: Weights, + tied: Vec, +} /// The mix of at most three classes that reproduces `p` best, starting from the nearest single -/// class `near` (squared distance, class). -fn best_mix(p: [f64; 4], near: (f64, usize), subs: &[Subset]) -> Mix { +/// class `near` (squared distance, class), and the other mixes that also reproduce it. +fn best_mixes(p: [f64; 4], near: (f64, usize), subs: &[Subset]) -> Mixes { + let reproduces = |m: &Candidate| m.res - m.penalty <= REPRODUCES; // Best single class is the starting point; try every two- and three-class mix. - let mut best = (near.0, vec![(near.1, 1.0f64)]); - let mut best_penalty = 0.0; - for s in subs { + let mut top = Candidate { res: near.0, penalty: 0.0, idx: [near.1, 0, 0], w: [1.0, 0.0, 0.0], n: 1 }; + // The other mixes of two classes that reproduce the pixel, also when the best mix does not (a + // single class carries no penalty and can come nearer than an exact mix of two): only a mix of + // two is switched to ([`across_edge`]). A mix holding the nearest class when that class alone + // reproduces the pixel adds a class of next to no weight to it, and is left out. (At most one + // candidate per pair of classes, so the list stays small with many classes.) Each is kept with + // its subset's index, and the best mix found is left out of them at the end. + let single = reproduces(&top).then_some(near.1); + let mut top_at = None; + let mut pairs: Vec<(usize, Candidate)> = Vec::new(); + for (at, s) in subs.iter().enumerate() { let mut rhs = [0.0f64; 3]; for (j, r) in rhs.iter_mut().enumerate().take(s.n) { *r = (0..4).map(|c| s.cols[j][c] * p[c]).sum::() + LAMBDA * LAMBDA; @@ -180,12 +547,17 @@ fn best_mix(p: [f64; 4], near: (f64, usize), subs: &[Subset]) -> Mix { let m: f64 = (0..s.n).map(|j| w[j] * s.cols[j][c]).sum(); res += (pc - m).powi(2); } - if res < best.0 { - best = (res, (0..s.n).map(|j| (s.idx[j], w[j])).collect()); - best_penalty = s.penalty; + let m = Candidate { res, penalty: s.penalty, idx: s.idx, w, n: s.n }; + if m.n == 2 && reproduces(&m) && single.is_none_or(|c| m.idx[0] != c && m.idx[1] != c) { + pairs.push((at, m)); + } + if res < top.res { + top = m; + top_at = Some(at); } } - ((best.0 - best_penalty).max(0.0) as f32, best.1.into_iter().map(|(c, w)| (c, w as f32)).collect()) + let tied = pairs.iter().filter(|&&(at, _)| Some(at) != top_at).map(|(_, m)| m.weights()).collect(); + Mixes { residual: (top.res - top.penalty).max(0.0) as f32, best: top.weights(), tied } } #[cfg(test)] @@ -199,7 +571,7 @@ mod tests { #[test] fn pure_pixels_are_exact() { let pix = vec![[1.0, 0.0, 0.0, 1.0], [0.0, 0.0, 0.0, 0.0]]; - let (pl, _) = unmix(&pix, 2, 1, &classes()); + let (pl, _, _) = unmix(&pix, 2, 1, &classes()); assert_eq!((pl[0][0], pl[2][1]), (1.0, 1.0)); } @@ -207,7 +579,7 @@ mod tests { fn a_blend_of_two_colours_recovers_its_proportions() { // 30% red over 70% blue. let pix = vec![[0.3, 0.0, 0.7, 1.0]]; - let (pl, _) = unmix(&pix, 1, 1, &classes()); + let (pl, _, _) = unmix(&pix, 1, 1, &classes()); assert!((pl[0][0] - 0.3).abs() < 0.02, "red {}", pl[0][0]); assert!((pl[1][0] - 0.7).abs() < 0.02, "blue {}", pl[1][0]); } @@ -216,7 +588,7 @@ mod tests { fn a_half_transparent_edge_is_half_covered() { // Red at 40% coverage over nothing: premultiplied (0.4, 0, 0, 0.4). let pix = vec![[0.4, 0.0, 0.0, 0.4]]; - let (pl, _) = unmix(&pix, 1, 1, &classes()); + let (pl, _, _) = unmix(&pix, 1, 1, &classes()); assert!((pl[0][0] - 0.4).abs() < 0.02 && (pl[2][0] - 0.6).abs() < 0.02, "{:?}", (pl[0][0], pl[2][0])); } @@ -224,7 +596,7 @@ mod tests { fn a_colour_no_class_can_explain_leaves_a_large_residual() { // Green is none of red, blue or transparent, nor any blend of them. let pix = vec![[0.0, 0.8, 0.0, 1.0], [0.3, 0.0, 0.7, 1.0]]; - let (_, res) = unmix(&pix, 2, 1, &classes()); + let (_, res, _) = unmix(&pix, 2, 1, &classes()); assert!(res[0] > 0.1, "unexplained pixel residual {}", res[0]); assert!(res[1] < 1e-3, "an explained blend residual {}", res[1]); } @@ -235,8 +607,12 @@ mod tests { let off = [0.97, 0.02, 0.02, 1.0]; let mut pix = vec![off; 1000]; pix.extend([[0.3, 0.0, 0.7, 1.0], [1.0, 0.0, 0.0, 1.0], [0.0, 0.0, 0.0, 0.0]]); - assert_eq!(count_ambiguous(&pix, &classes()), 2); - let (pl, res) = unmix(&pix, pix.len(), 1, &classes()); + // (The pure red and transparent pixels lie outside a flat area, so they count too: `unmix` + // checks whether another mix reproduces them.) + assert_eq!(count_ambiguous(&pix, pix.len(), 1, &classes()), 4); + // Pure pixels in a flat area do not count. + assert_eq!(count_ambiguous(&[[1.0, 0.0, 0.0, 1.0]; 9], 3, 3, &classes()), 0); + let (pl, res, _) = unmix(&pix, pix.len(), 1, &classes()); assert!(pl[0][0] > 0.95, "red {}", pl[0][0]); for i in 1..1000 { assert_eq!((pl[0][i], pl[1][i], pl[2][i], res[i]), (pl[0][0], pl[1][0], pl[2][0], res[0]), "pixel {i}"); @@ -244,10 +620,89 @@ mod tests { assert!((pl[0][1000] - 0.3).abs() < 0.02 && (pl[1][1000] - 0.7).abs() < 0.02); } + #[test] + fn an_edge_pixel_two_mixes_reproduce_takes_the_classes_beside_it() { + // A light gray lies on the line from black to white. A row of flat black, one edge pixel, + // flat white: the edge pixel is a blend of black and white, with no gray in it, also when + // it comes within `PURE` of the gray (0.905), and when the gray alone, which carries no + // penalty, comes nearer it than any mix of two does without reproducing it (0.91). + let classes = vec![[0.9, 0.9, 0.9, 1.0], [0.0, 0.0, 0.0, 1.0], [1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 0.0]]; + let row = |left: [f32; 4], v: f32| { + let mut pix = vec![left; 5]; + pix.push([v, v, v, 1.0]); + pix.extend([[1.0f32, 1.0, 1.0, 1.0]; 5]); + pix + }; + for v in [0.1f32, 0.3, 0.7, 0.85, 0.905, 0.91, 0.95, 0.98] { + let (pl, _, _) = unmix(&row([0.0, 0.0, 0.0, 1.0], v), 11, 1, &classes); + assert_eq!(pl[0][5], 0.0, "gray in a {v} edge pixel"); + assert!((pl[2][5] - v).abs() < 0.02 && (pl[1][5] - (1.0 - v)).abs() < 0.02, "{v}: black {} white {}", pl[1][5], pl[2][5]); + } + // Beside flat gray, a gray-to-white edge pixel keeps its gray. + let (pl, _, _) = unmix(&row([0.9, 0.9, 0.9, 1.0], 0.95), 11, 1, &classes); + assert!((pl[0][5] - 0.5).abs() < 0.02 && pl[1][5] == 0.0, "gray {} black {}", pl[0][5], pl[1][5]); + // A gray pixel between white ones, flat black four pixels off: a gray stroke, kept. + let mut pix = vec![[0.0f32, 0.0, 0.0, 1.0]; 4]; + pix.extend([[1.0f32, 1.0, 1.0, 1.0]; 2]); + pix.push([0.9, 0.9, 0.9, 1.0]); + pix.extend([[1.0f32, 1.0, 1.0, 1.0]; 5]); + let (pl, _, _) = unmix(&pix, 12, 1, &classes); + assert_eq!((pl[0][6], pl[1][6]), (1.0, 0.0), "the stroke"); + } + + #[test] + fn a_column_of_pixels_as_light_as_a_class_keeps_it() { + // Flat black, one column at the gray's value, flat white. In `LINE` rows or more the column + // is gray art (a one-pixel line, or a straight edge giving the same pixels); in fewer rows it + // is an edge between black and white. + let classes = vec![[0.9, 0.9, 0.9, 1.0], [0.0, 0.0, 0.0, 1.0], [1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 0.0]]; + for (rows, gray) in [(LINE, 1.0), (LINE + 10, 1.0), (LINE - 1, 0.0), (3, 0.0)] { + let mut pix = Vec::new(); + for _ in 0..rows { + pix.extend([[0.0f32, 0.0, 0.0, 1.0]; 5]); + pix.push([0.9, 0.9, 0.9, 1.0]); + pix.extend([[1.0f32, 1.0, 1.0, 1.0]; 5]); + } + let (pl, _, _) = unmix(&pix, 11, rows, &classes); + for y in 0..rows { + assert_eq!(pl[0][y * 11 + 5], gray, "{rows} rows: gray in row {y}"); + } + } + } + + #[test] + fn row_distances_match_a_scan_of_the_window_around_each_pixel() { + // Three classes scattered over 23 x 17 pixels, some pixels holding two, most none. + let (w, h, k) = (23usize, 17usize, 3usize); + let at = |j: usize| -> [Option; 2] { + match (j * 7919) % 97 { + 0..=2 => [Some(0), None], + 3 => [Some(1), Some(2)], + 4 | 5 => [None, Some(2)], + _ => [None; 2], + } + }; + let mut rows = RowDistances::new(at, w, h, k); + let mut dist = vec![0; k]; + for i in 0..w * h { + let (x, y) = (i % w, i / w); + let mut want = vec![NEARBY + 1; k]; + for yy in y.saturating_sub(NEARBY)..(y + NEARBY + 1).min(h) { + for xx in x.saturating_sub(NEARBY)..(x + NEARBY + 1).min(w) { + for c in at(yy * w + xx).into_iter().flatten() { + want[c] = want[c].min(xx.abs_diff(x).max(yy.abs_diff(y))); + } + } + } + rows.around(i, &mut dist); + assert_eq!(dist, want, "pixel ({x}, {y})"); + } + } + #[test] fn weights_sum_to_one() { let pix = vec![[0.2, 0.1, 0.5, 0.8], [0.9, 0.0, 0.05, 0.95]]; - let (pl, _) = unmix(&pix, 2, 1, &classes()); + let (pl, _, _) = unmix(&pix, 2, 1, &classes()); for i in 0..2 { let s: f32 = pl.iter().map(|p| p[i]).sum(); assert!((s - 1.0).abs() < 1e-4, "pixel {i} sums to {s}"); diff --git a/crates/trace/src/params.rs b/crates/trace/src/params.rs index 9c430dd19d..156d6fbef2 100644 --- a/crates/trace/src/params.rs +++ b/crates/trace/src/params.rs @@ -241,19 +241,19 @@ pub fn preset(name: &str) -> Option { // many as its tones need where it is not. // (Color detail 85: a colour on a hundredth of the picture is still one of its colours.) "auto color" => TraceParams { palette: Palette::Automatic, color_detail: 85.0, ..color(6, 65.0, 60.0, 16, Method::Abutting) }, - "high fidelity photo" => color(64, 90.0, 25.0, 4, Method::Overlapping), - "low fidelity photo" => color(20, 60.0, 50.0, 12, Method::Overlapping), - "3 colors" => color(3, 60.0, 60.0, 20, Method::Abutting), - "6 colors" => color(6, 65.0, 60.0, 16, Method::Abutting), - "16 colors" => color(16, 70.0, 55.0, 10, Method::Abutting), - "shades of gray" => TraceParams { mode: Mode::Grayscale, colors: 8, paths: 60.0, corners: 50.0, noise: 10, method: Method::Overlapping, ..d }, - "black and white logo" => bw(128, 95.0, 80.0, 8, true), - "sketched art" => bw(150, 50.0, 50.0, 100, false), - "silhouettes" => bw(200, 40.0, 60.0, 30, false), - "line art" => bw(128, 80.0, 70.0, 10, false), - "technical drawing" => bw(128, 95.0, 90.0, 4, true), + "high fidelity photo" => color(64, 50.0, 50.0, 5, Method::Overlapping), + "low fidelity photo" => color(20, 50.0, 50.0, 10, Method::Overlapping), + "3 colors" => color(3, 50.0, 50.0, 15, Method::Abutting), + "6 colors" => color(6, 50.0, 50.0, 15, Method::Abutting), + "16 colors" => color(16, 50.0, 50.0, 15, Method::Abutting), + "shades of gray" => TraceParams { mode: Mode::Grayscale, colors: 8, paths: 50.0, corners: 50.0, noise: 15, method: Method::Overlapping, ..d }, + "black and white logo" => bw(128, 50.0, 75.0, 25, true), + "sketched art" => bw(150, 50.0, 50.0, 20, false), + "silhouettes" => bw(200, 50.0, 50.0, 90, false), + "line art" => bw(128, 50.0, 75.0, 20, false), + "technical drawing" => bw(128, 50.0, 100.0, 1, true), // Black outlines: lines as stroked centre lines, wider areas as stroked outlines. - "outline" => TraceParams { fills: false, strokes: true, ..bw(128, 80.0, 70.0, 10, false) }, + "outline" => TraceParams { fills: false, strokes: true, ..bw(128, 50.0, 75.0, 20, false) }, // Flat-colour logos: colours found automatically, edges placed to a fraction of a pixel. "flat logo" => TraceParams { mode: Mode::Logo, colors: 8, paths: 60.0, corners: 50.0, noise: 6, snap_curves_to_lines: true, ..d }, _ => return None, diff --git a/crates/trace/src/quantize.rs b/crates/trace/src/quantize.rs index f5a2d9fa47..9a7031256a 100644 --- a/crates/trace/src/quantize.rs +++ b/crates/trace/src/quantize.rs @@ -1,7 +1,7 @@ //! Colour reduction and noise removal. Colours are compared in Oklab, where equal distances look //! equally different. -use crate::{Mode, Palette, Raster, TraceParams}; +use crate::{Mode, Palette, Raster, TraceParams, parallel_map}; mod cut_edge; mod denoise; @@ -191,6 +191,11 @@ fn own_colours(img: &Raster) -> Vec { /// [`own_colours`] among the pixels that `among` marks: the others are neither own colours nor /// the neighbours a pixel is a blend of. fn own_colours_among(img: &Raster, among: &[bool]) -> Vec { + own_colours_among_by(img, among, PIXELS_PER_SHARE) +} + +/// [`own_colours_among`], with the rows worked on in bands of about `per_share` pixels (see [`over_rows`]). +fn own_colours_among_by(img: &Raster, among: &[bool], per_share: usize) -> Vec { let (w, h) = (img.width as isize, img.height as isize); let px = img.rgba.as_chunks::<4>().0; let at = |x: isize, y: isize| { @@ -198,28 +203,52 @@ fn own_colours_among(img: &Raster, among: &[bool]) -> Vec { let p = px.get(i).filter(|_| among.get(i).copied().unwrap_or(false))?; Some([f64::from(p[0]), f64::from(p[1]), f64::from(p[2])]) }; - let mut out = Vec::with_capacity(px.len()); - for y in 0..h { - for x in 0..w { - let Some(p) = at(x, y) else { - out.push(false); - continue; - }; - let blend = [(1, 0), (0, 1), (1, 1), (1, -1)].into_iter().any(|(dx, dy)| { - let (Some(a), Some(b)) = (at(x - dx, y - dy), at(x + dx, y + dy)) else { return false }; - let d = [0, 1, 2].map(|k| b[k] - a[k]); - let len2: f64 = d.iter().map(|v| v * v).sum(); - if len2 <= 400.0 { - return false; - } - let t = (0..3).map(|k| (p[k] - a[k]) * d[k]).sum::() / len2; - let off2: f64 = (0..3).map(|k| (p[k] - a[k] - t * d[k]).powi(2)).sum(); - t > 0.06 && t < 0.94 && off2 < len2 / 16.0 - }); - out.push(!blend); + over_rows(img.width as usize, img.height as usize, per_share, |rows| { + let mut out = Vec::with_capacity(rows.len() * img.width as usize); + for y in rows.start as isize..rows.end as isize { + for x in 0..w { + let Some(p) = at(x, y) else { + out.push(false); + continue; + }; + let blend = [(1, 0), (0, 1), (1, 1), (1, -1)].into_iter().any(|(dx, dy)| { + let (Some(a), Some(b)) = (at(x - dx, y - dy), at(x + dx, y + dy)) else { return false }; + let d = [0, 1, 2].map(|k| b[k] - a[k]); + let len2: f64 = d.iter().map(|v| v * v).sum(); + if len2 <= 400.0 { + return false; + } + let t = (0..3).map(|k| (p[k] - a[k]) * d[k]).sum::() / len2; + let off2: f64 = (0..3).map(|k| (p[k] - a[k] - t * d[k]).powi(2)).sum(); + t > 0.06 && t < 0.94 && off2 < len2 / 16.0 + }); + out.push(!blend); + } } + out + }) +} + +/// About how many pixels one thread works through at a time in the passes over every pixel that +/// [`over_rows`] spreads over the available cores. A picture of fewer pixels is worked through on +/// one thread. +const PIXELS_PER_SHARE: usize = 1 << 16; + +/// `f` of each band of rows of a picture `w` pixels wide and `h` rows high, each band about +/// `per_share` pixels (at least one row), spread over the available cores (one thread on the web), +/// and the results joined in row order. Each band's result depends only on its rows, so the +/// joined result is the same however many threads there are. A picture with no pixels gives no +/// result. +fn over_rows(w: usize, h: usize, per_share: usize, f: impl Fn(std::ops::Range) -> Vec + Sync) -> Vec { + if w == 0 || h == 0 { + return Vec::new(); } - out + let rows = (per_share / w.max(1)).max(1); + let bands: Vec> = (0..h).step_by(rows).map(|y| y..(y + rows).min(h)).collect(); + if bands.len() <= 1 { + return bands.into_iter().flat_map(&f).collect(); + } + parallel_map(&bands, |rows| f(rows.clone())).into_iter().flatten().collect() } /// Whether the palette is made from the picture's own colours alone (`own` of `all` opaque @@ -325,3 +354,40 @@ fn merge_mixed(q: Quantized, w: usize, h: usize, keep: &[[u8; 3]]) -> Quantized let labels = q.labels.iter().map(|&l| into.get(l as usize).map_or(l, |&t| t as u16)).collect(); compact(labels, color.iter().map(|c| [c[0].round() as u8, c[1].round() as u8, c[2].round() as u8]).collect()) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn blend_pixels_are_found_the_same_however_the_picture_is_shared_out() { + // Slanted stripes of red and blue, blended over three pixels at each edge, with a little + // noise and a band of half-transparent pixels along the bottom. Odd sizes, so that the last + // band of rows is short. + let (w, h) = (173u32, 97u32); + let (red, blue) = ([200.0, 30.0, 40.0], [20.0, 60.0, 180.0]); + let img = Raster::from_fn(w, h, |x, y| { + let s = (x + y / 2) % 24; + let t = f64::from(s.saturating_sub(9).min(3)) / 3.0 - f64::from(s.saturating_sub(21).min(3)) / 3.0; + let noise = f64::from((x * 7 + y * 13) % 5) - 2.0; + let c = [0, 1, 2].map(|k| (red[k] + t * (blue[k] - red[k]) + noise).clamp(0.0, 255.0) as u8); + [c[0], c[1], c[2], if y + 2 >= h { 160 } else { 255 }] + }); + let all = w as usize * h as usize; + let opaque: Vec = img.rgba.as_chunks::<4>().0.iter().map(|p| p[3] >= 128).collect(); + // One row per share, a few rows per share, and the whole picture as one. + let own: Vec> = [1, 3 * w as usize + 5, all].iter().map(|&s| own_colours_among_by(&img, &opaque, s)).collect(); + assert_eq!(own[0].len(), all); + assert!(own[0].iter().any(|&o| !o), "the edges have blend pixels"); + assert!(own.iter().all(|o| *o == own[0])); + } + + #[test] + fn a_picture_with_no_pixels_is_not_shared_out() { + // No band for each of the rows of a picture with no columns, however many rows it has. + assert!(over_rows(0, usize::MAX, PIXELS_PER_SHARE, |_| vec![0u8]).is_empty()); + assert!(over_rows(5, 0, PIXELS_PER_SHARE, |_| vec![0u8]).is_empty()); + let img = Raster::new(0, u32::MAX, vec![]).unwrap(); + assert!(own_colours_among(&img, &[]).is_empty()); + } +} diff --git a/crates/trace/src/quantize/cut_edge.rs b/crates/trace/src/quantize/cut_edge.rs index 99b3c42845..4578fbe7fc 100644 --- a/crates/trace/src/quantize/cut_edge.rs +++ b/crates/trace/src/quantize/cut_edge.rs @@ -1,5 +1,6 @@ use super::palette::{Bin, HistKey, Used, centers, median_cut, nearest_lab}; -use super::{Mode, Palette, Quantized, Raster, TRANSPARENT, TraceParams, luma, oklab}; +use super::{Mode, PIXELS_PER_SHARE, Palette, Quantized, Raster, TRANSPARENT, TraceParams, luma, oklab, over_rows}; +use crate::parallel_map; /// `q` with its blend pixels settled, and the colours that leaves unused dropped. /// @@ -10,59 +11,136 @@ use super::{Mode, Palette, Quantized, Raster, TRANSPARENT, TraceParams, luma, ok /// own pixels within two pixels of it takes the side it is nearer to of the pair of those colours /// it is best a blend of, when that explains it twice as well as its own colour does. With one /// colour around it, it keeps its own. -pub(super) fn settled(mut q: Quantized, img: &Raster, own: &[bool]) -> Quantized { +pub(super) fn settled(q: Quantized, img: &Raster, own: &[bool]) -> Quantized { + settled_by(q, img, own, PIXELS_PER_SHARE) +} + +/// [`settled`], with the rows worked on in bands of about `per_share` pixels (see [`over_rows`]). +fn settled_by(mut q: Quantized, img: &Raster, own: &[bool], per_share: usize) -> 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(); + // Each pixel is settled by the labels as they were before any label changed. Each band of rows + // keeps its changes (see [`Changes`]), and they are made once every band is done. + let before = &q.labels; let color = |l: u16| q.palette.get(l as usize).map(|c| c.map(f64::from)); let dist = |a: [f64; 3], b: [f64; 3]| (0..3).map(|k| (a[k] - b[k]).powi(2)).sum::().sqrt(); - let mut changed = false; - for i in 0..w * h { - let mine_l = before[i]; - if own[i] || mine_l == TRANSPARENT { - continue; - } - let (x, y) = (i % w, i / w); - // The colours of the picture's own pixels within two pixels (seldom more than three). - let mut near: Vec = Vec::new(); - for yy in y.saturating_sub(2)..=(y + 2).min(h - 1) { - for xx in x.saturating_sub(2)..=(x + 2).min(w - 1) { - let j = yy * w + xx; - if own[j] && before[j] != TRANSPARENT && !near.contains(&before[j]) { - near.push(before[j]); + let bands: Vec<(usize, Changes)> = over_rows(w, h, per_share, |rows| { + let (first, end) = (rows.start * w, rows.end * w); + let mut band = Changes::new(end - first); + for i in first..end { + let mine_l = before[i]; + if own[i] || mine_l == TRANSPARENT { + continue; + } + let (x, y) = (i % w, i / w); + // The colours of the picture's own pixels within two pixels (seldom more than three). + let mut near: Vec = Vec::new(); + for yy in y.saturating_sub(2)..=(y + 2).min(h - 1) { + for xx in x.saturating_sub(2)..=(x + 2).min(w - 1) { + let j = yy * w + xx; + if own[j] && before[j] != TRANSPARENT && !near.contains(&before[j]) { + near.push(before[j]); + } } } - } - let (Some(p), Some(mine)) = (img.rgba.get(i * 4..i * 4 + 3).map(|p| [f64::from(p[0]), f64::from(p[1]), f64::from(p[2])]), color(mine_l)) - else { - continue; - }; - if near.len() < 2 || near.contains(&mine_l) { - continue; - } - let mut best: Option<(f64, u16)> = None; - for (n, &a) in near.iter().enumerate() { - for &b in &near[n + 1..] { - let (Some(ca), Some(cb)) = (color(a), color(b)) else { continue }; - let d = [0, 1, 2].map(|k| cb[k] - ca[k]); - let len2: f64 = d.iter().map(|v| v * v).sum(); - let t = if len2 > 0.0 { ((0..3).map(|k| (p[k] - ca[k]) * d[k]).sum::() / len2).clamp(0.0, 1.0) } else { 0.0 }; - let off = dist(p, [0, 1, 2].map(|k| ca[k] + t * d[k])); - if best.is_none_or(|x| off < x.0) { - best = Some((off, if t < 0.5 { a } else { b })); + let (Some(p), Some(mine)) = (img.rgba.get(i * 4..i * 4 + 3).map(|p| [f64::from(p[0]), f64::from(p[1]), f64::from(p[2])]), color(mine_l)) + else { + continue; + }; + if near.len() < 2 || near.contains(&mine_l) { + continue; + } + let mut best: Option<(f64, u16)> = None; + for (n, &a) in near.iter().enumerate() { + for &b in &near[n + 1..] { + let (Some(ca), Some(cb)) = (color(a), color(b)) else { continue }; + let d = [0, 1, 2].map(|k| cb[k] - ca[k]); + let len2: f64 = d.iter().map(|v| v * v).sum(); + let t = if len2 > 0.0 { ((0..3).map(|k| (p[k] - ca[k]) * d[k]).sum::() / len2).clamp(0.0, 1.0) } else { 0.0 }; + let off = dist(p, [0, 1, 2].map(|k| ca[k] + t * d[k])); + if best.is_none_or(|x| off < x.0) { + best = Some((off, if t < 0.5 { a } else { b })); + } } } + if let Some((off, to)) = best + && off < 0.5 * dist(p, mine) + { + band.set(i - first, to, || before.get(first..end).unwrap_or_default().to_vec()); + } } - if let Some((off, to)) = best - && off < 0.5 * dist(p, mine) - { - q.labels[i] = to; - changed = true; + if band.is_empty() { vec![] } else { vec![(first, band)] } + }); + if bands.is_empty() { + return q; + } + for (first, band) in bands { + band.each(|at, to| { + if let Some(l) = q.labels.get_mut(first + at) { + *l = to; + } + }); + } + compact(q.labels, q.palette) +} + +/// The labels a pass changes in one part of a picture, `len` pixels long, counting each pixel from +/// the part's first. They are kept as pairs of a pixel and its new label until the pairs would take +/// more memory than a copy of the part's labels, and as that copy, with the changes made, after +/// that. The pairs take at most as much memory as the copy, and a part holds both only while it +/// moves the pairs into the copy. +struct Changes { + len: usize, + few: Vec<(usize, u16)>, + copy: Option>, +} + +impl Changes { + fn new(len: usize) -> Self { + Changes { len, few: vec![], copy: None } + } + + /// Changes the label of the pixel `at` to `to`. `labels` gives the part's labels as they were + /// before any changed, for the copy. + fn set(&mut self, at: usize, to: u16, labels: impl FnOnce() -> Vec) { + if let Some(copy) = &mut self.copy { + if let Some(l) = copy.get_mut(at) { + *l = to; + } + return; + } + // The most pairs that take no more memory than a copy of the part's labels. The pairs grow + // by doubling up to that many, and no further. + let most = self.len * size_of::() / size_of::<(usize, u16)>(); + if self.few.len() < most { + if self.few.len() == self.few.capacity() { + self.few.reserve_exact(self.few.capacity().max(4).min(most - self.few.len())); + } + self.few.push((at, to)); + return; + } + let mut copy = labels(); + for (at, to) in std::mem::take(&mut self.few).into_iter().chain([(at, to)]) { + if let Some(l) = copy.get_mut(at) { + *l = to; + } + } + self.copy = Some(copy); + } + + fn is_empty(&self) -> bool { + self.few.is_empty() && self.copy.is_none() + } + + /// `f` of each changed pixel and its new label (of every pixel of the part, once it is a copy). + fn each(self, mut f: impl FnMut(usize, u16)) { + match self.copy { + Some(copy) => copy.into_iter().enumerate().for_each(|(at, to)| f(at, to)), + None => self.few.into_iter().for_each(|(at, to)| f(at, to)), } } - 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 @@ -122,12 +200,47 @@ const ON_THE_LINE: f64 = 0.15; /// 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 { +pub(super) fn settled_wide(q: Quantized, img: &Raster, own: &[bool], gray: bool) -> Quantized { + settled_wide_by(q, img, own, gray, PIXELS_PER_SHARE) +} + +/// [`settled_wide`], with its strips of columns worked on in groups of about `per_share` pixels +/// (at least one strip), spread over the available cores (one thread on the web). +fn settled_wide_by(mut q: Quantized, img: &Raster, own: &[bool], gray: bool, per_share: usize) -> Quantized { let (w, h) = (img.width as usize, img.height as usize); - if q.labels.len() != w * h || own.len() != w * h { + if q.labels.len() != w * h || own.len() != w * h || w == 0 || h == 0 { return q; } - let before = q.labels.clone(); + // Each pixel is settled by the labels as they were before any label changed. Each group of + // strips keeps its changes (see [`Changes`]), and they are made once every group is done. + let strip = BLEND_STRIP.min(w).max(1); + let per_group = (per_share / (strip * h).max(1)).max(1); + let cols = strip.saturating_mul(per_group); + let groups: Vec> = (0..w).step_by(cols).map(|x| x..x.saturating_add(cols).min(w)).collect(); + let settle = |cols: &std::ops::Range| (cols.clone(), settled_wide_strips(&q, img, own, gray, cols.clone())); + let mut settled: Vec<(std::ops::Range, Changes)> = + if groups.len() <= 1 { groups.iter().map(settle).collect() } else { parallel_map(&groups, settle) }; + settled.retain(|(_, changes)| !changes.is_empty()); + if settled.is_empty() { + return q; + } + for (cols, group) in settled { + let gw = cols.len().max(1); + group.each(|at, to| { + if let Some(l) = q.labels.get_mut((at / gw) * w + cols.start + at % gw) { + *l = to; + } + }); + } + compact(q.labels, q.palette) +} + +/// The labels that [`settled_wide`] changes in the columns `cols` (whole strips of [`BLEND_STRIP`] +/// columns, or the picture's last columns), each pixel counted row by row across those columns. +fn settled_wide_strips(q: &Quantized, img: &Raster, own: &[bool], gray: bool, cols: std::ops::Range) -> Changes { + let (w, h) = (img.width as usize, img.height as usize); + let gw = cols.len(); + let before = &q.labels; 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 @@ -135,7 +248,9 @@ pub(super) fn settled_wide(mut q: Quantized, img: &Raster, own: &[bool], gray: b // 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 strip = BLEND_STRIP.min(w).max(1); + 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])] }; + let mut settled = Changes::new(gw * h); let mut rows = vec![0u64; span * strip * words]; let mut counts = vec![0u32; q.palette.len()]; let mut window = vec![0u64; words]; @@ -178,12 +293,10 @@ pub(super) fn settled_wide(mut q: Quantized, img: &Raster, own: &[bool], gray: b } } }; - 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); + for (x0, y) in cols.clone().step_by(strip).flat_map(|x0| (0..h).map(move |y| (x0, y))) { + let x1 = (x0 + strip).min(cols.end); if y == 0 { for yy in 0..BLEND_REACH.min(h) { row_colors(yy, x0, x1, &mut rows); @@ -265,12 +378,13 @@ pub(super) fn settled_wide(mut q: Quantized, img: &Raster, own: &[bool], gray: b && !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; + settled.set(y * gw + x - cols.start, to, || { + (0..h).flat_map(|yy| before.get(yy * w + cols.start..yy * w + cols.end).unwrap_or_default()).copied().collect() + }); } } } - if changed { compact(q.labels, q.palette) } else { q } + settled } /// Whether `img` is continuous tone (a photo, a gradient) rather than flat art, however noisy @@ -283,11 +397,11 @@ pub(super) fn settled_wide(mut q: Quantized, img: &Raster, own: &[bool], gray: b /// channels within 8 levels of each other) is therefore also continuous tone when eight colors /// stay more than 0.065 as far as a single color does. So is a sepia, single-hue or duotone /// picture whose tones follow one curve through the color cube (19 in 20 of its opaque pixels on -/// it, see [`on_one_curve`]). Neither is when sixteen colors stay at most a fifth as far as eight -/// do. That exception holds for flat art of up to sixteen clean levels, gray or tinted, where -/// sixteen colors come within about a level of every pixel. On gray and tinted photos sixteen -/// colors stay 0.18 to 0.57 as far as eight do, and on most anti-aliased or noisy gray flat art -/// 0.24 to 0.5 as far, so the exception holds for neither. +/// it, see [`on_one_curve`]). Neither is, however far eight colors stay, when sixteen colors stay +/// at most a tenth as far as eight do. That exception holds for flat art of up to sixteen clean +/// levels, gray or tinted, where sixteen colors come within about a level of every pixel. On gray +/// and tinted photos sixteen colors stay 0.18 to 0.57 as far as eight do, and on most anti-aliased +/// or noisy gray flat art 0.24 to 0.5 as far, so the exception holds for neither. pub(crate) fn continuous_tone(img: &Raster) -> bool { let hk = HistKey::new(img); let mut bins = vec![Bin::default(); 1 << 15]; @@ -318,10 +432,14 @@ pub(crate) fn continuous_tone(img: &Raster) -> bool { return false; } let one = unsaid(1); - if eight > 0.1 * one { - return true; + if eight <= 0.065 * one { + return false; } - eight > 0.065 * one && unsaid(16) > 0.2 * eight && (20 * neutral >= 19 * opaque || 20 * on_one_curve(img) >= 19 * opaque) + let one_line = || 20 * neutral >= 19 * opaque || 20 * on_one_curve(img) >= 19 * opaque; + if eight > 0.1 * one { + return !(unsaid(16) <= 0.1 * eight && one_line()); + } + unsaid(16) > 0.1 * eight && one_line() } /// How far (levels) a pixel may lie from the tone curve of its picture and still count as on it, @@ -656,6 +774,109 @@ fn edge_blend_of(own: [f64; 3], beside: [u8; 3], alpha: u8) -> bool { mod tests { use super::*; + /// Rings of four colors around a point off the center, blended over three pixels at each edge, + /// with a little noise, and a band of half-transparent pixels along the bottom. + fn rings(w: u32, h: u32) -> Raster { + let colors = [[200.0, 30.0, 40.0], [20.0, 60.0, 180.0], [240.0, 210.0, 50.0], [25.0, 25.0, 25.0]]; + Raster::from_fn(w, h, |x, y| { + let r = (f64::from(x) - 0.4 * f64::from(w)).hypot(f64::from(y) - 0.55 * f64::from(h)) / 9.0; + let (ring, t) = (r.floor() as usize, ((r.fract() - 0.8) / 0.2).clamp(0.0, 1.0)); + let (a, b) = (colors[ring % 4], colors[(ring + 1) % 4]); + let noise = f64::from((x * 7 + y * 13) % 5) - 2.0; + let c = [0, 1, 2].map(|k| (a[k] + t * (b[k] - a[k]) + noise).clamp(0.0, 255.0) as u8); + [c[0], c[1], c[2], if y + 2 >= h { 160 } else { 255 }] + }) + } + + #[test] + fn changes_are_copied_out_once_their_pairs_would_take_more_memory_than_the_labels() { + let labels: Vec = (0..64).collect(); + let pairs = labels.len() * size_of::() / size_of::<(usize, u16)>(); + let mut changes = Changes::new(labels.len()); + for at in 0..pairs { + changes.set(at * 3, 99, || labels.clone()); + } + assert!(changes.copy.is_none()); + assert!(changes.few.capacity() <= pairs, "the pairs take no more memory than a copy of the labels"); + changes.set(63, 98, || labels.clone()); + assert!(changes.few.is_empty() && changes.copy.is_some()); + changes.set(1, 97, || labels.clone()); + let mut out = labels.clone(); + changes.each(|at, to| out[at] = to); + let mut expected = labels.clone(); + (0..pairs).for_each(|at| expected[at * 3] = 99); + (expected[63], expected[1]) = (98, 97); + assert_eq!(out, expected); + } + + #[test] + fn blend_pixels_settle_the_same_however_the_picture_is_shared_out() { + // Odd sizes, so that the last band of rows and the last strip of columns are short. + let img = rings(173, 97); + let all = img.width as usize * img.height as usize; + let opaque: Vec = img.rgba.as_chunks::<4>().0.iter().map(|p| p[3] >= 128).collect(); + let own = super::super::own_colours_among(&img, &opaque); + // Two colors for each blend, and an olive that the blends lie nearer to than to their sides, + // each pixel labeled with the nearest of them (none for a transparent one). + let palette = vec![[200, 30, 40], [20, 60, 180], [240, 210, 50], [25, 25, 25], [120, 120, 60]]; + let labels = img + .rgba + .as_chunks::<4>() + .0 + .iter() + .map(|p| { + let d = |c: &[u8; 3]| (0..3).map(|k| (i32::from(p[k]) - i32::from(c[k])).pow(2)).sum::(); + (0..palette.len()).min_by_key(|&i| d(&palette[i])).map_or(TRANSPARENT, |i| i as u16) + }) + .collect(); + let q = Quantized { labels, palette }; + // One row (or one strip) per share, a few rows per share, and the whole picture as one. + let shares = [1, 3 * 173 + 5, all]; + for (name, settle) in [ + ("settled", &(|s| settled_by(q.clone(), &img, &own, s)) as &dyn Fn(usize) -> Quantized), + ("settled_wide", &|s| settled_wide_by(q.clone(), &img, &own, false, s)), + ("settled_wide gray", &|s| settled_wide_by(q.clone(), &img, &own, true, s)), + ] { + let out: Vec = shares.iter().map(|&s| settle(s)).collect(); + assert_ne!(out[0], q, "{name} settles some blend pixels"); + assert!(out.iter().all(|o| *o == out[0]), "{name}"); + } + } + + #[test] + fn blend_pixels_settle_the_same_when_most_of_a_share_changes() { + // Columns of red and blue own pixels, two blend pixels between each pair: one nearer to red + // and one nearer to blue, both labeled with an olive. Half the pixels of each band of rows and + // of each group of strips change, more than the eighth at which a share's changes are copied + // out (see [`Changes`]). 44 columns, so that the last strip of 7 is short. + let (w, h) = (44u32, 5u32); + let (red, blue) = ([200u8, 30, 40], [20u8, 60, 180]); + let mix = |t: f64| [0, 1, 2].map(|k| (f64::from(red[k]) + t * (f64::from(blue[k]) - f64::from(red[k]))).round() as u8); + let img = Raster::from_fn(w, h, |x, _| { + let c = [red, mix(0.3), mix(0.7), blue][x as usize % 4]; + [c[0], c[1], c[2], 255] + }); + let own: Vec = (0..w * h).map(|i| matches!(i % w % 4, 0 | 3)).collect(); + let labels = (0..w * h).map(|i| [0, 2, 2, 1][(i % w % 4) as usize]).collect(); + let q = Quantized { labels, palette: vec![red, blue, [120, 120, 60]] }; + let expected = Quantized { labels: (0..w * h).map(|i| [0, 0, 1, 1][(i % w % 4) as usize]).collect(), palette: vec![red, blue] }; + let all = (w * h) as usize; + for s in [1, 3 * 7 * h as usize, all] { + assert_eq!(settled_by(q.clone(), &img, &own, s), expected, "settled, {s} pixels per share"); + assert_eq!(settled_wide_by(q.clone(), &img, &own, false, s), expected, "settled_wide, {s} pixels per share"); + } + } + + #[test] + fn a_picture_with_no_pixels_settles_to_itself() { + let q = Quantized { labels: vec![], palette: vec![[0, 0, 0], [255, 255, 255]] }; + for (w, h) in [(u32::MAX, 0), (0, u32::MAX)] { + let img = Raster::new(w, h, vec![]).unwrap(); + assert_eq!(settled_by(q.clone(), &img, &[], PIXELS_PER_SHARE), q, "settled, {w} x {h}"); + assert_eq!(settled_wide_by(q.clone(), &img, &[], false, PIXELS_PER_SHARE), q, "settled_wide, {w} x {h}"); + } + } + #[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 diff --git a/crates/trace/src/raster.rs b/crates/trace/src/raster.rs index 5e198e6fb7..51312c685a 100644 --- a/crates/trace/src/raster.rs +++ b/crates/trace/src/raster.rs @@ -48,6 +48,54 @@ pub(crate) fn fit_size(w: u32, h: u32, max: u64) -> (u32, u32) { (nw, nh) } +/// The `w × h` RGBA8 `rgba` reduced to `nw × nh` (at most `w × h`): each pixel covers a block of +/// whole source pixels, and every source pixel falls in exactly one block. A pixel's alpha is the +/// mean of its block's alphas, and its color is the block's colors weighted by their alpha, so a +/// clear pixel next to an opaque one does not darken or tint it. A wholly clear block (every alpha +/// 0) keeps the plain mean of its colors. +pub(crate) fn box_reduced(rgba: &[u8], w: u32, h: u32, nw: u32, nh: u32) -> Vec { + let span = |i: u32, n: u32, of: u32| { + let at = |i: u32| usize::try_from(u64::from(i) * u64::from(of) / u64::from(n.max(1))).unwrap_or(usize::MAX); + let start = at(i); + start..at(i + 1).max(start + 1) + }; + let cols: Vec<_> = (0..nw).map(|x| span(x, nw, w)).collect(); + let mut out = Vec::with_capacity(nw as usize * nh as usize * 4); + // Per output column: the alpha-weighted color sums, the alpha sum and the plain color sums. + let mut sums = vec![[0u64; 7]; cols.len()]; + let row_len = w as usize * 4; + for ty in 0..nh { + let rows = span(ty, nh, h); + sums.fill([0; 7]); + for y in rows.clone() { + let Some(row) = rgba.get(y * row_len..(y + 1) * row_len) else { break }; + for (s, c) in sums.iter_mut().zip(&cols) { + let px = row.get(c.start * 4..c.end * 4).unwrap_or_default(); + for &[r, g, b, a] in px.as_chunks::<4>().0 { + let a64 = u64::from(a); + s[0] += u64::from(r) * a64; + s[1] += u64::from(g) * a64; + s[2] += u64::from(b) * a64; + s[3] += a64; + s[4] += u64::from(r); + s[5] += u64::from(g); + s[6] += u64::from(b); + } + } + } + for (s, c) in sums.iter().zip(&cols) { + let count = (rows.len() * c.len()).max(1) as u64; + let mean = |v: u64, n: u64| u8::try_from((v + n / 2) / n).unwrap_or(u8::MAX); + if s[3] == 0 { + out.extend_from_slice(&[mean(s[4], count), mean(s[5], count), mean(s[6], count), 0]); + } else { + out.extend_from_slice(&[mean(s[0], s[3]), mean(s[1], s[3]), mean(s[2], s[3]), mean(s[3], count)]); + } + } + } + out +} + /// An RGBA8 raster (row-major, top row first). #[derive(Clone, Debug, PartialEq)] pub struct Raster { @@ -150,12 +198,14 @@ impl Raster { let mut limits = image::Limits::default(); limits.max_alloc = Some(if cfg!(target_arch = "wasm32") { 512 << 20 } else { MAX_SOURCE_PIXELS * 4 }); reader.limits(limits); - let img = reader.decode().map_err(decode_err)?.into_rgba8(); + Ok(Self::fitted(&reader.decode().map_err(decode_err)?.into_rgba8(), MAX_PIXELS)) + } + /// `img` scaled down, aspect kept, to the largest size of at most `max` pixels. + pub(crate) fn fitted(img: &image::RgbaImage, max: u64) -> Self { let (w, h) = img.dimensions(); - let (nw, nh) = fit_size(w, h, MAX_PIXELS); + let (nw, nh) = fit_size(w, h, max); // Box-filtered: every source pixel counts, so thin lines and anti-aliased edges survive. - let small = image::imageops::thumbnail(&img, nw, nh); - Ok(Self { width: nw, height: nh, rgba: small.into_raw() }) + Self { width: nw, height: nh, rgba: box_reduced(img.as_raw(), w, h, nw, nh) } } /// Encode as PNG. pub fn encode_png(&self) -> Vec { diff --git a/crates/trace/src/tests.rs b/crates/trace/src/tests.rs index 3b4e84989a..2e24eb80bb 100644 --- a/crates/trace/src/tests.rs +++ b/crates/trace/src/tests.rs @@ -892,6 +892,35 @@ fn presets_resolve() { assert!(preset("nope").is_none()); } +#[test] +fn presets_have_their_paths_corners_and_noise() { + let expected: &[(&str, f64, f64, u32)] = &[ + ("Default", 50.0, 75.0, 25), + ("High Fidelity Photo", 50.0, 50.0, 5), + ("Low Fidelity Photo", 50.0, 50.0, 10), + ("3 Colors", 50.0, 50.0, 15), + ("6 Colors", 50.0, 50.0, 15), + ("16 Colors", 50.0, 50.0, 15), + ("Shades of Gray", 50.0, 50.0, 15), + ("Black and White Logo", 50.0, 75.0, 25), + ("Sketched Art", 50.0, 50.0, 20), + ("Silhouettes", 50.0, 50.0, 90), + ("Line Art", 50.0, 75.0, 20), + ("Technical Drawing", 50.0, 100.0, 1), + ("Outline", 50.0, 75.0, 20), + ]; + for &(name, paths, corners, noise) in expected { + let p = preset(name).unwrap(); + assert_eq!((p.paths, p.corners, p.noise), (paths, corners, noise), "{name}"); + } + // The color counts stay as they were. + let colors: Vec = ["High Fidelity Photo", "Low Fidelity Photo", "3 Colors", "6 Colors", "16 Colors", "Shades of Gray"] + .iter() + .map(|n| preset(n).unwrap().colors) + .collect(); + assert_eq!(colors, [64, 20, 3, 6, 16, 8]); +} + #[test] fn params_json_roundtrip_and_partial() { let p = preset("6 Colors").unwrap(); @@ -1085,6 +1114,30 @@ fn decode_to_fit_scales_an_oversized_image_down() { assert!(matches!(Raster::decode_to_fit(&png_header(9000, 9000)), Err(TraceError::Decode(_)))); } +/// Scaling an oversized image down weighs each color by its alpha: a clear pixel next to an +/// opaque one leaves the opaque color as it is and only lowers the alpha. +#[test] +fn scaling_down_weighs_color_by_alpha() { + use crate::raster::box_reduced; + const RED: [u8; 4] = [200, 30, 30, 255]; + // Opaque red and clear black columns, decoded from a PNG and scaled to fit as `decode_to_fit` + // does: each scaled pixel covers a red and a clear one. + let half_clear = Raster::from_fn(4, 2, |x, _| if x % 2 == 0 { RED } else { [0; 4] }); + let decoded = image::load_from_memory(&half_clear.encode_png()).unwrap().into_rgba8(); + let fitted = Raster::fitted(&decoded, 2); + assert_eq!((fitted.width, fitted.height), (2, 1)); + assert_eq!(fitted.rgba, [[200, 30, 30, 128]; 2].concat()); + // A partly clear blue pulls an opaque red toward it by its alpha. + let mixed = Raster::from_fn(2, 1, |x, _| if x == 0 { [255, 0, 0, 255] } else { [0, 0, 255, 85] }); + assert_eq!(box_reduced(&mixed.rgba, 2, 1, 1, 1), [191, 0, 64, 170]); + // A wholly clear block stays clear, with the plain mean of its colors. + let clear = Raster::from_fn(2, 1, |x, _| [100 * x as u8, 0, 0, 0]); + assert_eq!(box_reduced(&clear.rgba, 2, 1, 1, 1), [50, 0, 0, 0]); + // A 3 → 2 reduction counts every source pixel once. + let ramp = Raster::from_fn(3, 3, |x, y| [(x * 60 + y * 10) as u8, 0, 0, 255]); + assert_eq!(box_reduced(&ramp.rgba, 3, 3, 2, 2), [0, 0, 0, 255, 90, 0, 0, 255, 15, 0, 0, 255, 105, 0, 0, 255]); +} + /// Four flat colours with anti-aliased (blended) edges between the quadrants. fn flat_quads() -> Raster { const C: [[u8; 3]; 4] = [[220, 30, 30], [30, 200, 40], [30, 40, 210], [240, 220, 20]]; @@ -2009,6 +2062,16 @@ fn a_gray_photo_is_continuous_tone_as_its_color_original_is() { } } +/// A gray photo with little or no noise (a render, a denoised scan) is continuous tone, as its +/// color original is. Sixteen colors stay 0.19 as far from its pixels as eight do. +#[test] +fn a_clean_gray_photo_is_continuous_tone_as_its_color_original_is() { + for noise in [0.0, 1.0, 2.0, 3.0] { + assert!(quantize::continuous_tone(&photo_scene(noise, false)), "color, noise {noise}"); + assert!(quantize::continuous_tone(&photo_scene(noise, true)), "gray, noise {noise}"); + } +} + /// Sepia: dark brown to cream. const SEPIA: [[f64; 3]; 2] = [[45.0, 28.0, 15.0], [250.0, 235.0, 205.0]]; /// A single blue hue: navy to pale blue. @@ -2206,6 +2269,59 @@ fn tinted_flat_art_stays_flat_art() { } } +/// `levels` clean gray bands 20 px wide, evenly spaced from black to white. +fn even_gray_bands(levels: u32) -> Raster { + Raster::from_fn(levels * 20, 60, |x, _| { + let v = (x / 20 * 255 / (levels - 1)) as u8; + [v, v, v, 255] + }) +} + +#[test] +fn flat_art_of_up_to_sixteen_clean_levels_stays_flat_art() { + // Equal bands: eight colors leave more than a tenth of what a single color leaves. + let tints: [(&str, &[[f64; 3]]); 4] = [("gray", &GRAY_RAMP), ("sepia", &SEPIA), ("blue", &BLUE), ("duotone", &DUOTONE)]; + let mut smoothed = vec![]; + for (name, stops) in tints { + for levels in [10, 12, 14, 16] { + let bands = tinted(&even_gray_bands(levels), stops, 0.0); + if quantize::continuous_tone(&bands) { + smoothed.push(format!("{levels} {name} bands")); + } + if quantize::continuous_tone(&beside_transparent_colors(&bands)) { + smoothed.push(format!("{levels} {name} bands beside transparent colors")); + } + } + } + assert!(smoothed.is_empty(), "continuous tone: {smoothed:?}"); +} + +#[test] +fn thin_lines_on_flat_art_of_up_to_sixteen_clean_levels_are_traced() { + for levels in [12, 16] { + for (name, stops) in [("gray", &GRAY_RAMP[..]), ("sepia", &SEPIA[..])] { + let bands = even_gray_bands(levels); + // A 1 px black line across the bands at y = 30, and a 1 px white line down the second + // band at x = 25. + let lined = Raster::from_fn(bands.width, bands.height, |x, y| { + if y == 30 { + [0, 0, 0, 255] + } else if x == 25 { + [255, 255, 255, 255] + } else { + let i = ((y * bands.width + x) * 4) as usize; + [bands.rgba[i], bands.rgba[i + 1], bands.rgba[i + 2], 255] + } + }); + let res = trace(&tinted(&lined, stops, 0.0), &sixteen_colors()); + assert_eq!(res.palette.len(), levels as usize, "{levels} {name} bands: {:?}", res.palette); + // The black band with the black line; the white band above and below the line; the + // white line above and below it; the second band in four; each other band in two. + assert_eq!(res.paths.len(), 1 + 2 + 2 + 4 + 2 * (levels as usize - 3), "{levels} {name} bands"); + } + } +} + #[test] fn pictures_without_tones_are_not_continuous_tone() { let photo = tinted(&photo_scene(6.0, true), &SEPIA, 2.0); diff --git a/crates/ui-egui/src/addons/cutting.rs b/crates/ui-egui/src/addons/cutting.rs index 15a6790872..314a25fd0c 100644 --- a/crates/ui-egui/src/addons/cutting.rs +++ b/crates/ui-egui/src/addons/cutting.rs @@ -3,6 +3,7 @@ //! of `addon.cutting.bridges`. Weed Box and Lines… opens it on the options of `addon.cutting.weed`, //! with a Preview, and runs the command on OK. A Spacing above 0 is sent instead of the Count. //! Banner Hems and Grommets… opens it on the options of `addon.cutting.banner`, with a Preview. +//! Nest Shapes… opens it on the options of `addon.cutting.nest`, with a Preview. use serde_json::json; @@ -18,6 +19,8 @@ pub const WEED: &str = "addon.cutting.weed"; pub const WEED_DIRECTIONS: &[(&str, &str)] = &[("Horizontal", "horizontal"), ("Vertical", "vertical"), ("Both", "both")]; /// Banner Hems and Grommets' command. pub const BANNER: &str = "addon.cutting.banner"; +/// Nest Shapes' command. +pub const NEST: &str = "addon.cutting.nest"; /// Object › Plug-ins › Cutting Tools. pub fn menu() -> Vec { @@ -36,6 +39,11 @@ pub fn menu() -> Vec { "diameter": 27, "weight": 0.3, "swatch": "[Registration]" }), ), + Item::Cmd( + "Nest Shapes…", + NEST, + json!({"roll": false, "width": 0, "height": 0, "margin": 18, "spacing": 9, "rotate": false, "usePreviewBounds": true}), + ), ] } diff --git a/crates/ui-egui/src/addons/cutting/tests.rs b/crates/ui-egui/src/addons/cutting/tests.rs index 99580b369c..7e2787996f 100644 --- a/crates/ui-egui/src/addons/cutting/tests.rs +++ b/crates/ui-egui/src/addons/cutting/tests.rs @@ -210,3 +210,57 @@ fn banner_hems_and_grommets_previews_cancels_and_runs_on_ok() { // 528 pt along the top and bottom need 6 gaps, 328 pt down the sides 4: 20 grommets. assert_eq!(count(&app), nodes + 1 + 4 + 20 * 4); } + +/// Object › Plug-ins › Cutting Tools › Nest Shapes… opens the command dialog on its defaults with +/// Preview off, previews the packed objects, puts them back on Cancel and keeps them as one step +/// on OK. +#[test] +fn nest_shapes_previews_cancels_and_runs_on_ok() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); + let a = app.run("shape.rectangle", json!({"x": 700, "y": 100, "width": 50, "height": 40})).unwrap()["id"].clone(); + let b = app.run("shape.rectangle", json!({"x": 800, "y": 100, "width": 60, "height": 30})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + let steps = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len(); + let (start, n) = (app.session.doc().unwrap().doc.clone(), steps(&app)); + let open = |app: &mut VectorcraftApp| { + let entries = menus::menu_entries(app); + let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Cutting Tools"] && e.label == "Nest Shapes…").unwrap(); + assert!(item.enabled); + let (cmd, p) = menus::click_target(&item.label, item.command.as_deref().unwrap(), &item.params); + menus::invoke(app, &cmd, p); + }; + + open(&mut app); + let d = app.ui.dialog.as_ref().expect("a dialog opens"); + assert_eq!((d.str("__command"), d.str("__label")), (super::NEST.to_string(), "Nest Shapes".to_string())); + assert_eq!((d.bool("roll"), d.bool("rotate"), d.bool("usePreviewBounds"), d.bool("preview")), (false, false, true, false)); + let shown = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + for s in ["Nest Shapes", "Roll", "Width", "Height", "Margin", "Spacing", "Rotate", "Use Preview Bounds", "Preview"] { + assert!(shown.contains(s), "{s} in {shown}"); + } + crate::i18n::set_current(crate::i18n::Lang::from_code("de").expect("de registered")); + let german = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + crate::i18n::set_current(crate::i18n::Lang::EN); + for s in ["Formen verschachteln", "Rolle"] { + assert!(german.contains(s), "{s} in {german}"); + } + assert_eq!(app.session.doc().unwrap().doc, start, "no preview without the checkbox"); + + crate::dialogs::set_field(app.ui.dialog.as_mut().unwrap(), "preview".into(), json!(true)); + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert_ne!(app.session.doc().unwrap().doc, start, "previewed"); + crate::dialogs::cancel(&mut app); + assert_eq!(app.session.doc().unwrap().doc, start, "Cancel puts the objects back"); + assert_eq!(steps(&app), n, "and adds no undo step"); + + open(&mut app); + crate::dialogs::set_field(app.ui.dialog.as_mut().unwrap(), "margin".into(), json!("0 pt")); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(steps(&app), n + 1, "one undo step"); + let doc = &app.session.doc().unwrap().doc; + let left = |id: &serde_json::Value| doc.node(vectorcraft_doc::NodeId(id.as_u64().unwrap())).unwrap().geometric_bounds().unwrap().x0; + // The taller object goes first, its 1 pt stroke at the artboard's corner, and the other 9 pt to + // the right of its stroke. + assert_eq!((left(&a), left(&b)), (0.5, 0.5 + 51.0 + 9.0)); +} diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 286b4d4d02..8c6d669e14 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -164,6 +164,17 @@ pub struct CacheKey { /// The display profile the frame is converted into ([`crate::display_profile::DisplayProfile::key`]), /// 0 for none. pub display: u64, + /// The paper under the art that translucent art is blended with before the conversion + /// ([`crate::display_profile::convert_over`]). None without a display profile, and in Outline. + pub backdrop: Option>, +} + +impl CacheKey { + /// [`Self::backdrop`] with the zoom its grid's cells are measured at, as + /// [`crate::display_profile::convert_over`] takes it. + pub(crate) fn over(&self) -> Option<(&crate::display_profile::Backdrop, f64)> { + self.backdrop.as_deref().map(|b| (b, self.zoom)) + } } #[derive(Clone, Copy, Debug, Default)] diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index a947dde852..9120fe0cff 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -15,6 +15,7 @@ use crate::stylus::StylusFeed; use crate::theme::{self, Tokens}; use crate::{CacheKey, VectorcraftApp, now_ms, widgets}; +mod alternates_bar; mod artboards; mod context; mod contour_bar; @@ -186,6 +187,11 @@ pub(crate) fn dragging(ctx: &egui::Context) -> bool { ctx.data(|d| d.get_temp::(drag_id()).is_some()) } +/// Whether the canvas is holding a Zoom tool drag: a marquee, which Space moves, or an animated zoom. +pub(crate) fn dragging_zoom(ctx: &egui::Context) -> bool { + ctx.data(|d| matches!(d.get_temp::(drag_id()), Some(Drag::ZoomBox { .. } | Drag::ZoomScrub { .. }))) +} + /// The part of `outer` inside the scroll bars, and the part of that inside the rulers, which shows /// the document. Normal Screen Mode and Full Screen Mode with Menu Bar keep the scroll bars along /// the right and bottom edges; Full Screen and Presentation Mode have none. @@ -436,6 +442,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } if app.ui.screen_mode < 3 { contour_bar::contour_bar(app, ui, &xf); + // After the task bar, which the row of character alternates keeps clear of. + alternates_bar::alternates_bar(app, ui, &xf); } if app.ui.screen_mode < 3 { crate::free_transform::show(app, ui, xf.rect); @@ -623,6 +631,7 @@ fn cache_key( trace_source: app.ui.trace_hold_source.clone(), // Preferences › Performance › Use Monitor Profile for Canvas. display: app.display_profile.key(app.session.prefs.monitor_profile_display), + backdrop: backdrop(app, st, app.outline_view()), } } @@ -887,9 +896,10 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) { } if let (Some([x0, y0, x1, y1]), Some(tex)) = (region, &mut app.canvas.texture) { let renderer = &mut app.canvas.renderer; - let mut part = - effects.view(|| renderer.render(doc, x1 - x0, y1 - y0, Affine::translate((-f64::from(x0), -f64::from(y0))) * view, &opts)); - crate::display_profile::convert(display.as_deref(), &mut part.pixels); + let part_view = Affine::translate((-f64::from(x0), -f64::from(y0))) * view; + let mut part = effects.view(|| renderer.render(doc, x1 - x0, y1 - y0, part_view, &opts)); + let width = part.width; + crate::display_profile::convert_over(display.as_deref(), &mut part.pixels, width, part_view, key.over()); let color = color_image(&part); let options = if pixel.is_some() { egui::TextureOptions::NEAREST } else { egui::TextureOptions::LINEAR }; tex.set_partial([x0 as usize, y0 as usize], color, options); @@ -927,7 +937,8 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) { let renderer = &mut app.canvas.renderer; let mut img = effects.view(|| renderer.render(doc, w, h, view, &opts)); effects.first_view_done(); - crate::display_profile::convert(display.as_deref(), &mut img.pixels); + let width = img.width; + crate::display_profile::convert_over(display.as_deref(), &mut img.pixels, width, view, key.over()); upload(app, ui.ctx(), img, pixel.is_some()); app.canvas.key = Some(key.clone()); app.canvas.shown = Some((doc.clone(), opts.clone())); @@ -982,13 +993,11 @@ fn paint_paper( let on_display = |c: Color32| crate::display_profile::color32(display.as_deref(), c); if !shows_artboards(app) { // View › Hide Artboards: no edges and no pasteboard, the whole canvas paper (#4038). - let setup = &doc.setup; - painter.rect_filled(rect, 0.0, on_display(if setup.simulate_paper { crate::panels::c32(&setup.paper()) } else { Color32::WHITE })); + painter.rect_filled(rect, 0.0, on_display(paper_color(&doc.setup))); } else { let setup = &doc.setup; - let grid = (st.transparency_grid && setup.background == vectorcraft_doc::Background::Transparent) - .then(|| checker_texture(ui.ctx(), setup, display.as_deref())); - let paper = if setup.simulate_paper { crate::panels::c32(&setup.paper()) } else { Color32::WHITE }; + let grid = shows_transparency_grid(st).then(|| checker_texture(ui.ctx(), setup, display.as_deref())); + let paper = paper_color(setup); for ab in &doc.artboards { let q = xf.quad(ab.rect); // Hard 2 pt drop shadow, right and bottom (measured: #4d4d4d then #565656 on #606060). @@ -998,14 +1007,52 @@ fn paint_paper( match &grid { Some((tex, cell)) => checker(painter, &q, ab.rect, xf.zoom, tex.id(), *cell), None => { - let fill = ab.color.map_or(paper, |c| crate::panels::c32(&c) * paper); - painter.add(Shape::convex_polygon(q, on_display(fill), Stroke::NONE)); + painter.add(Shape::convex_polygon(q, on_display(artboard_paper(ab, paper)), Stroke::NONE)); } } } } } +/// The color of the paper: Simulate Colored Paper's, else white. +fn paper_color(setup: &vectorcraft_doc::DocSetup) -> Color32 { + if setup.simulate_paper { crate::panels::c32(&setup.paper()) } else { Color32::WHITE } +} + +/// The color of artboard `ab`'s paper, the paper `paper`: an artboard with a background color +/// multiplies it with the paper, each sRGB channel artboard × paper / 255, rounded. +fn artboard_paper(ab: &vectorcraft_doc::Artboard, paper: Color32) -> Color32 { + ab.color.map_or(paper, |c| crate::panels::c32(&c) * paper) +} + +/// The transparency grid covers the artboards of document `st`: it is shown, and the Background +/// Contents are transparent. +fn shows_transparency_grid(st: &vectorcraft_engine::DocState) -> bool { + st.transparency_grid && st.doc.setup.background == vectorcraft_doc::Background::Transparent +} + +/// The paper [`paint_paper`] draws for document `st`, which translucent art is blended with before +/// the display profile's conversion. None without a display profile, and in Outline (`outline`), +/// whose white canvas is the interface's. +fn backdrop(app: &VectorcraftApp, st: &vectorcraft_engine::DocState, outline: bool) -> Option> { + if outline || app.display_profile.transform(app.session.prefs.monitor_profile_display).is_none() { + return None; + } + let rgb = |c: Color32| [c.r(), c.g(), c.b()]; + let setup = &st.doc.setup; + let paper = paper_color(setup); + let b = if shows_artboards(app) { + crate::display_profile::Backdrop { + everywhere: None, + artboards: st.doc.artboards.iter().map(|ab| (ab.rect, rgb(artboard_paper(ab, paper)))).collect(), + grid: shows_transparency_grid(st).then(|| (setup.grid_colors.map(|c| rgb(crate::panels::c32(&c))), setup.grid_size.cell())), + } + } else { + crate::display_profile::Backdrop { everywhere: Some(rgb(paper)), artboards: vec![], grid: None } + }; + Some(std::sync::Arc::new(b)) +} + /// The last rendered frame, placed through the current view while a new one is on its way. fn reproject_frame(app: &VectorcraftApp, painter: &egui::Painter, xf: &Xf, rect: egui::Rect, (key_doc, rotation): (usize, f64)) { if let (Some(tex), Some(k)) = (&app.canvas.texture, &app.canvas.key) diff --git a/crates/ui-egui/src/canvas/alternates_bar.rs b/crates/ui-egui/src/canvas/alternates_bar.rs new file mode 100644 index 0000000000..83914ef11d --- /dev/null +++ b/crates/ui-egui/src/canvas/alternates_bar.rs @@ -0,0 +1,163 @@ +//! Character alternates on the canvas: with a Type tool and exactly one character selected, a +//! small row of that character's alternate glyphs shows beside it. A click on a glyph draws the +//! character with it, as a double-click on the glyph in the Glyphs panel's Show › Alternates for +//! Current Selection does, through the same command and so as one undo step. An arrow at the end +//! of the row opens the Glyphs panel when the character has more alternates than the row shows. +//! Preferences › Type › Show Character Alternates (`showCharacterAlternates`) turns the row off. +//! +//! Public behavior: selecting a character shows its alternate glyphs next to it, a click replaces +//! the character's glyph, at most five alternates show, and a control to their right opens the +//! Glyphs panel for the rest ("Replace a character with on-canvas alternate glyphs", +//! ; +//! [Replace characters with alternate glyphs](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/replace-characters-with-alternate-glyphs.html)). +//! The row's place, its size and the preference are VectorCraft's own. + +use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_geom::Point; +use vectorcraft_text::FontDb; + +use super::{CornerRadius, Pos2, Sense, Shape, Stroke, StrokeKind, Tokens, Ui, Vec2, VectorcraftApp, Xf, pos2, vec2}; +use crate::panels::glyphs; + +/// The side of one glyph cell, in points. +const CELL: f32 = 28.0; +/// The width of the arrow that opens the Glyphs panel. +const MORE: f32 = 16.0; +/// The space between the row's edge and its cells: the frame's 1-point line and 3 points inside it. +const PAD: f32 = 4.0; +/// The space between the selected character and the row. +const GAP: f32 = 6.0; + +fn bar_id() -> egui::Id { + egui::Id::unique("character-alternates-bar") +} + +/// Where the row was last drawn (none while it isn't shown). +#[cfg(test)] +pub(super) fn bar_rect(ctx: &egui::Context) -> Option { + let id = bar_id(); + ctx.memory(|m| m.areas().is_visible(&egui::LayerId::new(egui::Order::Middle, id)).then(|| m.area_rect(id)).flatten()) +} + +/// The size of a row of `count` glyphs, with the arrow when `more`. +fn bar_size(count: usize, more: bool) -> Vec2 { + let cells = count as f32 * CELL + if more { MORE } else { 0.0 }; + vec2(cells + 2.0 * PAD, CELL + 2.0 * PAD) +} + +/// The document-space highlight quads of bytes `a..b` of text `id`, and whether the text is set +/// vertically. Kept until the document or the selection changes, so the text is laid out once for +/// each, not in every frame. Empty for a character the text does not draw (overset area type). +fn character_quads(app: &VectorcraftApp, ui: &Ui, id: NodeId, (a, b): (usize, usize)) -> Option<(Vec<[Point; 4]>, bool)> { + type Quads = (Vec<[Point; 4]>, bool); + let st = app.session.active()?; + let key = (st.uid, st.revision, id, a, b); + let slot = bar_id().with("quads"); + if let Some((cached_key, quads)) = ui.ctx().data(|d| d.get_temp::<((u64, u64, NodeId, usize, usize), Quads)>(slot)) + && cached_key == key + { + return Some(quads); + } + let NodeKind::Text(tx) = &st.doc.node(id)?.kind else { return None }; + let lay = vectorcraft_text::layout(FontDb::global(), tx); + let quads: Vec<[Point; 4]> = vectorcraft_text::selection_quads(&lay, a, b).into_iter().map(|q| q.map(|c| tx.xf * c)).collect(); + let found = (quads, tx.vertical); + ui.ctx().data_mut(|d| d.insert_temp(slot, (key, found.clone()))); + Some(found) +} + +/// The top-left corner of a row of `size` beside the selected character's screen box `sel`, inside +/// `area`. The row goes under a character of horizontal type, or over it when there is no room +/// under it; beside a character of vertical type, on its right, or on its left when there is no +/// room on the right. A side is also given up when the row would cover `avoid` there (the +/// Contextual Task Bar). With no room on either side the row takes the first one, moved into +/// `area`. +fn place(sel: egui::Rect, size: Vec2, area: egui::Rect, vertical: bool, avoid: Option) -> Pos2 { + let sides = if vertical { + [pos2(sel.right() + GAP, sel.center().y - size.y / 2.0), pos2(sel.left() - GAP - size.x, sel.center().y - size.y / 2.0)] + } else { + [pos2(sel.center().x - size.x / 2.0, sel.bottom() + GAP), pos2(sel.center().x - size.x / 2.0, sel.top() - GAP - size.y)] + }; + let last = (area.max - size).max(area.min); + // Along the character's line the row may slide to stay on the canvas; across it, it may not. + let slide = |at: Pos2| if vertical { pos2(at.x, at.y.clamp(area.min.y, last.y)) } else { pos2(at.x.clamp(area.min.x, last.x), at.y) }; + let fits = |at: Pos2| { + let r = egui::Rect::from_min_size(at, size); + area.contains_rect(r) && avoid.is_none_or(|bar| !bar.intersects(r)) + }; + let sides = sides.map(slide); + sides.into_iter().find(|at| fits(*at)).unwrap_or_else(|| sides[0].clamp(area.min, last)) +} + +/// The row of alternate glyphs beside the Type tool's one selected character. +pub(super) fn alternates_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { + // Not while a press or a drag is choosing the selection: the row would follow the pointer. + if !app.session.prefs.show_character_alternates || !app.session.tool_wants_text() || app.session.tool_busy() { + return; + } + let Some(found) = glyphs::on_canvas(app, ui) else { return }; + let Some((quads, vertical)) = character_quads(app, ui, found.id, found.bytes) else { return }; + let corners: Vec = quads.iter().flatten().map(|p| xf.to_screen(*p)).collect(); + if corners.is_empty() { + return; + } + let sel = egui::Rect::from_points(&corners); + // A character scrolled off the canvas has no row. + if !sel.intersects(xf.rect) { + return; + } + let t = Tokens::get(ui.ctx()); + let count = found.count(); + let at = place(sel, bar_size(count, found.more), xf.rect.shrink(4.0), vertical, super::task_bar_rect(ui.ctx())); + let px = (CELL * ui.ctx().pixels_per_point()).round().clamp(8.0, 256.0) as u32; + let (mut pick, mut more) = (None, false); + egui::Area::new(bar_id()).order(egui::Order::Middle).fixed_pos(at).show(ui.ctx(), |ui| { + egui::Frame::NONE + .fill(t.panel) + .stroke(Stroke::new(1.0, t.border)) + .corner_radius(CornerRadius::same(4)) + .inner_margin(egui::Margin::same(PAD as i8 - 1)) + .shadow(egui::epaint::Shadow { offset: [0, 3], blur: 10, spread: 0, color: egui::Color32::from_black_alpha(70) }) + .show(ui, |ui| { + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing = vec2(0.0, 0.0); + for i in 0..count { + let (rect, resp) = ui.allocate_exact_size(vec2(CELL, CELL), Sense::click()); + if resp.hovered() { + ui.painter().rect_filled(rect, 2, t.hover); + } + ui.painter().rect_stroke(rect.shrink(0.5), 0, Stroke::new(0.5, t.border), StrokeKind::Inside); + if let Some(tex) = found.texture(ui.ctx(), i, px) { + let uv = egui::Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)); + ui.painter().image(tex.id(), rect, uv, t.text_strong); + } + let tip = found.tip(i); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &tip)); + if resp.on_hover_text(&tip).clicked() { + pick = Some(i); + } + } + if found.more { + let (rect, resp) = ui.allocate_exact_size(vec2(MORE, CELL), Sense::click()); + if resp.hovered() { + ui.painter().rect_filled(rect, 2, t.hover); + } + let c = rect.center(); + let arrow = vec![pos2(c.x - 2.5, c.y - 5.0), pos2(c.x + 3.5, c.y), pos2(c.x - 2.5, c.y + 5.0)]; + ui.painter().add(Shape::convex_polygon(arrow, t.text_strong, Stroke::NONE)); + let tip = tl!("Show all alternates in the Glyphs panel"); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tip)); + more = resp.on_hover_text(tip).clicked(); + } + }); + }); + }); + if let Some(i) = pick { + found.pick(app, i); + } else if more { + glyphs::show_alternates(app, ui.ctx()); + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/canvas/alternates_bar/tests.rs b/crates/ui-egui/src/canvas/alternates_bar/tests.rs new file mode 100644 index 0000000000..be2eb59f97 --- /dev/null +++ b/crates/ui-egui/src/canvas/alternates_bar/tests.rs @@ -0,0 +1,247 @@ +use egui::{Pos2, Rect}; +use serde_json::{Value, json}; +use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_text::FontDb; + +use super::*; + +/// The Type tool editing `text` in a new document. +fn editing(text: &str, vertical: bool) -> (VectorcraftApp, Value) { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + app.session.select_tool("type", Default::default()).unwrap(); + let id = app.run("text.create", json!({"x": 120, "y": 80, "text": text, "vertical": vertical})).unwrap()["id"].clone(); + app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap(); + (app, id) +} + +fn select(app: &mut VectorcraftApp, start: usize, end: usize) { + app.session.set_tool_option("select", &json!({"start": start, "end": end})); +} + +const SCREEN: Rect = Rect::from_min_max(Pos2::ZERO, Pos2::new(800.0, 600.0)); + +/// One frame of the canvas with `events`; where the row of alternates is afterwards, if it shows. +fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> Option { + egui_extras::install_image_loaders(ctx); + let raw = egui::RawInput { screen_rect: Some(SCREEN), events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| super::super::show(app, ui)); + out.textures_delta.clear(); + bar_rect(ctx) +} + +/// The glyphs the row offers and whether it has the arrow, as the canvas finds them. +fn offered(app: &mut VectorcraftApp, ctx: &egui::Context) -> Option<(Vec, bool)> { + let mut found = None; + let raw = egui::RawInput { screen_rect: Some(SCREEN), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + found = glyphs::on_canvas(app, ui).map(|f| ((0..f.count()).filter_map(|i| f.gid(i)).collect(), f.more)); + }); + out.textures_delta.clear(); + found +} + +/// A click at `at`, with a frame before it that lays the row out and moves the pointer there. +fn click(app: &mut VectorcraftApp, ctx: &egui::Context, at: Pos2) { + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(app, ctx, vec![egui::Event::PointerMoved(at)]); + frame(app, ctx, vec![button(true), button(false)]); +} + +/// The center of cell `i` of the row at `bar`. +fn cell(bar: Rect, i: usize) -> Pos2 { + bar.min + vec2(PAD + CELL * (i as f32 + 0.5), PAD + CELL / 2.0) +} + +/// The center of the arrow of a row of `count` cells at `bar`. +fn arrow(bar: Rect, count: usize) -> Pos2 { + bar.min + vec2(PAD + CELL * count as f32 + MORE / 2.0, PAD + CELL / 2.0) +} + +fn glyph_ids(app: &VectorcraftApp, id: &Value) -> Vec { + let NodeKind::Text(text) = &app.session.active().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap().kind else { panic!("text") }; + let mut glyphs = vectorcraft_text::layout(FontDb::global(), text).glyphs; + glyphs.sort_by_key(|g| g.byte); + glyphs.iter().map(|g| g.gid).collect() +} + +fn undo_steps(app: &VectorcraftApp) -> usize { + app.session.active().unwrap().history.undo.len() +} + +/// The screen box of bytes `a..b` of the text, as the canvas of [`frame`] draws it. +fn character_box(app: &VectorcraftApp, id: &Value, a: usize, b: usize) -> Rect { + let NodeKind::Text(text) = &app.session.active().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap().kind else { panic!("text") }; + let lay = vectorcraft_text::layout(FontDb::global(), text); + let xf = app.canvas_xf().expect("a frame was drawn"); + let corners: Vec = vectorcraft_text::selection_quads(&lay, a, b).iter().flatten().map(|p| xf.to_screen(text.xf * *p)).collect(); + Rect::from_points(&corners) +} + +/// With the Type tool and exactly one character selected, the canvas shows up to five of that +/// character's alternates beside it, without the glyph it is drawn with, and an arrow when it has +/// more. A click draws the character with the glyph as one undo step and keeps the text. A caret, +/// a longer selection, a character without alternates, another tool and the preference turned off +/// each show no row. +#[test] +fn one_selected_character_shows_its_alternates_and_a_click_replaces_its_glyph() { + use vectorcraft_text::test_fonts::{alternates_family, alternates_font, unencoded_glyphs}; + FontDb::global().add_font(alternates_font(true).expect("the test font builds")); + let [u1, ..] = unencoded_glyphs().expect("unencoded glyphs"); + let (mut app, id) = editing("xay", false); + app.run("text.setRangeStyle", json!({"id": id, "font": alternates_family(true)})).unwrap(); + let ctx = egui::Context::default(); + let drawn = glyph_ids(&app, &id); + + select(&mut app, 1, 1); + assert_eq!(frame(&mut app, &ctx, vec![]), None, "a caret selects no character"); + select(&mut app, 0, 2); + assert_eq!(frame(&mut app, &ctx, vec![]), None, "two characters are selected"); + select(&mut app, 0, 1); + assert_eq!(frame(&mut app, &ctx, vec![]), None, "x has no alternates"); + + select(&mut app, 1, 2); + let bar = frame(&mut app, &ctx, vec![]).expect("the a has alternates"); + let task_bar = super::super::task_bar_rect(&ctx).expect("the task bar shows for type being edited"); + let (gids, more) = offered(&mut app, &ctx).expect("offered"); + assert_eq!(gids.len(), glyphs::ON_CANVAS_ALTERNATES, "five of the six alternates"); + assert!(more, "the sixth is in the Glyphs panel"); + assert_eq!(gids[0], u1); + assert!(!gids.contains(&drawn[1]), "the glyph the a is drawn with is not offered"); + assert_eq!(bar.size(), bar_size(5, true), "five cells and the arrow"); + // The Contextual Task Bar is under the type, so the row goes over the character. + // The row is placed on whole pixels, so it is within one of where the character's box puts it. + let sel = character_box(&app, &id, 1, 2); + assert!(task_bar.intersects(Rect::from_min_size(pos2(bar.left(), sel.bottom() + GAP), bar.size())), "{task_bar:?} {sel:?}"); + assert!((sel.top() - bar.bottom() - GAP).abs() < 1.0, "over the character: {bar:?} {sel:?}"); + assert!((bar.center().x - sel.center().x).abs() < 1.0, "centered on it"); + // Without the task bar the row is under the character. + app.ui.task_bar = false; + frame(&mut app, &ctx, vec![]); + let under = frame(&mut app, &ctx, vec![]).expect("the row"); + assert!((under.top() - sel.bottom() - GAP).abs() < 1.0, "under the character: {under:?} {sel:?}"); + app.ui.task_bar = true; + frame(&mut app, &ctx, vec![]); + assert_eq!(frame(&mut app, &ctx, vec![]), Some(bar)); + + // A click on the first glyph. + let undo = undo_steps(&app); + click(&mut app, &ctx, cell(bar, 0)); + assert_eq!(undo_steps(&app), undo + 1, "one undo step; status: {}", app.ui.status); + assert_eq!(glyph_ids(&app, &id), [drawn[0], u1, drawn[2]], "the a is drawn with the glyph"); + let NodeKind::Text(text) = &app.session.active().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap().kind else { panic!("text") }; + assert_eq!(text.plain_text(), "xay", "the text keeps its characters"); + + // The row stays for the same character: its default glyph first, the drawn glyph left out. + let bar = frame(&mut app, &ctx, vec![]).expect("still one character selected"); + let (gids, _) = offered(&mut app, &ctx).expect("offered"); + assert_eq!(gids[0], drawn[1], "the default glyph comes first"); + assert!(!gids.contains(&u1)); + click(&mut app, &ctx, cell(bar, 0)); + assert_eq!(undo_steps(&app), undo + 2); + assert_eq!(glyph_ids(&app, &id), drawn, "the default glyph again"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(glyph_ids(&app, &id), [drawn[0], u1, drawn[2]], "undo takes one pick back"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(glyph_ids(&app, &id), drawn); + + // Preferences › Type › Show Character Alternates. + select(&mut app, 1, 2); + assert!(frame(&mut app, &ctx, vec![]).is_some()); + app.run("prefs.set", json!({"key": "showCharacterAlternates", "value": false})).unwrap(); + assert_eq!(frame(&mut app, &ctx, vec![]), None, "the preference is off"); + app.run("prefs.set", json!({"key": "showCharacterAlternates", "value": true})).unwrap(); + assert!(frame(&mut app, &ctx, vec![]).is_some()); + + app.session.select_tool("select", Default::default()).unwrap(); + assert_eq!(frame(&mut app, &ctx, vec![]), None, "the Selection tool edits no text"); +} + +/// The arrow at the end of the row opens the Glyphs panel on Show › Alternates for Current +/// Selection and changes nothing in the document. +#[test] +fn the_arrow_opens_the_glyphs_panel_on_the_alternates() { + use vectorcraft_text::test_fonts::{alternates_family, alternates_font}; + FontDb::global().add_font(alternates_font(true).expect("the test font builds")); + let (mut app, id) = editing("xay", false); + app.run("text.setRangeStyle", json!({"id": id, "font": alternates_family(true)})).unwrap(); + select(&mut app, 1, 2); + let ctx = egui::Context::default(); + app.run("window.panel.close", json!({"panel": "glyphs"})).ok(); + assert!(!crate::panel_docking::visible(&app.ui, "glyphs")); + let bar = frame(&mut app, &ctx, vec![]).expect("the row"); + let (undo, drawn) = (undo_steps(&app), glyph_ids(&app, &id)); + click(&mut app, &ctx, arrow(bar, 5)); + assert!(crate::panel_docking::visible(&app.ui, "glyphs"), "status: {}", app.ui.status); + // The Show menu's entry after its seven character subsets. + assert_eq!(crate::panels::pstate::(&ctx, "gl-subset"), 7); + assert_eq!(undo_steps(&app), undo); + assert_eq!(glyph_ids(&app, &id), drawn); +} + +/// A medial letter of a joined Arabic word gets the alternates of its medial form, and a click +/// applies the feature that draws one to that letter alone: its neighbors keep their joining +/// forms. Three alternates need no arrow. +#[test] +fn a_letter_of_a_joined_word_keeps_the_word_joined() { + use vectorcraft_text::test_fonts::{JOINING_ALTERNATES_FAMILY, joining_alternates_font, source_sans_gid}; + FontDb::global().add_font(joining_alternates_font().expect("the test font builds")); + let g = |c| u32::from(source_sans_gid(c).expect("a glyph")); + let (mut app, id) = editing("\u{628}\u{62A}\u{646}", false); + app.run("text.setRangeStyle", json!({"id": id, "font": JOINING_ALTERNATES_FAMILY})).unwrap(); + assert_eq!(glyph_ids(&app, &id), [g('B'), g('u'), g('M')]); + select(&mut app, 2, 4); + let ctx = egui::Context::default(); + let bar = frame(&mut app, &ctx, vec![]).expect("the medial teh has alternates"); + let (gids, more) = offered(&mut app, &ctx).expect("offered"); + assert_eq!((gids.len(), more), (3, false), "the medial form's three alternates: {gids:?}"); + assert_eq!(bar.size(), bar_size(3, false), "three cells and no arrow"); + let at = gids.iter().position(|gid| *gid == g('x')).expect("the alternate salt=2 draws"); + let undo = undo_steps(&app); + click(&mut app, &ctx, cell(bar, at)); + assert_eq!(undo_steps(&app), undo + 1, "status: {}", app.ui.status); + assert_eq!(glyph_ids(&app, &id), [g('B'), g('x'), g('M')], "the neighbors keep their initial and final forms"); + let NodeKind::Text(text) = &app.session.active().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap().kind else { panic!("text") }; + assert_eq!(text.plain_text(), "\u{628}\u{62A}\u{646}"); + assert!(text.runs.iter().all(|r| r.style.glyph_alternate.is_none()), "a feature draws it, not a glyph choice"); +} + +/// The row stands on the right of a character of vertical type, level with it. +#[test] +fn the_row_stands_beside_a_character_of_vertical_type() { + use vectorcraft_text::test_fonts::{alternates_family, alternates_font}; + FontDb::global().add_font(alternates_font(true).expect("the test font builds")); + let (mut app, id) = editing("xay", true); + app.run("text.setRangeStyle", json!({"id": id, "font": alternates_family(true)})).unwrap(); + select(&mut app, 1, 2); + let ctx = egui::Context::default(); + app.ui.task_bar = false; + // The first frame fits the view to the canvas. + frame(&mut app, &ctx, vec![]); + let bar = frame(&mut app, &ctx, vec![]).expect("the row"); + let sel = character_box(&app, &id, 1, 2); + assert!((bar.left() - sel.right() - GAP).abs() < 1.0, "on the right of the character: {bar:?} {sel:?}"); + assert!((bar.center().y - sel.center().y).abs() < 1.0, "level with it"); +} + +/// [`place`]: under the character, over it when the canvas ends below or the task bar is there, +/// on the right or left of vertical type, and inside the canvas when neither side has room. +#[test] +fn the_row_is_placed_on_the_side_that_has_room() { + let area = Rect::from_min_max(pos2(0.0, 0.0), pos2(400.0, 300.0)); + let size = vec2(100.0, 34.0); + let sel = Rect::from_min_max(pos2(190.0, 100.0), pos2(210.0, 130.0)); + assert_eq!(place(sel, size, area, false, None), pos2(150.0, 136.0), "under"); + let low = sel.translate(vec2(0.0, 150.0)); + assert_eq!(place(low, size, area, false, None), pos2(150.0, 210.0), "over: no room under"); + let task_bar = Rect::from_min_max(pos2(100.0, 140.0), pos2(300.0, 180.0)); + assert_eq!(place(sel, size, area, false, Some(task_bar)), pos2(150.0, 60.0), "over: the task bar is under"); + let edge = sel.translate(vec2(-185.0, 0.0)); + assert_eq!(place(edge, size, area, false, None), pos2(0.0, 136.0), "moved along the line to stay on the canvas"); + assert_eq!(place(sel, size, area, true, None), pos2(216.0, 98.0), "vertical type: on the right"); + let right = sel.translate(vec2(150.0, 0.0)); + assert_eq!(place(right, size, area, true, None), pos2(234.0, 98.0), "vertical type: on the left"); + let small = Rect::from_min_max(pos2(0.0, 0.0), pos2(400.0, 60.0)); + let inside = Rect::from_min_max(pos2(190.0, 20.0), pos2(210.0, 40.0)); + assert_eq!(place(inside, size, small, false, None), pos2(150.0, 26.0), "no room on either side: kept inside the canvas"); +} diff --git a/crates/ui-egui/src/canvas/input.rs b/crates/ui-egui/src/canvas/input.rs index 4d121eb2a3..88bb262844 100644 --- a/crates/ui-egui/src/canvas/input.rs +++ b/crates/ui-egui/src/canvas/input.rs @@ -179,6 +179,12 @@ pub(super) fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respo { double_click(app, ui, &f, p); } + if resp.triple_clicked() + && !f.modal + && let Some(p) = at + { + triple_click(app, ui, &f, p); + } if drag.is_some() || pointer.is_moving() || mods_changed { ui.ctx().request_repaint(); } @@ -373,7 +379,7 @@ fn drag_held(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, d: Drag, p: Pos2) } } Drag::ZoomBox { start } => { - let start = zoom_marquee_start(ui, start, before, p, space); + let start = zoom_marquee_start(ui, start, before, p); ui.data_mut(|dd| dd.insert_temp(drag_id(), Drag::ZoomBox { start })); marquee(ui.painter(), egui::Rect::from_two_pos(start, p)); } @@ -480,7 +486,7 @@ fn drag_released(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, d: Drag, p: Po let ui_zoom = app.canvas_ui_zoom; match d { Drag::ZoomBox { start } => { - let start = zoom_marquee_start(ui, start, before, p, space); + let start = zoom_marquee_start(ui, start, before, p); ui.data_mut(|dd| dd.remove::(zoom_space_free_id())); let r = egui::Rect::from_two_pos(start, p); if let Some(vm) = app.view_mut() { @@ -591,6 +597,23 @@ fn double_click(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, p: Pos2) { } } +/// A triple-click at `p`: the tool gets it, unless it is on an artboard's name. +fn triple_click(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, p: Pos2) { + let Pointing { m, space, xf, view, .. } = *f; + if artboard_name_at(app, ui, &xf, p).is_some() { + return; + } + let ev = PointerEvent { + kind: PointerKind::TripleClick, + pos: xf.to_doc(p), + mods: mods(m, space), + backquote: ui.input(|i| i.key_down(egui::Key::Backtick)), + pressure: 1.0, + pen: None, + }; + dispatch(app, &ev, view); +} + /// Where `button` went up in this frame, if it did. fn release_pos(ui: &Ui, button: egui::PointerButton) -> Option { ui.input(|i| { @@ -612,22 +635,25 @@ fn zoom_space_free_id() -> egui::Id { /// sizes the marquee until it is let go. A marquee with no size yet is sized by the movement, so /// Space pressed before the pointer moves does not keep it at the press point. The frame's pointer /// moves and Space presses and releases are taken in the order they came, so each move follows the -/// Space state it came with. -fn zoom_marquee_start(ui: &Ui, start: Pos2, before: Option, p: Pos2, space: bool) -> Pos2 { +/// Space state it came with. The Space key counts as held whatever the modifiers, so a marquee that +/// Cmd+Space started while the Type tool edits text follows the same rules once Cmd is let go. +fn zoom_marquee_start(ui: &Ui, start: Pos2, before: Option, p: Pos2) -> Pos2 { enum Step { Space(bool), Move(Pos2), } let id = zoom_space_free_id(); - let steps: Vec = ui.input(|i| { - i.events + let (steps, space): (Vec, bool) = ui.input(|i| { + let steps = i + .events .iter() .filter_map(|e| match e { egui::Event::Key { key: egui::Key::Space, pressed, repeat: false, .. } => Some(Step::Space(*pressed)), egui::Event::PointerMoved(q) => Some(Step::Move(*q)), _ => None, }) - .collect() + .collect(); + (steps, i.key_down(egui::Key::Space)) }); // Space as it was when the frame began: the opposite of its first press or release, else as it is now. let mut held = steps.iter().find_map(|s| if let Step::Space(down) = s { Some(!down) } else { None }).unwrap_or(space); diff --git a/crates/ui-egui/src/canvas/overlays.rs b/crates/ui-egui/src/canvas/overlays.rs index aefd9253e9..119c811d0b 100644 --- a/crates/ui-egui/src/canvas/overlays.rs +++ b/crates/ui-egui/src/canvas/overlays.rs @@ -276,26 +276,27 @@ pub(super) fn blend_widgets_overlay(app: &VectorcraftApp, p: &egui::Painter, xf: /// Objects on Path group selected). The Rotate All widget is joined by a line to the first object's /// attachment point. It stays while dragged. fn rotate_all_widget(p: &egui::Painter, xf: &Xf, tool: &str, doc: &vectorcraft_doc::Document, selection: &vectorcraft_doc::Selection) { - use vectorcraft_tools::objects_on_path::{ROTATE_ALL_RADIUS_PX, RotateAllWidget}; + use vectorcraft_tools::objects_on_path::{ROTATE_ALL_RADIUS_PX, Widgets}; if !matches!(tool, "selection" | "objectsOnPath") { return; } - member_widgets(p, xf, doc, selection); - if let Some(w) = RotateAllWidget::of(doc, selection, xf.zoom) { + let widgets = Widgets::of(doc, selection, xf.zoom); + member_widgets(p, xf, doc, &widgets.members); + if let Some(w) = widgets.rotate_all { let (on, c, color) = (xf.to_screen(w.pivot), xf.to_screen(w.at), c32(doc.layer_color(w.group))); p.line_segment([on, c], Stroke::new(1.0, color)); p.circle_filled(c, ROTATE_ALL_RADIUS_PX, Color32::WHITE); p.circle_stroke(c, ROTATE_ALL_RADIUS_PX, Stroke::new(1.0, color)); } - space_widget(p, xf, doc, selection); - move_all_widget(p, xf, doc, selection); + space_widget(p, xf, doc, widgets.space); + move_all_widget(p, xf, doc, widgets.move_all); } /// The Select/Move widgets: a ring on each object's attachment point, filled blue for the chosen /// object. They are drawn under the other widgets, which a press takes first. -fn member_widgets(p: &egui::Painter, xf: &Xf, doc: &vectorcraft_doc::Document, selection: &vectorcraft_doc::Selection) { - use vectorcraft_tools::objects_on_path::{MEMBER_RADIUS_PX, MemberWidget}; - for w in MemberWidget::all(doc, selection, xf.zoom) { +fn member_widgets(p: &egui::Painter, xf: &Xf, doc: &vectorcraft_doc::Document, widgets: &[vectorcraft_tools::objects_on_path::MemberWidget]) { + use vectorcraft_tools::objects_on_path::MEMBER_RADIUS_PX; + for w in widgets { let c = xf.to_screen(w.at); if w.chosen { p.circle(c, MEMBER_RADIUS_PX, MEMBER_CHOSEN, Stroke::new(1.0, Color32::WHITE)); @@ -310,9 +311,9 @@ pub(super) const MEMBER_CHOSEN: Color32 = Color32::from_rgb(0x1f, 0x6f, 0xeb); /// The Space widget (beside the Rotate All widget, with two or more objects on the path): a square /// joined by a line to the last object's attachment point. It stays while dragged. -fn space_widget(p: &egui::Painter, xf: &Xf, doc: &vectorcraft_doc::Document, selection: &vectorcraft_doc::Selection) { - use vectorcraft_tools::objects_on_path::{SPACE_HALF_PX, SpaceWidget}; - let Some(w) = SpaceWidget::of(doc, selection, xf.zoom) else { return }; +fn space_widget(p: &egui::Painter, xf: &Xf, doc: &vectorcraft_doc::Document, w: Option) { + use vectorcraft_tools::objects_on_path::SPACE_HALF_PX; + let Some(w) = w else { return }; let (on, c, color) = (xf.to_screen(w.last), xf.to_screen(w.at), c32(doc.layer_color(w.group))); let r = egui::Rect::from_center_size(c, vec2(2.0 * SPACE_HALF_PX, 2.0 * SPACE_HALF_PX)); p.line_segment([on, c], Stroke::new(1.0, color)); @@ -323,9 +324,9 @@ fn space_widget(p: &egui::Painter, xf: &Xf, doc: &vectorcraft_doc::Document, sel /// The Move All widget (beside the Rotate All widget, when the objects have room to move along the /// path): a diamond below the first object joined by a line to its attachment point. It stays while /// dragged. -fn move_all_widget(p: &egui::Painter, xf: &Xf, doc: &vectorcraft_doc::Document, selection: &vectorcraft_doc::Selection) { - use vectorcraft_tools::objects_on_path::{MOVE_ALL_HALF_PX, MoveAllWidget}; - let Some(w) = MoveAllWidget::of(doc, selection, xf.zoom) else { return }; +fn move_all_widget(p: &egui::Painter, xf: &Xf, doc: &vectorcraft_doc::Document, w: Option) { + use vectorcraft_tools::objects_on_path::MOVE_ALL_HALF_PX; + let Some(w) = w else { return }; let (on, c, color) = (xf.to_screen(w.first), xf.to_screen(w.at), c32(doc.layer_color(w.group))); let h = MOVE_ALL_HALF_PX; p.line_segment([on, c], Stroke::new(1.0, color)); diff --git a/crates/ui-egui/src/canvas/panes.rs b/crates/ui-egui/src/canvas/panes.rs index 76fb599fda..50fd2c9583 100644 --- a/crates/ui-egui/src/canvas/panes.rs +++ b/crates/ui-egui/src/canvas/panes.rs @@ -11,7 +11,7 @@ use super::grid::LineLook; use super::outline::{c32, node_outline, stroke_path, too_many_anchors}; use super::view::fit_zoom; use super::{ - Affine, CacheKey, Point, Rect, RulerScale, Sense, Stroke, StrokeKind, Tokens, Ui, VectorcraftApp, View, Xf, artboard_edges, cache_key, + Affine, CacheKey, Point, Rect, RulerScale, Sense, Stroke, StrokeKind, Tokens, Ui, VectorcraftApp, View, Xf, artboard_edges, backdrop, cache_key, dim_on_canvas, frame_options, frame_view, grid, guides_of, json, paint_paper, pixel_region, placed_key, plugin_key, pos2, rulers, shows_artboards, textured_quad, vec2, view_rects, }; @@ -29,7 +29,7 @@ type Slot = (u64, u32); pub struct Panes { /// Renders off the UI thread (None: on it, as on wasm). worker: Option>, - worker_started: bool, + pub(crate) worker_started: bool, /// Renders on the UI thread when there is no worker. renderer: Option, /// By slot: the render shown and what it shows. @@ -107,17 +107,16 @@ impl Panes { } let current = self.shown.get(&slot).is_some_and(|(k, _)| *k == key) || self.pending.get(&slot) == Some(&key); if !current { + // The document draws through its own assigned profiles, not the front document's, on + // the worker too. + let cms = vectorcraft_engine::cmd::colormgmt::doc_cms(&doc); let mut queued = false; if let Some(worker) = &self.worker { - let (job_doc, job_opts, job_display) = (doc.clone(), opts.clone(), display.clone()); + let (job_doc, job_opts, job_display, job_cms, job_key) = (doc.clone(), opts.clone(), display.clone(), cms.clone(), key.clone()); queued = worker.submit( slot, (slot, key.clone()), - Box::new(move |r| { - let mut img = r.render(&job_doc, w, h, view, &job_opts); - crate::display_profile::convert(job_display.as_deref(), &mut img.pixels); - Some(img) - }), + Box::new(move |r| Some(render_pane(r, (&job_doc, w, h, view, &job_opts), job_display.as_deref(), job_cms, job_key.over()))), ); if queued { self.pending.insert(slot, key.clone()); @@ -126,8 +125,8 @@ impl Panes { } } if !queued { - let mut img = self.renderer.get_or_insert_with(vectorcraft_render::Renderer::new).render(&doc, w, h, view, &opts); - crate::display_profile::convert(display.as_deref(), &mut img.pixels); + let r = self.renderer.get_or_insert_with(vectorcraft_render::Renderer::new); + let img = render_pane(r, (&doc, w, h, view, &opts), display.as_deref(), cms, key.over()); self.upload(ctx, slot, key, &img); } } @@ -146,6 +145,22 @@ impl Panes { } } +/// Render `doc` (`w` × `h` pixels through `view`, with `opts`) through the color settings `cms`, +/// then convert it into the display profile `display`, blended with the backdrop `over` first +/// ([`crate::display_profile::convert_over`]). +fn render_pane( + r: &mut vectorcraft_render::Renderer, + (doc, w, h, view, opts): (&vectorcraft_doc::Document, u32, u32, Affine, &vectorcraft_render::RenderOptions), + display: Option<&vectorcraft_color::cms::display::DisplayTransform>, + cms: Arc, + over: Option<(&crate::display_profile::Backdrop, f64)>, +) -> vectorcraft_render::Rendered { + let mut img = vectorcraft_color::cms::with_active(cms, || r.render(doc, w, h, view, opts)); + let width = img.width; + crate::display_profile::convert_over(display, &mut img.pixels, width, view, over); + img +} + /// The grid of `n` panes in `area`, filled row by row: as many columns as the square root of `n` /// rounded up, and as many rows as those columns need. The panes meet edge to edge and cover /// `area`; the spare cells of the last row stay empty. @@ -294,8 +309,16 @@ fn fit_pane(v: &mut View, doc: &vectorcraft_doc::Document, rect: egui::Rect, ui_ /// art, grid, artboards, guides and selected objects, and its rulers and the room of the canvas's /// scroll bars, so the document stays where it is when the pane becomes the canvas. True when a /// press in the pane asks for its window to become the current one. A floating window draws its -/// view with this too ([`crate::doc_windows`]). +/// view with this too ([`crate::doc_windows`]). The document's colors, its paper and transparency +/// grid included, draw through its own assigned profiles, not the front document's. pub(crate) fn pane(app: &mut VectorcraftApp, ui: &Ui, w: Win, cell: egui::Rect) -> bool { + let Some(st) = app.session.documents().get(w.0) else { return false }; + let cms = vectorcraft_engine::cmd::colormgmt::doc_cms(&st.doc); + vectorcraft_color::cms::with_active(cms, || draw_pane(app, ui, w, cell)) +} + +/// [`pane`], drawn through the color settings in place. +fn draw_pane(app: &mut VectorcraftApp, ui: &Ui, w: Win, cell: egui::Rect) -> bool { let t = Tokens::get(ui.ctx()); let ppp = ui.ctx().pixels_per_point(); let (full, rect) = view_rects(app, cell, ppp); @@ -328,6 +351,7 @@ pub(crate) fn pane(app: &mut VectorcraftApp, ui: &Ui, w: Win, cell: egui::Rect) // The current document's drag and Image Trace hold are not this document's, and this view has // its own Outline or Preview. (key.dragging, key.trace_source, key.outline) = (false, None, v.outline); + key.backdrop = backdrop(app, st, v.outline); let opts = frame_options(app, &key, st.shown_mask(), smooth_images); let (fw, fh, view) = frame_view(pixel, (pw, ph), &drawn, ppp); let doc = st.doc.clone(); diff --git a/crates/ui-egui/src/canvas/panes/tests.rs b/crates/ui-egui/src/canvas/panes/tests.rs index cb1394f612..005b930d01 100644 --- a/crates/ui-egui/src/canvas/panes/tests.rs +++ b/crates/ui-egui/src/canvas/panes/tests.rs @@ -358,3 +358,147 @@ fn a_resized_window_fits_the_tiled_documents_again_unless_one_was_zoomed() { } assert_eq!(app.views[1].zoom, zoomed.zoom, "the zoomed document keeps its zoom"); } + +/// The RGB of the middle pixel of the render that document `i`'s pane uploaded in `out`. +fn pane_middle(app: &VectorcraftApp, out: &egui::FullOutput, i: usize) -> [u8; 3] { + let uid = app.session.documents()[i].uid; + let id = app.canvas.panes.shown.iter().find(|(slot, _)| slot.0 == uid).map(|(_, (_, tex))| tex.id()).unwrap(); + let image = out.textures_delta.set.iter().find(|(t, _)| **t == id).and_then(|(_, d)| d.last()).map(|d| d.image.clone()).unwrap(); + let egui::ImageData::Color(img) = image; + let p = img.pixels[img.size[1] / 2 * img.size[0] + img.size[0] / 2]; + [p.r(), p.g(), p.b()] +} + +#[test] +fn other_panes_draw_through_their_documents_profiles() { + const CHILD: &str = "VECTORCRAFT_TEST_PANE_PROFILES"; + if std::env::var_os(CHILD).is_none() { + // Color settings are process-wide: assign profiles in a separate test process. + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "canvas::panes::tests::other_panes_draw_through_their_documents_profiles", "--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 pane profile test failed:\n{stdout}\n{}", + String::from_utf8_lossy(&output.stderr), + ); + return; + } + use vectorcraft_color::cms::{self, Cms, ColorSettings}; + let mut app = app_with(2); + app.session.prefs.monitor_profile_display = false; + // Each document is covered by one RGB rectangle; the second is assigned Display P3. + for i in 0..2 { + app.run("document.activate", json!({"index": i})).unwrap(); + app.run("shape.rectangle", json!({"x": -50, "y": -50, "width": 500, "height": 400})).unwrap(); + app.run("paint.setFill", json!({"color": "#339966"})).unwrap(); + } + app.run("edit.assignProfile", json!({"rgb": cms::DISPLAY_P3})).unwrap(); + // Its simulated paper shows in another color. + app.run("document.setup", json!({"gridColors": ["#cc6633", "#ffffff"], "simulatePaper": true})).unwrap(); + let in_p3 = |r: u8, g: u8, b: u8| { + let color = vectorcraft_color::Color::Rgb { r: r as f32 / 255.0, g: g as f32 / 255.0, b: b as f32 / 255.0 }; + let p3 = Cms::new(&ColorSettings { rgb: cms::DISPLAY_P3.into(), ..cms::working_settings() }).unwrap().display_rgb(&color); + (color, p3.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8)) + }; + let (color, p3) = in_p3(0x33, 0x99, 0x66); + let srgb = [0x33, 0x99, 0x66]; + assert_ne!(p3, srgb, "Display P3 draws the color differently"); + let (_, paper_p3) = in_p3(0xcc, 0x66, 0x33); + let near = |a: [u8; 3], b: [u8; 3]| a.iter().zip(b).all(|(x, y)| x.abs_diff(y) <= 1); + // Whether `out` fills a shape with the RGB `rgb`, give or take one. + let fills = |out: &egui::FullOutput, rgb: [u8; 3]| { + fn any(s: &Shape, f: &dyn Fn(Color32) -> bool) -> bool { + match s { + Shape::Vec(v) => v.iter().any(|s| any(s, f)), + Shape::Path(p) => f(p.fill), + _ => false, + } + } + out.shapes.iter().any(|c| any(&c.shape, &|c: Color32| c.a() == 255 && near([c.r(), c.g(), c.b()], rgb))) + }; + let ctx = egui::Context::default(); + let raw = || egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(1200.0, 800.0))), + max_texture_side: Some(8192), + ..Default::default() + }; + app.run("window.arrange.tile", json!({})).unwrap(); + // The first document in front: the second one's pane draws through Display P3, its paper too. + app.run("document.activate", json!({"index": 0})).unwrap(); + let mut out = ctx.run_ui(raw(), |ui| app.canvas_area(ui)); + let shown = pane_middle(&app, &out, 1); + assert!(fills(&out, paper_p3), "the back document's paper draws through its Display P3: {paper_p3:?}"); + assert!(!fills(&out, [0xcc, 0x66, 0x33]), "the back document's paper does not draw through the working space"); + out.textures_delta.clear(); + assert!(near(shown, p3), "the back document draws through its Display P3: {shown:?}, not {p3:?}"); + // The same in a floating window. + app.run("window.arrange.consolidateAllWindows", json!({})).unwrap(); + app.run("document.activate", json!({"index": 1})).unwrap(); + app.run("window.arrange.floatInWindow", json!({})).unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + let floating = |app: &mut VectorcraftApp| { + ctx.run_ui(raw(), |ui| { + app.canvas_area(ui); + crate::doc_windows::show(app, ui.ctx()); + }) + }; + // The window takes its place in the first frame and fades in over the next few. + for _ in 0..30 { + floating(&mut app).textures_delta.clear(); + } + app.canvas.panes.clear(); + let mut out = floating(&mut app); + let shown = pane_middle(&app, &out, 1); + assert!(fills(&out, paper_p3), "the floating document's paper draws through its Display P3: {paper_p3:?}"); + out.textures_delta.clear(); + assert!(near(shown, p3), "the floating document draws through its Display P3: {shown:?}, not {p3:?}"); + app.run("window.arrange.consolidateAllWindows", json!({})).unwrap(); + app.run("window.arrange.tile", json!({})).unwrap(); + app.canvas.panes.clear(); + // The second document in front: the first one's pane draws through the working sRGB. + app.run("document.activate", json!({"index": 1})).unwrap(); + let mut out = ctx.run_ui(raw(), |ui| app.canvas_area(ui)); + let shown = pane_middle(&app, &out, 0); + out.textures_delta.clear(); + assert!(near(shown, srgb), "the back document draws through the working space: {shown:?}, not {srgb:?}"); + // The same off the UI thread. + app.canvas.panes.clear(); + app.canvas.panes.worker = crate::thumb_worker::ThumbWorker::start(&ctx, "test-panes"); + app.canvas.panes.worker_started = true; + ctx.run_ui(raw(), |ui| app.canvas_area(ui)).textures_delta.clear(); + let done = app.canvas.panes.worker.as_ref().unwrap().wait().unwrap(); + assert_eq!(done.key.0.0, app.session.documents()[0].uid); + let img = done.img.unwrap(); + let at = ((img.height / 2 * img.width + img.width / 2) * 4) as usize; + let shown = [img.pixels[at], img.pixels[at + 1], img.pixels[at + 2]]; + assert!(near(shown, srgb), "the worker draws the back document through the working space: {shown:?}, not {srgb:?}"); + // A CMYK document behind the front one draws through its own assigned CMYK profile. + app.run("document.activate", json!({"index": 0})).unwrap(); + let steps = json!([ + {"command": "edit.assignProfile", "params": {"cmyk": cms::DEVICE_CMYK}}, + {"command": "file.documentColorMode", "params": {"mode": "cmyk"}}, + ]); + app.run("command.batch", json!({"commands": steps})).unwrap(); + app.run("select.all", json!({})).unwrap(); + app.run("paint.setFill", json!({"color": {"c": 60, "m": 10, "y": 80, "k": 0}})).unwrap(); + app.run("document.activate", json!({"index": 1})).unwrap(); + let ink = vectorcraft_color::Color::cmyk(0.6, 0.1, 0.8, 0.0); + let to_u8 = |c: [f32; 3]| c.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8); + let device = to_u8(Cms::new(&ColorSettings { cmyk: cms::DEVICE_CMYK.into(), ..cms::working_settings() }).unwrap().display_rgb(&ink)); + let front = to_u8(cms::active().display_rgb(&ink)); + let close = |a: [u8; 3], b: [u8; 3]| a.iter().zip(b).all(|(x, y)| x.abs_diff(y) <= 3); + assert!(!close(device, front), "the two CMYK profiles draw the color differently: {device:?}, {front:?}"); + app.canvas.panes.clear(); + ctx.run_ui(raw(), |ui| app.canvas_area(ui)).textures_delta.clear(); + let done = app.canvas.panes.worker.as_ref().unwrap().wait().unwrap(); + assert_eq!(done.key.0.0, app.session.documents()[0].uid); + let img = done.img.unwrap(); + let at = ((img.height / 2 * img.width + img.width / 2) * 4) as usize; + let shown = [img.pixels[at], img.pixels[at + 1], img.pixels[at + 2]]; + assert!(close(shown, device), "the back CMYK document draws through its Device CMYK: {shown:?}, not {device:?} (front: {front:?})"); + assert!(near(cms::active().display_rgb(&color).map(|v| (v * 255.0).round() as u8), p3), "the front document's profile stays active"); +} diff --git a/crates/ui-egui/src/canvas/raster.rs b/crates/ui-egui/src/canvas/raster.rs index f57a15a795..2f9a4f981f 100644 --- a/crates/ui-egui/src/canvas/raster.rs +++ b/crates/ui-egui/src/canvas/raster.rs @@ -226,7 +226,8 @@ pub(crate) fn render_job(r: &mut vectorcraft_render::Renderer, kept: &mut Option *kept = keeps.then(|| KeptFrame { key: job.key.clone(), opts: job.opts.clone(), view: job.view, pixels: holds_pixels.then(|| img.pixels.clone()) }); // The kept frame stays sRGB, so the next frame's copied pixels are converted only once. - crate::display_profile::convert(job.display.as_deref(), &mut img.pixels); + let width = img.width; + crate::display_profile::convert_over(job.display.as_deref(), &mut img.pixels, width, job.view, job.key.over()); WorkerFrame { img, moved, reused } } diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 5ef3789905..19d575b35b 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -2717,6 +2717,140 @@ fn the_canvas_is_drawn_through_the_display_profile_while_the_preference_is_on() assert_eq!(count(&mut app, red), Some(srgb)); } +/// With a display profile, translucent art and the anti-aliased edges of art over the paper are +/// blended with the paper in sRGB before the conversion: drawn over the converted paper, each such +/// pixel shows the converted blend. Opaque art, and art over the pasteboard, convert as before. The +/// part an edit renders again and the render worker's frame do the same, a change of the +/// transparency grid renders the art again, and Outline converts the art alone. +#[test] +fn translucent_art_over_the_paper_is_blended_before_the_display_profile() { + use crate::display_profile::{Found, Reading}; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.ui.task_bar = false; + app.ui.view.rulers = false; + app.canvas.worker_started = true; // every frame on this thread + let half = app.run("shape.rectangle", json!({"x": 100, "y": 50, "width": 200, "height": 200})).unwrap()["id"].clone(); + app.run("paint.setFill", json!({"ids": [half], "color": "#ff0000"})).unwrap(); + app.run("transparency.set", json!({"ids": [half], "opacity": 50})).unwrap(); + let disc = app.run("shape.ellipse", json!({"x": 20, "y": 20, "width": 60, "height": 60})).unwrap()["id"].clone(); + app.run("paint.setFill", json!({"ids": [disc], "color": "#2040c0"})).unwrap(); + // Left of the artboard, over the pasteboard. + let outside = app.run("shape.rectangle", json!({"x": -60, "y": 100, "width": 40, "height": 40})).unwrap()["id"].clone(); + app.run("paint.setFill", json!({"ids": [outside], "color": "#00ff00"})).unwrap(); + app.run("transparency.set", json!({"ids": [outside], "opacity": 50})).unwrap(); + app.run("select.none", json!({})).unwrap(); + let ctx = egui::Context::default(); + // The art's raster one frame uploads: where it goes ([x, y] for a part), its width and its pixels. + let upload = |app: &mut VectorcraftApp| -> Option<(Option<[usize; 2]>, usize, Vec)> { + let (_, mut delta) = frame_output(app, &ctx); + let art = app.canvas.texture.as_ref()?.id(); + let up = delta.set.iter().find(|e| e.0.eq(&art)).and_then(|e| e.1.last()).map(|d| { + let egui::ImageData::Color(img) = &d.image; + (d.pos, img.width(), img.pixels.clone()) + }); + delta.clear(); + up + }; + upload(&mut app).expect("the first frame"); + let v = app.view_mut().unwrap(); + (v.zoom, v.center) = (1.0, Point::new(120.0, 150.0)); + let (_, width, srgb) = upload(&mut app).expect("the view at 100%"); + let key = app.canvas.key.clone().unwrap(); + assert!(key.backdrop.is_none(), "no display profile: nothing to blend"); + let p3 = crate::display_profile::tests::p3(); + let t = vectorcraft_color::cms::display::DisplayTransform::from_icc(&p3).unwrap(); + app.display_profile.report(Reading { display: Some("DP-1".into()), found: Found::Profile { icc: p3, from: "test".into() } }); + let (_, _, shown) = upload(&mut app).expect("drawn again, converted"); + let key = app.canvas.key.clone().unwrap(); + assert!(key.backdrop.is_some()); + let white = t.apply8([255; 3]); + // What the canvas shows of pixel `c` over the converted paper `under`, as egui blends it. + let over = |c: egui::Color32, under: [u8; 3]| { + let k = 255 - u32::from(c.a()); + [0, 1, 2].map(|i| u32::from(c.to_array()[i]) + (u32::from(under[i]) * k + 127) / 255) + }; + let plain = |s: egui::Color32| { + let mut px = s.to_array(); + t.apply_premultiplied(&mut px); + egui::Color32::from_rgba_premultiplied(px[0], px[1], px[2], px[3]) + }; + let (view_w, view_h) = (key.w, key.h); + let (_, _, view) = frame_view( + None, + (view_w, view_h), + &View { zoom: key.zoom, center: Point::new(key.cx, key.cy), rotation: key.rot, ..View::default() }, + key.ppp, + ); + let to_doc = view.inverse(); + let (mut blended, mut beside) = (0, 0); + for (i, (s, c)) in srgb.iter().zip(&shown).enumerate() { + let p = to_doc * Point::new((i % width) as f64 + 0.5, (i / width) as f64 + 0.5); + if s.a() == 0 || s.a() == 255 { + assert_eq!(*c, plain(*s), "opaque and empty pixels convert as before, at {p:?}"); + } else if (1.0..399.0).contains(&p.x) && (1.0..299.0).contains(&p.y) { + let k = 255 - u32::from(s.a()); + let mix = [0, 1, 2].map(|j| (u32::from(s.to_array()[j]) + (255 * k + 127) / 255).min(255) as u8); + let want = t.apply8(mix); + let got = over(*c, white); + assert!((0..3).all(|j| got[j].abs_diff(u32::from(want[j])) <= 1), "at {p:?}: {got:?} shown, {want:?} wanted"); + blended += 1; + } else if p.x < -1.0 { + assert_eq!(*c, plain(*s), "over the pasteboard the art converts alone, at {p:?}"); + beside += 1; + } + } + assert!(blended > 1000 && beside > 500, "{blended} pixels over the paper, {beside} over the pasteboard"); + // The test tells the two apart: the fill converted alone, over the converted paper, shows another color. + let at = view * Point::new(200.0, 150.0); + let at = at.y as usize * width + at.x as usize; + let (s, c) = (srgb[at], shown[at]); + assert!((50..=205).contains(&s.a()), "the 50% fill at the center: {s:?}"); + let alone = over(plain(s), white); + assert!((0..3).any(|j| alone[j].abs_diff(over(c, white)[j]) > 2), "{alone:?} and {:?}", over(c, white)); + // The render worker's frame of the same key is the same. + let opts = app.canvas.shown.as_ref().unwrap().1.clone(); + let doc = app.session.active().unwrap().doc.clone(); + let display = app.display_profile.transform(true); + let job = |key: &CacheKey, doc: &std::sync::Arc| crate::render_worker::Job { + key: key.clone(), + doc: doc.clone(), + w: view_w, + h: view_h, + view, + opts: opts.clone(), + scope: vectorcraft_engine::file_access::ScopeHandle::capture(), + effects: Default::default(), + may_copy: false, + may_keep: false, + display: display.clone(), + }; + let worker = crate::canvas::render_job(&mut vectorcraft_render::Renderer::new(), &mut None, &job(&key, &doc)).img; + let near = |a: &[u8], b: egui::Color32| a.iter().zip(b.to_array()).all(|(x, y)| x.abs_diff(y) <= 1); + assert!(worker.pixels.as_chunks::<4>().0.iter().zip(&shown).all(|(a, b)| near(a, *b)), "the worker's frame matches"); + // An edit renders its part again, blended too. + app.run("paint.setFill", json!({"ids": [half], "color": "#0000ff"})).unwrap(); + let (pos, part_w, part) = upload(&mut app).expect("the edit shows"); + let [x0, y0] = pos.expect("only its part"); + let key = app.canvas.key.clone().unwrap(); + let doc = app.session.active().unwrap().doc.clone(); + let whole = crate::canvas::render_job(&mut vectorcraft_render::Renderer::new(), &mut None, &job(&key, &doc)).img; + let whole = whole.pixels.as_chunks::<4>().0; + for (i, c) in part.iter().enumerate() { + let at = (y0 + i / part_w) * view_w as usize + x0 + i % part_w; + assert!(near(&whole[at], *c), "the part matches the whole frame at {at}: {c:?}, {:?}", whole[at]); + } + assert!(part.iter().filter(|c| c.a() != 0 && c.a() != 255).count() > 1000, "the blue fill is in the part"); + // The transparency grid replaces the paper under the art: drawn again. + app.run("view.transparencyGrid", json!({"on": true})).unwrap(); + assert!(upload(&mut app).is_some_and(|(pos, ..)| pos.is_none()), "the grid renders the art again"); + assert!(app.canvas.key.as_ref().and_then(|k| k.backdrop.as_ref()).is_some_and(|b| b.grid.is_some())); + // Outline: the white canvas is the interface's, so the art converts alone. + app.run("view.outline", json!({})).unwrap(); + upload(&mut app).expect("Outline renders again"); + assert!(app.canvas.key.as_ref().is_some_and(|k| k.outline && k.backdrop.is_none())); +} + /// View › Hide Template (#2000): a template layer's art leaves the canvas, and Show Template /// draws it again, dimmed as before; each re-renders at once. #[test] @@ -5527,6 +5661,74 @@ fn a_pane_draws_its_own_views_outline() { } } +/// With a display profile, a split-view pane or floating window blends translucent art with the +/// paper before the conversion, as the canvas does, and in its own Outline converts the art alone. +#[test] +fn a_pane_blends_translucent_art_before_the_display_profile() { + use crate::display_profile::{Found, Reading}; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let half = app.run("shape.rectangle", json!({"x": 50, "y": 25, "width": 100, "height": 50})).unwrap()["id"].clone(); + app.run("paint.setFill", json!({"ids": [half], "color": "#ff0000"})).unwrap(); + app.run("transparency.set", json!({"ids": [half], "opacity": 50})).unwrap(); + app.run("select.none", json!({})).unwrap(); + crate::doc_windows::new_window(&mut app).unwrap(); + app.canvas.panes.worker_started = true; // every pane render on this thread + let p3 = crate::display_profile::tests::p3(); + let t = vectorcraft_color::cms::display::DisplayTransform::from_icc(&p3).unwrap(); + app.display_profile.report(Reading { display: Some("DP-1".into()), found: Found::Profile { icc: p3, from: "test".into() } }); + let ctx = egui::Context::default(); + let other = (0, 1); + let slot = (app.session.documents()[0].uid, 1); + // The pane's raster one frame uploads, and the key it was rendered for. + let pane = |app: &mut VectorcraftApp| -> (Vec, CacheKey) { + let cell = egui::Rect::from_min_size(pos2(0.0, 0.0), vec2(600.0, 400.0)); + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + panes::pane(app, ui, other, cell); + }); + let (key, tex) = app.canvas.panes.shown.get(&slot).expect("the pane's render"); + let id = tex.id(); + let pixels = out.textures_delta.set.iter().find(|e| e.0.eq(&id)).and_then(|e| e.1.last()).map(|d| { + let egui::ImageData::Color(img) = &d.image; + img.pixels.clone() + }); + let key = key.clone(); + out.textures_delta.clear(); + (pixels.expect("the pane uploads"), key) + }; + app.session.prefs.monitor_profile_display = false; + let (srgb, key) = pane(&mut app); + assert!(key.backdrop.is_none(), "no display profile: nothing to blend"); + app.session.prefs.monitor_profile_display = true; + let (shown, key) = pane(&mut app); + assert!(key.backdrop.is_some(), "the pane's Preview blends with its paper"); + assert_eq!(srgb.len(), shown.len()); + let plain = |s: egui::Color32| { + let mut px = s.to_array(); + t.apply_premultiplied(&mut px); + egui::Color32::from_rgba_premultiplied(px[0], px[1], px[2], px[3]) + }; + let mut blended = 0; + for (s, c) in srgb.iter().zip(&shown) { + if s.a() == 0 || s.a() == 255 { + assert_eq!(*c, plain(*s), "opaque and empty pixels convert as before"); + } else { + assert_eq!(c.a(), s.a(), "the alpha is kept"); + let p = plain(*s); + if (0..3).any(|j| c.to_array()[j].abs_diff(p.to_array()[j]) > 2) { + blended += 1; + } + } + } + assert!(blended > 100, "{blended} translucent pixels blended with the paper"); + // The pane's own Outline: the art converts alone, while the current view stays in Preview. + crate::doc_windows::view_mut(&mut app, other).unwrap().outline = true; + app.view_mut().unwrap().outline = false; + let (_, key) = pane(&mut app); + assert!(key.outline && key.backdrop.is_none(), "the pane's Outline has no paper to blend with"); +} + /// While the rulers' origin is dragged out of their corner, its crosshair draws over the canvas in /// the theme's dim text color in Preview, and in Outline in the dark gray that shows on the white /// canvas. @@ -5831,8 +6033,12 @@ fn show_hidden_characters_lays_out_only_type_that_changed() { let same = |a: &std::sync::Arc, b: &std::sync::Arc| std::sync::Arc::ptr_eq(a, b); let (before, after) = frames(&mut app, &|_| {}); assert!(before.iter().zip(&after).all(|(a, b)| same(a, b)), "a frame lays out no type"); + // Each attempt sets different text: text the object already has is no edit, and a second + // attempt with the same text would leave the object as it was. + let edits = std::cell::Cell::new(0); let (before, after) = frames(&mut app, &|app| { - app.session.execute("text.setText", &json!({"id": ids[1].0, "text": "a b c"})).unwrap(); + edits.set(edits.get() + 1); + app.session.execute("text.setText", &json!({"id": ids[1].0, "text": format!("a b c {}", edits.get())})).unwrap(); }); assert!(!same(&before[1], &after[1]), "the edited object is laid out again"); assert!(same(&before[0], &after[0]) && same(&before[2], &after[2]), "the others are not"); @@ -7416,6 +7622,73 @@ fn space_types_a_space_while_editing_text_and_does_not_pan() { assert_eq!(plain(&app, id), "a ", "the text is as typed"); } +/// While the Type tool edits text, a zoom marquee that Cmd+Space started keeps its Space rules once +/// Cmd is let go: Space held since the press sizes it, and Space pressed again moves it on every +/// frame it stays held, without typing a space. With no marquee, Space types a space again, and +/// during an animated zoom drag it types none. +#[test] +fn space_moves_a_text_edit_zoom_marquee_after_cmd_is_let_go() { + use egui::{Event, Modifiers}; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.prefs.placeholder_text = false; + app.run("prefs.set", json!({"key": "animatedZoom", "value": false})).unwrap(); + let ctx = egui::Context::default(); + let id = start_typing(&mut app, &ctx); + let rect = app.canvas_rect.unwrap(); + let at = rect.center() - vec2(100.0, 50.0); + let space = |pressed, modifiers| Event::Key { key: egui::Key::Space, physical_key: None, pressed, repeat: false, modifiers }; + let button = |pos, pressed, modifiers| Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers }; + let corners = |app: &mut VectorcraftApp| -> (Pos2, Pos2) { + let lines: Vec> = shapes(app, &ctx) + .into_iter() + .filter_map(|s| match s { + Shape::Path(p) if p.stroke.color == egui::epaint::ColorMode::Solid(Color32::from_white_alpha(230)) => Some(p.points), + _ => None, + }) + .collect(); + let [line] = &lines[..] else { panic!("one marquee: {lines:?}") }; + (line[0], line[2]) + }; + typing_frame(&mut app, &ctx, vec![Event::Text("a".into())]); + let z0 = app.view().unwrap().zoom; + // Space held since the Cmd+Space press sizes the marquee, also once Cmd is let go. + typing_frame(&mut app, &ctx, vec![Event::ModifiersChanged(Modifiers::COMMAND), space(true, Modifiers::COMMAND), Event::PointerMoved(at)]); + typing_frame(&mut app, &ctx, vec![button(at, true, Modifiers::COMMAND)]); + typing_frame(&mut app, &ctx, vec![Event::PointerMoved(at + vec2(50.0, 25.0))]); + typing_frame(&mut app, &ctx, vec![Event::ModifiersChanged(Modifiers::NONE), Event::PointerMoved(at + vec2(80.0, 40.0))]); + typing_frame(&mut app, &ctx, vec![Event::PointerMoved(at + vec2(100.0, 50.0))]); + assert_eq!(corners(&mut app), (at, at + vec2(100.0, 50.0)), "Space held since the press sizes it"); + // Let go and pressed again, Space moves the marquee on this frame and the frames after it. + typing_frame(&mut app, &ctx, vec![space(false, Modifiers::NONE)]); + typing_frame(&mut app, &ctx, vec![space(true, Modifiers::NONE), Event::Text(" ".into()), Event::PointerMoved(at + vec2(120.0, 60.0))]); + typing_frame(&mut app, &ctx, vec![Event::PointerMoved(at + vec2(140.0, 70.0))]); + assert_eq!(corners(&mut app), (at + vec2(40.0, 20.0), at + vec2(140.0, 70.0)), "Space moves it and keeps its 100 × 50 size"); + assert_eq!(plain(&app, id), "a", "the Space that moves the marquee types nothing"); + typing_frame(&mut app, &ctx, vec![space(false, Modifiers::NONE)]); + typing_frame(&mut app, &ctx, vec![space(true, Modifiers::NONE), Event::Ime(egui::ImeEvent::Commit(" ".into()))]); + assert_eq!(plain(&app, id), "a", "nor does a space an input method commits for it"); + // Let go, the drag sizes it again, and the release zooms to the moved marquee. + typing_frame(&mut app, &ctx, vec![space(false, Modifiers::NONE), Event::PointerMoved(at + vec2(180.0, 95.0))]); + assert_eq!(corners(&mut app), (at + vec2(40.0, 20.0), at + vec2(180.0, 95.0)), "let go, the drag sizes it again"); + typing_frame(&mut app, &ctx, vec![button(at + vec2(180.0, 95.0), false, Modifiers::NONE)]); + let want = z0 * f64::from((rect.width() / 140.0).min(rect.height() / 75.0)); + assert!((app.view().unwrap().zoom - want).abs() < 1e-6, "{z0} → {}, not {want}", app.view().unwrap().zoom); + assert!(app.session.tool_wants_text(), "editing goes on"); + // With no marquee, Space types a space. + typing_frame(&mut app, &ctx, vec![space(true, Modifiers::NONE), Event::Text(" ".into())]); + typing_frame(&mut app, &ctx, vec![space(false, Modifiers::NONE)]); + assert_eq!(plain(&app, id), "a ", "Space types a space"); + // With Animated Zoom, Space during the Cmd+Space drag does not type a space either. + app.run("prefs.set", json!({"key": "animatedZoom", "value": true})).unwrap(); + typing_frame(&mut app, &ctx, vec![Event::ModifiersChanged(Modifiers::COMMAND), space(true, Modifiers::COMMAND), Event::PointerMoved(at)]); + typing_frame(&mut app, &ctx, vec![button(at, true, Modifiers::COMMAND)]); + typing_frame(&mut app, &ctx, vec![Event::ModifiersChanged(Modifiers::NONE), space(false, Modifiers::NONE)]); + typing_frame(&mut app, &ctx, vec![space(true, Modifiers::NONE), Event::Text(" ".into())]); + typing_frame(&mut app, &ctx, vec![button(at, false, Modifiers::NONE)]); + typing_frame(&mut app, &ctx, vec![space(false, Modifiers::NONE)]); + assert_eq!(plain(&app, id), "a ", "the text is as typed"); +} + #[test] fn space_shift_drag_rotates_the_view_whatever_the_tool() { use egui::{Event, Modifiers}; diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 2779bc7f6d..a2c29fadc4 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -9,7 +9,7 @@ //! - `ui.menu.list`: flattened menu tree //! - `ui.contextMenu.list`: the canvas context menu for the current selection, flattened //! - `ui.tool.select {tool}`, `ui.tool.list` -//! - `ui.pointer {events:[{kind: down|drag|up|move|doubleclick, x, y, backquote?, space?: "doc"|"screen"}], mods?, backquote?}`: +//! - `ui.pointer {events:[{kind: down|drag|up|move|doubleclick|tripleclick, x, y, backquote?, space?: "doc"|"screen"}], mods?, backquote?}`: //! drive the active tool through the same path as the mouse, after the synthetic input sent //! before it was applied //! - `ui.key {key, shift?, alt?, cmd?}` / `ui.text {text}`: synthetic keyboard input @@ -41,6 +41,7 @@ use std::sync::atomic::{AtomicU8, AtomicU64, Ordering}; use std::sync::mpsc::Sender; use serde_json::{Value, json}; +use vectorcraft_engine::cmd::ParamsPlace; use vectorcraft_render::encode::{RasterExportOptions, RasterFormat}; use vectorcraft_tools::{Mods, PointerEvent, PointerKind}; @@ -427,17 +428,19 @@ impl Hiding { } /// The paths outside the read roots that `v`'s strings and keys name at any depth, written as paths -/// ([`unreadable_path_like`]) or held by a path param -/// ([`vectorcraft_engine::file_access::is_path_key`]), a relative one too, each as a hidden library id -/// (`loaded/`) with `loaded/` shown. A reply hides them as it hides a hidden library's -/// path, with that file name also for a hidden library shown as `loaded/ (2)`, so that it -/// reads the same whether or not a library was loaded from one of them. +/// ([`unreadable_path_like`]) or held by a path param, a relative one too, each as a hidden library id +/// (`loaded/`) with `loaded/` shown. A param is a path param as the command it is +/// for reads it ([`ParamsPlace`]: `engine.execute`'s `params`, a `command.batch` step's and a +/// recorded step's), so a web link or an export's folder grouping is not one. A reply hides them as +/// it hides a hidden library's path, with that file name also for a hidden library shown as +/// `loaded/ (2)`, so that it reads the same whether or not a library was loaded from one +/// of them. fn sent_paths(v: &Value, out: &mut Vec<(String, String)>) { - collect_sent_paths(v, false, out); + collect_sent_paths(v, ParamsPlace::top(None), false, out); } -/// [`sent_paths`] on `v`, which a path param holds when `path_param` is set. -fn collect_sent_paths(v: &Value, path_param: bool, out: &mut Vec<(String, String)>) { +/// [`sent_paths`] on `v`, found at `place`, which a path param holds when `path_param` is set. +fn collect_sent_paths(v: &Value, place: ParamsPlace, path_param: bool, out: &mut Vec<(String, String)>) { fn add(s: &str, path_param: bool, out: &mut Vec<(String, String)>) { if !unreadable_path_like(s) && !(path_param && !readable_value(s)) { return; @@ -459,11 +462,18 @@ fn collect_sent_paths(v: &Value, path_param: bool, out: &mut Vec<(String, String } match v { Value::String(s) => add(s, path_param, out), - Value::Array(items) => items.iter().for_each(|item| collect_sent_paths(item, path_param, out)), + Value::Array(items) => { + let step = ParamsPlace::step(items); + for (i, item) in items.iter().enumerate() { + collect_sent_paths(item, place.item(i, step), path_param, out); + } + } Value::Object(fields) => { + let carried = ParamsPlace::carried(fields); for (key, item) in fields { add(key, false, out); - collect_sent_paths(item, vectorcraft_engine::file_access::is_path_key(key), out); + let (below, location) = place.member(key, carried); + collect_sent_paths(item, below, location.is_some(), out); } } _ => {} @@ -1057,7 +1067,7 @@ fn steps_mut(set: &mut Value) -> impl Iterator) { leave_out_unreadable_pref_steps(command, params); - leave_out_unreadable_params(params); + leave_out_unreadable_params(params, ParamsPlace::of(command)); } /// Takes out of the params of a step running `command` the folder preferences' values the request @@ -1087,39 +1097,46 @@ fn leave_out_unreadable_pref_steps(command: &str, params: &mut serde_json::Map) { - use vectorcraft_engine::file_access::is_path_key; +/// Takes out of a recorded step's params at `place`, at any depth (the commands of a `command.batch` +/// step), the paths the request may not read: the value of a path param as the command reads it +/// ([`ParamsPlace`]: `path`, `file`, `diffPath`, `destinationFolder` and the like, but not a key that +/// names part of the document in that command), each path of a list under such a param, and under +/// any other param, as a key too, a string written as a path ([`unreadable_path_like`]). A web link, +/// a choice or a switch whose name ends like a path param's (`alignToPath`, `linksFolder`) stays, and +/// so does an empty or blank value, which names no path. +fn leave_out_unreadable_params(params: &mut serde_json::Map, place: ParamsPlace) { let shown = |p: &str| p.trim().is_empty() || readable_value(p); + let carried = ParamsPlace::carried(params); params.retain(|key, v| { !unreadable_path_like(key) && match v.as_str() { - Some(p) => !unreadable_path_like(p) && !(is_path_key(key) && !shown(p)), + Some(p) => !unreadable_path_like(p) && !(place.member(key, carried).1.is_some() && !shown(p)), None => true, } }); + let carried = ParamsPlace::carried(params); for (key, v) in params.iter_mut() { + let (below, location) = place.member(key, carried); if let Value::Array(paths) = v - && is_path_key(key) + && location.is_some() { paths.retain(|p| p.as_str().is_none_or(shown)); } - leave_out_unreadable_values(v); + leave_out_unreadable_values(v, below); } } -/// [`leave_out_unreadable_params`] on each object `v` holds, and a string written as a path that the -/// request may not read ([`unreadable_path_like`]) taken out of each list. -fn leave_out_unreadable_values(v: &mut Value) { +/// [`leave_out_unreadable_params`] on each object `v`, found at `place`, holds, and a string written +/// as a path that the request may not read ([`unreadable_path_like`]) taken out of each list. +fn leave_out_unreadable_values(v: &mut Value, place: ParamsPlace) { match v { - Value::Object(fields) => leave_out_unreadable_params(fields), + Value::Object(fields) => leave_out_unreadable_params(fields, place), Value::Array(items) => { items.retain(|item| !item.as_str().is_some_and(unreadable_path_like)); - items.iter_mut().for_each(leave_out_unreadable_values); + let step = ParamsPlace::step(items); + for (i, item) in items.iter_mut().enumerate() { + leave_out_unreadable_values(item, place.item(i, step)); + } } _ => {} } @@ -1274,7 +1291,9 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlReques /// Hides in `reply` the libraries hidden now and in `before`, and the paths outside the read root that /// `sent`, the request's params, holds ([`handle`]), and the recovery folders outside the read root -/// that are in use or that a failure message named. The `path` and `files` entries of the reply's +/// that are in use or that a failure message named, with each folder on the way to one that the reply +/// writes as a whole path ([`writes_whole_path`]): a failure names a file or a missing folder there. +/// The `path` and `files` entries of the reply's /// `result`, at any depth, that name a file the request gave inside the write roots, the file it /// wrote, stay as given ([`written_paths`]). fn hide_in_reply(app: &VectorcraftApp, reply: &mut Value, sent: &Value, before: Hiding) { @@ -1282,32 +1301,66 @@ fn hide_in_reply(app: &VectorcraftApp, reply: &mut Value, sent: &Value, before: return; } let mut given = Vec::new(); - written_paths(sent, false, &mut given); + written_paths(sent, ParamsPlace::top(None), false, &mut given); let kept = kept_written_paths(reply, &given); let mut hiding = unreadable_library_ids(app); hiding.merge(before); let mut paths = Vec::new(); sent_paths(sent, &mut paths); - // The status text of a recovery copy that failed names the recovery folder it went to. + // The status text of a recovery copy that failed names the recovery folder it went to, or the + // first folder on the way to it that is a file or is missing. let current = vectorcraft_engine::cmd::recovery::folder(&app.session).map(|(f, _)| f); for folder in app.recovery.named.iter().chain(current.as_ref()) { - collect_sent_paths(&json!(folder), true, &mut paths); + collect_sent_paths(&json!(folder), ParamsPlace::top(None), true, &mut paths); + for on_the_way in std::path::Path::new(folder).ancestors().skip(1).map(|p| p.to_string_lossy()) { + if !on_the_way.is_empty() && writes_whole_path(reply, &on_the_way) { + collect_sent_paths(&json!(on_the_way), ParamsPlace::top(None), true, &mut paths); + } + } } hiding.set_hidden(paths, cfg!(windows)); hide_library_ids(reply, &hiding); restore_written_paths(reply, kept); } -/// The strings that `v`'s path params hold at any depth ([`vectorcraft_engine::file_access::is_path_key`]) -/// that name a file inside the write roots; `v` is a path param's value when `path_param` is set. -fn written_paths(v: &Value, path_param: bool, out: &mut Vec) { - use vectorcraft_engine::file_access::{Access, current, is_path_key}; +/// Does `v` write `path` in a string or a key at any depth with no path text before it (a letter, a +/// digit, `_`, `-`, `.`, `~` or a separator) or after it ([`continues_path`]), a Windows path +/// ([`splits_at_backslash`]) with either separator and in any case of ASCII letters too? Only the text +/// is compared: nothing on disk is looked up. +fn writes_whole_path(v: &Value, path: &str) -> bool { + let windows = splits_at_backslash(path); + let path_before = + |before: &str| before.chars().next_back().is_some_and(|c| c.is_alphanumeric() || matches!(c, '_' | '-' | '.' | '~' | '/' | '\\')); + let whole = |s: &str| { + let spellings = if windows { vec![path.replace('\\', "/"), path.replace('/', "\\")] } else { vec![path.to_string()] }; + spellings.iter().any(|p| occurrences(s, p, windows).into_iter().any(|at| !path_before(&s[..at]) && !continues_path(&s[at + p.len()..]))) + }; + match v { + Value::String(s) => whole(s), + Value::Array(items) => items.iter().any(|item| writes_whole_path(item, path)), + Value::Object(fields) => fields.iter().any(|(key, item)| whole(key) || writes_whole_path(item, path)), + _ => false, + } +} + +/// The strings that `v`'s path params hold at any depth, as the command they are for reads them +/// ([`ParamsPlace`]), that name a file inside the write roots; `v`, found at `place`, is a path +/// param's value when `path_param` is set. +fn written_paths(v: &Value, place: ParamsPlace, path_param: bool, out: &mut Vec) { + use vectorcraft_engine::file_access::{Access, current}; match v { Value::String(s) if path_param && !s.is_empty() && current().is_some_and(|r| r.check(s, Access::Write).is_ok()) => out.push(s.clone()), - Value::Array(items) => items.iter().for_each(|item| written_paths(item, path_param, out)), + Value::Array(items) => { + let step = ParamsPlace::step(items); + for (i, item) in items.iter().enumerate() { + written_paths(item, place.item(i, step), path_param, out); + } + } Value::Object(fields) => { + let carried = ParamsPlace::carried(fields); for (key, item) in fields { - written_paths(item, is_path_key(key), out); + let (below, location) = place.member(key, carried); + written_paths(item, below, location.is_some(), out); } } _ => {} @@ -1842,7 +1895,7 @@ fn rotate_view_pointer( PointerKind::Up => { app.control_rotate_press = None; } - PointerKind::Move | PointerKind::DoubleClick => {} + PointerKind::Move | PointerKind::DoubleClick | PointerKind::TripleClick => {} } Ok(()) } @@ -1910,6 +1963,7 @@ fn pointer_events_inner(app: &mut VectorcraftApp, ctx: &egui::Context, req: &Con "up" => PointerKind::Up, "move" => PointerKind::Move, "doubleclick" | "dblclick" => PointerKind::DoubleClick, + "tripleclick" => PointerKind::TripleClick, other => return Err(format!("unknown pointer kind `{other}`")), }; PointerEvent::json_check(e)?; diff --git a/crates/ui-egui/src/control/tests.rs b/crates/ui-egui/src/control/tests.rs index b60b1adfdc..7aa73e8a7e 100644 --- a/crates/ui-egui/src/control/tests.rs +++ b/crates/ui-egui/src/control/tests.rs @@ -306,7 +306,7 @@ fn a_spaced_absolute_path_outside_the_read_root_is_left_out() { assert!(super::unreadable_path_like(" /outside/root/x")); assert!(super::unreadable_path_like("\tfile:///outside/root/x ")); assert!(!super::unreadable_path_like(&inside), "{inside}"); - super::leave_out_unreadable_params(params.as_object_mut().unwrap()); + super::leave_out_unreadable_params(params.as_object_mut().unwrap(), vectorcraft_engine::cmd::ParamsPlace::top(None)); }); assert_eq!(params, json!({"keep": inside, "list": []})); } @@ -337,10 +337,74 @@ fn a_url_naming_another_host_stays_without_a_read_root() { assert!(super::readable_value("file://host/share/a.svg")); let mut params = json!({"path": "file://host/share/a.svg", "list": ["file://host/share/b.svg"]}); let fields = params.as_object_mut().unwrap(); - super::leave_out_unreadable_params(fields); + super::leave_out_unreadable_params(fields, vectorcraft_engine::cmd::ParamsPlace::top(None)); assert_eq!(params, json!({"path": "file://host/share/a.svg", "list": ["file://host/share/b.svg"]})); } +/// Under a read root, a recorded step loses a relative path outside it under a key that names a file +/// or a folder as its command reads it (also inside a `command.batch` step), and a `file:` URL outside +/// it under any key. A web link, a choice or a switch whose name ends like a path key's, and a key +/// that names part of the document in its command, keep their values; the same key in a command that +/// doesn't take it as a param names a file. +#[test] +fn recorded_steps_filter_only_unreadable_locations() { + use vectorcraft_engine::cmd::ParamsPlace; + let root = std::env::temp_dir().join(format!("vc-recorded-locations-{}", std::process::id())); + std::fs::create_dir_all(&root).unwrap(); + let roots = vectorcraft_engine::file_access::AutomationRoots::new(&[&root], &[]).unwrap(); + let steps = [ + ("document.compare", json!({"diffPath": "elsewhere/a.svg", "directory": "elsewhere", "keep": 1})), + ("attributes.set", json!({"url": "https://example.com/elsewhere/a.html", "note": "kept"})), + ("object.slice.options", json!({"url": "file:///elsewhere/a.html"})), + ("object.path.simplify", json!({"wholePaths": "elsewhere/a", "alignToPath": "elsewhere/b", "linksFolder": "elsewhere/c"})), + ("document.exportPresets.save", json!({"settings": {"folders": "item/format", "formats": [{"folder": "elsewhere/png"}]}})), + ("text.createInPath", json!({"path": "elsewhere/shape"})), + ("object.setLiveShape", json!({"path": "elsewhere/shape"})), + ("command.batch", json!({"commands": [{"command": "document.save", "params": {"path": "elsewhere/b.svg"}}]})), + ]; + let filtered: Vec = vectorcraft_engine::file_access::confine(roots.as_ref(), || { + steps + .iter() + .map(|(id, params)| { + let mut params = params.clone(); + super::leave_out_unreadable_params(params.as_object_mut().unwrap(), ParamsPlace::of(id)); + params + }) + .collect() + }); + let _ = std::fs::remove_dir_all(root); + let want = [ + json!({"keep": 1}), + json!({"url": "https://example.com/elsewhere/a.html", "note": "kept"}), + json!({}), + json!({"wholePaths": "elsewhere/a", "alignToPath": "elsewhere/b", "linksFolder": "elsewhere/c"}), + json!({"settings": {"folders": "item/format", "formats": [{}]}}), + json!({"path": "elsewhere/shape"}), + json!({}), + json!({"commands": [{"command": "document.save", "params": {}}]}), + ]; + assert_eq!(filtered, want); +} + +/// A request's relative path outside the read root is hidden in a reply where the command it calls +/// reads it as a file, and a web link or a key that names part of the document there is not. +#[test] +fn a_request_sends_paths_as_its_command_reads_them() { + let root = std::env::temp_dir().join(format!("vc-sent-command-paths-{}", std::process::id())); + std::fs::create_dir_all(&root).unwrap(); + let roots = vectorcraft_engine::file_access::AutomationRoots::new(&[&root], &[]).unwrap(); + let mut sent = Vec::new(); + vectorcraft_engine::file_access::confine(roots.as_ref(), || { + super::sent_paths(&json!({"command": "attributes.set", "params": {"url": "https://example.com/a/page.html"}}), &mut sent); + super::sent_paths(&json!({"command": "object.path.simplify", "params": {"wholePaths": "out/w.svg"}}), &mut sent); + super::sent_paths(&json!({"command": "document.compare", "params": {"diffPath": "out/d.svg"}}), &mut sent); + super::sent_paths(&json!({"command": "file.place", "params": {"directory": "out/folder"}}), &mut sent); + }); + let _ = std::fs::remove_dir_all(root); + let pair = |path: &str, name: &str| (format!("loaded/{path}"), format!("loaded/{name}")); + assert_eq!(sent, [pair("out/d.svg", "d.svg"), pair("out/folder", "folder")]); +} + /// A hidden path quoted with `{:?}` is hidden with its quotes and control characters escaped. #[test] fn a_reply_hides_a_quoted_path_with_escaped_quotes() { @@ -474,6 +538,36 @@ fn a_recovery_folder_outside_the_read_root_is_hidden_in_the_status() { assert_eq!(inspect(&mut app, format!("Copies go to {inside}")), json!(format!("Copies go to {inside}"))); } +/// `ui.inspect` shows a file on the way to a recovery folder outside the read root, which a failed +/// recovery copy names, by its name, and a missing folder on the way too. A path that only begins or +/// only ends with a folder on the way stays. +#[test] +fn a_file_on_the_way_to_a_recovery_folder_outside_the_read_root_is_hidden_in_the_status() { + let mut app = VectorcraftApp::new(Session::new(), Services::default()); + let outside = crate::tests_folder::Folder::new("recovery-in-the-way"); + let file = outside.file("private", b"a file"); + let folder = std::path::Path::new(&file).join("recovery").to_string_lossy().into_owned(); + app.session.recovery.set_default_folder(Some(folder)); + let root = crate::tests_folder::Folder::new("recovery-in-the-way-root"); + let roots = vectorcraft_engine::file_access::AutomationRoots::new(&[root.as_path()], &[]).unwrap(); + let inspect = |app: &mut VectorcraftApp, status: String| { + app.ui.status = status; + let reply = vectorcraft_engine::file_access::confine(roots.as_ref(), || input_request(app, "ui.inspect", json!({}))); + reply["result"]["ui"]["status"].clone() + }; + let status = format!("Couldn't save recovery data: {file} is not a folder"); + assert_eq!(inspect(&mut app, status), "Couldn't save recovery data: private is not a folder"); + let missing = outside.join("gone"); + let folder = missing.join("recovery").to_string_lossy().into_owned(); + app.session.recovery.set_default_folder(Some(folder)); + let status = format!("Couldn't save recovery data: couldn't make {}", missing.display()); + assert_eq!(inspect(&mut app, status), "Couldn't save recovery data: couldn't make gone"); + let under = format!("Copies go near {}", outside.join("other.svg").display()); + assert_eq!(inspect(&mut app, under.clone()), json!(under)); + let longer = format!("Copies go near /work{}", missing.display()); + assert_eq!(inspect(&mut app, longer.clone()), json!(longer)); +} + /// A path outside the read root that a request sent is shown by its file name in a reply that succeeded /// as in one that failed. #[test] diff --git a/crates/ui-egui/src/cursors.rs b/crates/ui-egui/src/cursors.rs index a438a71881..5495d3753c 100644 --- a/crates/ui-egui/src/cursors.rs +++ b/crates/ui-egui/src/cursors.rs @@ -677,18 +677,16 @@ fn glyph(c: Cursor, p: Pos2) -> Option> { ink.circle_stroke(p + vec2(8.0, 8.0), 3.0, Stroke::new(3.0, HALO)); ink.circle_stroke(p + vec2(8.0, 8.0), 3.0, Stroke::new(1.2, INK)); } - // The Pencil's crosshair with a short straight line where the closing ring goes. + // The Pencil's crosshair with a short level line where the closing ring goes. Cursor::PencilStraight => { crosshair(ink, p); - line(ink, p + vec2(5.0, 12.0), p + vec2(12.0, 5.0)); + line(ink, p + vec2(3.55, 8.5), p + vec2(13.45, 8.5)); } - // The straight-line cursor's line leaving a filled square: the end point a line continues from. + // The Pencil's crosshair with a short line rising to the right where the closing ring goes: + // the stroke carries on from the path. Cursor::PencilContinue => { crosshair(ink, p); - // The square first, so its halo does not cover the line. - let end = p + vec2(5.0, 12.0); - poly(ink, [(-2.0, -2.0), (2.0, -2.0), (2.0, 2.0), (-2.0, 2.0)].map(|(x, y)| end + vec2(x, y)).to_vec(), INK, INK); - line(ink, end, p + vec2(12.0, 5.0)); + line(ink, p + vec2(5.0, 12.0), p + vec2(12.0, 5.0)); } Cursor::Eyedropper => eyedropper(ink, p), Cursor::ResizeH => double_arrow(ink, p, vec2(1.0, 0.0)), diff --git a/crates/ui-egui/src/cursors/tests.rs b/crates/ui-egui/src/cursors/tests.rs index ae1947616f..49c932175d 100644 --- a/crates/ui-egui/src/cursors/tests.rs +++ b/crates/ui-egui/src/cursors/tests.rs @@ -244,7 +244,7 @@ fn the_pencil_new_path_cursor_is_the_crosshair_with_a_star() { } } -/// The Pencil's straight-line cursor is the crosshair with a short straight line below right, +/// The Pencil's straight-line cursor is the crosshair with a short level line below right, /// through the point where the closing cursor's ring is hollow. #[test] fn the_pencil_straight_line_cursor_is_the_crosshair_with_a_line() { @@ -264,15 +264,18 @@ fn the_pencil_straight_line_cursor_is_the_crosshair_with_a_line() { assert_eq!(at(&cross, 8.5, 8.5)[3], 0, "the crosshair has no badge at {ppp}"); // Along the line, not across it: no ink off its ends. assert!(!inked(at(&img, 5.0, 5.0)) && !inked(at(&img, 12.0, 12.0)), "a line, not a cross, at {ppp}"); + // Level: inked at both ends of it, and not where the continuation cursor's line rises. + assert!(inked(at(&img, 4.5, 8.5)) && inked(at(&img, 12.5, 8.5)), "a level line at {ppp}"); + assert!(!inked(at(&img, 6.0, 11.0)) && !inked(at(&img, 11.0, 6.0)), "not a rising one at {ppp}"); assert_ne!(img, ring, "at {ppp}"); assert_eq!(at(&img, -6.0, 0.0), at(&cross, -6.0, 0.0), "the arms are the crosshair's at {ppp}"); } } -/// The Pencil's continuation cursor is the straight-line cursor with a filled square on the -/// line's lower end, beside the line where the straight-line cursor has no ink. +/// The Pencil's continuation cursor is the crosshair with a short line rising to the right below +/// right, where the straight-line cursor's line is level. #[test] -fn the_pencil_continuation_cursor_is_the_straight_line_cursor_with_an_end_point() { +fn the_pencil_continuation_cursor_is_the_crosshair_with_a_rising_line() { for ppp in [1.0, 2.0] { let cross = rasterize(Cursor::Crosshair, ppp).unwrap(); let img = rasterize(Cursor::PencilContinue, ppp).unwrap(); @@ -285,8 +288,10 @@ fn the_pencil_continuation_cursor_is_the_straight_line_cursor_with_an_end_point( }; let inked = |p: [u8; 4]| p[3] > 200 && p[0] < 64; assert!(inked(at(&img, 8.5, 8.5)), "the line crosses the badge's middle at {ppp}"); - assert!(inked(at(&img, 3.5, 13.5)), "the end point's square at {ppp}"); - assert!(!inked(at(&straight, 3.5, 13.5)), "the straight-line cursor has no end point at {ppp}"); + assert!(inked(at(&img, 5.0, 11.0)) && inked(at(&img, 10.0, 6.0)), "the line rises to the right at {ppp}"); + assert!(!inked(at(&straight, 6.0, 11.0)), "the straight-line cursor's line is level at {ppp}"); + assert!(!inked(at(&img, 4.5, 8.5)) && !inked(at(&img, 12.5, 8.5)), "not a level one at {ppp}"); + assert!(!inked(at(&img, 3.5, 13.5)), "no end point square at {ppp}"); assert!(!inked(at(&img, 12.0, 12.0)), "a line, not a cross, at {ppp}"); assert_eq!(at(&img, -6.0, 0.0), at(&cross, -6.0, 0.0), "the arms are the crosshair's at {ppp}"); } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 5afad21b0d..4ac6da2fbe 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -122,6 +122,7 @@ pub(crate) mod shapes; pub mod shortcut_import; pub(crate) mod simplify_slider; pub mod slices; +pub mod smart_punctuation; pub(crate) mod smooth_slider; pub mod spot_colors; pub mod svg_filter; @@ -157,9 +158,10 @@ pub use export_as::{export_selection, open as open_export_as}; pub(crate) use export_for_screens::drop_unread_screen_settings; pub use export_for_screens::open as open_export_for_screens; pub(crate) use export_for_screens::{ - KIND as EXPORT_FOR_SCREENS, PresetPick as ScreenPresetPick, export_preset as screen_export_preset, formats as screen_formats, - import_presets as screen_import_presets, open_assets as open_export_for_screens_assets, preset_list as screen_preset_list, - saved_options as screen_saved_options, saved_rows as screen_saved_rows, + KIND as EXPORT_FOR_SCREENS, PresetPick as ScreenPresetPick, artboard_name_editing as export_artboard_name_editing, + export_preset as screen_export_preset, formats as screen_formats, import_presets as screen_import_presets, + open_assets as open_export_for_screens_assets, preset_list as screen_preset_list, saved_options as screen_saved_options, + saved_rows as screen_saved_rows, settings_format as screen_settings_format, }; pub(crate) use form::{humanize, number_list_text, plugin_color_button, read_number_list, unit_suffix}; pub use new_document::{create_without_dialog as new_document_without_dialog, open as open_new_document, preset_card}; @@ -430,6 +432,7 @@ registry! { VectorHalftone: [halftone::KIND] => halftone::SPEC, SimplifySlider: [simplify_slider::KIND] => simplify_slider::SPEC, SmoothSlider: [smooth_slider::KIND] => smooth_slider::SPEC, + SmartPunctuation: [smart_punctuation::KIND] => smart_punctuation::SPEC, PerspectiveGrid: [perspective_grid::KIND] => perspective_grid::SPEC, Envelope: [envelope::WARP, envelope::MESH, envelope::OPTIONS] => envelope::SPEC, LiquifyOptions: [liquify::KIND] => liquify::SPEC, diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index 6656b45bf5..35890cd18e 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -65,8 +65,8 @@ pub(super) const SPEC: DialogSpec = DialogSpec { /// grid options lists one, and the radial and mirror pages do not. Type on a Path Options does /// too (#5360), as public tutorials of the dialog show, and Type Tools › Release Type on a Path /// works the same way (#5532), and so do Image Tools › Remove Background and Color Mask and -/// Cutting Tools › Weed Box and Lines and Banner Hems and Grommets. (Cancel rolls a preview back -/// whichever dialog started it.) +/// Cutting Tools › Weed Box and Lines, Banner Hems and Grommets and Nest Shapes. (Cancel rolls a +/// preview back whichever dialog started it.) fn previews(d: &Dialog) -> bool { match d.str("__command").as_str() { "object.repeat.options" => d.fields.contains_key("gridType"), @@ -75,7 +75,8 @@ fn previews(d: &Dialog) -> bool { | crate::addons::image::REMOVE_BACKGROUND | crate::addons::image::COLOR_MASK | crate::addons::cutting::WEED - | crate::addons::cutting::BANNER => true, + | crate::addons::cutting::BANNER + | crate::addons::cutting::NEST => true, _ => false, } } @@ -123,6 +124,7 @@ fn lengths(command: &str) -> &'static [&'static str] { "perspective.grid.set" => &["cell", "distance"], crate::addons::cutting::WEED => &["margin", "spacing", "gap", "weight"], crate::addons::cutting::BANNER => &["hem", "spacing", "grommetInset", "diameter", "weight"], + crate::addons::cutting::NEST => &["width", "height", "margin", "spacing"], "object.repeat.options" => &["radius", "hSpacing", "vSpacing"], "text.areaOptions" => &["width", "height", "gutter", "rowGutter", "inset", "firstBaselineMin", "lineGap"], "type.pathOptions" => &["spacing"], @@ -150,6 +152,7 @@ fn order(command: &str) -> &'static [&'static str] { crate::addons::cutting::BANNER => { &["hem", "top", "right", "bottom", "left", "grommets", "spacing", "grommetInset", "diameter", "weight", "swatch"] } + crate::addons::cutting::NEST => &["roll", "width", "height", "margin", "spacing", "rotate", "usePreviewBounds"], // The public Trap options' order. "object.pathfinder.trap" => &["thickness", "heightWidth", "tintReduction", "trapsWithProcessColor", "reverseTraps"], "addon.color.printFixes" => &["inkLimit", "excludePureBlack", "removeWhiteOverprint", "overprintBlack", "textOnly", "fill", "stroke"], @@ -517,7 +520,7 @@ mod tests { } /// Text Wrap Options › Offset is a distance, and its range is the one `object.textWrap.options` - /// keeps an Offset to. + /// accepts: the command takes the range's ends and refuses an Offset outside them. #[test] fn text_wrap_offset_is_a_distance_within_the_commands_range() { assert!(lengths("object.textWrap.options").contains(&"offset")); @@ -531,8 +534,11 @@ mod tests { s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); s.execute("select.all", &json!({})).unwrap(); s.execute("object.textWrap.make", &json!({})).unwrap(); - for (sent, end) in [(5000.0, *range.end()), (-5000.0, *range.start())] { - assert_eq!(s.execute("object.textWrap.options", &json!({ "offset": sent })).unwrap()["offset"], json!(end)); + for end in [*range.end(), *range.start()] { + assert_eq!(s.execute("object.textWrap.options", &json!({ "offset": end })).unwrap()["offset"], json!(end)); + } + for sent in [5000.0, -5000.0] { + assert!(s.execute("object.textWrap.options", &json!({ "offset": sent })).is_err(), "{sent}"); } } diff --git a/crates/ui-egui/src/dialogs/effect.rs b/crates/ui-egui/src/dialogs/effect.rs index 777c872494..2c2673d468 100644 --- a/crates/ui-egui/src/dialogs/effect.rs +++ b/crates/ui-egui/src/dialogs/effect.rs @@ -227,6 +227,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { None if id == TWEAK => tweak_fields(ui, d, app.session.general_unit()), None if id == DROP_SHADOW => drop_shadow_fields(ui, d, app.session.general_unit()), None if id == "artistic.filmGrain" => film_grain_fields(ui, d), + None if id == RADIAL_BLUR => radial_blur_fields(ui, d, app.session.general_unit()), None if id == free_distort::FREE_DISTORT => { free_distort::fields(app, ui, d); values_changed(d) @@ -287,6 +288,127 @@ fn film_grain_fields(ui: &mut egui::Ui, d: &mut Dialog) -> bool { before != d.fields } +/// The Radial Blur effect (Effect › Blur › Radial Blur…). +const RADIAL_BLUR: &str = "blur.radial"; +/// Radial Blur's Blur Center: its parameters (0..1 across and down the object's bounds). +const BLUR_CENTER: [&str; 2] = ["centerX", "centerY"]; + +/// Radial Blur: Amount, Blur Method and Quality as the other effects show their parameters, then +/// the Blur Center box with its Horizontal and Vertical fields. Returns whether the values differ +/// from those last previewed. +fn radial_blur_fields(ui: &mut egui::Ui, d: &mut Dialog, unit: vectorcraft_doc::Unit) -> bool { + let before = d.fields.clone(); + // The center is the box's, not a pair of plain number rows. + let center: Vec<(String, Value)> = BLUR_CENTER.iter().filter_map(|k| d.fields.remove(*k).map(|v| (k.to_string(), v))).collect(); + let doc = vectorcraft_effects::effect_info(RADIAL_BLUR).map(|e| e.params).unwrap_or_default(); + form::param_fields(ui, d, &|_| false, &|k| choices(RADIAL_BLUR, k), &|k| doc_rank(doc, k), unit); + d.fields.extend(center); + ui.add_space(6.0); + blur_center(ui, d); + before != d.fields +} + +/// The Blur Center box's side (points). +const CENTER_BOX: f32 = 120.0; + +/// A Blur Center coordinate kept to a hundredth of a percent of the box. +fn center_round(x: f64) -> f64 { + (x * 1e4).round() / 1e4 +} + +/// Radial Blur's Blur Center: a box standing for the object's bounds, with the blur's pattern (rays +/// for Zoom, rings for Spin) drawn about the center. A press or a drag in the box puts the center +/// there; with the keyboard focus the arrow keys move it 1 % of the box (10 % with Shift). The +/// Horizontal and Vertical fields beside it type the same position in percent of the bounds' width +/// and height. Changes go to `d.fields["centerX"]` and `["centerY"]`. +fn blur_center(ui: &mut egui::Ui, d: &mut Dialog) { + use egui::{Key, Modifiers, Sense, Stroke}; + let [kx, ky] = BLUR_CENTER; + let mut c = [d.f64(kx, 0.5).clamp(0.0, 1.0), d.f64(ky, 0.5).clamp(0.0, 1.0)]; + let before = c; + let t = Tokens::get(ui.ctx()); + let zoom = d.str("method").eq_ignore_ascii_case("zoom"); + form::caption(ui, "Blur Center"); + ui.horizontal(|ui| { + let (rect, _) = ui.allocate_exact_size(egui::vec2(CENTER_BOX, CENTER_BOX), Sense::hover()); + let id = ui.scope_id().with("radial-blur-center"); + let resp = ui.interact(rect, id, Sense::click_and_drag()); + let percent = |v: f64| (v * 1000.0).round() / 10.0; + let name = tl!("Blur Center").to_string(); + let value = format!("{}: {}%, {}: {}%", tl!("Horizontal"), percent(c[0]), tl!("Vertical"), percent(c[1])); + let enabled = ui.is_enabled(); + resp.widget_info(|| egui::WidgetInfo { + current_text_value: Some(value.clone()), + ..egui::WidgetInfo::labeled(egui::Role::Slider, enabled, &name) + }); + if resp.drag_started() || resp.clicked() { + resp.request_focus(); + } + if let Some(p) = resp.interact_pointer_pos() + && (resp.dragged() || resp.clicked() || resp.drag_started()) + { + let unit = |v: f32, lo: f32| f64::from(((v - lo) / CENTER_BOX).clamp(0.0, 1.0)); + c = [center_round(unit(p.x, rect.left())), center_round(unit(p.y, rect.top()))]; + } + if resp.has_focus() { + ui.memory_mut(|m| { + m.set_focus_lock_filter(id, egui::EventFilter { horizontal_arrows: true, vertical_arrows: true, ..Default::default() }) + }); + for (key, dx, dy) in [(Key::ArrowLeft, -1.0, 0.0), (Key::ArrowRight, 1.0, 0.0), (Key::ArrowUp, 0.0, -1.0), (Key::ArrowDown, 0.0, 1.0)] { + // Shift first: a key without modifiers also matches the key with Shift. + for (modifiers, step) in [(Modifiers::SHIFT, 0.1), (Modifiers::NONE, 0.01)] { + if ui.input_mut(|i| i.consume_key(modifiers, key)) { + c = [center_round((c[0] + dx * step).clamp(0.0, 1.0)), center_round((c[1] + dy * step).clamp(0.0, 1.0))]; + } + } + } + } + if resp.hovered() || resp.dragged() { + ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair); + } + // The box, and the pattern about the center: rays for Zoom, rings for Spin. + let painter = ui.painter_at(rect); + painter.rect_filled(rect, 2.0, t.input); + let at = egui::pos2(rect.left() + c[0] as f32 * CENTER_BOX, rect.top() + c[1] as f32 * CENTER_BOX); + let faint = Stroke::new(1.0, t.text_dim.gamma_multiply(0.6)); + let reach = CENTER_BOX * std::f32::consts::SQRT_2; + if zoom { + for k in 0..24 { + let a = k as f32 * std::f32::consts::TAU / 24.0; + let dir = egui::vec2(a.cos(), a.sin()); + painter.line_segment([at + dir * 6.0, at + dir * reach], faint); + } + } else { + for k in 1..=12 { + painter.circle_stroke(at, k as f32 * reach / 12.0, faint); + } + } + painter.circle(at, 3.5, if resp.has_focus() { t.accent } else { t.panel }, Stroke::new(1.5, t.text)); + let border = if resp.has_focus() { t.accent } else { t.input_border }; + painter.rect_stroke(rect, 2.0, Stroke::new(1.0, border), egui::StrokeKind::Inside); + // The same position typed in percent. + ui.vertical(|ui| { + egui::Grid::new("blur-center-fields").num_columns(2).spacing([8.0, 8.0]).show(ui, |ui| { + for (i, label) in ["Horizontal", "Vertical"].into_iter().enumerate() { + let row = ui.label(egui::RichText::new(format!("{}:", tl!(label))).color(t.text)); + ui.label_inputs_by(row.id, |ui| { + if let Some(x) = + widgets::range_field_named(ui, ("blur-center", i), None, c[i] * 100.0, 0.0..=100.0, &form::unit_suffix("%"), 1, 72.0) + { + c[i] = center_round((x / 100.0).clamp(0.0, 1.0)); + } + }); + ui.end_row(); + } + }); + }); + }); + if c != before { + d.fields.insert(kx.into(), json!(c[0])); + d.fields.insert(ky.into(), json!(c[1])); + } +} + /// The Glass effect (Effect › Distort › Glass…). const GLASS: &str = "distort.glass"; /// The Texturizer effect (Effect › Texture › Texturizer…). @@ -1258,4 +1380,69 @@ mod tests { assert_eq!((param("opacity"), param("blur")), (Some(99.0), Some(0.0)), "{effect}: OK applies them"); } } + + /// Effect > Blur > Radial Blur: a press in the Blur Center box puts the center there, the + /// arrow keys move it 1 % (10 % with Shift) and stop at the edges, screen readers get its + /// position, the generic rows leave it to the box, and OK applies it. + #[test] + fn radial_blur_center_box_sets_the_center_by_pointer_and_keys() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + app.run("select.all", json!({})).unwrap(); + app.run("effect.dialog", json!({"effect": RADIAL_BLUR})).unwrap(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, Default::default()); + let time = std::cell::Cell::new(0.0); + // One frame → the box's screen-reader node (bounds, value) and the labels drawn. + let frame = |app: &mut VectorcraftApp, events: Vec| { + time.set(time.get() + 0.05); + let mut out = ctx.run_ui(egui::RawInput { time: Some(time.get()), events, ..Default::default() }, |ui| super::super::show(app, ui.ctx())); + out.textures_delta.clear(); + let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + let labels: Vec = nodes.iter().filter_map(|(_, n)| n.label().map(str::to_string)).collect(); + let center = nodes.iter().find(|(_, n)| n.label() == Some("Blur Center") && n.role() == egui::accesskit::Role::Slider).map(|(_, n)| { + let b = n.bounds().unwrap_or_default(); + (egui::Rect::from_min_max(egui::pos2(b.x0 as f32, b.y0 as f32), egui::pos2(b.x1 as f32, b.y1 as f32)), n.value().map(str::to_string)) + }); + (center, labels) + }; + for _ in 0..6 { + frame(&mut app, vec![]); + } + let (Some((rect, value)), labels) = frame(&mut app, vec![]) else { panic!("the dialog has a Blur Center box") }; + assert_eq!(value.as_deref(), Some("Horizontal: 50%, Vertical: 50%"), "the default center is the middle"); + assert!(!labels.iter().any(|l| l.starts_with("Center")), "no plain Center X or Center Y rows: {labels:?}"); + let field = |app: &VectorcraftApp, k: &str| app.ui.dialog.as_ref().unwrap().fields.get(k).and_then(Value::as_f64); + let pos = rect.min + egui::vec2(0.25 * rect.width(), 0.75 * rect.height()); + let button = |pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + frame(&mut app, vec![egui::Event::PointerMoved(pos), button(true)]); + frame(&mut app, vec![button(false)]); + frame(&mut app, vec![]); + let at = |app: &VectorcraftApp| (field(app, "centerX").unwrap_or(-1.0), field(app, "centerY").unwrap_or(-1.0)); + let (x, y) = at(&app); + assert!((x - 0.25).abs() < 0.01 && (y - 0.75).abs() < 0.01, "the press puts the center there: {x}, {y}"); + let key = |key, modifiers| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }; + app.ui.dialog.as_mut().unwrap().fields.insert("centerX".into(), json!(0.25)); + app.ui.dialog.as_mut().unwrap().fields.insert("centerY".into(), json!(0.75)); + frame(&mut app, vec![key(egui::Key::ArrowRight, egui::Modifiers::NONE)]); + frame(&mut app, vec![key(egui::Key::ArrowUp, egui::Modifiers::SHIFT)]); + assert_eq!(at(&app), (0.26, 0.65), "the arrow keys move it 1 %, 10 % with Shift"); + for _ in 0..10 { + frame(&mut app, vec![key(egui::Key::ArrowDown, egui::Modifiers::SHIFT)]); + } + assert_eq!(at(&app), (0.26, 1.0), "it stops at the edge"); + let (Some((_, value)), _) = frame(&mut app, vec![]) else { panic!("the box is still there") }; + assert_eq!(value.as_deref(), Some("Horizontal: 26%, Vertical: 100%")); + super::super::confirm(&mut app).unwrap(); + let st = app.session.doc().unwrap(); + let fx = &st.doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.effects[0]; + assert_eq!( + (fx.id.as_str(), fx.params["centerX"].as_f64(), fx.params["centerY"].as_f64()), + (RADIAL_BLUR, Some(0.26), Some(1.0)), + "OK applies it" + ); + } } diff --git a/crates/ui-egui/src/dialogs/effect_gallery.rs b/crates/ui-egui/src/dialogs/effect_gallery.rs index 03c862171d..c78854d439 100644 --- a/crates/ui-egui/src/dialogs/effect_gallery.rs +++ b/crates/ui-egui/src/dialogs/effect_gallery.rs @@ -271,6 +271,7 @@ fn preview_space(w: usize, h: usize) -> PixelSpace { to_doc: Affine::IDENTITY, px: 1.0, center: Point::new(wf / 2.0, hf / 2.0), + size: vectorcraft_geom::Vec2::new(wf, hf), channels: vectorcraft_effects::pixel::Channels::Rgb, line: 1.0, extent: 0.5 * wf.hypot(hf), diff --git a/crates/ui-egui/src/dialogs/export_as.rs b/crates/ui-egui/src/dialogs/export_as.rs index add0fbed73..cd18d6b153 100644 --- a/crates/ui-egui/src/dialogs/export_as.rs +++ b/crates/ui-egui/src/dialogs/export_as.rs @@ -140,7 +140,10 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { } // Nothing to export keeps the dialog open too (before the save dialog, not after it). An // exporter plug-in decides for itself what it can write. - if !use_artboards && plugin.is_none() && app.session.active().is_some_and(|s| vectorcraft_render::encode::art_bounds(&s.doc).is_none()) { + if !use_artboards + && plugin.is_none() + && app.session.active().is_some_and(|s| vectorcraft_engine::cmd::fileio::export_art_bounds(&s.doc, f.id).is_none()) + { return Err("nothing to export: the document has no visible art (or turn on Use Artboards)".into()); } app.ui.dialog = None; diff --git a/crates/ui-egui/src/dialogs/export_for_screens.rs b/crates/ui-egui/src/dialogs/export_for_screens.rs index 54c98052bf..5b28affa2f 100644 --- a/crates/ui-egui/src/dialogs/export_for_screens.rs +++ b/crates/ui-egui/src/dialogs/export_for_screens.rs @@ -156,7 +156,8 @@ pub fn open(app: &mut VectorcraftApp) { // `folders: "format"`, any other sorting a folder per scale. let folders = get("folders").and_then(Value::as_str); let subfolders = match folders { - Some("none") => false, + // An export reads empty folders as none. + Some("none" | "") => false, Some(_) => true, None => flag("subfolders", saved.is_empty() || preset.is_some()), }; @@ -391,6 +392,11 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { ui.vertical(|ui| { ui.set_width(LEFT_W); if let Some(i) = widgets::tab_bar(ui, &[tl!("Artboards"), tl!("Assets")], tab) { + if i != tab + && let Some((board, text, _)) = take_artboard_edit(app, d) + { + rename_artboard(app, board, &text); + } d.fields.insert("tab".into(), json!(TABS.get(i).copied().unwrap_or("artboards"))); } ui.add_space(6.0); @@ -520,23 +526,33 @@ fn select_options(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { fn artboard_tiles(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, list: bool) { let mut boards = boards(app, d); let before = boards.clone(); + let mut editing = take_artboard_edit(app, d); + let mut rename = None; let names: Vec = app.session.active().map(|s| s.doc.artboards.iter().map(|a| a.name.clone()).collect()).unwrap_or_default(); + let ids: Vec = app.session.active().map(|s| s.doc.artboards.iter().map(|a| a.id).collect()).unwrap_or_default(); ui.add_enabled_ui(d.str("select") != "full", |ui| { - tiles(ui, "efs-artboards", names.len(), list, |ui, i, r| { - match artboard_thumb(app, ui.ctx(), i) { - Some(tex) => { - let sz = tex.size_vec2(); - let s = (r.width() / sz.x).min(r.height() / sz.y).min(1.0); - let uv = egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)); - ui.painter().image(tex.id(), egui::Rect::from_center_size(r.center(), sz * s), uv, egui::Color32::WHITE); + tiles( + ui, + "efs-artboards", + names.len(), + list, + |ui, i, r| { + match artboard_thumb(app, ui.ctx(), i) { + Some(tex) => { + let sz = tex.size_vec2(); + let s = (r.width() / sz.x).min(r.height() / sz.y).min(1.0); + let uv = egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)); + ui.painter().image(tex.id(), egui::Rect::from_center_size(r.center(), sz * s), uv, egui::Color32::WHITE); + } + None => { + ui.painter().rect_filled(r, 2.0, egui::Color32::WHITE); + } } - None => { - ui.painter().rect_filled(r, 2.0, egui::Color32::WHITE); - } - } - let name = names.get(i).cloned().unwrap_or_default(); - (format!("{} {name}", i + 1), name, boards.get(i).copied().unwrap_or(false)) - }) + let name = names.get(i).cloned().unwrap_or_default(); + (format!("{} {name}", i + 1), name, boards.get(i).copied().unwrap_or(false)) + }, + Some(&mut |ui, i, rect, id, name| edit_artboard_name(ui, ids.get(i).copied(), rect, id, name, &mut editing, &mut rename)), + ) .into_iter() .for_each(|i| { if let Some(b) = boards.get_mut(i) { @@ -544,6 +560,16 @@ fn artboard_tiles(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, l } }); }); + // A field whose artboard was deleted while it was typed in is closed, so Escape reaches the dialog again. + if d.str("select") != "full" + && let Some(uid) = app.session.active().map(|s| s.uid) + && let Some((board, text, focus)) = editing.filter(|(board, _, _)| ids.contains(board)) + { + d.fields.insert(RENAME_ARTBOARD.into(), json!((uid, board, text, focus))); + } + if let Some((board, name)) = rename { + rename_artboard(app, board, &name); + } if boards != before { set_select(d, if boards.iter().all(|b| *b) { "all" } else { "range" }); d.fields.insert("range".into(), json!(range_text(&boards))); @@ -551,6 +577,100 @@ fn artboard_tiles(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, l } } +/// Inline editor state belongs to this dialog, not to the document or its export settings. +const RENAME_ARTBOARD: &str = "__renameArtboard"; + +/// Whether an artboard name is being typed in Export for Screens: a field is open for an artboard +/// of the active document. +pub(crate) fn artboard_name_editing(app: &VectorcraftApp, d: &Dialog) -> bool { + d.kind == KIND + && d.fields + .get(RENAME_ARTBOARD) + .and_then(|value| serde_json::from_value::<(u64, u32, String, bool)>(value.clone()).ok()) + .zip(app.session.active()) + .is_some_and(|((uid, board, ..), s)| s.uid == uid && s.doc.artboards.iter().any(|a| a.id == board)) +} + +/// The artboard being renamed (its id, so the name goes to the same artboard after the artboards +/// change order), the name as typed, and whether the field still has to take the focus. A field +/// opened in another document than the active one is closed. +fn take_artboard_edit(app: &VectorcraftApp, d: &mut Dialog) -> Option<(u32, String, bool)> { + let doc = app.session.active().map(|s| s.uid); + d.fields + .remove(RENAME_ARTBOARD) + .and_then(|value| serde_json::from_value::<(u64, u32, String, bool)>(value).ok()) + .filter(|(uid, ..)| Some(*uid) == doc) + .map(|(_, board, text, focus)| (board, text, focus)) +} + +/// The field of the artboard with id `board`, the same wherever its tile is drawn. +fn artboard_name_field(board: u32) -> egui::Id { + egui::Id::unique(("efs-artboard-name", board)) +} + +fn rename_artboard(app: &mut VectorcraftApp, board: u32, text: &str) { + let name = text.trim(); + let Some(index) = app.session.active().and_then(|s| s.doc.artboards.iter().position(|a| a.id == board && a.name != name)) else { return }; + if !name.is_empty() + && let Err(err) = app.run("artboard.rename", json!({"indices": [index], "name": name})) + { + app.status(err); + } +} + +/// The caption of the artboard with id `board`: its name field while it is renamed, else a target +/// for the double-click that opens it → whether the click toggles the artboard's checkbox, and +/// whether the field was drawn over the caption. +fn edit_artboard_name( + ui: &mut egui::Ui, + board: Option, + rect: egui::Rect, + id: egui::Id, + name: &str, + editing: &mut Option<(u32, String, bool)>, + rename: &mut Option<(u32, String)>, +) -> (bool, bool) { + if let Some((b, text, focus)) = editing.as_mut().filter(|(b, _, _)| Some(*b) == board) { + let field = artboard_name_field(*b); + let cancel = ui.input(|i| i.key_pressed(egui::Key::Escape)); + let enter = crate::shortcuts::pressed_anew(ui.ctx(), egui::Key::Enter); + if enter { + widgets::reject_dialog_commit(ui.ctx()); + } + let response = ui.put(rect, egui::TextEdit::singleline(text).id(field).font(egui::FontId::proportional(11.0)).desired_width(rect.width())); + if *focus { + widgets::focus_field(ui, field, text); + *focus = false; + } else if cancel || enter || response.lost_focus() { + if !cancel { + *rename = Some((*b, std::mem::take(text))); + } + response.surrender_focus(); + *editing = None; + } + (false, true) + } else { + let response = ui.interact(rect, id, egui::Sense::click()); + if let Some(board) = board + && response.double_clicked() + { + *editing = Some((board, name.into(), true)); + ui.ctx().request_repaint(); + // If both releases arrived this frame, the first click did not toggle the row. + // Otherwise, undo the toggle from the first click on this caption. + let toggle = !ui.input(|input| { + input.events.iter().filter(|event| { + matches!(event, egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, .. } if rect.contains(*pos)) + }).nth(1).is_some() + }); + return (toggle, false); + } + (response.clicked(), false) + } +} + +type CaptionEdit<'a> = dyn FnMut(&mut egui::Ui, usize, egui::Rect, egui::Id, &str) -> (bool, bool) + 'a; + /// `count` thumbnails in a grid (or, with `list`, a list) that scrolls: `paint` draws thumbnail `i` /// into its rect and gives its caption, its checkbox's name and whether it is checked → the /// thumbnails whose checkbox (or picture) was clicked. @@ -560,6 +680,7 @@ fn tiles( count: usize, list: bool, mut paint: impl FnMut(&mut egui::Ui, usize, egui::Rect) -> (String, String, bool), + mut caption_edit: Option<&mut CaptionEdit<'_>>, ) -> Vec { let t = Tokens::get(ui.ctx()); let mut toggled = vec![]; @@ -580,11 +701,22 @@ fn tiles( let label_at = if list { egui::pos2(pic.right() + 8.0, pic.center().y) } else { egui::pos2(pic.left(), pic.bottom() + 9.0) }; let galley = ui.painter().layout(caption, egui::FontId::proportional(11.0), t.text, if list { cell.x - side - 12.0 } else { side }); - ui.painter().galley(egui::pos2(label_at.x, label_at.y - galley.size().y / 2.0), galley, t.text); + let label_pos = egui::pos2(label_at.x, label_at.y - galley.size().y / 2.0); + let caption_clicked = if let Some(edit) = &mut caption_edit { + let rect = egui::Rect::from_min_max(egui::pos2(label_at.x, r.top().max(label_at.y - 9.0)), r.right_bottom()); + let (clicked, field) = edit(ui, i, rect, resp.id.with("name"), &name); + if !field { + ui.painter().galley(label_pos, galley, t.text); + } + clicked + } else { + ui.painter().galley(label_pos, galley, t.text); + false + }; // The checkbox sits on the thumbnail's lower left corner, as Illustrator's. let bx = egui::Rect::from_min_size(egui::pos2(pic.left() + 4.0, pic.bottom() - 18.0), egui::vec2(14.0, 14.0)); let mut child = ui.new_child(egui::UiBuilder::new().max_rect(bx)); - if widgets::check_box(&mut child, &name, checked, true) || resp.clicked() { + if widgets::check_box(&mut child, &name, checked, true) || resp.clicked() || caption_clicked { toggled.push(i); } } @@ -621,18 +753,25 @@ fn assets(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, list: bool) { // Asked for until its row is in view: the dialog's first frame only measures it. let scroll_to = d.fields.get("__scrollTo").and_then(Value::as_u64).filter(|id| shown.iter().any(|a| a.id == *id)); let mut in_view = scroll_to.is_none(); - let clicked = tiles(ui, "efs-assets", shown.len(), list, |ui, i, r| { - let Some(a) = shown.get(i) else { return (String::new(), String::new(), false) }; - crate::panels::asset_export::paint_thumb(ui, st, a, r); - if scroll_to == Some(a.id) { - if ui.clip_rect().contains_rect(r) { - in_view = true; - } else { - ui.scroll_to_rect(r, Some(egui::Align::Center)); + let clicked = tiles( + ui, + "efs-assets", + shown.len(), + list, + |ui, i, r| { + let Some(a) = shown.get(i) else { return (String::new(), String::new(), false) }; + crate::panels::asset_export::paint_thumb(ui, st, a, r); + if scroll_to == Some(a.id) { + if ui.clip_rect().contains_rect(r) { + in_view = true; + } else { + ui.scroll_to_rect(r, Some(egui::Align::Center)); + } } - } - (a.name.clone(), a.name.clone(), on.contains(&a.id)) - }); + (a.name.clone(), a.name.clone(), on.contains(&a.id)) + }, + None, + ); for i in clicked { if let Some(a) = shown.get(i) { if on.contains(&a.id) { @@ -955,14 +1094,7 @@ pub(crate) fn formats(ui: &mut egui::Ui, d: &mut Dialog, mut menu: Option &'static str { + rows.first() + .and_then(|r| r["format"].as_str()) + .and_then(fileio::format) + .map(|f| f.id) + .filter(|f| SETTINGS.iter().any(|(id, _)| id == f)) + .unwrap_or("png") +} + /// Format Settings: the options of format `id` that apply to every row of it, then Done. fn format_settings(ui: &mut egui::Ui, d: &mut Dialog, id: &str) { let t = Tokens::get(ui.ctx()); diff --git a/crates/ui-egui/src/dialogs/graph_data.rs b/crates/ui-egui/src/dialogs/graph_data.rs index 16d22d4430..ecfb0c303e 100644 --- a/crates/ui-egui/src/dialogs/graph_data.rs +++ b/crates/ui-egui/src/dialogs/graph_data.rs @@ -32,6 +32,8 @@ const MAX_COLS: usize = MAX_GRAPH_SERIES + 1; const MIN_ROWS: usize = 8; const MIN_COLS: usize = 6; const MAX_CELL: usize = 256; +/// The largest file Import Data reads, 1 MB (1,048,576 bytes), the same as Import Data Sets'. +const MAX_IMPORT_BYTES: usize = 1 << 20; /// The Cell Style limits (Adjust column width and decimal digits). const MAX_DECIMALS: u64 = 10; const MAX_WIDTH: u64 = 20; @@ -147,7 +149,10 @@ pub(crate) fn grid_from_text(text: &str) -> Grid { } /// A text file's bytes as text: UTF-16 with its byte-order mark (spreadsheets' "Unicode Text"), -/// else UTF-8 without one. +/// else UTF-16 without one when the bytes hold NUL bytes and Import Data Sets' rule gives them a +/// byte order ([`vectorcraft_engine::cmd::utf16_order_without_mark`]), else UTF-8 with or without +/// one. UTF-16 is read as it is after a byte-order mark: an odd last byte is left out, and an +/// unpaired surrogate reads as U+FFFD. pub(crate) fn decode(bytes: &[u8]) -> String { let utf16 = |rest: &[u8], le: bool| { let units: Vec = rest.as_chunks::<2>().0.iter().map(|p| if le { u16::from_le_bytes(*p) } else { u16::from_be_bytes(*p) }).collect(); @@ -157,7 +162,10 @@ pub(crate) fn decode(bytes: &[u8]) -> String { [0xFF, 0xFE, rest @ ..] => utf16(rest, true), [0xFE, 0xFF, rest @ ..] => utf16(rest, false), [0xEF, 0xBB, 0xBF, rest @ ..] => String::from_utf8_lossy(rest).into_owned(), - _ => String::from_utf8_lossy(bytes).into_owned(), + _ => match bytes.contains(&0).then(|| vectorcraft_engine::cmd::utf16_order_without_mark(bytes)).flatten() { + Some(le) => utf16(bytes, le), + None => String::from_utf8_lossy(bytes).into_owned(), + }, } } @@ -332,9 +340,16 @@ fn revert(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { fn import(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { let pick = crate::FilePick { filters: vec![crate::FilePick::filter("Text", &["txt", "tsv", "csv"])], ..Default::default() }; let path = crate::picks::open(app, &pick).ok_or("cancelled")?; - // The button is off where files can't be read. - let Some(read) = app.services.read.as_ref() else { return Ok(()) }; - let bytes = read(&path)?; + // One byte past the limit tells a larger file apart without reading all of it. + let bytes = match (&app.services.read_head, &app.services.read) { + (Some(read_head), _) => read_head(&path, MAX_IMPORT_BYTES + 1)?, + (None, Some(read)) => read(&path)?, + // The button is off where files can't be read. + (None, None) => return Ok(()), + }; + if bytes.len() > MAX_IMPORT_BYTES { + return Err("the file is larger than 1 MB".into()); + } replace_grid(d, grid_from_text(&decode(&bytes))); Ok(()) } @@ -517,6 +532,28 @@ mod tests { assert_eq!(grid_from_text(&wide)[0].len(), MAX_COLS); } + #[test] + fn utf16_without_a_byte_order_mark_reads_by_its_line_breaks() { + let text = "\tSales é\r\nQ1\t1\n"; + let le: Vec = text.encode_utf16().flat_map(u16::to_le_bytes).collect(); + let be: Vec = text.encode_utf16().flat_map(u16::to_be_bytes).collect(); + assert_eq!(decode(&le), text, "little-endian"); + assert_eq!(decode(&be), text, "big-endian"); + assert_eq!(grid_from_text(&decode(&le)), g(&[&["", "Sales é"], &["Q1", "1"]])); + // One row has no line break: the side of each unit that holds the NUL byte gives the order. + for (bytes, order) in [(b"\0Q\x001\0\t\x002".to_vec(), "big-endian"), (b"Q\x001\0\t\x002\0".to_vec(), "little-endian")] { + assert_eq!(decode(&bytes), "Q1\t2", "one line, {order}"); + } + // A file cut short by one byte, or with an unpaired surrogate, reads as it would after a + // byte-order mark. + assert_eq!(decode(&[le.as_slice(), &[0x0A]].concat()), text, "odd length"); + assert_eq!(decode(&[le.as_slice(), &[0x00, 0xD8]].concat()), format!("{text}\u{FFFD}"), "unpaired surrogate"); + // A line break in both byte orders leaves the order unknown, and UTF-8 with a stray NUL + // byte isn't UTF-16: both read as UTF-8, as before. + assert_eq!(decode(&[0x0A, 0, 0, 0x0A]), "\n\0\0\n"); + assert_eq!(decode(b"a,b\n1,2\0"), "a,b\n1,2\0"); + } + #[test] fn a_sheet_sent_wider_and_taller_than_a_graph_is_cut_to_one() { // One long row and one long column: their product would be ten billion cells. @@ -527,6 +564,46 @@ mod tests { assert_eq!(p["series"].as_array().unwrap().len(), MAX_COLS - 1); } + /// Import Data reads a file no further than one byte past 1 MB where the host can read part of + /// a file: a larger file is refused with the sheet left as it was, and a file at the limit is + /// read. Where the host only reads whole files, a larger file is refused too. + #[test] + fn import_data_refuses_a_file_larger_than_its_limit() { + use std::{cell::RefCell, collections::HashMap, rc::Rc}; + let (mut app, _) = app_with(",a\nQ1,1", "column"); + open(&mut app).unwrap(); + let mut d = app.ui.dialog.clone().unwrap(); + let at_limit = [b"\tb\nQ2\t2\n".as_slice(), &vec![b' '; MAX_IMPORT_BYTES - 8]].concat(); + let files: HashMap> = + [("/big.txt".to_string(), vec![b'1'; MAX_IMPORT_BYTES + 1]), ("/limit.txt".to_string(), at_limit)].into(); + let files = Rc::new(files); + let picked = Rc::new(RefCell::new(String::new())); + let p = picked.clone(); + app.services.pick_open = Some(Box::new(move |_: &crate::FilePick| Some(p.borrow().clone()))); + app.services.read = Some(Box::new(|_: &str| Err("the whole file was read".to_string()))); + let asked = Rc::new(RefCell::new(vec![])); + let (f, a) = (files.clone(), asked.clone()); + app.services.read_head = Some(Box::new(move |path: &str, max: usize| { + a.borrow_mut().push(max); + Ok(f.get(path).ok_or("no such file")?.iter().copied().take(max).collect()) + })); + let before = grid(&d); + *picked.borrow_mut() = "/big.txt".into(); + assert_eq!(import(&mut app, &mut d), Err("the file is larger than 1 MB".to_string())); + assert_eq!(grid(&d), before, "the sheet is left as it was"); + *picked.borrow_mut() = "/limit.txt".into(); + import(&mut app, &mut d).unwrap(); + assert_eq!((cell_at(&d, 0, 1), cell_at(&d, 1, 0)), ("b", "Q2")); + assert_eq!(*asked.borrow(), [MAX_IMPORT_BYTES + 1; 2], "each read stops one byte past the limit"); + // A host that reads only whole files. + app.services.read_head = None; + let f = files.clone(); + app.services.read = Some(Box::new(move |path: &str| Ok(f.get(path).ok_or("no such file")?.clone()))); + *picked.borrow_mut() = "/big.txt".into(); + assert_eq!(import(&mut app, &mut d), Err("the file is larger than 1 MB".to_string())); + assert_eq!(cell_at(&d, 0, 1), "b"); + } + #[test] fn transpose_switch_and_moves() { assert_eq!(transpose(&g(&[&["", "a", "b"], &["Q1", "1", "2"]])), g(&[&["", "Q1"], &["a", "1"], &["b", "2"]])); diff --git a/crates/ui-egui/src/dialogs/import_pdf.rs b/crates/ui-egui/src/dialogs/import_pdf.rs index 1baa838d90..4820680a09 100644 --- a/crates/ui-egui/src/dialogs/import_pdf.rs +++ b/crates/ui-egui/src/dialogs/import_pdf.rs @@ -2,7 +2,8 @@ //! asks which pages (a preview with page navigation), the box to crop to and the password. //! //! Fields: `mode` (`open` | `place`), `name`, `path?`, `pageCount`, `page` (the page shown, and the -//! one placed; 1-based), `allPages` and `range` (open), `cropTo` and `password`. `__locked` is set +//! one placed; 1-based), `allPages`, `range` and `linkPages` (open: Import PDF Pages as Links, for +//! a file read from a path and opened without a password), `cropTo` and `password`. `__locked` is set //! until the password is accepted: OK then unlocks the file. `__place` keeps the other `file.place` //! params (Link, Template, `at`…). The file's bytes stay out of the fields, in //! [`crate::state::UiState::dialog_file`]. @@ -142,6 +143,7 @@ pub fn offer(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option Option { Some(d.str("password")).filter(|p| !p.is_empty()) } +/// Can the pages open linked: the file was read from a path (a linked page is read from its +/// file again) and opens without a password (`document.open`'s `linkPages` refuses one). +fn can_link(d: &Dialog) -> bool { + d.fields.get("path").and_then(Value::as_str).is_some() && password(d).is_none() +} + +/// Import PDF Pages as Links is checked, and can be. +fn links_on(d: &Dialog) -> bool { + d.bool("linkPages") && can_link(d) +} + /// OK: unlock the file with the password, else open the pages or place the page. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let file = app.ui.dialog_file.clone().ok_or("the PDF is no longer loaded")?; @@ -213,6 +226,9 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { if !d.bool("allPages") && !range.trim().is_empty() { p["pages"] = json!(range); } + if links_on(&d) { + p["linkPages"] = json!(true); + } io::open_document(app, &name, &file.bytes, path, &p).map(|_| ()) }; match r { @@ -291,6 +307,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { } }); widgets::dim_label(ui, tl!("e.g. 1-3, 5")); + ui.add_space(10.0); + if widgets::check(ui, tl!("Import PDF pages as links"), links_on(d), can_link(d)) { + d.fields.insert("linkPages".into(), json!(!d.bool("linkPages"))); + } } }); }); diff --git a/crates/ui-egui/src/dialogs/justification.rs b/crates/ui-egui/src/dialogs/justification.rs index dc42dcff87..168f5cfda1 100644 --- a/crates/ui-egui/src/dialogs/justification.rs +++ b/crates/ui-egui/src/dialogs/justification.rs @@ -9,8 +9,10 @@ //! Fields: `wordMin`, `wordDesired`, `wordMax` (0..1000), `letterMin`, `letterDesired`, //! `letterMax` (-100..500), `glyphMin`, `glyphDesired`, `glyphMax` (50..200), `autoLeading` //! (0..500), `singleWord` (`fullJustify`, `alignLeft`, `alignCenter`, `alignRight`) and `preview`, -//! with `__initial` (the values it opened with), `__targets` (the type and range it acts on) and, -//! after Select All in threaded text, `__story` (the edited frame, whose story it acts on). +//! with `__initial` (the values it opened with), `__targets` (the type and range it acts on; with +//! the Selection tool, every frame of each story selected when the dialog opened, locked and hidden +//! frames included) and, after Select All in threaded text, `__story` (the edited frame, whose +//! story it acts on). //! //! Behaviour reference (public documentation): //! . @@ -95,6 +97,9 @@ pub fn open(app: &mut VectorcraftApp) -> Result { targets = json!({"ids": [id.0], "start": a, "end": b}); // After Select All in threaded text: every paragraph of every frame ([`params`]). story = crate::panels::character::text_story(app).map(|_| id.0); + } else { + // With the Selection tool: every frame of each selected story. + crate::panels::character::target_selected_stories(app, &mut targets); } let mut values = Map::new(); for (_, prefix, _) in ROWS { @@ -423,6 +428,74 @@ mod tests { } } + /// A threaded story of three frames, its second frame locked and its third hidden, a type object + /// of its own, and the first frame selected with the Selection tool → the app, the frames and + /// the other type object. + fn story_selected_in_its_first_frame() -> (VectorcraftApp, [u64; 3], u64) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 900, "height": 300})).unwrap(); + let story = "The quick brown fox jumps over the lazy dog.\n".repeat(12); + let area = json!({"x": 10, "y": 10, "text": story, "size": 12, "area": {"width": 150, "height": 60}}); + let a = app.run("text.create", area).unwrap()["id"].as_u64().unwrap(); + let b = app.run("text.thread.add", json!({"from": a, "rect": [200, 10, 150, 60]})).unwrap()["id"].as_u64().unwrap(); + let c = app.run("text.thread.add", json!({"from": b, "rect": [400, 10, 150, 200]})).unwrap()["id"].as_u64().unwrap(); + let other = app.run("text.create", json!({"x": 10, "y": 250, "text": "Other", "size": 12})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [b]})).unwrap(); + app.run("object.lock", json!({})).unwrap(); + app.run("select.set", json!({"ids": [c]})).unwrap(); + app.run("object.hide", json!({})).unwrap(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + (app, [a, b, c], other) + } + + /// Every paragraph's Auto Leading in `id`. + fn auto_leadings(app: &VectorcraftApp, id: u64) -> Vec { + match &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => (0..t.paragraph_count()).map(|i| t.para_at(i).justification.auto_leading).collect(), + _ => panic!("not text"), + } + } + + /// With the Selection tool a selected frame of threaded text stands for its whole story: the + /// dialog opens blank where a locked or hidden frame differs, previews on every frame, Cancel + /// restores them, and OK changes every frame of the story as it was when the dialog opened, in + /// one undo step, leaving other type and a selection made later alone. + #[test] + fn selection_tool_justification_reaches_every_frame_of_the_story() { + let (mut app, frames, other) = story_selected_in_its_first_frame(); + let [a, _, c] = frames; + for id in frames { + assert!(!auto_leadings(&app, id).is_empty(), "frame {id} holds text"); + } + app.run("text.setFormat", json!({"ids": [c], "autoLeading": 150})).unwrap(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + app.run("ui.justification", json!({})).unwrap(); + assert!(!app.ui.dialog.as_ref().unwrap().fields.contains_key("autoLeading"), "the hidden frame differs"); + set(&mut app, "autoLeading", json!(200)); + set(&mut app, "preview", json!(true)); + frame(&mut app); + for id in frames { + assert!(auto_leadings(&app, id).iter().all(|l| *l == 200.0), "the preview shows on frame {id}"); + } + super::super::cancel(&mut app); + assert!(auto_leadings(&app, a).iter().all(|l| *l == 120.0)); + assert!(auto_leadings(&app, c).iter().all(|l| *l == 150.0), "Cancel restores the hidden frame"); + + app.run("ui.justification", json!({})).unwrap(); + // A selection made while the dialog is open does not change what it acts on. + app.run("select.set", json!({"ids": [other]})).unwrap(); + set(&mut app, "autoLeading", json!(140)); + let undo = app.session.active().unwrap().history.undo.len(); + super::super::confirm(&mut app).unwrap(); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1, "one undo step"); + for id in frames { + assert!(auto_leadings(&app, id).iter().all(|l| *l == 140.0), "frame {id} takes the change"); + } + assert!(auto_leadings(&app, other).iter().all(|l| *l == 120.0), "other type keeps its paragraphs"); + app.run("edit.undo", json!({})).unwrap(); + assert!(auto_leadings(&app, c).iter().all(|l| *l == 150.0), "undo restores the hidden frame"); + } + /// When paragraphs in scope disagree, only shared justification values are filled in. #[test] fn justification_dialog_mixed_paragraph_fields_show_blank() { diff --git a/crates/ui-egui/src/dialogs/missing_links.rs b/crates/ui-egui/src/dialogs/missing_links.rs index 46a8dca322..28a6e57828 100644 --- a/crates/ui-egui/src/dialogs/missing_links.rs +++ b/crates/ui-egui/src/dialogs/missing_links.rs @@ -43,19 +43,27 @@ fn ids(rows: &[Value]) -> Vec { /// then about its modified ones, then about the fonts it opened without /// ([`super::missing_fonts`]). The web reads no linked files, so missing ones just show their /// previews there. The status bar shows what it says about the linked files followed by the open's -/// `notes` ([`crate::io::show_opened`]). +/// `notes` ([`crate::io::show_opened`]). On the web, with both missing and modified files and +/// Update Links not asking, the line about the missing files comes first and the line about the +/// modified ones is the first of the notes. pub fn after_open(app: &mut VectorcraftApp, r: &Value, notes: Vec) { after_open_for(app, r, notes, cfg!(target_arch = "wasm32")); } -fn after_open_for(app: &mut VectorcraftApp, r: &Value, notes: Vec, web: bool) { +fn after_open_for(app: &mut VectorcraftApp, r: &Value, mut notes: Vec, web: bool) { // The fonts' dialog waits for these questions (one dialog at a time). super::missing_fonts::after_open(app, r); let rows = |k: &str| r[k].as_array().cloned().unwrap_or_default(); let (missing, modified) = (rows("missingLinks"), ids(&rows("modifiedLinks"))); let notice = if missing.is_empty() || web { let unreadable = (!missing.is_empty()).then(|| unreadable_status(missing.len())); - ask_update(app, modified).or(unreadable) + match (ask_update(app, modified), unreadable) { + (Some(changed), Some(unreadable)) => { + notes.insert(0, changed); + Some(unreadable) + } + (changed, unreadable) => changed.or(unreadable), + } } else { open(app, missing, modified, ¬es); None @@ -390,6 +398,43 @@ mod tests { assert_eq!((app.ui.status.as_str(), &app.ui.status_notes), (notice, &None)); } + /// On the web, an open with linked files it can't read and modified ones, with Update Links + /// not asking: the status bar shows the line about the unreadable files and counts the line + /// about the modified ones as the first note, ahead of the open's notes, and keeps them all + /// for its hover. With Ask When Modified the update question opens and the line about the + /// unreadable files stays. + #[test] + fn a_web_open_with_unreadable_and_modified_links_keeps_both_lines() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.session.prefs.update_links = "manually".into(); + let missing = json!([{ "name": "a.png", "path": "/gone/a.png", "ids": [1] }, { "name": "b.png", "path": "/gone/b.png", "ids": [2] }]); + let r = json!({ "missingLinks": missing, "modifiedLinks": [{ "ids": [3] }] }); + let unreadable = "2 linked files can't be read here: their previews show"; + let changed = changed_on_disk_status(1); + + let notes = vec!["a note".to_string(), "another note".to_string()]; + after_open_for(&mut app, &r, notes.clone(), true); + let kept = [vec![changed.clone()], notes].concat(); + assert_eq!(app.ui.status, crate::io::opened_after_notice(unreadable, 3, &changed)); + assert_eq!(app.ui.status_notes, Some((app.ui.status.clone(), kept))); + assert!(app.ui.dialog.is_none()); + + after_open_for(&mut app, &r, vec![], true); + assert_eq!(app.ui.status, crate::io::opened_after_notice(unreadable, 1, &changed)); + assert_eq!(app.ui.status_notes, Some((app.ui.status.clone(), vec![changed.clone()]))); + + // One kind of line alone shows as before. + after_open_for(&mut app, &json!({ "modifiedLinks": [{ "ids": [3] }] }), vec![], true); + assert_eq!((app.ui.status.clone(), &app.ui.status_notes), (changed, &None)); + + app.session.prefs.update_links = "askWhenModified".into(); + after_open_for(&mut app, &r, vec![], true); + let d = app.ui.dialog.as_ref().expect("asks"); + assert_eq!((d.kind.as_str(), d.str("__command")), (super::super::confirm::KIND, "links.update".to_string())); + assert_eq!((app.ui.status.as_str(), &app.ui.status_notes), (unreadable, &None)); + } + /// The line about modified linked files that follows the Linked File Not Found dialog keeps the /// notes of that open, also when another message was shown meanwhile. An open without notes /// shows the line alone, even while the status bar shows an earlier open's notes, and a later diff --git a/crates/ui-egui/src/dialogs/perspective_options.rs b/crates/ui-egui/src/dialogs/perspective_options.rs index 91e74de0e2..901023fabc 100644 --- a/crates/ui-egui/src/dialogs/perspective_options.rs +++ b/crates/ui-egui/src/dialogs/perspective_options.rs @@ -1,8 +1,9 @@ //! Perspective Grid Options (double-click the Perspective Grid tool): whether the Plane Switching -//! Widget shows and which corner of the window it sits in. OK runs `perspective.widget.options` -//! (the options live in the preferences). +//! Widget shows and which corner of the window it sits in, and what Automatic Plane Positioning +//! takes a point from. OK runs `perspective.widget.options` (the options live in the preferences). //! -//! Fields: `show` (bool) and `position` (`topLeft`, `topRight`, `bottomLeft`, `bottomRight`). +//! Fields: `show` (bool), `position` (`topLeft`, `topRight`, `bottomLeft`, `bottomRight`), +//! `anchorPoint` (bool) and `gridlineIntersection` (bool). use serde_json::{Value, json}; use vectorcraft_tools::distort::perspective::widget::WidgetCorner; @@ -38,5 +39,13 @@ fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { ui.add_space(8.0); let corners: Vec<(&str, &str)> = WidgetCorner::ALL.iter().map(|c| (c.id(), c.label())).collect(); ui.add_enabled_ui(on, |ui| form::choice(ui, d, "position", tl!("Widget Position:"), (110.0, 160.0), &corners)); + ui.add_space(8.0); + widgets::section_header(ui, tl!("Automatic Plane Positioning")); + for (key, label) in [("anchorPoint", tl!("Anchor Point of Perspective Artwork")), ("gridlineIntersection", tl!("Intersection of Gridlines"))] { + let on = d.bool(key); + if widgets::check(ui, label, on, true) { + d.fields.insert(key.into(), json!(!on)); + } + } false } diff --git a/crates/ui-egui/src/dialogs/smart_punctuation.rs b/crates/ui-egui/src/dialogs/smart_punctuation.rs new file mode 100644 index 0000000000..1ebe084e02 --- /dev/null +++ b/crates/ui-egui/src/dialogs/smart_punctuation.rs @@ -0,0 +1,169 @@ +//! Type › Smart Punctuation…: which keyboard characters to replace with their typographic forms, +//! where (the selected type or the whole document) and whether to report how many of each were +//! replaced. OK runs `type.smartPunctuation` as one undo step, and the dialog opens on the fields +//! confirmed last. +//! +//! Fields: the switches `fiLigatures`, `flLigatures`, `quotes`, `spaces`, `dashes`, `ellipsis` and +//! `fractions`, `scope` (`selection` or `document`) and `report`. + +use serde_json::{Value, json}; + +use super::{DialogResult, DialogSpec, form, run_and_close}; +use crate::state::Dialog; +use crate::{VectorcraftApp, widgets}; + +/// The dialog kind of Smart Punctuation. +pub const KIND: &str = "smartPunctuation"; + +const CMD: &str = "type.smartPunctuation"; + +pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Smart Punctuation").into(), body, confirm, min_width: 300.0, ..DialogSpec::FORM }; + +/// The replacement options in the dialog's order: (field, the key of their count in the +/// command's reply, label). +fn options() -> [(&'static str, &'static str, &'static str); 7] { + [ + ("fiLigatures", "fiLigatures", tl!("ff, fi, ffi Ligatures")), + ("flLigatures", "flLigatures", tl!("ff, fl, ffl Ligatures")), + ("quotes", "quotes", tl!("Smart Quotes")), + ("spaces", "spaces", tl!("Smart Spaces")), + ("dashes", "dashes", tl!("En, Em Dashes")), + ("ellipsis", "ellipses", tl!("Ellipses")), + ("fractions", "fractions", tl!("Expert Fractions")), + ] +} + +/// The fields the menu item opens with: those confirmed last, else quotes, dashes and ellipses on +/// (the command's defaults). With nothing selected, the whole document. +pub fn fields(app: &VectorcraftApp) -> Value { + let mut f = match &app.ui.smart_punctuation { + Value::Object(o) => Value::Object(o.clone()), + _ => json!({ + "fiLigatures": false, + "flLigatures": false, + "quotes": true, + "spaces": false, + "dashes": true, + "ellipsis": true, + "fractions": false, + "scope": "selection", + "report": false, + }), + }; + if !has_selection(app) { + f["scope"] = json!("document"); + } + f +} + +fn has_selection(app: &VectorcraftApp) -> bool { + app.session.active().is_some_and(|d| !d.selection.is_empty()) +} + +/// The command's parameters: the switches and the scope. +fn params(d: &Dialog) -> Value { + let mut p = serde_json::Map::new(); + for (key, ..) in options() { + p.insert(key.into(), json!(d.bool(key))); + } + p.insert("scope".into(), json!(if d.str("scope") == "document" { "document" } else { "selection" })); + Value::Object(p) +} + +fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + for (key, _, label) in options() { + form::check(ui, d, key, label); + } + ui.add_space(8.0); + widgets::section_header(ui, tl!("Replace In")); + let selected = has_selection(app); + let scope = d.str("scope"); + for (value, label, enabled) in [("selection", tl!("Selected Text Only"), selected), ("document", tl!("Entire Document"), true)] { + let on = if selected { scope == value } else { value == "document" }; + if widgets::radio(ui, label, on, enabled) { + d.fields.insert("scope".into(), json!(value)); + } + } + ui.add_space(8.0); + form::check(ui, d, "report", tl!("Report Results")); + false +} + +/// Runs the command, keeps the fields for the next time, and with Report Results on lists how many +/// of each chosen replacement it made. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { + let r = run_and_close(app, CMD, params(d))?; + app.ui.smart_punctuation = Value::Object(d.fields.clone()); + if d.bool("report") { + let lines: Vec = options() + .into_iter() + .filter(|(key, ..)| d.bool(key)) + .map(|(_, count, label)| format!("{label}: {}", r["replaced"][count].as_u64().unwrap_or(0))) + .collect(); + super::confirm::tell(app, tl!("Smart Punctuation"), &lines.join("\n")); + } + Ok(r) +} + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_engine::Session; + + fn app_with_text(text: &str) -> (VectorcraftApp, u64) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let id = app.run("text.create", json!({"x": 10, "y": 40, "text": text, "font": "Source Sans 3"})).unwrap()["id"].as_u64().unwrap(); + (app, id) + } + + fn plain(app: &VectorcraftApp, id: u64) -> String { + match &app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind { + vectorcraft_doc::NodeKind::Text(t) => t.plain_text(), + _ => String::new(), + } + } + + /// The menu item opens the dialog; OK replaces in one undo step, reports each chosen + /// replacement's count, and the next opening starts from the fields confirmed. + #[test] + fn menu_item_opens_the_dialog_and_ok_reports_the_counts() { + let (mut app, id) = app_with_text("\"Hi\". 1/2 -- off"); + app.run("select.set", json!({"ids": [id]})).unwrap(); + crate::menus::invoke(&mut app, CMD, json!({})); + let d = app.ui.dialog.as_mut().expect("Smart Punctuation opens"); + assert_eq!((d.kind.as_str(), d.str("scope")), (KIND, "selection".to_string())); + for key in ["spaces", "fractions", "fiLigatures", "report"] { + d.fields.insert(key.into(), json!(true)); + } + d.fields.insert("ellipsis".into(), json!(false)); + let undo = app.session.doc().unwrap().history.undo.len(); + super::super::confirm(&mut app).unwrap(); + assert_eq!(plain(&app, id), "“Hi”. ½ – o\u{FB00}"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1); + let told = app.ui.dialog.as_ref().expect("Report Results shows the counts"); + assert_eq!(told.kind, crate::dialogs::confirm::MESSAGE); + assert_eq!(told.str("detail"), "ff, fi, ffi Ligatures: 1\nSmart Quotes: 2\nSmart Spaces: 1\nEn, Em Dashes: 1\nExpert Fractions: 1"); + app.ui.dialog = None; + crate::menus::invoke(&mut app, CMD, json!({})); + let again = app.ui.dialog.as_ref().unwrap(); + assert!(again.bool("fractions") && again.bool("report") && !again.bool("ellipsis")); + } + + /// With nothing selected the dialog replaces in the entire document, and without Report + /// Results it shows no message. An unchanged document keeps its undo history. + #[test] + fn with_nothing_selected_the_whole_document_is_replaced() { + let (mut app, id) = app_with_text("a--b"); + app.run("select.none", json!({})).unwrap(); + crate::menus::invoke(&mut app, CMD, json!({})); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("scope"), "document"); + super::super::confirm(&mut app).unwrap(); + assert_eq!(plain(&app, id), "a–b"); + assert!(app.ui.dialog.is_none()); + let undo = app.session.doc().unwrap().history.undo.len(); + crate::menus::invoke(&mut app, CMD, json!({})); + super::super::confirm(&mut app).unwrap(); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); + } +} diff --git a/crates/ui-egui/src/dialogs/svg_filter.rs b/crates/ui-egui/src/dialogs/svg_filter.rs index af6849de43..f092a55cc4 100644 --- a/crates/ui-egui/src/dialogs/svg_filter.rs +++ b/crates/ui-egui/src/dialogs/svg_filter.rs @@ -1,16 +1,22 @@ -//! Apply SVG Filter (Effect › SVG Filters › Apply SVG Filter…): the document's SVG filters in a -//! list. OK applies the selected one to the selection as a live effect (`svgFilter.apply`), or, -//! opened from the Appearance panel for an applied SVG filter, puts it in that effect's place -//! (`effect.setParams`). New and Edit open the filter's code under the list; Save adds the filter -//! or replaces the one being edited (`svgFilter.define`). Delete removes the selected filter -//! (`svgFilter.delete`) and Import… adds the filters of an SVG file (`svgFilter.import`). Those -//! act at once. Effect › SVG Filters lists the same filters below its first items. +//! Apply SVG Filter (Effect › SVG Filters › Apply SVG Filter…): the default SVG filters and the +//! document's own in a list, the defaults first. OK applies the selected one to the selection as a +//! live effect, or, opened from the Appearance panel for an applied SVG filter, puts it in that +//! effect's place (`svgFilter.apply`, with `index`). New and Edit open the filter's code under the +//! list; Save adds the filter or replaces the one being edited (`svgFilter.define`). Delete +//! removes the selected filter (`svgFilter.delete`) and Import… adds the filters of an SVG file +//! (`svgFilter.import`). Those act at once. Effect › SVG Filters lists the same filters below its +//! first items. +//! +//! A default is not in the document until it is applied or edited: the document then holds a copy +//! under the default's name, which is listed in the default's place. Delete is off for a default +//! the document holds no copy of. //! //! Fields: `selected` (a filter's name), `code` (the code being edited), `editing` (`""`, `"new"` //! or the name of the filter being edited), and with an applied effect `__index`, `__item` and //! `missing` (the name of a deleted filter the effect names). use serde_json::{Value, json}; +use vectorcraft_effects::svg_filter::defaults::{DEFAULT_FILTERS, Listed, default_filter, listed}; use vectorcraft_engine::doc::SvgFilter; use super::DialogSpec; @@ -25,20 +31,21 @@ pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Apply SVG Filter…").trim_end_matches('…').to_string(), body, confirm, - ok_enabled: Some(|app, d| d.str("editing").is_empty() && filters(app).iter().any(|f| f.name == d.str("selected"))), + ok_enabled: Some(|app, d| d.str("editing").is_empty() && filters(app).0.iter().any(|f| f.filter.name == d.str("selected"))), min_width: 440.0, ..DialogSpec::FORM }; -/// The active document's SVG filters. -fn filters(app: &VectorcraftApp) -> Vec { - app.session.active().map(|st| st.doc.svg_filters.clone()).unwrap_or_default() +/// The filters the dialog lists for the active document, and how many come first as the defaults. +fn filters(app: &VectorcraftApp) -> (Vec, usize) { + listed(app.session.active().map(|st| st.doc.svg_filters.as_slice()).unwrap_or_default()) } /// `ui.svgFilterDialog {index?, item?}`: open Apply SVG Filter for the active document; with /// `index`, for the applied SVG filter at `index` of `item` (null: the object's effects): the -/// document's filter of its name selected; when the document has none of its name, the name shown -/// above the list if the filter was deleted, or else its code open as a new filter. +/// document's filter of its name selected, or the default of its name when the effect draws with +/// the default's code or with nothing; when neither has its name, the name shown above the list if +/// the filter was deleted, or else its code open as a new filter. pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { if app.session.active().is_none() { return Err("no document open".into()); @@ -53,17 +60,19 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { let e = applied.get(k as usize).filter(|e| e.id == vectorcraft_effects::SVG_FILTER).ok_or_else(|| format!("no SVG filter at index {k}"))?; let name = e.params.get("name").and_then(Value::as_str).unwrap_or_default().to_string(); let xml = e.params.get("xml").and_then(Value::as_str).unwrap_or_default().to_string(); - let held = filters(app).into_iter().find(|f| f.name == name); - match held { - // The document's filter it names: selected. - Some(_) => fields["selected"] = json!(name), + let held = app.session.active().is_some_and(|st| st.doc.svg_filters.iter().any(|f| f.name == name)); + // A default the document holds no copy of, when the effect draws with its code or with nothing. + let default = default_filter(&name).is_some_and(|d| xml.is_empty() || xml == d.xml); + if held || default { + // The filter it names: selected. + fields["selected"] = json!(name); + } else if xml.is_empty() { // Deleted from the document: shown above the list, not selectable; OK waits for a choice. - None if xml.is_empty() => fields["missing"] = json!(name), + fields["missing"] = json!(name); + } else { // A filter the document doesn't hold (from an opened file): its code, to add it. - None => { - fields["code"] = json!(xml); - fields["editing"] = json!("new"); - } + fields["code"] = json!(xml); + fields["editing"] = json!("new"); } fields["__index"] = json!(k); // As given: `null` is the object's own effects, and none is the active item's. @@ -75,33 +84,39 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { Ok(Value::Null) } -/// OK: the selected filter to the selection, or in the applied effect's place. +/// OK: the selected filter to the selection, or in the applied effect's place. A default the +/// document holds no copy of is copied into it in the same undo step. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let name = d.str("selected"); - let f = filters(app).into_iter().find(|f| f.name == name).ok_or("select an SVG filter")?; - let r = match d.fields.get("__index").and_then(Value::as_u64) { - Some(k) => { - let mut p = json!({ "index": k, "params": { "name": f.name, "xml": f.xml } }); - if let Some(item) = d.fields.get("__item") { - p["item"] = item.clone(); - } - app.run("effect.setParams", p)? + let f = filters(app).0.into_iter().find(|f| f.filter.name == name).ok_or("select an SVG filter")?; + let mut p = json!({ "name": f.filter.name }); + if let Some(k) = d.fields.get("__index").and_then(Value::as_u64) { + p["index"] = json!(k); + if let Some(item) = d.fields.get("__item") { + p["item"] = item.clone(); } - None => app.run("svgFilter.apply", json!({ "name": f.name }))?, - }; + } + let r = app.run("svgFilter.apply", p)?; app.ui.dialog = None; Ok(r) } -/// The active document's filter names, mirrored for the (static) menu tree ([`sync`]). +/// The names of the active document's filters that are not a default's, mirrored for the (static) +/// menu tree ([`sync`]). fn names_store() -> &'static std::sync::RwLock> { static NAMES: std::sync::OnceLock>> = std::sync::OnceLock::new(); NAMES.get_or_init(Default::default) } -/// Mirror the active document's SVG filter names for the menu tree (cheap when unchanged). +/// The names of `held`, a document's filters, that are not a default's, in their order. +fn own_names(held: &[SvgFilter]) -> Vec { + held.iter().filter(|f| default_filter(&f.name).is_none()).map(|f| f.name.clone()).collect() +} + +/// Mirror the active document's SVG filter names for the menu tree (cheap when unchanged). A +/// filter with a default's name is the menu's entry of that name already. pub fn sync(app: &VectorcraftApp) { - let names: Vec = app.session.active().map(|st| st.doc.svg_filters.iter().map(|f| f.name.clone()).collect()).unwrap_or_default(); + let names: Vec = app.session.active().map(|st| own_names(&st.doc.svg_filters)).unwrap_or_default(); let same = names_store().read().map(|v| v.len() == names.len() && v.iter().zip(&names).all(|(a, b)| *a == b)).unwrap_or(true); if !same { if let Ok(mut v) = names_store().write() { @@ -111,20 +126,23 @@ pub fn sync(app: &VectorcraftApp) { } } -/// Effect › SVG Filters: Apply SVG Filter…, Import SVG Filter… and then the active document's -/// filters, each applying itself to the selection. +/// Effect › SVG Filters: Apply SVG Filter…, Import SVG Filter…, the default filters and then the +/// active document's other filters, each applying itself to the selection. pub fn menu_items() -> Vec { items_for(names_store().read().map(|v| v.clone()).unwrap_or_default()) } -/// [`menu_items`] for filters named `names`. +/// [`menu_items`] for a document whose filters that are not a default's are named `names`. fn items_for(names: Vec<&'static str>) -> Vec { use crate::menus::Item; + let apply = |n: &'static str| Item::Cmd(n, "svgFilter.apply", json!({ "name": n })); let mut v = vec![Item::Cmd("Apply SVG Filter…", "ui.svgFilterDialog", Value::Null), Item::Cmd("Import SVG Filter…", "ui.importSvgFilter", Value::Null)]; + v.push(Item::Sep); + v.extend(DEFAULT_FILTERS.iter().map(|d| apply(d.name))); if !names.is_empty() { v.push(Item::Sep); - v.extend(names.into_iter().map(|n| Item::Cmd(n, "svgFilter.apply", json!({ "name": n })))); + v.extend(names.into_iter().map(apply)); } v } @@ -170,7 +188,8 @@ enum Action { } fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { - let list = filters(app); + let (list, defaults) = filters(app); + let held = list.iter().filter(|f| !f.default).count(); let selected = d.str("selected"); let editing = d.str("editing"); let mut act = None; @@ -184,7 +203,11 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { if !missing.is_empty() { ui.add_enabled_ui(false, |ui| ui.selectable_label(false, missing.as_str())); } - for f in &list { + for (i, Listed { filter: f, .. }) in list.iter().enumerate() { + // The document's other filters follow the defaults, below a line. + if i == defaults && i > 0 { + ui.separator(); + } let r = ui.selectable_label(f.name == selected, f.name.as_str()); if r.double_clicked() && editing.is_empty() { act = Some(Action::Edit(f.name.clone())); @@ -195,17 +218,20 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { }); }); ui.add_space(6.0); - let has = list.iter().any(|f| f.name == selected); + let chosen = list.iter().find(|f| f.filter.name == selected); + let has = chosen.is_some(); + // A default the document holds no copy of has nothing to delete. + let deletable = chosen.is_some_and(|f| !f.default); ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = 4.0; let idle = editing.is_empty(); - if ui.add_enabled_ui(idle && list.len() < SvgFilter::MAX, |ui| widgets::flat_button(ui, tl!("New"), 64.0)).inner.clicked() { + if ui.add_enabled_ui(idle && held < SvgFilter::MAX, |ui| widgets::flat_button(ui, tl!("New"), 64.0)).inner.clicked() { act = Some(Action::New); } if ui.add_enabled_ui(idle && has, |ui| widgets::flat_button(ui, tl!("Edit"), 64.0)).inner.clicked() { act = Some(Action::Edit(selected.clone())); } - if ui.add_enabled_ui(idle && has, |ui| widgets::flat_button(ui, tl!("Delete"), 64.0)).inner.clicked() { + if ui.add_enabled_ui(idle && deletable, |ui| widgets::flat_button(ui, tl!("Delete"), 64.0)).inner.clicked() { act = Some(Action::Delete); } if crate::picks::can(app, &PickRequest::Open(pick())) @@ -245,7 +271,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { Ok(()) } Some(Action::Edit(name)) => { - if let Some(f) = list.iter().find(|f| f.name == name) { + if let Some(f) = list.iter().map(|f| &f.filter).find(|f| f.name == name) { d.fields.insert("selected".into(), json!(f.name)); d.fields.insert("editing".into(), json!(f.name)); d.fields.insert("code".into(), json!(f.xml)); @@ -322,7 +348,9 @@ mod tests { crate::menus::invoke(&mut app, "ui.svgFilterDialog", json!({})); let mut d = app.ui.dialog.clone().unwrap(); assert_eq!(d.kind, KIND); - assert!(frame(&mut app, &mut d).iter().any(|t| t == "Shift"), "the filter's name, as it is"); + // Below the defaults, which fill the rows the list shows at first. + assert_eq!(filters(&app).0.last().map(|f| f.filter.name.as_str()), Some("Shift"), "the filter's name, as it is"); + assert!(!frame(&mut app, &mut d).is_empty()); assert!(!(SPEC.ok_enabled.unwrap())(&app, &d), "nothing selected"); d.fields.insert("selected".into(), json!("Shift")); assert!((SPEC.ok_enabled.unwrap())(&app, &d)); @@ -411,11 +439,30 @@ mod tests { use crate::menus::Item; let ids = |items: &[Item]| items.iter().map(|i| if let Item::Cmd(l, c, p) = i { format!("{l} {c} {p}") } else { "—".into() }).collect::>(); - assert_eq!(ids(&items_for(vec![])), ["Apply SVG Filter… ui.svgFilterDialog null", "Import SVG Filter… ui.importSvgFilter null"]); + // The defaults follow the commands in every document, and with no document. + let plain = ids(&items_for(vec![])); assert_eq!( - ids(&items_for(vec!["Shift", "A (1)"]))[2..], - ["—", "Shift svgFilter.apply {\"name\":\"Shift\"}", "A (1) svgFilter.apply {\"name\":\"A (1)\"}"] + plain[..4], + [ + "Apply SVG Filter… ui.svgFilterDialog null", + "Import SVG Filter… ui.importSvgFilter null", + "—", + "Soft Blur svgFilter.apply {\"name\":\"Soft Blur\"}" + ] ); + assert_eq!(plain.len(), 3 + DEFAULT_FILTERS.len()); + assert_eq!(plain.last().map(String::as_str), Some("Hue Shift svgFilter.apply {\"name\":\"Hue Shift\"}")); + // The document's other filters come below them. + let with = ids(&items_for(vec!["Shift", "A (1)"])); + assert_eq!(with[..plain.len()], plain[..]); + assert_eq!(with[plain.len()..], ["—", "Shift svgFilter.apply {\"name\":\"Shift\"}", "A (1) svgFilter.apply {\"name\":\"A (1)\"}"]); + // A document's filter with a default's name is that default's entry. + let held = [ + SvgFilter { name: "Glow".into(), xml: String::new() }, + SvgFilter { name: "Shift".into(), xml: String::new() }, + SvgFilter { name: "glow".into(), xml: String::new() }, + ]; + assert_eq!(own_names(&held), ["Shift", "glow"]); let mut app = app(); assert!(!crate::menus::enabled(&app, "svgFilter.apply"), "nothing selected"); app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); @@ -423,6 +470,88 @@ mod tests { assert_eq!(crate::menus::display_label(&app, "svgFilter.apply", "Shift"), "Shift", "a filter's name as it is"); } + /// The steps in the active document's undo history. + fn steps(app: &VectorcraftApp) -> usize { + app.session.active().unwrap().history.undo.len() + } + + #[test] + fn a_default_is_listed_first_and_ok_copies_it_into_the_document() { + let mut app = app(); + app.session.execute("svgFilter.define", &json!({"xml": SHIFT})).unwrap(); + let id = app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + open(&mut app, &json!({})).unwrap(); + let mut d = app.ui.dialog.clone().unwrap(); + let (list, defaults) = filters(&app); + let names: Vec<&str> = list.iter().map(|f| f.filter.name.as_str()).collect(); + assert_eq!((defaults, names.len()), (DEFAULT_FILTERS.len(), DEFAULT_FILTERS.len() + 1)); + assert_eq!((names[0], names[defaults - 1], names[defaults]), ("Soft Blur", "Hue Shift", "Shift"), "the defaults, then the document's own"); + assert!(frame(&mut app, &mut d).iter().any(|t| t == "Soft Blur"), "a default's name, as it is"); + d.fields.insert("selected".into(), json!("Soft Shadow")); + assert!((SPEC.ok_enabled.unwrap())(&app, &d), "a default can be applied"); + let before = steps(&app); + confirm(&mut app, &d).unwrap(); + assert_eq!(steps(&app), before + 1, "one undo step"); + let doc = &app.session.active().unwrap().doc; + assert_eq!(doc.svg_filters.iter().map(|f| f.name.as_str()).collect::>(), ["Shift", "Soft Shadow"]); + let fx = &doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.effects; + assert_eq!((fx.len(), fx[0].params["name"].as_str()), (1, Some("Soft Shadow"))); + assert_eq!(fx[0].params["xml"].as_str(), default_filter("Soft Shadow").map(|f| f.xml)); + // Opened for that effect, the document's copy is selected; OK with another default puts it + // in the effect's place and copies it, in one step. + app.run("effect.dialog", json!({"effect": "svg.filter", "index": 0, "item": null})).unwrap(); + let mut d = app.ui.dialog.clone().unwrap(); + assert_eq!((d.str("selected").as_str(), d.str("editing").as_str()), ("Soft Shadow", "")); + d.fields.insert("selected".into(), json!("Invert")); + let before = steps(&app); + confirm(&mut app, &d).unwrap(); + assert_eq!(steps(&app), before + 1); + let doc = &app.session.active().unwrap().doc; + let fx = &doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.effects; + assert_eq!((fx.len(), fx[0].params["name"].as_str()), (1, Some("Invert")), "in its place, not added"); + assert_eq!(doc.svg_filters.len(), 3); + } + + /// Edit on a default opens its code, and Save keeps the edited copy in the document under the + /// default's name; an effect that names a default the document no longer holds selects it. + #[test] + fn an_edited_default_is_saved_in_the_document() { + let mut app = app(); + let id = app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + // Save, as its button does for the default being edited. + let edited = r#""#; + let r = app.run("svgFilter.define", json!({"xml": edited, "replace": "Thin"})).unwrap(); + assert_eq!(r["name"], "Thin"); + assert_eq!(filters(&app).0.iter().filter(|f| !f.default).map(|f| f.filter.xml.as_str()).collect::>(), [edited]); + assert_eq!(filters(&app).0.len(), DEFAULT_FILTERS.len(), "in the default's place"); + app.session.execute("svgFilter.apply", &json!({"name": "Thin"})).unwrap(); + // Deleted: the default is listed again, and the effect that names it selects the default. + app.session.execute("svgFilter.delete", &json!({"name": "Thin"})).unwrap(); + assert!(filters(&app).0.iter().all(|f| f.default)); + app.run("effect.dialog", json!({"effect": "svg.filter", "index": 0, "item": null})).unwrap(); + let d = app.ui.dialog.clone().unwrap(); + assert_eq!((d.str("selected").as_str(), d.str("missing").as_str(), d.str("editing").as_str()), ("Thin", "", "")); + confirm(&mut app, &d).unwrap(); + let doc = &app.session.active().unwrap().doc; + let fx = &doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.effects; + assert_eq!(fx[0].params["xml"].as_str(), default_filter("Thin").map(|f| f.xml), "the default again"); + // An applied filter with a default's name and other code opens as code to save. + let e = vectorcraft_doc::Effect { + id: "svg.filter".into(), + params: json!({"name": "Glow", "xml": ""}), + visible: true, + }; + app.session + .edit("Plant", |d, _| { + d.node_mut(vectorcraft_doc::NodeId(id)).unwrap().appearance.effects = vec![e]; + Ok(()) + }) + .unwrap(); + app.run("effect.dialog", json!({"effect": "svg.filter", "index": 0, "item": null})).unwrap(); + let d = app.ui.dialog.clone().unwrap(); + assert_eq!((d.str("editing").as_str(), d.str("selected").as_str()), ("new", "")); + } + #[test] fn new_saves_the_code_and_selects_the_filter() { let mut app = app(); diff --git a/crates/ui-egui/src/dialogs/svg_options.rs b/crates/ui-egui/src/dialogs/svg_options.rs index b477bb35c0..19737e4c16 100644 --- a/crates/ui-egui/src/dialogs/svg_options.rs +++ b/crates/ui-egui/src/dialogs/svg_options.rs @@ -269,30 +269,45 @@ fn artboards(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { }); } -/// The SVG the current options write for the first chosen artboard (read-only, selectable), -/// encoded again only when the options or the document change. +/// The SVG the current options write for the first chosen artboard, or under Export Selection for +/// the selection alone, cropped to it (read-only, selectable), encoded again only when the +/// options, the document or the selection change. fn code_view(app: &VectorcraftApp, ui: &mut egui::Ui, d: &Dialog) { let t = Tokens::get(ui.ctx()); let Some(st) = app.session.active() else { return }; + let selection = d.bool(super::export_as::SELECTION_FIELD); let mut opts = options(d); - if let Some(o) = opts.as_object_mut() - && let Some(r) = o.remove("range") - { - // The first artboard of the range (or the first one). - let first = r.as_str().and_then(|r| r.split([',', '-', '\u{2013}']).next()).and_then(|n| n.trim().parse::().ok()); - o.insert("artboard".into(), json!(first.map_or(0, |n| n.saturating_sub(1)))); + if let Some(o) = opts.as_object_mut() { + if selection { + // Export Selection writes one crop, without artboards to choose. + for k in vectorcraft_engine::cmd::fileio::ARTBOARD_PARAMS.iter().chain(&["useArtboards"]) { + o.remove(*k); + } + } else if let Some(r) = o.remove("range") { + // The first artboard of the range (or the first one). + let first = r.as_str().and_then(|r| r.split([',', '-', '\u{2013}']).next()).and_then(|n| n.trim().parse::().ok()); + o.insert("artboard".into(), json!(first.map_or(0, |n| n.saturating_sub(1)))); + } } - // One cached text, replaced when the document or the options change. + // One cached text, replaced when the document, the options or the selection change. let key = egui::Id::unique("svg-code"); // The read roots in force and the document's folder decide whether the text may be shown. let roots = vectorcraft_engine::file_access::current().map(|r| r.describe()); - let sig = egui::Id::unique((st.uid, st.revision, opts.to_string(), roots, st.path.as_deref())).value(); + let selected = selection.then(|| st.selection.objects.clone()); + let sig = egui::Id::unique((st.uid, st.revision, opts.to_string(), roots, st.path.as_deref(), selected)).value(); let code: Arc = match ui.ctx().data(|m| m.get_temp::<(u64, Arc)>(key)).filter(|(s, _)| *s == sig) { Some((_, c)) => c, None => { const MAX: usize = 200_000; - let encoded = vectorcraft_engine::cmd::fileio::check_linked_scripts("document.export", "svg", st) - .and_then(|()| vectorcraft_engine::cmd::fileio::encode_all(&st.doc, "svg", &json!({ "svg": opts }))); + let encoded = vectorcraft_engine::cmd::fileio::check_linked_scripts("document.export", "svg", st).and_then(|()| { + let params = json!({ "svg": opts }); + if selection { + let (doc, _) = vectorcraft_engine::cmd::fileio::selection_doc(st, "document.exportSelection", false)?; + vectorcraft_engine::cmd::fileio::encode_all(&doc, "svg", ¶ms) + } else { + vectorcraft_engine::cmd::fileio::encode_all(&st.doc, "svg", ¶ms) + } + }); let mut text = match encoded { // Shown as text whatever the file's encoding. Ok(enc) => enc @@ -431,6 +446,37 @@ mod tests { let _ = std::fs::remove_dir_all(root); } + /// Show Code under Export Selection shows the SVG that OK writes: the selection alone, cropped + /// to it with what its effects draw, not the whole document. + #[test] + fn show_code_under_export_selection_shows_the_selection() { + let (mut app, written) = app("/tmp/selection.svg"); + app.run("shape.rectangle", json!({"x": 70, "y": 40, "width": 20, "height": 20})).unwrap(); + app.run("effect.apply", json!({"effect": "stylize.dropShadow"})).unwrap(); + app.run("document.exportSelection", Value::Null).unwrap(); + let d = app.ui.dialog.as_mut().expect("SVG Options opened"); + assert_eq!(d.kind, KIND); + assert!(d.bool(super::super::export_as::SELECTION_FIELD)); + d.fields.insert("showCode".into(), json!(true)); + // The text the code view shows after two frames in one context. + let ctx = egui::Context::default(); + theme::install_fonts(&ctx); + for _ in 0..2 { + let mut out = ctx.run_ui(Default::default(), |ui| super::super::show(&mut app, ui.ctx())); + out.textures_delta.clear(); + } + let code = ctx.data(|m| m.get_temp::<(u64, Arc)>(egui::Id::unique("svg-code"))).map(|(_, c)| c.to_string()).unwrap_or_default(); + super::super::confirm(&mut app).unwrap(); + let svg = text(&written, 0); + assert_eq!(written.borrow()[0].0, "/tmp/selection.svg"); + assert_eq!(code, svg, "Show Code shows what OK writes"); + // The shadow reaches past the 21-point square, and the other rectangle is left out. + assert!(!svg.contains("viewBox=\"0 0 120 80\"") && !svg.contains("viewBox=\"0 0 21 21\""), "{svg}"); + assert!(!svg.contains("width=\"40\""), "{svg}"); + assert_eq!(svg.matches(" Vec { + let doc = &app.session.active().unwrap().doc; + doc.layers.iter().flat_map(|l| l.children().cloned().unwrap_or_default()).map(|n| matches!(n.kind, NodeKind::PlacedDocument(_))).collect() +} + +#[test] +fn import_pdf_pages_as_links_opens_each_page_linked() { + let dir = vectorcraft_testkit::TempDir::new("import-pdf-link-pages"); + let path = dir.join("three.pdf").to_string_lossy().into_owned(); + std::fs::write(&path, three_pages()).unwrap(); + let mut app = app(); + io::open_bytes(&mut app, &path, &three_pages(), Some(path.clone())).unwrap(); + assert_eq!(field(&app, "linkPages"), false, "off by default"); + frame(&mut app); + set(&mut app, "linkPages", json!(true)); + set(&mut app, "allPages", json!(false)); + set(&mut app, "range", json!("1, 3")); + frame(&mut app); + confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(artboard_widths(&app), [100.0, 300.0]); + assert_eq!(placed_pages(&app), [true, true]); + // A file given without its path, or opened with a password, can't link its pages: they open as art. + io::open_bytes(&mut app, "three.pdf", &three_pages(), None).unwrap(); + set(&mut app, "linkPages", json!(true)); + frame(&mut app); + confirm(&mut app).unwrap(); + assert_eq!(placed_pages(&app), [false, false, false]); + let two = pdf(&[PdfPage::new(10.0, 10.0, "0 g 0 0 5 5 re f"), PdfPage::new(20.0, 10.0, "0 g 0 0 5 5 re f")], Some("pw")); + let locked = dir.join("two.pdf").to_string_lossy().into_owned(); + std::fs::write(&locked, &two).unwrap(); + io::open_bytes(&mut app, &locked, &two, Some(locked.clone())).unwrap(); + set(&mut app, "password", json!("pw")); + confirm(&mut app).unwrap(); + set(&mut app, "linkPages", json!(true)); + frame(&mut app); + confirm(&mut app).unwrap(); + assert_eq!(placed_pages(&app), [false, false]); +} + #[test] fn single_page_pdfs_open_directly() { let mut app = app(); diff --git a/crates/ui-egui/src/dialogs/tests_perspective.rs b/crates/ui-egui/src/dialogs/tests_perspective.rs index 97255bd22d..38aaf67770 100644 --- a/crates/ui-egui/src/dialogs/tests_perspective.rs +++ b/crates/ui-egui/src/dialogs/tests_perspective.rs @@ -250,6 +250,26 @@ fn double_clicking_the_tool_opens_perspective_grid_options() { assert!(!app.session.prefs.perspective_widget.show); } +#[test] +fn perspective_grid_options_hold_automatic_plane_positioning() { + let mut app = app(); + app.run("tool.options", json!({"tool": "perspectiveGrid"})).unwrap(); + assert_eq!((field(&app, "anchorPoint"), field(&app, "gridlineIntersection")), (json!(true), json!(true)), "both on by default"); + frame(&mut app); + set(&mut app, "gridlineIntersection", json!(false)); + frame(&mut app); + super::confirm(&mut app).unwrap(); + assert_eq!(kind(&app), None); + let o = app.session.prefs.perspective_widget; + assert!(o.anchor_point && !o.gridline_intersection && o.show); + // The dialog opens on what was set, and a value that is not true or false is refused. + app.run("tool.options", json!({"tool": "perspectiveGrid"})).unwrap(); + assert_eq!(field(&app, "gridlineIntersection"), json!(false)); + set(&mut app, "anchorPoint", json!("off")); + assert!(super::confirm(&mut app).is_err()); + assert!(app.session.prefs.perspective_widget.anchor_point); +} + #[test] fn digit_keys_switch_planes_and_the_widget_follows_the_window() { let mut app = app(); diff --git a/crates/ui-egui/src/dialogs/tests_screens.rs b/crates/ui-egui/src/dialogs/tests_screens.rs index 1bd4f10afc..e26c82de60 100644 --- a/crates/ui-egui/src/dialogs/tests_screens.rs +++ b/crates/ui-egui/src/dialogs/tests_screens.rs @@ -1319,3 +1319,231 @@ fn the_dialog_builds_the_preset_list_again_only_when_the_presets_change() { let mine = list.as_array().unwrap().iter().find(|p| p["name"] == "Mine").unwrap(); assert_eq!(mine["settings"]["formats"][0]["format"], "pdf", "{list}"); } + +/// #7275: a double-click on an artboard name enters rename without leaving Export for Screens. +#[test] +fn same_frame_artboard_double_click_keeps_export_selection() { + for view in ["grid", "list"] { + for checked in [true, false] { + let (mut app, _) = app(2, true); + open(&mut app); + set(&mut app, "view", json!(view)); + let mut h = ScreensFrame::new(); + let out = h.settle(&mut app); + let name = app.session.active().unwrap().doc.artboards[0].name.clone(); + let at = screen_text_at(&out, &format!("1 {name}")); + if !checked { + h.click(&mut app, at); + h.time += 1.0; + h.settle(&mut app); + } + let before = field(&app, "boards"); + h.frame(&mut app, vec![egui::Event::PointerMoved(at)]); + let events = [true, false, true, false] + .into_iter() + .map(|pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }) + .collect(); + h.frame(&mut app, events); + h.settle(&mut app); + assert!(h.ctx.egui_wants_keyboard_input(), "{view}, checked={checked}"); + assert_eq!(field(&app, "boards"), before, "{view}, checked={checked}"); + } + } +} + +/// #7275: a double-click on an artboard name enters rename without leaving Export for Screens. +#[test] +fn switching_export_tabs_commits_an_artboard_name() { + for view in ["grid", "list"] { + let (mut app, log) = app(2, true); + open(&mut app); + set(&mut app, "view", json!(view)); + let mut h = ScreensFrame::new(); + let before = field(&app, "boards"); + let out = h.settle(&mut app); + let old = app.session.active().unwrap().doc.artboards[0].name.clone(); + let at = screen_text_at(&out, &format!("1 {old}")); + h.frame(&mut app, vec![egui::Event::PointerMoved(at)]); + for pressed in [true, false, true, false] { + h.frame( + &mut app, + vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }], + ); + } + h.settle(&mut app); + assert!(h.ctx.egui_wants_keyboard_input()); + h.frame(&mut app, vec![egui::Event::Text("Committed on tab".into())]); + h.click_label(&mut app, "Assets"); + assert_eq!(app.session.active().unwrap().doc.artboards[0].name, "Committed on tab"); + assert_eq!(field(&app, "tab"), "assets"); + assert_eq!(field(&app, "boards"), before); + assert!(log.borrow().is_empty()); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().doc.artboards[0].name, old); + } +} + +/// #7275: a double-click on an artboard name enters rename without leaving Export for Screens. +#[test] +fn double_clicking_an_artboard_name_in_export_for_screens_renames_it() { + for view in ["grid", "list"] { + let (mut app, log) = app(2, true); + open(&mut app); + set(&mut app, "view", json!(view)); + let mut h = ScreensFrame::new(); + let before = field(&app, "boards"); + let out = h.settle(&mut app); + let old = app.session.active().unwrap().doc.artboards[0].name.clone(); + let at = screen_text_at(&out, &format!("1 {old}")); + h.frame(&mut app, vec![egui::Event::PointerMoved(at)]); + for pressed in [true, false, true, false] { + h.frame( + &mut app, + vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }], + ); + } + h.settle(&mut app); + assert!(h.ctx.egui_wants_keyboard_input(), "double-clicking the artboard name must open an editable field"); + h.frame(&mut app, vec![egui::Event::Text("Renamed".into())]); + h.frame( + &mut app, + vec![egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }], + ); + h.settle(&mut app); + assert_eq!(app.session.active().unwrap().doc.artboards[0].name, "Renamed"); + assert_eq!(kind(&app), Some(export_for_screens::KIND)); + assert_eq!(field(&app, "boards"), before, "renaming must not change the checked artboards"); + assert!(log.borrow().is_empty(), "renaming must not export"); + // The real shortcut handler runs before the dialog body. Escape cancels only the name. + let out = h.settle(&mut app); + let at = screen_text_at(&out, "1 Renamed"); + h.frame(&mut app, vec![egui::Event::PointerMoved(at)]); + for pressed in [true, false, true, false] { + h.frame( + &mut app, + vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }], + ); + } + h.settle(&mut app); + h.frame(&mut app, vec![egui::Event::Text("Discard".into())]); + let key = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + h.time += 0.1; + let input = egui::RawInput { + events: vec![key], + time: Some(h.time), + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1100.0, 900.0))), + ..Default::default() + }; + let mut out = h.ctx.run_ui(input, |ui| { + crate::shortcuts::handle(&mut app, ui.ctx()); + super::show(&mut app, ui.ctx()); + }); + out.textures_delta.clear(); + h.settle(&mut app); + assert_eq!(kind(&app), Some(export_for_screens::KIND)); + assert_eq!(app.session.active().unwrap().doc.artboards[0].name, "Renamed"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().doc.artboards[0].name, old); + } +} + +/// #7275: the typed name goes to the artboard whose name was double-clicked, even when the +/// artboards change order (a command from the control channel or MCP) while it is typed. When that +/// artboard is deleted, the field closes and Escape closes the dialog. +#[test] +fn an_artboard_name_follows_its_artboard_while_it_is_typed() { + for view in ["grid", "list"] { + let (mut app, log) = app(3, true); + open(&mut app); + set(&mut app, "view", json!(view)); + let mut h = ScreensFrame::new(); + let names = |app: &VectorcraftApp| app.session.active().unwrap().doc.artboards.iter().map(|a| a.name.clone()).collect::>(); + let rename = |h: &mut ScreensFrame, app: &mut VectorcraftApp, label: &str| { + let out = h.settle(app); + let at = screen_text_at(&out, label); + h.frame(app, vec![egui::Event::PointerMoved(at)]); + for pressed in [true, false, true, false] { + h.frame( + app, + vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }], + ); + } + h.settle(app); + assert!(h.ctx.egui_wants_keyboard_input(), "{view}: the double-click opens the name"); + }; + let enter = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + rename(&mut h, &mut app, "2 Artboard 2"); + app.run("artboard.reorder", json!({"index": 1, "to": 0})).unwrap(); + h.frame(&mut app, vec![egui::Event::Text("Hero".into())]); + h.frame(&mut app, vec![enter]); + h.settle(&mut app); + assert_eq!(names(&app), ["Hero", "Artboard 1", "Artboard 3"], "{view}"); + assert_eq!(kind(&app), Some(export_for_screens::KIND), "{view}"); + assert!(log.borrow().is_empty(), "{view}: renaming must not export"); + // The artboard is deleted while its name is typed: the field closes, no other artboard + // takes the name, and Escape closes the dialog again. + rename(&mut h, &mut app, "2 Artboard 1"); + h.frame(&mut app, vec![egui::Event::Text("Gone".into())]); + app.run("artboard.delete", json!({"indices": [1]})).unwrap(); + h.settle(&mut app); + assert!(!h.ctx.egui_wants_keyboard_input(), "{view}: the field of a deleted artboard closes"); + assert_eq!(names(&app), ["Hero", "Artboard 3"], "{view}"); + let escape = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + h.time += 0.1; + let input = egui::RawInput { + events: vec![escape], + time: Some(h.time), + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1100.0, 900.0))), + ..Default::default() + }; + let mut out = h.ctx.run_ui(input, |ui| { + crate::shortcuts::handle(&mut app, ui.ctx()); + super::show(&mut app, ui.ctx()); + }); + out.textures_delta.clear(); + h.settle(&mut app); + assert_eq!(kind(&app), None, "{view}: Escape closes the dialog"); + assert_eq!(names(&app), ["Hero", "Artboard 3"], "{view}"); + assert!(log.borrow().is_empty(), "{view}: renaming must not export"); + } +} + +/// #7275: a name typed while another document becomes active (a command from the control channel +/// or MCP) renames no artboard in either document, and Escape closes the dialog. +#[test] +fn an_artboard_name_stays_with_its_document() { + let (mut app, log) = app(2, true); + app.run("file.new", json!({"width": 60, "height": 40, "artboards": 2})).unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + open(&mut app); + let mut h = ScreensFrame::new(); + let names = |app: &VectorcraftApp, i: usize| app.session.documents()[i].doc.artboards.iter().map(|a| a.name.clone()).collect::>(); + let out = h.settle(&mut app); + let at = screen_text_at(&out, "2 Artboard 2"); + h.frame(&mut app, vec![egui::Event::PointerMoved(at)]); + for pressed in [true, false, true, false] { + h.frame(&mut app, vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }]); + } + h.settle(&mut app); + assert!(h.ctx.egui_wants_keyboard_input(), "the double-click opens the name"); + h.frame(&mut app, vec![egui::Event::Text("Elsewhere".into())]); + app.run("document.activate", json!({"index": 1})).unwrap(); + let escape = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + h.time += 0.1; + let input = egui::RawInput { + events: vec![escape], + time: Some(h.time), + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1100.0, 900.0))), + ..Default::default() + }; + let mut out = h.ctx.run_ui(input, |ui| { + crate::shortcuts::handle(&mut app, ui.ctx()); + super::show(&mut app, ui.ctx()); + }); + out.textures_delta.clear(); + h.settle(&mut app); + assert_eq!(kind(&app), None, "Escape closes the dialog"); + assert_eq!(names(&app, 0), ["Artboard 1", "Artboard 2"]); + assert_eq!(names(&app, 1), ["Artboard 1", "Artboard 2"]); + assert!(log.borrow().is_empty(), "renaming must not export"); +} diff --git a/crates/ui-egui/src/display_profile.rs b/crates/ui-egui/src/display_profile.rs index 486489e6fe..b3f10ab27e 100644 --- a/crates/ui-egui/src/display_profile.rs +++ b/crates/ui-egui/src/display_profile.rs @@ -1,6 +1,8 @@ //! Preferences › Performance › Use Monitor Profile for Canvas: the canvas's art, its artboards' //! paper and the transparency grid are converted from sRGB into the ICC profile of the display -//! that shows most of the main window, as the last step before they are drawn. +//! that shows most of the main window, as the last step before they are drawn. Translucent art +//! and the anti-aliased edges of art over the paper or the grid are blended with it in sRGB first, +//! and the blend is converted ([`convert_over`]). //! //! The desktop app reads the display's profile on a background thread and hands the reading to //! [`DisplayProfile::report`], which checks the profile and builds its conversion table there. @@ -14,6 +16,7 @@ use std::sync::{Arc, RwLock}; use serde_json::{Value, json}; use vectorcraft_color::cms::display::DisplayTransform; pub use vectorcraft_color::cms::display::MAX_PROFILE_BYTES; +use vectorcraft_geom::{Affine, Point, Rect}; /// What the desktop app read for the display showing the main window. #[derive(Clone, Debug, PartialEq)] @@ -221,6 +224,264 @@ pub(crate) fn convert(t: Option<&DisplayTransform>, pixels: &mut [u8]) { t.apply_premultiplied(pixels); } +/// The document's paper under the canvas's art, which the canvas draws converted into the display +/// profile before the art: [`convert_over`] blends translucent art with it before converting. +/// The pasteboard and Outline's white canvas are interface colors and are not part of it. +#[derive(Clone, Debug, PartialEq)] +pub struct Backdrop { + /// View › Hide Artboards: the sRGB color of the paper that covers the whole canvas. + pub(crate) everywhere: Option<[u8; 3]>, + /// The artboards in the order they are drawn (the last on top), each with its paper's sRGB color. + pub(crate) artboards: Vec<(Rect, [u8; 3])>, + /// The transparency grid, which covers every artboard's paper: its two sRGB colors, and its cell + /// in screen points, counted from each artboard's top left corner. + pub(crate) grid: Option<([[u8; 3]; 2], f32)>, +} + +/// A color of the backdrop: in sRGB, and as the canvas shows it, converted. +#[derive(Clone, Copy, PartialEq)] +struct Paper { + srgb: [u8; 3], + shown: [u8; 3], +} + +/// An artboard of the backdrop, as [`Over`] looks it up. +struct Board { + /// Its rectangle in the document, normalized. + rect: Rect, + /// The corner the transparency grid's cells are counted from. + origin: Point, + paper: Paper, +} + +/// No artboard at a pixel of a row ([`Over::owners`]). +const NO_BOARD: u32 = u32::MAX; + +/// The first pixel at or after `x` that no artboard has taken yet, in the chain `next` (each +/// pixel's next candidate; a pixel not taken is its own), shortening the chain on the way. +fn untaken(next: &mut [u32], x: usize) -> usize { + let mut root = x; + while next[root] as usize != root { + root = next[root] as usize; + } + let mut at = x; + while next[at] as usize != root { + let n = next[at] as usize; + next[at] = root as u32; + at = n; + } + root +} + +/// [`Backdrop`] converted for a frame: what [`convert_over`] needs for each pixel. +struct Over<'a> { + t: &'a DisplayTransform, + /// The frame's pixels → the document. + to_doc: Affine, + everywhere: Option, + boards: Vec, + /// The grid's two colors and its cell in document points. + grid: Option<([Paper; 2], f64)>, +} + +impl<'a> Over<'a> { + /// For a frame of `width` × `height` pixels. None when the backdrop has no paper, or `view` + /// (the document → the pixels) can't be undone. The artboards that lie wholly outside the + /// frame are left out, so a row looks only at the artboards in view. + fn new(t: &'a DisplayTransform, b: &Backdrop, view: Affine, zoom: f64, (width, height): (usize, usize)) -> Option { + let det = view.determinant(); + if (b.everywhere.is_none() && b.artboards.is_empty()) || !det.is_finite() || det.abs() < 1e-12 { + return None; + } + let paper = |srgb: [u8; 3]| Paper { srgb, shown: t.apply8(srgb) }; + let to_doc = view.inverse(); + // The frame in the document, a pixel wider on every side than its pixels' centers reach. + let frame = to_doc.transform_rect_bbox(Rect::new(-1.0, -1.0, width as f64 + 1.0, height as f64 + 1.0)); + let in_view = |r: &Rect| r.x0 <= frame.x1 && frame.x0 <= r.x1 && r.y0 <= frame.y1 && frame.y0 <= r.y1; + let boards = b + .artboards + .iter() + .map(|&(r, color)| Board { rect: r.abs(), origin: r.origin(), paper: paper(color) }) + .filter(|b| in_view(&b.rect)) + .collect(); + let zoom = if zoom.is_finite() && zoom > 0.0 { zoom } else { 1.0 }; + Some(Self { + t, + to_doc, + everywhere: b.everywhere.map(paper), + boards, + grid: b.grid.map(|([a, c], cell)| ([paper(a), paper(c)], (f64::from(cell) / zoom).max(5e-10))), + }) + } + + /// The pixels `start..end` of the row whose centers lie at height `y` that artboard `b` covers, + /// their centers inside its rectangle. None when it covers none of the row's `width` pixels. + fn span(&self, b: &Board, y: f64, width: usize) -> Option<(usize, usize)> { + let at = self.to_doc * Point::new(0.0, y); + let [dx, dy, ..] = self.to_doc.as_coeffs(); + // Where along the row the document point stays within the rectangle, axis by axis. The + // rectangle holds its minimum edge and not its maximum one, so a row that runs toward the + // minimum holds its end there and not its start: each bound keeps whether it is held. + let (mut lo, mut hi) = ((f64::NEG_INFINITY, true), (f64::INFINITY, true)); + for (start, slope, min, max) in [(at.x, dx, b.rect.x0, b.rect.x1), (at.y, dy, b.rect.y0, b.rect.y1)] { + if slope == 0.0 { + if !(min <= start && start < max) { + return None; + } + continue; + } + let (t0, t1) = ((min - start) / slope, (max - start) / slope); + let (from, to) = if slope > 0.0 { ((t0, true), (t1, false)) } else { ((t1, false), (t0, true)) }; + // The tighter bound wins, and of two equal bounds the one not held. + if from.0 > lo.0 || (from.0 == lo.0 && !from.1) { + lo = from; + } + if to.0 < hi.0 || (to.0 == hi.0 && !to.1) { + hi = to; + } + } + // Pixel i's center is i + 0.5: the first pixel whose center is past `lo` (or on it, when + // held), up to the first one past `hi` (or on it, when not held). + let start = if lo.1 { (lo.0 - 0.5).ceil() } else { (lo.0 - 0.5).floor() + 1.0 }; + let end = if hi.1 { (hi.0 - 0.5).floor() + 1.0 } else { (hi.0 - 0.5).ceil() }; + let clamp = |v: f64| v.clamp(0.0, width as f64) as usize; + let (mut start, mut end) = (clamp(start), clamp(end)); + end = end.max(start); + // Rounding can put a bound a pixel away from where the rectangle's own test of each pixel's + // center puts it: move each end until the two agree. + let inside = |i: usize| b.rect.contains(self.to_doc * Point::new(i as f64 + 0.5, y)); + for _ in 0..2 { + if start < end && !inside(start) { + start += 1; + } else if start > 0 && inside(start - 1) { + start -= 1; + } + } + for _ in 0..2 { + if end > start && !inside(end - 1) { + end -= 1; + } else if end < width && inside(end) { + end += 1; + } + } + (start < end).then_some((start, end)) + } + + /// `owner` becomes the artboard on top at each of the `width` pixels of the row whose centers + /// lie at height `y` ([`NO_BOARD`] where there is none). Each pixel is taken once, by the + /// topmost artboard over it, so a row costs its width plus its artboards however they overlap. + fn owners(&self, y: f64, width: usize, owner: &mut Vec, next: &mut Vec) { + owner.clear(); + owner.resize(width, NO_BOARD); + next.clear(); + next.extend(0..=width as u32); + for (k, b) in self.boards.iter().enumerate().rev() { + let Some((start, end)) = self.span(b, y, width) else { continue }; + let mut x = untaken(next, start); + while x < end { + owner[x] = k as u32; + next[x] = x as u32 + 1; + x = untaken(next, x + 1); + } + } + } + + /// The paper at pixel `i` of the row at height `y`, whose artboard on top is `owner`. + fn paper_at(&self, owner: u32, i: usize, y: f64) -> Option { + let b = self.boards.get(owner as usize)?; + Some(match &self.grid { + Some((colors, cell)) => { + let p = self.to_doc * Point::new(i as f64 + 0.5, y); + let cells = ((p.x - b.origin.x) / cell).floor() + ((p.y - b.origin.y) / cell).floor(); + colors[usize::from(cells.rem_euclid(2.0) >= 1.0)] + } + None => b.paper, + }) + } + + /// Rows `first_row..` of the frame, `width` pixels each, in `pixels`. + fn rows(&self, pixels: &mut [u8], first_row: usize, width: usize) { + let mut last_px = ([0u8; 4], [0u8; 4]); + let mut last_mix = (([0u8; 4], [0u8; 3]), [0u8; 4]); + let (mut owner, mut next) = (Vec::new(), Vec::new()); + for (j, line) in pixels.chunks_exact_mut(width * 4).enumerate() { + let y = (first_row + j) as f64 + 0.5; + // Found for the row's first translucent pixel. + let mut found = false; + for (i, px) in line.as_chunks_mut::<4>().0.iter_mut().enumerate() { + let a = px[3]; + if a == 0 { + continue; + } + let paper = if a == 255 { + None + } else if self.everywhere.is_some() { + self.everywhere + } else { + if !found { + self.owners(y, width, &mut owner, &mut next); + found = true; + } + self.paper_at(owner[i], i, y) + }; + match paper { + Some(p) if last_mix.0 == (*px, p.srgb) => *px = last_mix.1, + Some(p) => { + let input = (*px, p.srgb); + // Drawn over the converted paper, the pixel shows `px` over the paper in sRGB, converted. + let under = 255 - u32::from(a); + let mix = |c: usize| (u32::from(px[c]) + (u32::from(p.srgb[c]) * under + 127) / 255).min(255) as u8; + let shown = self.t.apply8([mix(0), mix(1), mix(2)]); + for ((o, s), u) in px.iter_mut().zip(shown).zip(p.shown) { + let paper_part = ((u32::from(u) * under + 127) / 255) as i32; + *o = (i32::from(s) - paper_part).clamp(0, 255) as u8; + } + last_mix = (input, *px); + } + None if last_px.0 == *px => *px = last_px.1, + None => { + let input = *px; + self.t.apply_premultiplied(px); + last_px = (input, *px); + } + } + } + } + } +} + +/// [`convert`], with each translucent pixel over the paper or the transparency grid of `backdrop` +/// blended with it in sRGB before the conversion. The canvas draws the art over the paper +/// converted: such a pixel keeps its alpha and takes the color that, drawn over the converted +/// paper, shows the blend converted. Opaque and fully transparent pixels, and pixels over the +/// pasteboard, convert as [`convert`] converts them. The pixels are rows of `width`; `view` maps the +/// document to them, and the backdrop's `zoom` is the canvas's screen points per document point, +/// in which the grid's cells are measured. +pub(crate) fn convert_over(t: Option<&DisplayTransform>, pixels: &mut [u8], width: u32, view: Affine, backdrop: Option<(&Backdrop, f64)>) { + let Some(t) = t else { return }; + let width = width as usize; + let over = backdrop + .filter(|_| width > 0 && pixels.len().is_multiple_of(width * 4)) + .and_then(|(b, zoom)| Over::new(t, b, view, zoom, (width, pixels.len() / (width * 4)))); + let Some(over) = over else { return convert(Some(t), pixels) }; + #[cfg(not(target_arch = "wasm32"))] + { + const PIECE: usize = 256 * 1024 * 4; + let threads = std::thread::available_parallelism().map_or(1, usize::from).min(16); + if threads > 1 && pixels.len() > PIECE { + let rows = (pixels.len() / (width * 4)).div_ceil(threads); + let over = &over; + std::thread::scope(|scope| { + for (k, piece) in pixels.chunks_mut(rows * width * 4).enumerate() { + scope.spawn(move || over.rows(piece, k * rows, width)); + } + }); + return; + } + } + over.rows(pixels, 0, width); +} + /// The opaque or translucent color `c` through `t`. pub(crate) fn color32(t: Option<&DisplayTransform>, c: egui::Color32) -> egui::Color32 { let Some(t) = t else { return c }; @@ -308,4 +569,211 @@ pub(crate) mod tests { let [r, g, b] = t.apply8([255, 0, 0]); assert_eq!(color32(Some(&t), egui::Color32::RED), egui::Color32::from_rgb(r, g, b)); } + + /// What the canvas shows of pixel `px` drawn over the converted paper `under`, as egui blends it. + fn shown_over(px: [u8; 4], under: [u8; 3]) -> [u32; 3] { + let k = 255 - u32::from(px[3]); + [0, 1, 2].map(|i| u32::from(px[i]) + (u32::from(under[i]) * k + 127) / 255) + } + + /// `px` blended with the sRGB paper `paper`, converted. + fn blended(t: &DisplayTransform, px: [u8; 4], paper: [u8; 3]) -> [u8; 3] { + let k = 255 - u32::from(px[3]); + t.apply8([0, 1, 2].map(|i| (u32::from(px[i]) + (u32::from(paper[i]) * k + 127) / 255).min(255) as u8)) + } + + fn assert_near(got: [u32; 3], want: [u8; 3], at: &str) { + assert!((0..3).all(|i| got[i].abs_diff(u32::from(want[i])) <= 1), "{at}: {got:?} shown, {want:?} wanted"); + } + + /// One row of `n` pixels, every one `px`. + fn row(n: usize, px: [u8; 4]) -> Vec { + px.repeat(n) + } + + #[test] + fn translucent_pixels_over_the_paper_are_blended_before_they_are_converted() { + let t = DisplayTransform::from_icc(&p3()).unwrap(); + let half_red = [128, 0, 0, 128]; + let b = Backdrop { everywhere: None, artboards: vec![(Rect::new(0.0, 0.0, 10.0, 1.0), [255; 3])], grid: None }; + let mut px = row(20, half_red); + px[12..16].copy_from_slice(&[255, 0, 0, 255]); + px[16..20].copy_from_slice(&[0; 4]); + convert_over(Some(&t), &mut px, 20, Affine::IDENTITY, Some((&b, 1.0))); + let at = |i: usize| -> [u8; 4] { px[i * 4..i * 4 + 4].try_into().unwrap() }; + let white = t.apply8([255; 3]); + assert_near(shown_over(at(0), white), blended(&t, half_red, [255; 3]), "over the paper"); + // Converted alone and drawn over the converted paper, the pixel shows another color. + let mut alone = half_red; + t.apply_premultiplied(&mut alone); + let want = blended(&t, half_red, [255; 3]); + assert!((0..3).any(|i| shown_over(alone, white)[i].abs_diff(u32::from(want[i])) > 2), "{alone:?}"); + assert_eq!(at(0)[3], 128, "the alpha is kept"); + // Opaque and empty pixels, and pixels over the pasteboard, convert as before. + let red = t.apply8([255, 0, 0]); + assert_eq!((at(3), at(4)), ([red[0], red[1], red[2], 255], [0; 4])); + assert_eq!(at(15), alone, "over the pasteboard"); + // Without a backdrop, and without a profile, as before. + let mut plain = row(20, half_red); + convert_over(Some(&t), &mut plain, 20, Affine::IDENTITY, None); + assert_eq!(plain, row(20, alone)); + let mut srgb = row(20, half_red); + convert_over(None, &mut srgb, 20, Affine::IDENTITY, Some((&b, 1.0))); + assert_eq!(srgb, row(20, half_red)); + } + + #[test] + fn the_backdrop_is_found_through_the_view() { + let t = DisplayTransform::from_icc(&p3()).unwrap(); + // Papers far apart: a pixel blended with the wrong one shows a color several levels off. + let half = [128, 0, 0, 128]; + let (light, dark) = ([255, 230, 230], [40, 40, 30]); + // A later artboard is drawn over an earlier one. + let b = Backdrop { + everywhere: None, + artboards: vec![(Rect::new(0.0, 0.0, 100.0, 100.0), light), (Rect::new(50.0, 0.0, 100.0, 100.0), dark)], + grid: None, + }; + // A view turned a quarter clockwise and moved: pixel x runs down the document's y axis. + let view = Affine::translate((10.0, 0.0)) * Affine::rotate(std::f64::consts::FRAC_PI_2) * Affine::translate((-20.0, -60.0)); + let mut px = row(10, half); + convert_over(Some(&t), &mut px, 10, view, Some((&b, 1.0))); + // Pixel (2.5, 0.5) is document point (20.5, 67.5): on the first artboard only. + let at = |i: usize| -> [u8; 4] { px[i * 4..i * 4 + 4].try_into().unwrap() }; + assert_near(shown_over(at(2), t.apply8(light)), blended(&t, half, light), "on the first artboard"); + let view = Affine::translate((-60.0, -5.0)); + let mut px = row(10, half); + convert_over(Some(&t), &mut px, 10, view, Some((&b, 1.0))); + let at = |i: usize| -> [u8; 4] { px[i * 4..i * 4 + 4].try_into().unwrap() }; + assert_near(shown_over(at(0), t.apply8(dark)), blended(&t, half, dark), "where the second covers the first"); + // View › Hide Artboards: the paper everywhere. + let all = Backdrop { everywhere: Some(dark), artboards: vec![], grid: None }; + let mut px = row(10, half); + convert_over(Some(&t), &mut px, 10, Affine::translate((-5000.0, 0.0)), Some((&all, 1.0))); + assert_near(shown_over(px[..4].try_into().unwrap(), t.apply8(dark)), blended(&t, half, dark), "Hide Artboards"); + // Overlapping artboards under a turned and scaled view, against a direct lookup of the + // artboard on top whose rectangle holds each pixel's center. + let boards: Vec<(Rect, [u8; 3])> = (0..12u8) + .map(|k| { + let (x, y) = (f64::from(k) * 7.0, f64::from(k % 3) * 9.0); + (Rect::new(x, y, x + 15.0, y + 20.0), if k % 2 == 0 { [255, 255, 255 - k] } else { [20 + k, 20, 30] }) + }) + .collect(); + let check = |boards: &[(Rect, [u8; 3])], view: Affine, (w, h): (usize, usize)| { + let b = Backdrop { everywhere: None, artboards: boards.to_vec(), grid: None }; + let mut px = row(w * h, half); + convert_over(Some(&t), &mut px, w as u32, view, Some((&b, 1.0))); + let to_doc = view.inverse(); + let mut on_paper = 0; + for i in 0..w * h { + let p = to_doc * Point::new((i % w) as f64 + 0.5, (i / w) as f64 + 0.5); + let mut want = half.to_vec(); + match boards.iter().rev().find(|(r, _)| r.contains(p)) { + Some(&(_, paper)) => { + let one = Backdrop { everywhere: Some(paper), artboards: vec![], grid: None }; + convert_over(Some(&t), &mut want, 1, Affine::IDENTITY, Some((&one, 1.0))); + on_paper += 1; + } + None => t.apply_premultiplied(&mut want), + } + assert_eq!(&px[i * 4..i * 4 + 4], &want[..], "pixel {i} at {p:?} through {view:?}"); + } + assert!(on_paper > 100 && on_paper < w * h, "{on_paper} pixels on the artboards"); + }; + check(&boards, Affine::rotate(0.3) * Affine::scale(1.7) * Affine::translate((5.0, -3.0)), (64, 48)); + // Rows that run backward across the artboards, with pixel centers on their edges: an edge + // at the minimum is on the artboard, one at the maximum is not. + check(&boards, Affine::new([-1.0, 0.0, 0.0, 1.0, 92.5, 0.0]), (96, 44)); + check(&boards, Affine::new([-1.0, 0.0, 0.0, -1.0, 92.5, 40.5]), (96, 44)); + // A sheared view where a computed bound falls on a pixel center that rounding puts just + // outside the artboard: the pixel's own center decides. + check(&[(Rect::new(-100.0, -2.0, 100.0, 100.0), [40, 40, 30])], Affine::new([3.0, 1.5, 0.1, 0.5, -0.3, 0.0]), (64, 48)); + } + + #[test] + fn the_transparency_grid_is_blended_cell_by_cell() { + let t = DisplayTransform::from_icc(&p3()).unwrap(); + let half = [128, 0, 0, 128]; + // Far apart, so that a pixel blended with the other cell's color shows several levels off. + let (light, dark) = ([255; 3], [40; 3]); + // Cells of 10 points from the artboard's corner at (5, 0), here 1 pixel a point. + let b = Backdrop { everywhere: None, artboards: vec![(Rect::new(5.0, 0.0, 65.0, 20.0), [255, 0, 0])], grid: Some(([light, dark], 10.0)) }; + let check = |zoom: f64, cells: [(usize, [u8; 3]); 3]| { + let mut px = row(60, half); + convert_over(Some(&t), &mut px, 60, Affine::IDENTITY, Some((&b, zoom))); + for (i, paper) in cells { + assert_near( + shown_over(px[i * 4..i * 4 + 4].try_into().unwrap(), t.apply8(paper)), + blended(&t, half, paper), + &format!("pixel {i} at {zoom}"), + ); + } + }; + check(1.0, [(6, light), (16, dark), (26, light)]); + // At 200% a cell is 5 document points. + check(2.0, [(6, light), (11, dark), (16, light)]); + } + + #[test] + fn large_frames_blend_the_same_on_several_threads() { + let t = DisplayTransform::from_icc(&p3()).unwrap(); + let b = Backdrop { + everywhere: None, + artboards: vec![(Rect::new(0.0, 0.0, 500.0, 900.0), [240, 230, 220])], + grid: Some(([[255; 3], [200; 3]], 8.0)), + }; + let (w, h) = (1000, 1000); + let mut big: Vec = (0..w * h * 4).map(|i| (i * 7 % 251) as u8).collect(); + for px in big.as_chunks_mut::<4>().0 { + let a = px[3]; + for c in &mut px[..3] { + *c = (*c).min(a); + } + } + let mut one = big.clone(); + Over::new(&t, &b, Affine::IDENTITY, 1.0, (w, h)).unwrap().rows(&mut one, 0, w); + convert_over(Some(&t), &mut big, w as u32, Affine::IDENTITY, Some((&b, 1.0))); + assert_eq!(big, one); + } + + #[test] + fn artboards_outside_the_frame_are_not_looked_up() { + let t = DisplayTransform::from_icc(&p3()).unwrap(); + let half = [128, 0, 0, 128]; + // A row of 1,000 artboards 30 points apart, each 20 wide and 40 high. + let artboards: Vec<(Rect, [u8; 3])> = (0..1000u32) + .map(|k| { + let x = f64::from(k) * 30.0; + (Rect::new(x, 0.0, x + 20.0, 40.0), [255 - (k % 200) as u8, 240, 230]) + }) + .collect(); + let b = Backdrop { everywhere: None, artboards: artboards.clone(), grid: None }; + // A turned frame of 64 × 48 pixels over the artboards near x = 15,000. + let view = Affine::rotate(0.4) * Affine::translate((-15_000.0, -5.0)); + let (w, h) = (64, 48); + let over = Over::new(&t, &b, view, 1.0, (w, h)).unwrap(); + assert!((1..=4).contains(&over.boards.len()), "{} artboards kept", over.boards.len()); + // Each pixel still uses the artboard its center is on. + let mut px = row(w * h, half); + convert_over(Some(&t), &mut px, w as u32, view, Some((&b, 1.0))); + let to_doc = view.inverse(); + let mut on_paper = 0; + for i in 0..w * h { + let p = to_doc * Point::new((i % w) as f64 + 0.5, (i / w) as f64 + 0.5); + let mut want = half.to_vec(); + match artboards.iter().rev().find(|(r, _)| r.contains(p)) { + Some(&(_, paper)) => { + let one = Backdrop { everywhere: Some(paper), artboards: vec![], grid: None }; + convert_over(Some(&t), &mut want, 1, Affine::IDENTITY, Some((&one, 1.0))); + on_paper += 1; + } + None => t.apply_premultiplied(&mut want), + } + assert_eq!(&px[i * 4..i * 4 + 4], &want[..], "pixel {i} at {p:?}"); + } + assert!(on_paper > 100 && on_paper < w * h, "{on_paper} pixels on the artboards"); + // A frame over none of the artboards keeps none, and converts as without a backdrop. + let away = Affine::translate((0.0, -500.0)); + assert_eq!(Over::new(&t, &b, away, 1.0, (w, h)).map(|o| o.boards.len()), Some(0)); + } } diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 8db6de2f96..377df81a72 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -317,7 +317,7 @@ pub static LANGUAGES: [LangInfo; 29] = [ complete_menus: true, catalog: OnceLock::new(), }, - // Danish; every `da-*` locale (`da-DK`, `da_DK.UTF-8`…) resolves here. + // Danish: the whole interface and the status and error messages; every `da-*` locale (`da-DK`, `da_DK.UTF-8`…) resolves here. LangInfo { code: "da", name: "Dansk", diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 8cb531e411..7b487589f4 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -13,6 +13,7 @@ Edge Brightness Яркост на ръба Smoothness Гладкост Radial Blur… Лъчезарно размазване… + Blur Center Център на размазването Smart Blur… Интелигентно размазване… Sharpen Изостряне Unsharp Mask… Контурна маска… @@ -630,6 +631,7 @@ font-technology Variable Променливи Copy All Styles Копиране на всички стилове Copy Color Value (Hex) Копиране на цветова стойност (Hex) Copy Fonts Used in the Document Копиране на шрифтовете, използвани в документа + Copy Info Копиране на информация Copy Links Копиране на връзките Copy Selected Style Копиране на избрания стил Copy to User Defined Копиране в потребителски @@ -889,6 +891,9 @@ font-technology Variable Променливи The selected character's font is not available. Шрифтът на избрания знак не е наличен. No alternates for the selected character. Няма алтернативи за избрания знак. Double-click to replace Двойно щракване за замяна + Click to replace Щракване за замяна + Show all alternates in the Glyphs panel Показване на всички алтернативи в панела „Глифи“ + Show Character Alternates Показване на алтернативите на знака Select one character with the Type tool first. Първо изберете един знак с инструмента „Текст“. {glyph} is a glyph of {font}, not of the font the selected text is set in ({text_font}). {glyph} е глиф на {font}, а не на шрифта, с който е зададен избраният текст ({text_font}). {glyph} belongs to {base} (U+{base_code}) {place}; your selection is {sel} (U+{code}). {glyph} принадлежи на {base} (U+{base_code}) {place}; избраният от вас знак е {sel} (U+{code}). @@ -1284,6 +1289,7 @@ font-technology Variable Променливи Format Формат Format Options Опции за формат Format Settings Настройки на формата + Format Settings… Настройки на формата… Format: Формат: Formats: Формати: Fractional Widths Дробни ширини @@ -1630,6 +1636,7 @@ font-technology Variable Променливи Images: Изображения: Import Keyboard Shortcuts… Импортиране на клавишни комбинации… Import PDF Импортиране на PDF + Import PDF pages as links Импортиране на страниците на PDF като връзки Import PDF Presets Импортиране на PDF предварителни настройки Import Perspective Grid Presets Импортиране на предварителни настройки за перспективна мрежа Import Print Presets Импортиране на предварителни настройки за печат @@ -3348,6 +3355,18 @@ digits Malayalam Малаялам Smart Guides (View → Smart Guides) Интелигентни водачи (Изглед → Интелигентни водачи) Smart Guides (⌘U) Интелигентни водачи (⌘U) Smart Punctuation… Интелигентна пунктуация… + Smart Punctuation Интелигентна пунктуация + ff, fi, ffi Ligatures Лигатури ff, fi, ffi + ff, fl, ffl Ligatures Лигатури ff, fl, ffl + Smart Quotes Интелигентни кавички + Smart Spaces Интелигентни интервали + En, Em Dashes Средни и дълги тирета + Ellipses Многоточия + Expert Fractions Експертни дроби + Replace In Замяна в + Selected Text Only Само избрания текст + Entire Document Целия документ + Report Results Отчет за резултатите Smooth Гладък Corner Ъгъл Relative Относителен @@ -3378,6 +3397,7 @@ digits Malayalam Малаялам Solid Плътен Sort by Kind Сортиране по вид Sort by Name Сортиране по име + Sort by Size Сортиране по размер Sort by Status Сортиране по състояние Source code on GitHub Изходен код в GitHub Source Sans 3 Source Sans 3 @@ -4163,6 +4183,7 @@ axis Both И двете Stop the script and undo what it did? Then quit again. Да се спре ли скриптът и да се отменят ли промените му? След това излезте отново. This script has added a great many objects. Continue, or stop it and undo what it did? Този скрипт добави изключително много обекти. Да продължи ли, или да се спре и да се отменят промените му? @msg Copied the script report Копиран е отчетът за скрипта +@msg Copied the link info Информацията за връзката е копирана @msg Corners edits the corners of a path Ъглите редактират ъглите на пътя @msg Couldn't copy to the system clipboard: {e} Неуспешно копиране в системния клипборд: {e} @msg Couldn't open {name}: {e} Неуспешно отваряне на {name}: {e} @@ -6860,11 +6881,20 @@ breakText Glyphs Глифи Open Tutorial Sample Отваряне на примерния файл на урока Finish Tutorial Завършване на урок Next Tutorial Следващ урок + Show Learn Tab Показване на раздел в Обучение + Show Skill Показване на умение + Back One Level Едно ниво назад Back to Skills Обратно към уменията @msg tutorial `{id}` has no practice sample урокът `{id}` няма примерен файл за упражнение @msg open the practice sample of `{id}` first (see learn.openSample) първо отворете примерния файл за упражнение на `{id}` (вижте learn.openSample) @msg finish `{id}` first (see learn.finish) първо завършете `{id}` (вижте learn.finish) @msg `{id}` is the last tutorial in its skill `{id}` е последният урок в своето умение + Reset progress Нулиране на напредъка + Mark Tutorial Step Отбелязване на стъпка от урока + Reset Learn Progress Нулиране на напредъка в обучението +@msg missing `step` (see learn.show) липсва `step` (вижте learn.show) +@msg `step` must be a step number from 0 to {last} `step` трябва да е номер на стъпка от 0 до {last} +@msg `{id}` is finished (see learn.resetProgress) `{id}` е завършен (вижте learn.resetProgress) # Deferred plug-in effects Refresh Deferred Effects Обновяване на отложените ефекти @@ -6887,3 +6917,6 @@ breakText Glyphs Глифи Grommets Капси Grommet Inset Отстъп на капсите от ръба Diameter Диаметър + Nest Shapes… Подреждане на форми… + Nest Shapes Подреждане на форми + Roll Ролка diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 57790c64c6..3850e2d812 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -421,6 +421,18 @@ Title Case Svaka Riječ Velikim Slovom Sentence case Veliko početno slovo rečenice Smart Punctuation… Pametna interpunkcija… + Smart Punctuation Pametna interpunkcija + ff, fi, ffi Ligatures Ligature ff, fi, ffi + ff, fl, ffl Ligatures Ligature ff, fl, ffl + Smart Quotes Pametni navodnici + Smart Spaces Pametni razmaci + En, Em Dashes Srednje i duge crtice + Ellipses Tri tačke + Expert Fractions Stručni razlomci + Replace In Zamijeni u + Selected Text Only Samo odabrani tekst + Entire Document Cijeli dokument + Report Results Izvještaj o rezultatima Create Outlines Kreiraj obrise Optical Margin Alignment Optičko poravnanje margina Dynamic Text Dinamički tekst @@ -959,6 +971,7 @@ Free Transform Slobodna transformacija Perspective Distort Izobličenje perspektive Radial Blur… Radijalno zamućenje… + Blur Center Središte zamućenja Smart Blur… Pametno zamućenje… Sharpen Izoštri Unsharp Mask… Maska izoštravanja… @@ -1701,6 +1714,9 @@ digits Malayalam Malajalam The selected character's font is not available. Font odabranog znaka nije dostupan. No alternates for the selected character. Nema alternativa za odabrani znak. Double-click to replace Dvostruki klik za zamjenu + Click to replace Klik za zamjenu + Show all alternates in the Glyphs panel Prikaži sve alternative u panelu Glifovi + Show Character Alternates Prikaži alternative znaka Select one character with the Type tool first. Prvo odaberite jedan znak alatom za tekst. {glyph} is a glyph of {font}, not of the font the selected text is set in ({text_font}). {glyph} je glif fonta {font}, a ne fonta kojim je postavljen odabrani tekst ({text_font}). {glyph} belongs to {base} (U+{base_code}) {place}; your selection is {sel} (U+{code}). {glyph} pripada znaku {base} (U+{base_code}) {place}; vaš odabir je {sel} (U+{code}). @@ -2246,6 +2262,7 @@ digits Malayalam Malajalam @msg paths entry {i} needs path and ids (object ids no other entry has) unos {i} u paths treba path i ids (ID-ove objekata koje nema nijedan drugi unos) @msg scope missingInFolder takes path: the folder of that file is searched for the other missing links scope missingInFolder uzima path: u folderu te datoteke traže se ostale nedostajuće veze Show Missing Prikaži nedostajuće + Sort by Size Sortiraj po veličini Sort by Status Sortiraj po statusu Clear Overrides Očisti zamjene Create New {kind} Style Kreiraj novi {kind} stil @@ -2500,6 +2517,7 @@ digits Malayalam Malajalam Export Asset Izvezi resurs Export to: Izvezi u: Format Settings Postavke formata + Format Settings… Postavke formata… Formats: Formati: Full Document Cijeli dokument Include Bleed Uključi napust @@ -2598,6 +2616,7 @@ digits Malayalam Malajalam e.g. 1-3, 5 npr. 1-3, 5 First Page Prva stranica Import PDF Uvezi PDF + Import PDF pages as links Uvezi stranice PDF-a kao veze Last Page Posljednja stranica Next Page Sljedeća stranica of {count} od {count} @@ -2681,6 +2700,7 @@ digits Malayalam Malajalam Transparent Background Prozirna pozadina Choose… Odaberi… Copy Fonts Used in the Document Kopiraj fontove korištene u dokumentu + Copy Info Kopiraj informacije Copy Links Kopiraj veze Create Report Kreiraj izvještaj Fonts whose licence doesn't allow embedding are not copied. Fontovi čija licenca ne dozvoljava ugrađivanje ne kopiraju se. @@ -4528,6 +4548,7 @@ imageTrace Outline Obris Stop the script and undo what it did? Then quit again. Zaustaviti skriptu i poništiti ono što je uradila? Zatim ponovo izađite. This script has added a great many objects. Continue, or stop it and undo what it did? Ova skripta je dodala veoma mnogo objekata. Nastaviti, ili je zaustaviti i poništiti ono što je uradila? @msg Copied the script report Izvještaj skripte kopiran +@msg Copied the link info Informacije o vezi kopirane @msg Corners edits the corners of a path Uglovi uređuje uglove putanje @msg Couldn't copy to the system clipboard: {e} Nije moguće kopirati u sistemski međuspremnik: {e} @msg Couldn't open {name}: {e} Nije moguće otvoriti {name}: {e} @@ -6170,7 +6191,7 @@ axis Y Axis Y osa @plural Result: {n}|Results: {n} Rezultat: {n}|Rezultati: {n}|Rezultati: {n} @msg select one object odaberite jedan objekat @msg Global Edit works on paths, compound paths, symbol instances and groups of them Globalno uređivanje radi na putanjama, složenim putanjama, instancama simbola i njihovim grupama -@msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again nisu pronađeni slični objekti (rotirane ili zrcaljene kopije se ne podudaraju); promijenite opcije globalnog uređivanja i pokušajte ponovo +@msg no similar objects found (reflected copies are not matched); change the Global Edit Options and try again nisu pronađeni slični objekti (zrcaljene kopije se ne podudaraju); promijenite opcije globalnog uređivanja i pokušajte ponovo @msg Global Edit is off Globalno uređivanje je isključeno @msg only an object of the Global Edit other than the one it started from can be left out iz globalnog uređivanja može se isključiti samo objekt koji nije onaj od kojeg je počelo @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all ili raspon poput 1, 3-5, a ne {v} @@ -6913,11 +6934,20 @@ shape Open Otvoren Open Tutorial Sample Otvori uzorak tutorijala Finish Tutorial Završi tutorijal Next Tutorial Sljedeći tutorijal + Show Learn Tab Prikaži karticu u Učenju + Show Skill Prikaži vještinu + Back One Level Jedan nivo nazad Back to Skills Nazad na vještine @msg tutorial `{id}` has no practice sample tutorijal `{id}` nema uzorak za vježbu @msg open the practice sample of `{id}` first (see learn.openSample) prvo otvorite uzorak za vježbu tutorijala `{id}` (vidi learn.openSample) @msg finish `{id}` first (see learn.finish) prvo završite `{id}` (vidi learn.finish) @msg `{id}` is the last tutorial in its skill `{id}` je posljednji tutorijal u svojoj vještini + Reset progress Vrati napredak na početno + Mark Tutorial Step Označi korak tutorijala + Reset Learn Progress Vrati napredak učenja na početno +@msg missing `step` (see learn.show) nedostaje `step` (vidi learn.show) +@msg `step` must be a step number from 0 to {last} `step` mora biti broj koraka od 0 do {last} +@msg `{id}` is finished (see learn.resetProgress) `{id}` je završen (vidi learn.resetProgress) # Deferred plug-in effects Refresh Deferred Effects Osvježi odgođene efekte @@ -6940,3 +6970,6 @@ shape Open Otvoren Grommets Ušice Grommet Inset Udaljenost ušica od ruba Diameter Prečnik + Nest Shapes… Slaganje oblika… + Nest Shapes Slaganje oblika + Roll Rolna diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 882adefa39..d962f8afc4 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -930,6 +930,7 @@ antiAlias Sharp Nítid Copy Guide Copia la guia Copy in Perspective Copia en perspectiva Copy into the document's folder Copia a la carpeta del document + Copy Info Copia la informació Copy Links Copia els enllaços Copy only fonts you own or are licensed to install. Copia només els tipus de lletra que tinguis o que tinguis llicència per instal·lar. Copy Report Copia l’informe @@ -1307,6 +1308,9 @@ antiAlias Sharp Nítid The selected character's font is not available. El tipus de lletra del caràcter seleccionat no està disponible. No alternates for the selected character. No hi ha alternatives per al caràcter seleccionat. Double-click to replace Feu doble clic per substituir + Click to replace Feu clic per substituir + Show all alternates in the Glyphs panel Mostra totes les alternatives al tauler Glifs + Show Character Alternates Mostra les alternatives del caràcter Select one character with the Type tool first. Selecciona primer un caràcter amb l’eina de text. {glyph} is a glyph of {font}, not of the font the selected text is set in ({text_font}). {glyph} és un glif de {font}, no del tipus de lletra amb què està escrit el text seleccionat ({text_font}). {glyph} belongs to {base} (U+{base_code}) {place}; your selection is {sel} (U+{code}). {glyph} pertany a {base} (U+{base_code}) {place}; la teva selecció és {sel} (U+{code}). @@ -1794,6 +1798,7 @@ digits Malayalam Malaiàlam Format Format Format Options Opcions de format Format Settings Configuració de format + Format Settings… Configuració de format… Format: Format: Formats: Formats: Fractional Widths Amplades fraccionàries @@ -2101,6 +2106,7 @@ digits Malayalam Malaiàlam Import Library… Importa biblioteca… Import Matches Importa coincidències Import PDF Importa PDF + Import PDF pages as links Importa les pàgines del PDF com a enllaços Import PDF Presets Importa preajustos de PDF Import Perspective Grid Presets Importa preajustos de quadrícula de perspectiva Import Print Presets Importa preajustos d’impressió @@ -3391,6 +3397,7 @@ digits Malayalam Malaiàlam Radial Radial Radial Blur Desenfocament radial Radial Blur… Desenfocament radial… + Blur Center Centre del desenfocament Radial Dividers: Divisors radials: Radial Glows Resplendors radials Radial Gradient Degradat radial @@ -4372,6 +4379,18 @@ digits Malayalam Malaiàlam Smart Guides (View → Smart Guides) Guies intel·ligents (Visualitza → Guies intel·ligents) Smart Guides (⌘U) Guies intel·ligents (⌘U) Smart Punctuation… Puntuació intel·ligent… + Smart Punctuation Puntuació intel·ligent + ff, fi, ffi Ligatures Lligadures ff, fi, ffi + ff, fl, ffl Ligatures Lligadures ff, fl, ffl + Smart Quotes Cometes intel·ligents + Smart Spaces Espais intel·ligents + En, Em Dashes Ratlles en i em + Ellipses Punts suspensius + Expert Fractions Fraccions expertes + Replace In Reemplaça a + Selected Text Only Només el text seleccionat + Entire Document Tot el document + Report Results Informa dels resultats Smooth Suavitza Smooth Color Color suau Smooth Tool Eina de suavitzat @@ -4407,6 +4426,7 @@ digits Malayalam Malaiàlam Sort by Luminance Ordena per lluminositat Sort by Name Ordena per nom Sort by Popularity Ordena per popularitat + Sort by Size Ordena per mida Sort by Status Ordena per estat Sort Swatches Ordena les mostres Source code on GitHub Codi font a GitHub @@ -5579,6 +5599,7 @@ digits Malayalam Malaiàlam @msg there is no script engine named {name} no hi ha cap motor d'scripts anomenat {name} @msg Running a script S'està executant un script @msg Copied the script report S’ha copiat l’informe de l’script +@msg Copied the link info S’ha copiat la informació de l’enllaç @msg Corners edits the corners of a path Cantonades edita les cantonades d’un traçat @msg could not decode image: {0} no s’ha pogut descodificar la imatge: {0} @msg Couldn't copy to the system clipboard: {e} No s’ha pogut copiar al porta-retalls del sistema: {e} @@ -5866,7 +5887,7 @@ digits Malayalam Malaiàlam @msg no segment {segment} on line {line} no hi ha el segment {segment} a la línia {line} @msg no selected slice in the image: select slices, or save all of them no hi ha cap tall seleccionat a la imatge: seleccioneu talls o deseu-los tots @msg no selection bounds no hi ha límits de selecció -@msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again no s’ha trobat cap objecte similar (les còpies girades o reflexades no coincideixen); canvieu les opcions d’edició global i torneu-ho a provar +@msg no similar objects found (reflected copies are not matched); change the Global Edit Options and try again no s’ha trobat cap objecte similar (les còpies reflexades no coincideixen); canvieu les opcions d’edició global i torneu-ho a provar @msg Global Edit is off L’edició global no està activa @msg only an object of the Global Edit other than the one it started from can be left out només es pot excloure un objecte de l’edició global que no sigui aquell amb què va començar @msg no slice selected no hi ha cap tall seleccionat @@ -6332,6 +6353,8 @@ digits Malayalam Malaiàlam @msg the spine has no segments l’espina no té segments @msg the stroke has no weight el traç no té gruix @msg the SVG's elements are nested more than {0} deep els elements de l’SVG estan imbricats a més de {0} nivells de profunditat +@msg the SVG's style sheets take too long to match fer coincidir els fulls d’estil de l’SVG triga massa +@msg the SVG's styles expand to more than {0} MB els estils de l’SVG s’expandeixen a més de {0} MB @msg the target layer is locked or hidden la capa de destinació està blocada o amagada @msg the thumbnail image is malformed la imatge de la miniatura està mal formada @msg the top object must be a path, compound path or text object to use as a clipping mask l’objecte superior ha de ser un traçat, un traçat compost o un objecte de text per fer-lo servir com a màscara de retall @@ -7448,11 +7471,20 @@ breakText Glyphs Glifs Open Tutorial Sample Obre la mostra del tutorial Finish Tutorial Acaba el tutorial Next Tutorial Tutorial següent + Show Learn Tab Mostra una pestanya d'Aprèn + Show Skill Mostra l'habilitat + Back One Level Torna un nivell enrere Back to Skills Torna a les habilitats @msg tutorial `{id}` has no practice sample el tutorial `{id}` no té cap mostra de pràctica @msg open the practice sample of `{id}` first (see learn.openSample) obriu primer la mostra de pràctica de `{id}` (vegeu learn.openSample) @msg finish `{id}` first (see learn.finish) acabeu primer `{id}` (vegeu learn.finish) @msg `{id}` is the last tutorial in its skill `{id}` és l’últim tutorial de la seva habilitat + Reset progress Restableix el progrés + Mark Tutorial Step Marca el pas del tutorial + Reset Learn Progress Restableix el progrés d’aprenentatge +@msg missing `step` (see learn.show) falta `step` (vegeu learn.show) +@msg `step` must be a step number from 0 to {last} `step` ha de ser un número de pas de 0 a {last} +@msg `{id}` is finished (see learn.resetProgress) `{id}` està acabat (vegeu learn.resetProgress) # Deferred plug-in effects Refresh Deferred Effects Actualitza els efectes ajornats @@ -7482,3 +7514,122 @@ breakText Glyphs Glifs Grommets Ullets Grommet Inset Distància dels ullets a la vora Diameter Diàmetre + Nest Shapes… Encaixa les formes… + Nest Shapes Encaixa les formes + Roll Rotlle +# Status and error messages of image export, color profiles and libraries, 3D effects, path operations and scripts. +@msg 3D effects require finite coordinates within 100 million points Els efectes 3D requereixen coordenades finites dins de 100 milions de punts +@msg 3D effects require one to ten lights Els efectes 3D requereixen d’un a deu llums +@msg BMP depth {_1}: 1, 4, 8, 16, 24 or 32 bits per pixel Profunditat BMP {_1}: 1, 4, 8, 16, 24 o 32 bits per píxel +@msg BMP encoding failed: {width} × {height} pixels doesn't fit the format or the pixel buffer La codificació BMP ha fallat: {width} × {height} píxels no caben al format ni a la memòria intermèdia de píxels +@msg GIF encoding failed: the palette image is malformed La codificació GIF ha fallat: la imatge de paleta està mal formada +@msg GIF encoding failed: {e} La codificació GIF ha fallat: {e} +@msg JPEG colour profile: {e} Perfil de color JPEG: {e} +@msg JPEG encoding failed: pixel buffer doesn't match the image size La codificació JPEG ha fallat: la memòria intermèdia de píxels no coincideix amb la mida de la imatge +@msg JPEG encoding failed: {e} La codificació JPEG ha fallat: {e} +@msg PNG encoding failed: pixel buffer doesn't match the image size La codificació PNG ha fallat: la memòria intermèdia de píxels no coincideix amb la mida de la imatge +@msg PNG encoding failed: the palette image is malformed La codificació PNG ha fallat: la imatge de paleta està mal formada +@msg PNG encoding failed: {e} La codificació PNG ha fallat: {e} +@msg PNG encoding failed: {width} × {height} pixels is not a valid image size La codificació PNG ha fallat: {width} × {height} píxels no és una mida d’imatge vàlida +@msg PSD colour profile: {e} Perfil de color PSD: {e} +@msg PSD encoding failed: the pixel buffer doesn't match the image size La codificació PSD ha fallat: la memòria intermèdia de píxels no coincideix amb la mida de la imatge +@msg Revolve profile contains invalid coordinates El perfil de Revolució conté coordenades no vàlides +@msg Revolve profile is too complex El perfil de Revolució és massa complex +@msg Revolve projection is not finite La projecció de Revolució no és finita +@msg Revolve requires finite profile coordinates within 100 million points Revolució requereix coordenades de perfil finites dins de 100 milions de punts +@msg Revolve surface is too complex; reduce Segments or simplify the profile La superfície de Revolució és massa complexa; redueix Segments o simplifica el perfil +@msg Revolve surface is too complex; simplify the profile La superfície de Revolució és massa complexa; simplifica el perfil +@msg Revolve visibility cannot split the projected boundary La visibilitat de Revolució no pot dividir el contorn projectat +@msg Revolve visibility creates too many fragments La visibilitat de Revolució crea massa fragments +@msg Revolve visibility creates too many vector anchors La visibilitat de Revolució crea massa punts d’ancoratge vectorials +@msg Revolve visibility exceeds its geometry work limit La visibilitat de Revolució supera el seu límit de treball geomètric +@msg Revolve visibility exceeds its spatial index limit La visibilitat de Revolució supera el seu límit d’índex espacial +@msg Revolve visibility has too many boundary crossings La visibilitat de Revolució té massa encreuaments de contorn +@msg Revolve visibility has too many input anchors La visibilitat de Revolució té massa punts d’ancoratge d’entrada +@msg Revolve visibility requires convex cap sectors La visibilitat de Revolució requereix sectors de tapa convexos +@msg Revolve visibility requires finite projected faces La visibilitat de Revolució requereix cares projectades finites +@msg SVG options: {e} Opcions SVG: {e} +@msg Save for Web settings: {e} Paràmetres de Desa per a web: {e} +@msg TIFF colour profile: {e} Perfil de color TIFF: {e} +@msg TIFF encoding failed: the pixel buffer doesn't match the image size La codificació TIFF ha fallat: la memòria intermèdia de píxels no coincideix amb la mida de la imatge +@msg TIFF encoding failed: {e} La codificació TIFF ha fallat: {e} +@msg Targa depth {_1}: 16, 24 or 32 bits per pixel Profunditat Targa {_1}: 16, 24 o 32 bits per píxel +@msg Targa encoding failed: the pixel buffer doesn't match the image size La codificació Targa ha fallat: la memòria intermèdia de píxels no coincideix amb la mida de la imatge +@msg The 3D projection is not finite La projecció 3D no és finita +@msg The 3D shadow is too complex; turn Shadows off or simplify the art L’ombra 3D és massa complexa; desactiva Ombres o simplifica la il·lustració +@msg The shape contains invalid coordinates La forma conté coordenades no vàlides +@msg Too many Revolve faces for visibility evaluation Massa cares de Revolució per avaluar-ne la visibilitat +@msg VectorCraft reads at most {ASE_MAX_ENTRIES} colors and groups from a swatch exchange file, and this library has {entries} VectorCraft llegeix com a màxim {ASE_MAX_ENTRIES} colors i grups d’un fitxer d’intercanvi de mostres, i aquesta biblioteca en té {entries} +@msg WebP encoding failed: {e} La codificació WebP ha fallat: {e} +@msg [{j}] `{_1}`: {why} [{j}] `{_1}`: {why} +@msg `answers[{i}]` {e} `answers[{i}]` {e} +@msg `index` must be a whole number `index` ha de ser un nombre enter +@msg `view` is smallThumb, mediumThumb, largeThumb, smallList or largeList `view` és smallThumb, mediumThumb, largeThumb, smallList o largeList +@msg a line can't run from a point to itself una línia no pot anar d’un punt a ell mateix +@msg a line needs at least two points una línia necessita almenys dos punts +@msg a number cannot be read no es pot llegir un número +@msg a swatch exchange block is too long un bloc d’intercanvi de mostres és massa llarg +@msg a swatch exchange name is too long un nom d’intercanvi de mostres és massa llarg +@msg a {sw} × {sh} image can't be resized to {width} × {height} pixels una imatge de {sw} × {sh} no es pot redimensionar a {width} × {height} píxels +@msg a {width} × {height} image is too large una imatge de {width} × {height} és massa gran +@msg a {width} × {height} image: {e} una imatge de {width} × {height}: {e} +@msg an image could not be written: {e} no s’ha pogut escriure una imatge: {e} +@msg an image that couldn't be read was left out s’ha omès una imatge que no s’ha pogut llegir +@msg can't open “{name}”: {e} no es pot obrir “{name}”: {e} +@msg cannot align zip entries to {align} bytes no es poden alinear les entrades del zip a {align} bytes +@msg cannot open the automation {kind} root `{_1}`: {e} no es pot obrir l’arrel {kind} de l’automatització `{_1}`: {e} +@msg cannot read profile: {0} no es pot llegir el perfil: {0} +@msg color book version {version} isn't supported (only 1) la versió {version} del llibre de colors no és compatible (només 1) +@msg color books in color space {other} aren't supported (only RGB, CMYK and Lab) els llibres de colors en l’espai de color {other} no són compatibles (només RGB, CMYK i Lab) +@msg file name too long to zip: {_1} nom de fitxer massa llarg per afegir-lo al zip: {_1} +@msg file name too long to zip: {name} nom de fitxer massa llarg per afegir-lo al zip: {name} +@msg freeform line {i}: {e} línia de forma lliure {i}: {e} +@msg freeform point {i}: {e} punt de forma lliure {i}: {e} +@msg give `{key}` or `{other}`, not both indiqueu `{key}` o `{other}`, no tots dos +@msg grayscale profiles can't be working spaces yet els perfils d’escala de grisos encara no poden ser espais de treball +@msg input contains NaN or infinite coordinates l’entrada conté coordenades NaN o infinites +@msg input path could not be closed no s’ha pogut tancar el traçat d’entrada +@msg invalid ICC profile: {0} perfil ICC no vàlid: {0} +@msg invalid scale {scale} escala no vàlida {scale} +@msg its localized names take more than {_1} KB els seus noms localitzats ocupen més de {_1} KB +@msg its objects are nested too deep ({e}) els seus objectes estan imbricats massa profundament ({e}) +@msg its tag table lists the `{_1}` tag more than once la seva taula d’etiquetes inclou l’etiqueta `{_1}` més d’una vegada +@msg not a graphic style library: {e} no és una biblioteca d’estils gràfics: {e} +@msg not a swatch library (.vcswatches or .gpl) no és una biblioteca de mostres (.vcswatches o .gpl) +@msg not a swatch library (format `{_1}`) no és una biblioteca de mostres (format `{_1}`) +@msg not a swatch library: {e} no és una biblioteca de mostres: {e} +@msg not an action set file ({e}) no és un fitxer de conjunt d’accions ({e}) +@msg profile colour space {other} is not RGB, CMYK or Gray l’espai de color del perfil, {other}, no és RGB, CMYK ni Gray +@msg regular expression too large expressió regular massa gran +@msg script file is not UTF-8 text: {value} el fitxer de l’script no és text UTF-8: {value} +@msg stop {i}: {e} la parada {i}: {e} +@msg swatch exchange version {major}.{minor} isn't supported (only 1.x) la versió {major}.{minor} del fitxer d’intercanvi de mostres no és compatible (només 1.x) +@msg the color book holds more than {ASE_MAX_ENTRIES} colors el llibre de colors conté més de {ASE_MAX_ENTRIES} colors +@msg the color book is cut short el llibre de colors està tallat +@msg the color book's names take more than {_1} MB els noms del llibre de colors ocupen més de {_1} MB +@msg the image would be {w} × {h} pixels; raster exports are limited to {MAX_RASTER_SIDE} pixels per side and {_1} megapixels: lower the scale or resolution la imatge faria {w} × {h} píxels; les exportacions ràster estan limitades a {MAX_RASTER_SIDE} píxels per costat i {_1} megapíxels: reduïu l’escala o la resolució +@msg the optimised image can't be read back: {e} la imatge optimitzada no es pot tornar a llegir: {e} +@msg the pixel buffer doesn't match the image size la memòria intermèdia de píxels no coincideix amb la mida de la imatge +@msg the preview: {e} la previsualització: {e} +@msg the request may not read the New Document profiles folder la sol·licitud no pot llegir la carpeta de perfils de document nou +@msg the shapes are too degenerate to combine les formes són massa degenerades per combinar-les +@msg the shapes cross themselves and each other too often to combine les formes es creuen amb si mateixes i entre elles massa vegades per combinar-les +@msg the swatch exchange file holds more than {ASE_MAX_ENTRIES} colors and groups el fitxer d’intercanvi de mostres conté més de {ASE_MAX_ENTRIES} colors i grups +@msg the swatch exchange file is cut short el fitxer d’intercanvi de mostres està tallat +@msg the {_1} plate can't be read: {e} la planxa {_1} no es pot llegir: {e} +@msg this binary DXF file is damaged or cut short aquest fitxer DXF binari està malmès o tallat +@msg this is a DWG drawing, which can't be read: save it from the CAD app as a DXF and open that aquest és un dibuix DWG, que no es pot llegir: desa’l des de l’aplicació CAD com a DXF i obre’l +@msg too many classes massa classes +@msg too many groups massa grups +@msg too many layers for PSD (at most 32767) massa capes per a PSD (com a màxim 32767) +@msg too many swatch exchange blocks massa blocs d’intercanvi de mostres +@msg unknown colour profile: {0} perfil de color desconegut: {0} +@msg {_1} clashes with a built-in profile name {_1} coincideix amb el nom d’un perfil integrat +@msg {_1} × {_2} pixels is too large for GIF (at most 65535 pixels a side): lower the resolution {_1} × {_2} píxels és massa gran per a GIF (com a màxim 65535 píxels per costat): reduïu la resolució +@msg {_1}: no usable transform to/from sRGB {_1}: no hi ha cap transformació utilitzable a sRGB o des de sRGB +@msg {name} is not a CMYK profile {name} no és un perfil CMYK +@msg {name} is not an RGB profile {name} no és un perfil RGB +@msg {path}: could not be read {path}: no s’ha pogut llegir +@msg {width} × {height} pixels is too large for JPEG (at most 65535 pixels a side): lower the resolution {width} × {height} píxels és massa gran per a JPEG (com a màxim 65535 píxels per costat): reduïu la resolució +@msg {width} × {height} pixels is too large for Targa (at most 65535 pixels a side): lower the resolution {width} × {height} píxels és massa gran per a Targa (com a màxim 65535 píxels per costat): reduïu la resolució +@msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} píxels és massa gran per a PSD (com a màxim {MAX_SIDE} píxels per costat): reduïu la resolució diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index d95879fc03..1bd4a8ff10 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -428,6 +428,18 @@ Title Case Velká Počáteční Písmena Sentence case Velké první písmeno věty Smart Punctuation… Inteligentní interpunkce… + Smart Punctuation Inteligentní interpunkce + ff, fi, ffi Ligatures Ligatury ff, fi, ffi + ff, fl, ffl Ligatures Ligatury ff, fl, ffl + Smart Quotes Inteligentní uvozovky + Smart Spaces Inteligentní mezery + En, Em Dashes Krátké a dlouhé pomlčky + Ellipses Výpustky + Expert Fractions Odborné zlomky + Replace In Nahradit v + Selected Text Only Pouze vybraný text + Entire Document Celý dokument + Report Results Zobrazit výsledky Create Outlines Převést na křivky Optical Margin Alignment Optické zarovnání okrajů Dynamic Text Dynamický text @@ -978,6 +990,7 @@ # Photoshop-style raster effects (Effect menu, their dialogs). Radial Blur… Radiální rozostření… + Blur Center Střed rozostření Smart Blur… Chytré rozostření… Sharpen Zostření Unsharp Mask… Maska rozostření… @@ -1730,6 +1743,9 @@ digits Malayalam Malajálamské The selected character's font is not available. Písmo vybraného znaku není k dispozici. No alternates for the selected character. Vybraný znak nemá žádné alternativy. Double-click to replace Dvojklikem nahradíte + Click to replace Kliknutím nahradíte + Show all alternates in the Glyphs panel Zobrazit všechny alternativy v panelu Glyfy + Show Character Alternates Zobrazovat alternativy znaku Select one character with the Type tool first. Nejprve nástrojem Text vyberte jeden znak. {glyph} is a glyph of {font}, not of the font the selected text is set in ({text_font}). {glyph} je glyf písma {font}, ne písma, kterým je vybraný text nastaven ({text_font}). {glyph} belongs to {base} (U+{base_code}) {place}; your selection is {sel} (U+{code}). {glyph} patří znaku {base} (U+{base_code}) {place}; váš výběr je {sel} (U+{code}). @@ -2277,6 +2293,7 @@ digits Malayalam Malajálamské @msg paths entry {i} needs path and ids (object ids no other entry has) položka {i} v paths potřebuje path a ids (ID objektů, které nemá žádná jiná položka) @msg scope missingInFolder takes path: the folder of that file is searched for the other missing links scope missingInFolder bere path: ve složce tohoto souboru se hledají ostatní chybějící propojení Show Missing Zobrazit chybějící + Sort by Size Seřadit podle velikosti Sort by Status Seřadit podle stavu Clear Overrides Vymazat přepsání Create New {kind} Style Vytvořit nový styl ({kind}) @@ -2533,6 +2550,7 @@ digits Malayalam Malajálamské Export Asset Exportovat prvek Export to: Exportovat do: Format Settings Nastavení formátu + Format Settings… Nastavení formátu… Formats: Formáty: Full Document Celý dokument Include Bleed Zahrnout spadávku @@ -2633,6 +2651,7 @@ digits Malayalam Malajálamské e.g. 1-3, 5 např. 1-3, 5 First Page První stránka Import PDF Importovat PDF + Import PDF pages as links Importovat stránky PDF jako propojení Last Page Poslední stránka Next Page Další stránka of {count} z {count} @@ -2716,6 +2735,7 @@ digits Malayalam Malajálamské Transparent Background Průhledné pozadí Choose… Vybrat… Copy Fonts Used in the Document Kopírovat písma použitá v dokumentu + Copy Info Kopírovat informace Copy Links Kopírovat propojené soubory Create Report Vytvořit zprávu Fonts whose licence doesn't allow embedding are not copied. Písma, jejichž licence nepovoluje vkládání, se nekopírují. @@ -4685,6 +4705,7 @@ imageTrace Outline Obrys @msg there is no script engine named {name} skriptovací jádro s názvem {name} neexistuje @msg Running a script Běží skript @msg Copied the script report Zpráva o skriptu zkopírována +@msg Copied the link info Informace o propojení zkopírovány @msg Corners edits the corners of a path Rohy upravuje rohy cesty @msg Couldn't copy to the system clipboard: {e} Nelze kopírovat do systémové schránky: {e} @msg Couldn't open {name}: {e} {name} nelze otevřít: {e} @@ -6674,7 +6695,7 @@ axis Y Axis osa Y @plural Result: {n}|Results: {n} Výsledek: {n}|Výsledky: {n}|Výsledky: {n} @msg select one object vyberte jeden objekt @msg Global Edit works on paths, compound paths, symbol instances and groups of them Globální úpravy pracují s cestami, složenými cestami, instancemi symbolů a jejich skupinami -@msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again nebyly nalezeny žádné podobné objekty (otočené a zrcadlené kopie se nevyhledávají); změňte možnosti globálních úprav a zkuste to znovu +@msg no similar objects found (reflected copies are not matched); change the Global Edit Options and try again nebyly nalezeny žádné podobné objekty (zrcadlené kopie se nevyhledávají); změňte možnosti globálních úprav a zkuste to znovu @msg Global Edit is off Globální úpravy nejsou zapnuté @msg only an object of the Global Edit other than the one it started from can be left out z globálních úprav lze vyřadit jen jiný objekt než ten, od kterého začaly @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all nebo rozsah, například 1, 3-5, ne {v} @@ -7445,6 +7466,122 @@ breakText Glyphs Glyfy @plural {n} line cut|{n} lines cut {n} řádek zkrácen|{n} řádky zkráceny|{n} řádků zkráceno @msg `first` and `last` must be numbers of lines the console holds, first before last `first` a `last` musí být čísla řádků, které konzole uchovává, `first` před `last` +# Messages of the effects, 3D, image export, color profiles, swatch exchange files, color books and DXF import. +@msg 3D effects require finite coordinates within 100 million points 3D efekty vyžadují konečné souřadnice v rozsahu 100 milionů bodů +@msg 3D effects require one to ten lights 3D efekty vyžadují jedno až deset světel +@msg BMP depth {_1}: 1, 4, 8, 16, 24 or 32 bits per pixel hloubka BMP {_1}: 1, 4, 8, 16, 24 nebo 32 bitů na obrazový bod +@msg BMP encoding failed: {width} × {height} pixels doesn't fit the format or the pixel buffer kódování BMP selhalo: {width} × {height} obrazových bodů neodpovídá formátu ani vyrovnávací paměti obrazových bodů +@msg GIF encoding failed: the palette image is malformed kódování GIF selhalo: obraz s paletou je chybně utvořený +@msg GIF encoding failed: {e} kódování GIF selhalo: {e} +@msg JPEG colour profile: {e} barevný profil JPEG: {e} +@msg JPEG encoding failed: pixel buffer doesn't match the image size kódování JPEG selhalo: vyrovnávací paměť obrazových bodů neodpovídá velikosti obrazu +@msg JPEG encoding failed: {e} kódování JPEG selhalo: {e} +@msg PNG encoding failed: pixel buffer doesn't match the image size kódování PNG selhalo: vyrovnávací paměť obrazových bodů neodpovídá velikosti obrazu +@msg PNG encoding failed: the palette image is malformed kódování PNG selhalo: obraz s paletou je chybně utvořený +@msg PNG encoding failed: {e} kódování PNG selhalo: {e} +@msg PNG encoding failed: {width} × {height} pixels is not a valid image size kódování PNG selhalo: {width} × {height} obrazových bodů není platná velikost obrazu +@msg PSD colour profile: {e} barevný profil PSD: {e} +@msg PSD encoding failed: the pixel buffer doesn't match the image size kódování PSD selhalo: vyrovnávací paměť obrazových bodů neodpovídá velikosti obrazu +@msg Revolve profile contains invalid coordinates Profil rotačního tělesa obsahuje neplatné souřadnice +@msg Revolve profile is too complex Profil rotačního tělesa je příliš složitý +@msg Revolve projection is not finite Projekce rotačního tělesa není konečná +@msg Revolve requires finite profile coordinates within 100 million points Rotační těleso vyžaduje konečné souřadnice profilu v rozsahu 100 milionů bodů +@msg Revolve surface is too complex; reduce Segments or simplify the profile Povrch rotačního tělesa je příliš složitý; snižte Segmenty nebo zjednodušte profil +@msg Revolve surface is too complex; simplify the profile Povrch rotačního tělesa je příliš složitý; zjednodušte profil +@msg Revolve visibility cannot split the projected boundary Výpočet viditelnosti rotačního tělesa nedokáže rozdělit promítnutou hranici +@msg Revolve visibility creates too many fragments Výpočet viditelnosti rotačního tělesa vytváří příliš mnoho fragmentů +@msg Revolve visibility creates too many vector anchors Výpočet viditelnosti rotačního tělesa vytváří příliš mnoho vektorových kotevních bodů +@msg Revolve visibility exceeds its geometry work limit Výpočet viditelnosti rotačního tělesa překračuje svůj limit geometrických výpočtů +@msg Revolve visibility exceeds its spatial index limit Výpočet viditelnosti rotačního tělesa překračuje svůj limit prostorového indexu +@msg Revolve visibility has too many boundary crossings Výpočet viditelnosti rotačního tělesa má příliš mnoho průsečíků hranic +@msg Revolve visibility has too many input anchors Výpočet viditelnosti rotačního tělesa má příliš mnoho vstupních kotevních bodů +@msg Revolve visibility requires convex cap sectors Výpočet viditelnosti rotačního tělesa vyžaduje konvexní výseče podstav +@msg Revolve visibility requires finite projected faces Výpočet viditelnosti rotačního tělesa vyžaduje konečné promítnuté stěny +@msg SVG options: {e} Možnosti SVG: {e} +@msg Save for Web settings: {e} Nastavení Uložit pro web: {e} +@msg TIFF colour profile: {e} barevný profil TIFF: {e} +@msg TIFF encoding failed: the pixel buffer doesn't match the image size kódování TIFF selhalo: vyrovnávací paměť obrazových bodů neodpovídá velikosti obrazu +@msg TIFF encoding failed: {e} kódování TIFF selhalo: {e} +@msg Targa depth {_1}: 16, 24 or 32 bits per pixel hloubka Targa {_1}: 16, 24 nebo 32 bitů na obrazový bod +@msg Targa encoding failed: the pixel buffer doesn't match the image size kódování Targa selhalo: vyrovnávací paměť obrazových bodů neodpovídá velikosti obrazu +@msg The 3D projection is not finite 3D projekce není konečná +@msg The 3D shadow is too complex; turn Shadows off or simplify the art 3D stín je příliš složitý; vypněte Stíny nebo zjednodušte kresbu +@msg The shape contains invalid coordinates Tvar obsahuje neplatné souřadnice +@msg Too many Revolve faces for visibility evaluation Rotační těleso má příliš mnoho stěn pro výpočet viditelnosti +@msg VectorCraft reads at most {ASE_MAX_ENTRIES} colors and groups from a swatch exchange file, and this library has {entries} VectorCraft čte ze souboru pro výměnu vzorníku nejvýše {ASE_MAX_ENTRIES} barev a skupin a tato knihovna jich má {entries} +@msg WebP encoding failed: {e} kódování WebP selhalo: {e} +@msg [{j}] `{_1}`: {why} [{j}] `{_1}`: {why} +@msg `answers[{i}]` {e} `answers[{i}]` {e} +@msg `view` is smallThumb, mediumThumb, largeThumb, smallList or largeList `view` je smallThumb, mediumThumb, largeThumb, smallList nebo largeList +@msg a line can't run from a point to itself čára nemůže vést z bodu zpět do téhož bodu +@msg a line needs at least two points čára potřebuje alespoň dva body +@msg a number cannot be read číslo nelze přečíst +@msg a swatch exchange block is too long blok souboru pro výměnu vzorníku je příliš dlouhý +@msg a swatch exchange name is too long název v souboru pro výměnu vzorníku je příliš dlouhý +@msg a {sw} × {sh} image can't be resized to {width} × {height} pixels velikost obrazu {sw} × {sh} nelze změnit na {width} × {height} obrazových bodů +@msg a {width} × {height} image is too large obraz {width} × {height} je příliš velký +@msg a {width} × {height} image: {e} obraz {width} × {height}: {e} +@msg an image could not be written: {e} obraz se nepodařilo zapsat: {e} +@msg an image that couldn't be read was left out obraz, který nešlo přečíst, byl vynechán +@msg can't open “{name}”: {e} nelze otevřít „{name}“: {e} +@msg cannot align zip entries to {align} bytes položky zipu nelze zarovnat na {align} bajtů +@msg cannot open the automation {kind} root `{_1}`: {e} nelze otevřít kořen automatizace pro {kind} `{_1}`: {e} +@msg cannot read profile: {0} profil nelze přečíst: {0} +@msg color book version {version} isn't supported (only 1) verze barevné knihy {version} není podporována (pouze 1) +@msg color books in color space {other} aren't supported (only RGB, CMYK and Lab) barevné knihy v barevném prostoru {other} nejsou podporovány (pouze RGB, CMYK a Lab) +@msg file name too long to zip: {_1} název souboru je pro zip příliš dlouhý: {_1} +@msg file name too long to zip: {name} název souboru je pro zip příliš dlouhý: {name} +@msg freeform line {i}: {e} volná čára {i}: {e} +@msg freeform point {i}: {e} volný bod {i}: {e} +@msg give `{key}` or `{other}`, not both zadejte `{key}` nebo `{other}`, ne obojí +@msg grayscale profiles can't be working spaces yet profily ve stupních šedi zatím nemohou být pracovními prostory +@msg input contains NaN or infinite coordinates vstup obsahuje souřadnice NaN nebo nekonečné souřadnice +@msg input path could not be closed vstupní cestu se nepodařilo uzavřít +@msg invalid ICC profile: {0} neplatný profil ICC: {0} +@msg invalid scale {scale} neplatné měřítko {scale} +@msg its localized names take more than {_1} KB jeho lokalizované názvy zabírají více než {_1} KB +@msg its objects are nested too deep ({e}) jeho objekty jsou vnořené příliš hluboko ({e}) +@msg its tag table lists the `{_1}` tag more than once jeho tabulka značek uvádí značku `{_1}` více než jednou +@msg not a graphic style library: {e} nejde o knihovnu grafických stylů: {e} +@msg not a swatch library (.vcswatches or .gpl) nejde o knihovnu vzorníku (.vcswatches nebo .gpl) +@msg not a swatch library (format `{_1}`) nejde o knihovnu vzorníku (formát `{_1}`) +@msg not a swatch library: {e} nejde o knihovnu vzorníku: {e} +@msg not an action set file ({e}) nejde o soubor sady akcí ({e}) +@msg profile colour space {other} is not RGB, CMYK or Gray barevný prostor profilu {other} není RGB, CMYK ani Gray +@msg regular expression too large regulární výraz je příliš velký +@msg script file is not UTF-8 text: {value} soubor skriptu není text v kódování UTF-8: {value} +@msg stop {i}: {e} zarážka {i}: {e} +@msg swatch exchange version {major}.{minor} isn't supported (only 1.x) verze souboru pro výměnu vzorníku {major}.{minor} není podporována (pouze 1.x) +@msg the color book holds more than {ASE_MAX_ENTRIES} colors barevná kniha obsahuje více než {ASE_MAX_ENTRIES} barev +@msg the color book is cut short barevná kniha je useknutá +@msg the color book's names take more than {_1} MB názvy barevné knihy zabírají více než {_1} MB +@msg the image would be {w} × {h} pixels; raster exports are limited to {MAX_RASTER_SIDE} pixels per side and {_1} megapixels: lower the scale or resolution obraz by měl {w} × {h} obrazových bodů; rastrové exporty jsou omezeny na {MAX_RASTER_SIDE} obrazových bodů na stranu a {_1} megapixelů: snižte měřítko nebo rozlišení +@msg the optimised image can't be read back: {e} optimalizovaný obraz nelze zpětně přečíst: {e} +@msg the pixel buffer doesn't match the image size vyrovnávací paměť obrazových bodů neodpovídá velikosti obrazu +@msg the preview: {e} náhled: {e} +@msg the request may not read the New Document profiles folder požadavek nesmí číst složku profilů nového dokumentu +@msg the shapes are too degenerate to combine tvary jsou příliš degenerované na sloučení +@msg the shapes cross themselves and each other too often to combine tvary protínají samy sebe i sebe navzájem příliš často na sloučení +@msg the swatch exchange file holds more than {ASE_MAX_ENTRIES} colors and groups soubor pro výměnu vzorníku obsahuje více než {ASE_MAX_ENTRIES} barev a skupin +@msg the swatch exchange file is cut short soubor pro výměnu vzorníku je useknutý +@msg the {_1} plate can't be read: {e} výtažek {_1} nelze přečíst: {e} +@msg this binary DXF file is damaged or cut short tento binární soubor DXF je poškozený nebo useknutý +@msg this is a DWG drawing, which can't be read: save it from the CAD app as a DXF and open that toto je výkres DWG, který nelze přečíst: uložte jej v aplikaci CAD jako DXF a otevřete ten +@msg too many classes příliš mnoho tříd znaků +@msg too many groups příliš mnoho skupin +@msg too many layers for PSD (at most 32767) příliš mnoho vrstev pro PSD (nejvýše 32767) +@msg too many swatch exchange blocks příliš mnoho bloků souboru pro výměnu vzorníku +@msg unknown colour profile: {0} neznámý barevný profil: {0} +@msg {_1} clashes with a built-in profile name {_1} koliduje s názvem vestavěného profilu +@msg {_1} × {_2} pixels is too large for GIF (at most 65535 pixels a side): lower the resolution {_1} × {_2} obrazových bodů je pro GIF příliš mnoho (nejvýše 65535 obrazových bodů na stranu): snižte rozlišení +@msg {_1}: no usable transform to/from sRGB {_1}: žádná použitelná transformace do sRGB nebo ze sRGB +@msg {name} is not a CMYK profile {name} není profil CMYK +@msg {name} is not an RGB profile {name} není profil RGB +@msg {path}: could not be read {path}: nelze přečíst +@msg {width} × {height} pixels is too large for JPEG (at most 65535 pixels a side): lower the resolution {width} × {height} obrazových bodů je pro JPEG příliš mnoho (nejvýše 65535 obrazových bodů na stranu): snižte rozlišení +@msg {width} × {height} pixels is too large for Targa (at most 65535 pixels a side): lower the resolution {width} × {height} obrazových bodů je pro Targa příliš mnoho (nejvýše 65535 obrazových bodů na stranu): snižte rozlišení +@msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} obrazových bodů je pro PSD příliš mnoho (nejvýše {MAX_SIDE} obrazových bodů na stranu): snižte rozlišení + # Learn panel Learn Výuka Explore tutorials Prozkoumat výukové kurzy @@ -7467,11 +7604,20 @@ breakText Glyphs Glyfy Open Tutorial Sample Otevřít ukázku výukového kurzu Finish Tutorial Dokončit výukový kurz Next Tutorial Další výukový kurz + Show Learn Tab Zobrazit kartu Výuky + Show Skill Zobrazit dovednost + Back One Level O úroveň zpět Back to Skills Zpět na dovednosti @msg tutorial `{id}` has no practice sample výukový kurz `{id}` nemá cvičnou ukázku @msg open the practice sample of `{id}` first (see learn.openSample) nejprve otevřete cvičnou ukázku kurzu `{id}` (viz learn.openSample) @msg finish `{id}` first (see learn.finish) nejprve dokončete `{id}` (viz learn.finish) @msg `{id}` is the last tutorial in its skill `{id}` je poslední výukový kurz své dovednosti + Reset progress Obnovit postup + Mark Tutorial Step Označit krok výukového kurzu + Reset Learn Progress Obnovit postup učení +@msg missing `step` (see learn.show) chybí `step` (viz learn.show) +@msg `step` must be a step number from 0 to {last} `step` musí být číslo kroku od 0 do {last} +@msg `{id}` is finished (see learn.resetProgress) `{id}` je dokončen (viz learn.resetProgress) # Deferred plug-in effects Refresh Deferred Effects Obnovit odložené efekty @@ -7501,6 +7647,9 @@ breakText Glyphs Glyfy Grommets Průchodky Grommet Inset Odstup průchodek od okraje Diameter Průměr + Nest Shapes… Skládat tvary… + Nest Shapes Skládat tvary + Roll Role @msg 'caller', 'callee' and 'arguments' cannot be used on strict mode functions 'caller', 'callee' a 'arguments' nelze použít u funkcí ve striktním režimu @msg A profile supports one Revolve effect. Edit the existing effect's options instead. Profil podporuje jeden efekt Rotační těleso. Upravte místo toho volby stávajícího efektu. @msg Add Points at Crossings: a path went missing Přidat body v křížení: jedna cesta se ztratila @@ -8886,6 +9035,8 @@ breakText Glyphs Glyfy @msg the RTF file is too large to place as type (at most {_1} MB) soubor RTF je příliš velký na umístění jako text (nejvýše {_1} MB) @msg the SVG expands to more than {0} nested SVG images SVG se rozvine na více než {0} vnořených obrázků SVG @msg the SVG expands to more than {0} objects SVG se rozvine na více než {0} objektů +@msg the SVG's style sheets take too long to match porovnání šablon stylů SVG trvá příliš dlouho +@msg the SVG's styles expand to more than {0} MB styly SVG se rozvinou na více než {0} MB @msg the SVG file is larger than {MAX_IMPORT_BYTES} bytes soubor SVG je větší než {MAX_IMPORT_BYTES} bajtů @msg the SVG has no drawable objects SVG nemá žádné vykreslitelné objekty @msg the SVGZ file unpacks to more than {_1} MB soubor SVGZ se rozbalí na více než {_1} MB diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index f320896f62..d6785ff924 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -25,6 +25,615 @@ @msg {key} must be [x, y] with finite coordinates {key} skal være [x, y] med endelige koordinater @msg ids must contain 1–10000 object ids ids skal indeholde 1–10000 objekt-id’er +# Status and error messages: 3D assets, type on a path, scripts and their File and $ objects, presets, +# PDF page sizes, Objects on Path, plug-ins, file readers and data sets. Names in backticks, command ids, +# double-quoted values and bare true, false and null stay as the English writes them; names the user +# gave are quoted »…«, and numbers use a period between thousands (2.048). +@msg {what} can't be exported in 3D: {e} {what} kan ikke eksporteres i 3D: {e} +@msg asset {id} isn't a 3D asset aktiv {id} er ikke et 3D-aktiv +@msg asset {id} is a 3D asset: assets.export3D writes it aktiv {id} er et 3D-aktiv: assets.export3D skriver det +@msg no 3D assets yet: collect an object with a 3D effect first (assets.add3D) ingen 3D-aktiver endnu: saml først et objekt med en 3D-effekt (assets.add3D) +@msg select an object with a 3D effect (or give its ids) markér et objekt med en 3D-effekt (eller angiv dets id’er) +@msg select point type or type on a path markér punkttekst eller tekst på en kurve +@msg type on a path in a thread cannot use Dynamic Text: {frames} tekst på en kurve i en tekstkæde kan ikke bruge dynamisk tekst: {frames} +@msg type on an open or compound path cannot be centered on its top or bottom: {open} tekst på en åben eller sammensat kurve kan ikke centreres på dens top eller bund: {open} +@msg type on a path with no length or no height cannot be centered: {flat} tekst på en kurve uden længde eller højde kan ikke centreres: {flat} +@msg type on a path in a thread cannot be centered on its top or bottom: {frames} tekst på en kurve i en tekstkæde kan ikke centreres på dens top eller bund: {frames} +@msg select type on a closed path markér tekst på en lukket kurve +@msg `Custom` stands for changed settings: save the preset under another name `Custom` står for ændrede indstillinger: gem forudindstillingen under et andet navn +@msg the selection has no gradient fill markeringen har ingen gradientudfyldning +@msg the selection has no gradient stroke markeringen har ingen gradientstreg +@msg the selection has no pattern fill markeringen har ingen mønsterudfyldning +@msg the selection has no pattern stroke markeringen har ingen mønsterstreg +@msg no gradient swatch `{name}` ingen gradientfarveprøve `{name}` +@msg no pattern swatch `{name}` ingen mønsterfarveprøve `{name}` +@msg the library item is damaged bibliotekselementet er beskadiget +@msg its zlib compression is damaged dens zlib-komprimering er beskadiget +@msg its Zstandard compression is damaged dens Zstandard-komprimering er beskadiget +@msg it decompresses to more than {_1} MB den udpakkes til mere end {_1} MB +@msg its editing data is for a different page dens redigeringsdata er til en anden side +@msg `fontHeightReference` must be "emBox", "capHeight", "xHeight" or "icfBox" `fontHeightReference` skal være "emBox", "capHeight", "xHeight" eller "icfBox" +@msg Choose a .js or .jsx script Vælg et .js- eller .jsx-script +@msg Ran {name} Kørte {name} +@msg The script was stopped and its changes were undone Scriptet blev stoppet, og dets ændringer blev fortrudt +@msg a script is running: stop it or wait for it to finish et script kører: stop det, eller vent, til det er færdigt +@msg this is a compiled script, which cannot be run; use its source text dette er et kompileret script, som ikke kan køres; brug dets kildetekst +@msg the script is not UTF-8 text scriptet er ikke UTF-8-tekst +@msg the script is too large to run scriptet er for stort til at blive kørt +@msg a drag or an undo group is open; finish it before running a script en trækning eller en fortrydelsesgruppe er åben; afslut den, før du kører et script +@msg the script left a document that cannot be kept scriptet efterlod et dokument, der ikke kan beholdes +@msg the script is no longer in the Scripts folder scriptet ligger ikke længere i mappen Scripter +@msg the script's run is no longer available scriptets kørsel er ikke længere tilgængelig +@msg a failed command changed undo steps that could not be put back, so the script was stopped en mislykket kommando ændrede fortrydelsestrin, der ikke kunne genskabes, så scriptet blev stoppet +@msg a recovery copy could not be written, so the script was not run en gendannelseskopi kunne ikke skrives, så scriptet blev ikke kørt +@msg Script file access denied Scriptets filadgang blev nægtet +@msg Script file exceeds 8 MiB Scriptfilen er større end 8 MiB +@msg Script file is not open Scriptfilen er ikke åben +@msg Script file cannot be decoded Scriptfilen kan ikke afkodes +@msg Script file is not a regular file Scriptfilen er ikke en almindelig fil +@msg Script file does not exist Scriptfilen findes ikke +@msg Script file could not be read Scriptfilen kunne ikke læses +@msg Script folder has more than 2,048 entries Scriptmappen har mere end 2.048 elementer +@msg Script file open mode must be r, w, e or a Scriptfilens åbningstilstand skal være r, w, e eller a +@msg Script file writing is not available Skrivning af scriptfiler er ikke tilgængelig +@msg Script file dialogs are not available Scriptfildialoger er ikke tilgængelige +@msg Script files cannot be opened in another application Scriptfiler kan ikke åbnes i et andet program +@msg Script file access is unavailable on the web Scriptets filadgang er ikke tilgængelig på nettet +@msg Script has 256 files open Scriptet har 256 filer åbne +@msg Script file path exceeds 32,767 characters Scriptfilens sti er længere end 32.767 tegn +@msg Script folder mask takes too many steps to match Scriptmappens maske kræver for mange trin at matche +@msg the script opened more file data than one run may open (32 MiB) scriptet åbnede flere fildata, end én kørsel må åbne (32 MiB) +@msg File.seek: takes a position and a mode File.seek: tager en position og en tilstand +@msg vc.run: give a command id, as a string vc.run: angiv et kommando-id som en streng +@msg vc.run: takes a command id and an object of parameters vc.run: tager et kommando-id og et objekt med parametre +@msg vc.run: the parameters must be an object vc.run: parametrene skal være et objekt +@msg vc.run: the result{place} is too large for a script vc.run: resultatet{place} er for stort til et script +@msg $.evalFile requires a file path $.evalFile kræver en filsti +@msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: tidsgrænsen skal være et endeligt antal millisekunder, 0 eller mere +@msg $.evalFile: takes a file path and a timeout $.evalFile: tager en filsti og en tidsgrænse +@msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: linje {line}, kolonne {column} i {file}: {e} (kastet) +@msg {name}: line {line}, column {column}: {e} (thrown) {name}: linje {line}, kolonne {column}: {e} (kastet) +@msg {name}: {e} (thrown) {name}: {e} (kastet) +@msg {name}: line {line}, column {column} of {file}: {e} (limit) {name}: linje {line}, kolonne {column} i {file}: {e} (grænse) +@msg {name}: line {line}, column {column}: {e} (limit) {name}: linje {line}, kolonne {column}: {e} (grænse) +@msg {name}: {e} (limit) {name}: {e} (grænse) +@msg {name}: line {line}, column {column} of {file}: {e} (syntax) {name}: linje {line}, kolonne {column} i {file}: {e} (syntaksfejl) +@msg {name}: line {line}, column {column}: {e} (syntax) {name}: linje {line}, kolonne {column}: {e} (syntaksfejl) +@msg {name}: {e} (syntax) {name}: {e} (syntaksfejl) +@msg {name}: line {line}, column {column} of {file}: {e} (stopped) {name}: linje {line}, kolonne {column} i {file}: {e} (stoppet) +@msg {name}: line {line}, column {column}: {e} (stopped) {name}: linje {line}, kolonne {column}: {e} (stoppet) +@msg {name}: {e} (stopped) {name}: {e} (stoppet) +@msg {name}: line {line}, column {column} of {file}: {e} (internal) {name}: linje {line}, kolonne {column} i {file}: {e} (intern fejl) +@msg {name}: line {line}, column {column}: {e} (internal) {name}: linje {line}, kolonne {column}: {e} (intern fejl) +@msg {name}: {e} (internal) {name}: {e} (intern fejl) +@msg {e} (these files stay written: {paths}) {e} (disse filer forbliver skrevet: {paths}) +@msg $.{name}: give a name, as a string $.{name}: angiv et navn som en streng +@msg $.locale: give a locale such as "en" or "de_DE", or null for the interface's $.locale: angiv en landestandard som "en" eller "de_DE", eller null for brugerfladens +@msg $.localize: give true or false $.localize: angiv true eller false +@msg $.flags: only 512, which turns localization on, or 0 can be set $.flags: kun 512, som slår lokalisering til, eller 0 kan angives +@msg $.flags: give a number $.flags: angiv et tal +@msg $.appEncoding: scripts here read and write UTF-8 only $.appEncoding: scripter her læser og skriver kun UTF-8 +@msg $.appEncoding: give an encoding's name, as a string $.appEncoding: angiv navnet på en tegnkodning som en streng +@msg $.memCache: the memory cache size cannot be set $.memCache: hukommelsescachens størrelse kan ikke angives +@msg $.setenv: give a value, as a string $.setenv: angiv en værdi som en streng +@msg $.setenv: only {_1} can be set $.setenv: kun {_1} kan angives +@msg $.setenv: a value has at most {MAX_ENV_BYTES} letters, digits and _ . - @ $.setenv: en værdi har højst {MAX_ENV_BYTES} bogstaver, cifre og _ . - @ +@msg $.sleep: give a number of milliseconds from 0 to {MAX_SLEEP_MS} $.sleep: angiv et antal millisekunder fra 0 til {MAX_SLEEP_MS} +@msg $.sleep: give a number of milliseconds $.sleep: angiv et antal millisekunder +@msg $.sleep: a run cannot wait inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code $.sleep: en kørsel kan ikke vente i et tilbagekald fra en indbygget funktion, en getter, en konvertering eller en fil, som $.evalFile kører; kald den fra scriptets egen kode +@msg $.bp: scripts here have no debugger $.bp: scripter her har ingen debugger +@msg $.colorPicker: scripts cannot show a dialog yet $.colorPicker: scripter kan endnu ikke vise en dialog +@msg {name}: give a message {name}: angiv en meddelelse +@msg {name}: give the text the field starts with {name}: angiv den tekst, feltet starter med +@msg {name}: the message is longer than 16 KiB {name}: meddelelsen er længere end 16 KiB +@msg {name}: the title is longer than 256 bytes {name}: titlen er længere end 256 byte +@msg {name}: the text the field starts with is longer than 16 KiB {name}: den tekst, feltet starter med, er længere end 16 KiB +@msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: en dialog kan ikke åbne i et tilbagekald fra en indbygget funktion, en getter, en konvertering eller en fil, som $.evalFile kører; kald den fra scriptets egen kode +@msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: det næste svar i `answers` er til {_1}, ikke til {name} +@msg {name}: `answers` has no answer left for this dialog {name}: `answers` har intet svar tilbage til denne dialog +@msg vc.document{place} is too large for a script vc.document{place} er for stort til et script +@msg vc.log: the log of this run is full vc.log: loggen for denne kørsel er fuld +@msg this function's script run has ended denne funktions scriptkørsel er afsluttet +@msg the script made more host calls than one run may make scriptet foretog flere værtskald, end én kørsel må foretage +@msg the script passed more data to and from commands than one run may pass scriptet sendte flere data til og fra kommandoer, end én kørsel må sende +@msg the script added more objects and data to the documents than one run may add scriptet tilføjede flere objekter og data til dokumenterne, end én kørsel må tilføje +@msg {what}: the object is not a File or a Folder {what}: objektet er ikke en File eller en Folder +@msg {what}: the count must be a finite number, 0 or more {what}: antallet skal være et endeligt tal, 0 eller mere +@msg File.seek: the position must be a finite number File.seek: positionen skal være et endeligt tal +@msg File.seek: the mode must be 0, 1 or 2 File.seek: tilstanden skal være 0, 1 eller 2 +@msg script file is compiled: {value} scriptfilen er kompileret: {value} +@msg `name` must be the name of a script engine `name` skal være navnet på en scriptmotor +@msg the main script engine is new for each run and is never kept, so it cannot be dropped hovedscriptmotoren er ny ved hver kørsel og bevares aldrig, så den kan ikke fjernes +@msg there is no script engine named {name} der findes ingen scriptmotor med navnet {name} +@msg Running a script Kører et script +@msg Data Recovery can't keep copies in {path}: {e} Datagendannelse kan ikke opbevare kopier i {path}: {e} +@msg Plug-ins can't be loaded from {path}: {e} Plug-ins kan ikke indlæses fra {path}: {e} +@msg select a path markér en kurve +@msg Save writes {_1}, not {_2}: use file.saveAsTemplate to write it Gem skriver {_1}, ikke {_2}: brug file.saveAsTemplate til at skrive det +@msg aiVersion 7 writes legacy .ai files, not .ait templates aiVersion 7 skriver ældre .ai-filer, ikke .ait-skabeloner +@msg `groupColors` must be an array `groupColors` skal være et array +@msg `preserve` must be an object `preserve` skal være et objekt +@msg `{key}` must be an array `{key}` skal være et array +@msg `{key}` must be a #rrggbb color `{key}` skal være en #rrggbb-farve +@msg `{key}` must be a #rrggbb color or a layer color name `{key}` skal være en #rrggbb-farve eller navnet på en lagfarve +@msg unknown Live Paint option `{key}` ukendt Live Paint-indstilling `{key}` +@msg unknown Shape Builder option `{key}` ukendt Formbygger-indstilling `{key}` +@msg `{key}` must be a profile name or null `{key}` skal være et profilnavn eller null +@msg `top` and `below` can't both be true `top` og `below` kan ikke begge være true +@msg `select` must be true or false `select` skal være true eller false +@msg `minAnchors` and `maxAnchors` must be whole numbers `minAnchors` og `maxAnchors` skal være heltal +@msg `{key}` must be a number not below 0 `{key}` skal være et tal, der ikke er under 0 +@msg `{key}` must be four numbers not below 0: [tl, tr, br, bl] `{key}` skal være fire tal, der ikke er under 0: [tl, tr, br, bl] +@msg `{key}` must be [x, y, width, height]: four finite numbers, width and height not negative `{key}` skal være [x, y, width, height]: fire endelige tal, hvor width og height ikke er negative +@msg `{min_key}` is greater than `{max_key}` `{min_key}` er større end `{max_key}` +@msg give at least one of `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` angiv mindst én af `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` +@msg a process color can't colorize a grayscale image with transparency: use a spot color, black or white en procesfarve kan ikke farvelægge et gråtonebillede med gennemsigtighed: brug en staffagefarve, sort eller hvid +@msg a key object sits on that point et nøgleobjekt ligger på det punkt +@msg `name` is empty `name` er tom +@msg `newName` is empty `newName` er tom +@msg `{name}` is a built-in preset and can't change: save it under another name `{name}` er en indbygget forudindstilling og kan ikke ændres: gem den under et andet navn +@msg `{name}` is a built-in preset and stays `{name}` er en indbygget forudindstilling og bevares +@msg a spine keeps at least two points en rygrad beholder mindst to punkter +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` er null, navnet på en lagfarve eller #rrggbb +@msg the Simplify slider is not open skyderen Forenkl er ikke åben +@msg the Smooth slider is not open skyderen Udglat er ikke åben +@msg handle must be in or out handle skal være in eller out +@msg index must be ≥ 0 index skal være ≥ 0 +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller siden for tegneflade {n} er {size}, længere end PDF's sidegrænse på 14.400 pt (200 in): den skrives med en UserUnit på {unit}, så programmer, der ignorerer UserUnit, viser den så mange gange mindre +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller: turn on Write pages longer than 200 in at full size in points siden for tegneflade {n} er {size}, længere end PDF's sidegrænse på 14.400 pt (200 in): den skrives med en UserUnit på {unit}, så programmer, der ignorerer UserUnit, viser den så mange gange mindre: slå Skriv sider længere end 200 in i fuld størrelse i punkter til +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in siden for tegneflade {n} er {size}, længere end PDF's sidegrænse på 14.400 pt (200 in): {label}-sider skrives uden en UserUnit, i punkter, og programmer, der overholder grænsen, beskærer siden til 200 in +@msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5 har ingen UserUnit, som en side længere end 14.400 pt (200 in) har brug for for at bevare sin størrelse: filen skrives som PDF 1.6 +@msg PDF 1.4 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to stay within PDF/A-2's page limit of 14,400 units: the file is written as PDF 1.6 PDF 1.4 har ingen UserUnit, som en side længere end 14.400 pt (200 in) har brug for for at holde sig inden for PDF/A-2's sidegrænse på 14.400 enheder: filen skrives som PDF 1.6 +@msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units siden for tegneflade {n} er {size}, for lang og smal til PDF's sidelængder på 3 til 14.400 enheder: den skrives med en UserUnit på {unit}, som holder den korte side på 3 enheder eller mere, og programmer, der overholder grænsen, beskærer den lange side til 14.400 enheder +@msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard {label}-filer rummer reelle tal op til {max}, og siden for tegneflade {n}, der er {side} pt lang, kræver større: vælg PDF 1.6 eller nyere uden en PDF/X-standard, eller en mindre tegneflade +@msg line {line}: value for `{var}` must be true or false linje {line}: værdien for `{var}` skal være true eller false +@msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes linje {line}: værdien for `{var}` er længere end {MAX_GRAPH_CSV} byte +@msg a bristle brush name can have at most {max} characters: `{name}` has {count} navnet på en børstepensel kan have højst {max} tegn: `{name}` har {count} +@msg `{file}` isn't a VectorCraft document, a PDF or a PDF-compatible .ai file `{file}` er ikke et VectorCraft-dokument, en PDF eller en PDF-kompatibel .ai-fil +@msg no saved preset named `{name}` ingen gemt forudindstilling med navnet `{name}` +@msg no saved preset named `{name}` to rename ingen gemt forudindstilling med navnet `{name}` at omdøbe +@msg `{ID}`: the reference would be larger than {MAX_BYTES} bytes `{ID}`: referencen ville være større end {MAX_BYTES} byte +@msg the artboard is locked tegnefladen er låst +@msg no such spine point intet sådant rygradpunkt +@msg `with` must be a list of at most 10000 spine point indexes `with` skal være en liste med højst 10000 rygradpunktindekser +@msg `with` moves points, not a handle `with` flytter punkter, ikke et håndtag +@msg no such spine segment intet sådant rygradsegment +@msg node {_1} is on a locked artboard node {_1} ligger på en låst tegneflade +@msg not a blend ikke en blanding +@msg not a PICT file ikke en PICT-fil +@msg thumbnail: no page {n} (the file has 1) miniature: ingen side {n} (filen har 1) +@msg select a blend or give `id` markér en blanding, eller angiv `id` +@msg select an Objects on Path group markér en gruppe med objekter på kurve +@msg choose the object to detach with its Select/Move widget vælg det objekt, der skal frigøres, med dets Markér/Flyt-kontrol +@msg a path inside a compound path, blend, envelope, repeat or Intertwine group can't take objects en kurve i en sammensat kurve, blanding, kuvert, gentagelse eller sammenfletningsgruppe kan ikke modtage objekter +@msg a clipping path can't take objects en beskæringskurve kan ikke modtage objekter +@msg objects inside a blend, envelope, repeat or Intertwine group can't be attached to a path objekter i en blanding, kuvert, gentagelse eller sammenfletningsgruppe kan ikke knyttes til en kurve +@msg a clipping path can't be attached to a path en beskæringskurve kan ikke knyttes til en kurve +@msg `background` must be edges, corners or colors `background` skal være edges, corners eller colors +@msg `match` must be distance or channels `match` skal være distance eller channels +@msg `{key}` must be from 0 to 100 `{key}` skal være fra 0 til 100 +@msg `colors` must list 1 to 16 colors, each hex (#rrggbb or #rgb) or black, white, red, green or blue `colors` skal angive 1 til 16 farver, hver som hex (#rrggbb eller #rgb) eller black, white, red, green eller blue +@msg the linked image shows its preview: embed or relink it first det sammenkædede billede viser sin forhåndsvisning: integrér det, eller genopret linket først +@msg a CMYK image has no transparency to set et CMYK-billede har ingen gennemsigtighed at angive +@msg every pixel matches the background: no image would be left hver pixel matcher baggrunden: der ville ikke være noget billede tilbage +@msg an image of {w} × {h} pixels is too large to change et billede på {w} × {h} pixels er for stort til at ændre +@msg select an image with a color mask markér et billede med en farvemaske +@msg the color mask's settings are out of range farvemaskens indstillinger er uden for området +@msg a CMYK image can't take a color mask et CMYK-billede kan ikke få en farvemaske +@msg the mask would hide every pixel masken ville skjule hver pixel +@msg Recolor completed; {locked} and {hidden} were left unchanged Omfarvning fuldført; {locked} og {hidden} blev ikke ændret +@msg Recolor completed; {objects} were left unchanged Omfarvning fuldført; {objects} blev ikke ændret +@msg Recolor completed; {objects} was left unchanged Omfarvning fuldført; {objects} blev ikke ændret +@msg 1 locked object 1 låst objekt +@msg {n} locked objects {n} låste objekter +@msg 1 hidden object 1 skjult objekt +@msg {n} hidden objects {n} skjulte objekter +@msg t, dx and dy must be finite t, dx og dy skal være endelige +@msg the blend has no spine blandingen har ingen rygrad +@msg the spine has no segments rygraden har ingen segmenter +@msg panels can't be shown in Presentation Mode paneler kan ikke vises i Præsentationstilstand +@msg unknown preset `{name}`: not a built-in or saved preset (see imageTrace.presets) ukendt forudindstilling `{name}`: ikke en indbygget eller gemt forudindstilling (se imageTrace.presets) +@msg variables are locked variablerne er låst +@msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} mere end {MAX_CSV_ROWS} datasæt: Importér datasæt læser højst {MAX_CSV_ROWS} +@msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} mere end {MAX_CSV_COLS} variabler: Importér datasæt læser højst {MAX_CSV_COLS} +@msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` og `options.{key}: {inner}` er uenige: angiv indstillingen én gang +@msg x and y must be finite x og y skal være endelige +@msg {_1} is an exporter (File › Export › Export As…) {_1} er en eksportør (Filer › Eksportér › Eksportér som…) +@msg `documentData` is {size} bytes (limit {MAX_DOCUMENT_DATA}) `documentData` fylder {size} byte (grænse {MAX_DOCUMENT_DATA}) +@msg a mask that covers several layers comes in as a clipping group in each layer it covers en maske, der dækker flere lag, indlæses som en beskæringsgruppe i hvert lag, den dækker +@msg a graph's records don't end where they should: its art was read as it is en grafs poster slutter ikke, hvor de skal: dens grafik blev læst, som den er +@msg `{w}` takes no operands `{w}` tager ingen operander +@msg a wraparound group is inside a compound path en ombrydningsgruppe ligger i en sammensat kurve +@msg it ends inside a multi-layer mask den slutter inde i en maske over flere lag +@msg a multi-layer mask's operators are out of order operatorerne i en maske over flere lag står i forkert rækkefølge +@msg a multi-layer mask needs one clipping path en maske over flere lag kræver én beskæringskurve +@msg a group crosses a multi-layer mask en gruppe krydser en maske over flere lag +@msg graphs come in as plain art, without their data or settings grafer indlæses som almindelig grafik uden deres data eller indstillinger +@msg the active document changed while the question was open; nothing was deleted det aktive dokument ændrede sig, mens spørgsmålet var åbent; intet blev slettet +@msg The link is inside a symbol, graph design, pattern or opacity mask and has no place on the canvas Linket ligger i et symbol, et grafdesign, et mønster eller en opacitetsmaske og har ingen plads på lærredet +@msg source must be the id of a Shaper Group's original shape source skal være id’et for en shapergruppes oprindelige form +@msg group must be the id of a Shaper Group group skal være id’et for en shapergruppe +@msg the shape is not an editable original shape of that Shaper Group formen er ikke en redigerbar oprindelig form i den shapergruppe +@msg id {value} is a layer, not an object id {value} er et lag, ikke et objekt +@msg id {value} is a layer, not an object; move layers with layer.move id {value} er et lag, ikke et objekt; flyt lag med layer.move +@msg the PCX file is cut short PCX-filen er afkortet +@msg the PCX file's header is damaged PCX-filens header er beskadiget +@msg PCX files with {bits}-bit pixels in {planes} planes can't be read PCX-filer med {bits}-bit-pixels i {planes} planer kan ikke læses +@msg the Pixar file is cut short Pixar-filen er afkortet +@msg the Pixar file's header is damaged Pixar-filens header er beskadiget +@msg the Pixar file's image data is damaged Pixar-filens billeddata er beskadigede +@msg the JPEG 2000 file can't be read JPEG 2000-filen kan ikke læses +@msg the JPEG 2000 file has an unsupported color space or JPX content JPEG 2000-filen har et farverum eller JPX-indhold, der ikke understøttes +@msg the HEIC or HEIF file can't be read HEIC- eller HEIF-filen kan ikke læses +@msg the HEIC or HEIF file holds a kind of image that can't be read HEIC- eller HEIF-filen indeholder en billedtype, der ikke kan læses +@msg HEIC and HEIF images can't be opened in this build HEIC- og HEIF-billeder kan ikke åbnes i denne version +@msg the JPEG XL file is cut short JPEG XL-filen er afkortet +@msg the JPEG XL container is too large to read JPEG XL-containeren er for stor til at blive læst +@msg CMYK JPEG XL images can't be read CMYK-billeder i JPEG XL kan ikke læses +@msg the JPEG XL file can't be read: {e} JPEG XL-filen kan ikke læses: {e} +@msg Extrude & Bevel Ekstrudér og facet +@msg Revolve Omdrej +@msg Inflate Pust op +@msg Rotate Rotér +@msg Extrude & Bevel (Classic) Ekstrudér og facet (klassisk) +@msg Revolve (Classic) Omdrej (klassisk) +@msg Rotate (Classic) Rotér (klassisk) +@msg This effect Denne effekt +@msg clipping paths beskæringskurver +@msg other objects andre objekter +@msg {label} requires a group holding a shape with at least two anchors {label} kræver en gruppe, der indeholder en form med mindst to ankerpunkter +@msg Revolve requires a group holding a shape with at least two anchors Omdrej kræver en gruppe, der indeholder en form med mindst to ankerpunkter +@msg Revolve requires a shape with at least two anchors Omdrej kræver en form med mindst to ankerpunkter +@msg {label} on a group needs paths, compound paths, type, groups, clipping groups, blends and symbol instances: release or expand its {what} first. {label} på en gruppe kræver kurver, sammensatte kurver, tekst, grupper, beskæringsgrupper, blandinger og symbolforekomster: frigør eller udvid først dens {what}. +@msg {label} on a group takes at most {MAX_MEMBERS} objects {label} på en gruppe tager højst {MAX_MEMBERS} objekter +@msg A 3D effect on a group or layer goes on the group itself, not on its fill or stroke En 3D-effekt på en gruppe eller et lag anvendes på selve gruppen, ikke på dens udfyldning eller streg +@msg a 3D effect on a group's fill or stroke draws nothing en 3D-effekt på en gruppes udfyldning eller streg tegner intet +@msg a 3D effect on a group's fill or stroke draws nothing to export en 3D-effekt på en gruppes udfyldning eller streg tegner intet at eksportere +@msg The 3D object is too complex to export 3D-objektet er for komplekst til at blive eksporteret +@msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) objektet har ingen 3D-effekt (Ekstrudér og facet, Omdrej, Pust op eller Rotér) +@msg its 3D effect builds no solid dens 3D-effekt danner intet legeme +@msg bevel must be none or one of {_1} bevel skal være none eller en af {_1} +@msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1} kan ikke danne legemer af denne grafik: dens symbolforekomster, blandinger og beskæringsgrupper indeholder for mange objekter +@msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label} kan ikke danne et legeme af forekomsten af symbolet "{symbol}": symbolets grafik er ikke tilgængelig +@msg {_1}: the clipping path is too complex to cut the art with {_1}: beskæringskurven er for kompleks til at skære grafikken med +@msg {_1} takes at most {MAX_MEMBERS} objects {_1} tager højst {MAX_MEMBERS} objekter +@msg {_1} can't build solids from art nested more than {MAX_DEPTH} levels deep {_1} kan ikke danne legemer af grafik, der er indlejret mere end {MAX_DEPTH} niveauer dybt +@msg Revolve paint is too complex for this surface; reduce Segments or simplify the gradient Omdrej-malingen er for kompleks til denne overflade; reducér Segmenter, eller forenkl gradienten +@msg Revolve edge must be left or right Omdrej: edge skal være left eller right +@msg Revolve cap must be a boolean Omdrej: cap skal være en boolesk værdi +@msg the revolved object has no fill or stroke det omdrejede objekt har ingen udfyldning eller streg +@msg lightColor must be an opaque RGB color in #rrggbb form lightColor skal være en uigennemsigtig RGB-farve i formen #rrggbb +@msg lights must contain one to ten lights lights skal indeholde et til ti lys +@msg each light must be an object hvert lys skal være et objekt +@msg unknown light setting: use color, intensity, rotation, height, softness or behind ukendt lysindstilling: brug color, intensity, rotation, height, softness eller behind +@msg light {key} must be a number from {min} to {max} lys: {key} skal være et tal fra {min} til {max} +@msg light color must use opaque #rrggbb lys: color skal bruge uigennemsigtig #rrggbb +@msg light behind must be true or false lys: behind skal være true eller false +@msg shadow must be true or false shadow skal være true eller false +@msg shadowPosition must be behind or below shadowPosition skal være behind eller below +@msg {key} must be a number from {min} to {max} {key} skal være et tal fra {min} til {max} +@msg each of `{GRAPHICS}` must be an object hvert element i `{GRAPHICS}` skal være et objekt +@msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` elementer i `{GRAPHICS}` tager symbol, face, x, y, scale og rotation, ikke `{k}` +@msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol hvert element i `{GRAPHICS}` kræver `symbol`, navnet på et symbol +@msg `{GRAPHICS}` face must be front or back `{GRAPHICS}`: face skal være front eller back +@msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} `{GRAPHICS}`: {key} skal være et tal fra {lo} til {hi} +@msg `{GRAPHICS}` must be an array `{GRAPHICS}` skal være et array +@msg Graphics map onto the Plane, Extrude and Revolve object types Grafik kortlægges på objekttyperne Plan, Ekstrudér og Omdrej +@msg Revolve maps graphics onto its side: map them onto the front Omdrej kortlægger grafik på siden: kortlæg den på forsiden +@msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Grafikken er for kompleks til denne overflade: forenkl symbolernes grafik, eller reducér Segmenter +@msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` tager højst {MAX_GRAPHICS} grafikelementer +@msg A plane has one face: map its graphics onto the front Et plan har én flade: kortlæg dets grafik på forsiden +@msg The graphics are too complex: simplify the symbols' art Grafikken er for kompleks: forenkl symbolernes grafik +@msg A graphic's art may be nested at most {MAX_LEVELS} levels deep: simplify the symbol's art Et grafikelements grafik må højst være indlejret {MAX_LEVELS} niveauer dybt: forenkl symbolets grafik +@msg A graphic's art may nest symbols at most {MAX_NESTING} levels deep: simplify the symbol's art Et grafikelements grafik må højst indlejre symboler {MAX_NESTING} niveauer dybt: forenkl symbolets grafik +@msg A graphic's art holds too many objects: simplify the symbol's art Et grafikelements grafik indeholder for mange objekter: forenkl symbolets grafik +@msg A graphic draws at most {MAX_PIECES} fills and strokes: simplify the symbol's art Et grafikelement tegner højst {MAX_PIECES} udfyldninger og streger: forenkl symbolets grafik +@msg `surface` must be one of {_1} `surface` skal være en af {_1} +@msg {label} draws the source art for this object instead of its 3D surface {label} tegner kildegrafikken for dette objekt i stedet for dets 3D-overflade +@msg {label} draws no faces for this object {label} tegner ingen flader for dette objekt +@msg the wireframe has more than {MAX_WIRE_EDGES} edges trådmodellen har mere end {MAX_WIRE_EDGES} kanter +@msg the params must be an object, not {got} parametrene skal være et objekt, ikke {got} +@msg unknown parameter `{path}`; the object takes no keys ukendt parameter `{path}`; objektet tager ingen nøgler +@msg unknown parameter `{path}`; it takes: {keys} ukendt parameter `{path}`; den tager: {keys} +@msg missing `{path}` `{path}` mangler +@msg `{path}` must be {expected}, not {got} `{path}` skal være {expected}, ikke {got} +@msg `{path}` is nested too deeply `{path}` er indlejret for dybt +@msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}: ikke et PNG-, JPEG-, WebP-, TIFF- eller BMP-billede +@msg the image is {iw} × {ih} pixels and the artboard at that width is {rw} × {rh} pixels: their proportions differ billedet er {iw} × {ih} pixels, og tegnefladen i den bredde er {rw} × {rh} pixels: deres proportioner er forskellige +@msg `threshold` must be a number from 0 to 1 `threshold` skal være et tal fra 0 til 1 +@msg background {v}: a color such as "#808080" baggrund {v}: en farve som "#808080" +@msg comparing with an image file isn't available in the browser sammenligning med en billedfil er ikke tilgængelig i browseren +@msg columns {first} and {column} both name the variable `{name}` kolonnerne {first} og {column} angiver begge variablen `{name}` +@msg nothing in data set {name} was applied: no object is bound to a variable it has a value for intet i datasættet {name} blev anvendt: intet objekt er bundet til en variabel, som det har en værdi for +@msg no bound object reports a value (locked objects and embedded images report none) intet bundet objekt rapporterer en værdi (låste objekter og integrerede billeder rapporterer ingen) +@msg Edit Original opens image and document files only; “{name}” is not one Redigér original åbner kun billed- og dokumentfiler; »{name}« er ikke en sådan +@msg only http, https and mailto URLs open in the browser, not “{url}” kun http-, https- og mailto-URL’er åbnes i browseren, ikke »{url}« +@msg {id} opens another app: only the person at the keyboard can run it {id} åbner et andet program: kun personen ved tastaturet kan køre den +@msg “{name}” is not a file »{name}« er ikke en fil +@msg a mask has more than one art block en maske har mere end én grafikblok +@msg mask art ends outside a mask dictionary maskegrafik slutter uden for en maskeordbog +@msg cancelled; nothing was changed annulleret; intet blev ændret +@msg a linked image can't become a gradient mesh: embed it first et sammenkædet billede kan ikke blive et gradientnet: integrér det først +@msg the image has no usable size or position billedet har ingen brugbar størrelse eller position +@msg the image's pixels can't be read billedets pixels kan ikke læses +@msg Persistent libraries not found: {files} Vedvarende biblioteker blev ikke fundet: {files} +@msg `{given}` isn't a library panel (see window.swatchLibrary) `{given}` er ikke et bibliotekspanel (se window.swatchLibrary) +@msg library panel `{given}` isn't open bibliotekspanelet `{given}` er ikke åbent +@msg too many changed shortcuts for mange ændrede genveje +@msg library panel `{given}` isn't missing its library bibliotekspanelet `{given}` mangler ikke sit bibliotek +@msg too many library panels were opened in this session der blev åbnet for mange bibliotekspaneler i denne session +@msg The image is {_1} × {_2} pixels, more than {LARGE_TRACE_SIDE} on a side: it is traced, but more slowly. A lower-fidelity preset or a smaller copy of the image traces faster. Billedet er {_1} × {_2} pixels, mere end {LARGE_TRACE_SIDE} på en side: det spores, men langsommere. En forudindstilling med lavere præcision eller en mindre kopi af billedet spores hurtigere. +@msg The image was traced at {_1} × {_2} pixels, scaled down from {_3} × {_4} ({_5} megapixels at most). Billedet blev sporet ved {_1} × {_2} pixels, skaleret ned fra {_3} × {_4} (højst {_5} megapixel). +@msg byColor must be true or false byColor skal være true eller false +@msg byColor can't split Auto Grouping groups: trace without Auto Grouping byColor kan ikke opdele grupper fra Autogruppering: spor uden Autogruppering +@msg byColor can't regroup a trace with a live Pathfinder effect: expand without byColor byColor kan ikke omgruppere en sporing med en live Pathfinder-effekt: udvid uden byColor +@msg Flat Logo mode does not use keepColors: it traces the colors named in logoColors, or the colors it finds. Tilstanden Fladt logo bruger ikke keepColors: den sporer de farver, logoColors angiver, eller de farver, den finder. +@msg Nothing was traced: none of the colors the trace found matches keepColors ({_1}). Intet blev sporet: ingen af de farver, sporingen fandt, matcher keepColors ({_1}). +@msg Nothing was traced: Ignore Color leaves out every area of the colors keepColors lists. Intet blev sporet: Ignorér farve udelader alle områder med de farver, keepColors angiver. +@msg Nothing was traced: the colors that match keepColors produce no paths. Intet blev sporet: de farver, der matcher keepColors, danner ingen kurver. +@msg keepColors: none of the colors the trace found matches {c}, so nothing of it is traced. keepColors: ingen af de farver, sporingen fandt, matcher {c}, så intet af den spores. +@msg `colorGroup` needs `library: "document"` `colorGroup` kræver `library: "document"` +@msg `colorGroup` needs `palette: "documentLibrary"` `colorGroup` kræver `palette: "documentLibrary"` +@msg `colorGroup` needs `mode: "color"` `colorGroup` kræver `mode: "color"` +@msg no color group `{name}` in the document (see swatch.list) ingen farvegruppe `{name}` i dokumentet (se swatch.list) +@msg Flat Logo traced the image at {_1} × {_2} pixels, averaged down from {_3} × {_4}. Fladt logo sporede billedet ved {_1} × {_2} pixels, udjævnet ned fra {_3} × {_4}. +@msg {label} keeps 1 of the document's {n} artboards: the file reopens with one. Turn on Preserve Editing Capabilities to keep them all. {label} beholder 1 af dokumentets {n} tegneflader: filen genåbnes med én. Slå Bevar redigeringsfunktioner til for at beholde dem alle. +@msg `spread` must be pad, repeat or reflect `spread` skal være pad, repeat eller reflect +@msg `repeats` must be a whole number from 1 to {MAX_REPEATS} `repeats` skal være et heltal fra 1 til {MAX_REPEATS} +@msg `spread` applies to linear, radial, conic and diamond gradients `spread` gælder for lineære, radiale, koniske og diamantformede gradienter +@msg {_1} finished, but the document or the plug-in changed meanwhile: run it again {_1} blev færdig, men dokumentet eller plug-in'et ændrede sig i mellemtiden: kør det igen +@msg Running “{name}”… Kører »{name}«… +@msg a live effect runs while the document is drawn, so it can't be `heavy` en live-effekt kører, mens dokumentet tegnes, så den kan ikke være `heavy` +@msg an exporter always gets an export's budget: leave `budget` out en eksportør får altid et eksportbudget: udelad `budget` +@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants »{_1}« beder om et tungt budget (hver kørsel op til {minutes} minutter og {times} gange de sædvanlige instruktioner): en person skal godkende det i skrivebordsappen, eller send `allowHeavy: true` i en session startet med --allow-plugin-grants +@msg `name` must be 1-64 printable characters `name` skal være 1-64 tegn, der kan udskrives +@msg `version`, `description` or `author` is too long `version`, `description` eller `author` er for lang +@msg `warnings` must be a list of strings `warnings` skal være en liste med strenge +@msg `{k}` must be one of {_1} `{k}` skal være en af {_1} +@msg `{k}` must be {what} `{k}` skal være {what} +@msg an exporter declares 1 to {MAX_EXTENSIONS} `extensions` en eksportør angiver 1 til {MAX_EXTENSIONS} `extensions` +@msg at most {MAX_UNGROUPED} parameters outside groups: give the others a `group` højst {MAX_UNGROUPED} parametre uden for grupper: giv de andre en `group` +@msg can't encode the input kan ikke kode inputtet +@msg expected {{"dataBase64": "…"}} forventet: {{"dataBase64": "…"}} +@msg expected {{"objects": [...]}} forventet: {{"objects": [...]}} +@msg export `{name}`: {e} eksport `{name}`: {e} +@msg extension {e} is listed twice filtypenavnet {e} er angivet to gange +@msg extension {e}: use 1-16 lower-case letters and digits, without the dot filtypenavn {e}: brug 1-16 små bogstaver og cifre uden punktum +@msg invalid id {_1}: use 1-64 characters from A-Z a-z 0-9 . _ - ugyldigt id {_1}: brug 1-64 tegn fra A-Z a-z 0-9 . _ - +@msg invalid parameter name {k} ugyldigt parameternavn {k} +@msg manifest is not UTF-8 manifestet er ikke UTF-8 +@msg manifest is too long (limit {MAX_MANIFEST_BYTES} bytes) manifestet er for langt (grænse {MAX_MANIFEST_BYTES} byte) +@msg manifest is {_1} bytes (limit {MAX_MANIFEST_BYTES}) manifestet fylder {_1} byte (grænse {MAX_MANIFEST_BYTES}) +@msg module is {_1} bytes (limit {_2}) modulet fylder {_1} byte (grænse {_2}) +@msg needs approval: it asks for {0}, which the user grants when installing it on its own kræver godkendelse: det beder om {0}, som brugeren tildeler, når det installeres for sig selv +@msg not JSON: {e} ikke JSON: {e} +@msg not a WebAssembly binary (missing \0asm header) ikke en WebAssembly-binærfil (headeren \0asm mangler) +@msg parameter `{k}`: {what} parameteren `{k}`: {what} +@msg parameter `{name}`: {what} parameteren `{name}`: {what} +@msg plug-in parameters must be a JSON object plug-in-parametrene skal være et JSON-objekt +@msg the module must export its linear memory as `memory` modulet skal eksportere sin lineære hukommelse som `memory` +@msg the objects to change are no longer in the document de objekter, der skal ændres, er ikke længere i dokumentet +@msg the runtime panicked runtime-miljøet gik i panik +@msg unexpected host trap uventet trap i værten +@msg vc_abi_version returned {v}; this host implements version {ABI_VERSION} vc_abi_version returnerede {v}; denne vært implementerer version {ABI_VERSION} +@msg vc_alloc returned 0 (out of memory) vc_alloc returnerede 0 (ikke mere hukommelse) +@msg vc_alloc returned a block outside memory vc_alloc returnerede en blok uden for hukommelsen +@msg vc_run returned error code {packed} vc_run returnerede fejlkoden {packed} +@msg {_1} is not a file {_1} er ikke en fil +@msg {_1} is {_2} bytes (limit {_3}) {_1} fylder {_2} byte (grænse {_3}) +@msg {_1} objects (limit {MAX_OBJECTS}) {_1} objekter (grænse {MAX_OBJECTS}) +@msg {at}: {msg} {at}: {msg} +@msg {what} points outside memory {what} peger uden for hukommelsen +@msg `angle` must be a number `angle` skal være et tal +@msg `aspect` must be from 0.01 to 100 `aspect` skal være fra 0,01 til 100 +@msg `cap` must be "butt", "round" or "square" `cap` skal være "butt", "round" eller "square" +@msg `fillRule` must be "nonzero" or "evenodd" `fillRule` skal være "nonzero" eller "evenodd" +@msg `helpUrl` must be an https:// address of at most {MAX_HELP_URL} bytes `helpUrl` skal være en https://-adresse på højst {MAX_HELP_URL} byte +@msg `help` must be 1-{MAX_HELP} printable characters `help` skal være 1-{MAX_HELP} tegn, der kan udskrives +@msg `id` must be an effect id of 1-{MAX_EFFECT_ID} bytes `id` skal være et effekt-id på 1-{MAX_EFFECT_ID} byte +@msg `id` must be the id of an input object `id` skal være id’et for et inputobjekt +@msg `join` must be "miter", "round" or "bevel" `join` skal være "miter", "round" eller "bevel" +@msg `label` and `group` must be 1-{MAX_LABEL} printable characters `label` og `group` skal være 1-{MAX_LABEL} tegn, der kan udskrives +@msg `maxLength` must be 1-{MAX_TEXT}, and the default no longer `maxLength` skal være 1-{MAX_TEXT}, og standardværdien må ikke være længere +@msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many `minItems` og `maxItems` skal være 0-{MAX_LIST}, `maxItems` mindst 1, og standardværdien skal have så mange +@msg `name` must be a string `name` skal være en streng +@msg `opacity` must be a number `opacity` skal være et tal +@msg `type` must be "path" or "compound" `type` skal være "path" eller "compound" +@msg `unit` must be 1-{MAX_UNIT} printable characters `unit` skal være 1-{MAX_UNIT} tegn, der kan udskrives +@msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` `visibleWhen` angiver 1 til {MAX_CONDITION_VALUES} værdier for `{other}` +@msg `visibleWhen` names `{other}`, which isn't a parameter declared before this one `visibleWhen` angiver `{other}`, som ikke er en parameter, der er erklæret før denne +@msg `visibleWhen` names at most {MAX_CONDITIONS} parameters `visibleWhen` angiver højst {MAX_CONDITIONS} parametre +@msg `visibleWhen` takes `{other}`'s values, of a checkbox or a choice `visibleWhen` tager værdierne for `{other}`, fra et afkrydsningsfelt eller et valg +@msg `visible` must be true or false `visible` skal være true eller false +@msg `{key}` must be a number from {_1} to {_2} `{key}` skal være et tal fra {_1} til {_2} +@msg `{key}` must be an array of at most {MAX_ITEMS} entries `{key}` skal være et array med højst {MAX_ITEMS} elementer +@msg a color default must be a color object or a hex string such as "#3a7bd5" en standardfarve skal være et farveobjekt eller en hex-streng som "#3a7bd5" +@msg a color object or a hex string such as "#3a7bd5" et farveobjekt eller en hex-streng som "#3a7bd5" +@msg a freeform gradient holds at most {MAX_ITEMS} points and lines en friformsgradient indeholder højst {MAX_ITEMS} punkter og linjer +@msg a freeform gradient line names a point it doesn't have en linje i en friformsgradient angiver et punkt, som gradienten ikke har +@msg a gradient needs 1-{MAX_ITEMS} stops en gradient kræver 1-{MAX_ITEMS} farvestop +@msg a list of numbers en liste med tal +@msg a list of {min_items} to {max_items} numbers en liste med {min_items} til {max_items} tal +@msg a new object needs a `path` et nyt objekt kræver en `path` +@msg a number et tal +@msg a painted live effect returns only `objects` en malet live-effekt returnerer kun `objects` +@msg a painted live effect's piece has only `path`, `fillRule`, `fills` and `strokes` et stykke fra en malet live-effekt har kun `path`, `fillRule`, `fills` og `strokes` +@msg a read-only object was left out et skrivebeskyttet objekt blev udeladt +@msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given et skrivebeskyttet objekt blev udeladt: returnér det, som {{"id": …}} alene eller som det blev givet +@msg a string en streng +@msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` en streg har kun `paint`, `width`, `join`, `cap` og `miterLimit` +@msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} en streg skal være {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} +@msg an effect must be {{"id", "params"?, "visible"?}} en effekt skal være {{"id", "params"?, "visible"?}} +@msg an effect on a fill returns only `fills` en effekt på en udfyldning returnerer kun `fills` +@msg an effect on a stroke returns only `strokes` en effekt på en streg returnerer kun `strokes` +@msg an object must be a JSON object et objekt skal være et JSON-objekt +@msg bad range ugyldigt interval +@msg choices must be 1-64 non-empty, printable strings valgmulighederne skal være 1-64 ikke-tomme strenge, der kan udskrives +@msg coordinate out of range (limit ±{MAX_COORD} pt) koordinat uden for området (grænse ±{MAX_COORD} pt) +@msg default is not one of the options standardværdien er ikke en af valgmulighederne +@msg each piece needs a `path` hvert stykke kræver en `path` +@msg is listed twice er angivet to gange +@msg pattern transform out of range mønstertransformation uden for området +@msg read-only field '{field}' changed det skrivebeskyttede felt '{field}' blev ændret +@msg stops must be in order of `offset` farvestoppene skal stå i rækkefølge efter `offset` +@msg the document has no pattern {pattern} dokumentet har intet mønster {pattern} +@msg the document has no swatch {n} dokumentet har ingen farveprøve {n} +@msg the output outputtet +@msg the path has no anchor points kurven har ingen ankerpunkter +@msg too many anchor points (limit {MAX_ANCHORS}) for mange ankerpunkter (grænse {MAX_ANCHORS}) +@msg true or false true eller false +@msg a number >= {_1} et tal >= {_1} +@msg a number > {_1} et tal > {_1} +@msg a number <= {_1} et tal <= {_1} +@msg a number < {_1} et tal < {_1} +@msg a number {_1} to {_2} et tal fra {_1} til {_2} +@msg a number >= {_1} and < {_2} et tal >= {_1} og < {_2} +@msg a number > {_1} and <= {_2} et tal > {_1} og <= {_2} +@msg a number > {_1} and < {_2} et tal > {_1} og < {_2} +@msg a number ({_1}) et tal ({_1}) +@msg a number >= {_1} ({_2}) et tal >= {_1} ({_2}) +@msg a number > {_1} ({_2}) et tal > {_1} ({_2}) +@msg a number <= {_1} ({_2}) et tal <= {_1} ({_2}) +@msg a number < {_1} ({_2}) et tal < {_1} ({_2}) +@msg a number {_1} to {_2} ({_3}) et tal fra {_1} til {_2} ({_3}) +@msg a number >= {_1} and < {_2} ({_3}) et tal >= {_1} og < {_2} ({_3}) +@msg a number > {_1} and <= {_2} ({_3}) et tal > {_1} og <= {_2} ({_3}) +@msg a number > {_1} and < {_2} ({_3}) et tal > {_1} og < {_2} ({_3}) +@msg an integer et heltal +@msg an integer >= {_1} et heltal >= {_1} +@msg an integer <= {_1} et heltal <= {_1} +@msg an integer {_1} to {_2} et heltal fra {_1} til {_2} +@msg one of {_1} en af {_1} +@msg an object id (a non-negative integer) et objekt-id (et ikke-negativt heltal) +@msg a list of object ids en liste med objekt-id’er +@msg a color (a string, [r, g, b] or an object) en farve (en streng, [r, g, b] eller et objekt) +@msg [x, y] (two numbers) [x, y] (to tal) +@msg an object et objekt +@msg a list en liste +@msg unknown key `{k}`; the keys here are {_1} ukendt nøgle `{k}`; nøglerne her er {_1} +@msg {_1} is listed twice {_1} er angivet to gange +@msg {_1} is not the id of an input object {_1} er ikke id’et for et inputobjekt +@msg {_1} is read-only {_1} er skrivebeskyttet +@msg {what} must be from {lo} to {hi} {what} skal være fra {lo} til {hi} +@msg a color component en farvekomponent +@msg a plate en plade +@msg Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. Automatiseringen bad om at installere dette plug-in. Vælg selv Objekt › Plug-ins › Installér plug-in… for at installere det. +@msg “{name}” is another module than the plug-in with id {_1} and would get the settings and cache kept for it: install it with `replace: true` once the user agrees »{name}« er et andet modul end plug-in'et med id {_1} og ville få de indstillinger og den cache, der er gemt til det: installér det med `replace: true`, når brugeren accepterer +@msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call »{name}« angiver `{id}` i `commandAllowlist`, som et plug-in ikke må kalde +@msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} +@msg vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it vc_call `{shown}`: manifestets `commandAllowlist` angiver den ikke +@msg vc_call `{shown}`: the id or the arguments lie outside the module's memory vc_call `{shown}`: id’et eller argumenterne ligger uden for modulets hukommelse +@msg vc_call `{shown}`: the id or the arguments are not UTF-8 vc_call `{shown}`: id’et eller argumenterne er ikke UTF-8 +@msg vc_call `{shown}`: the arguments are not a JSON object vc_call `{shown}`: argumenterne er ikke et JSON-objekt +@msg only a filter with the usual budget declares `commandAllowlist` kun et filter med det sædvanlige budget angiver `commandAllowlist` +@msg command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run) kommandokald ({MAX_CALLS} kald og {MAX_CALL_BYTES} byte pr. kørsel) +@msg command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA}) kommandokaldets størrelse (vc_call `{shown}`: {len} byte, grænse {MAX_CALL_DATA}) +@msg at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist` højst {MAX_ALLOWED_COMMANDS} kommandoer i `commandAllowlist` +@msg a plug-in may not call this command et plug-in må ikke kalde denne kommando +@msg `commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist` `commandAllowlist` kræver tilladelsen `commands`, og `commands` kræver en `commandAllowlist` +@msg `commandAllowlist` names `{shown}`, which is not a command id or is listed twice `commandAllowlist` angiver `{shown}`, som ikke er et kommando-id eller er angivet to gange +@msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} tilladelsen `{permission}` kræver plug-in-API-niveau {PROGRESS_API}: angiv `api` {PROGRESS_API} +@msg the module imports `env.{name}` with another type than the host's: it is {signature} modulet importerer `env.{name}` med en anden type end værtens: den er {signature} +@msg the module imports `env.{name}`, which a plug-in may use only at plug-in API level {PROGRESS_API} (`api` {PROGRESS_API}) and with the permission `{permission}` modulet importerer `env.{name}`, som et plug-in kun må bruge på plug-in-API-niveau {PROGRESS_API} (`api` {PROGRESS_API}) og med tilladelsen `{permission}` +@msg the module imports `{from}.{name}`, which the host doesn't offer: a plug-in may import only the `env.vc_*` functions that docs/plugins.md lists (plug-in API level 2), and no WASI, files or network modulet importerer `{from}.{name}`, som værten ikke tilbyder: et plug-in må kun importere de `env.vc_*`-funktioner, som docs/plugins.md angiver (plug-in-API-niveau 2), og ingen WASI, filer eller netværk +@msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api` er {_1}; denne vært implementerer plug-in-API-niveau 1 til {API_LEVEL} +@msg `paintOutput` may only be true `paintOutput` må kun være true +@msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 `paintOutput` er kun til en live-effekt (`kind` "effect") ved `api` 2 +@msg `grant` must be a list of permission names `grant` skal være en liste med tilladelsesnavne +@msg `grant` names an unknown permission `{shown}` `grant` angiver en ukendt tilladelse `{shown}` +@msg a plug-in of kind `{_1}` needs the permission `{_2}` et plug-in af typen `{_1}` kræver tilladelsen `{_2}` +@msg at most {MAX_PERMISSIONS} `permissions` højst {MAX_PERMISSIONS} `permissions` +@msg permission `{shown}` doesn't apply to a plug-in of kind `{_1}` tilladelsen `{shown}` gælder ikke for et plug-in af typen `{_1}` +@msg permission `{shown}` is listed twice tilladelsen `{shown}` er angivet to gange +@msg only a filter declares `inputs` kun et filter angiver `inputs` +@msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` angiver en ukendt objekttype `{shown}`: brug type, image eller symbolInstance +@msg `inputs` lists `{shown}` twice `inputs` angiver `{shown}` to gange +@msg `inputs` needs `api` 2 or later `inputs` kræver `api` 2 eller nyere +@msg `inputs` needs the permission `doc.read` `inputs` kræver tilladelsen `doc.read` +@msg memory budget (object {_1} needs {size} bytes of input, {left} left) hukommelsesbudget (objekt {_1} kræver {size} byte input, {left} tilbage) +@msg object budget (more than {MAX_OBJECTS} read-only objects) objektbudget (mere end {MAX_OBJECTS} skrivebeskyttede objekter) +@msg instruction budget instruktionsbudget +@msg time budget tidsbudget +@msg memory budget (the selection is too large to hand over) hukommelsesbudget (markeringen er for stor til at blive overdraget) +@msg output size ({what} is {len} bytes, limit {max}) outputstørrelse ({what} fylder {len} byte, grænse {max}) +@msg the plug-in's grant can't be removed from the plug-in store plug-in'ets tilladelse kan ikke fjernes fra plug-in-lageret +@msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it tilladelsen `{shown}` er reserveret til et senere plug-in-API; denne vært tildeler den ikke +@msg unknown permission `{shown}` ukendt tilladelse `{shown}` +@msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants »{name}« beder om tilladelserne {asked}: en person skal godkende dem i skrivebordsappen, eller send `grant` i en session startet med --allow-plugin-grants +@msg `grant` and `allowHeavy` take effect only in a session started with --allow-plugin-grants: approve the plug-in in the desktop app `grant` og `allowHeavy` virker kun i en session startet med --allow-plugin-grants: godkend plug-in'et i skrivebordsappen +@msg Only the person at the keyboard can approve installing a plug-in Kun personen ved tastaturet kan godkende installation af et plug-in +@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed »{name}« fik ikke tildelt `{p}`, som dets output kræver: intet blev ændret +@msg a heavy filter runs in the background, so it can't declare `commands` et tungt filter kører i baggrunden, så det kan ikke angive `commands` +@msg at most {MAX_COMMANDS} `commands` højst {MAX_COMMANDS} `commands` +@msg command {name} is declared twice kommandoen {name} er erklæret to gange +@msg command {name}: `label` must be 1-64 printable characters kommandoen {name}: `label` skal være 1-64 tegn, der kan udskrives +@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter kommandoen {name}: brug et id på 1-{MAX_COMMAND_ID} tegn fra a-z 0-9 _, der starter med et bogstav +@msg command {name}: {e} kommandoen {name}: {e} +@msg manifest: {e} manifest: {e} +@msg manifest: {e} at line {line} column {column} manifest: {e} på linje {line} kolonne {column} +@msg `commands` must be a list of commands, each with an `id` and a `label` `commands` skal være en liste med kommandoer, hver med et `id` og et `label` +@msg command {name} must be an object with an `id` and a `label` kommandoen {name} skal være et objekt med et `id` og et `label` +@msg missing field `{key}` feltet `{key}` mangler +@msg duplicate field `{key}` dobbelt felt `{key}` +@msg only a filter or a live effect declares `commands` kun et filter eller en live-effekt angiver `commands` +@msg “{name}” › {label}: {e} »{name}« › {label}: {e} +@msg the module doesn't have the SHA-256 `hash` gives: nothing was installed modulet har ikke den SHA-256, som `hash` angiver: intet blev installeret +@msg select one object markér ét objekt +@msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again ingen lignende objekter fundet (roterede eller spejlede kopier matches ikke); ændr Indstillinger for global redigering, og prøv igen +@msg Global Edit is off Global redigering er slået fra +@msg only an object of the Global Edit other than the one it started from can be left out kun et objekt i den globale redigering, bortset fra det, den startede fra, kan udelades +@msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all eller et interval som 1, 3-5, ikke {v} +@msg `{_1}` has no symbols to place `{_1}` har ingen symboler at placere +@msg missing `library` (see symbol.libraries) `library` mangler (se symbol.libraries) +@msg no symbol `{n}` intet symbol `{n}` +@msg no symbol `{n}` in `{_1}` intet symbol `{n}` i `{_1}` +@msg no symbol library `{key}` (see symbol.libraries) intet symbolbibliotek `{key}` (se symbol.libraries) +@msg the document has no symbols to save dokumentet har ingen symboler at gemme +@msg `{_1}` has no brushes to apply `{_1}` har ingen pensler at anvende +@msg missing `library` (see brush.libraries) `library` mangler (se brush.libraries) +@msg no brush `{n}` ingen pensel `{n}` +@msg no brush `{n}` in `{_1}` ingen pensel `{n}` i `{_1}` +@msg no brush library `{key}` (see brush.libraries) intet penselbibliotek `{key}` (se brush.libraries) +@msg the document has no brushes to save dokumentet har ingen pensler at gemme +@msg a {width}×{height} screenshot's byte count overflows bytetallet for et skærmbillede på {width}×{height} løber over +@msg the window's {what} ({points} points × {scale} DPI) cannot size a screenshot vinduets {what} ({points} punkter × {scale} DPI) kan ikke give et skærmbillede en størrelse +@msg {label} must be a number {label} skal være et tal +@msg {label} must be a number of at least 0.1 {label} skal være et tal på mindst 0,1 +@msg {label} must be a number from {min} to {max} {label} skal være et tal fra {min} til {max} +@msg {label} must be a whole number from {min} to {max} {label} skal være et heltal fra {min} til {max} +@msg features lists at most {max} tags features angiver højst {max} tags +@msg unknown OpenType feature `{t}` ukendt OpenType-funktion `{t}` +@msg {label} must be a number above 0 and at most {max} {label} skal være et tal over 0 og højst {max} +@msg {label} must be at most {max} characters {label} må højst være {max} tegn +@msg {label} must be one character {label} skal være ét tegn +@msg at most {max} tab stops højst {max} tabulatorstop +@msg unknown align `{other}` ukendt justering `{other}` +@msg no character style `{name}` ingen tegnstil `{name}` +@msg {_1} is an importer (File › Open With) {_1} er en importør (Filer › Åbn med) +@msg missing `importer` (see document.formats) `importer` mangler (se document.formats) +@msg `importer` must be a plug-in format id (see document.formats) `importer` skal være id’et for et plug-in-format (se document.formats) +@msg “{shown}” opens {_1} files, not `{_2}` »{shown}« åbner {_1}-filer, ikke `{_2}` +@msg `{_1}` is a plug-in of kind `{_2}`, not an importer `{_1}` er et plug-in af typen `{_2}`, ikke en importør +@msg `{_1}` is a plug-in of kind `{_2}`, not an exporter `{_1}` er et plug-in af typen `{_2}`, ikke en eksportør +@msg `{_1}` is an importer: open a file with document.open {{"importer": "{_2}"}} `{_1}` er en importør: åbn en fil med document.open {{"importer": "{_2}"}} +@msg `{_1}` is an exporter: export with document.export {{"format": "{_2}"}} `{_1}` er en eksportør: eksportér med document.export {{"format": "{_2}"}} +@msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} `{_1}` er en live-effekt: anvend den med effect.apply {{"effect": "{_2}"}} +@msg the importer returned no objects importøren returnerede ingen objekter +@msg an importer returns `objects` and `warnings`, not `{key}` en importør returnerer `objects` og `warnings`, ikke `{key}` +@msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads filen er større end de {MAX_INPUT_BYTES} byte, en importør læser +@msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` en importør angiver 1 til {MAX_EXTENSIONS} `extensions` +@msg only an exporter or an importer declares `extensions` kun en eksportør eller en importør angiver `extensions` +@msg an importer always gets an import's budget: leave `budget` out en importør får altid et importbudget: udelad `budget` +@msg only paths and compound paths can be aligned to the pixel grid kun kurver og sammensatte kurver kan justeres til pixelgitteret +@msg `first` and `last` must be numbers of lines the console holds, first before last `first` og `last` skal være numre på linjer, som konsollen indeholder, first før last +@msg no plug-in effect is deferred ingen plug-in-effekt er udskudt +@msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. Åbnede med {n} udskudt plug-in-effekt. Effekt › Opdatér udskudte effekter kører den.|Åbnede med {n} udskudte plug-in-effekter. Effekt › Opdatér udskudte effekter kører dem. +@msg The selected art has no islands to bridge Den markerede grafik har ingen øer at bygge bro over +@msg No bridge of this width fits across the selected art Ingen bro med denne bredde passer hen over den markerede grafik +@msg Some islands could not be joined to the area around the art Nogle øer kunne ikke forbindes med området omkring grafikken +@msg `width` must be from {lo} to {hi} pt `width` skal være fra {lo} til {hi} pt +@msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` skal være et heltal fra 1 til {MAX_BRIDGES_PER_ISLAND} + File Filer New… Ny… New Without Dialog Ny uden dialog @@ -389,6 +998,18 @@ Title Case Stort bogstav i hvert ord Sentence case Stort begyndelsesbogstav Smart Punctuation… Smart tegnsætning… + Smart Punctuation Smart tegnsætning + ff, fi, ffi Ligatures Ligaturer ff, fi, ffi + ff, fl, ffl Ligatures Ligaturer ff, fl, ffl + Smart Quotes Smarte anførselstegn + Smart Spaces Smarte mellemrum + En, Em Dashes Korte og lange tankestreger + Ellipses Udeladelsesprikker + Expert Fractions Ekspertbrøker + Replace In Erstat i + Selected Text Only Kun markeret tekst + Entire Document Hele dokumentet + Report Results Rapportér resultater Create Outlines Opret konturer Optical Margin Alignment Optisk marginjustering Dynamic Text Dynamisk tekst @@ -901,6 +1522,7 @@ Free Transform Fri transformering Perspective Distort Perspektivforvrængning Radial Blur… Radial sløring… + Blur Center Sløringens midtpunkt Smart Blur… Smart sløring… Sharpen Skarphed Unsharp Mask… Uskarp maskering… @@ -1636,6 +2258,9 @@ digits Malayalam Malayalam The selected character's font is not available. Skrifttypen for det markerede tegn er ikke tilgængelig. No alternates for the selected character. Ingen alternativer til det markerede tegn. Double-click to replace Dobbeltklik for at erstatte + Click to replace Klik for at erstatte + Show all alternates in the Glyphs panel Vis alle alternativer i Glyffer-panelet + Show Character Alternates Vis tegnalternativer Select one character with the Type tool first. Markér først ét tegn med tekstværktøjet. {glyph} is a glyph of {font}, not of the font the selected text is set in ({text_font}). {glyph} er et glyf i {font}, ikke i den skrifttype, den markerede tekst er sat i ({text_font}). {glyph} belongs to {base} (U+{base_code}) {place}; your selection is {sel} (U+{code}). {glyph} hører til {base} (U+{base_code}) {place}; din markering er {sel} (U+{code}). @@ -2077,6 +2702,7 @@ digits Malayalam Malayalam @msg paths entry {i} needs path and ids (object ids no other entry has) post {i} i paths skal have path og ids (objekt-id'er, som ingen anden post har) @msg scope missingInFolder takes path: the folder of that file is searched for the other missing links scope missingInFolder tager path: der søges efter de andre manglende links i den fils mappe Show Missing Vis manglende + Sort by Size Sortér efter størrelse Sort by Status Sortér efter status Clear Overrides Ryd tilsidesættelser Create New {kind} Style Opret ny {kind}-typografi @@ -2326,6 +2952,7 @@ digits Malayalam Malayalam Export Asset Eksportér aktiv Export to: Eksportér til: Format Settings Formatindstillinger + Format Settings… Formatindstillinger… Formats: Formater: Full Document Hele dokumentet Include Bleed Medtag beskæring @@ -2415,6 +3042,7 @@ digits Malayalam Malayalam e.g. 1-3, 5 f.eks. 1-3, 5 First Page Første side Import PDF Importér PDF + Import PDF pages as links Importér PDF-sider som links Last Page Sidste side Next Page Næste side of {count} af {count} @@ -2498,6 +3126,7 @@ digits Malayalam Malayalam Transparent Background Gennemsigtig baggrund Choose… Vælg… Copy Fonts Used in the Document Kopiér skrifttyper, der bruges i dokumentet + Copy Info Kopiér info Copy Links Kopiér links Create Report Opret rapport Fonts whose licence doesn't allow embedding are not copied. Skrifttyper, hvis licens ikke tillader indlejring, kopieres ikke. @@ -4280,6 +4909,7 @@ imageTrace Outline Kontur Stop the script and undo what it did? Then quit again. Stop scriptet og fortryd det, det har gjort? Afslut derefter igen. This script has added a great many objects. Continue, or stop it and undo what it did? Dette script har tilføjet rigtig mange objekter. Fortsæt, eller stop det og fortryd det, det har gjort? @msg Copied the script report Kopierede scriptrapporten +@msg Copied the link info Kopierede linkinfo @msg Corners edits the corners of a path Hjørner redigerer hjørnerne på en kurve @msg Couldn't copy to the system clipboard: {e} Kunne ikke kopiere til systemets udklipsholder: {e} @msg Couldn't open {name}: {e} Kunne ikke åbne {name}: {e} @@ -4595,6 +5225,7 @@ imageTrace Outline Kontur @msg no action set to save intet handlingssæt at gemme @msg the action set file can't be read in full handlingssætfilen kan ikke læses helt @msgplural Loaded “{name}”: {n} step was left out|Loaded “{name}”: {n} steps were left out Indlæste »{name}«: {n} trin blev udeladt|Indlæste »{name}«: {n} trin blev udeladt +@msgplural Loaded “{name}”: {n} step has an unknown command and was kept: “{action}”, step {step}, `{command}`|Loaded “{name}”: {n} steps have unknown commands and were kept; the first: “{action}”, step {step}, `{command}` Indlæste »{name}«: {n} trin har en ukendt kommando og blev beholdt: »{action}«, trin {step}, `{command}`|Indlæste »{name}«: {n} trin har ukendte kommandoer og blev beholdt; det første: »{action}«, trin {step}, `{command}` @msg not an action set file ikke en handlingssætfil @msg the action set file is larger than 8 MiB handlingssætfilen er større end 8 MiB @msg the action set file holds more than 1,000 actions handlingssætfilen indeholder mere end 1.000 handlinger @@ -6875,11 +7506,20 @@ breakText Glyphs Glyffer Open Tutorial Sample Åbn eksempel til vejledning Finish Tutorial Afslut vejledning Next Tutorial Næste vejledning + Show Learn Tab Vis fane i Lær + Show Skill Vis færdighed + Back One Level Ét niveau tilbage Back to Skills Tilbage til færdigheder @msg tutorial `{id}` has no practice sample vejledningen `{id}` har intet øvelseseksempel @msg open the practice sample of `{id}` first (see learn.openSample) åbn først øvelseseksemplet til `{id}` (se learn.openSample) @msg finish `{id}` first (see learn.finish) afslut først `{id}` (se learn.finish) @msg `{id}` is the last tutorial in its skill `{id}` er den sidste vejledning i sin færdighed + Reset progress Nulstil fremskridt + Mark Tutorial Step Markér trin i vejledning + Reset Learn Progress Nulstil læringsfremskridt +@msg missing `step` (see learn.show) `step` mangler (se learn.show) +@msg `step` must be a step number from 0 to {last} `step` skal være et trinnummer fra 0 til {last} +@msg `{id}` is finished (see learn.resetProgress) `{id}` er afsluttet (se learn.resetProgress) # Deferred plug-in effects Refresh Deferred Effects Opdatér udskudte effekter @@ -6902,3 +7542,6 @@ breakText Glyphs Glyffer Grommets Maljer Grommet Inset Maljernes afstand fra kanten Diameter Diameter + Nest Shapes… Pak figurer tæt… + Nest Shapes Pak figurer tæt + Roll Rulle diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index d98afe5b03..f5d6467815 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -25,6 +25,7 @@ Edge Brightness Kantenhelligkeit Smoothness Glättung Radial Blur… Radialer Weichzeichner… + Blur Center Mittelpunkt der Weichzeichnung Smart Blur… Selektiver Weichzeichner… Sharpen Scharfzeichnen Unsharp Mask… Unscharf maskieren… @@ -623,6 +624,7 @@ font-technology Variable Variabel Copy All Styles Alle Stile kopieren Copy Color Value (Hex) Farbwert kopieren (Hex) Copy Fonts Used in the Document Im Dokument verwendete Schriften kopieren + Copy Info Informationen kopieren Copy Links Verknüpfungen kopieren Copy Selected Style Ausgewählten Stil kopieren Copy to User Defined In „Benutzerdefiniert“ kopieren @@ -891,6 +893,9 @@ font-technology Variable Variabel The selected character's font is not available. Die Schrift des ausgewählten Zeichens ist nicht verfügbar. No alternates for the selected character. Keine Alternativen für das ausgewählte Zeichen. Double-click to replace Doppelklicken zum Ersetzen + Click to replace Klicken zum Ersetzen + Show all alternates in the Glyphs panel Alle Alternativen im Bedienfeld „Glyphen“ anzeigen + Show Character Alternates Zeichenalternativen anzeigen Select one character with the Type tool first. Wählen Sie zuerst mit dem Text-Werkzeug ein Zeichen aus. {glyph} is a glyph of {font}, not of the font the selected text is set in ({text_font}). {glyph} ist eine Glyphe von {font}, nicht der Schrift, in der der ausgewählte Text gesetzt ist ({text_font}). {glyph} belongs to {base} (U+{base_code}) {place}; your selection is {sel} (U+{code}). {glyph} gehört zu {base} (U+{base_code}) {place}; Ihre Auswahl ist {sel} (U+{code}). @@ -1329,6 +1334,7 @@ file-filter Templates Vorlagen Format Format Format Options Formatoptionen Format Settings Formateinstellungen + Format Settings… Formateinstellungen… Format: Format: Formats: Formate: Fractional Widths Gebrochene Breiten @@ -1689,6 +1695,7 @@ file-filter Templates Vorlagen Images: Bilder: Import Keyboard Shortcuts… Tastaturbefehle importieren… Import PDF PDF importieren + Import PDF pages as links PDF-Seiten als Verknüpfungen importieren Import PDF Presets PDF-Vorgaben importieren Import Perspective Grid Presets Vorgaben für Perspektivenraster importieren Import Print Presets Druckvorgaben importieren @@ -3411,6 +3418,18 @@ effect Points Punkte Smart Guides (View → Smart Guides) Intelligente Hilfslinien (Ansicht → Intelligente Hilfslinien) Smart Guides (⌘U) Intelligente Hilfslinien (⌘U) Smart Punctuation… Typografische Satzzeichen… + Smart Punctuation Typografische Satzzeichen + ff, fi, ffi Ligatures Ligaturen ff, fi, ffi + ff, fl, ffl Ligatures Ligaturen ff, fl, ffl + Smart Quotes Typografische Anführungszeichen + Smart Spaces Intelligente Leerzeichen + En, Em Dashes Halbgeviert- und Geviertstriche + Ellipses Auslassungspunkte + Expert Fractions Expertenbrüche + Replace In Ersetzen in + Selected Text Only Nur ausgewählter Text + Entire Document Gesamtes Dokument + Report Results Ergebnisse anzeigen Smooth Glatt Corner Ecke Relative Relativ @@ -3441,6 +3460,7 @@ effect Points Punkte Solid Gefüllt Sort by Kind Nach Art sortieren Sort by Name Nach Name sortieren + Sort by Size Nach Größe sortieren Sort by Status Nach Status sortieren Source code on GitHub Quellcode auf GitHub Source Sans 3 Source Sans 3 @@ -4297,6 +4317,7 @@ theme Appearance Erscheinungsbild @msg there is no script engine named {name} es gibt keine Skript-Engine namens {name} @msg Running a script Skript wird ausgeführt @msg Copied the script report Skriptbericht kopiert +@msg Copied the link info Verknüpfungsinformationen kopiert @msg Corners edits the corners of a path „Ecken“ bearbeitet die Ecken eines Pfads @msg Couldn't copy to the system clipboard: {e} In die Systemzwischenablage konnte nicht kopiert werden: {e} @msg Couldn't open {name}: {e} {name} konnte nicht geöffnet werden: {e} @@ -6266,7 +6287,7 @@ axis Y Axis Y-Achse @plural Result: {n}|Results: {n} Ergebnis: {n}|Ergebnisse: {n} @msg select one object wählen Sie ein Objekt aus @msg Global Edit works on paths, compound paths, symbol instances and groups of them Globale Bearbeitung funktioniert mit Pfaden, zusammengesetzten Pfaden, Symbolinstanzen und Gruppen daraus -@msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again keine ähnlichen Objekte gefunden (gedrehte oder gespiegelte Kopien werden nicht erkannt); ändern Sie die Optionen für globale Bearbeitung und versuchen Sie es erneut +@msg no similar objects found (reflected copies are not matched); change the Global Edit Options and try again keine ähnlichen Objekte gefunden (gespiegelte Kopien werden nicht erkannt); ändern Sie die Optionen für globale Bearbeitung und versuchen Sie es erneut @msg Global Edit is off Globale Bearbeitung ist nicht aktiv @msg only an object of the Global Edit other than the one it started from can be left out nur ein Objekt der globalen Bearbeitung außer dem, mit dem sie begonnen hat, kann ausgeschlossen werden @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all oder ein Bereich wie 1, 3-5, nicht {v} @@ -7063,11 +7084,20 @@ breakText Glyphs Glyphen Open Tutorial Sample Übungsdatei des Lernprogramms öffnen Finish Tutorial Lernprogramm abschließen Next Tutorial Nächstes Lernprogramm + Show Learn Tab Registerkarte in Lernen anzeigen + Show Skill Fertigkeit anzeigen + Back One Level Eine Ebene zurück Back to Skills Zurück zu den Fertigkeiten @msg tutorial `{id}` has no practice sample das Lernprogramm `{id}` hat keine Übungsdatei @msg open the practice sample of `{id}` first (see learn.openSample) öffnen Sie zuerst die Übungsdatei von `{id}` (siehe learn.openSample) @msg finish `{id}` first (see learn.finish) schließen Sie zuerst `{id}` ab (siehe learn.finish) @msg `{id}` is the last tutorial in its skill `{id}` ist das letzte Lernprogramm seiner Fertigkeit + Reset progress Fortschritt zurücksetzen + Mark Tutorial Step Schritt des Lernprogramms markieren + Reset Learn Progress Lernfortschritt zurücksetzen +@msg missing `step` (see learn.show) `step` fehlt (siehe learn.show) +@msg `step` must be a step number from 0 to {last} `step` muss eine Schrittnummer von 0 bis {last} sein +@msg `{id}` is finished (see learn.resetProgress) `{id}` ist abgeschlossen (siehe learn.resetProgress) # Deferred plug-in effects Refresh Deferred Effects Zurückgestellte Effekte aktualisieren @@ -8570,6 +8600,8 @@ breakText Glyphs Glyphen @msg the RTF file is too large to place as type (at most {_1} MB) die RTF-Datei ist zu groß, um als Text platziert zu werden (höchstens {_1} MB) @msg the SVG expands to more than {0} nested SVG images das SVG wird zu mehr als {0} verschachtelten SVG-Bildern erweitert @msg the SVG expands to more than {0} objects das SVG wird zu mehr als {0} Objekten erweitert +@msg the SVG's style sheets take too long to match das Abgleichen der Stylesheets des SVG dauert zu lange +@msg the SVG's styles expand to more than {0} MB die Stile des SVG werden auf mehr als {0} MB erweitert @msg the SVG has no drawable objects das SVG hat keine zeichenbaren Objekte @msg the SVGZ file unpacks to more than {_1} MB die SVGZ-Datei wird auf mehr als {_1} MB entpackt @msg the Word document has more than {MAX_PAGES} pages of properties, too many to place das Word-Dokument hat mehr als {MAX_PAGES} Seiten an Eigenschaften, zu viele zum Platzieren @@ -9030,3 +9062,6 @@ breakText Glyphs Glyphen Grommets Ösen Grommet Inset Randabstand der Ösen Diameter Durchmesser + Nest Shapes… Formen verschachteln… + Nest Shapes Formen verschachteln + Roll Rolle diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 8facc3b3dd..95fa3504b2 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -10,6 +10,7 @@ Edge Brightness Φωτεινότητα ακμών Smoothness Ομαλότητα Radial Blur… Ακτινική θόλωση… + Blur Center Κέντρο θόλωσης Smart Blur… Έξυπνη θόλωση… Sharpen Όξυνση Unsharp Mask… Μάσκα όξυνσης… @@ -604,6 +605,7 @@ font-technology Variable Μεταβλητές Copy All Styles Αντιγραφή όλων των στυλ Copy Color Value (Hex) Αντιγραφή τιμής χρώματος (Hex) Copy Fonts Used in the Document Αντιγραφή γραμματοσειρών που χρησιμοποιούνται στο έγγραφο + Copy Info Αντιγραφή πληροφοριών Copy Links Αντιγραφή συνδέσεων Copy Selected Style Αντιγραφή επιλεγμένου στυλ Copy to User Defined Αντιγραφή σε ορισμένα από τον χρήστη @@ -862,6 +864,9 @@ font-technology Variable Μεταβλητές The selected character's font is not available. Η γραμματοσειρά του επιλεγμένου χαρακτήρα δεν είναι διαθέσιμη. No alternates for the selected character. Δεν υπάρχουν εναλλακτικοί για τον επιλεγμένο χαρακτήρα. Double-click to replace Διπλό κλικ για αντικατάσταση + Click to replace Κλικ για αντικατάσταση + Show all alternates in the Glyphs panel Εμφάνιση όλων των εναλλακτικών στον πίνακα Γλύφοι + Show Character Alternates Εμφάνιση εναλλακτικών χαρακτήρα Select one character with the Type tool first. Επιλέξτε πρώτα έναν χαρακτήρα με το εργαλείο κειμένου. {glyph} is a glyph of {font}, not of the font the selected text is set in ({text_font}). Ο γλύφος {glyph} ανήκει στη γραμματοσειρά {font}, όχι σε αυτήν του επιλεγμένου κειμένου ({text_font}). {glyph} belongs to {base} (U+{base_code}) {place}; your selection is {sel} (U+{code}). Ο γλύφος {glyph} ανήκει στο {base} (U+{base_code}) {place}· η επιλογή σας είναι {sel} (U+{code}). @@ -1262,6 +1267,7 @@ font-technology Variable Μεταβλητές Format Μορφή Format Options Επιλογές μορφής Format Settings Ρυθμίσεις μορφής + Format Settings… Ρυθμίσεις μορφής… Format: Μορφή: Formats: Μορφές: Fractional Widths Κλασματικά πλάτη @@ -1604,6 +1610,7 @@ font-technology Variable Μεταβλητές Images: Εικόνες: Import Keyboard Shortcuts… Εισαγωγή συντομεύσεων πληκτρολογίου… Import PDF Εισαγωγή PDF + Import PDF pages as links Εισαγωγή σελίδων PDF ως συνδέσμων Import PDF Presets Εισαγωγή προεπιλογών PDF Import Perspective Grid Presets Εισαγωγή προεπιλογών πλέγματος προοπτικής Import Print Presets Εισαγωγή προεπιλογών εκτύπωσης @@ -2443,6 +2450,7 @@ axis Both Και τα δύο @msg there is no script engine named {name} δεν υπάρχει μηχανή σεναρίων με όνομα {name} @msg Running a script Εκτελείται σενάριο @msg Copied the script report Η αναφορά του σεναρίου αντιγράφηκε +@msg Copied the link info Οι πληροφορίες συνδέσμου αντιγράφηκαν @msg Corners edits the corners of a path Η εντολή Γωνίες επεξεργάζεται τις γωνίες μιας διαδρομής @msg Couldn't copy to the system clipboard: {e} Δεν ήταν δυνατή η αντιγραφή στο πρόχειρο συστήματος: {e} @msg Couldn't open {name}: {e} Δεν ήταν δυνατό το άνοιγμα του {name}: {e} @@ -3981,6 +3989,18 @@ digits Malayalam Μαλαγιάλαμ Smart Guides (View → Smart Guides) Έξυπνοι οδηγοί (Προβολή → Έξυπνοι οδηγοί) Smart Guides (⌘U) Έξυπνοι οδηγοί (⌘U) Smart Punctuation… Έξυπνη στίξη… + Smart Punctuation Έξυπνη στίξη + ff, fi, ffi Ligatures Συμπλέγματα ff, fi, ffi + ff, fl, ffl Ligatures Συμπλέγματα ff, fl, ffl + Smart Quotes Έξυπνα εισαγωγικά + Smart Spaces Έξυπνα διαστήματα + En, Em Dashes Παύλες en και em + Ellipses Αποσιωπητικά + Expert Fractions Κλάσματα ειδικών + Replace In Αντικατάσταση σε + Selected Text Only Μόνο επιλεγμένο κείμενο + Entire Document Ολόκληρο το έγγραφο + Report Results Αναφορά αποτελεσμάτων Smooth Color Ομαλό χρώμα Smooth Tool Εξομάλυνση (Smooth Tool) Snap Curves To Lines Προσκόλληση καμπυλών σε γραμμές @@ -3997,6 +4017,7 @@ digits Malayalam Μαλαγιάλαμ Social Square Post 1080×1080 Τετράγωνη δημοσίευση κοινωνικών δικτύων 1080×1080 Sort by Kind Ταξινόμηση κατά είδος Sort by Name Ταξινόμηση κατά όνομα + Sort by Size Ταξινόμηση κατά μέγεθος Sort by Status Ταξινόμηση κατά κατάσταση Source code on GitHub Πηγαίος κώδικας στο GitHub Space After Paragraph Διάστημα μετά την παράγραφο @@ -4802,6 +4823,8 @@ digits Malayalam Μαλαγιάλαμ @msg result would exceed the canvas (coordinates out of range) το αποτέλεσμα θα υπερέβαινε τον καμβά (συντεταγμένες εκτός εύρους) @msg objects can't be nested more than 32 deep τα αντικείμενα δεν μπορούν να έχουν ένθεση μεγαλύτερη των 32 επιπέδων @msg the SVG's elements are nested more than {0} deep τα στοιχεία SVG έχουν ένθεση μεγαλύτερη των {0} επιπέδων +@msg the SVG's style sheets take too long to match η αντιστοίχιση των φύλλων στυλ του SVG διαρκεί πολύ +@msg the SVG's styles expand to more than {0} MB τα στυλ του SVG επεκτείνονται σε περισσότερα από {0} MB @msg scale must be a number from {_1} to {_2}, not {_3} το scale πρέπει να είναι αριθμός από {_1} έως {_2}, όχι {_3} @msg scale must be a number from {_1} to {_2}, not {s} το scale πρέπει να είναι αριθμός από {_1} έως {_2}, όχι {s} @msg select (or target) objects whose appearance isn't basic επιλέξτε (ή στοχεύστε) αντικείμενα των οποίων η εμφάνιση δεν είναι βασική @@ -6626,7 +6649,7 @@ axis Y Axis Άξονας Y @plural Result: {n}|Results: {n} Αποτέλεσμα: {n}|Αποτελέσματα: {n} @msg select one object επιλέξτε ένα αντικείμενο @msg Global Edit works on paths, compound paths, symbol instances and groups of them Η καθολική επεξεργασία λειτουργεί σε διαδρομές, σύνθετες διαδρομές, παρουσίες συμβόλων και ομάδες τους -@msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again δεν βρέθηκαν παρόμοια αντικείμενα (τα περιστραμμένα ή κατοπτρισμένα αντίγραφα δεν εντοπίζονται)· αλλάξτε τις επιλογές καθολικής επεξεργασίας και δοκιμάστε ξανά +@msg no similar objects found (reflected copies are not matched); change the Global Edit Options and try again δεν βρέθηκαν παρόμοια αντικείμενα (τα κατοπτρισμένα αντίγραφα δεν εντοπίζονται)· αλλάξτε τις επιλογές καθολικής επεξεργασίας και δοκιμάστε ξανά @msg Global Edit is off Η καθολική επεξεργασία δεν είναι ενεργή @msg only an object of the Global Edit other than the one it started from can be left out μπορεί να εξαιρεθεί μόνο ένα αντικείμενο της καθολικής επεξεργασίας εκτός από εκείνο με το οποίο ξεκίνησε @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all ή ένα εύρος όπως 1, 3-5, όχι {v} @@ -7420,11 +7443,20 @@ breakText Glyphs Γλύφοι Open Tutorial Sample Άνοιγμα δείγματος οδηγού εκμάθησης Finish Tutorial Ολοκλήρωση οδηγού εκμάθησης Next Tutorial Επόμενος οδηγός εκμάθησης + Show Learn Tab Εμφάνιση καρτέλας της Εκμάθησης + Show Skill Εμφάνιση δεξιότητας + Back One Level Ένα επίπεδο πίσω Back to Skills Πίσω στις δεξιότητες @msg tutorial `{id}` has no practice sample ο οδηγός εκμάθησης `{id}` δεν έχει δείγμα εξάσκησης @msg open the practice sample of `{id}` first (see learn.openSample) ανοίξτε πρώτα το δείγμα εξάσκησης του `{id}` (δείτε learn.openSample) @msg finish `{id}` first (see learn.finish) ολοκληρώστε πρώτα το `{id}` (δείτε learn.finish) @msg `{id}` is the last tutorial in its skill το `{id}` είναι ο τελευταίος οδηγός εκμάθησης της δεξιότητάς του + Reset progress Επαναφορά προόδου + Mark Tutorial Step Σήμανση βήματος οδηγού εκμάθησης + Reset Learn Progress Επαναφορά προόδου εκμάθησης +@msg missing `step` (see learn.show) λείπει το `step` (δείτε learn.show) +@msg `step` must be a step number from 0 to {last} το `step` πρέπει να είναι αριθμός βήματος από 0 έως {last} +@msg `{id}` is finished (see learn.resetProgress) το `{id}` έχει ολοκληρωθεί (δείτε learn.resetProgress) # Deferred plug-in effects Refresh Deferred Effects Ανανέωση εφέ σε αναμονή @@ -7454,3 +7486,123 @@ breakText Glyphs Γλύφοι Grommets Τρουκς Grommet Inset Απόσταση τρουκς από την άκρη Diameter Διάμετρος + Nest Shapes… Ένθεση σχημάτων… + Nest Shapes Ένθεση σχημάτων + Roll Ρολό + +# Messages of the effects, 3D, image export, color profiles, swatch exchange files, color books, DXF import and PDF export. +@msg 3D effects require finite coordinates within 100 million points Τα εφέ 3D απαιτούν πεπερασμένες συντεταγμένες εντός 100 εκατομμυρίων τυπογραφικών στιγμών +@msg 3D effects require one to ten lights Τα εφέ 3D απαιτούν από ένα έως δέκα φώτα +@msg BMP depth {_1}: 1, 4, 8, 16, 24 or 32 bits per pixel Βάθος BMP {_1}: 1, 4, 8, 16, 24 ή 32 bit ανά εικονοστοιχείο +@msg BMP encoding failed: {width} × {height} pixels doesn't fit the format or the pixel buffer Η κωδικοποίηση BMP απέτυχε: τα {width} × {height} εικονοστοιχεία δεν ταιριάζουν στη μορφή ή στην προσωρινή μνήμη εικονοστοιχείων +@msg GIF encoding failed: the palette image is malformed Η κωδικοποίηση GIF απέτυχε: η εικόνα παλέτας είναι κακοσχηματισμένη +@msg GIF encoding failed: {e} Η κωδικοποίηση GIF απέτυχε: {e} +@msg JPEG colour profile: {e} Προφίλ χρώματος JPEG: {e} +@msg JPEG encoding failed: pixel buffer doesn't match the image size Η κωδικοποίηση JPEG απέτυχε: η προσωρινή μνήμη εικονοστοιχείων δεν αντιστοιχεί στο μέγεθος της εικόνας +@msg JPEG encoding failed: {e} Η κωδικοποίηση JPEG απέτυχε: {e} +@msg PNG encoding failed: pixel buffer doesn't match the image size Η κωδικοποίηση PNG απέτυχε: η προσωρινή μνήμη εικονοστοιχείων δεν αντιστοιχεί στο μέγεθος της εικόνας +@msg PNG encoding failed: the palette image is malformed Η κωδικοποίηση PNG απέτυχε: η εικόνα παλέτας είναι κακοσχηματισμένη +@msg PNG encoding failed: {e} Η κωδικοποίηση PNG απέτυχε: {e} +@msg PNG encoding failed: {width} × {height} pixels is not a valid image size Η κωδικοποίηση PNG απέτυχε: τα {width} × {height} εικονοστοιχεία δεν είναι έγκυρο μέγεθος εικόνας +@msg PSD colour profile: {e} Προφίλ χρώματος PSD: {e} +@msg PSD encoding failed: the pixel buffer doesn't match the image size Η κωδικοποίηση PSD απέτυχε: η προσωρινή μνήμη εικονοστοιχείων δεν αντιστοιχεί στο μέγεθος της εικόνας +@msg Revolve profile contains invalid coordinates Το προφίλ της περιστροφής γύρω από άξονα περιέχει μη έγκυρες συντεταγμένες +@msg Revolve profile is too complex Το προφίλ της περιστροφής γύρω από άξονα είναι πολύ σύνθετο +@msg Revolve projection is not finite Η προβολή της περιστροφής γύρω από άξονα δεν είναι πεπερασμένη +@msg Revolve requires finite profile coordinates within 100 million points Η περιστροφή γύρω από άξονα απαιτεί πεπερασμένες συντεταγμένες προφίλ εντός 100 εκατομμυρίων τυπογραφικών στιγμών +@msg Revolve surface is too complex; reduce Segments or simplify the profile Η επιφάνεια περιστροφής είναι πολύ σύνθετη· μειώστε τα «Τμήματα» ή απλοποιήστε το προφίλ +@msg Revolve surface is too complex; simplify the profile Η επιφάνεια περιστροφής είναι πολύ σύνθετη· απλοποιήστε το προφίλ +@msg Revolve visibility cannot split the projected boundary Ο έλεγχος ορατότητας της περιστροφής δεν μπορεί να διαιρέσει το προβαλλόμενο όριο +@msg Revolve visibility creates too many fragments Ο έλεγχος ορατότητας της περιστροφής δημιουργεί πάρα πολλά κομμάτια +@msg Revolve visibility creates too many vector anchors Ο έλεγχος ορατότητας της περιστροφής δημιουργεί πάρα πολλά διανυσματικά σημεία αγκύρωσης +@msg Revolve visibility exceeds its geometry work limit Ο έλεγχος ορατότητας της περιστροφής υπερβαίνει το όριο γεωμετρικών υπολογισμών του +@msg Revolve visibility exceeds its spatial index limit Ο έλεγχος ορατότητας της περιστροφής υπερβαίνει το όριο του χωρικού ευρετηρίου του +@msg Revolve visibility has too many boundary crossings Ο έλεγχος ορατότητας της περιστροφής έχει πάρα πολλές διασταυρώσεις ορίων +@msg Revolve visibility has too many input anchors Ο έλεγχος ορατότητας της περιστροφής έχει πάρα πολλά σημεία αγκύρωσης εισόδου +@msg Revolve visibility requires convex cap sectors Ο έλεγχος ορατότητας της περιστροφής απαιτεί κυρτούς τομείς καλυμμάτων +@msg Revolve visibility requires finite projected faces Ο έλεγχος ορατότητας της περιστροφής απαιτεί πεπερασμένες προβαλλόμενες έδρες +@msg SVG options: {e} Επιλογές SVG: {e} +@msg Save for Web settings: {e} Ρυθμίσεις αποθήκευσης για ιστό: {e} +@msg TIFF colour profile: {e} Προφίλ χρώματος TIFF: {e} +@msg TIFF encoding failed: the pixel buffer doesn't match the image size Η κωδικοποίηση TIFF απέτυχε: η προσωρινή μνήμη εικονοστοιχείων δεν αντιστοιχεί στο μέγεθος της εικόνας +@msg TIFF encoding failed: {e} Η κωδικοποίηση TIFF απέτυχε: {e} +@msg Targa depth {_1}: 16, 24 or 32 bits per pixel Βάθος Targa {_1}: 16, 24 ή 32 bit ανά εικονοστοιχείο +@msg Targa encoding failed: the pixel buffer doesn't match the image size Η κωδικοποίηση Targa απέτυχε: η προσωρινή μνήμη εικονοστοιχείων δεν αντιστοιχεί στο μέγεθος της εικόνας +@msg The 3D projection is not finite Η προβολή 3D δεν είναι πεπερασμένη +@msg The 3D shadow is too complex; turn Shadows off or simplify the art Η σκιά 3D είναι πολύ σύνθετη· απενεργοποιήστε τις «Σκιές» ή απλοποιήστε το σχέδιο +@msg The shape contains invalid coordinates Το σχήμα περιέχει μη έγκυρες συντεταγμένες +@msg Too many Revolve faces for visibility evaluation Πάρα πολλές έδρες περιστροφής για τον έλεγχο ορατότητας +@msg VectorCraft reads at most {ASE_MAX_ENTRIES} colors and groups from a swatch exchange file, and this library has {entries} Το VectorCraft διαβάζει το πολύ {ASE_MAX_ENTRIES} χρώματα και ομάδες από ένα αρχείο ανταλλαγής δειγμάτων, και αυτή η βιβλιοθήκη έχει {entries} +@msg WebP encoding failed: {e} Η κωδικοποίηση WebP απέτυχε: {e} +@msg [{j}] `{_1}`: {why} [{j}] `{_1}`: {why} +@msg `index` must be a whole number Το `index` πρέπει να είναι ακέραιος αριθμός +@msg `view` is smallThumb, mediumThumb, largeThumb, smallList or largeList Το `view` είναι smallThumb, mediumThumb, largeThumb, smallList ή largeList +@msg a line can't run from a point to itself μια γραμμή δεν μπορεί να ξεκινά και να καταλήγει στο ίδιο σημείο +@msg a line needs at least two points μια γραμμή χρειάζεται τουλάχιστον δύο σημεία +@msg a number cannot be read ένας αριθμός δεν μπορεί να διαβαστεί +@msg a swatch exchange block is too long ένα μπλοκ του αρχείου ανταλλαγής δειγμάτων είναι πολύ μεγάλο +@msg a swatch exchange name is too long ένα όνομα του αρχείου ανταλλαγής δειγμάτων είναι πολύ μεγάλο +@msg a {sw} × {sh} image can't be resized to {width} × {height} pixels μια εικόνα {sw} × {sh} δεν μπορεί να αλλάξει μέγεθος σε {width} × {height} εικονοστοιχεία +@msg a {width} × {height} image is too large μια εικόνα {width} × {height} είναι πολύ μεγάλη +@msg a {width} × {height} image: {e} μια εικόνα {width} × {height}: {e} +@msg an image could not be written: {e} μια εικόνα δεν μπόρεσε να γραφτεί: {e} +@msg an image that couldn't be read was left out παραλείφθηκε μια εικόνα που δεν μπόρεσε να διαβαστεί +@msg can't open “{name}”: {e} δεν είναι δυνατό το άνοιγμα του «{name}»: {e} +@msg cannot align zip entries to {align} bytes δεν είναι δυνατή η στοίχιση των καταχωρίσεων zip σε {align} byte +@msg cannot open the automation {kind} root `{_1}`: {e} δεν είναι δυνατό το άνοιγμα της ρίζας αυτοματισμού ({kind}) `{_1}`: {e} +@msg cannot read profile: {0} δεν είναι δυνατή η ανάγνωση του προφίλ: {0} +@msg color book version {version} isn't supported (only 1) η έκδοση {version} του βιβλίου χρωμάτων δεν υποστηρίζεται (μόνο 1) +@msg color books in color space {other} aren't supported (only RGB, CMYK and Lab) τα βιβλία χρωμάτων στον χρωματικό χώρο {other} δεν υποστηρίζονται (μόνο RGB, CMYK και Lab) +@msg file name too long to zip: {_1} το όνομα αρχείου είναι πολύ μεγάλο για συμπίεση zip: {_1} +@msg file name too long to zip: {name} το όνομα αρχείου είναι πολύ μεγάλο για συμπίεση zip: {name} +@msg freeform line {i}: {e} γραμμή ελεύθερης μορφής {i}: {e} +@msg freeform point {i}: {e} σημείο ελεύθερης μορφής {i}: {e} +@msg give `{key}` or `{other}`, not both δώστε `{key}` ή `{other}`, όχι και τα δύο +@msg grayscale profiles can't be working spaces yet τα προφίλ κλίμακας του γκρι δεν μπορούν ακόμη να είναι χρωματικοί χώροι εργασίας +@msg input contains NaN or infinite coordinates η είσοδος περιέχει συντεταγμένες NaN ή άπειρες συντεταγμένες +@msg input path could not be closed η διαδρομή εισόδου δεν μπόρεσε να κλείσει +@msg invalid ICC profile: {0} μη έγκυρο προφίλ ICC: {0} +@msg invalid scale {scale} μη έγκυρη κλίμακα {scale} +@msg its localized names take more than {_1} KB τα τοπικοποιημένα ονόματά του καταλαμβάνουν περισσότερα από {_1} KB +@msg its objects are nested too deep ({e}) τα αντικείμενά του είναι ένθετα σε πολύ μεγάλο βάθος ({e}) +@msg its tag table lists the `{_1}` tag more than once ο πίνακας ετικετών του περιέχει την ετικέτα `{_1}` περισσότερες από μία φορές +@msg knockout groups with too many overlapping translucent elements are written as PDF knockout groups: their translucent elements knock out what they cover fully οι ομάδες διάτρησης με πάρα πολλά επικαλυπτόμενα ημιδιαφανή στοιχεία γράφονται ως ομάδες διάτρησης PDF: τα ημιδιαφανή στοιχεία τους διατρυπούν πλήρως ό,τι καλύπτουν +@msg not a graphic style library: {e} δεν είναι βιβλιοθήκη στυλ γραφικών: {e} +@msg not a swatch library (.vcswatches or .gpl) δεν είναι βιβλιοθήκη δειγμάτων (.vcswatches ή .gpl) +@msg not a swatch library (format `{_1}`) δεν είναι βιβλιοθήκη δειγμάτων (μορφή `{_1}`) +@msg not a swatch library: {e} δεν είναι βιβλιοθήκη δειγμάτων: {e} +@msg not an action set file ({e}) δεν είναι αρχείο συνόλου ενεργειών ({e}) +@msg profile colour space {other} is not RGB, CMYK or Gray ο χρωματικός χώρος {other} του προφίλ δεν είναι RGB, CMYK ή Gray +@msg regular expression too large η κανονική έκφραση είναι πολύ μεγάλη +@msg script file is not UTF-8 text: {value} το αρχείο σεναρίου δεν είναι κείμενο UTF-8: {value} +@msg stop {i}: {e} σημείο χρώματος {i}: {e} +@msg swatch exchange version {major}.{minor} isn't supported (only 1.x) η έκδοση {major}.{minor} του αρχείου ανταλλαγής δειγμάτων δεν υποστηρίζεται (μόνο 1.x) +@msg the color book holds more than {ASE_MAX_ENTRIES} colors το βιβλίο χρωμάτων περιέχει περισσότερα από {ASE_MAX_ENTRIES} χρώματα +@msg the color book is cut short το βιβλίο χρωμάτων είναι περικομμένο +@msg the color book's names take more than {_1} MB τα ονόματα του βιβλίου χρωμάτων καταλαμβάνουν περισσότερα από {_1} MB +@msg the image would be {w} × {h} pixels; raster exports are limited to {MAX_RASTER_SIDE} pixels per side and {_1} megapixels: lower the scale or resolution η εικόνα θα ήταν {w} × {h} εικονοστοιχεία· οι εξαγωγές raster περιορίζονται σε {MAX_RASTER_SIDE} εικονοστοιχεία ανά πλευρά και {_1} μεγαεικονοστοιχεία: μειώστε την κλίμακα ή την ανάλυση +@msg the optimised image can't be read back: {e} η βελτιστοποιημένη εικόνα δεν μπορεί να διαβαστεί ξανά: {e} +@msg the pixel buffer doesn't match the image size η προσωρινή μνήμη εικονοστοιχείων δεν αντιστοιχεί στο μέγεθος της εικόνας +@msg the preview: {e} η προεπισκόπηση: {e} +@msg the request may not read the New Document profiles folder το αίτημα δεν επιτρέπεται να διαβάσει τον φάκελο προφίλ νέου εγγράφου +@msg the shapes are too degenerate to combine τα σχήματα είναι πολύ εκφυλισμένα για να συνδυαστούν +@msg the shapes cross themselves and each other too often to combine τα σχήματα τέμνουν τον εαυτό τους και το ένα το άλλο πάρα πολλές φορές για να συνδυαστούν +@msg the swatch exchange file holds more than {ASE_MAX_ENTRIES} colors and groups το αρχείο ανταλλαγής δειγμάτων περιέχει περισσότερα από {ASE_MAX_ENTRIES} χρώματα και ομάδες +@msg the swatch exchange file is cut short το αρχείο ανταλλαγής δειγμάτων είναι περικομμένο +@msg the {_1} plate can't be read: {e} η πλάκα {_1} δεν μπορεί να διαβαστεί: {e} +@msg this binary DXF file is damaged or cut short αυτό το δυαδικό αρχείο DXF είναι κατεστραμμένο ή περικομμένο +@msg this is a DWG drawing, which can't be read: save it from the CAD app as a DXF and open that αυτό είναι σχέδιο DWG και δεν μπορεί να διαβαστεί: αποθηκεύστε το ως DXF από την εφαρμογή CAD και ανοίξτε το +@msg too many classes υπερβολικά πολλές κλάσεις +@msg too many groups υπερβολικά πολλές ομάδες +@msg too many layers for PSD (at most 32767) πάρα πολλά επίπεδα για PSD (το πολύ 32767) +@msg too many swatch exchange blocks πάρα πολλά μπλοκ στο αρχείο ανταλλαγής δειγμάτων +@msg unknown colour profile: {0} άγνωστο προφίλ χρώματος: {0} +@msg {_1} clashes with a built-in profile name το {_1} συγκρούεται με το όνομα ενός ενσωματωμένου προφίλ +@msg {_1} × {_2} pixels is too large for GIF (at most 65535 pixels a side): lower the resolution τα {_1} × {_2} εικονοστοιχεία είναι υπερβολικό μέγεθος για GIF (το πολύ 65535 εικονοστοιχεία ανά πλευρά): μειώστε την ανάλυση +@msg {_1}: no usable transform to/from sRGB {_1}: δεν υπάρχει χρησιμοποιήσιμος μετασχηματισμός προς/από sRGB +@msg {name} is not a CMYK profile το {name} δεν είναι προφίλ CMYK +@msg {name} is not an RGB profile το {name} δεν είναι προφίλ RGB +@msg {path}: could not be read {path}: δεν ήταν δυνατή η ανάγνωση +@msg {width} × {height} pixels is too large for JPEG (at most 65535 pixels a side): lower the resolution τα {width} × {height} εικονοστοιχεία είναι υπερβολικό μέγεθος για JPEG (το πολύ 65535 εικονοστοιχεία ανά πλευρά): μειώστε την ανάλυση +@msg {width} × {height} pixels is too large for Targa (at most 65535 pixels a side): lower the resolution τα {width} × {height} εικονοστοιχεία είναι υπερβολικό μέγεθος για Targa (το πολύ 65535 εικονοστοιχεία ανά πλευρά): μειώστε την ανάλυση +@msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution τα {w} × {h} εικονοστοιχεία είναι υπερβολικό μέγεθος για PSD (το πολύ {MAX_SIDE} εικονοστοιχεία ανά πλευρά): μειώστε την ανάλυση diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3de5287c48..a3456fe48e 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -18,6 +18,7 @@ Edge Brightness Brillo del borde Smoothness Suavizado Radial Blur… Desenfoque radial… + Blur Center Centro del desenfoque Smart Blur… Desenfoque inteligente… Sharpen Enfocar Unsharp Mask… Máscara de enfoque… @@ -645,6 +646,7 @@ font-technology Variable Variables Copy All Styles Copiar todos los estilos Copy Color Value (Hex) Copiar valor de color (hex) Copy Fonts Used in the Document Copiar fuentes usadas en el documento + Copy Info Copiar información Copy Links Copiar vínculos Copy Selected Style Copiar estilo seleccionado Copy to User Defined Copiar en Definido por el usuario @@ -904,6 +906,9 @@ font-technology Variable Variables The selected character's font is not available. La fuente del carácter seleccionado no está disponible. No alternates for the selected character. No hay alternativas para el carácter seleccionado. Double-click to replace Doble clic para reemplazar + Click to replace Clic para reemplazar + Show all alternates in the Glyphs panel Mostrar todas las alternativas en el panel Glifos + Show Character Alternates Mostrar alternativas de carácter Select one character with the Type tool first. Primero selecciona un carácter con la herramienta Texto. {glyph} is a glyph of {font}, not of the font the selected text is set in ({text_font}). {glyph} es un glifo de {font}, no de la fuente del texto seleccionado ({text_font}). {glyph} belongs to {base} (U+{base_code}) {place}; your selection is {sel} (U+{code}). {glyph} pertenece a {base} (U+{base_code}) {place}; tu selección es {sel} (U+{code}). @@ -1338,6 +1343,7 @@ font-technology Variable Variables Format Formato Format Options Opciones de formato Format Settings Ajustes de formato + Format Settings… Ajustes de formato… Format: Formato: Formats: Formatos: Fractional Widths Anchuras fraccionarias @@ -1685,6 +1691,7 @@ font-technology Variable Variables Images: Imágenes: Import Keyboard Shortcuts… Importar métodos abreviados de teclado… Import PDF Importar PDF + Import PDF pages as links Importar páginas PDF como vínculos Import PDF Presets Importar preajustes de PDF Import Perspective Grid Presets Importar preajustes de cuadrícula de perspectiva Import Print Presets Importar preajustes de impresión @@ -3441,6 +3448,18 @@ digits Malayalam Malayálam Smart Guides (View → Smart Guides) Guías inteligentes (Ver → Guías inteligentes) Smart Guides (⌘U) Guías inteligentes (⌘U) Smart Punctuation… Puntuación inteligente… + Smart Punctuation Puntuación inteligente + ff, fi, ffi Ligatures Ligaduras ff, fi, ffi + ff, fl, ffl Ligatures Ligaduras ff, fl, ffl + Smart Quotes Comillas inteligentes + Smart Spaces Espacios inteligentes + En, Em Dashes Semirrayas y rayas + Ellipses Puntos suspensivos + Expert Fractions Fracciones expertas + Replace In Reemplazar en + Selected Text Only Solo el texto seleccionado + Entire Document Todo el documento + Report Results Informar de los resultados Smooth Suavizar Corner Vértice Relative Relativo @@ -3471,6 +3490,7 @@ digits Malayalam Malayálam Solid Sólido Sort by Kind Ordenar por tipo Sort by Name Ordenar por nombre + Sort by Size Ordenar por tamaño Sort by Status Ordenar por estado Source code on GitHub Código fuente en GitHub Source Sans 3 Source Sans 3 @@ -4374,6 +4394,7 @@ axis Both Ambos @msg there is no script engine named {name} no hay ningún motor de scripts llamado {name} @msg Running a script Ejecutando un script @msg Copied the script report Se copió el informe del script +@msg Copied the link info Se copió la información del vínculo @msg Corners edits the corners of a path Esquinas edita las esquinas de un trazado @msg Couldn't copy to the system clipboard: {e} No se pudo copiar al portapapeles del sistema: {e} @msg Couldn't open {name}: {e} No se pudo abrir {name}: {e} @@ -4846,6 +4867,8 @@ axis Both Ambos @msg result would exceed the canvas (coordinates out of range) el resultado excedería el lienzo (coordenadas fuera de rango) @msg objects can't be nested more than 32 deep los objetos no pueden anidarse a más de 32 niveles @msg the SVG's elements are nested more than {0} deep los elementos del SVG están anidados a más de {0} niveles +@msg the SVG's style sheets take too long to match la comparación de las hojas de estilo del SVG tarda demasiado +@msg the SVG's styles expand to more than {0} MB los estilos del SVG se expanden a más de {0} MB @msg scale must be a number from {_1} to {_2}, not {_3} scale debe ser un número de {_1} a {_2}, no {_3} @msg scale must be a number from {_1} to {_2}, not {s} scale debe ser un número de {_1} a {_2}, no {s} @msg select (or target) objects whose appearance isn't basic selecciona (o apunta a) objetos cuya apariencia no sea básica @@ -6617,7 +6640,7 @@ axis Y Axis Eje Y @plural Result: {n}|Results: {n} Resultado: {n}|Resultados: {n} @msg select one object seleccione un objeto @msg Global Edit works on paths, compound paths, symbol instances and groups of them La edición global funciona con trazados, trazados compuestos, instancias de símbolos y grupos de ellos -@msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again no se encontraron objetos similares (las copias giradas o reflejadas no coinciden); cambie las opciones de edición global e inténtelo de nuevo +@msg no similar objects found (reflected copies are not matched); change the Global Edit Options and try again no se encontraron objetos similares (las copias reflejadas no coinciden); cambie las opciones de edición global e inténtelo de nuevo @msg Global Edit is off La edición global no está activa @msg only an object of the Global Edit other than the one it started from can be left out solo se puede excluir un objeto de la edición global distinto de aquel con el que empezó @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all o un intervalo como 1, 3-5, no {v} @@ -7332,6 +7355,122 @@ breakText Glyphs Glifos @msg only an exporter or an importer declares `extensions` solo un plugin de exportación o de importación declara `extensions` @msg an importer always gets an import's budget: leave `budget` out un plugin de importación siempre recibe el presupuesto de una importación: omita `budget` +# Messages of the image encoders, color profiles, swatch exchange files and color books, 3D and Revolve, path operations, DXF import, the script engine and parameter checks. +@msg 3D effects require finite coordinates within 100 million points Los efectos 3D requieren coordenadas finitas dentro de 100 millones de puntos +@msg 3D effects require one to ten lights Los efectos 3D requieren de una a diez luces +@msg BMP depth {_1}: 1, 4, 8, 16, 24 or 32 bits per pixel Profundidad de BMP {_1}: 1, 4, 8, 16, 24 o 32 bits por píxel +@msg BMP encoding failed: {width} × {height} pixels doesn't fit the format or the pixel buffer Error al codificar BMP: {width} × {height} píxeles no caben en el formato o no coinciden con el búfer de píxeles +@msg GIF encoding failed: the palette image is malformed Error al codificar GIF: la imagen con paleta está mal formada +@msg GIF encoding failed: {e} Error al codificar GIF: {e} +@msg JPEG colour profile: {e} Perfil de color de JPEG: {e} +@msg JPEG encoding failed: pixel buffer doesn't match the image size Error al codificar JPEG: el búfer de píxeles no coincide con el tamaño de la imagen +@msg JPEG encoding failed: {e} Error al codificar JPEG: {e} +@msg PNG encoding failed: pixel buffer doesn't match the image size Error al codificar PNG: el búfer de píxeles no coincide con el tamaño de la imagen +@msg PNG encoding failed: the palette image is malformed Error al codificar PNG: la imagen con paleta está mal formada +@msg PNG encoding failed: {e} Error al codificar PNG: {e} +@msg PNG encoding failed: {width} × {height} pixels is not a valid image size Error al codificar PNG: {width} × {height} píxeles no es un tamaño de imagen válido +@msg PSD colour profile: {e} Perfil de color de PSD: {e} +@msg PSD encoding failed: the pixel buffer doesn't match the image size Error al codificar PSD: el búfer de píxeles no coincide con el tamaño de la imagen +@msg Revolve profile contains invalid coordinates El perfil de Revolución contiene coordenadas no válidas +@msg Revolve profile is too complex El perfil de Revolución es demasiado complejo +@msg Revolve projection is not finite La proyección de Revolución no es finita +@msg Revolve requires finite profile coordinates within 100 million points Revolución requiere coordenadas de perfil finitas dentro de 100 millones de puntos +@msg Revolve surface is too complex; reduce Segments or simplify the profile La superficie de Revolución es demasiado compleja; reduce Segmentos o simplifica el perfil +@msg Revolve surface is too complex; simplify the profile La superficie de Revolución es demasiado compleja; simplifica el perfil +@msg Revolve visibility cannot split the projected boundary La visibilidad de Revolución no puede dividir el contorno proyectado +@msg Revolve visibility creates too many fragments La visibilidad de Revolución crea demasiados fragmentos +@msg Revolve visibility creates too many vector anchors La visibilidad de Revolución crea demasiados puntos de ancla vectoriales +@msg Revolve visibility exceeds its geometry work limit La visibilidad de Revolución supera su límite de trabajo geométrico +@msg Revolve visibility exceeds its spatial index limit La visibilidad de Revolución supera su límite de índice espacial +@msg Revolve visibility has too many boundary crossings La visibilidad de Revolución tiene demasiados cruces de contorno +@msg Revolve visibility has too many input anchors La visibilidad de Revolución tiene demasiados puntos de ancla de entrada +@msg Revolve visibility requires convex cap sectors La visibilidad de Revolución requiere sectores de tapa convexos +@msg Revolve visibility requires finite projected faces La visibilidad de Revolución requiere caras proyectadas finitas +@msg SVG options: {e} Opciones de SVG: {e} +@msg Save for Web settings: {e} Ajustes de Guardar para web: {e} +@msg TIFF colour profile: {e} Perfil de color de TIFF: {e} +@msg TIFF encoding failed: the pixel buffer doesn't match the image size Error al codificar TIFF: el búfer de píxeles no coincide con el tamaño de la imagen +@msg TIFF encoding failed: {e} Error al codificar TIFF: {e} +@msg Targa depth {_1}: 16, 24 or 32 bits per pixel Profundidad de Targa {_1}: 16, 24 o 32 bits por píxel +@msg Targa encoding failed: the pixel buffer doesn't match the image size Error al codificar Targa: el búfer de píxeles no coincide con el tamaño de la imagen +@msg The 3D projection is not finite La proyección 3D no es finita +@msg The 3D shadow is too complex; turn Shadows off or simplify the art La sombra 3D es demasiado compleja; desactiva Sombras o simplifica la ilustración +@msg The shape contains invalid coordinates La forma contiene coordenadas no válidas +@msg Too many Revolve faces for visibility evaluation Demasiadas caras de Revolución para evaluar la visibilidad +@msg VectorCraft reads at most {ASE_MAX_ENTRIES} colors and groups from a swatch exchange file, and this library has {entries} VectorCraft lee como máximo {ASE_MAX_ENTRIES} colores y grupos de un archivo de intercambio de muestras, y esta biblioteca tiene {entries} +@msg WebP encoding failed: {e} Error al codificar WebP: {e} +@msg [{j}] `{_1}`: {why} [{j}] `{_1}`: {why} +@msg `answers[{i}]` {e} `answers[{i}]` {e} +@msg `view` is smallThumb, mediumThumb, largeThumb, smallList or largeList `view` es smallThumb, mediumThumb, largeThumb, smallList o largeList +@msg a line can't run from a point to itself una línea no puede ir de un punto a sí mismo +@msg a line needs at least two points una línea necesita al menos dos puntos +@msg a number cannot be read no se puede leer un número +@msg a swatch exchange block is too long un bloque de intercambio de muestras es demasiado largo +@msg a swatch exchange name is too long un nombre de intercambio de muestras es demasiado largo +@msg a {sw} × {sh} image can't be resized to {width} × {height} pixels una imagen de {sw} × {sh} no se puede cambiar de tamaño a {width} × {height} píxeles +@msg a {width} × {height} image is too large una imagen de {width} × {height} es demasiado grande +@msg a {width} × {height} image: {e} una imagen de {width} × {height}: {e} +@msg an image could not be written: {e} no se pudo escribir una imagen: {e} +@msg an image that couldn't be read was left out se omitió una imagen que no se pudo leer +@msg can't open “{name}”: {e} no se puede abrir «{name}»: {e} +@msg cannot align zip entries to {align} bytes no se pueden alinear las entradas zip a {align} bytes +@msg cannot open the automation {kind} root `{_1}`: {e} no se puede abrir la carpeta raíz de automatización ({kind}) `{_1}`: {e} +@msg cannot read profile: {0} no se puede leer el perfil: {0} +@msg color book version {version} isn't supported (only 1) no se admite la versión {version} del libro de colores (solo 1) +@msg color books in color space {other} aren't supported (only RGB, CMYK and Lab) no se admiten libros de colores en el espacio de color {other} (solo RGB, CMYK y Lab) +@msg file name too long to zip: {_1} nombre de archivo demasiado largo para comprimirlo en zip: {_1} +@msg file name too long to zip: {name} nombre de archivo demasiado largo para comprimirlo en zip: {name} +@msg freeform line {i}: {e} línea de forma libre {i}: {e} +@msg freeform point {i}: {e} punto de forma libre {i}: {e} +@msg give `{key}` or `{other}`, not both indica `{key}` o `{other}`, no ambos +@msg grayscale profiles can't be working spaces yet los perfiles de escala de grises todavía no pueden ser espacios de trabajo +@msg input contains NaN or infinite coordinates la entrada contiene coordenadas NaN o infinitas +@msg input path could not be closed no se pudo cerrar el trazado de entrada +@msg invalid ICC profile: {0} perfil ICC no válido: {0} +@msg invalid scale {scale} escala no válida {scale} +@msg its localized names take more than {_1} KB sus nombres localizados ocupan más de {_1} KB +@msg its objects are nested too deep ({e}) sus objetos están anidados a demasiada profundidad ({e}) +@msg its tag table lists the `{_1}` tag more than once su tabla de etiquetas incluye la etiqueta `{_1}` más de una vez +@msg not a graphic style library: {e} no es una biblioteca de estilos gráficos: {e} +@msg not a swatch library (.vcswatches or .gpl) no es una biblioteca de muestras (.vcswatches o .gpl) +@msg not a swatch library (format `{_1}`) no es una biblioteca de muestras (formato `{_1}`) +@msg not a swatch library: {e} no es una biblioteca de muestras: {e} +@msg not an action set file ({e}) no es un archivo de conjunto de acciones ({e}) +@msg profile colour space {other} is not RGB, CMYK or Gray el espacio de color {other} del perfil no es RGB, CMYK ni Gray +@msg regular expression too large expresión regular demasiado grande +@msg script file is not UTF-8 text: {value} el archivo de script no es texto UTF-8: {value} +@msg stop {i}: {e} parada {i}: {e} +@msg swatch exchange version {major}.{minor} isn't supported (only 1.x) no se admite la versión {major}.{minor} de intercambio de muestras (solo 1.x) +@msg the color book holds more than {ASE_MAX_ENTRIES} colors el libro de colores contiene más de {ASE_MAX_ENTRIES} colores +@msg the color book is cut short el libro de colores está truncado +@msg the color book's names take more than {_1} MB los nombres del libro de colores ocupan más de {_1} MB +@msg the image would be {w} × {h} pixels; raster exports are limited to {MAX_RASTER_SIDE} pixels per side and {_1} megapixels: lower the scale or resolution la imagen mediría {w} × {h} píxeles; las exportaciones de mapa de bits se limitan a {MAX_RASTER_SIDE} píxeles por lado y {_1} megapíxeles: baja la escala o la resolución +@msg the optimised image can't be read back: {e} la imagen optimizada no se puede volver a leer: {e} +@msg the pixel buffer doesn't match the image size el búfer de píxeles no coincide con el tamaño de la imagen +@msg the preview: {e} la previsualización: {e} +@msg the request may not read the New Document profiles folder la solicitud no puede leer la carpeta de perfiles de Nuevo documento +@msg the shapes are too degenerate to combine las formas están demasiado degeneradas para combinarlas +@msg the shapes cross themselves and each other too often to combine las formas se cruzan consigo mismas y entre sí demasiadas veces para combinarlas +@msg the swatch exchange file holds more than {ASE_MAX_ENTRIES} colors and groups el archivo de intercambio de muestras contiene más de {ASE_MAX_ENTRIES} colores y grupos +@msg the swatch exchange file is cut short el archivo de intercambio de muestras está truncado +@msg the {_1} plate can't be read: {e} no se puede leer la plancha {_1}: {e} +@msg this binary DXF file is damaged or cut short este archivo DXF binario está dañado o truncado +@msg this is a DWG drawing, which can't be read: save it from the CAD app as a DXF and open that este es un dibujo DWG, que no se puede leer: guárdalo desde la aplicación de CAD como DXF y abre ese archivo +@msg too many classes demasiadas clases +@msg too many groups demasiados grupos +@msg too many layers for PSD (at most 32767) demasiadas capas para PSD (como máximo 32767) +@msg too many swatch exchange blocks demasiados bloques de intercambio de muestras +@msg unknown colour profile: {0} perfil de color desconocido: {0} +@msg {_1} clashes with a built-in profile name {_1} coincide con el nombre de un perfil integrado +@msg {_1} × {_2} pixels is too large for GIF (at most 65535 pixels a side): lower the resolution {_1} × {_2} píxeles es demasiado grande para GIF (como máximo 65535 píxeles por lado): baja la resolución +@msg {_1}: no usable transform to/from sRGB {_1}: no hay ninguna transformación utilizable a sRGB ni desde sRGB +@msg {name} is not a CMYK profile {name} no es un perfil CMYK +@msg {name} is not an RGB profile {name} no es un perfil RGB +@msg {path}: could not be read {path}: no se pudo leer +@msg {width} × {height} pixels is too large for JPEG (at most 65535 pixels a side): lower the resolution {width} × {height} píxeles es demasiado grande para JPEG (como máximo 65535 píxeles por lado): baja la resolución +@msg {width} × {height} pixels is too large for Targa (at most 65535 pixels a side): lower the resolution {width} × {height} píxeles es demasiado grande para Targa (como máximo 65535 píxeles por lado): baja la resolución +@msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} píxeles es demasiado grande para PSD (como máximo {MAX_SIDE} píxeles por lado): baja la resolución + # Copy Troubleshooting Info Copy Troubleshooting Info Copiar información de solución de problemas @msg Copied the troubleshooting info Se copió la información de solución de problemas @@ -7411,11 +7550,20 @@ breakText Glyphs Glifos Open Tutorial Sample Abrir muestra del tutorial Finish Tutorial Terminar tutorial Next Tutorial Tutorial siguiente + Show Learn Tab Mostrar pestaña de Aprender + Show Skill Mostrar habilidad + Back One Level Volver un nivel Back to Skills Volver a las habilidades @msg tutorial `{id}` has no practice sample el tutorial `{id}` no tiene muestra de práctica @msg open the practice sample of `{id}` first (see learn.openSample) abre primero la muestra de práctica de `{id}` (consulta learn.openSample) @msg finish `{id}` first (see learn.finish) termina primero `{id}` (consulta learn.finish) @msg `{id}` is the last tutorial in its skill `{id}` es el último tutorial de su habilidad + Reset progress Restablecer progreso + Mark Tutorial Step Marcar paso del tutorial + Reset Learn Progress Restablecer progreso de aprendizaje +@msg missing `step` (see learn.show) falta `step` (consulta learn.show) +@msg `step` must be a step number from 0 to {last} `step` debe ser un número de paso de 0 a {last} +@msg `{id}` is finished (see learn.resetProgress) `{id}` está terminado (consulta learn.resetProgress) # Deferred plug-in effects Refresh Deferred Effects Actualizar efectos aplazados @@ -7445,3 +7593,6 @@ breakText Glyphs Glifos Grommets Ojales Grommet Inset Distancia de los ojales al borde Diameter Diámetro + Nest Shapes… Anidar formas… + Nest Shapes Anidar formas + Roll Rollo diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index d06a0bb02b..89934ae48e 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -425,6 +425,18 @@ Title Case Otsikon kirjainkoko Sentence case Virkkeen kirjainkoko Smart Punctuation… Älykäs välimerkitys… + Smart Punctuation Älykäs välimerkitys + ff, fi, ffi Ligatures Ligatuurit ff, fi, ffi + ff, fl, ffl Ligatures Ligatuurit ff, fl, ffl + Smart Quotes Älykkäät lainausmerkit + Smart Spaces Älykkäät välilyönnit + En, Em Dashes Lyhyet ja pitkät ajatusviivat + Ellipses Kolme pistettä + Expert Fractions Erikoismurtoluvut + Replace In Korvaa kohteessa + Selected Text Only Vain valittu teksti + Entire Document Koko asiakirja + Report Results Näytä tulokset Create Outlines Muunna ääriviivoiksi Optical Margin Alignment Optinen reunustasaus Dynamic Text Dynaaminen teksti @@ -962,6 +974,7 @@ Free Transform Vapaa muunnos Perspective Distort Perspektiivivääristys Radial Blur… Säteittäinen sumennus… + Blur Center Sumennuksen keskipiste Smart Blur… Älykäs sumennus… Sharpen Terävöitä Unsharp Mask… Epäterävä maski… @@ -1703,6 +1716,9 @@ digits Malayalam Malajalam The selected character's font is not available. Valitun merkin fontti ei ole saatavilla. No alternates for the selected character. Valitulla merkillä ei ole vaihtoehtoja. Double-click to replace Korvaa kaksoisnapsauttamalla + Click to replace Korvaa napsauttamalla + Show all alternates in the Glyphs panel Näytä kaikki vaihtoehdot Merkit-paneelissa + Show Character Alternates Näytä merkin vaihtoehdot Select one character with the Type tool first. Valitse ensin yksi merkki tekstityökalulla. {glyph} is a glyph of {font}, not of the font the selected text is set in ({text_font}). {glyph} on fontin {font} glyfi, ei valitun tekstin fontin ({text_font}). {glyph} belongs to {base} (U+{base_code}) {place}; your selection is {sel} (U+{code}). {glyph} kuuluu merkille {base} (U+{base_code}) {place}; valintasi on {sel} (U+{code}). @@ -2238,6 +2254,7 @@ digits Malayalam Malajalam @msg paths entry {i} needs path and ids (object ids no other entry has) paths-merkintä {i} tarvitsee path- ja ids-arvot (objektitunnukset, joita millään muulla merkinnällä ei ole) @msg scope missingInFolder takes path: the folder of that file is searched for the other missing links scope missingInFolder ottaa path-arvon: muita puuttuvia linkkejä haetaan tämän tiedoston kansiosta Show Missing Näytä puuttuvat + Sort by Size Lajittele koon mukaan Sort by Status Lajittele tilan mukaan Clear Overrides Tyhjennä ohitukset Create New {kind} Style Luo uusi tyyli: {kind} @@ -2488,6 +2505,7 @@ digits Malayalam Malajalam Export Asset Vie resurssi Export to: Vie kohteeseen: Format Settings Muotoasetukset + Format Settings… Muotoasetukset… Formats: Muodot: Full Document Koko asiakirja Include Bleed Sisällytä leikkuuvara @@ -2577,6 +2595,7 @@ digits Malayalam Malajalam e.g. 1-3, 5 esim. 1-3, 5 First Page Ensimmäinen sivu Import PDF Tuo PDF + Import PDF pages as links Tuo PDF-sivut linkkeinä Last Page Viimeinen sivu Next Page Seuraava sivu of {count} / {count} @@ -2660,6 +2679,7 @@ digits Malayalam Malajalam Transparent Background Läpinäkyvä tausta Choose… Valitse… Copy Fonts Used in the Document Kopioi asiakirjassa käytetyt fontit + Copy Info Kopioi tiedot Copy Links Kopioi linkit Create Report Luo raportti Fonts whose licence doesn't allow embedding are not copied. Fontteja, joiden lisenssi ei salli upottamista, ei kopioida. @@ -4599,6 +4619,7 @@ imageTrace Outline Ääriviiva @msg there is no script engine named {name} skriptimoottoria nimeltä {name} ei ole @msg Running a script Suoritetaan komentosarjaa @msg Copied the script report Komentosarjan raportti kopioitiin +@msg Copied the link info Linkin tiedot kopioitiin @msg Corners edits the corners of a path Kulmat-toiminto muokkaa polun kulmia @msg Couldn't copy to the system clipboard: {e} Järjestelmän leikepöydälle ei voitu kopioida: {e} @msg Couldn't open {name}: {e} Tiedostoa {name} ei voitu avata: {e} @@ -5061,6 +5082,8 @@ imageTrace Outline Ääriviiva @msg result would exceed the canvas (coordinates out of range) tulos ylittäisi kankaan (koordinaatit alueen ulkopuolella) @msg objects can't be nested more than 32 deep objekteja ei voi sisäkkäistää yli 32 tason syvyyteen @msg the SVG's elements are nested more than {0} deep elementit ovat SVG-tiedostossa sisäkkäin yli {0} tason syvyydessä +@msg the SVG's style sheets take too long to match SVG-tiedoston tyylisivujen täsmäytys kestää liian kauan +@msg the SVG's styles expand to more than {0} MB SVG-tiedoston tyylit laajenevat yli {0} megatavuksi @msg scale must be a number from {_1} to {_2}, not {_3} scale-arvon on oltava luku väliltä {_1}–{_2}, ei {_3} @msg scale must be a number from {_1} to {_2}, not {s} scale-arvon on oltava luku väliltä {_1}–{_2}, ei {s} @msg select (or target) objects whose appearance isn't basic valitse (tai kohdista) objektit, joiden ulkoasu ei ole perusulkoasu @@ -6704,7 +6727,7 @@ axis Y Axis Y-akseli @plural Result: {n}|Results: {n} Tulos: {n}|Tulokset: {n} @msg select one object valitse yksi objekti @msg Global Edit works on paths, compound paths, symbol instances and groups of them Yleismuokkaus toimii poluille, yhdistelmäpoluille, symbolien esiintymille ja niiden ryhmille -@msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again samankaltaisia objekteja ei löytynyt (kierrettyjä tai peilattuja kopioita ei tunnisteta); muuta yleismuokkauksen asetuksia ja yritä uudelleen +@msg no similar objects found (reflected copies are not matched); change the Global Edit Options and try again samankaltaisia objekteja ei löytynyt (peilattuja kopioita ei tunnisteta); muuta yleismuokkauksen asetuksia ja yritä uudelleen @msg Global Edit is off Yleismuokkaus ei ole käynnissä @msg only an object of the Global Edit other than the one it started from can be left out yleismuokkauksesta voi jättää pois vain muun objektin kuin sen, josta se alkoi @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all tai alue, kuten 1, 3-5, ei {v} @@ -7502,11 +7525,20 @@ breakText Glyphs Merkit Open Tutorial Sample Avaa opetusohjelman harjoitustiedosto Finish Tutorial Viimeistele opetusohjelma Next Tutorial Seuraava opetusohjelma + Show Learn Tab Näytä Opi-paneelin välilehti + Show Skill Näytä taito + Back One Level Taso takaisin Back to Skills Takaisin taitoihin @msg tutorial `{id}` has no practice sample opetusohjelmalla `{id}` ei ole harjoitustiedostoa @msg open the practice sample of `{id}` first (see learn.openSample) avaa ensin opetusohjelman `{id}` harjoitustiedosto (ks. learn.openSample) @msg finish `{id}` first (see learn.finish) viimeistele ensin `{id}` (ks. learn.finish) @msg `{id}` is the last tutorial in its skill `{id}` on taitonsa viimeinen opetusohjelma + Reset progress Palauta edistyminen + Mark Tutorial Step Merkitse opetusohjelman vaihe + Reset Learn Progress Palauta oppimisen edistyminen +@msg missing `step` (see learn.show) `step` puuttuu (ks. learn.show) +@msg `step` must be a step number from 0 to {last} `step` on oltava vaiheen numero, vähintään 0 ja enintään {last} +@msg `{id}` is finished (see learn.resetProgress) `{id}` on viimeistelty (ks. learn.resetProgress) # Deferred plug-in effects Refresh Deferred Effects Päivitä lykätyt tehosteet @@ -7536,3 +7568,125 @@ breakText Glyphs Merkit Grommets Purjerenkaat Grommet Inset Purjerenkaiden etäisyys reunasta Diameter Halkaisija + Nest Shapes… Sijoittele muodot… + Nest Shapes Sijoittele muodot + Roll Rulla + +# Messages of the effects, 3D, image and PDF export, color profiles, swatch exchange files, color books and DXF import. +@msg 3D effects require finite coordinates within 100 million points 3D-tehosteet vaativat äärelliset koordinaatit 100 miljoonan pisteen rajoissa +@msg 3D effects require one to ten lights 3D-tehosteet vaativat 1–10 valonlähdettä +@msg BMP depth {_1}: 1, 4, 8, 16, 24 or 32 bits per pixel BMP-värisyvyys {_1}: 1, 4, 8, 16, 24 tai 32 bittiä pikseliä kohti +@msg BMP encoding failed: {width} × {height} pixels doesn't fit the format or the pixel buffer BMP-koodaus epäonnistui: {width} × {height} pikseliä ei mahdu tiedostomuotoon tai pikselipuskuriin +@msg GIF encoding failed: the palette image is malformed GIF-koodaus epäonnistui: palettikuva on virheellinen +@msg GIF encoding failed: {e} GIF-koodaus epäonnistui: {e} +@msg JPEG colour profile: {e} JPEG-väriprofiili: {e} +@msg JPEG encoding failed: pixel buffer doesn't match the image size JPEG-koodaus epäonnistui: pikselipuskuri ei vastaa kuvan kokoa +@msg JPEG encoding failed: {e} JPEG-koodaus epäonnistui: {e} +@msg PNG encoding failed: pixel buffer doesn't match the image size PNG-koodaus epäonnistui: pikselipuskuri ei vastaa kuvan kokoa +@msg PNG encoding failed: the palette image is malformed PNG-koodaus epäonnistui: palettikuva on virheellinen +@msg PNG encoding failed: {e} PNG-koodaus epäonnistui: {e} +@msg PNG encoding failed: {width} × {height} pixels is not a valid image size PNG-koodaus epäonnistui: {width} × {height} pikseliä ei ole kelvollinen kuvakoko +@msg PSD colour profile: {e} PSD-väriprofiili: {e} +@msg PSD encoding failed: the pixel buffer doesn't match the image size PSD-koodaus epäonnistui: pikselipuskuri ei vastaa kuvan kokoa +@msg Revolve profile contains invalid coordinates Pyöräytä-tehosteen profiilissa on virheellisiä koordinaatteja +@msg Revolve profile is too complex Pyöräytä-tehosteen profiili on liian monimutkainen +@msg Revolve projection is not finite Pyöräytä-tehosteen projektio ei ole äärellinen +@msg Revolve requires finite profile coordinates within 100 million points Pyöräytä vaatii äärelliset profiilin koordinaatit 100 miljoonan pisteen rajoissa +@msg Revolve surface is too complex; reduce Segments or simplify the profile Pyöräytä-tehosteen pinta on liian monimutkainen; pienennä Segmentit-arvoa tai yksinkertaista profiilia +@msg Revolve surface is too complex; simplify the profile Pyöräytä-tehosteen pinta on liian monimutkainen; yksinkertaista profiilia +@msg Revolve visibility cannot split the projected boundary Pyöräytä-tehosteen näkyvyyslaskenta ei voi jakaa projisoitua reunaa +@msg Revolve visibility creates too many fragments Pyöräytä-tehosteen näkyvyyslaskenta tuottaa liikaa osia +@msg Revolve visibility creates too many vector anchors Pyöräytä-tehosteen näkyvyyslaskenta tuottaa liikaa vektorin ankkuripisteitä +@msg Revolve visibility exceeds its geometry work limit Pyöräytä-tehosteen näkyvyyslaskenta ylittää geometrialaskennan työmäärän rajan +@msg Revolve visibility exceeds its spatial index limit Pyöräytä-tehosteen näkyvyyslaskenta ylittää paikkaindeksin rajan +@msg Revolve visibility has too many boundary crossings Pyöräytä-tehosteen näkyvyyslaskennassa on liikaa reunan ylityksiä +@msg Revolve visibility has too many input anchors Pyöräytä-tehosteen näkyvyyslaskennassa on liikaa syötteen ankkuripisteitä +@msg Revolve visibility requires convex cap sectors Pyöräytä-tehosteen näkyvyyslaskenta vaatii kuperat päätysektorit +@msg Revolve visibility requires finite projected faces Pyöräytä-tehosteen näkyvyyslaskenta vaatii äärelliset projisoidut tahkot +@msg SVG options: {e} SVG-asetukset: {e} +@msg Save for Web settings: {e} Verkkotallennuksen asetukset: {e} +@msg TIFF colour profile: {e} TIFF-väriprofiili: {e} +@msg TIFF encoding failed: the pixel buffer doesn't match the image size TIFF-koodaus epäonnistui: pikselipuskuri ei vastaa kuvan kokoa +@msg TIFF encoding failed: {e} TIFF-koodaus epäonnistui: {e} +@msg Targa depth {_1}: 16, 24 or 32 bits per pixel Targa-värisyvyys {_1}: 16, 24 tai 32 bittiä pikseliä kohti +@msg Targa encoding failed: the pixel buffer doesn't match the image size Targa-koodaus epäonnistui: pikselipuskuri ei vastaa kuvan kokoa +@msg The 3D projection is not finite 3D-projektio ei ole äärellinen +@msg The 3D shadow is too complex; turn Shadows off or simplify the art 3D-varjo on liian monimutkainen; poista Varjot käytöstä tai yksinkertaista kuvitusta +@msg The shape contains invalid coordinates Muodossa on virheellisiä koordinaatteja +@msg Too many Revolve faces for visibility evaluation Pyöräytä-tehosteessa on liian monta tahkoa näkyvyyden arviointiin +@msg VectorCraft reads at most {ASE_MAX_ENTRIES} colors and groups from a swatch exchange file, and this library has {entries} VectorCraft lukee värimallien vaihtotiedostosta enintään {ASE_MAX_ENTRIES} väriä ja ryhmää, ja tässä kirjastossa niitä on {entries} +@msg WebP encoding failed: {e} WebP-koodaus epäonnistui: {e} +@msg [{j}] `{_1}`: {why} [{j}] `{_1}`: {why} +@msg `answers[{i}]` {e} `answers[{i}]` {e} +@msg `index` must be a whole number `index` on oltava kokonaisluku +@msg `view` is smallThumb, mediumThumb, largeThumb, smallList or largeList `view` on smallThumb, mediumThumb, largeThumb, smallList tai largeList +@msg a line can't run from a point to itself viiva ei voi kulkea pisteestä samaan pisteeseen +@msg a line needs at least two points viiva tarvitsee vähintään kaksi pistettä +@msg a number cannot be read lukua ei voi lukea +@msg a swatch exchange block is too long värimallien vaihtotiedoston lohko on liian pitkä +@msg a swatch exchange name is too long värimallien vaihtotiedoston nimi on liian pitkä +@msg a {sw} × {sh} image can't be resized to {width} × {height} pixels {sw} × {sh} -kuvan kokoa ei voi muuttaa kokoon {width} × {height} pikseliä +@msg a {width} × {height} image is too large {width} × {height} -kuva on liian suuri +@msg a {width} × {height} image: {e} {width} × {height} -kuva: {e} +@msg an image could not be written: {e} kuvaa ei voitu kirjoittaa: {e} +@msg an image that couldn't be read was left out kuva, jota ei voitu lukea, jätettiin pois +@msg can't open “{name}”: {e} tiedostoa ”{name}” ei voi avata: {e} +@msg cannot align zip entries to {align} bytes zip-merkintöjä ei voi tasata {align} tavun rajoihin +@msg cannot open the automation {kind} root `{_1}`: {e} automaation {kind}-juurikansiota `{_1}` ei voi avata: {e} +@msg cannot read profile: {0} profiilia ei voi lukea: {0} +@msg color book version {version} isn't supported (only 1) värikirjan versiota {version} ei tueta (vain 1) +@msg color books in color space {other} aren't supported (only RGB, CMYK and Lab) väriavaruuden {other} värikirjoja ei tueta (vain RGB, CMYK ja Lab) +@msg file name too long to zip: {_1} tiedostonimi on liian pitkä zip-pakettiin: {_1} +@msg file name too long to zip: {name} tiedostonimi on liian pitkä zip-pakettiin: {name} +@msg freeform line {i}: {e} vapaamuotoinen viiva {i}: {e} +@msg freeform point {i}: {e} vapaamuotoinen piste {i}: {e} +@msg give `{key}` or `{other}`, not both anna `{key}` tai `{other}`, ei molempia +@msg grayscale profiles can't be working spaces yet harmaasävyprofiileja ei voi vielä käyttää työväriavaruuksina +@msg input contains NaN or infinite coordinates syötteessä on NaN-arvoja tai äärettömiä koordinaatteja +@msg input path could not be closed syötepolkua ei voitu sulkea +@msg invalid ICC profile: {0} virheellinen ICC-profiili: {0} +@msg invalid scale {scale} virheellinen skaalaus {scale} +@msg its localized names take more than {_1} KB sen lokalisoidut nimet vievät yli {_1} KB +@msg its objects are nested too deep ({e}) sen objektit ovat sisäkkäin liian monella tasolla ({e}) +@msg its tag table lists the `{_1}` tag more than once sen tunnistetaulukossa `{_1}`-tunniste on useammin kuin kerran +@msg knockout groups with too many overlapping translucent elements are written as PDF knockout groups: their translucent elements knock out what they cover fully poistoryhmät, joissa on liian monta päällekkäistä läpikuultavaa elementtiä, kirjoitetaan PDF-poistoryhminä: niiden läpikuultavat elementit poistavat peittämänsä alueen kokonaan +@msg knockout groups with brushed strokes over other translucent elements are written as PDF knockout groups: their translucent elements knock out what they cover fully poistoryhmät, joissa on sivellinviivoja muiden läpikuultavien elementtien päällä, kirjoitetaan PDF-poistoryhminä: niiden läpikuultavat elementit poistavat peittämänsä alueen kokonaan +@msg not a graphic style library: {e} ei grafiikkatyylikirjasto: {e} +@msg not a swatch library (.vcswatches or .gpl) ei värimallikirjasto (.vcswatches tai .gpl) +@msg not a swatch library (format `{_1}`) ei värimallikirjasto (muoto `{_1}`) +@msg not a swatch library: {e} ei värimallikirjasto: {e} +@msg not an action set file ({e}) ei toimintosarjatiedosto ({e}) +@msg profile colour space {other} is not RGB, CMYK or Gray profiilin väriavaruus {other} ei ole RGB, CMYK tai Gray +@msg regular expression too large säännöllinen lauseke on liian suuri +@msg script file is not UTF-8 text: {value} komentosarjatiedosto ei ole UTF-8-tekstiä: {value} +@msg stop {i}: {e} väripiste {i}: {e} +@msg swatch exchange version {major}.{minor} isn't supported (only 1.x) värimallien vaihtotiedoston versiota {major}.{minor} ei tueta (vain 1.x) +@msg the color book holds more than {ASE_MAX_ENTRIES} colors värikirjassa on yli {ASE_MAX_ENTRIES} väriä +@msg the color book is cut short värikirja on katkennut +@msg the color book's names take more than {_1} MB värikirjan nimet vievät yli {_1} MB +@msg the image would be {w} × {h} pixels; raster exports are limited to {MAX_RASTER_SIDE} pixels per side and {_1} megapixels: lower the scale or resolution kuvasta tulisi {w} × {h} pikseliä; rasteriviennin raja on {MAX_RASTER_SIDE} pikseliä sivua kohti ja {_1} megapikseliä: pienennä skaalausta tai tarkkuutta +@msg the optimised image can't be read back: {e} optimoitua kuvaa ei voi lukea takaisin: {e} +@msg the pixel buffer doesn't match the image size pikselipuskuri ei vastaa kuvan kokoa +@msg the preview: {e} esikatselu: {e} +@msg the request may not read the New Document profiles folder pyyntö ei saa lukea uuden asiakirjan profiilien kansiota +@msg the shapes are too degenerate to combine muodot ovat liian surkastuneita yhdistettäviksi +@msg the shapes cross themselves and each other too often to combine muodot leikkaavat itseään ja toisiaan liian usein yhdistettäviksi +@msg the swatch exchange file holds more than {ASE_MAX_ENTRIES} colors and groups värimallien vaihtotiedostossa on yli {ASE_MAX_ENTRIES} väriä ja ryhmää +@msg the swatch exchange file is cut short värimallien vaihtotiedosto on katkennut +@msg the {_1} plate can't be read: {e} {_1}-painolevyä ei voi lukea: {e} +@msg this binary DXF file is damaged or cut short tämä binäärinen DXF-tiedosto on vioittunut tai katkennut +@msg this is a DWG drawing, which can't be read: save it from the CAD app as a DXF and open that tämä on DWG-piirustus, jota ei voi lukea: tallenna se CAD-sovelluksesta DXF-muodossa ja avaa se +@msg too many classes liikaa luokkia +@msg too many groups liikaa ryhmiä +@msg too many layers for PSD (at most 32767) liikaa tasoja PSD-tiedostoon (enintään 32767) +@msg too many swatch exchange blocks liikaa värimallien vaihtotiedoston lohkoja +@msg unknown colour profile: {0} tuntematon väriprofiili: {0} +@msg {_1} clashes with a built-in profile name {_1} on ristiriidassa sisäisen profiilin nimen kanssa +@msg {_1} × {_2} pixels is too large for GIF (at most 65535 pixels a side): lower the resolution {_1} × {_2} pikseliä on liian suuri GIF-kuvalle (enintään 65535 pikseliä sivua kohti): pienennä tarkkuutta +@msg {_1}: no usable transform to/from sRGB {_1}: ei käyttökelpoista muunnosta sRGB:hen tai sRGB:stä +@msg {name} is not a CMYK profile {name} ei ole CMYK-profiili +@msg {name} is not an RGB profile {name} ei ole RGB-profiili +@msg {path}: could not be read {path}: ei voitu lukea +@msg {width} × {height} pixels is too large for JPEG (at most 65535 pixels a side): lower the resolution {width} × {height} pikseliä on liian suuri JPEG-kuvalle (enintään 65535 pikseliä sivua kohti): pienennä tarkkuutta +@msg {width} × {height} pixels is too large for Targa (at most 65535 pixels a side): lower the resolution {width} × {height} pikseliä on liian suuri Targa-kuvalle (enintään 65535 pikseliä sivua kohti): pienennä tarkkuutta +@msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} pikseliä on liian suuri PSD-kuvalle (enintään {MAX_SIDE} pikseliä sivua kohti): pienennä tarkkuutta diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 3dfd5ad5d9..ca40abddef 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -19,6 +19,7 @@ Edge Brightness Luminosité du bord Smoothness Lissage Radial Blur… Flou radial… + Blur Center Centre du flou Smart Blur… Flou optimisé… Sharpen Renforcement Unsharp Mask… Accentuation… @@ -646,6 +647,7 @@ font-technology Variable Variables Copy All Styles Copier tous les styles Copy Color Value (Hex) Copier la valeur de couleur (hex) Copy Fonts Used in the Document Copier les polices utilisées dans le document + Copy Info Copier les informations Copy Links Copier les liens Copy Selected Style Copier le style sélectionné Copy to User Defined Copier dans Défini par l’utilisateur @@ -907,6 +909,9 @@ font-technology Variable Variables The selected character's font is not available. La police du caractère sélectionné n’est pas disponible. No alternates for the selected character. Aucune variante pour le caractère sélectionné. Double-click to replace Double-cliquez pour remplacer + Click to replace Cliquez pour remplacer + Show all alternates in the Glyphs panel Afficher toutes les variantes dans le panneau Glyphes + Show Character Alternates Afficher les variantes de caractère Select one character with the Type tool first. Sélectionnez d’abord un caractère avec l’outil Texte. {glyph} is a glyph of {font}, not of the font the selected text is set in ({text_font}). {glyph} est un glyphe de {font}, et non de la police du texte sélectionné ({text_font}). {glyph} belongs to {base} (U+{base_code}) {place}; your selection is {sel} (U+{code}). {glyph} appartient à {base} (U+{base_code}) {place} ; votre sélection est {sel} (U+{code}). @@ -1332,6 +1337,7 @@ font-technology Variable Variables Format Format Format Options Options de format Format Settings Paramètres de format + Format Settings… Paramètres de format… Format: Format : Formats: Formats : Fractional Widths Largeurs fractionnaires @@ -1679,6 +1685,7 @@ font-technology Variable Variables Images: Images : Import Keyboard Shortcuts… Importer des raccourcis clavier… Import PDF Importer un PDF + Import PDF pages as links Importer les pages PDF comme liens Import PDF Presets Importer des paramètres prédéfinis PDF Import Perspective Grid Presets Importer des paramètres prédéfinis de grille de perspective Import Print Presets Importer des paramètres prédéfinis d’impression @@ -3433,6 +3440,18 @@ digits Malayalam Malayalam Smart Guides (View → Smart Guides) Repères commentés (Affichage → Repères commentés) Smart Guides (⌘U) Repères commentés (⌘U) Smart Punctuation… Ponctuation typographique… + Smart Punctuation Ponctuation typographique + ff, fi, ffi Ligatures Ligatures ff, fi, ffi + ff, fl, ffl Ligatures Ligatures ff, fl, ffl + Smart Quotes Guillemets typographiques + Smart Spaces Espaces typographiques + En, Em Dashes Tirets demi-cadratin et cadratin + Ellipses Points de suspension + Expert Fractions Fractions expertes + Replace In Remplacer dans + Selected Text Only Texte sélectionné uniquement + Entire Document Document entier + Report Results Afficher les résultats Smooth Lisser Corner Angle Relative Relatif @@ -3463,6 +3482,7 @@ digits Malayalam Malayalam Solid Plein Sort by Kind Trier par type Sort by Name Trier par nom + Sort by Size Trier par taille Sort by Status Trier par état Source code on GitHub Code source sur GitHub Source Sans 3 Source Sans 3 @@ -4363,6 +4383,7 @@ axis Both Les deux @msg there is no script engine named {name} il n'y a aucun moteur de script nommé {name} @msg Running a script Exécution d’un script @msg Copied the script report Rapport du script copié +@msg Copied the link info Informations sur le lien copiées @msg Corners edits the corners of a path Angles modifie les angles d’un tracé @msg Couldn't copy to the system clipboard: {e} Impossible de copier dans le presse-papiers du système : {e} @msg Couldn't open {name}: {e} Impossible d’ouvrir {name} : {e} @@ -6669,7 +6690,7 @@ axis Y Axis Axe Y @plural Result: {n}|Results: {n} Résultat : {n}|Résultats : {n} @msg select one object sélectionnez un seul objet @msg Global Edit works on paths, compound paths, symbol instances and groups of them La modification globale s’applique aux tracés, aux tracés transparents, aux occurrences de symboles et aux groupes de ces objets -@msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again aucun objet similaire trouvé (les copies pivotées ou symétriques ne sont pas reconnues) ; modifiez les options de modification globale et réessayez +@msg no similar objects found (reflected copies are not matched); change the Global Edit Options and try again aucun objet similaire trouvé (les copies symétriques ne sont pas reconnues) ; modifiez les options de modification globale et réessayez @msg Global Edit is off La modification globale n’est pas active @msg only an object of the Global Edit other than the one it started from can be left out seul un objet de la modification globale autre que celui à partir duquel elle a commencé peut être exclu @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards` : all ou une plage telle que 1, 3-5, et non {v} @@ -7462,11 +7483,20 @@ breakText Glyphs Glyphes Open Tutorial Sample Ouvrir le fichier d’exercice du tutoriel Finish Tutorial Terminer le tutoriel Next Tutorial Tutoriel suivant + Show Learn Tab Afficher un onglet d'Apprendre + Show Skill Afficher la compétence + Back One Level Revenir d'un niveau Back to Skills Retour aux compétences @msg tutorial `{id}` has no practice sample le tutoriel `{id}` n’a pas de fichier d’exercice @msg open the practice sample of `{id}` first (see learn.openSample) ouvrez d’abord le fichier d’exercice de `{id}` (voir learn.openSample) @msg finish `{id}` first (see learn.finish) terminez d’abord `{id}` (voir learn.finish) @msg `{id}` is the last tutorial in its skill `{id}` est le dernier tutoriel de sa compétence + Reset progress Réinitialiser la progression + Mark Tutorial Step Marquer une étape du tutoriel + Reset Learn Progress Réinitialiser la progression d’apprentissage +@msg missing `step` (see learn.show) `step` manquant (voir learn.show) +@msg `step` must be a step number from 0 to {last} `step` doit être un numéro d’étape de 0 à {last} +@msg `{id}` is finished (see learn.resetProgress) `{id}` est terminé (voir learn.resetProgress) # Deferred plug-in effects Refresh Deferred Effects Actualiser les effets différés @@ -8866,6 +8896,8 @@ breakText Glyphs Glyphes @msg the RTF file is too large to place as type (at most {_1} MB) le fichier RTF est trop volumineux pour être importé comme texte (au plus {_1} Mo) @msg the SVG expands to more than {0} nested SVG images le SVG se développe en plus de {0} images SVG imbriquées @msg the SVG expands to more than {0} objects le SVG se développe en plus de {0} objets +@msg the SVG's style sheets take too long to match la mise en correspondance des feuilles de style du SVG prend trop de temps +@msg the SVG's styles expand to more than {0} MB les styles du SVG se développent en plus de {0} Mo @msg the SVG file is larger than {MAX_IMPORT_BYTES} bytes le fichier SVG dépasse {MAX_IMPORT_BYTES} octets @msg the SVG has no drawable objects le SVG n’a aucun objet dessinable @msg the SVGZ file unpacks to more than {_1} MB le fichier SVGZ se décompresse en plus de {_1} Mo @@ -9300,3 +9332,122 @@ breakText Glyphs Glyphes Grommets Œillets Grommet Inset Distance des œillets au bord Diameter Diamètre + Nest Shapes… Imbriquer les formes… + Nest Shapes Imbriquer les formes + Roll Rouleau + +# Messages of the effects, 3D, image export, color profiles, swatch exchange files, color books and DXF import. +@msg 3D effects require finite coordinates within 100 million points Les effets 3D exigent des coordonnées finies comprises dans 100 millions de points +@msg 3D effects require one to ten lights Les effets 3D exigent d’une à dix lumières +@msg BMP depth {_1}: 1, 4, 8, 16, 24 or 32 bits per pixel Profondeur BMP {_1} : 1, 4, 8, 16, 24 ou 32 bits par pixel +@msg BMP encoding failed: {width} × {height} pixels doesn't fit the format or the pixel buffer Échec de l’encodage BMP : {width} × {height} pixels ne conviennent ni au format ni au tampon de pixels +@msg GIF encoding failed: the palette image is malformed Échec de l’encodage GIF : l’image à palette est mal formée +@msg GIF encoding failed: {e} Échec de l’encodage GIF : {e} +@msg JPEG colour profile: {e} Profil colorimétrique JPEG : {e} +@msg JPEG encoding failed: pixel buffer doesn't match the image size Échec de l’encodage JPEG : le tampon de pixels ne correspond pas à la taille de l’image +@msg JPEG encoding failed: {e} Échec de l’encodage JPEG : {e} +@msg PNG encoding failed: pixel buffer doesn't match the image size Échec de l’encodage PNG : le tampon de pixels ne correspond pas à la taille de l’image +@msg PNG encoding failed: the palette image is malformed Échec de l’encodage PNG : l’image à palette est mal formée +@msg PNG encoding failed: {e} Échec de l’encodage PNG : {e} +@msg PNG encoding failed: {width} × {height} pixels is not a valid image size Échec de l’encodage PNG : {width} × {height} pixels n’est pas une taille d’image valide +@msg PSD colour profile: {e} Profil colorimétrique PSD : {e} +@msg PSD encoding failed: the pixel buffer doesn't match the image size Échec de l’encodage PSD : le tampon de pixels ne correspond pas à la taille de l’image +@msg Revolve profile contains invalid coordinates Le profil de révolution contient des coordonnées non valides +@msg Revolve profile is too complex Le profil de révolution est trop complexe +@msg Revolve projection is not finite La projection de la révolution n’est pas finie +@msg Revolve requires finite profile coordinates within 100 million points La révolution exige des coordonnées de profil finies comprises dans 100 millions de points +@msg Revolve surface is too complex; reduce Segments or simplify the profile La surface de révolution est trop complexe ; réduisez Segments ou simplifiez le profil +@msg Revolve surface is too complex; simplify the profile La surface de révolution est trop complexe ; simplifiez le profil +@msg Revolve visibility cannot split the projected boundary La visibilité de la révolution ne peut pas diviser le contour projeté +@msg Revolve visibility creates too many fragments La visibilité de la révolution crée trop de fragments +@msg Revolve visibility creates too many vector anchors La visibilité de la révolution crée trop de points d’ancrage vectoriels +@msg Revolve visibility exceeds its geometry work limit La visibilité de la révolution dépasse sa limite de calcul géométrique +@msg Revolve visibility exceeds its spatial index limit La visibilité de la révolution dépasse sa limite d’index spatial +@msg Revolve visibility has too many boundary crossings La visibilité de la révolution compte trop de croisements de contour +@msg Revolve visibility has too many input anchors La visibilité de la révolution compte trop de points d’ancrage en entrée +@msg Revolve visibility requires convex cap sectors La visibilité de la révolution exige des secteurs de fermeture convexes +@msg Revolve visibility requires finite projected faces La visibilité de la révolution exige des faces projetées finies +@msg SVG options: {e} Options SVG : {e} +@msg Save for Web settings: {e} Réglages d’Enregistrer pour le web : {e} +@msg TIFF colour profile: {e} Profil colorimétrique TIFF : {e} +@msg TIFF encoding failed: the pixel buffer doesn't match the image size Échec de l’encodage TIFF : le tampon de pixels ne correspond pas à la taille de l’image +@msg TIFF encoding failed: {e} Échec de l’encodage TIFF : {e} +@msg Targa depth {_1}: 16, 24 or 32 bits per pixel Profondeur Targa {_1} : 16, 24 ou 32 bits par pixel +@msg Targa encoding failed: the pixel buffer doesn't match the image size Échec de l’encodage Targa : le tampon de pixels ne correspond pas à la taille de l’image +@msg The 3D projection is not finite La projection 3D n’est pas finie +@msg The 3D shadow is too complex; turn Shadows off or simplify the art L’ombre 3D est trop complexe ; désactivez Ombres ou simplifiez l’illustration +@msg The shape contains invalid coordinates La forme contient des coordonnées non valides +@msg Too many Revolve faces for visibility evaluation Trop de faces de révolution pour évaluer la visibilité +@msg VectorCraft reads at most {ASE_MAX_ENTRIES} colors and groups from a swatch exchange file, and this library has {entries} VectorCraft lit au plus {ASE_MAX_ENTRIES} couleurs et groupes d’un fichier d’échange de nuances, et cette bibliothèque en contient {entries} +@msg WebP encoding failed: {e} Échec de l’encodage WebP : {e} +@msg [{j}] `{_1}`: {why} [{j}] `{_1}` : {why} +@msg `answers[{i}]` {e} `answers[{i}]` {e} +@msg `view` is smallThumb, mediumThumb, largeThumb, smallList or largeList `view` vaut smallThumb, mediumThumb, largeThumb, smallList ou largeList +@msg a line can't run from a point to itself une ligne ne peut pas relier un point à lui-même +@msg a line needs at least two points une ligne nécessite au moins deux points +@msg a number cannot be read un nombre ne peut pas être lu +@msg a swatch exchange block is too long un bloc du fichier d’échange de nuances est trop long +@msg a swatch exchange name is too long un nom du fichier d’échange de nuances est trop long +@msg a {sw} × {sh} image can't be resized to {width} × {height} pixels une image de {sw} × {sh} ne peut pas être redimensionnée à {width} × {height} pixels +@msg a {width} × {height} image is too large une image de {width} × {height} est trop grande +@msg a {width} × {height} image: {e} une image de {width} × {height} : {e} +@msg an image could not be written: {e} une image n’a pas pu être écrite : {e} +@msg an image that couldn't be read was left out une image illisible a été omise +@msg can't open “{name}”: {e} impossible d’ouvrir « {name} » : {e} +@msg cannot align zip entries to {align} bytes impossible d’aligner les entrées zip sur {align} octets +@msg cannot open the automation {kind} root `{_1}`: {e} impossible d’ouvrir le dossier racine d’automatisation ({kind}) `{_1}` : {e} +@msg cannot read profile: {0} impossible de lire le profil : {0} +@msg color book version {version} isn't supported (only 1) la version {version} du carnet de couleurs n’est pas prise en charge (seulement 1) +@msg color books in color space {other} aren't supported (only RGB, CMYK and Lab) les carnets de couleurs dans l’espace colorimétrique {other} ne sont pas pris en charge (seulement RVB, CMJN et Lab) +@msg file name too long to zip: {_1} nom de fichier trop long pour le zip : {_1} +@msg file name too long to zip: {name} nom de fichier trop long pour le zip : {name} +@msg freeform line {i}: {e} ligne libre {i} : {e} +@msg freeform point {i}: {e} point libre {i} : {e} +@msg give `{key}` or `{other}`, not both indiquez `{key}` ou `{other}`, pas les deux +@msg grayscale profiles can't be working spaces yet les profils en niveaux de gris ne peuvent pas encore servir d’espaces de travail +@msg input contains NaN or infinite coordinates l’entrée contient des coordonnées NaN ou infinies +@msg input path could not be closed le tracé d’entrée n’a pas pu être fermé +@msg invalid ICC profile: {0} profil ICC non valide : {0} +@msg invalid scale {scale} échelle non valide {scale} +@msg its localized names take more than {_1} KB ses noms localisés occupent plus de {_1} Ko +@msg its objects are nested too deep ({e}) ses objets sont trop profondément imbriqués ({e}) +@msg its tag table lists the `{_1}` tag more than once sa table de balises répertorie la balise `{_1}` plus d’une fois +@msg not a graphic style library: {e} ce n’est pas une bibliothèque de styles graphiques : {e} +@msg not a swatch library (.vcswatches or .gpl) ce n’est pas une bibliothèque de nuances (.vcswatches ou .gpl) +@msg not a swatch library (format `{_1}`) ce n’est pas une bibliothèque de nuances (format `{_1}`) +@msg not a swatch library: {e} ce n’est pas une bibliothèque de nuances : {e} +@msg not an action set file ({e}) ce n’est pas un fichier de jeu de scripts ({e}) +@msg profile colour space {other} is not RGB, CMYK or Gray l’espace colorimétrique {other} du profil n’est pas RVB, CMJN ou Niveaux de gris +@msg regular expression too large expression régulière trop volumineuse +@msg script file is not UTF-8 text: {value} le fichier de script n’est pas du texte UTF-8 : {value} +@msg stop {i}: {e} étape de dégradé {i} : {e} +@msg swatch exchange version {major}.{minor} isn't supported (only 1.x) la version {major}.{minor} du fichier d’échange de nuances n’est pas prise en charge (seulement 1.x) +@msg the color book holds more than {ASE_MAX_ENTRIES} colors le carnet de couleurs contient plus de {ASE_MAX_ENTRIES} couleurs +@msg the color book is cut short le carnet de couleurs est tronqué +@msg the color book's names take more than {_1} MB les noms du carnet de couleurs occupent plus de {_1} Mo +@msg the image would be {w} × {h} pixels; raster exports are limited to {MAX_RASTER_SIDE} pixels per side and {_1} megapixels: lower the scale or resolution l’image mesurerait {w} × {h} pixels ; les exports en pixels sont limités à {MAX_RASTER_SIDE} pixels par côté et à {_1} mégapixels : réduisez l’échelle ou la résolution +@msg the optimised image can't be read back: {e} l’image optimisée ne peut pas être relue : {e} +@msg the pixel buffer doesn't match the image size le tampon de pixels ne correspond pas à la taille de l’image +@msg the preview: {e} l’aperçu : {e} +@msg the request may not read the New Document profiles folder la requête n’est pas autorisée à lire le dossier des profils de nouveau document +@msg the shapes are too degenerate to combine les formes sont trop dégénérées pour être combinées +@msg the shapes cross themselves and each other too often to combine les formes se croisent elles-mêmes et entre elles trop souvent pour être combinées +@msg the swatch exchange file holds more than {ASE_MAX_ENTRIES} colors and groups le fichier d’échange de nuances contient plus de {ASE_MAX_ENTRIES} couleurs et groupes +@msg the swatch exchange file is cut short le fichier d’échange de nuances est tronqué +@msg the {_1} plate can't be read: {e} la plaque {_1} ne peut pas être lue : {e} +@msg too many classes trop de classes +@msg too many groups trop de groupes +@msg too many layers for PSD (at most 32767) trop de calques pour le PSD (32767 au plus) +@msg too many swatch exchange blocks trop de blocs dans le fichier d’échange de nuances +@msg unknown colour profile: {0} profil colorimétrique inconnu : {0} +@msg {_1} clashes with a built-in profile name {_1} entre en conflit avec le nom d’un profil intégré +@msg {_1}: no usable transform to/from sRGB {_1} : aucune transformation utilisable vers ou depuis sRGB +@msg {name} is not a CMYK profile {name} n’est pas un profil CMJN +@msg {name} is not an RGB profile {name} n’est pas un profil RVB +@msg {path}: could not be read {path} : lecture impossible +@msg {width} × {height} pixels is too large for JPEG (at most 65535 pixels a side): lower the resolution {width} × {height} pixels, c’est trop grand pour le JPEG (65535 pixels par côté au plus) : réduisez la résolution +@msg {width} × {height} pixels is too large for Targa (at most 65535 pixels a side): lower the resolution {width} × {height} pixels, c’est trop grand pour le Targa (65535 pixels par côté au plus) : réduisez la résolution +@msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} pixels, c’est trop grand pour le PSD ({MAX_SIDE} pixels par côté au plus) : réduisez la résolution +@msg this is a DWG drawing, which can't be read: save it from the CAD app as a DXF and open that c’est un dessin DWG, qui ne peut pas être lu : enregistrez-le depuis l’application de CAO au format DXF et ouvrez ce fichier +@msg this binary DXF file is damaged or cut short ce fichier DXF binaire est endommagé ou tronqué +@msg {_1} × {_2} pixels is too large for GIF (at most 65535 pixels a side): lower the resolution {_1} × {_2} pixels, c’est trop grand pour le GIF (65535 pixels par côté au plus) : réduisez la résolution diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 716d851655..9bf646d1dc 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -743,6 +743,7 @@ Copy Artboard આર્ટબોર્ડ નકલ કરો Copy Color Value (Hex) રંગ મૂલ્યની નકલ કરો (Hex) Copy Guide ગાઇડ નકલ કરો + Copy Info માહિતી નકલ કરો Copy Report રિપોર્ટ નકલ કરો Copy Script Console સ્ક્રિપ્ટ કન્સોલ નકલ કરો Copy Selected પસંદ કરેલું નકલ કરો @@ -1046,6 +1047,9 @@ Double-click to insert દાખલ કરવા ડબલ-ક્લિક કરો Double-click to rename નામ બદલવા ડબલ-ક્લિક કરો Double-click to replace બદલવા ડબલ-ક્લિક કરો + Click to replace બદલવા ક્લિક કરો + Show all alternates in the Glyphs panel ગ્લિફ્સ પેનલમાં બધા વૈકલ્પિક બતાવો + Show Character Alternates અક્ષરના વૈકલ્પિક બતાવો Double-click to target the contents સામગ્રી લક્ષ્ય બનાવવા ડબલ-ક્લિક કરો Download: ડાઉનલોડ: Drag ખેંચો @@ -1454,6 +1458,7 @@ Format Options ફોર્મેટ વિકલ્પો Format Presets ફોર્મેટ પ્રીસેટ્સ Format Settings ફોર્મેટ સેટિંગ્સ + Format Settings… ફોર્મેટ સેટિંગ્સ… Format: ફોર્મેટ: Formats: ફોર્મેટ્સ: Fractional Widths અપૂર્ણાંક પહોળાઈ @@ -1708,6 +1713,7 @@ Import Library લાઇબ્રેરી આયાત કરો Import Matches આયાત મેળ Import PDF PDF આયાત કરો + Import PDF pages as links PDF પેજને લિંક તરીકે આયાત કરો Import PDF Presets PDF આયાત પ્રીસેટ્સ Import Perspective Grid Presets પર્સ્પેક્ટિવ ગ્રિડ પ્રીસેટ્સ આયાત કરો Import Preferences પસંદગીઓ આયાત કરો @@ -2765,6 +2771,7 @@ Radar Graph Tool રડાર ગ્રાફ ટૂલ Radial રેડિયલ Radial Blur… રેડિયલ બ્લર… + Blur Center બ્લરનું કેન્દ્ર Radial Dividers: રેડિયલ વિભાજક: Radial Glows રેડિયલ ઝગમગાટ Radial Gradient રેડિયલ ગ્રેડિઅન્ટ @@ -3561,6 +3568,18 @@ Smart Pen Panel સ્માર્ટ પેન પેનલ Smart Pen Tool સ્માર્ટ પેન ટૂલ Smart Punctuation… સ્માર્ટ વિરામચિહ્નો… + Smart Punctuation સ્માર્ટ વિરામચિહ્નો + ff, fi, ffi Ligatures ff, fi, ffi લિગેચર + ff, fl, ffl Ligatures ff, fl, ffl લિગેચર + Smart Quotes સ્માર્ટ અવતરણચિહ્નો + Smart Spaces સ્માર્ટ જગ્યાઓ + En, Em Dashes En અને Em ડૅશ + Ellipses એલિપ્સિસ + Expert Fractions નિષ્ણાત અપૂર્ણાંકો + Replace In આમાં બદલો + Selected Text Only માત્ર પસંદ કરેલું લખાણ + Entire Document આખો દસ્તાવેજ + Report Results પરિણામોનો અહેવાલ Smooth સ્મૂધ Smooth Anchors… એન્કર સ્મૂધ કરો… Smooth Tool સ્મૂધ ટૂલ @@ -4533,6 +4552,9 @@ antiAlias Sharp શાર્પ Open Tutorial Sample ટ્યુટોરિયલનો નમૂનો ખોલો Finish Tutorial ટ્યુટોરિયલ પૂર્ણ કરો Next Tutorial આગળનો ટ્યુટોરિયલ + Show Learn Tab શીખો ટૅબ બતાવો + Show Skill કૌશલ્ય બતાવો + Back One Level એક સ્તર પાછા જાઓ Back to Skills કૌશલ્યો પર પાછા જાઓ Cutting Tools કટિંગ ટૂલ્સ Stencil Bridges… સ્ટેન્સિલ બ્રિજિસ… diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 3c77aa0a99..01e758f46b 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -763,8 +763,8 @@ antiAlias Sharp शार्प Change Case प्रकरण बदलें Change Panel Layout पैनल लेआउट बदलें Change Screen Mode (F) स्क्रीन मोड बदलें (F) - Change to Artboard Rulers आर्टबोर्ड शासकों में परिवर्तन - Change to Global Rulers वैश्विक शासकों में परिवर्तन + Change to Artboard Rulers आर्टबोर्ड रूलर्स में परिवर्तन + Change to Global Rulers ग्लोबल रूलर्स में परिवर्तन Change to Left-to-Right Layout लेफ्ट-टू-राइट लेआउट में परिवर्तन Change to Right-to-Left Layout राइट-टू-लेफ्ट लेआउट में परिवर्तन Changed since the last check. आखिरी चेक के बाद से बदल गया। @@ -780,12 +780,12 @@ antiAlias Sharp शार्प Channel 4 चैनल 4 Character कैरेक्टर Character / Paragraph कैरेक्टर / पैराग्राफ - Character Alignment चरित्र संरेखण - Character Color चरित्र रंग - Character Direction चरित्र निर्देशन - Character options चरित्र ऑप्शन्स - Character Rotation चरित्र रोटेशन - Character Set: चरित्र सेट: + Character Alignment कैरेक्टर संरेखण + Character Color कैरेक्टर रंग + Character Direction कैरेक्टर दिशा + Character options कैरेक्टर ऑप्शन्स + Character Rotation कैरेक्टर रोटेशन + Character Set: कैरेक्टर सेट: Character Style कैरेक्टर स्टाइल Character Style Options कैरेक्टर स्टाइल ऑप्शन्स Character Styles कैरेक्टर स्टाइल्स @@ -975,7 +975,7 @@ antiAlias Sharp शार्प Compatible Gradient and Gradient Mesh Printing कंपैटिबल ग्रेडिएंट और ग्रेडिएंट मेश प्रिंटिंग Compiled or not text संकलित या टेक्स्ट नहीं Compiled script: ask its author for the .jsx file कंपाइल की हुई स्क्रिप्ट: इसके लेखक से .jsx फ़ाइल माँगें - Complement संगम + Complement पूरक Complementary पूरक Complementary 2 पूरक 2 Complete पूरा करना @@ -992,18 +992,18 @@ antiAlias Sharp शार्प Compression संपीड़न Compression › Color › Above Ppi संपीड़न › रंग › पीपीआई के ऊपर Compression: संपीड़न: - Concave अवतरण + Concave अवतल Concentric Dividers: सांद्रिक विभाजक: Condition identifier: शर्त पहचानकर्ता: Configure Shape आकार को कॉन्फ़िगर करें Conflict {n} of {count} {count} में से विरोध {n} Connect कनेक्ट - Connect Selected End Points कनेक्ट सिलेक्टेड अंत अंक + Connect Selected End Points सिलेक्टेड एंड पॉइंट्स कनेक्ट करें Consider Open Filled Paths as Closed बंद के रूप में ओपन भरा पाथ पर विचार करें Consolidate All Windows सभी विंडो एक साथ लाएँ - Constrain कंस्ट्रक्शन - Constrain Angle कंस्ट्रक्शन एंगल - Constrain Width and Height Proportions कंस्ट्रक्शन चौड़ाई और ऊंचाई के अनुपात + Constrain सीमित करें + Constrain Angle कंस्ट्रेन एंगल + Constrain Width and Height Proportions चौड़ाई और ऊंचाई का अनुपात बनाए रखें Construction Guides निर्माण गाइड Conté Crayon कॉन्टे क्रेयॉन Conté Crayon… कॉन्टे क्रेयॉन… @@ -1061,6 +1061,7 @@ antiAlias Sharp शार्प Copy Guide कॉपी गाइड Copy in Perspective पर्सपेक्टिव में प्रतिलिपि Copy into the document's folder डॉक्यूमेंट के फ़ोल्डर में कॉपी करें + Copy Info जानकारी कॉपी करें Copy Links कॉपी लिंक Copy only fonts you own or are licensed to install. केवल उन फ़ॉन्टों को कॉपी करें जिन्हें आप स्वयं करते हैं या इंस्टॉल करने के लिए लाइसेंस प्राप्त हैं। Copy Report रिपोर्ट कॉपी करें @@ -1182,7 +1183,7 @@ antiAlias Sharp शार्प Cut Artboard कट आर्टबोर्ड Rename Artboards आर्टबोर्ड्स का नाम बदलें Cut Path कट पाथ - Cut Path at Selected Anchor Points सिलेक्टेड एंकर अंक पर पाथ काटें + Cut Path at Selected Anchor Points सिलेक्टेड एंकर पॉइंट्स पर पाथ काटें Cutout कटआउट Cutout… कटआउट… Cyan सियान @@ -1326,7 +1327,7 @@ antiAlias Sharp शार्प Description: विवरण: Deselect डीसिलेक्ट करें Design… डिजाइन… - Desired देसी + Desired वांछित Destination Folder: गंतव्य फ़ोल्डर: Destination: गंतव्य: Detail डिटेल @@ -1355,7 +1356,7 @@ antiAlias Sharp शार्प Dimensions आयाम Direct Selection प्रत्यक्ष सिलेक्शन Direct Selection Tool डायरेक्ट सिलेक्शन टूल - Direct-select anchor points to edit them. उन्हें संपादित करने के लिए डायरेक्ट-सिलेक्शन एंकर अंक। + Direct-select anchor points to edit them. एंकर पॉइंट्स को संपादित करने के लिए उन्हें डायरेक्ट-सिलेक्ट करें। Direction Balance दिशा संतुलन Direction Handles निर्देशन हैंडल Direction: दिशा: @@ -1463,6 +1464,9 @@ antiAlias Sharp शार्प Double-click to insert सम्मिलित करने के लिए डबल क्लिक करें Double-click to rename नाम बदलने के लिए डबल क्लिक करें Double-click to replace प्रतिस्थापित करने के लिए डबल क्लिक करें + Click to replace प्रतिस्थापित करने के लिए क्लिक करें + Show all alternates in the Glyphs panel ग्लिफ़्स पैनल में सभी ऑप्शन दिखाएँ + Show Character Alternates कैरेक्टर के ऑप्शन दिखाएँ Select one character with the Type tool first. पहले टाइप टूल से एक कैरेक्टर सिलेक्ट करें। {glyph} is a glyph of {font}, not of the font the selected text is set in ({text_font}). {glyph} {font} का ग्लिफ़ है, उस फ़ॉन्ट का नहीं जिसमें सिलेक्ट किया टेक्स्ट सेट है ({text_font})। {glyph} belongs to {base} (U+{base_code}) {place}; your selection is {sel} (U+{code}). {glyph} {base} (U+{base_code}) का है, {place}; आपका सिलेक्शन {sel} (U+{code}) है। @@ -1683,7 +1687,7 @@ antiAlias Sharp शार्प Envelope #10 लिफाफाफा #10 Envelope Distort एन्वेलप डिस्टॉर्ट Envelope DL लिफ़ाफ़ा DL - Envelope Info लिफाफे की जानकारी + Envelope Info एन्वेलप जानकारी Envelope Mesh एन्वेलप मेश Envelope Options एन्वेलप ऑप्शन्स Envelope Options… एन्वेलप ऑप्शन्स… @@ -1694,7 +1698,7 @@ antiAlias Sharp शार्प Eraser Tool इरेज़र टूल Error त्रुटि Esc Esc - Even शाम + Even बराबर Even Fields सम फ़ील्ड्स Even-Numbered Anchors यहां तक कि संख्या वाले एंकर Event: कार्यक्रम: @@ -1869,7 +1873,7 @@ antiAlias Sharp शार्प Fill new strokes नए स्ट्रोक भरें Fill New Type Objects With Placeholder Text नए टाइप ऑब्जेक्ट्स में प्लेसहोल्डर टेक्स्ट भरें Fill Pattern पैटर्न भरें - Fill Rule नियम भरें + Fill Rule फ़िल रूल Fill with Placeholder Text प्लेसहोल्डर टेक्स्ट से भरें Fill: फ़िल: Fill: click for swatches, Shift-click for the color mixer फ़िल: स्वॉचेस के लिए क्लिक करें, कलर मिक्सर के लिए Shift-क्लिक करें @@ -1877,7 +1881,7 @@ antiAlias Sharp शार्प Filled Open Paths भरा खुला पाथ Filled Square भरा वर्ग Filling in form fields and signing फॉर्म फ़ील्ड में भरना और साइन करना - Fills भरता + Fills फ़िल्स Film & Video फ़िल्म और वीडियो Film Grain… फ़िल्म ग्रेन… Filter फ़िल्टर @@ -1981,7 +1985,7 @@ antiAlias Sharp शार्प fonts not copied: {fonts} फ़ॉन्ट कॉपी नहीं हुए: {fonts} Fonts whose licence doesn't allow embedding are not copied. जिन फ़ॉन्ट का लाइसेंस एम्बेडिंग की अनुमति नहीं देता है, उन्हें कॉपी नहीं किया जाता है। For Fractions: फ्रैक्शन के लिए: - Force सेना + Force बलपूर्वक Forced Line Break जबरन लाइन ब्रेक Foreground Level फ़ोरग्राउंड स्तर Forget Import Matches फॉरगेट आयात मैच @@ -1990,6 +1994,7 @@ antiAlias Sharp शार्प Format Options फ़ॉर्मेट ऑप्शन्स Format Presets फ़ॉर्मैट प्रीसेट Format Settings फ़ॉर्मैट सेटिंग + Format Settings… फ़ॉर्मैट सेटिंग… Format: फ़ॉर्मेट: Formats: फ़ॉर्मैट: Fractional Widths आंशिक चौड़ाई @@ -2019,7 +2024,7 @@ antiAlias Sharp शार्प Full Width पूर्ण चौड़ाई Fully Inside पूरी तरह से अंदर Fully Outside पूरी तरह बाहर - Function Key: समारोह कुंजी: + Function Key: फ़ंक्शन की: Fuzziness: फ़ज़ीनेस: Gamma गामा Gamut Check गैमट जाँच @@ -2217,8 +2222,8 @@ antiAlias Sharp शार्प Hide Gradient Annotator ग्रेडिएंट एनोटेटर छिपाएँ Hide Grid ग्रिड छिपाएँ Hide Guides गाइड्स छिपाएँ - Hide Hidden Characters छिपे हुए चरित्र छुपाएं - Hide Live Paint Gaps छुपा लाइव पेंट गैप + Hide Hidden Characters हिडन कैरेक्टर छिपाएँ + Hide Live Paint Gaps लाइव पेंट गैप छिपाएँ Hide Note नोट छिपाएँ Hide Options ऑप्शन्स छिपाएँ Hide Others अन्य छिपाएँ @@ -2230,23 +2235,23 @@ antiAlias Sharp शार्प Hide Template टेम्पलेट छिपाएँ Hide Text Threads टेक्स्ट थ्रेड छुपाएं Hide Thumbnail थंबनेल छिपाएँ - Hide Thumbnails हिंदुस्तान + Hide Thumbnails थंबनेल छिपाएँ Hide Transparency Grid पारदर्शिता ग्रिड छिपाएँ Hide Units इकाइयाँ छिपाएँ Hide VectorCraft VectorCraft छिपाएँ - Hide Video Rulers वीडियो शासक + Hide Video Rulers वीडियो रूलर्स छिपाएँ High उच्च High (300 ppi) उच्च (300 ppi) - High Contrast उच्च न्यायालय - High Contrast 2 उच्च न्यायालय 2 - High Contrast 3 उच्च न्यायालय 3 + High Contrast उच्च कंट्रास्ट + High Contrast 2 उच्च कंट्रास्ट 2 + High Contrast 3 उच्च कंट्रास्ट 3 High Fidelity Photo उच्च निष्ठा फोटो High Performance (discrete) उच्च निष्पादन (डिस्क्रीट) High Quality Print उच्च गुणवत्ता वाले प्रिंट High resolution उच्च रिज़ॉल्यूशन High Resolution उच्च रिज़ॉल्यूशन Highlight हाइलाइट - Highlight Alternate Glyphs हाइलाइट अल्टरनेटर ग्लिफ़ + Highlight Alternate Glyphs अल्टरनेट ग्लिफ़ हाइलाइट करें Highlight anchors on mouse over माउस ओवर पर हाइलाइट एंकर Highlight Area हाइलाइट क्षेत्र Highlight Font Name हाइलाइट फ़ॉन्ट नाम @@ -2329,6 +2334,7 @@ antiAlias Sharp शार्प Import Library… आयात लाइब्रेरी… Import Matches आयात मैच Import PDF PDF आयात करें + Import PDF pages as links PDF पृष्ठों को लिंक के रूप में आयात करें Import PDF Presets PDF प्रीसेट्स इम्पोर्ट करें Import Perspective Grid Presets आयात पर्सपेक्टिव ग्रिड प्रीसेट Import Preset… प्रीसेट इम्पोर्ट करें… @@ -2470,7 +2476,7 @@ antiAlias Sharp शार्प Keep Original मूल रखें Keep Plain Text प्लेन टेक्स्ट रखें Keep selected सिलेक्ट करें - Keep Shared Points Together साझा अंक एक साथ रखें + Keep Shared Points Together साझा पॉइंट्स एक साथ रखें Keep the pasted color as a new swatch with a numbered name. पेस्ट किए गए रंग को क्रमांकित नाम वाले नए स्वॉच के रूप में रखें। Keep this row's colors (exclude) इस पंक्ति के रंग (बाहर) रखें Keep visible surfaces only when expanding विस्तार करते समय केवल दृश्यमान सतहों को रखें @@ -2757,7 +2763,7 @@ antiAlias Sharp शार्प Manage Workspaces… वर्कस्पेस प्रबंधित करें… Manually मैन्युअल Marathi मराठी - Mark as trapped निशानेबाज़ी + Mark as trapped ट्रैप्ड के रूप में चिह्नित करें Mark Older Files as [Converted] When Opened पुरानी फ़ाइलें ओपन करने पर उन्हें [Converted] चिह्नित करें Marker… मार्कर… Marks मार्क्स @@ -2828,7 +2834,7 @@ antiAlias Sharp शार्प Minimize छोटा करें Minimum न्यूनतम Minimum angle न्यूनतम कोण - Minimum must not exceed Desired, nor Desired Maximum. न्यूनतम से अधिक नहीं होना चाहिए, न ही अधिकतम होना चाहिए। + Minimum must not exceed Desired, nor Desired Maximum. न्यूनतम, वांछित से अधिक नहीं होना चाहिए और वांछित, अधिकतम से अधिक नहीं होना चाहिए। Minimum: न्यूनतम: Minus Back पीछे वाला घटाएँ Minus Front सामने वाला घटाएँ @@ -3032,7 +3038,7 @@ antiAlias Sharp शार्प Next Segment अगला खंड No नहीं No actions. Press ● to record. कोई कार्रवाई नहीं। प्रेस ● रिकॉर्ड करने के लिए। - No alternates for the selected character. सिलेक्टेड चरित्र के लिए कोई ऑप्शन नहीं। + No alternates for the selected character. सिलेक्टेड कैरेक्टर के लिए कोई अल्टरनेट नहीं। No artboards match. कोई आर्टबोर्ड मैच नहीं। No assets कोई संपत्ति नहीं No assets yet. Collect art with Object › Collect for Export, or drag it into the Asset Export panel. अभी कोई एसेट नहीं है। ऑब्जेक्ट › एक्सपोर्ट के लिए कलेक्ट करें से आर्टवर्क जोड़ें या उसे एसेट एक्सपोर्ट पैनल में ड्रैग करें। @@ -3115,7 +3121,7 @@ antiAlias Sharp शार्प Number of Recent Fonts हाल ही में फ़ॉन्ट की संख्या Number: संख्या: Numbered List क्रमांकित सूची - Numbers Without Units Are Points यूनिट्स के बिना नंबर अंक हैं + Numbers Without Units Are Points यूनिट्स के बिना संख्याएँ पॉइंट में हैं Numerator न्यूमेरेटर Object ऑब्जेक्ट Object Highlighting ऑब्जेक्ट हाइलाइटिंग @@ -3289,7 +3295,7 @@ antiAlias Sharp शार्प Outer Glow… बाहरी ग्लो… Outline रूपरेखा Outline Object रूपरेखा ऑब्जेक्ट - Outline Others अन्य लोग + Outline Others अन्य को आउटलाइन व्यू में दिखाएँ Outline Stroke स्ट्रोक को आउटलाइन में बदलें Outline Text टेक्स्ट को आउटलाइन में बदलें Outlined Strokes रेखांकित स्ट्रोक @@ -3343,7 +3349,7 @@ antiAlias Sharp शार्प Pages पृष्ठ Paint Daubs पेंट डॉब्स Paint Daubs… पेंट डॉब्स… - Paint Fills पेंट भरता + Paint Fills फ़िल्स पेंट करें Paint Opacity: पेंट ओपेसिटी: Paint Stops At: पेंट स्टॉप: Paint Strokes पेंट स्ट्रोक @@ -3576,7 +3582,7 @@ antiAlias Sharp शार्प Pointillize पॉइंटिलाइज़ Pointillize… पॉइंटिलाइज़… Points पॉइंट्स - Points per segment प्रति खंड अंक + Points per segment प्रति सेगमेंट पॉइंट्स Points: पॉइंट्स: Points: clicks add free points पॉइंट्स: क्लिक से अलग-अलग पॉइंट जुड़ते हैं Polar Grid ध्रुवीय ग्रिड @@ -3727,6 +3733,7 @@ antiAlias Sharp शार्प Radial रेडियल Radial Blur रेडियल ब्लर Radial Blur… रेडियल ब्लर… + Blur Center ब्लर का केंद्र Radial Dividers: रेडियल विभाजक: Radial Glows रेडियल चमक Radial Gradient रेडियल ग्रेडिएंट @@ -3914,7 +3921,7 @@ antiAlias Sharp शार्प Remove Line Breaks लाइन ब्रेक हटाएँ Remove Paragraph Breaks पैराग्राफ ब्रेक निकालें Remove Plug-in प्लग-इन निकालें - Remove Points, Keep Shape अंक निकालें, आकार रखें + Remove Points, Keep Shape पॉइंट्स हटाएँ, शेप रखें Remove Redundant Points गैरज़रूरी पॉइंट हटाएँ Remove Selected Assets सिलेक्टेड परिसंपत्तियों को हटा दें Remove Selected Entry सिलेक्टेड प्रविष्टि निकालें @@ -4019,7 +4026,7 @@ antiAlias Sharp शार्प Edit Arrowheads… एरोहेड्स संपादित करें… Reload Arrowheads एरोहेड्स फिर से लोड करें Reset Rotate View व्यू घुमाएँ रीसेट करें - Reset Ruler Origin शासकीय उत्पत्ति रीसेट करें + Reset Ruler Origin रूलर ओरिजिन रीसेट करें Reset Symbol Instance सिंबल इंस्टेंस रीसेट करें Reset Text Transform टेक्स्ट ट्रांसफॉर्मर को रीसेट करें Reset Text Transform and Scale टेक्स्ट ट्रांसफॉर्म और स्केल को रीसेट करें @@ -4093,7 +4100,7 @@ antiAlias Sharp शार्प RGB: RGB: Ridges per segment: प्रति खंड रिज: Right दाएँ - Right Complement सही पूरक + Right Complement राइट कम्प्लीमेंट Right Diagonal दायाँ विकर्ण Right Grid: राइट ग्रिड: Right in Front फ्रंट में राइट @@ -4152,14 +4159,14 @@ antiAlias Sharp शार्प Ruby रूबी Ruby… रूबी… Rule: नियम: - Ruler Origin शासकीय उत्पत्ति + Ruler Origin रूलर ओरिजिन Rulers रूलर्स Rulers & Grids रूलर्स और ग्रिड Run Length रन लंबाई Run Plug-in रन प्लग-इन Runs code the checker can't read रन कोड चेकर को पढ़ा नहीं जा सकता Russian रूसी - Same समीर + Same समान Same As Source स्रोत के समान Same file एक ही फ़ाइल Same item as a later row बाद में पंक्ति के रूप में समान आइटम @@ -4302,8 +4309,8 @@ antiAlias Sharp शार्प Saved Views सेव किया गया दृश्य Saves the current bars, toolbar and panel layout. वर्तमान बार, टूलबार और पैनल लेआउट को सेव करता है। Saving सेव किया जा रहा है - Saving {} बचत {} - Saving Poster.vectorcraft बचत Poster.vectorcraft + Saving {} {} सेव किया जा रहा है + Saving Poster.vectorcraft Poster.vectorcraft सेव किया जा रहा है Saving recovery data for {} {} के लिए रिकवरी डेटा सेव करना Scale आकार बदलें Scale Artwork with Artboard आर्टबोर्ड के साथ स्केल आर्टवर्क @@ -4367,7 +4374,7 @@ antiAlias Sharp शार्प Select a character with the Type tool to see its alternates. अल्टरनेट ग्लिफ़ देखने के लिए टाइप टूल से कोई कैरेक्टर सिलेक्ट करें। Select a parametric shape to edit it. With none selected, these set the next shape. एडिट करने के लिए पैरामीट्रिक शेप सिलेक्ट करें। कोई शेप सिलेक्ट न होने पर ये सेटिंग्स अगली शेप पर लागू होंगी। Select a text object एक टेक्स्ट ऑब्जेक्ट चुनें - Select a text object to edit its character attributes. अपने चरित्र विशेषताओं को संपादित करने के लिए एक टेक्स्ट ऑब्जेक्ट चुनें। + Select a text object to edit its character attributes. कैरेक्टर एट्रिब्यूट्स संपादित करने के लिए एक टेक्स्ट ऑब्जेक्ट चुनें। Select a text object to edit its paragraph attributes. अपनी पैराग्राफ विशेषताओं को संपादित करने के लिए एक टेक्स्ट ऑब्जेक्ट चुनें। Select a text object to set its tab stops. अपने टैब स्टॉप सेट करने के लिए एक टेक्स्ट ऑब्जेक्ट चुनें। Select All सभी सिलेक्ट करें @@ -4396,7 +4403,7 @@ antiAlias Sharp शार्प Select by Link Status… लिंक स्थिति द्वारा सिलेक्ट करें… Select Data Set डेटा सेट सिलेक्ट करें Select Embedded एम्बेडेड सिलेक्ट करें - Select Fills भरता सिलेक्ट करें + Select Fills फ़िल्स सिलेक्ट करें Select Freeform Point फ़्रीफ़ॉर्म पॉइंट सिलेक्ट करें Select Gradient Stop ग्रेडिएंट स्टॉप चुनें Select Guides गाइड्स सिलेक्ट करें @@ -4643,7 +4650,7 @@ antiAlias Sharp शार्प Show Tool Tips टूल युक्तियाँ दिखाएँ Show Toolbar शो टूलबार Show Transparency Grid पारदर्शिता ग्रिड दिखाएँ - Show Video Rulers शो वीडियो शासक + Show Video Rulers वीडियो रूलर्स दिखाएँ Show Video Safe Areas वीडियो सुरक्षित क्षेत्र दिखाएं Show Vivid/Muted चमकीले/मंद दिखाएँ Show Warm/Cool शो वार्म / कूल @@ -4726,6 +4733,18 @@ antiAlias Sharp शार्प Smart Pen Panel स्मार्ट पेन पैनल Smart Pen Tool स्मार्ट पेन टूल Smart Punctuation… स्मार्ट विराम-चिह्न… + Smart Punctuation स्मार्ट विराम-चिह्न + ff, fi, ffi Ligatures ff, fi, ffi लिगेचर + ff, fl, ffl Ligatures ff, fl, ffl लिगेचर + Smart Quotes स्मार्ट उद्धरण-चिह्न + Smart Spaces स्मार्ट स्पेस + En, Em Dashes एन और एम डैश + Ellipses दीर्घविराम + Expert Fractions विशेषज्ञ भिन्न + Replace In इसमें रिप्लेस करें + Selected Text Only केवल सिलेक्ट किया गया टेक्स्ट + Entire Document पूरा डॉक्यूमेंट + Report Results परिणाम रिपोर्ट करें Smooth स्मूथ Smooth Anchors चिकना एंकर Smooth Anchors… चिकना एंकर… @@ -4765,6 +4784,7 @@ antiAlias Sharp शार्प Sort by Luminance द्वारा क्रमबद्ध Luminance Sort by Name नाम से क्रमबद्ध करें Sort by Popularity लोकप्रियता द्वारा क्रमबद्ध + Sort by Size आकार द्वारा क्रमबद्ध Sort by Status स्थिति द्वारा क्रमबद्ध Sort By: द्वारा क्रमबद्ध: Sort Objects ऑब्जेक्ट्स को क्रमबद्ध करें @@ -5096,7 +5116,7 @@ antiAlias Sharp शार्प The Print Tiling tool placed the pages. प्रिंट टाइलिंग टूल ने पृष्ठों को रखा। The samples show this brush on a blue stroke. नमूने इस ब्रश को ब्लू स्ट्रोक पर दिखाते हैं। The search stopped at its limit: search a smaller folder. सर्च अपनी लिमिट तक पहुँच गई: छोटे फ़ोल्डर में सर्च करें। - The selected character's font is not available. सिलेक्टेड चरित्र का फ़ॉन्ट उपलब्ध नहीं है। + The selected character's font is not available. सिलेक्टेड कैरेक्टर का फ़ॉन्ट उपलब्ध नहीं है। The selected objects have no CSS of their own (see below). सिलेक्टेड ऑब्जेक्ट का अपना CSS नहीं है (नीचे देखें)। The system's settings of this printer इस प्रिंटर की प्रणाली की सेटिंग These fonts aren't available. Their text shows in another font. ये फ़ॉन्ट उपलब्ध नहीं हैं। इनका टेक्स्ट दूसरे फ़ॉन्ट में दिखता है। @@ -5130,7 +5150,7 @@ antiAlias Sharp शार्प Tile Edge Color टाइल एज रंग Tile Edge Color… टाइल एज रंग… Tile Full Pages टाइल पूर्ण पृष्ठ - Tile Imageable Areas टाइल कल्पनाशील क्षेत्र + Tile Imageable Areas इमेजेबल क्षेत्र टाइल करें Tile Range: टाइल रेंज: Tile Size टाइल साइज़ Tile Type: टाइल प्रकार: @@ -5239,9 +5259,9 @@ antiAlias Sharp शार्प Transverse (the page a quarter turn on the paper) ट्रांसवर्स (पेपर पर एक चौथाई मोड़ पृष्ठ) Trap ट्रैप Trap… ट्रैप… - Traps with Process Color प्रक्रिया रंग के साथ जाल - Triad त्रिदाद - Triad 2 त्रिद 2 + Traps with Process Color प्रोसेस रंग के साथ ट्रैप + Triad त्रिक + Triad 2 त्रिक 2 Triad 3 त्रिक 3 Triangle त्रिभुज Triangle (open) त्रिभुज (ओपन) @@ -5249,7 +5269,7 @@ antiAlias Sharp शार्प Trim ट्रिम करें Trim covered geometry on Expand Appearance. Live preview keeps the full surface. Transparent paints and surfaces exceeding visibility limits retain all faces. अपीयरेंस एक्सपैंड करने पर ढकी हुई ज्यामिति ट्रिम करें। लाइव प्रीव्यू पूरी सतह रखता है। ट्रांसपेरेंट पेंट और विज़िबिलिटी लिमिट से बड़ी सतहों के सभी फेस बने रहते हैं। Trim mark weight: ट्रिम मार्क वजन: - Trim marks ट्रिम अंक + Trim marks ट्रिम मार्क्स Trim View ट्रिम देखें True Colors असली रंग True colour needs version 2004 or later: the nearest of 256 colours is written. ट्रू कलर के लिए संस्करण 2004 या बाद का चाहिए: अभी 256 रंगों में सबसे निकट वाला रंग लिखा जाता है। @@ -5476,7 +5496,7 @@ antiAlias Sharp शार्प Video 1920×1080 1920 × 1080 वीडियो Video 3840×2160 वीडियो 3840 × 2160 Video Banner 2560×1440 वीडियो बैनर 2560 × 1440 - Video Ruler Pixel Aspect Ratio: वीडियो शासक पिक्सेल दृष्टि अनुपात: + Video Ruler Pixel Aspect Ratio: वीडियो रूलर पिक्सेल आस्पेक्ट रेशियो: Fade Region Outside Artboard आर्टबोर्ड के बाहर का क्षेत्र धुंधला करें Update While Dragging खींचते समय अपडेट करें Video Thumbnail 1280×720 वीडियो थंबनेल 1280 × 720 @@ -5501,7 +5521,7 @@ antiAlias Sharp शार्प Warp Options वार्प ऑप्शन्स Warp Tool वार्प टूल Watch 184×224 घड़ी 184 × 224 - Watch 198×242 देखें 198 × 242 + Watch 198×242 घड़ी 198 × 242 Water Paper वॉटर पेपर Water Paper… वॉटर पेपर… Watercolor वॉटरकलर @@ -5998,7 +6018,7 @@ antiAlias Sharp शार्प @msg `{name}` is no recovery entry name `{name}` कोई वसूली प्रविष्टि नाम नहीं है @msg `{name}` isn't a colour swatch `{name}` रंग स्वॉच नहीं है @msg `{name}` takes a paint of its own kind (colour, gradient or pattern) `{name}` अपने ही प्रकार का पेंट लेता है (रंग, ग्रेडिएंट या पैटर्न) -@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: न्यूनतम इच्छा से अधिक नहीं होना चाहिए, न ही इच्छा अधिकतम +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: न्यूनतम, वांछित से अधिक नहीं होना चाहिए और वांछित, अधिकतम से अधिक नहीं होना चाहिए @msg `{other}` doesn't trace an image `{other}` एक इमेज का पता नहीं लगा @msg `{path}` must be a bool or an object of bools `{path}` एक bool होना चाहिए या एक ऑब्जेक्ट होना चाहिए। @msg `{s}` is not a colour (#rrggbb or a preset name) `{s}` एक रंग नहीं है (#rrggbb या एक पूर्व निर्धारित नाम) @@ -6353,7 +6373,7 @@ antiAlias Sharp शार्प @msg a wraparound group is inside a compound path एक रैपराउंड समूह एक मिश्रित पाथ के अंदर है @msg action is required action आवश्यक है @msg add a format to export निर्यात करने के लिए एक फ़ॉर्मैट जोड़ें -@msg Add Points at Crossings: a path went missing क्रॉसिंग्स में अंक जोड़ें: एक पाथ गायब हो गया +@msg Add Points at Crossings: a path went missing क्रॉसिंग पर पॉइंट जोड़ें: एक पाथ गायब हो गया @msg aiVersion {v}: "pdf" (PDF-compatible, the default) or "7" (legacy .ai, version 7) aiVersion {v}: "pdf" (PDF-संगत, डिफ़ॉल्ट) या "7" (पुरानी .ai, संस्करण 7) @msg aiVersion 7 writes legacy .ai files, not .ait templates aiVersion 7 विरासत .ai फ़ाइलों को लिखते हैं, .ait टेम्पलेट नहीं @msg All colors are within the CMYK gamut सभी रंग CMYK गामट के भीतर हैं @@ -6541,7 +6561,7 @@ antiAlias Sharp शार्प @msg choose at least one status कम से कम एक स्थिति चुनें @msg Choose original artwork, not a dimension's generated paths मूल आर्टवर्क चुनें, एक आयाम उत्पन्न पाथ नहीं @msg choose the font files to add जोड़ने के लिए फ़ॉन्ट फ़ाइलों को चुनें -@msg Choose two different points दो अलग-अलग अंक चुनें +@msg Choose two different points दो अलग-अलग पॉइंट्स चुनें @msg Choose two non-parallel straight segments दो गैर-parallel सीधे खंड चुनें @msg Choose two nonzero angle arms दो nonzero कोण हथियार चुनें @msg Click in type with a Type tool to split it इसे विभाजित करने के लिए टाइप टूल के साथ टाइप करें @@ -6691,6 +6711,7 @@ antiAlias Sharp शार्प @msg there is no script engine named {name} {name} नाम का कोई स्क्रिप्ट इंजन नहीं है @msg Running a script स्क्रिप्ट चल रही है @msg Copied the script report Copied स्क्रिप्ट रिपोर्ट +@msg Copied the link info लिंक जानकारी कॉपी की गई @msg copy needs path: the file to copy into the document's folder copy के लिए path चाहिए: डॉक्यूमेंट के फ़ोल्डर में कॉपी करने वाली फ़ाइल @msg copy takes images only: relink placed documents where their files are copy केवल इमेज लेता है: प्लेस किए गए डॉक्यूमेंट्स को वहीं फिर से लिंक करें जहाँ उनकी फ़ाइलें हैं @msg copying a file isn't available on the web एक फ़ाइल की प्रतिलिपि वेब पर उपलब्ध नहीं है @@ -6758,7 +6779,7 @@ antiAlias Sharp शार्प @msg Dimension mode does not match its source आयाम मोड अपने स्रोत से मेल नहीं खाता है @msg Dimension point is outside the canvas आयाम बिंदु कैनवास के बाहर है @msg Dimension size is outside its supported range आयाम आकार अपनी समर्थित सीमा से बाहर है -@msg direct-select anchor points of a path एक पाथ के प्रत्यक्ष सिलेक्शन एंकर अंक +@msg direct-select anchor points of a path किसी पाथ के एंकर पॉइंट्स डायरेक्ट-सिलेक्ट करें @msg direct-select anchor points to cut at (not the end points of open paths) डायरेक्ट-सिलेक्शन एंकर पॉइंट्स को कट करने के लिए ( ओपन पाथ के अंतिम बिंदु नहीं) @msg direct-select the anchor points to remove हटाने के लिए एंकर पॉइंट्स सिलेक्ट करें @msg distance must be > 0 distance > 0 होना चाहिए @@ -6813,7 +6834,7 @@ antiAlias Sharp शार्प @msg exit isolation mode first पहले अलगाव मोड से बाहर निकलें @msg Expand Appearance: the selection has a basic appearance उपस्थिति का विस्तार: सिलेक्शन में एक बुनियादी उपस्थिति है @msg Expand: no brush strokes selected विस्तार: सिलेक्टेड कोई ब्रश स्ट्रोक नहीं -@msg Expand: no gradient fills विस्तार: कोई ग्रेडिएंट भरता नहीं +@msg Expand: no gradient fills एक्सपैंड: कोई ग्रेडिएंट फ़िल नहीं @msg Expand: nothing to expand विस्तार: विस्तार करने के लिए कुछ नहीं @msg expanded SVG styles exceed the import size limit विस्तारित SVG स्टाइल्स आयात आकार सीमा से अधिक है @msg expected {{"dataBase64": "…"}} अपेक्षित: {{"dataBase64": "…"}} @@ -6946,7 +6967,7 @@ antiAlias Sharp शार्प @msg Global Edit is off ग्लोबल एडिट बंद है @msg Global Edit works on paths, compound paths, symbol instances and groups of them ग्लोबल एडिट पाथ, मिश्रित पाथ, सिंबल उदाहरणों और उनके समूहों पर काम करता है @msg global must be true or false global को true या false होना चाहिए -@msg glyph {_1} is not drawn for {ch} with the character's style (such as All Caps, Small Caps or a numeral system) Glyph {_1} चरित्र की स्टाइल (जैसे सभी कैप्स, छोटे कैप्स या एक संख्यात्मक प्रणाली) के साथ {ch} के लिए तैयार नहीं है। +@msg glyph {_1} is not drawn for {ch} with the character's style (such as All Caps, Small Caps or a numeral system) Glyph {_1} कैरेक्टर की स्टाइल (जैसे सभी कैप्स, छोटे कैप्स या एक संख्यात्मक प्रणाली) के साथ {ch} के लिए तैयार नहीं है। @msg glyph {g} is not an alternate of {ch} in {_1} {_2} Glyph {g} {_1} {_2} में {ch} का एक वैकल्पिक नहीं है। @msg gradient “{name}” isn't defined in the file: a plain colour stands in for it ग्रेडिएंट "{name}" को फ़ाइल में परिभाषित नहीं किया गया है: इसके लिए एक सादे रंग खड़ा है @msg gradient must be "objects" or "mesh" gradient "objects" या "mesh" होना चाहिए @@ -7203,8 +7224,8 @@ antiAlias Sharp शार्प @msg missing point लापता बिंदु @msg missing point [x,y] लापता बिंदु [x,y] @msg missing point `{key}` ([x, y]) लापता बिंदु `{key}` ([x, y]) -@msg missing points लापता अंक -@msg missing points [[x,y]…] लापता अंक [[x,y]...] +@msg missing points पॉइंट्स नहीं दिए गए +@msg missing points [[x,y]…] पॉइंट्स नहीं दिए गए [[x,y]…] @msg missing segment लापता खंड @msg missing stops लापता ठहराव @msg missing subpaths लापता subpaths @@ -7251,7 +7272,7 @@ antiAlias Sharp शार्प @msg no active data set कोई सक्रिय डेटा सेट नहीं @msg no active document कोई सक्रिय डॉक्यूमेंट @msg no active perspective plane कोई सक्रिय पर्सपेक्टिव विमान नहीं -@msg no anchor points selected कोई एंकर अंक नहीं चुना गया +@msg no anchor points selected कोई एंकर पॉइंट सिलेक्ट नहीं है @msg no app to open files here यहां फ़ाइलों को ओपन करने के लिए कोई ऐप नहीं है @msg no appearance item {index} कोई उपस्थिति आइटम {index} @msg no artboard कोई आर्टबोर्ड नहीं @@ -7276,7 +7297,7 @@ antiAlias Sharp शार्प @msg no brush selected कोई ब्रश नहीं चुना गया @msg no catalog कोई सूची नहीं @msg no changes since the last save आखिरी सेव के बाद से कोई बदलाव नहीं -@msg no character at byte {start} byte {start} पर कोई चरित्र नहीं +@msg no character at byte {start} byte {start} पर कोई कैरेक्टर नहीं @msg no character style `{name}` कोई कैरेक्टर स्टाइल `{name}` @msg no clock to keep a heartbeat by हार्टबीट का समय रखने के लिए कोई घड़ी नहीं @msg no color group `{name}` in the document (see swatch.list) डॉक्यूमेंट में कोई रंग समूह `{name}` (देखें swatch.list) @@ -7413,7 +7434,7 @@ antiAlias Sharp शार्प @msg no selected slice in the image: select slices, or save all of them इमेज में कोई सिलेक्टेड स्लाइस नहीं: स्लाइस सिलेक्ट करें, या सभी स्लाइस सेव करें @msg no selection bounds कोई सिलेक्शन सीमा नहीं @msg no series {i} कोई श्रृंखला {i} -@msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again कोई समान ऑब्जेक्ट नहीं पाया (घूर्णित या परिलक्षित प्रतियां मिलान नहीं की जाती हैं); वैश्विक संपादन ऑप्शन्स बदलें और फिर से प्रयास करें +@msg no similar objects found (reflected copies are not matched); change the Global Edit Options and try again कोई समान ऑब्जेक्ट नहीं पाया (परिलक्षित प्रतियां मिलान नहीं की जाती हैं); वैश्विक संपादन ऑप्शन्स बदलें और फिर से प्रयास करें @msg no slice {n} in the image (see slice.list) इमेज में कोई स्लाइस {n} नहीं है (slice.list देखें) @msg no slice selected सिलेक्टेड कोई स्लाइस नहीं @msg no source art कोई स्रोत कला @@ -7780,7 +7801,7 @@ antiAlias Sharp शार्प @msg Saved to User Defined: {_1} उपयोगकर्ता परिभाषित करने के लिए सेव किया गया: {_1} @msg savedPreset: {e} savedPreset: {e} @msg Saving सेव किया जा रहा है -@msg Saving {_1} बचत {_1} +@msg Saving {_1} {_1} सेव किया जा रहा है @msg Saving recovery data for {_1} {_1} के लिए रिकवरी डेटा सेव करना @msg scale `{s}`: a factor such as 2x, a width (100w), a height (100h) or a resolution (72ppi) पैमाने `{s}`: एक कारक जैसे 2x, चौड़ाई (100w), ऊंचाई (100h) या एक रिज़ॉल्यूशन (72ppi) @msg scale must be a number above 0, at most 64 scale 0 से बड़ी और अधिकतम 64 संख्या होनी चाहिए @@ -7872,7 +7893,7 @@ antiAlias Sharp शार्प @msg Select only dimensions केवल आयाम सिलेक्ट करें @msg select open paths to close बंद करने के लिए खुले रास्ते सिलेक्ट करें @msg select paths पाथ चुनें -@msg select paths or anchor points पाथ या एंकर अंक चुनें +@msg select paths or anchor points पाथ या एंकर पॉइंट्स चुनें @msg select paths or compound paths पाथ या यौगिक पाथ सिलेक्ट करें @msg select paths to join जोड़ने के लिए पाथ सिलेक्ट करें @msg select paths with dashed strokes to expand विस्तृत करने के लिए डैश स्ट्रोक के साथ पाथ सिलेक्ट करें @@ -7880,7 +7901,7 @@ antiAlias Sharp शार्प @msg select plain rectangles, ellipses or regular polygons to convert बदलने के लिए सादे आयत, अंडाकार या नियमित बहुभुजों सिलेक्ट करें @msg Select point type पॉइंट टाइप सिलेक्ट करें @msg select rows or objects to collect इकट्ठा करने के लिए पंक्तियों या ऑब्जेक्ट्स सिलेक्ट करें -@msg select segments, or paths, to add points to खंडों, या पाथ का सिलेक्ट करने के लिए, अंक जोड़ने के लिए +@msg select segments, or paths, to add points to पॉइंट्स जोड़ने के लिए सेगमेंट या पाथ सिलेक्ट करें @msg select some type first पहले कुछ टाइप सिलेक्ट करें @msg select something to export निर्यात करने के लिए कुछ का सिलेक्शन @msg select something to export (or turn off selectedOnly) एक्सपोर्ट करने के लिए कुछ चुनें (या selectedOnly बंद करें) @@ -8066,7 +8087,7 @@ antiAlias Sharp शार्प @msg the artboards don't fit on the canvas: fewer artboards, less spacing or a smaller size आर्टबोर्ड कैनवास पर फिट नहीं हैं: कम आर्टबोर्ड, कम रिक्ति या छोटे आकार @msg the background worker stopped पृष्ठभूमि कार्यकर्ता बंद कर दिया @msg the blend has no spine मिश्रण में कोई रीढ़ नहीं है -@msg the character's size can't be measured चरित्र का आकार मापा नहीं जा सकता है +@msg the character's size can't be measured कैरेक्टर का आकार मापा नहीं जा सकता है @msg the CMYK image couldn't be written CMYK इमेज को नहीं लिखा जा सकता @msg the Color Picker is not open रंग पिकर खुला नहीं है @msg the compound shape is too complex to expand मिश्रित आकार का विस्तार करने के लिए बहुत जटिल है @@ -8119,7 +8140,7 @@ antiAlias Sharp शार्प @msg the file's variable library couldn't be read: the Variables panel doesn't list it फ़ाइल की वेरिएबल लाइब्रेरी पढ़ी नहीं जा सकी: वेरिएबल्स पैनल उसे सूचीबद्ध नहीं करता @msg the file's variable library was partly read (entries skipped: {_1}): the Variables panel lists the rest फ़ाइल की वेरिएबल लाइब्रेरी आंशिक रूप से पढ़ी गई (छोड़ी गई प्रविष्टियाँ: {_1}): वेरिएबल्स पैनल शेष प्रविष्टियाँ दिखाता है @msg the files come to more than 1 GB: add fewer at a time फ़ाइलों को 1 GB से अधिक करने के लिए आते हैं: एक समय में कम जोड़ें -@msg the first character of a line has no character before it to kern: it moves only up and down (dy) एक पंक्ति के पहले चरित्र में बर्न से पहले कोई चरित्र नहीं है: यह केवल ऊपर और नीचे चला जाता है (डी) +@msg the first character of a line has no character before it to kern: it moves only up and down (dy) किसी लाइन के पहले कैरेक्टर से पहले कर्न करने के लिए कोई कैरेक्टर नहीं है: यह केवल ऊपर और नीचे जाता है (dy) @msg the font {_1} is not available फ़ॉन्ट {_1} उपलब्ध नहीं है @msg the format has no file extension फ़ॉर्मैट में कोई फ़ाइल एक्सटेंशन नहीं है @msg the graphic can't be read: {e} ग्राफिक पढ़ा नहीं जा सकता: {e} @@ -8280,6 +8301,8 @@ antiAlias Sharp शार्प @msg the subpath is closed or too short to close सबपैथ बंद है या बंद करने के लिए बहुत कम है @msg the SVG expands to more than {0} nested SVG images SVG {0} नेस्टेड SVG इमेज से अधिक का विस्तार करता है @msg the SVG expands to more than {0} objects SVG {0} ऑब्जेक्ट्स से अधिक का विस्तार करता है +@msg the SVG's style sheets take too long to match SVG की स्टाइल शीट का मिलान करने में बहुत अधिक समय लगता है +@msg the SVG's styles expand to more than {0} MB SVG की शैलियाँ {0} MB से अधिक तक विस्तारित होती हैं @msg the SVG has no drawable objects SVG में कोई आकर्षक ऑब्जेक्ट नहीं है @msg the SVG's elements are nested more than {0} deep SVG के तत्वों को {0} से अधिक गहरा घोंसला दिया जाता है @msg the SVGZ file unpacks to more than {_1} MB SVGZ फ़ाइल ने {_1} MB से अधिक के लिए अनपैक किया @@ -8407,8 +8430,8 @@ antiAlias Sharp शार्प @msg unknown brush type `{o}` अज्ञात ब्रश प्रकार `{o}` @msg unknown category `{c}` अज्ञात श्रेणी `{c}` @msg unknown category `{c}` ({_1}) अज्ञात श्रेणी `{c}` ({_1}) -@msg unknown character `{c}` अज्ञात चरित्र `{c}` -@msg unknown character style number field अज्ञात चरित्र स्टाइल संख्या क्षेत्र +@msg unknown character `{c}` अज्ञात कैरेक्टर `{c}` +@msg unknown character style number field अज्ञात कैरेक्टर स्टाइल संख्या फ़ील्ड @msg unknown CMYK profile `{name}` अज्ञात CMYK प्रोफ़ाइल `{name}` @msg unknown command `{0}` अज्ञात आदेश `{0}` @msg step {step} of “{action}” runs the unknown command `{command}` “{action}” का चरण {step} अज्ञात आदेश `{command}` चलाता है @@ -8858,11 +8881,20 @@ theme Appearance अपीयरेंस Open Tutorial Sample ट्यूटोरियल का नमूना खोलें Finish Tutorial ट्यूटोरियल पूरा करें Next Tutorial अगला ट्यूटोरियल + Show Learn Tab सीखें का टैब दिखाएँ + Show Skill कौशल दिखाएँ + Back One Level एक स्तर वापस Back to Skills कौशल पर वापस जाएँ @msg tutorial `{id}` has no practice sample ट्यूटोरियल `{id}` का कोई अभ्यास नमूना नहीं है @msg open the practice sample of `{id}` first (see learn.openSample) पहले `{id}` का अभ्यास नमूना खोलें (learn.openSample देखें) @msg finish `{id}` first (see learn.finish) पहले `{id}` पूरा करें (learn.finish देखें) @msg `{id}` is the last tutorial in its skill `{id}` अपने कौशल का अंतिम ट्यूटोरियल है + Reset progress प्रगति रीसेट करें + Mark Tutorial Step ट्यूटोरियल चरण चिह्नित करें + Reset Learn Progress सीखने की प्रगति रीसेट करें +@msg missing `step` (see learn.show) लापता `step` (learn.show देखें) +@msg `step` must be a step number from 0 to {last} `step` 0 से {last} तक की चरण संख्या होनी चाहिए +@msg `{id}` is finished (see learn.resetProgress) `{id}` पूरा हो चुका है (learn.resetProgress देखें) # Deferred plug-in effects Refresh Deferred Effects स्थगित इफ़ेक्ट्स रिफ्रेश करें @@ -8892,3 +8924,6 @@ theme Appearance अपीयरेंस Grommets आईलेट Grommet Inset किनारे से आईलेट की दूरी Diameter व्यास + Nest Shapes… आकृतियाँ सटाकर रखें… + Nest Shapes आकृतियाँ सटाकर रखें + Roll रोल diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index c4cdb9d544..0a09eb2e55 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -838,6 +838,7 @@ font-technology Variable Változó Copy Artboard Rajztábla másolása Copy Color Value (Hex) Színérték másolása (hex) Copy Fonts Used in the Document A dokumentumban használt betűtípusok másolása + Copy Info Adatok másolása Copy Links Csatolások másolása Copy only fonts you own or are licensed to install. Csak olyan betűtípust másolj, amely a tiéd, vagy amelynek telepítésére licenced van. Copy Selected Style Kijelölt stílus másolása @@ -1172,6 +1173,9 @@ font-technology Variable Változó The selected character's font is not available. A kijelölt karakter betűtípusa nem érhető el. No alternates for the selected character. A kijelölt karakternek nincsenek változatai. Double-click to replace Csere dupla kattintással + Click to replace Csere kattintással + Show all alternates in the Glyphs panel Minden változat megjelenítése a Glifák panelen + Show Character Alternates Karakterváltozatok megjelenítése Select one character with the Type tool first. Előbb jelölj ki egy karaktert a Szöveg eszközzel. {glyph} is a glyph of {font}, not of the font the selected text is set in ({text_font}). A(z) {glyph} a(z) {font} glifája, nem a kijelölt szöveg betűtípusáé ({text_font}). {glyph} belongs to {base} (U+{base_code}) {place}; your selection is {sel} (U+{code}). A(z) {glyph} ehhez tartozik: {base} (U+{base_code}) {place}; a te kijelölésed: {sel} (U+{code}). @@ -1663,6 +1667,7 @@ file-filter Templates Sablonok Format Formátum Format Options Formátumbeállítások Format Settings Formátumbeállítások + Format Settings… Formátumbeállítások… Format: Formátum: Formats: Formátumok: Fractional Widths Tört szélességek @@ -2103,6 +2108,7 @@ file-filter Templates Sablonok Import Library Könyvtár importálása Import Library… Könyvtár importálása… Import PDF PDF importálása + Import PDF pages as links PDF-oldalak importálása csatolásként Import PDF Presets PDF-előbeállítások importálása Import Perspective Grid Presets Perspektivikus rács előbeállításainak importálása Import Print Presets Nyomtatási előbeállítások importálása @@ -3256,6 +3262,7 @@ mark-style Japanese Japán Radial Körkörös Radial Blur Körkörös elmosás Radial Blur… Körkörös elmosás… + Blur Center Elmosás középpontja Radial Glows Körkörös ragyogások Organic Fades Organikus áttűnések Holographic Holografikus @@ -4093,6 +4100,18 @@ mark-style Japanese Japán Smart Guides (View → Smart Guides) Intelligens segédvonalak (Nézet → Intelligens segédvonalak) Smart Guides (⌘U) Intelligens segédvonalak (⌘U) Smart Punctuation… Intelligens írásjelek… + Smart Punctuation Intelligens írásjelek + ff, fi, ffi Ligatures ff, fi, ffi ligatúrák + ff, fl, ffl Ligatures ff, fl, ffl ligatúrák + Smart Quotes Intelligens idézőjelek + Smart Spaces Intelligens szóközök + En, Em Dashes Gondolatjelek és nagykötőjelek + Ellipses Három pont + Expert Fractions Szakértői törtek + Replace In Csere helye + Selected Text Only Csak a kijelölt szöveg + Entire Document Teljes dokumentum + Report Results Eredmények jelentése Smooth Simítás Smooth Color Sima színátmenet Smooth Tool Simítás @@ -4123,6 +4142,7 @@ mark-style Japanese Japán Sort by Luminance Rendezés fénysűrűség szerint Sort by Name Rendezés név szerint Sort by Popularity Rendezés gyakoriság szerint + Sort by Size Rendezés méret szerint Sort by Status Rendezés állapot szerint Source code on GitHub Forráskód a GitHubon Source Image Forráskép @@ -5186,6 +5206,7 @@ imageTrace Outline Körvonal @msg there is no script engine named {name} nincs {name} nevű parancsfájlmotor @msg Running a script Parancsfájl futtatása @msg Copied the script report Szkriptjelentés másolva +@msg Copied the link info Csatolás adatai másolva @msg Corners edits the corners of a path a Sarkok parancs egy útvonal sarkait szerkeszti @msg could not decode image: {0} a kép nem dekódolható: {0} @msg Couldn't copy to the system clipboard: {e} Nem sikerült a rendszer vágólapjára másolni: {e} @@ -6657,7 +6678,7 @@ axis Y Axis Y tengely @plural Result: {n}|Results: {n} Eredmény: {n} @msg select one object jelöljön ki egy objektumot @msg Global Edit works on paths, compound paths, symbol instances and groups of them A globális szerkesztés útvonalakon, összetett útvonalakon, szimbólumpéldányokon és ezek csoportjain működik -@msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again nem található hasonló objektum (az elforgatott vagy tükrözött másolatok nem számítanak egyezésnek); módosítsa a globális szerkesztés beállításait, és próbálja újra +@msg no similar objects found (reflected copies are not matched); change the Global Edit Options and try again nem található hasonló objektum (a tükrözött másolatok nem számítanak egyezésnek); módosítsa a globális szerkesztés beállításait, és próbálja újra @msg Global Edit is off A globális szerkesztés nincs bekapcsolva @msg only an object of the Global Edit other than the one it started from can be left out a globális szerkesztésből csak a kiindulási objektumtól eltérő objektum zárható ki @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all vagy egy tartomány, például 1, 3-5, nem {v} @@ -7451,11 +7472,20 @@ breakText Glyphs Glifák Open Tutorial Sample Oktatóanyag mintafájljának megnyitása Finish Tutorial Oktatóanyag befejezése Next Tutorial Következő oktatóanyag + Show Learn Tab Tanulás lap megjelenítése + Show Skill Készség megjelenítése + Back One Level Egy szinttel vissza Back to Skills Vissza a készségekhez @msg tutorial `{id}` has no practice sample nincs gyakorló mintafájl ehhez az oktatóanyaghoz: `{id}` @msg open the practice sample of `{id}` first (see learn.openSample) előbb nyissa meg a gyakorló mintafájlt ehhez: `{id}` (lásd: learn.openSample) @msg finish `{id}` first (see learn.finish) előbb fejezze be ezt: `{id}` (lásd: learn.finish) @msg `{id}` is the last tutorial in its skill a készsége utolsó oktatóanyaga: `{id}` + Reset progress Előrehaladás visszaállítása + Mark Tutorial Step Oktatóanyag lépésének megjelölése + Reset Learn Progress Tanulási előrehaladás visszaállítása +@msg missing `step` (see learn.show) hiányzik: `step` (lásd: learn.show) +@msg `step` must be a step number from 0 to {last} a `step` értéke 0 és {last} közötti lépésszám legyen +@msg `{id}` is finished (see learn.resetProgress) befejezve: `{id}` (lásd: learn.resetProgress) # Deferred plug-in effects Refresh Deferred Effects Elhalasztott effektusok frissítése @@ -7485,6 +7515,1826 @@ breakText Glyphs Glifák Grommets Ringlik Grommet Inset Ringlik távolsága a széltől Diameter Átmérő + Nest Shapes… Alakzatok elrendezése… + Nest Shapes Alakzatok elrendezése + Roll Tekercs + +# Status and error messages of commands, scripts, file import and export, and plug-ins. +@msg 'caller', 'callee' and 'arguments' cannot be used on strict mode functions a 'caller', a 'callee' és az 'arguments' nem használható szigorú módú függvényeken +@msg A profile supports one Revolve effect. Edit the existing effect's options instead. Egy profilon egy Forgatás tengely körül effektus lehet. Inkább a meglévő effektus beállításait szerkeszd. +@msg Add Points at Crossings: a path went missing Pontok hozzáadása a kereszteződésekben: egy útvonal eltűnt +@msg Alignment must be one of the choices Az igazítás csak a választási lehetőségek egyike lehet +@msg Boolean.prototype.{name} was called on a value that is not a Boolean a Boolean.prototype.{name} hívása olyan értéken történt, amely nem Boolean +@msg CMYK images whose samples couldn't be read in CMYK were imported in RGB Azok a CMYK-képek, amelyek mintái nem voltak CMYK-ban olvashatók, RGB-ben lettek importálva +@msg CSS options: {e} CSS-beállítások: {e} +@msg CSV has a header but no data rows A CSV-ben van fejléc, de nincsenek adatsorok +@msg CSV holds NUL bytes: save it as UTF-8, or as UTF-16 with a byte-order mark A CSV NUL bájtokat tartalmaz: mentsd UTF-8-ként, vagy bájtsorrendjellel ellátott UTF-16-ként +@msg CSV is empty A CSV üres +@msg CSV is larger than {MAX_CSV_BYTES} bytes A CSV nagyobb, mint {MAX_CSV_BYTES} bájt +@msg CSV is not UTF-16 A CSV nem UTF-16 kódolású +@msg CSV is not UTF-8 A CSV nem UTF-8 kódolású +@msg CSV would be larger than {MAX_CSV_BYTES} bytes A CSV nagyobb lenne, mint {MAX_CSV_BYTES} bájt +@msg Cannot write to the location of “{name}”; choose where to save it Nem lehet írni ennek a helyére: „{name}”; válaszd ki, hová kerüljön a mentés +@msg Choose original artwork, not a dimension's generated paths Eredeti grafikát válassz, ne egy méretvonal generált útvonalait +@msg Contour: select paths or shapes Kontúr: jelölj ki útvonalakat vagy alakzatokat +@msg Contour: the Offset Path effect is not available Kontúr: az Útvonal eltolása effektus nem érhető el +@msg Create needs fills, strokes or both A létrehozáshoz kitöltések, körvonalak vagy mindkettő kell +@msg DCS files can only be placed linked: use File › Place with Link on A DCS-fájlok csak csatolva helyezhetők el: használd a Fájl › Elhelyezés parancsot bekapcsolt Csatolás beállítással +@msg DXF options: {e} DXF-beállítások: {e} +@msg DXF scale must be a positive number up to {_1}, not {scale} A DXF-lépték pozitív szám lehet, legfeljebb {_1}; ez nem az: {scale} +@msg DXF {field} `{s}`: {allowed} DXF {field} `{s}`: {allowed} +@msg Date.prototype method called on a value that is not a Date object Date.prototype metódus hívása olyan értéken történt, amely nem Date objektum +@msg Dimension is locked or hidden A méretvonal zárolt vagy rejtett +@msg Dimension mode does not match its source A méretvonal módja nem egyezik a forrásával +@msg Draw Inside needs exactly one selected path, compound path or text A Rajzolás belülre módhoz pontosan egy kijelölt útvonal, összetett útvonal vagy szöveg kell +@msg EPS Save writes all artwork: use document.export for selected-only EPS Az EPS-mentés a teljes grafikát kiírja: csak a kijelölést tartalmazó EPS-hez használd a document.export parancsot +@msg EPS flattener: {e} EPS-lapító: {e} +@msg EPS options: {e} EPS-beállítások: {e} +@msg EPS {field} `{s}`: {allowed} EPS {field} `{s}`: {allowed} +@msg Error.prototype.toString was called on a value that is not an object az Error.prototype.toString hívása olyan értéken történt, amely nem objektum +@msg Export for Screens writes png, png8, jpg, webp, gif, tiff, bmp, tga, psd, svg, svgz, pdf, eps, ai or vectorcraft Az Exportálás képernyőkre ezeket írja: png, png8, jpg, webp, gif, tiff, bmp, tga, psd, svg, svgz, pdf, eps, ai vagy vectorcraft +@msg Flare click coordinates must be finite numbers A Fényvillanás kattintási koordinátái véges számok legyenek +@msg Function.prototype.toString was called on a value that is not a function a Function.prototype.toString hívása olyan értéken történt, amely nem függvény +@msg HTML Text applies to object slices of type only A HTML-szöveg csak szövegobjektumból készült szeletekre alkalmazható +@msg Identify Objects By is XML ID: the name must be a valid XML ID (start with a letter, underscore or colon; no spaces) Az Objektumok azonosítása beállítás XML-azonosító: a névnek érvényes XML-azonosítónak kell lennie (betűvel, aláhúzásjellel vagy kettősponttal kezdődik; szóköz nélkül) +@msg Image Trace failed: internal error: its thread stopped (please report this bug) A képvektorizálás nem sikerült: belső hiba: a szála leállt (kérjük, jelentsd ezt a hibát) +@msg Image Trace failed: {e} A képvektorizálás nem sikerült: {e} +@msg Image Trace finished, but its document was closed A képvektorizálás elkészült, de a dokumentumát bezárták +@msg Image Trace finished, but the image or its settings changed meanwhile: trace it again A képvektorizálás elkészült, de a kép vagy a beállításai közben megváltoztak: vektorizáld újra +@msg Import SVG Filter reads SVG files, not SVGZ Az SVG-szűrő importálása SVG-fájlokat olvas, SVGZ-fájlokat nem +@msg Invalid dimension offset Érvénytelen méretvonal-eltolás +@msg Invalid point Érvénytelen pont +@msg JSON.parse: {why} (at offset {at}) JSON.parse: {why} (eltolás: {at}) +@msg JSON.stringify cannot write a structure that contains itself a JSON.stringify nem tud olyan szerkezetet kiírni, amely önmagát tartalmazza +@msg Join: a subpath went missing Összekapcsolás: egy részútvonal eltűnt +@msg Line Gap must be a number A Sorköz szám kell legyen +@msg Lock Workspace is not available in VectorCraft A Munkaterület zárolása nem érhető el a VectorCraftban +@msg Move Panel to New Window is not available: floating panels stay in the main window A Panel áthelyezése új ablakba nem érhető el: a lebegő panelek a főablakban maradnak +@msg Namespace.prototype.toString needs a Namespace a Namespace.prototype.toString hívásához Namespace kell +@msg New Document profiles need the preferences folder, which this run doesn't have Az új dokumentumok profiljaihoz a beállítások mappája kell, amely ebben a futásban nincs meg +@msg Number.prototype.{name} was called on a value that is not a number a Number.prototype.{name} hívása olyan értéken történt, amely nem szám +@msg Object.create's prototype must be an object or null az Object.create prototípusa objektum vagy null lehet +@msg Object.{function} was given a value that is not an object az Object.{function} olyan értéket kapott, amely nem objektum +@msg Offset Path: the path is too complex to offset Útvonal eltolása: az útvonal túl összetett az eltoláshoz +@msg Offset Path: {e} Útvonal eltolása: {e} +@msg PDF content is incomplete or exceeds the reader's limits; no document was imported A PDF tartalma hiányos, vagy túllépi az olvasó korlátait; nem lett dokumentum importálva +@msg PDF flattener: {e} PDF-lapító: {e} +@msg PDF options: {e} PDF-beállítások: {e} +@msg QName.prototype.toString needs a QName a QName.prototype.toString hívásához QName kell +@msg Recolor Artwork is no longer open A Grafika átszínezése már nincs megnyitva +@msg RegExp.prototype.{name} was called on a value that is not a RegExp object a RegExp.prototype.{name} hívása olyan értéken történt, amely nem RegExp objektum +@msg SVG is not UTF-8, UTF-16 or ISO 8859-1 Az SVG nem UTF-8, UTF-16 vagy ISO 8859-1 kódolású +@msg Save writes one artboard: name one, or export several with document.export A mentés egy rajztáblát ír ki: nevezz meg egyet, vagy exportálj többet a document.export paranccsal +@msg Select a dimension first Előbb jelölj ki egy méretvonalat +@msg Select dimensions to update Jelöld ki a frissítendő méretvonalakat +@msg Select only dimensions Csak méretvonalakat jelölj ki +@msg Select two or more objects, or a group Jelölj ki két vagy több objektumot, vagy egy csoportot +@msg Shaper needs 1–64 source paths Az Alakformálóhoz 1–64 forrásútvonal kell +@msg Stencil Bridges: the selected art is too large or too detailed to bridge Sablonhidak: a kijelölt grafika túl nagy vagy túl részletes a hidak elhelyezéséhez +@msg String.prototype.toString was called on a value that is not a string a String.prototype.toString hívása olyan értéken történt, amely nem karakterlánc +@msg Switch x/y is for scatter graphs Az x/y felcserélése szóródiagramokhoz való +@msg Text options: {e} Szövegbeállítások: {e} +@msg The {name} profile could not be read, so the new document has the default settings: {reason} Ez a profil nem volt olvasható: {name}; ezért az új dokumentum az alapértelmezett beállításokat kapta: {reason} +@msg Trap: more than {_1} pairs of objects lie close enough to trap, or too many objects share a horizontal range; trap fewer objects at a time Csapdázás: több mint {_1} objektumpár van elég közel a csapdázáshoz, vagy túl sok objektum esik azonos vízszintes tartományba; egyszerre kevesebb objektumot csapdázz +@msg Weed Box and Lines: no weeding line fits outside the art, and the weed box is off Gyomláló keret és vonalak: a grafikán kívül nem fér el gyomlálóvonal, és a gyomláló keret ki van kapcsolva +@msg \\ at end of pattern \\ a minta végén +@msg `alignOn` cannot be empty `alignOn`: nem lehet üres +@msg `alignOn` must be a string `alignOn`: karakterlánc kell +@msg `align` is start, center or end `align`: start, center vagy end +@msg `align` must be a string `align`: karakterlánc kell +@msg `anchors` must be an array of [subpath, anchor] pairs `anchors`: [subpath, anchor] párok tömbje kell +@msg `anchors` must list anchor indices (0, 1, 2…), not {k} `anchors`: horgonypont-indexek listája kell (0, 1, 2…), ez nem az: {k} +@msg `anchors` must list anchor indices (0, 1, 2…), not {v} `anchors`: horgonypont-indexek listája kell (0, 1, 2…), ez nem az: {v} +@msg `answer` for this {kind} dialog must be one of: {_1} `answer`: ennél a párbeszédablaknál ({kind}) ezek egyike kell: {_1} +@msg `answers` has more than {MAX_ANSWERS} answers `answers`: több mint {MAX_ANSWERS} választ tartalmaz +@msg `answers` is larger than 1 MiB `answers`: nagyobb 1 MiB-nál +@msg `answers` must be a list of answers `answers`: válaszok listája kell +@msg `artboard` must be the index of an artboard of the document `artboard`: a dokumentum egyik rajztáblájának indexe kell +@msg `artboardsAt` must be [x, y] `artboardsAt`: [x, y] kell +@msg `artboards` must be a list of artboard indices `artboards`: rajztáblaindexek listája kell +@msg `artboards` names an artboard the document does not have `artboards`: olyan rajztáblát nevez meg, amely nincs a dokumentumban +@msg `artboards` names an artboard twice `artboards`: egy rajztáblát kétszer nevez meg +@msg `asset` is the asset id (see assets.list) `asset`: az elem azonosítója (lásd: assets.list) +@msg `at` must be [x, y] (got {at}) `at`: [x, y] kell (kapott érték: {at}) +@msg `at` must be a byte offset `at`: bájteltolás kell +@msg `at` must be a point [x, y] `at`: [x, y] pont kell +@msg `autoLeading` must be a number `autoLeading`: szám kell +@msg `background` must be "", "matte" or #rrggbb `background`: "", "matte" vagy #rrggbb kell +@msg `beside` needs `side` `beside`: `side` is kell hozzá +@msg `burasagari` must be "none", "standard" or "forced" `burasagari`: "none", "standard" vagy "forced" kell +@msg `center` must be [x, y] `center`: [x, y] kell +@msg `charAlign` must be "romanBaseline", "emBoxTop", "emBoxCenter", "emBoxBottom", "icfTop" or "icfBottom" `charAlign`: "romanBaseline", "emBoxTop", "emBoxCenter", "emBoxBottom", "icfTop" vagy "icfBottom" kell +@msg `charDirection` must be "default", "leftToRight" or "rightToLeft" `charDirection`: "default", "leftToRight" vagy "rightToLeft" kell +@msg `clearStroke` requires `stroke: false`, `ids: []` and no `stop` `clearStroke`: `stroke: false` és `ids: []` kell hozzá, `stop` nélkül +@msg `clear` must be a list of type object ids, not {v} `clear`: szövegobjektum-azonosítók listája kell, ez nem az: {v} +@msg `clear` must list type objects; {_1} is not one `clear`: szövegobjektumok listája kell; ez nem az: {_1} +@msg `clear` must not list `id` `clear`: nem szerepelhet benne az `id` +@msg `code` must be a whole number `code`: egész szám kell +@msg `colorMode` must be one of rgb, cmyk `colorMode`: ezek egyike kell: rgb, cmyk +@msg `color` needs a `rule` to make the theme from `color`: `rule` is kell hozzá, amelyből a téma készül +@msg `colors` does not apply to the {name} reduction `colors`: ennél a színcsökkentésnél nem használható: {name} +@msg `colors` is empty `colors`: üres +@msg `colors` must be a whole number from 2 to 256 `colors`: 2 és 256 közötti egész szám kell +@msg `colors` must be at least 9 for the uniform reduction `colors`: az egyenletes színcsökkentéshez legalább 9 kell +@msg `colors` must be between 1 and {MAX_THEME_COLORS} (got {n}) `colors`: 1 és {MAX_THEME_COLORS} közötti érték kell (kapott érték: {n}) +@msg `columnType` is vertical, uniform, repeating or sliding `columnType`: vertical, uniform, repeating vagy sliding +@msg `columns` must be a whole number 1..50 `columns`: egész szám kell, 1..50 +@msg `commands` must not be empty `commands`: nem lehet üres +@msg `contents` goes with `to` `contents`: a `to` kulccsal együtt használható +@msg `corners` must be sharp, round or square, not `{other}` `corners`: sharp, round vagy square kell, ez nem az: `{other}` +@msg `corners` must list anchor indices (0, 1, 2…), not {v} `corners`: horgonypont-indexek listája kell (0, 1, 2…), ez nem az: {v} +@msg `count` must be a whole number from 0 to {MAX_COUNT} `count`: 0 és {MAX_COUNT} közötti egész szám kell +@msg `count` must be a whole number from 1 to 100 `count`: 1 és 100 közötti egész szám kell +@msg `dataBase64` is larger than the module limit `dataBase64`: nagyobb a modulok méretkorlátjánál +@msg `dataBase64` is not valid base64 `dataBase64`: nem érvényes base64 +@msg `defaultsOnly` cannot be combined with `ids`, `reverse` or `append` `defaultsOnly`: nem használható együtt ezekkel: `ids`, `reverse`, `append` +@msg `depth` and `childLimit` slice the summary: pass `summary: true` `depth` és `childLimit`: az összegzést szűkítik; add meg ezt: `summary: true` +@msg `design` is a design name, or null for plain columns `design`: diagramminta neve, vagy null az egyszerű oszlopokhoz +@msg `design` is a design name, or null for the default marker `design`: diagramminta neve, vagy null az alapértelmezett jelölőhöz +@msg `destinationFolder` is required when destination is `folder` `destinationFolder`: kötelező, ha a cél `folder` +@msg `destination` must be `none`, `saveAndClose` or `folder` `destination`: `none`, `saveAndClose` vagy `folder` kell +@msg `diameter` must be from 0.1 to 2500 pt `diameter`: 0.1 és 2500 pt közötti érték kell +@msg `digits` must be one of {_1} `digits`: ezek egyike kell: {_1} +@msg `dimImages` is a percentage or false `dimImages`: százalék vagy false +@msg `direction` must be "auto", "leftToRight" or "rightToLeft" `direction`: "auto", "leftToRight" vagy "rightToLeft" kell +@msg `ditherAmount` must be a number from 0 to 100 `ditherAmount`: 0 és 100 közötti szám kell +@msg `each` is the value one design stands for, more than 0 `each`: az az érték, amelyet egy minta jelöl; 0-nál nagyobb +@msg `end` must be "start" or "end" `end`: "start" vagy "end" kell +@msg `ends` applies to joining exactly two paths `ends`: pontosan két útvonal összekapcsolásakor használható +@msg `event` must be one of {_1} `event`: ezek egyike kell: {_1} +@msg `every` must be "all", "odd" or "even", not {v} `every`: "all", "odd" vagy "even" kell, ez nem az: {v} +@msg `expand` must be true or false `expand`: true vagy false kell +@msg `fidelity` must be from {lo} to {hi} pt `fidelity`: {lo} és {hi} pt közötti érték kell +@msg `files` must be 1 to 1000 paths of font files the last text.findFontFiles search found `files`: a legutóbbi text.findFontFiles keresés által talált betűtípusfájlok 1–1000 elérési útja kell +@msg `focal` and `radius` cannot be used together `focal` és `radius`: nem használhatók együtt +@msg `focal` must be an array of [subpath, anchor] pairs `focal`: [subpath, anchor] párok tömbje kell +@msg `focal` names [{si}, {ai}], which is not an anchor of the path `focal`: ezt nevezi meg: [{si}, {ai}], de ez nem az útvonal horgonypontja +@msg `folder` must be an absolute folder path `folder`: abszolút mappaútvonal kell +@msg `fontAxes` must be an object of axis tags and values, such as {"wght"} `fontAxes`: tengelycímkék és értékek objektuma kell, például {"wght"} +@msg `format` must be a string `format`: karakterlánc kell +@msg `format` must be one of {_1} `format`: ezek egyike kell: {_1} +@msg `fractions` is chop or scale `fractions`: chop vagy scale +@msg `from` and `to` must differ `from` és `to`: különbözniük kell +@msg `from` has an empty frame `from`: üres a kerete +@msg `from` must be a non-negative integer `from`: nemnegatív egész szám kell +@msg `from` must be area type or type on a path `from`: területszöveg vagy útvonalszöveg kell +@msg `gid` must be a glyph id, not {v} `gid`: glifaazonosító kell, ez nem az: {v} +@msg `glyphAlternate` belongs to one character, not to a character style (text.setGlyphAlternate sets it) `glyphAlternate`: egyetlen karakterhez tartozik, nem karakterstílushoz (a text.setGlyphAlternate állítja be) +@msg `glyphAlternate` takes only null, which takes a glyph choice away (text.setGlyphAlternate makes one) `glyphAlternate`: csak null adható meg, amely megszünteti a glifaválasztást (a text.setGlyphAlternate hoz létre ilyet) +@msg `group` must be one of {_1} `group`: ezek egyike kell: {_1} +@msg `group` must be the Objects on Path group of `member` and `target` `group`: a `member` és a `target` Objektumok útvonalon csoportja kell +@msg `guide` must be a guide index (guide.list) `guide`: segédvonalindex kell (guide.list) +@msg `hAlign` must be default, left, center or right `hAlign`: default, left, center vagy right kell +@msg `id` is an object id, not {v} `id`: objektumazonosító, ez nem az: {v} +@msg `id` must be a node id `id`: csomópont-azonosító kell +@msg `id` must be an object id, not {v} `id`: objektumazonosító kell, ez nem az: {v} +@msg `ids` must name Objects on Path groups or objects in them `ids`: Objektumok útvonalon csoportokat vagy a bennük lévő objektumokat kell megneveznie +@msg `ids` takes at most {MAX_INSPECT_IDS} ids `ids`: legfeljebb {MAX_INSPECT_IDS} azonosítót fogad +@msg `imageMap` must be none, rectangle or polygon `imageMap`: none, rectangle vagy polygon kell +@msg `includeArtboardFill` must be true or false `includeArtboardFill`: true vagy false kell +@msg `includeSubdirs` must be true or false `includeSubdirs`: true vagy false kell +@msg `index` must be a point index `index`: pontindex kell +@msg `index` must be a whole number or null `index`: egész szám vagy null kell +@msg `indices` must be a non-empty array of item indices `indices`: elemindexek nem üres tömbje kell +@msg `item` needs `index` `item`: `index` is kell hozzá +@msg `items` is a list of {kind, item} `items`: {kind, item} elemek listája +@msg `items` is empty `items`: üres +@msg `items` must be a list of {id, points} `items`: {id, points} elemek listája kell +@msg `items` must be a list of {{id, anchors?}}, not {v} `items`: {{id, anchors?}} elemek listája kell, ez nem az: {v} +@msg `items` must be an array of {id, anchors} `items`: {id, anchors} elemek tömbje kell +@msg `items` must be an array of {{id, corners?}}, not {v} `items`: {{id, corners?}} elemek tömbje kell, ez nem az: {v} +@msg `kashida` must be "none", "short", "medium", "long" or "stylistic" `kashida`: "none", "short", "medium", "long" vagy "stylistic" kell +@msg `kerningBefore` belongs to a line's first character, not to a character style (text.setRangeStyle sets it) `kerningBefore`: a sor első karakteréhez tartozik, nem karakterstílushoz (a text.setRangeStyle állítja be) +@msg `kind` is one of {_1} `kind`: ezek egyike: {_1} +@msg `kind` must be "round", "invertedRound" or "chamfer", not {v} `kind`: "round", "invertedRound" vagy "chamfer" kell, ez nem az: {v} +@msg `kind` must be `text`, `visibility`, `image` or `graph` `kind`: `text`, `visibility`, `image` vagy `graph` kell +@msg `kind` must be a string `kind`: karakterlánc kell +@msg `kind` must be image, noImage or htmlText `kind`: image, noImage vagy htmlText kell +@msg `kinsokuType` must be "pushInFirst", "pushOutFirst" or "pushOutOnly" `kinsokuType`: "pushInFirst", "pushOutFirst" vagy "pushOutOnly" kell +@msg `kinsoku` must be "none", "hard" or "soft" `kinsoku`: "none", "hard" vagy "soft" kell +@msg `label` must be a non-empty name of at most 200 characters `label`: nem üres, legfeljebb 200 karakteres név kell +@msg `language` must be a language name or tag, such as "Turkish" or "tr" `language`: nyelvnév vagy nyelvcímke kell, például "Turkish" vagy "tr" +@msg `leader` must be a string `leader`: karakterlánc kell +@msg `leadingModel` must be "romanBaseline" or "emBoxTop" `leadingModel`: "romanBaseline" vagy "emBoxTop" kell +@msg `leading` must be from 0.1 to 5000, or null for Auto `leading`: 0.1 és 5000 közötti érték kell, vagy null az automatikushoz +@msg `length` must be a number of at most 1000000 pt either way `length`: szám kell, bármelyik irányban legfeljebb 1000000 pt +@msg `line` must be true or false `line`: true vagy false kell +@msg `max` must be 1 to {MAX_SUGGESTIONS} `max`: 1 és {MAX_SUGGESTIONS} közötti érték kell +@msg `minAngle` ({min_angle}°) can't be more than `maxAngle` ({max_angle}°) `minAngle` ({min_angle}°): nem lehet nagyobb ennél: `maxAngle` ({max_angle}°) +@msg `mode` must be "handles", "straight" or "smooth" `mode`: "handles", "straight" vagy "smooth" kell +@msg `mode` must be "straight", "bezier" or "arc" `mode`: "straight", "bezier" vagy "arc" kell +@msg `mode` must be one of {_1} `mode`: ezek egyike kell: {_1} +@msg `mojikumi` must be "none", "yakumonoHankaku", "gyomatsuYakumonoHankaku", "gyomatsuYakumonoZenkaku", "yakumonoZenkaku" or "lineEndHalf" `mojikumi`: "none", "yakumonoHankaku", "gyomatsuYakumonoHankaku", "gyomatsuYakumonoZenkaku", "yakumonoZenkaku" vagy "lineEndHalf" kell +@msg `name` must be a name that is not empty `name`: nem üres név kell +@msg `name` must not be empty `name`: nem lehet üres +@msg `names` is a list of preset names `names`: előbeállítás-nevek listája +@msg `names` lists preset names `names`: előbeállítás-neveket sorol fel +@msg `names` must be a list of names `names`: nevek listája kell +@msg `names` must be a list of swatch names `names`: színmintanevek listája kell +@msg `names` must be an array of style names `names`: stílusnevek tömbje kell +@msg `new` is a design name, or true `new`: diagramminta neve vagy true +@msg `origin` must be [x, y] in points `origin`: [x, y] kell pontban megadva +@msg `path` must be a folder `path`: mappa kell +@msg `path` must be a path object `path`: útvonalobjektum kell +@msg `picks` must be an array (got {v}) `picks`: tömb kell (kapott érték: {v}) +@msg `picks` must hold 1 to {MAX_PICKS} picks (got {_1}) `picks`: 1 és {MAX_PICKS} közötti számú választást kell tartalmaznia (kapott érték: {_1}) +@msg `pivot` must be a whole number from 0 to 8 `pivot`: 0 és 8 közötti egész szám kell +@msg `points` must be a list of [x, y] points `points`: [x, y] pontok listája kell +@msg `points` must be a list of point indexes `points`: pontindexek listája kell +@msg `points` must be an array of point indices `points`: pontindexek tömbje kell +@msg `points` must be point indexes `points`: pontindexek kellenek +@msg `points` must hold from 2 to 100000 points `points`: 2 és 100000 közötti számú pontot kell tartalmaznia +@msg `port` must be "in" or "out" `port`: "in" vagy "out" kell +@msg `position` is above or below `position`: above vagy below +@msg `preset` must be a string `preset`: karakterlánc kell +@msg `radius` must be 0 or more `radius`: 0 vagy nagyobb érték kell +@msg `ratio` must be from 0.1 to 0.5 `ratio`: 0.1 és 0.5 közötti érték kell +@msg `rect` must be [x, y, width, height] `rect`: [x, y, width, height] kell +@msg `rect` must be [x, y, width, height] with a positive size `rect`: [x, y, width, height] kell pozitív mérettel +@msg `rect` must be [x0, y0, x1, y1] (got {r}) `rect`: [x0, y0, x1, y1] kell (kapott érték: {r}) +@msg `relation` must be overlap, inside or outside `relation`: overlap, inside vagy outside kell +@msg `replace` must be a string `replace`: karakterlánc kell +@msg `reversed` must be true or false `reversed`: true vagy false kell +@msg `rotate` must be a finite number `rotate`: véges szám kell +@msg `rows` must be lists of numbers or nulls, not {r} `rows`: számok vagy null értékek listái kellenek, ez nem az: {r} +@msg `rule` must be nonZero or evenOdd `rule`: nonZero vagy evenOdd kell +@msg `scale` must be a number from 0.001 to 1000 `scale`: 0.001 és 1000 közötti szám kell +@msg `scale` must be a number in (0, 100] `scale`: a (0, 100] tartományba eső szám kell +@msg `scope.{key}` must be a non-empty array `scope.{key}`: nem üres tömb kell +@msg `scope` must be "document", {artboards} or {layers} `scope`: "document", {artboards} vagy {layers} kell +@msg `scope` must be "selection" or "document", not {other} `scope`: "selection" vagy "document" kell, ez nem az: {other} +@msg `script` must be a string `script`: karakterlánc kell +@msg `seriesIndexes` is a non-empty list of series indexes `seriesIndexes`: adatsorindexek nem üres listája +@msg `seriesIndexes` needs a `type` or a `valueAxis` `seriesIndexes`: `type` vagy `valueAxis` is kell hozzá +@msg `shift` must be a number of points `shift`: pontban megadott szám kell +@msg `showCenter` must be true or false `showCenter`: true vagy false kell +@msg `side` must be "left", "right", "top" or "bottom" `side`: "left", "right", "top" vagy "bottom" kell +@msg `side` places the artboard: leave out x, y, width and height `side`: ez helyezi el a rajztáblát; hagyd el az x, y, width és height értéket +@msg `singleWordJustification` must be "fullJustify", "alignLeft", "alignCenter" or "alignRight" `singleWordJustification`: "fullJustify", "alignLeft", "alignCenter" vagy "alignRight" kell +@msg `size` is a percentage of the base text's size, 1 to 100 `size`: az alapszöveg méretének százaléka, 1 és 100 között +@msg `source` and `target` are the same object `source` és `target`: ugyanaz az objektum +@msg `source` is the only path in series group `target` `source`: az egyetlen útvonal ebben a sorozatcsoportban: `target` +@msg `source` must be `folder` or `datasets` `source`: `folder` vagy `datasets` kell +@msg `spacing` makes more than {MAX_COUNT} lines across the box `spacing`: ezzel több mint {MAX_COUNT} vonal jutna a keretre +@msg `spacing` must be a number `spacing`: szám kell +@msg `spacing` must be a number of points, 0 or more, or "auto" `spacing`: pontban megadott, 0 vagy nagyobb szám, vagy "auto" kell +@msg `spacing` must be more than 0 and at most {MAX_DISTANCE} pt `spacing`: 0-nál nagyobb és legfeljebb {MAX_DISTANCE} pt érték kell +@msg `start` must be a finite number `start`: véges szám kell +@msg `starts` must be an array of anchor indices (or nulls) `starts`: horgonypont-indexek (vagy null értékek) tömbje kell +@msg `status` must be linked, embedded, missing or modified, or a list of them `status`: linked, embedded, missing vagy modified kell, vagy ezek listája +@msg `stop` must be a stop index `stop`: színátmenetpont-index kell +@msg `story` styles the whole story: give no `start` or `end` `story`: a teljes szövegfolyamot formázza; ne adj meg `start` vagy `end` értéket +@msg `story` takes the whole story: give no `start` or `end` `story`: a teljes szövegfolyamra vonatkozik; ne adj meg `start` vagy `end` értéket +@msg `strokeMode` applies to strokes (stroke: true) `strokeMode`: körvonalakra vonatkozik (stroke: true) +@msg `style` must be roman or japanese `style`: roman vagy japanese kell +@msg `subpaths` must be two integer indices `subpaths`: két egész indexet kell megadni +@msg `symbol` must be a symbol name `symbol`: szimbólumnév kell +@msg `target` must be "object" or "contents", not {v} `target`: "object" vagy "contents" kell, ez nem az: {v} +@msg `target` must be an object of the same Objects on Path group as `member` `target`: ugyanannak az Objektumok útvonalon csoportnak egy objektuma kell, mint a `member` +@msg `tint` applies to global and spot colours `tint`: globális színekre és direktszínekre vonatkozik +@msg `tint` goes with a global or spot `swatch` `tint`: globális vagy direktszínű `swatch` értékkel együtt használható +@msg `tint` must be a number (%) `tint`: szám kell (%) +@msg `tint` needs a global or spot colour `tint`: globális szín vagy direktszín kell hozzá +@msg `to` is already threaded `to`: már láncolva van +@msg `to` is the design's new name `to`: a diagramminta új neve +@msg `to` must be [x, y] `to`: [x, y] kell +@msg `to` must be a closed path, area type or type on a path other than `from` `to`: zárt útvonal, területszöveg vagy útvonalszöveg kell, amely nem azonos ezzel: `from` +@msg `to` must be a whole number `to`: egész szám kell +@msg `to` takes the rows of one object's stack, not aligned rows `to`: egyetlen objektum halmának sorait fogadja, nem igazított sorokat +@msg `tolerance` must be from 0 to 100 pt `tolerance`: 0 és 100 pt közötti érték kell +@msg `useLab` must be true or false `useLab`: true vagy false kell +@msg `vAlign` must be default, top, middle, baseline or bottom `vAlign`: default, top, middle, baseline vagy bottom kell +@msg `values` must be a list `values`: lista kell +@msg `values` must be an object `values`: objektum kell +@msg `values` must name hex, rgb, cmyk, lab or gray `values`: ezek közül kell megneveznie: hex, rgb, cmyk, lab vagy gray +@msg `values` names a kind twice `values`: egy fajtát kétszer nevez meg +@msg `version` must be 0 or {_1} `version`: 0 vagy {_1} kell +@msg `version` must be 0 or {newest} `version`: 0 vagy {newest} kell +@msg `warichuAlign` must be one of {_1} `warichuAlign`: ezek egyike kell: {_1} +@msg `warichuLines` must be a whole number from {_1} to {_2} `warichuLines`: {_1} és {_2} közötti egész szám kell +@msg `weight` must be from 0.01 to 1000 pt `weight`: 0.01 és 1000 pt közötti érték kell +@msg `weights` must be a list of {_1} numbers, one per row (got {v}) `weights`: {_1} számból álló lista kell, soronként egy (kapott érték: {v}) +@msg `xml` must be a string `xml`: karakterlánc kell +@msg `{KEY}` entry {n} gives the paragraph at byte {start} of {_1} other indents than an entry before it `{KEY}`, {n}. bejegyzés: más behúzásokat ad a(z) {_1} objektum {start}. bájtjánál kezdődő bekezdésnek, mint egy korábbi bejegyzés +@msg `{KEY}` entry {n} must be an object `{KEY}`, {n}. bejegyzés: objektum kell +@msg `{KEY}` entry {n} sets neither `leftIndent` nor `firstLineIndent` `{KEY}`, {n}. bejegyzés: sem a `leftIndent`, sem a `firstLineIndent` értéket nem állítja be +@msg `{KEY}` entry {n}: `id` must be an object id `{KEY}`, {n}. bejegyzés: `id`: objektumazonosító kell +@msg `{KEY}` entry {n}: `start` must be a byte offset `{KEY}`, {n}. bejegyzés: `start`: bájteltolás kell +@msg `{KEY}` entry {n}: `{k}` must be a number from -{MAX_PARA} to {MAX_PARA} pt `{KEY}`, {n}. bejegyzés: `{k}`: -{MAX_PARA} és {MAX_PARA} pt közötti szám kell +@msg `{KEY}` entry {n}: no paragraph of {_1} starts at byte {start} `{KEY}`, {n}. bejegyzés: a(z) {_1} objektumnak nincs a(z) {start}. bájtnál kezdődő bekezdése +@msg `{KEY}` entry {n}: unknown key `{k}` `{KEY}`, {n}. bejegyzés: ismeretlen kulcs: `{k}` +@msg `{KEY}` entry {n}: {_1} is not a type object `{KEY}`, {n}. bejegyzés: nem szövegobjektum: {_1} +@msg `{KEY}` is empty `{KEY}`: üres +@msg `{KEY}` must be a list `{KEY}`: lista kell +@msg `{KEY}` takes at most {MAX_PARAGRAPH_INDENTS} entries (got {_1}) `{KEY}`: legfeljebb {MAX_PARAGRAPH_INDENTS} bejegyzést fogad (kapott érték: {_1}) +@msg `{KEY}` takes no `{other}` beside it `{KEY}`: mellette nem adható meg ez: `{other}` +@msg `{_1}` can't be edited or removed nem szerkeszthető és nem távolítható el: `{_1}` +@msg `{_1}` is built in and always listed beépített elem, mindig szerepel a listán: `{_1}` +@msg `{_1}` is not a font file the last text.findFontFiles search found nem a legutóbbi text.findFontFiles keresés által talált betűtípusfájl: `{_1}` +@msg `{_1}` would be overwritten by the package: choose a different folder or name a csomag felülírná ezt: `{_1}`; válassz másik mappát vagy nevet +@msg `{base}` is larger than {_1} MB nagyobb, mint {_1} MB: `{base}` +@msg `{base}` is not in the DCS file's folder nincs a DCS-fájl mappájában: `{base}` +@msg `{file}` has no art to place nincs benne elhelyezhető grafika: `{file}` +@msg `{file}` is over {_1} MB nagyobb, mint {_1} MB: `{file}` +@msg `{f}` belongs to a VectorCraft that is running egy futó VectorCrafthoz tartozik: `{f}` +@msg `{f}` is the copy of a document open now egy most megnyitott dokumentum másolata: `{f}` +@msg `{id}` is no writable format (see document.formats) nem írható formátum: `{id}` (lásd: document.formats) +@msg `{id}` isn't a loaded library nem betöltött könyvtár: `{id}` +@msg `{key}` has no colours `{key}`: nincsenek benne színek +@msg `{key}` holds more than {MAX_EDIT_WORDS} words `{key}`: több mint {MAX_EDIT_WORDS} szót tartalmaz +@msg `{key}` is a design name `{key}`: diagramminta neve +@msg `{key}` is a design name or a list of them `{key}`: diagramminta neve vagy ilyen nevek listája +@msg `{key}` is longer than {MAX_NAME} characters `{key}`: hosszabb {MAX_NAME} karakternél +@msg `{key}` is out of range `{key}`: tartományon kívül esik +@msg `{key}` must be 0 or more `{key}`: 0 vagy nagyobb érték kell +@msg `{key}` must be [min, desired, max] or {{min?, desired?, max?}}, in percent `{key}`: [min, desired, max] vagy {{min?, desired?, max?}} kell, százalékban +@msg `{key}` must be [x, y] numbers `{key}`: [x, y] számpár kell +@msg `{key}` must be a list of words `{key}`: szavak listája kell +@msg `{key}` must be a list, not {v} `{key}`: lista kell, ez nem az: {v} +@msg `{key}` must be a non-negative integer `{key}`: nemnegatív egész szám kell +@msg `{key}` must be a number or null, not {v} `{key}`: szám vagy null kell, ez nem az: {v} +@msg `{key}` must be a number {_1}..{_2} `{key}`: szám kell, {_1}..{_2} +@msg `{key}` must be a whole number of 0 or more `{key}`: 0 vagy nagyobb egész szám kell +@msg `{key}` must be a whole number of at least 0, not {n} `{key}`: legalább 0 értékű egész szám kell, ez nem az: {n} +@msg `{key}` must be an appearance item index (paint order) or null `{key}`: megjelenési elem indexe (festési sorrend) vagy null kell +@msg `{key}` must be an array of asset ids (see assets.list) `{key}`: elemazonosítók tömbje kell (lásd: assets.list) +@msg `{key}` must be from 0 to 180 degrees, not {a} `{key}`: 0 és 180 fok közötti érték kell, ez nem az: {a} +@msg `{key}` must be from 0 to {MAX_DISTANCE} pt `{key}`: 0 és {MAX_DISTANCE} pt közötti érték kell +@msg `{key}` must be from {_1} to {shift_max} `{key}`: {_1} és {shift_max} közötti érték kell +@msg `{key}` must be from {lo} to {hi}, not {v} `{key}`: {lo} és {hi} közötti érték kell, ez nem az: {v} +@msg `{key}` must be one of auto, always, never `{key}`: ezek egyike kell: auto, always, never +@msg `{key}` must be one of miter, round, bevel `{key}`: ezek egyike kell: miter, round, bevel +@msg `{key}` must be one word of at most {_1} characters `{key}`: egyetlen, legfeljebb {_1} karakteres szó kell +@msg `{key}` must hold single words of at most {_1} characters `{key}`: különálló, legfeljebb {_1} karakteres szavakat kell tartalmaznia +@msg `{key}` must name an object attached to the path of an Objects on Path group `{key}`: egy Objektumok útvonalon csoport útvonalához csatolt objektumot kell megneveznie +@msg `{key}` names an object that is hidden or locked `{key}`: rejtett vagy zárolt objektumot nevez meg +@msg `{key}`: not a colour: {v} `{key}`: nem szín: {v} +@msg `{k}.family` is required `{k}.family`: kötelező +@msg `{k}` is a number 0..1 `{k}`: szám, 0..1 +@msg `{k}` is true or false `{k}`: true vagy false +@msg `{k}` isn't an export setting: {_1} `{k}`: nem exportálási beállítás: {_1} +@msg `{k}` must be a byte offset `{k}`: bájteltolás kell +@msg `{k}` must be a number `{k}`: szám kell +@msg `{k}` must be a number of points `{k}`: pontban megadott szám kell +@msg `{k}` must be a string `{k}`: karakterlánc kell +@msg `{k}` must be a whole number `{k}`: egész szám kell +@msg `{k}` must be from {lo} to {hi} for {key} `{k}`: {lo} és {hi} közötti érték kell ehhez: {key} +@msg `{k}` must be {what}, not {v} `{k}`: ez kell: {what}; ez nem az: {v} +@msg `{l}` isn't a global or spot colour nem globális szín és nem direktszín: `{l}` +@msg `{m}` isn't a bitmap: use clipboard.importSvg, importPdf or importText nem bitkép: `{m}`; használd a clipboard.importSvg, az importPdf vagy az importText parancsot +@msg `{name}` can't be deleted nem törölhető: `{name}` +@msg `{name}` can't be duplicated nem kettőzhető: `{name}` +@msg `{name}` can't be edited nem szerkeszthető: `{name}` +@msg `{name}` can't be edited this way így nem szerkeszthető: `{name}` +@msg `{name}` can't be renamed nem nevezhető át: `{name}` +@msg `{name}` can't name a folder nem nevezhet meg mappát: `{name}` +@msg `{name}` has no art to place nincs benne elhelyezhető grafika: `{name}` +@msg `{name}` has no text to place nincs benne elhelyezhető szöveg: `{name}` +@msg `{name}` in the Word document is not UTF-8 or UTF-16 text a Word-dokumentumban lévő `{name}` nem UTF-8 vagy UTF-16 szöveg +@msg `{name}` in the Word document is not well-formed XML: {e} a Word-dokumentumban lévő `{name}` nem jól formált XML: {e} +@msg `{name}` in the Word document nests elements more than {MAX_NESTING} deep a Word-dokumentumban lévő `{name}` elemei {MAX_NESTING} szintnél mélyebben vannak egymásba ágyazva +@msg `{name}` is a built-in preset and is read-only: save it under another name `{name}` beépített előbeállítás, csak olvasható: mentsd más néven +@msg `{name}` is a built-in preset: save under another name `{name}` beépített előbeállítás: mentsd más néven +@msg `{name}` is a built-in profile and stays `{name}` beépített profil, megmarad +@msg `{name}` is a file of its own, which can only be found next to the DCS file's path `{name}` külön fájl, amely csak a DCS-fájl elérési útja mellett található meg +@msg `{name}` is a tint of `{base}`: edit `{base}` (a tint swatch only takes a new name) `{name}` ennek a tónusa: `{base}`; ezt szerkeszd: `{base}` (egy tónusszínminta csak új nevet kaphat) +@msg `{name}` is a working space: choose another with edit.colorSettings first `{name}` munkaszíntér: előbb válassz másikat az edit.colorSettings paranccsal +@msg `{name}` is built in and stays `{name}` beépített elem, megmarad +@msg `{name}` takes a paint of its own kind (colour, gradient or pattern) `{name}` csak a saját fajtájának megfelelő festést fogad (szín, színátmenet vagy mintázat) +@msg `{name}`: {_1}: {e} `{name}`: {_1}: {e} +@msg `{n}` can't be deleted nem törölhető: `{n}` +@msg `{n}` can't be merged nem egyesíthető: `{n}` +@msg `{n}` can't be moved nem helyezhető át: `{n}` +@msg `{n}` is not a colour swatch nem színes színminta: `{n}` +@msg `{n}` isn't a solid colour nem egyszínű szín: `{n}` +@msg `{n}`: colour groups hold solid colours only `{n}`: a színcsoportok csak egyszínű színeket tartalmazhatnak +@msg `{other}` doesn't trace an image nem vektorizál képet: `{other}` +@msg `{s}`: the step's references copy in more than {_1} MB of values `{s}`: a lépés hivatkozásai több mint {_1} MB értéket másolnak be +@msg `{tag}` is not an axis tag: a tag is four characters, such as "wght" nem tengelycímke: `{tag}`; a címke négy karakterből áll, például "wght" +@msg `{to}` is empty or already used üres vagy már használatban van: `{to}` +@msg `{u}` is no Unicode character nem Unicode-karakter: `{u}` +@msg `{what}` is longer than {MAX_TEXT} bytes `{what}`: hosszabb {MAX_TEXT} bájtnál +@msg `{what}` must be text `{what}`: szöveg kell +@msg `{word}` isn't in the custom dictionary nincs az egyéni szótárban: `{word}` +@msg a CMap has too many mappings egy CMap túl sok leképezést tartalmaz +@msg a DXF drawing has one origin: pass useArtboards: true for one drawing per artboard egy DXF-rajznak egy origója van: add meg a useArtboards: true értéket, ha rajztáblánként egy rajz kell +@msg a PDF presets file with over {_1} presets olyan PDF-előbeállításfájl, amelyben több mint {_1} előbeállítás van +@msg a \\u escape needs four hexadecimal digits a \\u escape-sorozathoz négy hexadecimális számjegy kell +@msg a batch preview cannot switch documents a kötegelt előnézet nem válthat dokumentumot +@msg a brush named `{nn}` exists már van ilyen nevű ecset: `{nn}` +@msg a comma in an XPath expression must separate function arguments XPath-kifejezésben a vessző csak függvényargumentumokat választhat el +@msg a container of the listed objects is gone a felsorolt objektumok egyik tárolója már nincs meg +@msg a content stream can't be read egy tartalomfolyam nem olvasható +@msg a content stream isn't a stream egy tartalomfolyam nem adatfolyam +@msg a design holds at most {_1} objects egy diagramminta legfeljebb {_1} objektumot tartalmazhat +@msg a design needs a name a diagrammintának név kell +@msg a dictionary grew too large egy szótár túl nagyra nőtt +@msg a document holds at most {_1} SVG filters egy dokumentum legfeljebb {_1} SVG-szűrőt tartalmazhat +@msg a document keeps at most {_1} graph designs egy dokumentum legfeljebb {_1} diagrammintát tárol +@msg a document keeps at most {_1} saved selections egy dokumentum legfeljebb {_1} mentett kijelölést tárol +@msg a document keeps at most {_1} views egy dokumentum legfeljebb {_1} nézetet tárol +@msg a document links at most {MAX_SVG_SCRIPTS} JavaScript files egy dokumentum legfeljebb {MAX_SVG_SCRIPTS} JavaScript-fájlt csatolhat +@msg a document with unsaved changes has no recovery copy a mentetlen módosításokat tartalmazó dokumentumnak nincs helyreállítási másolata +@msg a feConvolveMatrix filter's order is {x}×{y}, which overflows the kernel-size multiply usvg makes egy feConvolveMatrix szűrő rendje {x}×{y}, ami túlcsordítja az usvg kernelméret-szorzását +@msg a font's data is too large egy betűtípus adatai túl nagyok +@msg a font's subroutines are too large egy betűtípus szubrutinjai túl nagyok +@msg a function declaration without a name név nélküli függvénydeklaráció +@msg a gradient preset is already called {n} már van ilyen nevű színátmenet-előbeállítás: {n} +@msg a graph has at most {_1} series, so it transposes with at most that many categories egy diagramnak legfeljebb {_1} adatsora lehet, ezért legfeljebb ennyi kategóriával cserélhető fel a sor és az oszlop +@msg a host value has too many entries egy gazdaérték túl sok elemet tartalmaz +@msg a host value is nested too deep egy gazdaérték túl mélyen van egymásba ágyazva +@msg a layer can't be merged into its own sublayer egy réteg nem egyesíthető a saját alrétegébe +@msg a layer's form box isn't an array egy réteg formaobjektumának kerete nem tömb +@msg a layer's form can't be read egy réteg formaobjektuma nem olvasható +@msg a layer's form has no box egy réteg formaobjektumának nincs kerete +@msg a layer's form has no dictionary egy réteg formaobjektumának nincs szótára +@msg a legend draws at most {MAX_CHIPS} swatches a jelmagyarázat legfeljebb {MAX_CHIPS} színmintát rajzol ki +@msg a name names one asset: give multiple: false, or one object egy név egy elemet nevez meg: adj meg multiple: false értéket, vagy egyetlen objektumot +@msg a namespace declaration uses a reserved prefix or URI egy névtér-deklaráció foglalt előtagot vagy URI-t használ +@msg a namespace qualifier is undefined egy névtérminősítő nincs definiálva +@msg a namespace with an empty URI cannot have a prefix üres URI-jú névtérnek nem lehet előtagja +@msg a number has no digits egy számban nincsenek számjegyek +@msg a number's exponent has no digits egy szám kitevőjében nincsenek számjegyek +@msg a number's fraction has no digits egy szám törtrészében nincsenek számjegyek +@msg a page can't be read egy oldal nem olvasható +@msg a page object is used by something else egy oldalobjektumot valami más is használ +@msg a page thumbnail must be RGB pixels, 1 to {THUMBNAIL_SIZE} a side (got {w} × {h}) az oldalbélyegkép RGB-képpontokból álljon, oldalanként 1 és {THUMBNAIL_SIZE} között (kapott méret: {w} × {h}) +@msg a pattern layer doesn't end what it starts egy mintázatréteg nem zárja le, amit megkezd +@msg a pattern layer's colors hold something else egy mintázatréteg színei mást tartalmaznak +@msg a pattern named `{n}` exists már van ilyen nevű mintázat: `{n}` +@msg a plug-in with id {_1} is already installed már telepítve van ilyen azonosítójú bővítmény: {_1} +@msg a preset named `{n}` exists már van ilyen nevű előbeállítás: `{n}` +@msg a print presets file with over {_1} presets olyan nyomtatási előbeállításfájl, amelyben több mint {_1} előbeállítás van +@msg a profile is already called {n} már van ilyen nevű profil: {n} +@msg a property descriptor cannot have both a value or writable and a get or set egy tulajdonságleíróban nem lehet egyszerre value vagy writable és get vagy set +@msg a property descriptor must be an object a tulajdonságleíró objektum kell legyen +@msg a property's {name} must be a function or undefined egy tulajdonság {name} értéke függvény vagy undefined lehet +@msg a row can't go into itself egy sor nem kerülhet önmagába +@msg a series goes on the left or the right value axis egy adatsor a bal vagy a jobb értéktengelyre kerül +@msg a start must be an anchor index ≥ 0 or null a kezdőpont ≥ 0 horgonypontindex vagy null lehet +@msg a stream in it would decode to more than 256 MB, or its decode parameters can't be applied egy benne lévő adatfolyam kibontva 256 MB-nál nagyobb lenne, vagy a dekódolási paraméterei nem alkalmazhatók +@msg a string holds a control character egy karakterlánc vezérlőkaraktert tartalmaz +@msg a string holds an escape sequence JSON does not have egy karakterlánc olyan escape-sorozatot tartalmaz, amely a JSON-ban nem létezik +@msg a string is not closed egy karakterlánc nincs lezárva +@msg a style named `{name}` already exists már van ilyen nevű stílus: `{name}` +@msg a style named `{to}` already exists már van ilyen nevű stílus: `{to}` +@msg a swatch needs a colour, gradient or pattern a színmintához szín, színátmenet vagy mintázat kell +@msg a symbol named `{n}` already exists már van ilyen nevű szimbólum: `{n}` +@msg a theme has 1 to {THEME_SIZE} colours egy témában 1–{THEME_SIZE} szín lehet +@msg a theme is already called {name} (replace: "{name}" overwrites it) már van ilyen nevű téma: {name} (a replace: "{name}" felülírja) +@msg a toolbar name has at most {MAX_NAME} characters az eszköztár neve legfeljebb {MAX_NAME} karakter lehet +@msg a view named `{_1}` exists már van ilyen nevű nézet: `{_1}` +@msg a view named `{name}` exists már van ilyen nevű nézet: `{name}` +@msg a workspace keeps at most {MAX} toolbars egy munkaterület legfeljebb {MAX} eszköztárat tárol +@msg a {_1} series can't go in a {_2} graph {_1} típusú adatsor nem kerülhet {_2} típusú diagramba +@msg aiVersion {v}: "pdf" (PDF-compatible, the default) or "7" (legacy .ai, version 7) aiVersion {v}: "pdf" (PDF-kompatibilis, ez az alapértelmezés) vagy "7" (régi .ai, 7-es verzió) +@msg already editing an opacity mask már folyik egy átlátszósági maszk szerkesztése +@msg already editing another object's opacity mask már folyik egy másik objektum átlátszósági maszkjának szerkesztése +@msg already in pattern editing mode már mintázatszerkesztési módban vagy +@msg an SVG filter is named by its id: give `xml` with `name` az SVG-szűrőt az azonosítója nevezi meg: a `name` mellé add meg az `xml` értéket +@msg an XML element has two attributes with the same name egy XML-elemnek két azonos nevű attribútuma van +@msg an XML value cannot be inserted into itself or its descendants egy XML-érték nem szúrható be önmagába vagy a leszármazottaiba +@msg an XML value's children cannot be assigned by position egy XML-érték gyermekei nem adhatók meg pozíció szerint +@msg an XML value's children cannot be deleted by position egy XML-érték gyermekei nem törölhetők pozíció szerint +@msg an XMLList converts to XML only when it has one item egy XMLList csak akkor alakítható XML-lé, ha egy eleme van +@msg an XPath node test is missing hiányzik egy XPath-csomópontteszt +@msg an XPath operand is missing hiányzik egy XPath-operandus +@msg an XPath operator is missing hiányzik egy XPath-operátor +@msg an XPath predicate or step cannot follow here itt nem következhet XPath-predikátum vagy -lépés +@msg an XPath predicate or step follows a value that is not a node-set egy XPath-predikátum vagy -lépés olyan érték után áll, amely nem csomóponthalmaz +@msg an XPath step is missing hiányzik egy XPath-lépés +@msg an artboard is listed twice egy rajztábla kétszer szerepel +@msg an empty artboard has no width or height to scale to üres rajztáblának nincs szélessége vagy magassága, amelyhez méretezni lehetne +@msg an image couldn't be decoded and is missing from the picture egy képet nem sikerült dekódolni, ezért hiányzik az ábráról +@msg an image is too large for DXF and was left out egy kép túl nagy a DXF-hez, ezért kimaradt +@msg an image of {_1} MB, at most {_2} MB a kép {_1} MB, legfeljebb {_2} MB lehet +@msg an image of {declared_w} × {declared_h} pixels is too large to draw egy {declared_w} × {declared_h} képpontos kép túl nagy a kirajzoláshoz +@msg an image of {width} × {height} pixels is too large to draw egy {width} × {height} képpontos kép túl nagy a kirajzoláshoz +@msg an image of {w} × {h} pixels is too large to convert (at most {_1} pixels) egy {w} × {h} képpontos kép túl nagy az átalakításhoz (legfeljebb {_1} képpont) +@msg an index must be a whole number az index egész szám kell legyen +@msg an inline graphic has no glyphs egy szövegközi grafikának nincsenek glifái +@msg an invisible text form can't be read egy láthatatlan szöveg formaobjektuma nem olvasható +@msg an object is missing hiányzik egy objektum +@msg an object's header is missing hiányzik egy objektum fejléce +@msg an overprinting form can't be read egy felülnyomó formaobjektum nem olvasható +@msg an unread object has no readable bounds egy be nem olvasott objektumnak nincsenek olvasható határai +@msg an unread object holds a frame of threaded type egy be nem olvasott objektum láncolt szöveg keretét tartalmazza +@msg an unread object is missing from its layer egy be nem olvasott objektum hiányzik a rétegéből +@msg anchor `smooth` must be true or false horgonypont, `smooth`: true vagy false kell +@msg anchor `{key}` must be [x, y] horgonypont, `{key}`: [x, y] kell +@msg anchor `{key}` must be a number horgonypont, `{key}`: szám kell +@msg angle and roundness must be finite angle és roundness: véges érték kell +@msg angles must be a list as long as pins (degrees or null) angles: a pins listával azonos hosszúságú lista kell (fok vagy null) +@msg appearance must be flat|center|edge appearance: flat|center|edge kell +@msg apply is "fill" or "stroke", not `{other}` apply: "fill" vagy "stroke", ez nem az: `{other}` +@msg apply was called on a value that is not a function az apply hívása olyan értéken történt, amely nem függvény +@msg area must be a closed polygon of 3 to 100000 [x, y] points area: 3 és 100000 közötti számú [x, y] pontból álló zárt sokszög kell +@msg area type in a thread cannot use Dynamic Text: {frames} a láncolt szövegben lévő területszöveg nem használhat dinamikus szöveget: {frames} +@msg area type needs a path that encloses an area a területszöveghez területet körülzáró útvonal kell +@msg area type {_1} is named twice a területszöveg kétszer szerepel: {_1} +@msg array literal too long a tömbliterál túl hosszú +@msg arrowAlign must be extend|tip, got {o} arrowAlign: extend|tip kell, kapott érték: {o} +@msg arrowScale must be [start, end] arrowScale: [start, end] kell +@msg artboard is a 0-based index artboard: 0-tól kezdődő index +@msg artboard must be a 0-based index artboard: 0-tól kezdődő index kell +@msg artboard {i} doesn't print ez a rajztábla nem kerül nyomtatásra: {i} +@msg artboardLayout must be {layout?, columns?, spacing?, rightToLeft?} artboardLayout: {layout?, columns?, spacing?, rightToLeft?} kell +@msg artboardLayout.columns must be 1 or more artboardLayout.columns: 1 vagy nagyobb érték kell +@msg artboardLayout.layout must be gridByRow, gridByColumn, row or column artboardLayout.layout: gridByRow, gridByColumn, row vagy column kell +@msg artboardLayout.rightToLeft must be true or false artboardLayout.rightToLeft: true vagy false kell +@msg artboardLayout.spacing must be 0–{MAX_SPACING} pt artboardLayout.spacing: 0–{MAX_SPACING} pt kell +@msg artboards must be a non-empty list artboards: nem üres lista kell +@msg artboards must be a number artboards: szám kell +@msg asset `{_1}` has no art to export ebben az elemben nincs exportálható grafika: `{_1}` +@msg assignment to a constant binding értékadás konstans kötésnek +@msg at least one row that isn't excluded needs a weight above 0 legalább egy ki nem zárt sornak 0-nál nagyobb súly kell +@msg at most {MAX_KEYWORDS} keywords legfeljebb {MAX_KEYWORDS} kulcsszó +@msg at most {MAX_MATCHES} matches are kept legfeljebb {MAX_MATCHES} találat marad meg +@msg at most {MAX_POINTS} points legfeljebb {MAX_POINTS} pont +@msg at most {MAX_QUEUE} files legfeljebb {MAX_QUEUE} fájl +@msg at must be [x, y] at: [x, y] kell +@msg at/rect lie outside the canvas at/rect: a vásznon kívül esik +@msg attribute must be size|leading|tracking|kerning|baselineShift attribute: size|leading|tracking|kerning|baselineShift kell +@msg attrs must be an object attrs: objektum kell +@msg automation path rejected: the folder's name isn't valid text az automatizálás útvonala elutasítva: a mappa neve nem érvényes szöveg +@msg automation path rejected: {_1} isn't valid text az automatizálás útvonala elutasítva: nem érvényes szöveg: {_1} +@msg automation path rejected: {why}: {path} az automatizálás útvonala elutasítva: {why}: {path} +@msg axis must be "vertical", "horizontal" or an angle in degrees, not `{given}` axis: "vertical", "horizontal" vagy fokban megadott szög kell, ez nem az: `{given}` +@msg backgroundContents must be transparent or white backgroundContents: transparent vagy white kell +@msg bad AES key hibás AES-kulcs +@msg bad `runs`: {e} hibás `runs`: {e} +@msg bad arrowScale hibás arrowScale +@msg bad base64 hibás base64 +@msg bad color {c} hibás szín: {c} +@msg bad colour hibás szín +@msg bad colour in `colors` hibás szín itt: `colors` +@msg bad colour {v} hibás szín: {v} +@msg bad colour {v} in groupColors hibás szín a groupColors értékben: {v} +@msg bad cross-reference entry hibás kereszthivatkozási bejegyzés +@msg bad cross-reference table hibás kereszthivatkozási tábla +@msg bad current colour {v} hibás jelenlegi szín: {v} +@msg bad dataBase64 hibás dataBase64 +@msg bad edit hibás szerkesztés +@msg bad fill {v} hibás kitöltés: {v} +@msg bad fit: {e} hibás illesztés: {e} +@msg bad model {other} (keep, new or document) hibás modell: {other} (keep, new vagy document) +@msg bad new colour {v} hibás új szín: {v} +@msg bad object hibás objektum +@msg bad object number hibás objektumszám +@msg bad offset hibás eltolás +@msg bad path data: {e} hibás útvonaladatok: {e} +@msg bad point {v}: expected [x, y] hibás pont: {v}; [x, y] kell +@msg bad point {v}: expected [x, y] or [x, y, pressure] hibás pont: {v}; [x, y] vagy [x, y, pressure] kell +@msg bad reference hibás hivatkozás +@msg bad trailer size hibás trailerméret +@msg bad {k} colour hibás szín: {k} +@msg batches cannot nest kötegek nem ágyazhatók egymásba +@msg bind something to a variable first előbb köss valamit egy változóhoz +@msg bleed must be 0–{MAX_BLEED} pt: a number, [top, bottom, left, right] or {{top, bottom, left, right}} bleed: 0–{MAX_BLEED} pt kell: egy szám, [top, bottom, left, right] vagy {{top, bottom, left, right}} +@msg blend must be a mode name blend: keverési mód neve kell +@msg both sides of an XPath | must select nodes az XPath | mindkét oldalának csomópontokat kell kijelölnie +@msg brush must be a name or null brush: név vagy null kell +@msg by must be a number by: szám kell +@msg can't add page thumbnails: {why} nem adhatók hozzá oldalbélyegképek: {why} +@msg can't add the editing data for other apps: {why} nem adhatók hozzá a más alkalmazásoknak szánt szerkesztési adatok: {why} +@msg can't edit the written PDF: {why} a kiírt PDF nem szerkeszthető: {why} +@msg can't encrypt the PDF: {why} a PDF nem titkosítható: {why} +@msg can't linearise the PDF: {why} a PDF nem linearizálható: {why} +@msg can't open `{_1}`: {_2} nem nyitható meg: `{_1}`: {_2} +@msg can't open `{_1}`: {e} nem nyitható meg: `{_1}`: {e} +@msg can't open `{name}`: not a format VectorCraft reads (see document.formats) nem nyitható meg: `{name}`; ezt a formátumot a VectorCraft nem olvassa (lásd: document.formats) +@msg can't place `{name}`: not a format VectorCraft reads (see document.formats) nem helyezhető el: `{name}`; ezt a formátumot a VectorCraft nem olvassa (lásd: document.formats) +@msg can't read back the written PDF: {e} a kiírt PDF nem olvasható vissza: {e} +@msg can't read this Word document: {why} ez a Word-dokumentum nem olvasható: {why} +@msg can't write .{e} images: use .png, .jpg, .gif, .webp, .tif or .bmp .{e} képek nem írhatók: használd a .png, .jpg, .gif, .webp, .tif vagy .bmp formátumot +@msg can't write PDF layers, overprint or invisible text: {why} nem írhatók ki a PDF-rétegek, a felülnyomás vagy a láthatatlan szöveg: {why} +@msg can't write the file's copyright: {why} nem írható ki a fájl szerzői jogi adata: {why} +@msg can't write the file's modification date: {why} nem írható ki a fájl módosítási dátuma: {why} +@msg can't write the pages' user units: {why} nem írhatók ki az oldalak felhasználói egységei: {why} +@msg canceled megszakítva +@msg cannot convert the object to a primitive value az objektum nem alakítható primitív értékké +@msg cannot convert undefined or null to an object undefined vagy null nem alakítható objektummá +@msg cannot distort a zero-size or non-finite bounding box nulla méretű vagy nem véges határolókeret nem torzítható +@msg cannot move an object into itself egy objektum nem helyezhető át önmagába +@msg case must be upper|lower|title|sentence case: upper|lower|title|sentence kell +@msg category `{c}`: one of {_1} kategória `{c}`: ezek egyike: {_1} +@msg center must be [x, y] center: [x, y] kell +@msg character dimensions cannot be represented with the source text transform a karakterméretek nem ábrázolhatók a forrásszöveg transzformációjával +@msg character dimensions cannot be represented with the target text transform a karakterméretek nem ábrázolhatók a célszöveg transzformációjával +@msg choose at least one artboard válassz legalább egy rajztáblát +@msg choose at least one status válassz legalább egy állapotot +@msg clip must be true or false clip: true vagy false kell +@msg clippingMask must be true or false clippingMask: true vagy false kell +@msg closed must be a boolean closed: logikai érték kell +@msg collapsed must be true or false collapsed: true vagy false kell +@msg color.profile: no RGB or CMYK profile is called “{profile}” color.profile: nincs ilyen nevű RGB- vagy CMYK-profil: „{profile}” +@msg colorMode must be rgb or cmyk, not `{m}` colorMode: rgb vagy cmyk kell, ez nem az: `{m}` +@msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel: {own} (a dokumentum módja), grayscale vagy bitmap kell +@msg colour groups can't go into colour groups színcsoport nem kerülhet színcsoportba +@msg colour, mode and spot apply to solid-colour swatches only colour, mode és spot: csak egyszínű színmintákra vonatkozik +@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read {column}. oszlop: `{cell}` a diagramadat-fájlok `%` oszlopa, ezek beolvasása nem történik meg +@msg column {column}: `{cell}` names `{name}`, which is a {_1} variable {column}. oszlop: `{cell}` ezt nevezi meg: `{name}`, amely {_1} típusú változó +@msg column {column}: `{cell}` names no variable {column}. oszlop: `{cell}` nem nevez meg változót +@msg column {column}: the variable name is longer than {MAX_NAME} characters {column}. oszlop: a változó neve hosszabb {MAX_NAME} karakternél +@msg column: true floats the whole column and takes no onto, above or below column: true az egész oszlopot lebegővé teszi, és nem adható meg mellette onto, above vagy below +@msg command must be a shape.* command command: shape.* parancs kell +@msg commands[{i}]: missing `command` commands[{i}]: hiányzik: `command` +@msg composer must be "singleLine" or "everyLine" composer: "singleLine" vagy "everyLine" kell +@msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes összetett alakzatba útvonalak, összetett útvonalak, csoportok, összetett alakzatok, szöveg, összemosások és burkolók kerülhetnek +@msg compound {_1} must contain exactly one open path to join az összetett objektumnak ({_1}) pontosan egy összekapcsolható nyitott útvonalat kell tartalmaznia +@msg connect needs a path other than the one extended connect: a meghosszabbított útvonaltól különböző útvonal kell +@msg connect needs id connect: id is kell hozzá +@msg connect path has no open end connect: az útvonalnak nincs nyitott vége +@msg continuation must be an array of path chunks continuation: útvonaldarabok tömbje kell +@msg continuation requires points continuation: points is kell hozzá +@msg copy needs path: the file to copy into the document's folder copy: path is kell hozzá: a dokumentum mappájába másolandó fájl +@msg copy takes images only: relink placed documents where their files are copy: csak képeket fogad; az elhelyezett dokumentumokat ott csatold újra, ahol a fájljaik vannak +@msg copying a file isn't available on the web a webes változatban nem lehet fájlt másolni +@msg copyrightStatus must be unknown, copyrighted or publicDomain copyrightStatus: unknown, copyrighted vagy publicDomain kell +@msg copyrightUrl must be a URL (no spaces, at most 2048 characters) copyrightUrl: URL kell (szóköz nélkül, legfeljebb 2048 karakter) +@msg corners must be 4 [x, y] points (TL, TR, BR, BL) corners: 4 darab [x, y] pont kell (TL, TR, BR, BL) +@msg counterPer `{c}`: item or file counterPer `{c}`: item vagy file +@msg crop `{_1}`: only PDF pages have art, trim, bleed and media boxes; use "crop" or "bounding" crop `{_1}`: csak a PDF-oldalaknak van art, trim, bleed és media kerete; használd a "crop" vagy a "bounding" értéket +@msg crop rectangle doesn't overlap the image a vágási téglalap nem fedi a képet +@msg cross-reference and object streams aren't supported a kereszthivatkozási és objektumfolyamok nem támogatottak +@msg damaged compressed data: {e} sérült tömörített adatok: {e} +@msg dash lengths must be numbers, got {v} dash: a hosszak számok legyenek, kapott érték: {v} +@msg dash must be a list of lengths or null, got {v} dash: hosszak listája vagy null kell, kapott érték: {v} +@msg data key `{k}`: letters, digits, -, _ and . (not name or vc-…) data kulcs `{k}`: betűk, számjegyek, -, _ és . (nem lehet name vagy vc-…) +@msg data must be an object of key: value, not {v} data: kulcs: érték párokból álló objektum kell, ez nem az: {v} +@msg data set `{name}` holds a value for `{var}`, which the library doesn't declare a(z) `{name}` adatkészlet értéket tartalmaz ehhez: `{var}`, de ezt a könyvtár nem deklarálja +@msg data set `{name}` holds two values for `{var}` a(z) `{name}` adatkészlet két értéket tartalmaz ehhez: `{var}` +@msg data set `{name}` is declared twice az adatkészlet kétszer van deklarálva: `{name}` +@msg data takes at most {MAX_DATA} keys at once data: egyszerre legfeljebb {MAX_DATA} kulcsot fogad +@msg dataset `{name}` already exists már van ilyen adatkészlet: `{name}` +@msg dataset `{to}` already exists már van ilyen adatkészlet: `{to}` +@msg date `{d}`: YYYY-MM-DD dátum `{d}`: YYYY-MM-DD +@msg decoded data is too large a dekódolt adatok túl nagyok +@msg define a variable first előbb definiálj egy változót +@msg detect must be true or false detect: true vagy false kell +@msg direct-select anchor points of a path jelöld ki közvetlen kijelöléssel egy útvonal horgonypontjait +@msg distance must be > 0 distance: > 0 érték kell +@msg dx and dy give the arrow's direction dx és dy: a nyíl irányát adják meg +@msg dx and dy must be numbers dx és dy: számok kellenek +@msg dxf fitTo must be [width, height], positive dxf fitTo: [width, height] kell, pozitív értékekkel +@msg dxf must be an object of DXF import options dxf: a DXF-importálási beállítások objektuma kell +@msg dxf scale must be a positive number up to {_1}, not {s} dxf scale: pozitív szám kell, legfeljebb {_1}; ez nem az: {s} +@msg dxf unit `{u}`: a unit such as mm, cm, in or pt dxf unit `{u}`: mértékegység kell, például mm, cm, in vagy pt +@msg dxf: {e} dxf: {e} +@msg each format is an object {format, scale?, suffix?} minden formátum egy {format, scale?, suffix?} objektum +@msg each item needs an id minden elemnek azonosító kell +@msg each match needs `kind` minden találathoz `kind` kell +@msg each match needs a `name` minden találathoz `name` kell +@msg each of `fonts` is {family, style?}; 1 to 1000 of them a `fonts` minden eleme {family, style?}; 1–1000 darab lehet +@msg each of `items` is {kind, item} az `items` minden eleme {kind, item} +@msg each of `items` is {{id, corners?}} with an object id, not {it} az `items` minden eleme {{id, corners?}} objektumazonosítóval, ez nem az: {it} +@msg each path chunk must contain 1 to 4096 points minden útvonaldarabnak 1–4096 pontot kell tartalmaznia +@msg each pick is {{at: [x, y]}} or {{rect: [x0, y0, x1, y1]}} (got {v}) minden választás {{at: [x, y]}} vagy {{rect: [x0, y0, x1, y1]}} (kapott érték: {v}) +@msg each row needs `from` minden sorhoz `from` kell +@msg each stop needs a position minden színátmenetpontnak pozíció kell +@msg each subpath needs an anchors array minden részútvonalhoz anchors tömb kell +@msg each weight must be a number of 0 or more (got {v}) minden súly 0 vagy nagyobb szám legyen (kapott érték: {v}) +@msg easingType must be easeIn, easeOut, easeInOut or easeOutIn easingType: easeIn, easeOut, easeInOut vagy easeOutIn kell +@msg editingData must be true or false editingData: true vagy false kell +@msg editingData must be true, false or "always" editingData: true, false vagy "always" kell +@msg edits overlap a szerkesztések átfedik egymást +@msg effects of objects whose appearances differ can't be moved together eltérő megjelenésű objektumok effektusai nem helyezhetők át együtt +@msg empty header in column {_1} üres fejléc ebben az oszlopban: {_1} +@msg encoding `{_1}`: utf8 or utf16 kódolás `{_1}`: utf8 vagy utf16 +@msg ends must be two of "first" and "last" ends: két érték kell ezekből: "first" és "last" +@msg every numbered name for the result is taken az eredmény minden számozott neve foglalt +@msg expanded SVG styles exceed the import size limit a kibontott SVG-stílusok túllépik az importálási méretkorlátot +@msg export presets file is larger than {MAX_PRESET_FILE_BYTES} bytes az exportálási előbeállítások fájlja nagyobb, mint {MAX_PRESET_FILE_BYTES} bájt +@msg exportText must be editable or appearance exportText: editable vagy appearance kell +@msg exportType must be movieClip or graphic, not `{s}` exportType: movieClip vagy graphic kell, ez nem az: `{s}` +@msg extend needs id extend: id is kell hozzá +@msg featureChanges lists at most {MAX_FEATURE_CHANGES} tags featureChanges: legfeljebb {MAX_FEATURE_CHANGES} címkét sorolhat fel +@msg featureChanges must be a list of tags featureChanges: címkék listája kell +@msg features must be a list of tags features: címkék listája kell +@msg fidelity must be 0..100 fidelity: 0..100 kell +@msg files must be {name, dataBase64} files: {name, dataBase64} kell +@msg finally table {t} out of range a finally tábla tartományon kívül esik: {t} +@msg fit must be none|autoHeight|shrinkText|block, got {id} fit: none|autoHeight|shrinkText|block kell, kapott érték: {id} +@msg flags cannot be given with a RegExp object RegExp objektum mellett nem adhatók meg jelzők +@msg flattener: {e} lapító: {e} +@msg flattenerPreset `{name}`: high, medium, low or a saved one (see flattener.presets.list) flattenerPreset `{name}`: high, medium, low vagy egy mentett előbeállítás (lásd: flattener.presets.list) +@msg flipProfile must be along|across, got {o} flipProfile: along|across kell, kapott érték: {o} +@msg folders `{f}`: none, rows, format, item or itemFormat folders `{f}`: none, rows, format, item vagy itemFormat +@msg folders deeper than {MAX_BATCH_DEPTH} levels {MAX_BATCH_DEPTH} szintnél mélyebb mappák +@msg folders deeper than {MAX_DEPTH} levels {MAX_DEPTH} szintnél mélyebb mappák +@msg font family `{family}` is not available a betűcsalád nem érhető el: `{family}` +@msg font family `{tf}` is not available a betűcsalád nem érhető el: `{tf}` +@msg format `{f}`: pdf or postscript format `{f}`: pdf vagy postscript +@msg format `{f}`: text or json format `{f}`: text vagy json +@msg format is `{format}` a formátum: `{format}` +@msg formats must be an array of rows, not {v} formats: sorok tömbje kell, ez nem az: {v} +@msg frequency must be between 1 and 300 lines per inch frequency: 1 és 300 vonal/hüvelyk közötti érték kell +@msg from and to must be finite from és to: véges érték kell +@msg from must be [x0, y0, x1, y1] from: [x0, y0, x1, y1] kell +@msg function declaration index out of range a függvénydeklaráció indexe tartományon kívül esik +@msg give `before` or `after`, not both a `before` vagy az `after` értéket add meg, ne mindkettőt +@msg give `char`, `text`, `code` or `unicode` add meg a `char`, a `text`, a `code` vagy a `unicode` értéket +@msg give `colors`, or `color` and `rule` add meg a `colors` értéket, vagy a `color` és a `rule` értéket +@msg give `count` or `spacing`, not both a `count` vagy a `spacing` értéket add meg, ne mindkettőt +@msg give `event`, such as onclick add meg az `event` értéket, például onclick +@msg give `file`, the JavaScript file's path or URL add meg a `file` értéket: a JavaScript-fájl elérési útját vagy URL-jét +@msg give `fill` and/or `stroke` add meg a `fill` és/vagy a `stroke` értéket +@msg give `fill`, `stroke` or both add meg a `fill` vagy a `stroke` értéket, vagy mindkettőt +@msg give `folder` add meg a `folder` értéket +@msg give `fonts`, or open a document add meg a `fonts` értéket, vagy nyiss meg egy dokumentumot +@msg give `from` or `indices`, not both a `from` vagy az `indices` értéket add meg, ne mindkettőt +@msg give `id` (no text is being edited) add meg az `id` értéket (nincs szerkesztés alatt álló szöveg) +@msg give `id` and `anchors`, or `items`, not both az `id` és az `anchors` értéket, vagy az `items` értéket add meg, ne mindkettőt +@msg give `id` or `guide`, not both az `id` vagy a `guide` értéket add meg, ne mindkettőt +@msg give `length` or `to` add meg a `length` vagy a `to` értéket +@msg give `matches`: [{kind, name, target}] add meg a `matches` értéket: [{kind, name, target}] +@msg give `name` (or edit a pattern) add meg a `name` értéket (vagy szerkessz egy mintázatot) +@msg give `name` or `names` add meg a `name` vagy a `names` értéket +@msg give `name`, an SVG filter's name add meg a `name` értéket: egy SVG-szűrő nevét +@msg give `path` (a .wasm file) or `dataBase64` (the module) add meg a `path` (egy .wasm fájl) vagy a `dataBase64` (a modul) értéket +@msg give `path`, `data` or `dataBase64` add meg a `path`, a `data` vagy a `dataBase64` értéket +@msg give `path`, `data`, `dataBase64` or `csv` add meg a `path`, a `data`, a `dataBase64` vagy a `csv` értéket +@msg give `path`, `xml` or `dataBase64` add meg a `path`, az `xml` vagy a `dataBase64` értéket +@msg give `path`, an SVG file, or `svg`, SVG text add meg a `path` értéket (egy SVG-fájl) vagy az `svg` értéket (SVG-szöveg) +@msg give `script`, the JavaScript the event runs ("" removes the event) add meg a `script` értéket: az esemény által futtatott JavaScriptet (a "" eltávolítja az eseményt) +@msg give `text` (the reading) or `remove` add meg a `text` (az olvasat) vagy a `remove` értéket +@msg give `x` and `y` (and a `tolerance` of 0 or more) add meg az `x` és az `y` értéket (és egy 0 vagy nagyobb `tolerance` értéket) +@msg give `xml`, one SVG element add meg az `xml` értéket: egyetlen SVG elemet +@msg give a mode or r/g/b, c/m/y/k, gray or tint adjustments adj meg egy módot, vagy r/g/b, c/m/y/k, gray vagy tint módosításokat +@msg give a name, or paint the active proxy with a saved preset adj meg egy nevet, vagy fesd az aktív mintadobozt egy mentett előbeállítással +@msg give a name, or select a stroke with a saved profile adj meg egy nevet, vagy jelölj ki egy mentett profilú körvonalat +@msg give a pattern name or select an object painted with a pattern adj meg egy mintázatnevet, vagy jelölj ki egy mintázattal festett objektumot +@msg give at least one of clip, invert, disabled, linked adj meg legalább egyet ezek közül: clip, invert, disabled, linked +@msg give color, none, swatch or gradient adj meg color, none, swatch vagy gradient értéket +@msg give dataBase64 add meg a dataBase64 értéket +@msg give either at (a click) or area (a path drawn around the overlaps) add meg az at (egy kattintás) vagy az area (az átfedések köré rajzolt útvonal) értéket +@msg give exactly one of `at`, `rect` and `points` pontosan egyet adj meg ezek közül: `at`, `rect`, `points` +@msg give exactly one of `path`, `data` and `dataBase64` pontosan egyet adj meg ezek közül: `path`, `data`, `dataBase64` +@msg give formats or a preset, not both a formats értéket vagy egy előbeállítást adj meg, ne mindkettőt +@msg give index or indexes, not both az index vagy az indexes értéket add meg, ne mindkettőt +@msg give newName or delete add meg a newName vagy a delete értéket +@msg give offset or by add meg az offset vagy a by értéket +@msg give one element egyetlen elemet adj meg +@msg give one of `to`, `rect` or `at` egyet adj meg ezek közül: `to`, `rect`, `at` +@msg give one of assets, layers, selection or fullDocument egyet adj meg ezek közül: assets, layers, selection, fullDocument +@msg give only one of onto, above, below, icon and a column place csak egyet adj meg ezek közül: onto, above, below, icon vagy egy oszlopbeli hely +@msg give opacity or blend add meg az opacity vagy a blend értéket +@msg give origin: [x, y], or reset: true add meg ezt: origin: [x, y], vagy ezt: reset: true +@msg give overprintFill, overprintStroke, showCenter, imageMap, url or note add meg az overprintFill, overprintStroke, showCenter, imageMap, url vagy note értéket +@msg give path (a file) or folder add meg a path (egy fájl) vagy a folder értéket +@msg give path, or name and dataBase64 add meg a path értéket, vagy a name és a dataBase64 értéket +@msg give paths or files add meg a paths vagy a files értéket +@msg give rows, rowHeight, columns or columnWidth add meg a rows, rowHeight, columns vagy columnWidth értéket +@msg give svg, or dataBase64 of an SVG or SVGZ file add meg az svg értéket, vagy egy SVG- vagy SVGZ-fájl dataBase64 értékét +@msg give text add meg a text értéket +@msg give the asset a name adj nevet az elemnek +@msg give the preset a `name` adj `name` értéket az előbeállításnak +@msg give the preset a name adj nevet az előbeállításnak +@msg give the preset a name (1–64 characters) adj nevet az előbeállításnak (1–64 karakter) +@msg give the settings to change, e.g. {"formats"}]} add meg a módosítandó beállításokat, például {"formats"}]} +@msg give the style a name adj nevet a stílusnak +@msg give two or more style `names` adj meg két vagy több stílusnevet a `names` értékben +@msg give two or more swatches adj meg két vagy több színmintát +@msg give x, y, or a handle's length or angle add meg az x, az y értéket, vagy egy fogantyú hosszát vagy szögét +@msg give {key, value} or {values} add meg ezt: {key, value} vagy {values} +@msg global must be true or false global: true vagy false kell +@msg glyph {_1} is not drawn for {ch} with the character's style (such as All Caps, Small Caps or a numeral system) a(z) {_1} glifa nem ehhez a karakterhez rajzolódik ki a karakter stílusával: {ch} (ilyen például a Csupa nagybetű, a Kiskapitális vagy egy számrendszer) +@msg glyph {g} is not an alternate of {ch} in {_1} {_2} a(z) {g} glifa nem alternatívája ennek: {ch} (betűtípus: {_1} {_2}) +@msg gradient must be "objects" or "mesh" gradient: "objects" vagy "mesh" kell +@msg grays must be "profile" or "black", not `{g}` grays: "profile" vagy "black" kell, ez nem az: `{g}` +@msg gridColors must be a preset name or two colours gridColors: előbeállítás neve vagy két szín kell +@msg gridSize must be small, medium or large gridSize: small, medium vagy large kell +@msg guide {g} is not selected a segédvonal nincs kijelölve: {g} +@msg handle must be 0..3 handle: 0..3 kell +@msg handler at {_1} expects {_2} values but its range starts with {d} a(z) {_1} helyen lévő kezelő {_2} értéket vár, de a tartománya ennyivel kezdődik: {d} +@msg handler depth too large a kezelő mélysége túl nagy +@msg handler range {_1}..{_2} out of range a kezelő tartománya ({_1}..{_2}) tartományon kívül esik +@msg hiddenLayers must be true or false hiddenLayers: true vagy false kell +@msg hiddenObjects {v}: "layer" (the default), "omit" or "visible" hiddenObjects {v}: "layer" (ez az alapértelmezés), "omit" vagy "visible" +@msg highlight a layer to merge into emelj ki egy réteget, amelybe az egyesítés történjen +@msg highlight two or more rows in one layer or group emelj ki két vagy több sort egyetlen rétegben vagy csoportban +@msg highlight two or more rows to merge emelj ki két vagy több egyesítendő sort +@msg hvcC hvcC +@msg icon docks a panel in the icon column: use window.panel.dock icon: a panelt az ikonoszlopba dokkolja; használd a window.panel.dock parancsot +@msg id must be a dimension id id: méretvonal-azonosító kell +@msg image has no bounds a képnek nincsenek határai +@msg image {_1} is linked already a kép már csatolva van: {_1} +@msg imageMap `{m}`: none, client or server imageMap `{m}`: none, client vagy server +@msg images in a spot ink whose samples couldn't be read were imported in RGB azok a direktszínű képek, amelyek mintái nem voltak olvashatók, RGB-ben lettek importálva +@msg images past the most pixels one file may hold were left out kimaradtak azok a képek, amelyek túllépték az egy fájlban megengedett legnagyobb képpontszámot +@msg images too large to read were left out a beolvasáshoz túl nagy képek kimaradtak +@msg index out of range az index tartományon kívül esik +@msg indexes may hold at most {MAX_GUIDE_INDEXES} entries indexes: legfeljebb {MAX_GUIDE_INDEXES} elemet tartalmazhat +@msg indexes must be an array of guide indexes indexes: segédvonalindexek tömbje kell +@msg instances must be 1..1000 instances: 1..1000 kell +@msg instruction out of range az utasítás tartományon kívül esik +@msg instruction {pc} ({op}) pops below the stack a(z) {pc}. utasítás ({op}) a verem alja alól venne ki értéket +@msg instruction {pc} reached with stack depths {seen} and {d} a(z) {pc}. utasítás kétféle veremmélységgel érhető el: {seen} és {d} +@msg invalid `color` érvénytelen `color` +@msg invalid anchor index {v}: expected a non-negative integer érvénytelen horgonypontindex: {v}; nemnegatív egész szám kell +@msg invalid anchor reference {v}: expected [subpath, anchor] érvénytelen horgonypont-hivatkozás: {v}; [subpath, anchor] kell +@msg invalid angle érvénytelen szög +@msg invalid array length érvénytelen tömbhossz +@msg invalid brush: {e} érvénytelen ecset: {e} +@msg invalid color érvénytelen szín +@msg invalid colour {c} érvénytelen szín: {c} +@msg invalid delta érvénytelen eltérés +@msg invalid group érvénytelen csoport +@msg invalid object id {v}: expected a non-negative integer érvénytelen objektumazonosító: {v}; nemnegatív egész szám kell +@msg invalid point érvénytelen pont +@msg invalid regular expression flag '{_1}' érvénytelen jelző a reguláris kifejezésben: '{_1}' +@msg invalid regular expression: {m} érvénytelen reguláris kifejezés: {m} +@msg invalid size érvénytelen méret +@msg invalid t érvénytelen t +@msg invalid time value érvénytelen időérték +@msg invalid tolerance érvénytelen tűrés +@msg is a confirm's answer, whose `value` must be true or false egy megerősítés válasza, amelynek `value` értéke true vagy false lehet +@msg is a prompt's answer, whose `value` must be a string or null egy bekérés válasza, amelynek `value` értéke karakterlánc vagy null lehet +@msg is an alert's answer, whose `value` must be "ok" egy figyelmeztetés válasza, amelynek `value` értéke "ok" lehet +@msg is longer than 16 KiB hosszabb 16 KiB-nál +@msg it draws its image through a clipping path a képét vágóútvonalon keresztül rajzolja ki +@msg it draws no image nem rajzol ki képet +@msg it is larger than {MAX_DICTIONARY_FILE_BYTES} bytes nagyobb, mint {MAX_DICTIONARY_FILE_BYTES} bájt +@msg it isn't a file nem fájl +@msg it names {_1} plates, and at most {MAX_PLATES} are read {_1} színkivonatot nevez meg, de legfeljebb {MAX_PLATES} olvasható be +@msg its art is too long or too detailed for a head a grafikája túl hosszú vagy túl részletes egy nyílhegyhez +@msg its art paints nothing a grafikája semmit sem fest +@msg its artboards all lie beyond the canvas (more than {_1} pt from the origin) minden rajztáblája a vásznon kívül esik (több mint {_1} pt távolságra az origótól) +@msg its clipping masks are nested too deeply a vágómaszkjai túl mélyen vannak egymásba ágyazva +@msg its image is too large to read a képe túl nagy a beolvasáshoz +@msg its metadata has no description a metaadataiban nincs leírás +@msg its metadata has no direct length a metaadatainak nincs közvetlenül megadott hossza +@msg its plates are too large: more than {MAX_SAMPLES} pixels together a színkivonatai túl nagyok: együtt több mint {MAX_SAMPLES} képpont +@msg its plates are too large: {_1} plates of {w} × {h} pixels a színkivonatai túl nagyok: {_1} darab {w} × {h} képpontos színkivonat +@msg its plates can't be kept together a színkivonatai nem tarthatók együtt +@msg its shapes could not be combined into one az alakzatait nem sikerült eggyé egyesíteni +@msg join two different paths két különböző útvonalat kapcsolj össze +@msg jump to {pc}, past the end ugrás a végén túlra: {pc} +@msg justify must be auto|left|center|right|justifyAll justify: auto|left|center|right|justifyAll kell +@msg kbps must be a positive number, not {kbps} kbps: pozitív szám kell, ez nem az: {kbps} +@msg keywords must be a list of words or a comma-separated string keywords: szavak listája vagy vesszővel tagolt karakterlánc kell +@msg keywords must be at most {MAX_KEYWORD} characters, without control characters keywords: legfeljebb {MAX_KEYWORD} karakter lehet, vezérlőkarakterek nélkül +@msg kind must be 1, 2 or 3, or give a preset `name` (see perspective.presets.list) kind: 1, 2 vagy 3 kell, vagy adj meg egy előbeállítást a `name` értékben (lásd: perspective.presets.list) +@msg kind must be graphic, fillColor, strokeColor, fillGradient, strokeGradient, fillPattern, strokePattern, charStyle or paraStyle kind: graphic, fillColor, strokeColor, fillGradient, strokeGradient, fillPattern, strokePattern, charStyle vagy paraStyle kell +@msg knockout must be "on", "off", "neutral" or a bool, not {v} knockout: "on", "off", "neutral" vagy logikai érték kell, ez nem az: {v} +@msg layer `{name}` has no art to export ebben a rétegben nincs exportálható grafika: `{name}` +@msg layer must name a layer or sublayer layer: réteget vagy alréteget kell megneveznie +@msg layers can't be intertwined: select the objects in them rétegek nem fonhatók össze: a bennük lévő objektumokat jelöld ki +@msg layers go only at the top level or in layers, objects in layers and groups rétegek csak a legfelső szintre vagy rétegekbe kerülhetnek, objektumok rétegekbe és csoportokba +@msg layers must be true or false layers: true vagy false kell +@msg layout must be gridByRow, gridByColumn, row or column layout: gridByRow, gridByColumn, row vagy column kell +@msg leading must be a number or "auto" leading: szám vagy "auto" kell +@msg left/right must be non-negative widths left/right: nemnegatív szélességek kellenek +@msg legacyNameEncoding must be one of {_1} legacyNameEncoding: ezek egyike kell: {_1} +@msg level `{t}`: 2 or 3 level `{t}`: 2 vagy 3 +@msg line {line}: more than {MAX_CSV_COLS} columns {line}. sor: több mint {MAX_CSV_COLS} oszlop +@msg line {line}: unclosed quote {line}. sor: lezáratlan idézőjel +@msg line {line}: value for `{var}` must match its variable kind {line}. sor: a(z) `{var}` értékének meg kell felelnie a változó típusának +@msg lineEndings `{other}`: lf or crlf lineEndings `{other}`: lf vagy crlf +@msg loading profiles from disk isn't available in the browser böngészőben nem lehet profilokat lemezről betölteni +@msg localize: the first argument must be a localization object or a string localize: az első argumentum lokalizációs objektum vagy karakterlánc kell legyen +@msg margin: a {m} pt margin leaves no imageable area on the paper margin: {m} pt margó mellett nem marad nyomtatható terület a papíron +@msg matrix must be finite and invertible, depth finite matrix: véges és invertálható kell legyen, a depth véges +@msg matte: {e} matte: {e} +@msg member is for order front, forward, backward or back member: az order front, forward, backward vagy back értékéhez való +@msg missing `artboards` hiányzik: `artboards` +@msg missing `at` [x, y] hiányzik: `at` [x, y] +@msg missing `attrs` hiányzik: `attrs` +@msg missing `color` or `opacity` hiányzik: `color` vagy `opacity` +@msg missing `colors` hiányzik: `colors` +@msg missing `commands` hiányzik: `commands` +@msg missing `destinationFolder` hiányzik: `destinationFolder` +@msg missing `effect` id hiányzik az `effect` azonosítója +@msg missing `family` hiányzik: `family` +@msg missing `find` hiányzik: `find` +@msg missing `gid` (a glyph id, or null for the default glyph) hiányzik: `gid` (glifaazonosító, vagy null az alapértelmezett glifához) +@msg missing `group` hiányzik: `group` +@msg missing `id` hiányzik: `id` +@msg missing `id`: give one, or select one type object hiányzik: `id`; adj meg egyet, vagy jelölj ki egy szövegobjektumot +@msg missing `index` (a point index, or null to clear) hiányzik: `index` (pontindex, vagy null a törléshez) +@msg missing `index` (a stop index, or null to clear) hiányzik: `index` (színátmenetpont-index, vagy null a törléshez) +@msg missing `index` (an item index or null) hiányzik: `index` (elemindex vagy null) +@msg missing `item` hiányzik: `item` +@msg missing `library` hiányzik: `library` +@msg missing `library` (see graphicStyle.libraries) hiányzik: `library` (lásd: graphicStyle.libraries) +@msg missing `library` (see swatch.library.list) hiányzik: `library` (lásd: swatch.library.list) +@msg missing `map` (rows [{from, to}] or {current}) hiányzik: `map` ([{from, to}] sorok vagy {current}) +@msg missing `matrix` [a,b,c,d,e,f] hiányzik: `matrix` [a,b,c,d,e,f] +@msg missing `name` (see gradient.presets.list) hiányzik: `name` (lásd: gradient.presets.list) +@msg missing `offset` (a distance in points) hiányzik: `offset` (távolság pontban) +@msg missing `path` hiányzik: `path` +@msg missing `path` (a path object id) hiányzik: `path` (egy útvonalobjektum azonosítója) +@msg missing `picks` hiányzik: `picks` +@msg missing `rule` hiányzik: `rule` +@msg missing `source` id hiányzik a `source` azonosítója +@msg missing `start` (the byte offset of a character) hiányzik: `start` (egy karakter bájteltolása) +@msg missing `status`: linked, embedded, missing or modified hiányzik: `status`; linked, embedded, missing vagy modified lehet +@msg missing `target` id hiányzik a `target` azonosítója +@msg missing `text` hiányzik: `text` +@msg missing `to` hiányzik: `to` +@msg missing `to` (an index) hiányzik: `to` (egy index) +@msg missing `to`: a non-negative integer hiányzik: `to`; nemnegatív egész szám kell +@msg missing `type` hiányzik: `type` +@msg missing `value` hiányzik: `value` +@msg missing `word` hiányzik: `word` +@msg missing `{key}` hiányzik: `{key}` +@msg missing `{k}` hiányzik: `{k}` +@msg missing anchor hiányzik a horgonypont +@msg missing anchors hiányoznak a horgonypontok +@msg missing anchors [[subpath, anchor]…] hiányoznak a horgonypontok: [[subpath, anchor]…] +@msg missing array `{key}` hiányzik a tömb: `{key}` +@msg missing case hiányzik: case +@msg missing color hiányzik a szín +@msg missing commands hiányoznak a parancsok +@msg missing destination folder hiányzik a célmappa +@msg missing from hiányzik: from +@msg missing group hiányzik a csoport +@msg missing id or ids hiányzik: id vagy ids +@msg missing ids hiányzik: ids +@msg missing indexes hiányzik: indexes +@msg missing matrix [a,b,c,d,e,f] hiányzik: matrix [a,b,c,d,e,f] +@msg missing name hiányzik a név +@msg missing op hiányzik: op +@msg missing or invalid `color` hiányzó vagy érvénytelen `color` +@msg missing or unknown `tool` hiányzó vagy ismeretlen `tool` +@msg missing point hiányzik a pont +@msg missing point [x,y] hiányzik a pont: [x,y] +@msg missing point `{key}` ([x, y]) hiányzik a pont: `{key}` ([x, y]) +@msg missing points hiányoznak a pontok +@msg missing points [[x,y]…] hiányoznak a pontok: [[x,y]…] +@msg missing segment hiányzik a szakasz +@msg missing stops hiányoznak a színátmenetpontok +@msg missing subpaths hiányoznak a részútvonalak +@msg missing target hiányzik a cél +@msg missing to hiányzik: to +@msg missing x, y hiányzik: x, y +@msg mode is set, add or toggle, not `{other}` mode: set, add vagy toggle, ez nem az: `{other}` +@msg mode must be "cmyk" or "rgb" mode: "cmyk" vagy "rgb" kell +@msg mode must be area|onPath, got {o} mode: area|onPath kell, kapott érték: {o} +@msg more than 10000 linked files: package dependencies in smaller parts több mint 10000 csatolt fájl: kisebb részletekben csomagold a függőségeket +@msg more than 256 commands több mint 256 parancs +@msg more than {MAX_BATCH_FILES} data sets több mint {MAX_BATCH_FILES} adatkészlet +@msg more than {MAX_BATCH_FILES} files több mint {MAX_BATCH_FILES} fájl +@msg more than {MAX_CSV_ROWS} data rows több mint {MAX_CSV_ROWS} adatsor +@msg more than {MAX_FILES} images több mint {MAX_FILES} kép +@msg more than {MAX_IMPORT} presets több mint {MAX_IMPORT} előbeállítás +@msg moved must be [[x,y]…] moved: [[x,y]…] kell +@msg must be an object with `kind` and `value` `kind` és `value` kulcsot tartalmazó objektum kell +@msg must have `kind` alert, confirm or prompt a `kind` értéke alert, confirm vagy prompt kell legyen +@msg must have exactly `kind` and `value` pontosan a `kind` és a `value` kulcsot kell tartalmaznia +@msg name (a toolbar's name) is required name (egy eszköztár neve): kötelező +@msg name (a toolbar's name) must be a string name (egy eszköztár neve): karakterlánc kell +@msg name must be a toolbar's name name: egy eszköztár neve kell +@msg names is empty names: üres +@msg names must be an array of symbol names names: szimbólumnevek tömbje kell +@msg need `anchor` or `segment` + `t` `anchor` vagy `segment` + `t` kell +@msg need at least one anchor legalább egy horgonypont kell +@msg need at least one point legalább egy pont kell +@msg need at least two points legalább két pont kell +@msg needs a closing quote after the name a név után záró idézőjel kell +@msg needs a name név kell +@msg needs a name of at most 64 bytes legfeljebb 64 bájtos név kell +@msg needs a name of letters, digits and _, or a quoted name betűkből, számjegyekből és _ jelből álló név vagy idézőjelbe tett név kell +@msg needs a name without control characters vezérlőkarakterek nélküli név kell +@msg needs points pontok kellenek +@msg nesting too deep túl mély egymásba ágyazás +@msg nineSlice must be true or false nineSlice: true vagy false kell +@msg nineSliceGuides must be [left, top, right, bottom], each -16..16, with left + right < 1 and top + bottom < 1 nineSliceGuides: [left, top, right, bottom] kell, mindegyik -16..16, ahol left + right < 1 és top + bottom < 1 +@msg no HP-GL format nincs HP-GL formátum +@msg no New Document profile called `{shown}` ({_1}) nincs ilyen nevű új dokumentumprofil: `{shown}` ({_1}) +@msg no PDF preset named `{n}` nincs ilyen nevű PDF-előbeállítás: `{n}` +@msg no SVG filter at index {k} nincs SVG-szűrő ennél az indexnél: {k} +@msg no action set is current nincs aktuális műveletkészlet +@msg no active data set nincs aktív adatkészlet +@msg no appearance item {index} nincs ilyen megjelenési elem: {index} +@msg no arrowheads file here itt nincs nyílhegyfájl +@msg no artboard {_1} nincs ilyen rajztábla: {_1} +@msg no artboard {artboard} (0-based; the document has {_1}) nincs ilyen rajztábla: {artboard} (0-tól számozva; a dokumentumban {_1} van) +@msg no asset {id} nincs ilyen elem: {id} +@msg no asset {id} (see assets.list) nincs ilyen elem: {id} (lásd: assets.list) +@msg no assets to export nincs exportálható elem +@msg no assets yet: collect art for export first (assets.add) még nincsenek elemek: előbb gyűjts grafikát az exportáláshoz (assets.add) +@msg no brush named `{n}` nincs ilyen nevű ecset: `{n}` +@msg no character at byte {start} nincs karakter ennél a bájtnál: {start} +@msg no character has code {code} egyetlen karakternek sem ez a kódja: {code} +@msg no colour nincs szín +@msg no colour group `{group}` nincs ilyen színcsoport: `{group}` +@msg no colour group `{name}` nincs ilyen színcsoport: `{name}` +@msg no custom arrowhead {name} (see stroke.arrowheads.list) nincs ilyen egyéni nyílhegy: {name} (lásd: stroke.arrowheads.list) +@msg no data sets nincsenek adatkészletek +@msg no dataset named `{from}` nincs ilyen nevű adatkészlet: `{from}` +@msg no dataset named `{name}` nincs ilyen nevű adatkészlet: `{name}` +@msg no datasets nincsenek adatkészletek +@msg no design named `{name}` nincs ilyen nevű diagramminta: `{name}` +@msg no design named `{n}` nincs ilyen nevű diagramminta: `{n}` +@msg no design named `{old}` nincs ilyen nevű diagramminta: `{old}` +@msg no encoder for {_1} yet ehhez még nincs kódoló: {_1} +@msg no export preset `{name}` (see document.exportPresets.list) nincs ilyen exportálási előbeállítás: `{name}` (lásd: document.exportPresets.list) +@msg no file to open nincs megnyitandó fájl +@msg no folder: pass `path` or set Preferences › Plug-ins & Scratch Disks › Additional Plug-ins Folder nincs mappa: add meg a `path` értéket, vagy állítsd be ezt: Beállítások › Bővítmények & Munkalemezek › További bővítmények mappája +@msg no fonts to look for: they are all available nincs keresendő betűtípus: mindegyik elérhető +@msg no formats to export nincs exportálandó formátum +@msg no gradient preset `{name}` (see gradient.presets.list) nincs ilyen színátmenet-előbeállítás: `{name}` (lásd: gradient.presets.list) +@msg no graphic style `{n}` in `{_1}` nincs ilyen grafikai stílus: `{n}` (itt: `{_1}`) +@msg no graphic style library `{key}` (see graphicStyle.libraries) nincs ilyen grafikaistílus-könyvtár: `{key}` (lásd: graphicStyle.libraries) +@msg no guide selected nincs kijelölt segédvonal +@msg no guide selected (or give an index) nincs kijelölt segédvonal (vagy adj meg egy indexet) +@msg no guide {i} nincs ilyen segédvonal: {i} +@msg no images in the folder a mappában nincsenek képek +@msg no instructions nincsenek utasítások +@msg no item at index {_1} nincs elem ennél az indexnél: {_1} +@msg no item at index {from} nincs elem ennél az indexnél: {from} +@msg no item at one of the indices {idx} az indexek egyikénél nincs elem: {idx} +@msg no layer nincs réteg +@msg no layer to rename nincs átnevezhető réteg +@msg no layer {id} (see layer.list) nincs ilyen réteg: {id} (lásd: layer.list) +@msg no layers to export nincs exportálható réteg +@msg no library `{key}` nincs ilyen könyvtár: `{key}` +@msg no metafile format nincs metafájlformátum +@msg no object {_1} nincs ilyen objektum: {_1} +@msg no objects nincsenek objektumok +@msg no parent layer nincs szülőréteg +@msg no perspective grid preset named `{b}` (see perspective.presets.list) nincs ilyen nevű perspektivikusrács-előbeállítás: `{b}` (lásd: perspective.presets.list) +@msg no perspective grid preset named `{n}` nincs ilyen nevű perspektivikusrács-előbeállítás: `{n}` +@msg no point selected (give `index`) nincs kijelölt pont (add meg az `index` értéket) +@msg no preset called `{from}` (see file.newPresets) nincs ilyen nevű előbeállítás: `{from}` (lásd: file.newPresets) +@msg no preset called `{name}` (see file.newPresets) nincs ilyen nevű előbeállítás: `{name}` (lásd: file.newPresets) +@msg no preset named `{n}` nincs ilyen nevű előbeállítás: `{n}` +@msg no print preset named `{b}` (see print.presets.list) nincs ilyen nevű nyomtatási előbeállítás: `{b}` (lásd: print.presets.list) +@msg no print preset named `{name}` (presets: {_1}) nincs ilyen nevű nyomtatási előbeállítás: `{name}` (előbeállítások: {_1}) +@msg no print preset named `{n}` nincs ilyen nevű nyomtatási előbeállítás: `{n}` +@msg no profile named `{name}` nincs ilyen nevű profil: `{name}` +@msg no random numbers ({e}) nincsenek véletlenszámok ({e}) +@msg no readable files in the folder a mappában nincsenek olvasható fájlok +@msg no recovery copy `{f}` (see file.recovery.list) nincs ilyen helyreállítási másolat: `{f}` (lásd: file.recovery.list) +@msg no rows nincsenek sorok +@msg no saved PDF preset named `{name}` nincs ilyen nevű mentett PDF-előbeállítás: `{name}` +@msg no saved export preset `{name}` nincs ilyen mentett exportálási előbeállítás: `{name}` +@msg no saved gradient preset called {name} nincs ilyen nevű mentett színátmenet-előbeállítás: {name} +@msg no saved gradient presets nincs mentett színátmenet-előbeállítás +@msg no saved preset called `{name}` nincs ilyen nevű mentett előbeállítás: `{name}` +@msg no saved presets to export (name [Default] in `names` to export it) nincs exportálható mentett előbeállítás (az exportálásához nevezd meg a [Default] előbeállítást a `names` értékben) +@msg no saved presets to export (name built-in ones in `names`) nincs exportálható mentett előbeállítás (a beépítetteket a `names` értékben nevezd meg) +@msg no saved print preset named `{name}` nincs ilyen nevű mentett nyomtatási előbeállítás: `{name}` +@msg no saved profile called {name} nincs ilyen nevű mentett profil: {name} +@msg no saved selection `{name}` nincs ilyen mentett kijelölés: `{name}` +@msg no saved theme called {name} (see colorTheme.list) nincs ilyen nevű mentett téma: {name} (lásd: colorTheme.list) +@msg no saved views nincsenek mentett nézetek +@msg no selected or given object has a visible 3D effect egyik kijelölt vagy megadott objektumnak sincs látható 3D effektusa +@msg no series {i} nincs ilyen adatsor: {i} +@msg no slice {n} in the image (see slice.list) a képen nincs ilyen szelet: {n} (lásd: slice.list) +@msg no source art nincs forrásgrafika +@msg no stop {i} (the gradient has {n}) nincs ilyen színátmenetpont: {i} (a színátmenetnek {n} van) +@msg no style `{name}` nincs ilyen stílus: `{name}` +@msg no such artboard {v} nincs ilyen rajztábla: {v} +@msg no such assets (see assets.list) nincsenek ilyen elemek (lásd: assets.list) +@msg no such frame anchor, or the frame would reach past the canvas nincs ilyen kerethorgonypont, vagy a keret túlnyúlna a vásznon +@msg no such objects nincsenek ilyen objektumok +@msg no such path anchor, or the path would reach past the canvas nincs ilyen útvonal-horgonypont, vagy az útvonal túlnyúlna a vásznon +@msg no such rows nincsenek ilyen sorok +@msg no swatch `{keep}` nincs ilyen színminta: `{keep}` +@msg no swatch `{n}` nincs ilyen színminta: `{n}` +@msg no swatch `{n}` (swatches and colour groups move separately) nincs ilyen színminta: `{n}` (a színminták és a színcsoportok külön mozgathatók) +@msg no swatch library `{key}` (see swatch.library.list) nincs ilyen színmintakönyvtár: `{key}` (lásd: swatch.library.list) +@msg no swatch library `{key}` (see swatch.library.list; "document": the document's swatches) nincs ilyen színmintakönyvtár: `{key}` (lásd: swatch.library.list; "document": a dokumentum színmintái) +@msg no swatch library `{key}` (see swatch.library.list; "{DOCUMENT_SWATCHES}": the document's swatches) nincs ilyen színmintakönyvtár: `{key}` (lásd: swatch.library.list; "{DOCUMENT_SWATCHES}": a dokumentum színmintái) +@msg no swatch named `{n}` nincs ilyen nevű színminta: `{n}` +@msg no swatch or colour group `{n}` nincs ilyen színminta vagy színcsoport: `{n}` +@msg no swatch or colour group `{n}` in `{_1}` nincs ilyen színminta vagy színcsoport: `{n}` (itt: `{_1}`) +@msg no symbol named `{_1}` nincs ilyen nevű szimbólum: `{_1}` +@msg no symbol named `{name}` nincs ilyen nevű szimbólum: `{name}` +@msg no text objects selected nincs kijelölt szövegobjektum +@msg no toolbar named `{_1}` nincs ilyen nevű eszköztár: `{_1}` +@msg no toolbar named `{name}` nincs ilyen nevű eszköztár: `{name}` +@msg no tracing preset `{preset}` (see imageTrace.presets) nincs ilyen vektorizálási előbeállítás: `{preset}` (lásd: imageTrace.presets) +@msg no user library folder here (save with a path, or without one to get the data) itt nincs felhasználói könyvtármappa (ments elérési úttal, vagy anélkül, hogy megkapd az adatokat) +@msg no variable named `{from}` nincs ilyen nevű változó: `{from}` +@msg no variable named `{name}` nincs ilyen nevű változó: `{name}` +@msg no variable named `{var}` nincs ilyen nevű változó: `{var}` +@msg no variable named `{v}` nincs ilyen nevű változó: `{v}` +@msg no view named `{name}` nincs ilyen nevű nézet: `{name}` +@msg node {_1} already has the text variable `{_2}` a(z) {_1} csomópontnak már van szövegváltozója: `{_2}` +@msg node {_1} is not a graph nem diagram ez a csomópont: {_1} +@msg node {_1} is not an image nem kép ez a csomópont: {_1} +@msg node {_1} is not type nem szöveg ez a csomópont: {_1} +@msg not a DCS file nem DCS-fájl +@msg not a PDF presets file (format `{_1}`) nem PDF-előbeállításfájl (formátum: `{_1}`) +@msg not a PDF presets file: {e} nem PDF-előbeállításfájl: {e} +@msg not a RegExp object nem RegExp objektum +@msg not a Word document: its WordDocument stream doesn't start with a file information block nem Word-dokumentum: a WordDocument adatfolyama nem fájlinformációs blokkal kezdődik +@msg not a Word document: its compound file has no WordDocument stream nem Word-dokumentum: az összetett fájljában nincs WordDocument adatfolyam +@msg not a Word document: its main part is not a WordprocessingML document nem Word-dokumentum: a fő része nem WordprocessingML-dokumentum +@msg not a Word document: its package has no main document part nem Word-dokumentum: a csomagjában nincs fő dokumentumrész +@msg not a closed path nem zárt útvonal +@msg not a flattener presets file (format `{_1}`) nem lapítási előbeállításfájl (formátum: `{_1}`) +@msg not a flattener presets file: {e} nem lapítási előbeállításfájl: {e} +@msg not a layer or group nem réteg és nem csoport +@msg not a library file: {e} nem könyvtárfájl: {e} +@msg not a mesh envelope point nem hálós burkoló pontja +@msg not a perspective grid presets file (format `{_1}`) nem perspektivikusrács-előbeállításfájl (formátum: `{_1}`) +@msg not a perspective grid presets file: {e} nem perspektivikusrács-előbeállításfájl: {e} +@msg not a print presets file (format `{_1}`) nem nyomtatási előbeállításfájl (formátum: `{_1}`) +@msg not a print presets file: {e} nem nyomtatási előbeállításfájl: {e} +@msg not a regular expression nem reguláris kifejezés +@msg not a stored or deflated central record nem tárolt vagy deflate-tel tömörített központi rekord +@msg not a valid SVGZ file: {e} nem érvényes SVGZ-fájl: {e} +@msg not an RTF file: it doesn't start with {\\rtf nem RTF-fájl: nem ezzel kezdődik: {\\rtf +@msg not an action set: the text doesn't start with /version and a number nem műveletkészlet: a szöveg nem a /version szóval és egy számmal kezdődik +@msg not an image VectorCraft reads (see document.formats) nem olyan kép, amelyet a VectorCraft olvas (lásd: document.formats) +@msg not area type (text in a frame) outside perspective nem perspektíván kívüli területszöveg (keretben lévő szöveg) +@msg not editing an opacity mask nem folyik átlátszósági maszk szerkesztése +@msg not type on a path outside perspective nem perspektíván kívüli útvonalszöveg +@msg nothing prints semmi sem kerül nyomtatásra +@msg nothing to bind nincs mit kötni +@msg nothing to change nincs mit módosítani +@msg nothing to change: give dx, dy, hScale, vScale or rotation nincs mit módosítani: add meg a dx, dy, hScale, vScale vagy rotation értéket +@msg nothing to crop nincs mit körülvágni +@msg nothing to export nincs mit exportálni +@msg nothing to export: the document has no visible art nincs mit exportálni: a dokumentumban nincs látható grafika +@msg nothing to mark nincs mit megjelölni +@msg nothing to print: every artboard picked is blank nincs mit nyomtatni: minden kiválasztott rajztábla üres +@msg nothing to print: the document has no art that prints nincs mit nyomtatni: a dokumentumban nincs nyomtatásra kerülő grafika +@msg nothing to repeat nincs mit ismételni +@msg numbers out of order in {_1} quantifier a számok rossz sorrendben vannak ebben a kvantorban: {_1} +@msg object is not a path az objektum nem útvonal +@msg object transparency cannot be sampled onto highlighted characters; disable Transparency in Eyedropper Options or select the whole object az objektum átlátszósága nem vehető át kiemelt karakterekre; kapcsold ki az Átlátszóság beállítást a Pipetta beállításaiban, vagy jelöld ki a teljes objektumot +@msg object {_1} can't be set as point type ez az objektum nem állítható be pontszövegként: {_1} +@msg object {_1} has lost its file's contents: relink it ez az objektum elvesztette a fájlja tartalmát: {_1}; csatold újra +@msg object {_1} has no path ennek az objektumnak nincs útvonala: {_1} +@msg object {_1} has no size ennek az objektumnak nincs mérete: {_1} +@msg object {_1} is hidden or locked, or on a locked artboard ez az objektum rejtett vagy zárolt, vagy zárolt rajztáblán van: {_1} +@msg object {_1} is not a placed document ez az objektum nem elhelyezett dokumentum: {_1} +@msg object {_1} is not an Intertwine group ez az objektum nem összefonási csoport: {_1} +@msg object {_1} is not an image ez az objektum nem kép: {_1} +@msg object {_1} is not an image or a linked file ez az objektum nem kép és nem csatolt fájl: {_1} +@msg object {_1} is not an image or a placed document ez az objektum nem kép és nem elhelyezett dokumentum: {_1} +@msg object {_1} is not in this Intertwine group ez az objektum nincs ebben az összefonási csoportban: {_1} +@msg object {_1} needs a 3D effect ehhez az objektumhoz 3D effektus kell: {_1} +@msg object {_1} needs a 3D effect at index {index} a(z) {_1} objektumhoz 3D effektus kell ennél az indexnél: {index} +@msg object {_1}: a hollow Extrude & Bevel has no caps: turn on Cap to map a graphic {_1} objektum: az üreges Kihúzás és élletörés effektusnak nincsenek fedőlapjai; grafika leképezéséhez kapcsold be a Fedőlap beállítást +@msg object {_1}: with a depth of 0 the object has one face: map its graphics onto the front {_1} objektum: 0 mélységnél az objektumnak egy lapja van; a grafikáit az előlapra képezd le +@msg object {_1}: {_2} {_1} objektum: {_2} +@msg object {_1}: {e} {_1} objektum: {e} +@msg object {_1}: {name} at index {index} has no lighting presets; set its lights with effect.setParams {_1} objektum: a(z) {index} indexű {name} effektusnak nincsenek megvilágítási előbeállításai; a fényeit az effect.setParams paranccsal állítsd be +@msg object {id} has anchors 0–{_1} for `corners`, not {past} a(z) {id} objektum horgonypontjai a `corners` értékhez: 0–{_1}; ilyen nincs: {past} +@msg object {id} has {n} anchors, so no anchor {past} a(z) {id} objektumnak {n} horgonypontja van, ezért ilyen nincs: {past} +@msg objects must be none, move or copy objects: none, move vagy copy kell +@msg objects were left out objektumok maradtak ki +@msg offset out of range az eltolás tartományon kívül esik +@msg on must be true or false on: true vagy false kell +@msg only groups, layers, type and images have a Contents (Characters) row csak a csoportoknak, a rétegeknek, a szövegnek és a képeknek van Tartalom (Karakterek) sora +@msg only interior mesh lines can be deleted csak belső hálóvonalak törölhetők +@msg only solid colours can be added (not gradients or patterns) csak egyszínű színek adhatók hozzá (színátmenetek és mintázatok nem) +@msg only solid-colour swatches can be spot colours csak egyszínű színminták lehetnek direktszínek +@msg only this Affinity file's embedded preview could be read: use File › Open to see it with its warning, or export SVG or PDF from Affinity first ennek az Affinity-fájlnak csak a beágyazott előnézete volt olvasható: a Fájl › Megnyitás paranccsal megnézheted a figyelmeztetésével együtt, vagy előbb exportálj SVG-t vagy PDF-et az Affinityből +@msg only this Affinity file's embedded preview could be read; use File › Open to see it with its warning ennek az Affinity-fájlnak csak a beágyazott előnézete volt olvasható; a Fájl › Megnyitás paranccsal megnézheted a figyelmeztetésével együtt +@msg onto, above, below, icon and a column place belong to window.panel.float and window.panel.dock onto, above, below, icon és az oszlopbeli hely: a window.panel.float és a window.panel.dock parancshoz tartoznak +@msg onto, above, below, icon and a column place take no anchor, side, zone or before onto, above, below, icon és az oszlopbeli hely: nem adható meg mellettük anchor, side, zone vagy before +@msg onto, above, below, icon and a column place take no x, y, width or height onto, above, below, icon és az oszlopbeli hely: nem adható meg mellettük x, y, width vagy height +@msg opacity must be a number opacity: szám kell +@msg open a document to look for its linked files a csatolt fájlok kereséséhez nyiss meg egy dokumentumot +@msg operand too large az operandus túl nagy +@msg options must be an object (see file.formatOptions) options: objektum kell (lásd: file.formatOptions) +@msg order is a whole number from 0 to {others}, not `{v}` order: 0 és {others} közötti egész szám, ez nem az: `{v}` +@msg order must be leftToRight or rightToLeft order: leftToRight vagy rightToLeft kell +@msg orientation must be portrait or landscape, not `{o}` orientation: portrait vagy landscape kell, ez nem az: `{o}` +@msg outlineText {v}: true or false outlineText {v}: true vagy false +@msg output intent profile: {e} kimeneti cél profilja: {e} +@msg output.destination: no RGB or CMYK profile is called “{name}” output.destination: nincs ilyen nevű RGB- vagy CMYK-profil: „{name}” +@msg output.destination: {_1} files are CMYK, and “{name}” is an RGB profile output.destination: a(z) {_1} fájlok CMYK színmódúak, „{name}” pedig RGB-profil +@msg output.destination: {e} output.destination: {e} +@msg output.inks: no ink is set to print output.inks: egyetlen festék sincs nyomtatásra állítva +@msg output.outputIntent: no profile is called “{name}”, and a {std} output intent embeds its profile output.outputIntent: nincs ilyen nevű profil: „{name}”, a(z) {std} kimeneti cél pedig beágyazza a profilját +@msg output.outputIntent: no profile is called “{name}”: a {std} output intent embeds a profile, or names a registered printing condition (outputConditionId and registry) output.outputIntent: nincs ilyen nevű profil: „{name}”; a(z) {std} kimeneti cél beágyaz egy profilt, vagy megnevez egy regisztrált nyomtatási feltételt (outputConditionId és registry) +@msg output.outputIntent: {std} files print in CMYK, and “{name}” is an RGB profile output.outputIntent: a(z) {std} fájlok CMYK-ban nyomtatódnak, „{name}” pedig RGB-profil +@msg output.outputIntent: “{name}” is a grey profile, which can't be a {std} output intent output.outputIntent: „{name}” szürke profil, amely nem lehet {std} kimeneti cél +@msg overlap: {o} pt is half a tile or more overlap: {o} pt egy fél csempe vagy annál több +@msg overlapping Shaper paths must be in the same layer or group az egymást átfedő Alakformáló-útvonalaknak ugyanabban a rétegben vagy csoportban kell lenniük +@msg overlapping edits egymást átfedő szerkesztések +@msg page art conflicts with image data for {key} az oldal grafikája ütközik ennek a képadataival: {key} +@msg page art conflicts with pattern {name} az oldal grafikája ütközik ezzel a mintázattal: {name} +@msg page art conflicts with swatch {name} az oldal grafikája ütközik ezzel a színmintával: {name} +@msg page art is missing image data for {key} az oldal grafikájából hiányoznak ennek a képadatai: {key} +@msg page art is missing pattern {name} az oldal grafikájából hiányzik ez a mintázat: {name} +@msg page art is missing swatch {name} az oldal grafikájából hiányzik ez a színminta: {name} +@msg page must be a whole number from 1 page: 1-től kezdődő egész szám kell +@msg page thumbnail: {e} oldalbélyegkép: {e} +@msg page {page} of the PDF has no objects a PDF {page}. oldalán nincsenek objektumok +@msg page {page}: `{file}` has {n} {artboards} {page}. oldal: `{file}` tartalma: {n} {artboards} +@msg page {page}: `{name}` has {n} {pages} {page}. oldal: `{name}` tartalma: {n} {pages} +@msg pages must be a range such as "2-3" or a page number, not {v} pages: tartomány (például "2-3") vagy oldalszám kell, ez nem az: {v} +@msg pages: {e} pages: {e} +@msg panel position must be finite a panel pozíciója véges érték kell legyen +@msg parameters must be an object parameters: objektum kell +@msg params must be an object params: objektum kell +@msg passwords can have up to {MAX_PASSWORD} bytes a jelszavak legfeljebb {MAX_PASSWORD} bájtosak lehetnek +@msg path chunks must share their boundary point az útvonaldarabok határpontjának közösnek kell lennie +@msg path has no open end az útvonalnak nincs nyitott vége +@msg paths must be strings paths: karakterláncok kellenek +@msg pdfCompatible: false needs every artboard to keep the editable artwork pdfCompatible: false esetén minden rajztábla kell ahhoz, hogy a szerkeszthető grafika megmaradjon +@msg pdfCompatible: false needs the artboards to keep the editable artwork when useArtboards is false pdfCompatible: false esetén a rajztáblák kellenek a szerkeszthető grafika megtartásához, ha a useArtboards értéke false +@msg pdfs `{m}`: single or multiple pdfs `{m}`: single vagy multiple +@msg pickColorFrom is "artwork" or "swatches", not {v} pickColorFrom: "artwork" vagy "swatches", ez nem az: {v} +@msg pins and moved must be non-empty lists of the same length pins és moved: azonos hosszúságú, nem üres listák kellenek +@msg pins must be [[x,y]…] pins: [[x,y]…] kell +@msg pins must be finite pins: véges értékek kellenek +@msg place is above, below or inside, not `{other}` place: above, below vagy inside, ez nem az: `{other}` +@msg plane must be left|right|ground plane: left|right|ground kell +@msg plane must be left|right|ground|none plane: left|right|ground|none kell +@msg point is outside the mesh a pont a hálón kívül esik +@msg point x must be a number a pont x értéke szám kell legyen +@msg point y must be a number a pont y értéke szám kell legyen +@msg points must be [t, left, right] with non-negative widths points: [t, left, right] kell nemnegatív szélességekkel +@msg points must be [x,y] pairs points: [x,y] párok kellenek +@msg points must be a non-empty [[x,y,pressure?]…] list points: nem üres [[x,y,pressure?]…] lista kell +@msg points must be a non-empty list of finite [x,y] points: véges [x,y] értékek nem üres listája kell +@msg points must be an array or null points: tömb vagy null kell +@msg points must be finite points: véges értékek kellenek +@msg points must be finite [x,y] pairs points: véges [x,y] párok kellenek +@msg points must be finite canvas points points: véges vászonpontok kellenek +@msg points must contain 1–4096 coordinates points: 1–4096 koordinátát kell tartalmaznia +@msg position must be normal, superscript or subscript position: normal, superscript vagy subscript kell +@msg position must be topLeft, topRight, bottomLeft or bottomRight position: topLeft, topRight, bottomLeft vagy bottomRight kell +@msg positions must be between 0 and 100000 pt positions: 0 és 100000 pt közötti értékek kellenek +@msg ppi must be a positive number, not {ppi} ppi: pozitív szám kell, ez nem az: {ppi} +@msg ppi must be between 1 and 2400 ppi: 1 és 2400 közötti érték kell +@msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}`: nem transforms|bounds|fileDimensions|fit|fill +@msg preserveShape must be clippingMask|transparency preserveShape: clippingMask|transparency kell +@msg preset `{id}`: mobile or density preset `{id}`: mobile vagy density +@msg preset must be standard, diffuse, topLeft or right preset: standard, diffuse, topLeft vagy right kell +@msg preset must be the name of a print preset preset: egy nyomtatási előbeállítás neve kell +@msg previewMode must be default, pixel or overprint previewMode: default, pixel vagy overprint kell +@msg print settings: {e} nyomtatási beállítások: {e} +@msg procedures nest too deeply az eljárások túl mélyen ágyazódnak egymásba +@msg procedures nested too deeply az eljárások túl mélyen vannak egymásba ágyazva +@msg quotes must be {double?, single?} quotes: {double?, single?} kell +@msg quotes.{k} must be an opening and a closing quote, e.g. "“”" quotes.{k}: egy nyitó és egy záró idézőjel kell, például "“”" +@msg range out of order in character class rossz sorrendű tartomány a karakterosztályban +@msg rasterEffectsPpi must be 1–2400 (72 screen, 150 medium, 300 high) rasterEffectsPpi: 1–2400 kell (72 képernyő, 150 közepes, 300 magas) +@msg rating must be a whole number from 0 to {MAX_RATING} rating: 0 és {MAX_RATING} közötti egész szám kell +@msg rect and {k} contradict each other: give the area or the artboards rect és {k}: ellentmondanak egymásnak; a területet vagy a rajztáblákat add meg +@msg rect applies to raster formats, not {_1} rect: raszteres formátumokra vonatkozik, erre nem: {_1} +@msg rect is [x, y, width, height] in points rect: [x, y, width, height] pontban megadva +@msg rect must be [x, y, width, height] rect: [x, y, width, height] kell +@msg rect must be [x, y, width, height] with a positive width and height rect: [x, y, width, height] kell pozitív szélességgel és magassággal +@msg rect needs finite numbers and a positive width and height rect: véges számok, valamint pozitív szélesség és magasság kell +@msg redraw needs id redraw: id is kell hozzá +@msg redraw within must be a finite distance of 0 or more redraw within: 0 vagy nagyobb véges távolság kell +@msg reduce of an empty array with no initial value reduce hívása üres tömbön, kezdőérték nélkül +@msg registration must be 0..8 registration: 0..8 kell +@msg regular expression flag '{_1}' given twice a reguláris kifejezés jelzője kétszer szerepel: '{_1}' +@msg release a layer or a group réteget vagy csoportot oldj fel +@msg replace keeps the replaced object's place and transform: drop template, at and rect replace: megtartja a lecserélt objektum helyét és transzformációját; hagyd el a template, at és rect értéket +@msg replace: select the one object to replace replace: jelöld ki azt az egy objektumot, amelyet le kell cserélni +@msg resolution must be a number or screen|medium|high resolution: szám vagy screen|medium|high kell +@msg resolution must be between 1 and 2400 ppi resolution: 1 és 2400 ppi közötti érték kell +@msg rotation must be a number of degrees rotation: fokban megadott szám kell +@msg rotation must be finite rotation: véges érték kell +@msg rows and cols must be 1..50 rows és cols: 1..50 kell +@msg rows and columns must be 1..500 rows és columns: 1..500 kell +@msg rows of objects whose appearances differ can't be reordered together eltérő megjelenésű objektumok sorai nem rendezhetők át együtt +@msg sampled text would exceed the canvas (coordinates out of range) a mintavételezett szöveg túllépné a vásznat (a koordináták tartományon kívül esnek) +@msg save the document first: Package collects a saved document előbb mentsd a dokumentumot: a Csomagolás mentett dokumentumot gyűjt össze +@msg save the document first: copy puts the file in its folder előbb mentsd a dokumentumot: a copy a dokumentum mappájába teszi a fájlt +@msg savedPreset: {e} savedPreset: {e} +@msg scale `{s}`: a factor such as 2x, a width (100w), a height (100h) or a resolution (72ppi) scale `{s}`: szorzó (például 2x), szélesség (100w), magasság (100h) vagy felbontás (72ppi) kell +@msg scale must be a number above 0, at most 64 scale: 0-nál nagyobb, legfeljebb 64 értékű szám kell +@msg scale must be non-zero scale: nem lehet nulla +@msg scope must be selection or all (got {other}) scope: selection vagy all kell (kapott érték: {other}) +@msg scribble is too long a firka túl hosszú +@msg segment does not exist a szakasz nem létezik +@msg select a Shaper group jelölj ki egy alakformáló csoportot +@msg select a blend to set easing or color shift a gyorsítás vagy a színeltolás beállításához jelölj ki egy összemosást +@msg select a compound shape jelölj ki egy összetett alakzatot +@msg select a graph jelölj ki egy diagramot +@msg select a group or layer with visible, unlocked members jelölj ki egy csoportot vagy réteget, amelynek látható, nem zárolt tagjai vannak +@msg select a layer jelölj ki egy réteget +@msg select a text object jelölj ki egy szövegobjektumot +@msg select an SVG filter jelölj ki egy SVG-szűrőt +@msg select an image (or an Image Trace group) jelölj ki egy képet (vagy egy képvektorizálási csoportot) +@msg select an image, or pass id jelölj ki egy képet, vagy add meg az id értéket +@msg select an object (or pass `id`) jelölj ki egy objektumot (vagy add meg az `id` értéket) +@msg select an object with a 3D effect jelölj ki egy 3D effektussal rendelkező objektumot +@msg select an object with a 3D effect, or give its id in ids jelölj ki egy 3D effektussal rendelkező objektumot, vagy add meg az azonosítóját az ids értékben +@msg select an object with a freeform gradient jelölj ki egy szabad formájú színátmenettel rendelkező objektumot +@msg select an object with an opacity mask jelölj ki egy átlátszósági maszkkal rendelkező objektumot +@msg select area type jelölj ki területszöveget +@msg select area type (text in a frame) jelölj ki területszöveget (keretben lévő szöveget) +@msg select area type and closed paths (at least one area type object) jelölj ki területszöveget és zárt útvonalakat (legalább egy területszöveg-objektumot) +@msg select area type whose first line can fit its frame jelölj ki olyan területszöveget, amelynek az első sora elfér a keretében +@msg select artwork to add its colours jelölj ki grafikát a színei hozzáadásához +@msg select artwork to make a group of its colours jelölj ki grafikát, hogy a színeiből csoport készüljön +@msg select artwork to recolour, or give a colour `group` jelölj ki átszínezendő grafikát, vagy adj meg színcsoportot a `group` értékben +@msg select exactly two path ends to join pontosan két összekapcsolandó útvonalvéget jelölj ki +@msg select members of a compound shape jelöld ki egy összetett alakzat tagjait +@msg select objects or give ids jelölj ki objektumokat, vagy add meg az ids értéket +@msg select objects to align to the guide jelöld ki a segédvonalhoz igazítandó objektumokat +@msg select one Intertwine group egyetlen összefonási csoportot jelölj ki +@msg select one image or pass id egyetlen képet jelölj ki, vagy add meg az id értéket +@msg select one layer, group or object to rename egyetlen átnevezendő réteget, csoportot vagy objektumot jelölj ki +@msg select paths jelölj ki útvonalakat +@msg select paths or compound paths jelölj ki útvonalakat vagy összetett útvonalakat +@msg select rows or objects to collect jelöld ki az összegyűjtendő sorokat vagy objektumokat +@msg select something to export jelölj ki valamit az exportáláshoz +@msg select something to export (or turn off selectedOnly) jelölj ki valamit az exportáláshoz (vagy kapcsold ki a selectedOnly beállítást) +@msg select text to redefine the style from jelölj ki szöveget, amelyből a stílus újradefiniálható +@msg select the art and, on top of it, the mask object jelöld ki a grafikát és a fölötte lévő maszkobjektumot +@msg select the art for the design jelöld ki a diagrammintához szánt grafikát +@msg select the art for the pattern tile jelöld ki a mintacsempéhez szánt grafikát +@msg select the art to add first előbb jelöld ki a hozzáadandó grafikát +@msg select the art to collect (or give its ids) jelöld ki az összegyűjtendő grafikát (vagy add meg az azonosítóit) +@msg select the art to weed jelöld ki a gyomlálandó grafikát +@msg select the content and a path on top jelöld ki a tartalmat és egy fölötte lévő útvonalat +@msg select the images to relink, or pass ids jelöld ki az újracsatolandó képeket, vagy add meg az ids értéket +@msg select the images, or pass ids jelöld ki a képeket, vagy add meg az ids értéket +@msg select the linked images or placed documents, or pass ids jelöld ki a csatolt képeket vagy az elhelyezett dokumentumokat, vagy add meg az ids értéket +@msg select the object to copy from jelöld ki azt az objektumot, amelyről a másolás történjen +@msg select the objects (or give their ids) jelöld ki az objektumokat (vagy add meg az azonosítóikat) +@msg select the objects to attach to the path jelöld ki az útvonalhoz csatolandó objektumokat +@msg select the objects to bind jelöld ki a kötendő objektumokat +@msg select two or more objects to intertwine jelölj ki két vagy több összefonandó objektumot +@msg select two or more slices to combine jelölj ki két vagy több egyesítendő szeletet +@msg select type on a path jelölj ki útvonalszöveget +@msg select type on a path or area type jelölj ki útvonalszöveget vagy területszöveget +@msg selection `{m}`: one or each selection `{m}`: one vagy each +@msg settings is an object of document.exportForScreens params settings: a document.exportForScreens paramétereiből álló objektum +@msg settings must be an object settings: objektum kell +@msg show `{show}`: all, missing, modified or embedded show `{show}`: all, missing, modified vagy embedded +@msg show must be true or false show: true vagy false kell +@msg side is left or right, not `{v}` side: left vagy right, ez nem az: `{v}` +@msg size must be "small", "medium", "large" or a number of points over 0 up to {_1} size: "small", "medium", "large" vagy 0-nál nagyobb, legfeljebb {_1} pontérték kell +@msg size must be positive size: pozitív érték kell +@msg sizeMode is "fixed" or "pressure", not `{other}` sizeMode: "fixed" vagy "pressure", ez nem az: `{other}` +@msg sizeMode is "fixed" or "pressure", not {other} sizeMode: "fixed" vagy "pressure", ez nem az: {other} +@msg sizeVariation must be 0 or more sizeVariation: 0 vagy nagyobb érték kell +@msg smallCaps must be true or false smallCaps: true vagy false kell +@msg sort `{x}`: name, kind or status sort `{x}`: name, kind vagy status +@msg source paths are too large for Shaper a forrásútvonalak túl nagyok az Alakformálóhoz +@msg source text transform is collapsed or unrepresentable a forrásszöveg transzformációja összeesett vagy nem ábrázolható +@msg spot, mode and group apply to solid colours only spot, mode és group: csak egyszínű színekre vonatkozik +@msg status `{s}`: linked, embedded, missing or modified status `{s}`: linked, embedded, missing vagy modified +@msg steps must be 1..1000 steps: 1..1000 kell +@msg steps must be 1..{MAX_STEPS} steps: 1..{MAX_STEPS} kell +@msg stop {i}: `plates` must be four numbers from 0 to 1 (C, M, Y, K) {i}. színátmenetpont: `plates`: négy 0 és 1 közötti szám kell (C, M, Y, K) +@msg stopped before the archive was finished leállt, mielőtt az archívum elkészült volna +@msg strokeMode must be within|along|across, got {m} strokeMode: within|along|across kell, kapott érték: {m} +@msg strokeOptions must be an object of stroke.set options strokeOptions: a stroke.set beállításaiból álló objektum kell +@msg strokeWidth must be a positive number of pixels strokeWidth: képpontban megadott pozitív szám kell +@msg subpath {si} is not an open subpath ez a részútvonal nem nyitott: {si} +@msg subpaths required when joining the same path ugyanazon útvonal összekapcsolásakor a subpaths kötelező +@msg swatchConflict must be "merge" or "add", not {v} swatchConflict: "merge" vagy "add" kell, ez nem az: {v} +@msg table must be true or false table: true vagy false kell +@msg takes one name egy nevet fogad +@msg target text transform is collapsed or unrepresentable a célszöveg transzformációja összeesett vagy nem ábrázolható +@msg text must be {characterSet?, platform?, removeLineReturns?, removeParagraphReturns?, replaceSpaces?} text: {characterSet?, platform?, removeLineReturns?, removeParagraphReturns?, replaceSpaces?} kell +@msg text transform is collapsed or unrepresentable a szöveg transzformációja összeesett vagy nem ábrázolható +@msg text.replaceSpaces must be a whole number from 2 to 100 text.replaceSpaces: 2 és 100 közötti egész szám kell +@msg text.{key} `{v}`: use "{_1}" or "{_2}" text.{key} `{v}`: a "{_1}" vagy a "{_2}" értéket használd +@msg textureImage: give {path} or {name, dataBase64} of an image file, or a texture as effect.list gives it textureImage: add meg egy képfájl {path} vagy {name, dataBase64} értékét, vagy egy textúrát úgy, ahogy az effect.list megadja +@msg textureImage: {e} textureImage: {e} +@msg that makes more than {MAX_PIECES} slices ez több mint {MAX_PIECES} szeletet eredményezne +@msg that makes too many pieces (at most 100000) or dash steps: simplify the dash pattern or make the dashes longer ez túl sok darabot (legfeljebb 100000) vagy szaggatási lépést eredményezne: egyszerűsítsd a szaggatási mintát, vagy növeld a vonalkák hosszát +@msg that object is not in the overlap ez az objektum nincs az átfedésben +@msg the Affinity document has no page with a size az Affinity-dokumentumban nincs mérettel rendelkező oldal +@msg the CMYK image couldn't be written a CMYK-képet nem sikerült kiírni +@msg the Layers panel is not shown a Rétegek panel nem látható +@msg the Layers panel's search, filter or Show Layers Only hides its row a Rétegek panel keresése, szűrője vagy a Csak rétegek megjelenítése beállítás elrejti a sorát +@msg the Objects on Path group is hidden or locked az Objektumok útvonalon csoport rejtett vagy zárolt +@msg the PDF security settings were saved without their passwords: give openPassword or permissionsPassword again, or security without passwordRequired to export unprotected a PDF biztonsági beállításai a jelszavak nélkül lettek mentve: add meg újra az openPassword vagy a permissionsPassword értéket, vagy a védelem nélküli exportáláshoz a security értéket passwordRequired nélkül +@msg the RTF file has too many paragraphs or formatting changes to place as type (at most {MAX_PARAGRAPHS} paragraphs and {MAX_RUNS} runs) az RTF-fájlban túl sok a bekezdés vagy a formázásváltás ahhoz, hogy szövegként elhelyezhető legyen (legfeljebb {MAX_PARAGRAPHS} bekezdés és {MAX_RUNS} szövegrész) +@msg the RTF file is too large to place as type (at most {_1} MB) az RTF-fájl túl nagy ahhoz, hogy szövegként elhelyezhető legyen (legfeljebb {_1} MB) +@msg the SVG expands to more than {0} nested SVG images az SVG kibontva több mint {0} beágyazott SVG-képet tartalmaz +@msg the SVG expands to more than {0} objects az SVG kibontva több mint {0} objektumot tartalmaz +@msg the SVG's style sheets take too long to match az SVG stíluslapjainak illesztése túl sokáig tart +@msg the SVG's styles expand to more than {0} MB az SVG stílusai kibontva több mint {0} MB-ot foglalnak +@msg the SVG file is larger than {MAX_IMPORT_BYTES} bytes az SVG-fájl nagyobb, mint {MAX_IMPORT_BYTES} bájt +@msg the SVG has no drawable objects az SVG-ben nincsenek kirajzolható objektumok +@msg the SVGZ file unpacks to more than {_1} MB az SVGZ-fájl kicsomagolva nagyobb, mint {_1} MB +@msg the Word document has more than {MAX_PAGES} pages of properties, too many to place a Word-dokumentumban több mint {MAX_PAGES} oldalnyi tulajdonság van, ez túl sok az elhelyezéshez +@msg the Word document has more than {MAX_RUNS} runs of character or paragraph properties, too many to place a Word-dokumentumban több mint {MAX_RUNS} karakter- vagy bekezdéstulajdonság-szakasz van, ez túl sok az elhelyezéshez +@msg the Word document has more than {_1} MB of formatting properties, too many to place a Word-dokumentumban több mint {_1} MB formázási tulajdonság van, ez túl sok az elhelyezéshez +@msg the Word document has too much text or formatting to place as type (at most {MAX_PARAGRAPHS} paragraphs, {MAX_RUNS} runs and {_1} MB of text) a Word-dokumentumban túl sok a szöveg vagy a formázás ahhoz, hogy szövegként elhelyezhető legyen (legfeljebb {MAX_PARAGRAPHS} bekezdés, {MAX_RUNS} szövegrész és {_1} MB szöveg) +@msg the Word document has too much text to place as type (at most {_1} MB) a Word-dokumentumban túl sok a szöveg ahhoz, hogy szövegként elhelyezhető legyen (legfeljebb {_1} MB) +@msg the Word document is encrypted or protected with a password; save it without one to place it a Word-dokumentum titkosított vagy jelszóval védett; az elhelyezéshez mentsd jelszó nélkül +@msg the Word document is too large to place (its {name} stream holds more than {_1} MB) a Word-dokumentum túl nagy az elhelyezéshez (a(z) {name} adatfolyama több mint {_1} MB) +@msg the Word document was last saved with fast save, which VectorCraft doesn't read; save it again with fast save turned off a Word-dokumentum utoljára gyorsmentéssel lett mentve, amelyet a VectorCraft nem olvas; mentsd újra kikapcsolt gyorsmentéssel +@msg the Word document was saved by Word 6.0 or Word 95, which VectorCraft doesn't read; save it as a Word 97-2003 document a Word-dokumentumot a Word 6.0 vagy a Word 95 mentette, ezt a VectorCraft nem olvassa; mentsd Word 97-2003 dokumentumként +@msg the Word document's text is made of more than {MAX_PIECES} pieces, too many to place a Word-dokumentum szövege több mint {MAX_PIECES} darabból áll, ez túl sok az elhelyezéshez +@msg the XML operation needs an XML or XMLList value az XML-művelethez XML vagy XMLList érték kell +@msg the XPath expression does not evaluate to a node-set az XPath-kifejezés eredménye nem csomóponthalmaz +@msg the XPath expression ends early az XPath-kifejezés túl korán ér véget +@msg the XPath expression has an unmatched ) az XPath-kifejezésben pár nélküli ) van +@msg the XPath expression has an unmatched ] az XPath-kifejezésben pár nélküli ] van +@msg the XPath expression has an unmatched closing bracket az XPath-kifejezésben pár nélküli záró zárójel van +@msg the XPath expression selects a namespace node, which is not an XML value az XPath-kifejezés névtércsomópontot jelöl ki, amely nem XML-érték +@msg the XPath expression selects the root node, which is not an XML value az XPath-kifejezés a gyökércsomópontot jelöli ki, amely nem XML-érték +@msg the XPath function {name} needs a node-set ehhez az XPath-függvényhez csomóponthalmaz kell: {name} +@msg the XPath function {name} takes the wrong number of arguments ez az XPath-függvény nem megfelelő számú argumentumot kapott: {name} +@msg the XPath name functions need a node-set az XPath névfüggvényeihez csomóponthalmaz kell +@msg the XPath prefix {shown} is not bound to a namespace ez az XPath-előtag nincs névtérhez kötve: {shown} +@msg the XPath variable ${shown} is not bound ez az XPath-változó nincs kötve: ${shown} +@msg the action set ids are not a list a műveletkészlet-azonosítók nem alkotnak listát +@msg the active paint is not a gradient az aktív festés nem színátmenet +@msg the argument list is not an object az argumentumlista nem objektum +@msg the artboards don't fit on the canvas: fewer artboards, less spacing or a smaller size a rajztáblák nem férnek el a vásznon: kevesebb rajztábla, kisebb térköz vagy kisebb méret kell +@msg the artwork is too large for EPS: what follows 256 MB of PostScript was left out a grafika túl nagy az EPS-hez: ami 256 MB PostScript után következik, az kimaradt +@msg the bitmaps hold more pixels than one file may a bitképek több képpontot tartalmaznak, mint amennyi egy fájlban megengedett +@msg the character's size can't be measured a karakter mérete nem mérhető meg +@msg the code runs past its last instruction a kód túlfut az utolsó utasításán +@msg the compound shape is too complex to expand az összetett alakzat túl bonyolult a kibontáshoz +@msg the container of the listed objects is gone a felsorolt objektumok tárolója már nincs meg +@msg the copy `{user_id}` can't be read as a library a másolat nem olvasható be könyvtárként: `{user_id}` +@msg the copy would leave the canvas a másolat kikerülne a vászonról +@msg the curve tolerance must be from 0.01 to 10 points a görbetűrés 0,01 és 10 pont között lehet +@msg the custom dictionary couldn't be saved to {_1}: {e} az egyéni szótárat nem sikerült ide menteni: {_1}: {e} +@msg the custom dictionary {_1} can't be read ({why}), so it is left as it is az egyéni szótár nem olvasható: {_1} ({why}), ezért változatlan marad +@msg the cut cannot be made on this art: {e} a vágás ezen a grafikán nem végezhető el: {e} +@msg the data isn't an EMF or WMF picture az adatok nem EMF- vagy WMF-képet alkotnak +@msg the data isn't an EPS or PostScript picture az adatok nem EPS- vagy PostScript-képet alkotnak +@msg the deferred paste is no longer available a halasztott beillesztés már nem érhető el +@msg the design is too big to draw at every data point of this graph a diagramminta túl nagy ahhoz, hogy a diagram minden adatpontjánál kirajzolható legyen +@msg the design is too big to draw in every column of this graph a diagramminta túl nagy ahhoz, hogy a diagram minden oszlopában kirajzolható legyen +@msg the dialog it was opened over is no longer open a párbeszédablak, amely fölött megnyílt, már nincs nyitva +@msg the dictionary stack overflowed a szótárverem túlcsordult +@msg the document already has an SVG filter named {name} a dokumentumban már van ilyen nevű SVG-szűrő: {name} +@msg the document has another SVG filter named {name}: use svgFilter.apply, or svgFilter.define with `replace` to edit it a dokumentumban van egy másik ilyen nevű SVG-szűrő: {name}; használd az svgFilter.apply parancsot, vagy a szerkesztéséhez az svgFilter.define parancsot a `replace` értékkel +@msg the document has no SVG filter named {name} a dokumentumban nincs ilyen nevű SVG-szűrő: {name} +@msg the document has no SVG filter named {r} a dokumentumban nincs ilyen nevű SVG-szűrő: {r} +@msg the document has no color swatches a dokumentumban nincsenek színes színminták +@msg the document's swatches hold {_1} colors; the document reduction takes at most 255 a dokumentum színmintái {_1} színt tartalmaznak; a document színcsökkentés legfeljebb 255-öt fogad +@msg the editing data's hash has no place a szerkesztési adatok kivonatának nincs helye +@msg the entities the document declares expand to too much text a dokumentumban deklarált entitások túl sok szöveggé bomlanak ki +@msg the envelope's content has no bounds a burkoló tartalmának nincsenek határai +@msg the envelope's mesh is malformed a burkoló hálója hibás szerkezetű +@msg the file holds no `variableSets` element a fájlban nincs `variableSets` elem +@msg the file is larger than {_1} MB a fájl nagyobb, mint {_1} MB +@msg the file is too large a fájl túl nagy +@msg the file isn't valid SVG: {e} a fájl nem érvényes SVG: {e} +@msg the file names no plate a fájl nem nevez meg színkivonatot +@msg the file was updated or encrypted already a fájl már frissítve vagy titkosítva lett +@msg the first character of a line has no character before it to kern: it moves only up and down (dy) a sor első karaktere előtt nincs karakter, amelyhez alávágható lenne: csak felfelé és lefelé mozdul (dy) +@msg the font {_1} is not available ez a betűtípus nem érhető el: {_1} +@msg the format has no file extension a formátumnak nincs fájlkiterjesztése +@msg the function's prototype is not an object a függvény prototípusa nem objektum +@msg the graphic can't be read: {e} a grafika nem olvasható: {e} +@msg the graphic is empty a grafika üres +@msg the graphic's data is damaged a grafika adatai sérültek +@msg the graphic's document has no artboard a grafika dokumentumában nincs rajztábla +@msg the guide is hidden or locked a segédvonal rejtett vagy zárolt +@msg the header `{cell}` for `{name}` would read back as the variable `{other}`: rename one of them a(z) `{name}` változó `{cell}` fejléce a(z) `{other}` változóként olvasódna vissza: nevezd át az egyiket +@msg the image `{path}` isn't followed: {r} a kép nem lesz követve: `{path}`: {r} +@msg the image has no embedded pixels a képnek nincsenek beágyazott képpontjai +@msg the image is empty a kép üres +@msg the image is fully transparent a kép teljesen átlátszó +@msg the image is not on an artboard; pass rect a kép nincs rajztáblán; add meg a rect értéket +@msg the image's pixels are missing a kép képpontjai hiányoznak +@msg the image's pixels aren't in the document a kép képpontjai nincsenek a dokumentumban +@msg the image's pixels can't be read: {e} a kép képpontjai nem olvashatók: {e} +@msg the image's transparency doesn't fit it a kép átlátszósága nem illik a képhez +@msg the job would print more than {MAX_PAGES} pages a feladat több mint {MAX_PAGES} oldalt nyomtatna +@msg the job would print more than {_1} pages a feladat több mint {_1} oldalt nyomtatna +@msg the layers hold no art to mask a rétegekben nincs maszkolható grafika +@msg the layout moved az elrendezés elmozdult +@msg the library has a group `{name}` already a könyvtárban már van ilyen csoport: `{name}` +@msg the library has no group `{name}` a könyvtárban nincs ilyen csoport: `{name}` +@msg the library has no item `{item}` a könyvtárban nincs ilyen elem: `{item}` +@msg the library has no item `{other}` a könyvtárban nincs ilyen elem: `{other}` +@msg the library holds {MAX_GROUPS} groups already a könyvtár már {MAX_GROUPS} csoportot tartalmaz +@msg the library holds {MAX_ITEMS} items of this kind already a könyvtár már {MAX_ITEMS} ilyen fajta elemet tartalmaz +@msg the library's file is outside the read roots a könyvtár fájlja kívül esik az olvasási gyökereken +@msg the line is too long, or the paths it passes too many, to check a vonal túl hosszú, vagy túl sok útvonalon halad át az ellenőrzéshez +@msg the method needs an XML value a metódushoz XML-érték kell +@msg the name is empty a név üres +@msg the object has no fill, stroke or effect az objektumnak nincs kitöltése, körvonala vagy effektusa +@msg the object has no graphic style (pass `name`) az objektumnak nincs grafikai stílusa (add meg a `name` értéket) +@msg the objects don't match the plan az objektumok nem egyeznek a tervvel +@msg the open and permissions passwords must differ a megnyitási és a jogosultsági jelszónak különböznie kell +@msg the operand stack overflowed az operandusverem túlcsordult +@msg the page has no area az oldalnak nincs területe +@msg the page's type in an unread object's box isn't in its page art az oldal egy be nem olvasott objektum keretében lévő szövege nincs benne az oldal grafikájában +@msg the paint behind the proxy is not a gradient a mintadoboz mögötti festés nem színátmenet +@msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) a festés nem szabad formájú színátmenet (alkalmazz egyet a paint.editGradient {kind} paranccsal) +@msg the parameters or body do not form one function a paraméterek vagy a törzs nem alkotnak egyetlen függvényt +@msg the parent must be a layer or sublayer a szülő réteg vagy alréteg kell legyen +@msg the pasted SVG filter {name} draws differently from the document's filter of that name, and no free name fits it a beillesztett SVG-szűrő ({name}) másképp rajzol, mint a dokumentum azonos nevű szűrője, és nem jut neki szabad név +@msg the path can't be extended az útvonal nem hosszabbítható meg +@msg the path can't be inside one of the objects to attach az útvonal nem lehet az egyik csatolandó objektum belsejében +@msg the path has no segments to measure az útvonalnak nincs mérhető szakasza +@msg the path is empty az útvonal üres +@msg the path is too short to shorten that much az útvonal túl rövid ahhoz, hogy ennyivel rövidíthető legyen +@msg the paths are too many or too tangled to find where they cross túl sok az útvonal, vagy túlságosan összegabalyodtak ahhoz, hogy a metszéspontjaik megtalálhatók legyenek +@msg the pen table holds more than 255 pens a tolltábla több mint 255 tollat tartalmaz +@msg the picture has no objects az ábrán nincsenek objektumok +@msg the plates can't be kept a színkivonatok nem tarthatók meg +@msg the position table does not match the instructions a pozíciótábla nem egyezik az utasításokkal +@msg the program runs too long a program túl sokáig fut +@msg the program uses too much memory a program túl sok memóriát használ +@msg the prompt's text is longer than {MAX_PROMPT_BYTES} bytes a bekérés szövege hosszabb {MAX_PROMPT_BYTES} bájtnál +@msg the radix must be between 2 and 36 a számrendszer alapja 2 és 36 között lehet +@msg the rectangle must have a width and a height a téglalapnak szélesség és magasság kell +@msg the rectangle needs a size and must lie on the canvas a téglalapnak méret kell, és a vásznon kell lennie +@msg the rectangle or line reaches too many paths to check a téglalap vagy a vonal túl sok útvonalat ér el az ellenőrzéshez +@msg the right side of 'in' is not an object az 'in' jobb oldala nem objektum +@msg the right side of 'instanceof' is not a function az 'instanceof' jobb oldala nem függvény +@msg the selected art has no width a kijelölt grafikának nincs szélessége +@msg the selected art is nested more than {MAX_DEPTH} levels deep a kijelölt grafika {MAX_DEPTH} szintnél mélyebben van egymásba ágyazva +@msg the selected art is too large to measure a kijelölt grafika túl nagy a méréshez +@msg the selection draws nothing a kijelölés semmit sem rajzol ki +@msg the selection has no area a kijelölésnek nincs területe +@msg the selection has no art to export a kijelölésben nincs exportálható grafika +@msg the selection has no bounds a kijelölésnek nincsenek határai +@msg the selection has no graphic style a kijelölésnek nincs grafikai stílusa +@msg the selection has no outlines to weed around a kijelölésnek nincs körvonala, amely körül gyomlálni lehetne +@msg the slice would leave the canvas a szelet kikerülne a vászonról +@msg the spot colour couldn't be added a direktszínt nem sikerült hozzáadni +@msg the subpath has no ends to extend (it is closed or a single point) a részútvonalnak nincs meghosszabbítható vége (zárt, vagy egyetlen pontból áll) +@msg the symbols are nested too deeply to expand their instances a szimbólumok túl mélyen vannak egymásba ágyazva a példányaik kibontásához +@msg the text file is too large to place as type (at most {_1} MB) a szövegfájl túl nagy ahhoz, hogy szövegként elhelyezhető legyen (legfeljebb {_1} MB) +@msg the text is empty a szöveg üres +@msg the text is over {_1} MB a szöveg nagyobb, mint {_1} MB +@msg the top object must be a path a legfelső objektum útvonal kell legyen +@msg the trace was cancelled a vektorizálás megszakítva +@msg the trailer has no size a trailernek nincs mérete +@msg the type object is flattened to nothing a szövegobjektumból a lapítás után semmi sem marad +@msg the value bind was called on is not a function az érték, amelyen a bind hívása történt, nem függvény +@msg the value is not a constructor az érték nem konstruktor +@msg the value is not a function az érték nem függvény +@msg the value is not a valid XML name az érték nem érvényes XML-név +@msg the value is not an XML attribute name az érték nem XML-attribútumnév +@msg the value is not an XML name az érték nem XML-név +@msg the value of axis `{tag}` must be a number or null a(z) `{tag}` tengely értéke szám vagy null lehet +@msg the variable library declares more than {MAX_LIBRARY_DATASETS} data sets a változókönyvtár több mint {MAX_LIBRARY_DATASETS} adatkészletet deklarál +@msg the variable library declares more than {MAX_LIBRARY_ENTITIES} entities a változókönyvtár több mint {MAX_LIBRARY_ENTITIES} entitást deklarál +@msg the variable library declares more than {MAX_LIBRARY_VARIABLES} variables a változókönyvtár több mint {MAX_LIBRARY_VARIABLES} változót deklarál +@msg the variable library declares no variables a változókönyvtár nem deklarál változókat +@msg the variable library is larger than {MAX_LIBRARY_BYTES} bytes a változókönyvtár nagyobb, mint {MAX_LIBRARY_BYTES} bájt +@msg the variable library is not UTF-8 a változókönyvtár nem UTF-8 kódolású +@msg the variable library is not well-formed XML: {e} a változókönyvtár nem jól formált XML: {e} +@msg the variable library nests elements more than {MAX_LIBRARY_NESTING} deep a változókönyvtár elemei {MAX_LIBRARY_NESTING} szintnél mélyebben vannak egymásba ágyazva +@msg the variable library's document type declaration holds something other than entities of plain text a változókönyvtár dokumentumtípus-deklarációja mást is tartalmaz, mint egyszerű szöveges entitásokat +@msg the variable library's entities expand to more than {MAX_LIBRARY_BYTES} bytes a változókönyvtár entitásai kibontva nagyobbak, mint {MAX_LIBRARY_BYTES} bájt +@msg the weeding lines cross the art's outlines too many times to measure; use fewer lines a gyomlálóvonalak túl sokszor metszik a grafika körvonalait a méréshez; használj kevesebb vonalat +@msg the weeding lines pass too close to too many outline segments to measure; use fewer lines or a smaller gap a gyomlálóvonalak túl sok körvonalszakaszhoz haladnak túl közel a méréshez; használj kevesebb vonalat vagy kisebb hézagot +@msg the weeding lines would be more than {max_pieces} pieces a gyomlálóvonalak több mint {max_pieces} darabból állnának +@msg the window has no dock az ablaknak nincs dokkja +@msg the written PDF has no catalog a kiírt PDF-nek nincs katalógusa +@msg the written PDF has no cross-reference table a kiírt PDF-nek nincs kereszthivatkozási táblája +@msg the written PDF's metadata can't be edited a kiírt PDF metaadatai nem szerkeszthetők +@msg the {_1} plate lies outside the file ez a színkivonat a fájlon kívül esik: {_1} +@msg there are no colour swatches to draw nincs kirajzolható színes színminta +@msg there is already a design named `{name}` már van ilyen nevű diagramminta: `{name}` +@msg there is already a design named `{to}` már van ilyen nevű diagramminta: `{to}` +@msg there is already a toolbar named `{name}` már van ilyen nevű eszköztár: `{name}` +@msg there is already a toolbar named `{to}` már van ilyen nevű eszköztár: `{to}` +@msg there is no library: create one first nincs könyvtár: előbb hozz létre egyet +@msg these paths are too degenerate for Shaper ezek az útvonalak túlságosan elfajultak az Alakformálóhoz +@msg this is a binary DXF file, which can't be read: save it from the CAD app as an ASCII DXF and open that ez bináris DXF-fájl, amely nem olvasható: mentsd ASCII DXF-ként a CAD-alkalmazásból, és azt nyisd meg +@msg this warp's points can't be edited: use Reset with Mesh first ennek a hajlításnak a pontjai nem szerkeszthetők: előbb használd a Visszaállítás hálóval parancsot +@msg thumbnail: no page {v} (the {what} has {count}) bélyegkép: nincs ilyen oldal: {v} (a(z) {what} oldalszáma: {count}) +@msg tileRange of {what}: {e} tileRange ({what}): {e} +@msg title can't be empty title: nem lehet üres +@msg to (the new name) is required to (az új név): kötelező +@msg to must be fill or stroke to: fill vagy stroke kell +@msg to must be smooth or corner to: smooth vagy corner kell +@msg toExponential() digits must be between 0 and 20 toExponential(): a számjegyek száma 0 és 20 között lehet +@msg toFixed() digits must be between 0 and 20 toFixed(): a számjegyek száma 0 és 20 között lehet +@msg toISOString is not a function a toISOString nem függvény +@msg toPrecision() argument must be between 1 and 21 toPrecision(): az argumentum 1 és 21 között lehet +@msg toSource: a getter cannot be written as source toSource: getter nem írható ki forrásként +@msg toSource: an array with properties besides its elements, a property that is not enumerable or another prototype cannot be written as source toSource: nem írható ki forrásként az a tömb, amelynek az elemein kívül tulajdonságai is vannak, nem felsorolható tulajdonsága van, vagy más a prototípusa +@msg toSource: an object with a property that is not enumerable, or whose prototype is not Object.prototype, cannot be written as source toSource: nem írható ki forrásként az az objektum, amelynek nem felsorolható tulajdonsága van, vagy a prototípusa nem Object.prototype +@msg toSource: the source is too long toSource: a forrás túl hosszú +@msg toSource: the value contains itself toSource: az érték önmagát tartalmazza +@msg toSource: the value has too many entries toSource: az érték túl sok elemet tartalmaz +@msg toSource: the value is nested too deep toSource: az érték túl mélyen van egymásba ágyazva +@msg toString is not a function a toString nem függvény +@msg too large for a zip archive: package to a folder túl nagy egy zip-archívumhoz: csomagolj mappába +@msg too many Shaper edits túl sok Alakformáló-szerkesztés +@msg too many `points` (at most 100000) túl sok `points` elem (legfeljebb 100000) +@msg too many arguments túl sok argumentum +@msg too many characters: at most {MAX_CHARS} túl sok karakter: legfeljebb {MAX_CHARS} +@msg too many dots for this size: lower the frequency túl sok raszterpont ehhez a mérethez: csökkentsd a vonalsűrűséget +@msg too many filters over one file túl sok szűrő egyetlen fájlon +@msg too many overlapping paths for Shaper túl sok egymást átfedő útvonal az Alakformálóhoz +@msg too many quantifiers túl sok kvantor +@msg too many saved clips túl sok mentett vágóútvonal +@msg too many saved graphics states túl sok mentett grafikus állapot +@msg toolbar (a toolbar's name) must be a string toolbar (egy eszköztár neve): karakterlánc kell +@msg toolbar name can't be empty az eszköztár neve nem lehet üres +@msg transparentImages {v}: "flatten" (the default) or "omit" transparentImages {v}: "flatten" (ez az alapértelmezés) vagy "omit" +@msg two saved selections would be named `{_1}` két mentett kijelölés neve lenne ugyanaz: `{_1}` +@msg type dimension cannot be represented with this text transform a szövegméret nem ábrázolható ezzel a szövegtranszformációval +@msg type dimension must be finite a szövegméret véges érték kell legyen +@msg unexpected resources váratlan erőforrások +@msg unknown CMYK profile `{name}` ismeretlen CMYK-profil: `{name}` +@msg unknown File Info field `{k}` ismeretlen fájlinformációs mező: `{k}` +@msg unknown OpenType feature `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt; prefix - to turn off; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take an alternate's number as `tag=N` with N from 0 to {_1}, as `salt=2`) ismeretlen OpenType-funkció: `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt; a - előtag kikapcsolja; a swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom és aalt egy alternatíva számát `tag=N` alakban fogadja, ahol N 0 és {_1} között lehet, például `salt=2`) +@msg unknown OpenType feature `{t}` in featureChanges (the tags `features` takes) ismeretlen OpenType-funkció a featureChanges értékben: `{t}` (a `features` által fogadott címkék használhatók) +@msg unknown PDF preset `{name}` (presets: {_1}) ismeretlen PDF-előbeállítás: `{name}` (előbeállítások: {_1}) +@msg unknown Warp style ismeretlen hajlítási stílus +@msg unknown alignToPath `{a}` ismeretlen alignToPath: `{a}` +@msg unknown arrowhead {v} ismeretlen nyílhegy: {v} +@msg unknown artboardLayout key `{k}` (layout, columns, spacing, rightToLeft) ismeretlen artboardLayout kulcs: `{k}` (layout, columns, spacing, rightToLeft) +@msg unknown attribute `{attribute}` ismeretlen attribútum: `{attribute}` +@msg unknown attribute `{k}` ismeretlen attribútum: `{k}` +@msg unknown axis `{other}` (vertical|horizontal|free) ismeretlen tengely: `{other}` (vertical|horizontal|free) +@msg unknown blend mode `{b}` ismeretlen keverési mód: `{b}` +@msg unknown blend mode {b} ismeretlen keverési mód: {b} +@msg unknown brush type `{o}` ismeretlen ecsettípus: `{o}` +@msg unknown category `{c}` ismeretlen kategória: `{c}` +@msg unknown category `{c}` ({_1}) ismeretlen kategória: `{c}` ({_1}) +@msg unknown character `{c}` ismeretlen karakter: `{c}` +@msg unknown character style number field ismeretlen karakterstílus-számmező +@msg unknown dither `{d}` (diffusion, pattern, noise or none) ismeretlen dither: `{d}` (diffusion, pattern, noise vagy none) +@msg unknown effect `{e}` ismeretlen effektus: `{e}` +@msg unknown end {e} ismeretlen end: {e} +@msg unknown flattenerPreset `{name}` (High Resolution, Medium Resolution, Low Resolution or a saved one: see flattener.presets.list) ismeretlen flattenerPreset: `{name}` (High Resolution, Medium Resolution, Low Resolution vagy egy mentett előbeállítás: lásd: flattener.presets.list) +@msg unknown format `{f}` (vcswatches, gpl, ase or css) ismeretlen formátum: `{f}` (vcswatches, gpl, ase vagy css) +@msg unknown from {f} ismeretlen from: {f} +@msg unknown graph type `{t}` ismeretlen diagramtípus: `{t}` +@msg unknown grid colours `{name}` (one of {_1}) ismeretlen rácsszínek: `{name}` (ezek egyike kell: {_1}) +@msg unknown gridType `{t}` ismeretlen gridType: `{t}` +@msg unknown highlight `{v}` ismeretlen highlight: `{v}` +@msg unknown intent `{i}` ismeretlen intent: `{i}` +@msg unknown issue kind {id} ismeretlen problémafajta: {id} +@msg unknown issue kind {v} ismeretlen problémafajta: {v} +@msg unknown knockout state {k} ismeretlen kiütési állapot: {k} +@msg unknown language `{language}` (one of {_1}) ismeretlen nyelv: `{language}` (ezek egyike kell: {_1}) +@msg unknown language `{l}` (one of {_1}) ismeretlen nyelv: `{l}` (ezek egyike kell: {_1}) +@msg unknown method `{m}` ({_1}) ismeretlen módszer: `{m}` ({_1}) +@msg unknown mode `{other}` (gray, rgb, hsb, lab, cmyk or web) ismeretlen mód: `{other}` (gray, rgb, hsb, lab, cmyk vagy web) +@msg unknown mode `{other}` (mono|cmyk) ismeretlen mód: `{other}` (mono|cmyk) +@msg unknown mode `{other}` (rgb|cmyk|gray|global) ismeretlen mód: `{other}` (rgb|cmyk|gray|global) +@msg unknown mode `{other}` (set, add, subtract) ismeretlen mód: `{other}` (set, add, subtract) +@msg unknown mode `{o}` ismeretlen mód: `{o}` +@msg unknown mode {m} ismeretlen mód: {m} +@msg unknown model `{other}` ismeretlen modell: `{other}` +@msg unknown model `{other}` (keep, new or document) ismeretlen modell: `{other}` (keep, new vagy document) +@msg unknown op {o} ismeretlen op: {o} +@msg unknown order `{o}`: toggle, front, forward, backward or back ismeretlen order: `{o}`; toggle, front, forward, backward vagy back lehet +@msg unknown overprints `{v}` (preserve, simulate or discard) ismeretlen overprints: `{v}` (preserve, simulate vagy discard) +@msg unknown panel ismeretlen panel +@msg unknown panel `{panel}` ismeretlen panel: `{panel}` +@msg unknown parameter `{key}` ismeretlen paraméter: `{key}` +@msg unknown parameter `{within}settings.{format}`; {why} ismeretlen paraméter: `{within}settings.{format}`; {why} +@msg unknown parameter `{within}{key}`; {why} ismeretlen paraméter: `{within}{key}`; {why} +@msg unknown pieLegend `{v}` (none, standard or wedges) ismeretlen pieLegend: `{v}` (none, standard vagy wedges) +@msg unknown piePosition `{v}` (even, ratio or stacked) ismeretlen piePosition: `{v}` (even, ratio vagy stacked) +@msg unknown pieSort `{v}` (none, all or first) ismeretlen pieSort: `{v}` (none, all vagy first) +@msg unknown plate `{n}` ismeretlen színkivonat: `{n}` +@msg unknown preference `{k}` ismeretlen beállítás: `{k}` +@msg unknown profile {id} (see stroke.widthProfile.list) ismeretlen profil: {id} (lásd: stroke.widthProfile.list) +@msg unknown proof target `{t}` ismeretlen proofcél: `{t}` +@msg unknown quotes key `{k}` (double, single) ismeretlen quotes kulcs: `{k}` (double, single) +@msg unknown reduction `{reduction}` (selective, perceptual, adaptive, web, gray, blackWhite, uniform or document) ismeretlen színcsökkentés: `{reduction}` (selective, perceptual, adaptive, web, gray, blackWhite, uniform vagy document) +@msg unknown resolution `{v}` ismeretlen felbontás: `{v}` +@msg unknown rule `{rule}` ({_1}) ismeretlen szabály: `{rule}` ({_1}) +@msg unknown rule `{r}` (see color.harmony) ismeretlen szabály: `{r}` (lásd: color.harmony) +@msg unknown setting `{k}` ismeretlen beállítás: `{k}` +@msg unknown shape `{v}` (circle|ellipse|square|diamond|line) ismeretlen alakzat: `{v}` (circle|ellipse|square|diamond|line) +@msg unknown spacing `{o}` (smooth|steps|distance) ismeretlen spacing: `{o}` (smooth|steps|distance) +@msg unknown tileType `{t}` ({_1}) ismeretlen tileType: `{t}` ({_1}) +@msg unknown units ismeretlen mértékegység +@msg unknown units `{u}` ismeretlen mértékegység: `{u}` +@msg unknown value axis `{v}` (left, right or both) ismeretlen értéktengely: `{v}` (left, right vagy both) +@msg unknown variation `{v}` (tintsShades|warmCool|vividMuted) ismeretlen variáció: `{v}` (tintsShades|warmCool|vividMuted) +@msg unknown warp style `{s}` ismeretlen hajlítási stílus: `{s}` +@msg unknown {key} `{v}` (none, short or full) ismeretlen {key}: `{v}` (none, short vagy full) +@msg unknown {key} profile `{n}` ismeretlen {key} profil: `{n}` +@msg unknown {k} key `{key}` (size, position) ismeretlen {k} kulcs: `{key}` (size, position) +@msg unmatched ')' pár nélküli ')' +@msg unreadable object olvashatatlan objektum +@msg unsafe destination file name nem biztonságos célfájlnév +@msg unterminated character class lezáratlan karakterosztály +@msg unterminated group lezáratlan csoport +@msg use paths or compound paths útvonalakat vagy összetett útvonalakat használj +@msg useArtboards must be true or false, not {v} useArtboards: true vagy false kell, ez nem az: {v} +@msg value for `{var}` must match its variable kind a(z) `{var}` értékének meg kell felelnie a változó típusának +@msg variable `{_1}` is already defined a változó már definiálva van: `{_1}` +@msg variable `{name}` has no `trait` a(z) `{name}` változónak nincs `trait` értéke +@msg variable `{name}` is already defined a változó már definiálva van: `{name}` +@msg variable `{name}` is declared twice a változó kétszer van deklarálva: `{name}` +@msg variable `{to}` already exists már van ilyen változó: `{to}` +@msg view is required a view kötelező +@msg view must be one of {_1} view: ezek egyike kell: {_1} +@msg warpStyle can only edit an applied Warp effect warpStyle: csak már alkalmazott Hajlítás effektust szerkeszthet +@msg width and height must be more than 0 and at most {limit} width és height: 0-nál nagyobb és legfeljebb {limit} érték kell +@msg width factors must be finite a szélességszorzók véges értékek legyenek +@msg width must be positive width: pozitív érték kell +@msg width out of range a szélesség tartományon kívül esik +@msg width/height must be > 0 width/height: > 0 érték kell +@msg wordGap and lineGap need area type in the selection wordGap és lineGap: területszöveg kell a kijelölésben +@msg x and y must be finite numbers x és y: véges számok kellenek +@msg x and y must be given together x és y: együtt kell megadni +@msg xpath needs its variables as an object xpath: a változóit objektumként kell megadni +@msg xpath needs the expression as a string xpath: a kifejezést karakterláncként kell megadni +@msg zone needs an anchor: dock beside a panel with anchor, or in a new dock column with side (Start or End) zone: anchor is kell hozzá; dokkolj egy panel mellé az anchor értékkel, vagy új dokkoszlopba a side értékkel (Start vagy End) +@msg zoom must be positive zoom: pozitív érték kell +@msg {C}: no effect at index {list} {C}: nincs effektus ennél az indexnél: {list} +@msg {DEFAULT_PRESET} is protected and stays {DEFAULT_PRESET} védett, megmarad +@msg {DEFAULT_PRESET} is protected: save the settings under another name {DEFAULT_PRESET} védett: mentsd a beállításokat más néven +@msg {GRANT_NOT_REMOVED}, and its settings and cache can't be moved back from {_1} to {_2}: {e} {GRANT_NOT_REMOVED}, a beállításai és a gyorsítótára pedig nem helyezhetők vissza innen: {_1}, ide: {_2}: {e} +@msg {LABEL} produced an empty result {LABEL}: az eredmény üres +@msg {_1} MB of document, at most {_2} MB a dokumentum {_1} MB, legfeljebb {_2} MB lehet +@msg {_1} MB of images, at most {_2} MB a képek összesen {_1} MB, legfeljebb {_2} MB lehet +@msg {_1} bytes of RGBA data for a {width} × {height} image {_1} bájt RGBA-adat egy {width} × {height} méretű képhez +@msg {_1} can't be read, or changed since it was read: relink or update it first {_1}: nem olvasható, vagy a beolvasása óta megváltozott; előbb csatold újra vagy frissítsd +@msg {_1} can't go into {into} {_1}: nem kerülhet ide: {into} +@msg {_1} can't limit printing to low resolution: choose PDF 1.4 or later, or allow high-resolution printing {_1}: nem korlátozhatja a nyomtatást kis felbontásra; válassz PDF 1.4 vagy újabb verziót, vagy engedélyezd a nagy felbontású nyomtatást +@msg {_1} files can't be opened yet ezek a fájlok még nem nyithatók meg: {_1} +@msg {_1} files can't be password-protected: remove the passwords or choose no standard {_1} fájlok nem védhetők jelszóval: távolítsd el a jelszavakat, vagy ne válassz szabványt +@msg {_1} files can't be {_2} {_1} fájlokra ez nem lehetséges: {_2} +@msg {_1} files can't carry editing data: turn off preserveEditing {_1} fájlok nem tartalmazhatnak szerkesztési adatokat: kapcsold ki a preserveEditing beállítást +@msg {_1} files can't have PDF layers: turn off createLayers {_1} fájlokban nem lehetnek PDF-rétegek: kapcsold ki a createLayers beállítást +@msg {_1} files need a creation date, and this platform has no clock to give one {_1} fájlokhoz létrehozási dátum kell, ezen a platformon pedig nincs óra, amely megadná +@msg {_1} is not a folder: {e} nem mappa: {_1}: {e} +@msg {_1} isn't a path nem útvonal: {_1} +@msg {_1} options: {e} {_1} beállításai: {e} +@msg {_1} paints nothing to rasterize {_1}: semmi raszterizálhatót nem fest +@msg {_1} passwords can have up to {MAX_LEGACY_PASSWORD} ASCII characters (PDF 1.7 and later take any) {_1}: a jelszavak legfeljebb {MAX_LEGACY_PASSWORD} ASCII-karakterből állhatnak (a PDF 1.7 és az újabb verziók bármilyet elfogadnak) +@msg {_1} with linked images or an image map writes several files: use document.export {_1}: csatolt képekkel vagy képtérképpel több fájlt ír ki; használd a document.export parancsot +@msg {_1} writes one file per artboard here: use document.export, or name one artboard {_1}: itt rajztáblánként egy fájlt ír ki; használd a document.export parancsot, vagy nevezz meg egy rajztáblát +@msg {_1} × {_2} pixels is too large for {_3} (at most {max} pixels a side): lower the scale {_1} × {_2} képpont túl nagy ehhez: {_3} (oldalanként legfeljebb {max} képpont); csökkentsd a léptéket +@msg {_1}: belongs to another account {_1}: másik fiókhoz tartozik +@msg {_1}: not a folder of its own {_1}: nem saját mappa +@msg {_1}: not a plain file {_1}: nem egyszerű fájl +@msg {_1}: {_2} and {_3} are in the way {_1}: útban van: {_2} és {_3} +@msg {code}: {0} {code}: {0} +@msg {dest}: {e} {dest}: {e} +@msg {dir}: {e} {dir}: {e} +@msg {doc} has no folder nincs mappája: {doc} +@msg {file} isn't linked nincs csatolva: {file} +@msg {file} names more than one linked JavaScript file {file}: egynél több csatolt JavaScript-fájlt nevez meg +@msg {folder} is not a package folder nem csomagmappa: {folder} +@msg {folder}: more than {max} files and folders {folder}: több mint {max} fájl és mappa +@msg {folder}: {e} {folder}: {e} +@msg {g} is not a Live Paint group nem Élő festés csoport: {g} +@msg {id} is not a slice nem szelet: {id} +@msg {key} must be 0–{MAX_ADD_AROUND} pt {key}: 0–{MAX_ADD_AROUND} pt kell +@msg {key} must be [x,y] {key}: [x,y] kell +@msg {key} must be a percentage {min}..100 {key}: százalék kell, {min}..100 +@msg {key} must be a positive number, not {n} {key}: pozitív szám kell, ez nem az: {n} +@msg {key} must be a positive number, not {v} {key}: pozitív szám kell, ez nem az: {v} +@msg {key} must be one of {_1} {key}: ezek egyike kell: {_1} +@msg {key} must be {_1}, got {s} {key}: ez kell: {_1}; kapott érték: {s} +@msg {key} must name a floating panel {key}: lebegő panelt kell megneveznie +@msg {key} must name a panel in another group {key}: másik csoportban lévő panelt kell megneveznie +@msg {key} must name a panel that shows {key}: látható panelt kell megneveznie +@msg {key} must name a registered panel {key}: regisztrált panelt kell megneveznie +@msg {kind} files have no transparency, and the file would have {what}: flatten it first (object.flattenTransparency) {kind} fájlokban nincs átlátszóság, a fájlban viszont ez lenne: {what}; előbb lapítsd (object.flattenTransparency) +@msg {kind} images can't be opened (see document.formats) {kind} képek nem nyithatók meg (lásd: document.formats) +@msg {k} `{v}` is not one of the choices {k} `{v}`: nem a választási lehetőségek egyike +@msg {k} has control characters{_1} {k}: vezérlőkaraktereket tartalmaz{_1} +@msg {k} is too long (at most {MAX_TEXT} characters) {k}: túl hosszú (legfeljebb {MAX_TEXT} karakter) +@msg {k} must be > 0 {k}: > 0 érték kell +@msg {k} must be a number (pt) or a length such as "210 mm" {k}: szám (pt) vagy hosszúság kell, például "210 mm" +@msg {k} must be a number from {min} to {max} {k}: {min} és {max} közötti szám kell +@msg {k} must be a number or "auto" {k}: szám vagy "auto" kell +@msg {k} must be a string {k}: karakterlánc kell +@msg {k} must be text {k}: szöveg kell +@msg {k} must be true or false {k}: true vagy false kell +@msg {k} must be {{size?, position?}} {k}: {{size?, position?}} kell +@msg {k}: a custom arrowhead's path needs an area to fill and at most {most} anchors and {most} subpaths, each anchor within {far} head units of its tip {k}: az egyéni nyílhegy útvonalának kitölthető terület kell, legfeljebb {most} horgonyponttal és {most} részútvonallal, és minden horgonypont legfeljebb {far} nyílhegyegységre lehet a csúcsától +@msg {k}: bad custom arrowhead path: {e} {k}: hibás egyéni nyílhegyútvonal: {e} +@msg {k}: bad custom arrowhead: {e} {k}: hibás egyéni nyílhegy: {e} +@msg {k}: can't read `{s}` as a length {k}: nem olvasható hosszúságként: `{s}` +@msg {k}: custom must be a name {k}: custom: név kell +@msg {label} must be a number at most {max} {label}: legfeljebb {max} értékű szám kell +@msg {label} must be a number from -1296 to 1296 {label}: -1296 és 1296 közötti szám kell +@msg {label} must be a number from 1 to 10000 {label}: 1 és 10000 közötti szám kell +@msg {name} `{s}`: {ids} {name} `{s}`: {ids} +@msg {name} is built in and can't be deleted {name}: beépített elem, nem törölhető +@msg {name} must be a number {name}: szám kell +@msg {name} must be {lo}–{hi}{unit} (got {v}) {name}: {lo}–{hi}{unit} kell (kapott érték: {v}) +@msg {name}: CRC or size mismatch {name}: a CRC vagy a méret nem egyezik +@msg {name}: only this Affinity file's embedded preview could be read; use File › Open to see it with its warning, or export SVG or PDF from Affinity before placing {name}: ennek az Affinity-fájlnak csak a beágyazott előnézete volt olvasható; a Fájl › Megnyitás paranccsal megnézheted a figyelmeztetésével együtt, vagy az elhelyezés előtt exportálj SVG-t vagy PDF-et az Affinityből +@msg {name}: {e} {name}: {e} +@msg {native}; its embedded preview can't be read either ({e}) {native}; a beágyazott előnézete sem olvasható ({e}) +@msg {path}: copy takes a DCS file only when its plates are inside it; relink to it where its plate files are {path}: a copy csak akkor fogad DCS-fájlt, ha a színkivonatai benne vannak; ott csatold újra, ahol a színkivonatfájljai vannak +@msg {path}: larger than {_1} MB {path}: nagyobb, mint {_1} MB +@msg {shown} is not an XPath 1.0 function nem XPath 1.0-függvény: {shown} +@msg {std} files are CMYK, and the file would have colours in {_1} {std} fájlok CMYK színmódúak, a fájlban viszont ilyen színek is lennének: {_1} +@msg {std} files embed their fonts, and the file would have one that isn't {std} fájlok beágyazzák a betűtípusaikat, a fájlban viszont lenne olyan, amely nincs beágyazva +@msg {target} is the file this document was read from, and reading it left things out ({what}): writing over it would lose them for good. Write another file instead, or pass acknowledgeLoss: true to replace it anyway {target}: ebből a fájlból lett beolvasva ez a dokumentum, és a beolvasás során egyes részek kimaradtak ({what}): a felülírásával ezek végleg elvesznének. Írj inkább másik fájlt, vagy add meg az acknowledgeLoss: true értéket, ha mégis le akarod cserélni +@msg {ty} brushes need selected art (or params.{k}) {ty} ecsetekhez kijelölt grafika kell (vagy params.{k}) +@msg {v} is not an asset id nem elemazonosító: {v} +@msg {v} names no layer or sublayer {v}: nem nevez meg réteget vagy alréteget +@msg {what} can't be intertwined nem fonható össze: {what} +@msg {what} doesn't fit the paper with its bleed and marks {what}: a kifutóval és a jelekkel együtt nem fér el a papíron +@msg {what} is not a function nem függvény: {what} +@msg {what} would print more than {MAX_COPIES_PER_SHEET} copies on a sheet: scale it up {what}: egy ívre több mint {MAX_COPIES_PER_SHEET} példány kerülne; növeld a méretét +@msg {what} would print on more than {MAX_TILES} tiles: scale it down {what}: több mint {MAX_TILES} csempére kerülne nyomtatásra; csökkentsd a méretét +@msg {what} {i} out of range {what} {i}: tartományon kívül esik +@msg `{key}` must be from 0.01 to 1000 pt `{key}`: 0.01 és 1000 pt közötti érték kell +@msg select the banner, or mark every artboard jelöld ki a molinót, vagy jelöld meg az összes rajztáblát +@msg the banner has no width or height a molinónak nincs szélessége vagy magassága +@msg the grommet inset is too large for the banner a ringlik széltől mért távolsága túl nagy a molinóhoz +@msg the hem is too deep for the banner a szegés túl mély a molinóhoz +@msg the spacing makes more than {MAX_GROMMETS} grommets ezzel a térközzel több mint {MAX_GROMMETS} ringli keletkezne +@msg there is no banner to mark nincs megjelölhető molinó +@msg turn on at least one side kapcsolj be legalább egy oldalt +@msg with no hem and no grommets there is nothing to mark szegés és ringlik nélkül nincs mit megjelölni +@msg {saving} failed: {e} {saving}: sikertelen: {e} # Messages of the effects, 3D, image export, color profiles, swatch exchange files, color books and DXF import. @msg 3D effects require finite coordinates within 100 million points A 3D effektusokhoz 100 millió ponton belüli véges koordináták kellenek diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 208877f673..8006ecf2cd 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -389,6 +389,18 @@ Title Case Huruf besar di awal kata Sentence case Huruf besar di awal kalimat Smart Punctuation… Tanda baca cerdas… + Smart Punctuation Tanda baca cerdas + ff, fi, ffi Ligatures Ligatur ff, fi, ffi + ff, fl, ffl Ligatures Ligatur ff, fl, ffl + Smart Quotes Tanda kutip cerdas + Smart Spaces Spasi cerdas + En, Em Dashes Tanda pisah en dan em + Ellipses Elipsis + Expert Fractions Pecahan ahli + Replace In Ganti di + Selected Text Only Hanya teks terpilih + Entire Document Seluruh dokumen + Report Results Laporkan hasil Create Outlines Buat garis luar Optical Margin Alignment Perataan margin optik Dynamic Text Teks dinamis @@ -901,6 +913,7 @@ Free Transform Transformasi bebas Perspective Distort Distorsi perspektif Radial Blur… Kabur radial… + Blur Center Pusat kabur Smart Blur… Kabur cerdas… Sharpen Pertajam Unsharp Mask… Unsharp Mask… @@ -1636,6 +1649,9 @@ digits Malayalam Malayalam The selected character's font is not available. Font karakter yang dipilih tidak tersedia. No alternates for the selected character. Tidak ada alternatif untuk karakter yang dipilih. Double-click to replace Klik ganda untuk mengganti + Click to replace Klik untuk mengganti + Show all alternates in the Glyphs panel Tampilkan semua alternatif di panel Glif + Show Character Alternates Tampilkan alternatif karakter Select one character with the Type tool first. Pilih satu karakter dengan alat teks terlebih dahulu. {glyph} is a glyph of {font}, not of the font the selected text is set in ({text_font}). {glyph} adalah glif {font}, bukan dari font yang dipakai teks terpilih ({text_font}). {glyph} belongs to {base} (U+{base_code}) {place}; your selection is {sel} (U+{code}). {glyph} milik {base} (U+{base_code}) {place}; pilihan Anda adalah {sel} (U+{code}). @@ -2077,6 +2093,7 @@ digits Malayalam Malayalam @msg paths entry {i} needs path and ids (object ids no other entry has) entri paths {i} memerlukan path dan ids (id objek yang tidak dimiliki entri lain) @msg scope missingInFolder takes path: the folder of that file is searched for the other missing links scope missingInFolder menerima path: tautan hilang lainnya dicari di folder file tersebut Show Missing Tampilkan yang hilang + Sort by Size Urutkan berdasarkan ukuran Sort by Status Urutkan berdasarkan status Clear Overrides Hapus penimpaan Create New {kind} Style Buat gaya {kind} baru @@ -2326,6 +2343,7 @@ digits Malayalam Malayalam Export Asset Ekspor aset Export to: Ekspor ke: Format Settings Pengaturan format + Format Settings… Pengaturan format… Formats: Format: Full Document Dokumen penuh Include Bleed Sertakan bleed @@ -2415,6 +2433,7 @@ digits Malayalam Malayalam e.g. 1-3, 5 mis. 1-3, 5 First Page Halaman pertama Import PDF Impor PDF + Import PDF pages as links Impor halaman PDF sebagai tautan Last Page Halaman terakhir Next Page Halaman berikutnya of {count} dari {count} @@ -2498,6 +2517,7 @@ digits Malayalam Malayalam Transparent Background Latar belakang transparan Choose… Pilih… Copy Fonts Used in the Document Salin font yang digunakan dalam dokumen + Copy Info Salin info Copy Links Salin tautan Create Report Buat laporan Fonts whose licence doesn't allow embedding are not copied. Font yang lisensinya tidak mengizinkan penyematan tidak disalin. @@ -4280,6 +4300,7 @@ imageTrace Outline Kontur Stop the script and undo what it did? Then quit again. Hentikan skrip dan batalkan yang telah dilakukannya? Lalu keluar lagi. This script has added a great many objects. Continue, or stop it and undo what it did? Skrip ini telah menambahkan sangat banyak objek. Lanjutkan, atau hentikan dan batalkan yang telah dilakukannya? @msg Copied the script report Berhasil menyalin laporan skrip +@msg Copied the link info Berhasil menyalin info tautan @msg Corners edits the corners of a path Corners menyunting sudut jalur @msg Couldn't copy to the system clipboard: {e} Tidak dapat menyalin ke papan klip sistem: {e} @msg Couldn't open {name}: {e} Tidak dapat membuka {name}: {e} @@ -6875,11 +6896,20 @@ breakText Glyphs Glif Open Tutorial Sample Buka contoh tutorial Finish Tutorial Selesaikan tutorial Next Tutorial Tutorial berikutnya + Show Learn Tab Tampilkan tab Belajar + Show Skill Tampilkan keterampilan + Back One Level Kembali satu tingkat Back to Skills Kembali ke keterampilan @msg tutorial `{id}` has no practice sample tutorial `{id}` tidak memiliki contoh latihan @msg open the practice sample of `{id}` first (see learn.openSample) buka contoh latihan `{id}` terlebih dahulu (lihat learn.openSample) @msg finish `{id}` first (see learn.finish) selesaikan `{id}` terlebih dahulu (lihat learn.finish) @msg `{id}` is the last tutorial in its skill `{id}` adalah tutorial terakhir dalam keterampilannya + Reset progress Atur ulang kemajuan + Mark Tutorial Step Tandai langkah tutorial + Reset Learn Progress Atur ulang kemajuan belajar +@msg missing `step` (see learn.show) `step` tidak ada (lihat learn.show) +@msg `step` must be a step number from 0 to {last} `step` harus berupa nomor langkah dari 0 sampai {last} +@msg `{id}` is finished (see learn.resetProgress) `{id}` sudah selesai (lihat learn.resetProgress) # Deferred plug-in effects Refresh Deferred Effects Segarkan efek yang ditunda @@ -6902,3 +6932,6 @@ breakText Glyphs Glif Grommets Mata ayam Grommet Inset Jarak mata ayam dari tepi Diameter Diameter + Nest Shapes… Susun Bentuk… + Nest Shapes Susun Bentuk + Roll Gulungan diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 534a7a181f..f0bea31794 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -18,6 +18,7 @@ Edge Brightness Luminosità bordo Smoothness Uniformità Radial Blur… Sfocatura radiale… + Blur Center Centro della sfocatura Smart Blur… Sfocatura intelligente… Sharpen Nitidezza Unsharp Mask… Maschera di contrasto… @@ -645,6 +646,7 @@ font-technology Variable Variabili Copy All Styles Copia tutti gli stili Copy Color Value (Hex) Copia valore colore (hex) Copy Fonts Used in the Document Copia i font usati nel documento + Copy Info Copia informazioni Copy Links Copia collegamenti Copy Selected Style Copia stile selezionato Copy to User Defined Copia in Definito dall'utente @@ -912,6 +914,9 @@ font-technology Variable Variabili The selected character's font is not available. Il font del carattere selezionato non è disponibile. No alternates for the selected character. Nessuna alternativa per il carattere selezionato. Double-click to replace Fai doppio clic per sostituire + Click to replace Fai clic per sostituire + Show all alternates in the Glyphs panel Mostra tutte le alternative nel pannello Glifi + Show Character Alternates Mostra alternative carattere Select one character with the Type tool first. Seleziona prima un carattere con lo strumento Testo. {glyph} is a glyph of {font}, not of the font the selected text is set in ({text_font}). {glyph} è un glifo di {font}, non del font del testo selezionato ({text_font}). {glyph} belongs to {base} (U+{base_code}) {place}; your selection is {sel} (U+{code}). {glyph} appartiene a {base} (U+{base_code}) {place}; la tua selezione è {sel} (U+{code}). @@ -1359,6 +1364,7 @@ file-filter Templates Modelli Format Formato Format Options Opzioni formato Format Settings Impostazioni formato + Format Settings… Impostazioni formato… Format: Formato: Formats: Formati: Fractional Widths Larghezze frazionarie @@ -1720,6 +1726,7 @@ file-filter Templates Modelli Images: Immagini: Import Keyboard Shortcuts… Importa scelte rapide da tastiera… Import PDF Importa PDF + Import PDF pages as links Importa le pagine PDF come collegamenti Import PDF Presets Importa preset PDF Import Perspective Grid Presets Importa preset griglia prospettica Import Print Presets Importa preset di stampa @@ -3486,6 +3493,18 @@ digits Malayalam Malayalam Smart Guides (View → Smart Guides) Guide sensibili (Visualizza → Guide sensibili) Smart Guides (⌘U) Guide sensibili (⌘U) Smart Punctuation… Punteggiatura intelligente… + Smart Punctuation Punteggiatura intelligente + ff, fi, ffi Ligatures Legature ff, fi, ffi + ff, fl, ffl Ligatures Legature ff, fl, ffl + Smart Quotes Virgolette intelligenti + Smart Spaces Spazi intelligenti + En, Em Dashes Trattini medi e lineette + Ellipses Puntini di sospensione + Expert Fractions Frazioni esperte + Replace In Sostituisci in + Selected Text Only Solo testo selezionato + Entire Document Intero documento + Report Results Mostra risultati Smooth Smussa Corner Angolo Relative Relativo @@ -3516,6 +3535,7 @@ digits Malayalam Malayalam Solid Pieno Sort by Kind Ordina per tipo Sort by Name Ordina per nome + Sort by Size Ordina per dimensione Sort by Status Ordina per stato Source code on GitHub Codice sorgente su GitHub Source Sans 3 Source Sans 3 @@ -4426,6 +4446,7 @@ axis Both Entrambi @msg there is no script engine named {name} non esiste un motore di script chiamato {name} @msg Running a script Esecuzione di uno script @msg Copied the script report Rapporto dello script copiato +@msg Copied the link info Informazioni collegamento copiate @msg Corners edits the corners of a path Angoli modifica gli angoli di un tracciato @msg Couldn't copy to the system clipboard: {e} Impossibile copiare negli appunti di sistema: {e} @msg Couldn't open {name}: {e} Impossibile aprire {name}: {e} @@ -6300,7 +6321,7 @@ axis Y Axis Asse Y @plural Result: {n}|Results: {n} Risultato: {n}|Risultati: {n} @msg select one object selezionate un oggetto @msg Global Edit works on paths, compound paths, symbol instances and groups of them La modifica globale funziona su tracciati, tracciati composti, istanze di simboli e gruppi di essi -@msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again nessun oggetto simile trovato (le copie ruotate o riflesse non vengono riconosciute); cambiate le opzioni di modifica globale e riprovate +@msg no similar objects found (reflected copies are not matched); change the Global Edit Options and try again nessun oggetto simile trovato (le copie riflesse non vengono riconosciute); cambiate le opzioni di modifica globale e riprovate @msg Global Edit is off La modifica globale non è attiva @msg only an object of the Global Edit other than the one it started from can be left out si può escludere solo un oggetto della modifica globale diverso da quello da cui è partita @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all o un intervallo come 1, 3-5, non {v} @@ -7097,11 +7118,20 @@ breakText Glyphs Glifi Open Tutorial Sample Apri l’esempio del tutorial Finish Tutorial Termina il tutorial Next Tutorial Tutorial successivo + Show Learn Tab Mostra una scheda di Impara + Show Skill Mostra competenza + Back One Level Indietro di un livello Back to Skills Torna alle competenze @msg tutorial `{id}` has no practice sample il tutorial `{id}` non ha un esempio di esercitazione @msg open the practice sample of `{id}` first (see learn.openSample) apri prima l’esempio di esercitazione di `{id}` (vedi learn.openSample) @msg finish `{id}` first (see learn.finish) termina prima `{id}` (vedi learn.finish) @msg `{id}` is the last tutorial in its skill `{id}` è l’ultimo tutorial della sua competenza + Reset progress Reimposta i progressi + Mark Tutorial Step Segna il passaggio del tutorial + Reset Learn Progress Reimposta i progressi di apprendimento +@msg missing `step` (see learn.show) manca `step` (vedi learn.show) +@msg `step` must be a step number from 0 to {last} `step` deve essere un numero di passaggio da 0 a {last} +@msg `{id}` is finished (see learn.resetProgress) `{id}` è terminato (vedi learn.resetProgress) # Deferred plug-in effects Refresh Deferred Effects Aggiorna effetti rimandati @@ -8618,6 +8648,8 @@ breakText Glyphs Glifi @msg the RTF file is too large to place as type (at most {_1} MB) il file RTF è troppo grande per essere inserito come testo (al massimo {_1} MB) @msg the SVG expands to more than {0} nested SVG images l'SVG si espande in più di {0} immagini SVG annidate @msg the SVG expands to more than {0} objects l'SVG si espande in più di {0} oggetti +@msg the SVG's style sheets take too long to match l'abbinamento dei fogli di stile dell'SVG richiede troppo tempo +@msg the SVG's styles expand to more than {0} MB gli stili dell'SVG si espandono a oltre {0} MB @msg the SVG has no drawable objects l'SVG non ha oggetti disegnabili @msg the SVGZ file unpacks to more than {_1} MB il file SVGZ si decomprime in più di {_1} MB @msg the Word document has more than {MAX_PAGES} pages of properties, too many to place il documento Word ha più di {MAX_PAGES} pagine di proprietà, troppe per essere inserito @@ -8929,9 +8961,140 @@ breakText Glyphs Glifi @msg {what} can't be intertwined {what} non può essere intrecciato @msg {what} doesn't fit the paper with its bleed and marks {what} non entra nella carta con l'abbondanza e i segni @msg {what} would print on more than {MAX_TILES} tiles: scale it down {what} verrebbe stampato su più di {MAX_TILES} riquadri: riducilo +# Messages no catalog translated yet: image export and color profiles, color books and swatch exchange files, 3D and Revolve, and script and file errors. +@msg 3D effects require finite coordinates within 100 million points Gli effetti 3D richiedono coordinate finite entro 100 milioni di punti +@msg 3D effects require one to ten lights Gli effetti 3D richiedono da una a dieci luci +@msg BMP depth {_1}: 1, 4, 8, 16, 24 or 32 bits per pixel Profondità BMP {_1}: 1, 4, 8, 16, 24 o 32 bit per pixel +@msg BMP encoding failed: {width} × {height} pixels doesn't fit the format or the pixel buffer Codifica BMP non riuscita: {width} × {height} pixel non sono compatibili con il formato o con il buffer dei pixel +@msg GIF encoding failed: the palette image is malformed Codifica GIF non riuscita: l'immagine con palette non è valida +@msg GIF encoding failed: {e} Codifica GIF non riuscita: {e} +@msg JPEG colour profile: {e} Profilo colore JPEG: {e} +@msg JPEG encoding failed: pixel buffer doesn't match the image size Codifica JPEG non riuscita: il buffer dei pixel non corrisponde alle dimensioni dell'immagine +@msg JPEG encoding failed: {e} Codifica JPEG non riuscita: {e} +@msg PNG encoding failed: pixel buffer doesn't match the image size Codifica PNG non riuscita: il buffer dei pixel non corrisponde alle dimensioni dell'immagine +@msg PNG encoding failed: the palette image is malformed Codifica PNG non riuscita: l'immagine con palette non è valida +@msg PNG encoding failed: {e} Codifica PNG non riuscita: {e} +@msg PNG encoding failed: {width} × {height} pixels is not a valid image size Codifica PNG non riuscita: {width} × {height} pixel non è una dimensione valida per un'immagine +@msg PSD colour profile: {e} Profilo colore PSD: {e} +@msg PSD encoding failed: the pixel buffer doesn't match the image size Codifica PSD non riuscita: il buffer dei pixel non corrisponde alle dimensioni dell'immagine +@msg Revolve profile contains invalid coordinates Rivoluzione: il profilo contiene coordinate non valide +@msg Revolve profile is too complex Rivoluzione: il profilo è troppo complesso +@msg Revolve projection is not finite Rivoluzione: la proiezione non è finita +@msg Revolve requires finite profile coordinates within 100 million points Rivoluzione richiede coordinate del profilo finite entro 100 milioni di punti +@msg Revolve surface is too complex; reduce Segments or simplify the profile Rivoluzione: la superficie è troppo complessa; riduci Segmenti o semplifica il profilo +@msg Revolve surface is too complex; simplify the profile Rivoluzione: la superficie è troppo complessa; semplifica il profilo +@msg Revolve visibility cannot split the projected boundary Rivoluzione: il calcolo della visibilità non può dividere il contorno proiettato +@msg Revolve visibility creates too many fragments Rivoluzione: il calcolo della visibilità crea troppi frammenti +@msg Revolve visibility creates too many vector anchors Rivoluzione: il calcolo della visibilità crea troppi punti di ancoraggio vettoriali +@msg Revolve visibility exceeds its geometry work limit Rivoluzione: il calcolo della visibilità supera il suo limite di lavoro geometrico +@msg Revolve visibility exceeds its spatial index limit Rivoluzione: il calcolo della visibilità supera il suo limite di indice spaziale +@msg Revolve visibility has too many boundary crossings Rivoluzione: il calcolo della visibilità ha troppi attraversamenti del contorno +@msg Revolve visibility has too many input anchors Rivoluzione: il calcolo della visibilità ha troppi punti di ancoraggio in ingresso +@msg Revolve visibility requires convex cap sectors Rivoluzione: il calcolo della visibilità richiede settori convessi delle basi +@msg Revolve visibility requires finite projected faces Rivoluzione: il calcolo della visibilità richiede facce proiettate finite +@msg SVG options: {e} Opzioni SVG: {e} +@msg Save for Web settings: {e} Impostazioni di Salva per il web: {e} +@msg TIFF colour profile: {e} Profilo colore TIFF: {e} +@msg TIFF encoding failed: the pixel buffer doesn't match the image size Codifica TIFF non riuscita: il buffer dei pixel non corrisponde alle dimensioni dell'immagine +@msg TIFF encoding failed: {e} Codifica TIFF non riuscita: {e} +@msg Targa depth {_1}: 16, 24 or 32 bits per pixel Profondità Targa {_1}: 16, 24 o 32 bit per pixel +@msg Targa encoding failed: the pixel buffer doesn't match the image size Codifica Targa non riuscita: il buffer dei pixel non corrisponde alle dimensioni dell'immagine +@msg The 3D projection is not finite La proiezione 3D non è finita +@msg The 3D shadow is too complex; turn Shadows off or simplify the art L'ombra 3D è troppo complessa; disattiva Ombre o semplifica la grafica +@msg The shape contains invalid coordinates La forma contiene coordinate non valide +@msg Too many Revolve faces for visibility evaluation Troppe facce di Rivoluzione per il calcolo della visibilità +@msg VectorCraft reads at most {ASE_MAX_ENTRIES} colors and groups from a swatch exchange file, and this library has {entries} VectorCraft legge al massimo {ASE_MAX_ENTRIES} colori e gruppi da un file di scambio campioni, e questa libreria ne ha {entries} +@msg WebP encoding failed: {e} Codifica WebP non riuscita: {e} +@msg [{j}] `{_1}`: {why} [{j}] `{_1}`: {why} +@msg `answers[{i}]` {e} `answers[{i}]` {e} +@msg `view` is smallThumb, mediumThumb, largeThumb, smallList or largeList `view` è smallThumb, mediumThumb, largeThumb, smallList o largeList +@msg a line can't run from a point to itself una linea non può andare da un punto a sé stesso +@msg a line needs at least two points una linea richiede almeno due punti +@msg a number cannot be read impossibile leggere un numero +@msg a swatch exchange block is too long un blocco del file di scambio campioni è troppo lungo +@msg a swatch exchange name is too long un nome nel file di scambio campioni è troppo lungo +@msg a {sw} × {sh} image can't be resized to {width} × {height} pixels un'immagine di {sw} × {sh} non può essere ridimensionata a {width} × {height} pixel +@msg a {width} × {height} image is too large un'immagine di {width} × {height} è troppo grande +@msg a {width} × {height} image: {e} un'immagine di {width} × {height}: {e} +@msg an image could not be written: {e} impossibile scrivere un'immagine: {e} +@msg an image that couldn't be read was left out un'immagine che non è stato possibile leggere è stata omessa +@msg can't open “{name}”: {e} impossibile aprire “{name}”: {e} +@msg cannot align zip entries to {align} bytes impossibile allineare le voci zip a {align} byte +@msg cannot open the automation {kind} root `{_1}`: {e} impossibile aprire la cartella radice {kind} dell'automazione `{_1}`: {e} +@msg cannot read profile: {0} impossibile leggere il profilo: {0} +@msg color book version {version} isn't supported (only 1) la versione {version} del libro colori non è supportata (solo 1) +@msg color books in color space {other} aren't supported (only RGB, CMYK and Lab) i libri colori nello spazio colore {other} non sono supportati (solo RGB, CMYK e Lab) +@msg file name too long to zip: {_1} nome file troppo lungo per un archivio zip: {_1} +@msg file name too long to zip: {name} nome file troppo lungo per un archivio zip: {name} +@msg freeform line {i}: {e} linea libera {i}: {e} +@msg freeform point {i}: {e} punto libero {i}: {e} +@msg give `{key}` or `{other}`, not both indica `{key}` o `{other}`, non entrambi +@msg grayscale profiles can't be working spaces yet i profili in scala di grigi non possono ancora essere spazi di lavoro +@msg input contains NaN or infinite coordinates l'input contiene coordinate NaN o infinite +@msg input path could not be closed impossibile chiudere il tracciato di input +@msg invalid ICC profile: {0} profilo ICC non valido: {0} +@msg invalid scale {scale} scala non valida {scale} +@msg its localized names take more than {_1} KB i suoi nomi localizzati occupano più di {_1} KB +@msg its objects are nested too deep ({e}) i suoi oggetti sono annidati troppo in profondità ({e}) +@msg its tag table lists the `{_1}` tag more than once la sua tabella dei tag elenca il tag `{_1}` più di una volta +@msg not a graphic style library: {e} non è una libreria di stili grafici: {e} +@msg not a swatch library (.vcswatches or .gpl) non è una libreria campioni (.vcswatches o .gpl) +@msg not a swatch library (format `{_1}`) non è una libreria campioni (formato `{_1}`) +@msg not a swatch library: {e} non è una libreria campioni: {e} +@msg not an action set file ({e}) non è un file di set di azioni ({e}) +@msg profile colour space {other} is not RGB, CMYK or Gray lo spazio colore {other} del profilo non è RGB, CMYK o scala di grigi +@msg regular expression too large espressione regolare troppo grande +@msg script file is not UTF-8 text: {value} il file di script non è testo UTF-8: {value} +@msg stop {i}: {e} cursore colore {i}: {e} +@msg swatch exchange version {major}.{minor} isn't supported (only 1.x) la versione {major}.{minor} del file di scambio campioni non è supportata (solo 1.x) +@msg the color book holds more than {ASE_MAX_ENTRIES} colors il libro colori contiene più di {ASE_MAX_ENTRIES} colori +@msg the color book is cut short il libro colori è troncato +@msg the color book's names take more than {_1} MB i nomi del libro colori occupano più di {_1} MB +@msg the image would be {w} × {h} pixels; raster exports are limited to {MAX_RASTER_SIDE} pixels per side and {_1} megapixels: lower the scale or resolution l'immagine misurerebbe {w} × {h} pixel; le esportazioni raster sono limitate a {MAX_RASTER_SIDE} pixel per lato e {_1} megapixel: riduci la scala o la risoluzione +@msg the optimised image can't be read back: {e} impossibile rileggere l'immagine ottimizzata: {e} +@msg the pixel buffer doesn't match the image size il buffer dei pixel non corrisponde alle dimensioni dell'immagine +@msg the preview: {e} l'anteprima: {e} +@msg the request may not read the New Document profiles folder la richiesta non può leggere la cartella dei profili di nuovo documento +@msg the shapes are too degenerate to combine le forme sono troppo degeneri per essere combinate +@msg the shapes cross themselves and each other too often to combine le forme si intersecano con sé stesse e tra loro troppe volte per essere combinate +@msg the swatch exchange file holds more than {ASE_MAX_ENTRIES} colors and groups il file di scambio campioni contiene più di {ASE_MAX_ENTRIES} colori e gruppi +@msg the swatch exchange file is cut short il file di scambio campioni è troncato +@msg the {_1} plate can't be read: {e} impossibile leggere la lastra {_1}: {e} +@msg this binary DXF file is damaged or cut short questo file DXF binario è danneggiato o troncato +@msg this is a DWG drawing, which can't be read: save it from the CAD app as a DXF and open that questo è un disegno DWG, che non può essere letto: salvalo dall'app CAD come DXF e apri quel file +@msg too many classes troppe classi di caratteri +@msg too many groups troppi gruppi +@msg too many layers for PSD (at most 32767) troppi livelli per PSD (al massimo 32767) +@msg too many swatch exchange blocks troppi blocchi nel file di scambio campioni +@msg unknown colour profile: {0} profilo colore sconosciuto: {0} +@msg {_1} clashes with a built-in profile name {_1} coincide con il nome di un profilo incorporato +@msg {_1} × {_2} pixels is too large for GIF (at most 65535 pixels a side): lower the resolution {_1} × {_2} pixel è troppo grande per GIF (al massimo 65535 pixel per lato): riduci la risoluzione +@msg {_1}: no usable transform to/from sRGB {_1}: nessuna trasformazione utilizzabile da/verso sRGB +@msg {name} is not a CMYK profile {name} non è un profilo CMYK +@msg {name} is not an RGB profile {name} non è un profilo RGB +@msg {path}: could not be read {path}: lettura non riuscita +@msg {width} × {height} pixels is too large for JPEG (at most 65535 pixels a side): lower the resolution {width} × {height} pixel è troppo grande per JPEG (al massimo 65535 pixel per lato): riduci la risoluzione +@msg {width} × {height} pixels is too large for Targa (at most 65535 pixels a side): lower the resolution {width} × {height} pixel è troppo grande per Targa (al massimo 65535 pixel per lato): riduci la risoluzione +@msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} pixel è troppo grande per PSD (al massimo {MAX_SIDE} pixel per lato): riduci la risoluzione +# Messages other catalogs translate and Italian did not: Banner Hems and Grommets, parameter checks and recovery data. +@msg `{key}` must be from 0.01 to 1000 pt `{key}` deve essere compreso tra 0,01 e 1000 pt +@msg select the banner, or mark every artboard seleziona lo striscione, oppure contrassegna ogni tavola da disegno +@msg the banner has no width or height lo striscione non ha larghezza o altezza +@msg the grommet inset is too large for the banner la distanza degli occhielli dal bordo è troppo grande per lo striscione +@msg the hem is too deep for the banner l'orlo è troppo profondo per lo striscione +@msg the spacing makes more than {MAX_GROMMETS} grommets la spaziatura produce più di {MAX_GROMMETS} occhielli +@msg there is no banner to mark non c'è nessuno striscione da contrassegnare +@msg turn on at least one side attiva almeno un lato +@msg unknown parameter `{within}{key}`; {why} parametro sconosciuto `{within}{key}`; {why} +@msg with no hem and no grommets there is nothing to mark senza orlo e senza occhielli non c'è nulla da contrassegnare +@msg {name} must be {lo}–{hi}{unit} (got {v}) {name} deve essere {lo}–{hi}{unit} (ricevuto {v}) +@msg {saving} failed: {e} {saving} non riuscito: {e} Banner Hems and Grommets… Orli e occhielli per striscioni… Banner Hems and Grommets Orli e occhielli per striscioni Hem Orlo Grommets Occhielli Grommet Inset Distanza degli occhielli dal bordo Diameter Diametro + Nest Shapes… Annida forme… + Nest Shapes Annida forme + Roll Rotolo diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 98a188ee02..dd38ebbd8c 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -463,6 +463,18 @@ digits Malayalam マラヤーラム数字 Title Case 単語の先頭のみ大文字 Sentence case 文頭のみ大文字 Smart Punctuation… 欧文用字形の自動置換… + Smart Punctuation 欧文用字形の自動置換 + ff, fi, ffi Ligatures ff、fi、ffi 合字 + ff, fl, ffl Ligatures ff、fl、ffl 合字 + Smart Quotes スマート引用符 + Smart Spaces スマートスペース + En, Em Dashes EN ダッシュと EM ダッシュ + Ellipses 省略記号 + Expert Fractions エキスパート分数 + Replace In 置換範囲 + Selected Text Only 選択したテキストのみ + Entire Document ドキュメント全体 + Report Results 結果を表示 Create Outlines アウトラインを作成 Optical Margin Alignment 最適なマージン揃え Dynamic Text ダイナミックテキスト @@ -1557,6 +1569,9 @@ antiAlias Sharp シャープ The selected character's font is not available. 選択した文字のフォントを使用できません。 No alternates for the selected character. 選択した文字には異体字がありません。 Double-click to replace ダブルクリックで置換 + Click to replace クリックで置換 + Show all alternates in the Glyphs panel 字形パネルですべての異体字を表示 + Show Character Alternates 文字の異体字を表示 Select one character with the Type tool first. 先に文字ツールで文字を 1 つ選択してください。 {glyph} is a glyph of {font}, not of the font the selected text is set in ({text_font}). {glyph} は {font} のグリフで、選択したテキストのフォント ({text_font}) のものではありません。 {glyph} belongs to {base} (U+{base_code}) {place}; your selection is {sel} (U+{code}). {glyph} は {base} (U+{base_code}) の{place}のグリフです。選択中の文字は {sel} (U+{code}) です。 @@ -1834,6 +1849,7 @@ antiAlias Sharp シャープ Format 形式 Format Options 形式オプション Format Settings 形式の設定 + Format Settings… 形式の設定… Format: 形式: Formats: 形式: Fractions 分数 @@ -2071,6 +2087,7 @@ antiAlias Sharp シャープ Images: イメージ: Import Keyboard Shortcuts… キーボードショートカットを読み込み… Import PDF PDF を読み込み + Import PDF pages as links PDF ページをリンクとして読み込み Import PDF Presets PDF プリセットを読み込み Import Perspective Grid Presets 遠近グリッドプリセットを読み込み Import Print Presets プリントプリセットを読み込み @@ -3758,6 +3775,7 @@ gradient-kind Radial 円形 Convert To Outlines アウトラインに変換 Copy All Objects すべてのオブジェクトをコピー Copy Fonts Used in the Document ドキュメントで使用しているフォントをコピー + Copy Info 情報をコピー Copy Links リンクをコピー Couldn't copy to the system clipboard: {e} システムのクリップボードにコピーできませんでした:{e} Couldn't paste from the clipboard: {e} クリップボードからペーストできませんでした:{e} @@ -4023,6 +4041,7 @@ file-filter Templates テンプレート Small Thumbnails 小さいサムネール Smooth Color スムーズカラー Social Square Post 1080×1080 ソーシャル正方形投稿 1080×1080 + Sort by Size サイズ順に並べ替え Sort by Status 状態順に並べ替え Specified Distance 距離 Specified Steps ステップ数 @@ -4247,6 +4266,7 @@ theme Appearance 外観 # Photoshop-style raster effects (Effect menu, their dialogs). Radial Blur… ぼかし (放射状)… + Blur Center ぼかしの中心 Smart Blur… ぼかし (詳細)… Sharpen シャープ Unsharp Mask… アンシャープマスク… @@ -5191,6 +5211,7 @@ swatch Bright Violet ビビッドバイオレット @msg there is no script engine named {name} {name} という名前のスクリプトエンジンはありません @msg Running a script スクリプトを実行中 @msg Copied the script report スクリプトのレポートをコピーしました +@msg Copied the link info リンク情報をコピーしました @msg Exported {path} {path} を書き出しました @msg no CSS to copy: select objects with CSS of their own コピーする CSS がありません: 独自の CSS を持つオブジェクトを選択してください @msg unknown highlight `{h}` `{h}` は不明なハイライトの指定です @@ -6343,6 +6364,1812 @@ axis Y Axis Y 軸 @msg no menu item that can be inserted runs this command このコマンドを実行する、挿入できるメニュー項目はありません @msg the action already has 10,000 steps アクションにはすでに 10,000 ステップがあります @msg the action set would be larger than 8 MiB アクションセットが 8 MiB を超えます +@msg 'caller', 'callee' and 'arguments' cannot be used on strict mode functions strict モードの関数では 'caller'、'callee'、'arguments' を使用できません +@msg Alignment must be one of the choices 揃えには選択肢のいずれかを指定してください +@msg Boolean.prototype.{name} was called on a value that is not a Boolean Boolean.prototype.{name} が Boolean ではない値に対して呼び出されました +@msg CMYK images whose samples couldn't be read in CMYK were imported in RGB サンプルを CMYK で読み取れなかった CMYK 画像は RGB で読み込みました +@msg Cannot write to the location of “{name}”; choose where to save it 「{name}」の場所に書き込めません。保存先を選択してください +@msg DCS files can only be placed linked: use File › Place with Link on DCS ファイルはリンクとしてのみ配置できます: 「リンク」をオンにして「ファイル › 配置」を使用してください +@msg Date.prototype method called on a value that is not a Date object Date.prototype のメソッドが Date オブジェクトではない値に対して呼び出されました +@msg Error.prototype.toString was called on a value that is not an object Error.prototype.toString がオブジェクトではない値に対して呼び出されました +@msg Function.prototype.toString was called on a value that is not a function Function.prototype.toString が関数ではない値に対して呼び出されました +@msg Import SVG Filter reads SVG files, not SVGZ 「SVG フィルターを読み込み」が読み込むのは SVG ファイルで、SVGZ ファイルは読み込みません +@msg JSON.parse: {why} (at offset {at}) JSON.parse: {why} (オフセット {at}) +@msg JSON.stringify cannot write a structure that contains itself JSON.stringify は自身を含む構造を書き出せません +@msg Line Gap must be a number 行間には数値を指定してください +@msg Namespace.prototype.toString needs a Namespace Namespace.prototype.toString には Namespace が必要です +@msg New Document profiles need the preferences folder, which this run doesn't have 新規ドキュメントプロファイルには環境設定フォルダーが必要ですが、この実行環境にはありません +@msg Number.prototype.{name} was called on a value that is not a number Number.prototype.{name} が数値ではない値に対して呼び出されました +@msg Object.create's prototype must be an object or null Object.create のプロトタイプにはオブジェクトまたは null を指定してください +@msg Object.{function} was given a value that is not an object Object.{function} にオブジェクトではない値が渡されました +@msg QName.prototype.toString needs a QName QName.prototype.toString には QName が必要です +@msg RegExp.prototype.{name} was called on a value that is not a RegExp object RegExp.prototype.{name} が RegExp オブジェクトではない値に対して呼び出されました +@msg Stencil Bridges: the selected art is too large or too detailed to bridge ステンシルブリッジ: 選択したアートが大きすぎるか細かすぎるため、ブリッジを作成できません +@msg String.prototype.toString was called on a value that is not a string String.prototype.toString が文字列ではない値に対して呼び出されました +@msg The {name} profile could not be read, so the new document has the default settings: {reason} {name} プロファイルを読み込めなかったため、新規ドキュメントには初期設定を使用しました: {reason} +@msg Trap: more than {_1} pairs of objects lie close enough to trap, or too many objects share a horizontal range; trap fewer objects at a time トラップ: トラップできるほど近いオブジェクトの組が {_1} 組を超えているか、水平方向の範囲が重なるオブジェクトが多すぎます。一度にトラップするオブジェクトを減らしてください +@msg Weed Box and Lines: no weeding line fits outside the art, and the weed box is off カス取り枠とライン: アートの外側に収まるカス取りラインがなく、カス取り枠もオフになっています +@msg \\ at end of pattern パターンの末尾に \\ があります +@msg `alignOn` cannot be empty `alignOn` を空にすることはできません +@msg `alignOn` must be a string `alignOn` には文字列を指定してください +@msg `align` must be a string `align` には文字列を指定してください +@msg `answer` for this {kind} dialog must be one of: {_1} この {kind} ダイアログの `answer` には次のいずれかを指定してください: {_1} +@msg `answers` has more than {MAX_ANSWERS} answers `answers` の回答が {MAX_ANSWERS} 個を超えています +@msg `answers` is larger than 1 MiB `answers` が 1 MiB を超えています +@msg `answers` must be a list of answers `answers` には回答のリストを指定してください +@msg `artboard` must be the index of an artboard of the document `artboard` にはドキュメントのアートボードのインデックスを指定してください +@msg `artboardsAt` must be [x, y] `artboardsAt` には [x, y] を指定してください +@msg `artboards` names an artboard the document does not have `artboards` にドキュメントにないアートボードが指定されています +@msg `artboards` names an artboard twice `artboards` に同じアートボードが 2 回指定されています +@msg `at` must be [x, y] (got {at}) `at` には [x, y] を指定してください (指定値: {at}) +@msg `at` must be a point [x, y] `at` には点 [x, y] を指定してください +@msg `beside` needs `side` `beside` には `side` が必要です +@msg `code` must be a whole number `code` には整数を指定してください +@msg `colorMode` must be one of rgb, cmyk `colorMode` には rgb、cmyk のいずれかを指定してください +@msg `colors` does not apply to the {name} reduction `colors` は {name} 減色には適用されません +@msg `colors` must be a whole number from 2 to 256 `colors` には 2 から 256 までの整数を指定してください +@msg `colors` must be at least 9 for the uniform reduction 均等減色では `colors` に 9 以上を指定してください +@msg `colors` must be between 1 and {MAX_THEME_COLORS} (got {n}) `colors` には 1 から {MAX_THEME_COLORS} までの値を指定してください (指定値: {n}) +@msg `count` must be a whole number from 0 to {MAX_COUNT} `count` には 0 から {MAX_COUNT} までの整数を指定してください +@msg `ditherAmount` must be a number from 0 to 100 `ditherAmount` には 0 から 100 までの数値を指定してください +@msg `fidelity` must be from {lo} to {hi} pt `fidelity` には {lo}~{hi} pt の値を指定してください +@msg `focal` and `radius` cannot be used together `focal` と `radius` は同時に使用できません +@msg `focal` must be an array of [subpath, anchor] pairs `focal` には [subpath, anchor] の組の配列を指定してください +@msg `focal` names [{si}, {ai}], which is not an anchor of the path `focal` に指定された [{si}, {ai}] はパスのアンカーではありません +@msg `glyphAlternate` takes only null, which takes a glyph choice away (text.setGlyphAlternate makes one) `glyphAlternate` に指定できるのは null のみで、字形の選択を解除します (選択は text.setGlyphAlternate で行います) +@msg `group` must be one of {_1} `group` には {_1} のいずれかを指定してください +@msg `group` must be the Objects on Path group of `member` and `target` `group` には `member` と `target` のパス上のオブジェクトグループを指定してください +@msg `id` is an object id, not {v} `id` にはオブジェクト ID を指定してください ({v} は指定できません) +@msg `item` needs `index` `item` には `index` が必要です +@msg `kerningBefore` belongs to a line's first character, not to a character style (text.setRangeStyle sets it) `kerningBefore` は文字スタイルではなく行の先頭文字の設定です (text.setRangeStyle で設定します) +@msg `kinsokuType` must be "pushInFirst", "pushOutFirst" or "pushOutOnly" `kinsokuType` には "pushInFirst"、"pushOutFirst"、"pushOutOnly" のいずれかを指定してください +@msg `leader` must be a string `leader` には文字列を指定してください +@msg `max` must be 1 to {MAX_SUGGESTIONS} `max` には 1~{MAX_SUGGESTIONS} を指定してください +@msg `name` must be a name that is not empty `name` には空でない名前を指定してください +@msg `name` must not be empty `name` を空にすることはできません +@msg `origin` must be [x, y] in points `origin` にはポイント単位の [x, y] を指定してください +@msg `picks` must be an array (got {v}) `picks` には配列を指定してください (指定値: {v}) +@msg `picks` must hold 1 to {MAX_PICKS} picks (got {_1}) `picks` には 1~{MAX_PICKS} 個の指定が必要です (指定数: {_1}) +@msg `points` must hold from 2 to 100000 points `points` には 2~100000 個の点が必要です +@msg `radius` must be 0 or more `radius` には 0 以上を指定してください +@msg `rect` must be [x, y, width, height] `rect` には [x, y, width, height] を指定してください +@msg `rect` must be [x0, y0, x1, y1] (got {r}) `rect` には [x0, y0, x1, y1] を指定してください (指定値: {r}) +@msg `replace` must be a string `replace` には文字列を指定してください +@msg `rows` must be lists of numbers or nulls, not {r} `rows` には数値または null のリストを指定してください ({r} は指定できません) +@msg `scale` must be a number from 0.001 to 1000 `scale` には 0.001 から 1000 までの数値を指定してください +@msg `scope.{key}` must be a non-empty array `scope.{key}` には空でない配列を指定してください +@msg `scope` must be "document", {artboards} or {layers} `scope` には "document"、{artboards}、{layers} のいずれかを指定してください +@msg `side` must be "left", "right", "top" or "bottom" `side` には "left"、"right"、"top"、"bottom" のいずれかを指定してください +@msg `side` places the artboard: leave out x, y, width and height `side` でアートボードを配置します: x、y、width、height は省略してください +@msg `source` is the only path in series group `target` `source` は系列グループ `target` の唯一のパスです +@msg `spacing` makes more than {MAX_COUNT} lines across the box `spacing` ではボックス全体のラインが {MAX_COUNT} 本を超えます +@msg `spacing` must be more than 0 and at most {MAX_DISTANCE} pt `spacing` には 0 より大きく {MAX_DISTANCE} pt 以下の値を指定してください +@msg `target` must be an object of the same Objects on Path group as `member` `target` には `member` と同じパス上のオブジェクトグループのオブジェクトを指定してください +@msg `tolerance` must be from 0 to 100 pt `tolerance` には 0~100 pt の値を指定してください +@msg `version` must be 0 or {_1} `version` には 0 または {_1} を指定してください +@msg `version` must be 0 or {newest} `version` には 0 または {newest} を指定してください +@msg `warichuAlign` must be one of {_1} `warichuAlign` には {_1} のいずれかを指定してください +@msg `warichuLines` must be a whole number from {_1} to {_2} `warichuLines` には {_1} から {_2} までの整数を指定してください +@msg `weight` must be from 0.01 to 1000 pt `weight` には 0.01~1000 pt の値を指定してください +@msg `weights` must be a list of {_1} numbers, one per row (got {v}) `weights` には行ごとに 1 つずつ、{_1} 個の数値のリストを指定してください (指定値: {v}) +@msg `xml` must be a string `xml` には文字列を指定してください +@msg `{KEY}` entry {n} gives the paragraph at byte {start} of {_1} other indents than an entry before it `{KEY}` のエントリ {n} は、{_1} のバイト {start} の段落に、前のエントリとは異なるインデントを指定しています +@msg `{KEY}` entry {n} must be an object `{KEY}` のエントリ {n} にはオブジェクトを指定してください +@msg `{KEY}` entry {n} sets neither `leftIndent` nor `firstLineIndent` `{KEY}` のエントリ {n} は `leftIndent` も `firstLineIndent` も設定していません +@msg `{KEY}` entry {n}: `id` must be an object id `{KEY}` のエントリ {n}: `id` にはオブジェクト ID を指定してください +@msg `{KEY}` entry {n}: `start` must be a byte offset `{KEY}` のエントリ {n}: `start` にはバイトオフセットを指定してください +@msg `{KEY}` entry {n}: `{k}` must be a number from -{MAX_PARA} to {MAX_PARA} pt `{KEY}` のエントリ {n}: `{k}` には -{MAX_PARA}~{MAX_PARA} pt の数値を指定してください +@msg `{KEY}` entry {n}: no paragraph of {_1} starts at byte {start} `{KEY}` のエントリ {n}: {_1} にはバイト {start} から始まる段落がありません +@msg `{KEY}` entry {n}: unknown key `{k}` `{KEY}` のエントリ {n}: `{k}` は不明なキーです +@msg `{KEY}` entry {n}: {_1} is not a type object `{KEY}` のエントリ {n}: {_1} はテキストオブジェクトではありません +@msg `{KEY}` is empty `{KEY}` が空です +@msg `{KEY}` must be a list `{KEY}` にはリストを指定してください +@msg `{KEY}` takes at most {MAX_PARAGRAPH_INDENTS} entries (got {_1}) `{KEY}` に指定できるエントリは最大 {MAX_PARAGRAPH_INDENTS} 個です (指定数: {_1}) +@msg `{KEY}` takes no `{other}` beside it `{KEY}` と一緒に `{other}` は指定できません +@msg `{base}` is larger than {_1} MB `{base}` は {_1} MB を超えています +@msg `{base}` is not in the DCS file's folder `{base}` は DCS ファイルのフォルダーにありません +@msg `{key}` holds more than {MAX_EDIT_WORDS} words `{key}` の単語が {MAX_EDIT_WORDS} 個を超えています +@msg `{key}` must be 0 or more `{key}` には 0 以上を指定してください +@msg `{key}` must be [x, y] numbers `{key}` には数値の [x, y] を指定してください +@msg `{key}` must be a list of words `{key}` には単語のリストを指定してください +@msg `{key}` must be a list, not {v} `{key}` にはリストを指定してください ({v} は指定できません) +@msg `{key}` must be a number or null, not {v} `{key}` には数値または null を指定してください ({v} は指定できません) +@msg `{key}` must be a whole number of 0 or more `{key}` には 0 以上の整数を指定してください +@msg `{key}` must be from 0 to {MAX_DISTANCE} pt `{key}` には 0~{MAX_DISTANCE} pt の値を指定してください +@msg `{key}` must be from {lo} to {hi}, not {v} `{key}` には {lo}~{hi} の値を指定してください ({v} は指定できません) +@msg `{key}` must be one of auto, always, never `{key}` には auto、always、never のいずれかを指定してください +@msg `{key}` must be one of miter, round, bevel `{key}` には miter、round、bevel のいずれかを指定してください +@msg `{key}` must be one word of at most {_1} characters `{key}` には {_1} 文字以内の 1 語を指定してください +@msg `{key}` must hold single words of at most {_1} characters `{key}` には {_1} 文字以内の単語を 1 語ずつ指定してください +@msg `{key}` must name an object attached to the path of an Objects on Path group `{key}` にはパス上のオブジェクトグループのパスに配置されたオブジェクトを指定してください +@msg `{key}` names an object that is hidden or locked `{key}` に指定されたオブジェクトは非表示またはロックされています +@msg `{name}` is a file of its own, which can only be found next to the DCS file's path `{name}` は独立したファイルで、DCS ファイルのパスと同じ場所でのみ見つけられます +@msg `{name}`: {_1}: {e} `{name}`: {_1}: {e} +@msg `{u}` is no Unicode character `{u}` は Unicode 文字ではありません +@msg `{word}` isn't in the custom dictionary `{word}` はカスタム辞書にありません +@msg a CMap has too many mappings CMap のマッピングが多すぎます +@msg a \\u escape needs four hexadecimal digits \\u エスケープには 4 桁の 16 進数が必要です +@msg a comma in an XPath expression must separate function arguments XPath 式のカンマは関数の引数を区切るものでなければなりません +@msg a document holds at most {_1} SVG filters ドキュメントに含められる SVG フィルターは最大 {_1} 個です +@msg a document with unsaved changes has no recovery copy 未保存の変更があるドキュメントに復帰用のコピーがありません +@msg a font's data is too large フォントのデータが大きすぎます +@msg a font's subroutines are too large フォントのサブルーチンが大きすぎます +@msg a function declaration without a name 名前のない関数宣言です +@msg a host value has too many entries ホストの値のエントリが多すぎます +@msg a host value is nested too deep ホストの値の入れ子が深すぎます +@msg a namespace declaration uses a reserved prefix or URI 名前空間の宣言で予約済みのプレフィックスまたは URI が使用されています +@msg a namespace qualifier is undefined 名前空間の修飾子が定義されていません +@msg a namespace with an empty URI cannot have a prefix URI が空の名前空間にはプレフィックスを付けられません +@msg a number has no digits 数値に数字がありません +@msg a number's exponent has no digits 数値の指数部に数字がありません +@msg a number's fraction has no digits 数値の小数部に数字がありません +@msg a property descriptor cannot have both a value or writable and a get or set プロパティ記述子に value または writable と get または set の両方を指定することはできません +@msg a property descriptor must be an object プロパティ記述子にはオブジェクトを指定してください +@msg a property's {name} must be a function or undefined プロパティの {name} には関数または undefined を指定してください +@msg a stream in it would decode to more than 256 MB, or its decode parameters can't be applied 含まれるストリームをデコードすると 256 MB を超えるか、デコードパラメーターを適用できません +@msg a string holds a control character 文字列に制御文字が含まれています +@msg a string holds an escape sequence JSON does not have 文字列に JSON にないエスケープシーケンスが含まれています +@msg a string is not closed 文字列が閉じていません +@msg an SVG filter is named by its id: give `xml` with `name` SVG フィルターの名前はその ID です: `xml` と `name` を指定してください +@msg an XML element has two attributes with the same name XML 要素に同じ名前の属性が 2 つあります +@msg an XML value cannot be inserted into itself or its descendants XML 値をそれ自身またはその子孫に挿入することはできません +@msg an XML value's children cannot be assigned by position XML 値の子を位置で代入することはできません +@msg an XML value's children cannot be deleted by position XML 値の子を位置で削除することはできません +@msg an XMLList converts to XML only when it has one item XMLList を XML に変換できるのは、項目が 1 つの場合だけです +@msg an XPath node test is missing XPath のノードテストがありません +@msg an XPath operand is missing XPath のオペランドがありません +@msg an XPath operator is missing XPath の演算子がありません +@msg an XPath predicate or step cannot follow here ここに XPath の述語やステップを続けることはできません +@msg an XPath predicate or step follows a value that is not a node-set XPath の述語またはステップがノードセットではない値の後にあります +@msg an XPath step is missing XPath のステップがありません +@msg an image couldn't be decoded and is missing from the picture 画像をデコードできなかったため、図に含まれていません +@msg an image of {w} × {h} pixels is too large to convert (at most {_1} pixels) {w} × {h} ピクセルの画像は大きすぎて変換できません (最大 {_1} ピクセル) +@msg apply was called on a value that is not a function apply が関数ではない値に対して呼び出されました +@msg area type in a thread cannot use Dynamic Text: {frames} スレッド内のエリア内文字ではダイナミックテキストを使用できません: {frames} +@msg array literal too long 配列リテラルが長すぎます +@msg assignment to a constant binding 定数バインディングへの代入です +@msg at least one row that isn't excluded needs a weight above 0 除外されていない行の少なくとも 1 つに 0 より大きいウェイトが必要です +@msg bad point {v}: expected [x, y] 点 {v} が正しくありません: [x, y] を指定してください +@msg blend must be a mode name blend には描画モードの名前を指定してください +@msg both sides of an XPath | must select nodes XPath の | の両辺でノードを選択する必要があります +@msg canceled キャンセルしました +@msg cannot convert the object to a primitive value オブジェクトをプリミティブ値に変換できません +@msg cannot convert undefined or null to an object undefined または null をオブジェクトに変換できません +@msg character dimensions cannot be represented with the source text transform 文字の寸法をソースのテキスト変形で表すことができません +@msg character dimensions cannot be represented with the target text transform 文字の寸法をターゲットのテキスト変形で表すことができません +@msg continuation must be an array of path chunks continuation にはパスチャンクの配列を指定してください +@msg continuation requires points continuation には点が必要です +@msg each path chunk must contain 1 to 4096 points 各パスチャンクには 1~4096 個の点が必要です +@msg each pick is {{at: [x, y]}} or {{rect: [x0, y0, x1, y1]}} (got {v}) 各指定は {{at: [x, y]}} または {{rect: [x0, y0, x1, y1]}} です (指定値: {v}) +@msg each weight must be a number of 0 or more (got {v}) 各ウェイトには 0 以上の数値を指定してください (指定値: {v}) +@msg finally table {t} out of range finally テーブル {t} が範囲外です +@msg flags cannot be given with a RegExp object RegExp オブジェクトと一緒にフラグを指定することはできません +@msg function declaration index out of range 関数宣言のインデックスが範囲外です +@msg give `char`, `text`, `code` or `unicode` `char`、`text`、`code`、`unicode` のいずれかを指定してください +@msg give `count` or `spacing`, not both `count` または `spacing` のどちらか一方を指定してください +@msg give `name`, an SVG filter's name SVG フィルターの名前を `name` に指定してください +@msg give `path`, an SVG file, or `svg`, SVG text SVG ファイルを `path` に、または SVG テキストを `svg` に指定してください +@msg give `xml`, one SVG element SVG の 要素を 1 つ `xml` に指定してください +@msg give exactly one of `at`, `rect` and `points` `at`、`rect`、`points` のうち 1 つだけを指定してください +@msg give exactly one of `path`, `data` and `dataBase64` `path`、`data`、`dataBase64` のうち 1 つだけを指定してください +@msg give index or indexes, not both index または indexes のどちらか一方を指定してください +@msg give one element 要素を 1 つ指定してください +@msg give opacity or blend opacity または blend を指定してください +@msg handler at {_1} expects {_2} values but its range starts with {d} {_1} のハンドラーは {_2} 個の値を想定していますが、範囲の開始時は {d} 個です +@msg handler depth too large ハンドラーの深さが大きすぎます +@msg handler range {_1}..{_2} out of range ハンドラーの範囲 {_1}..{_2} が範囲外です +@msg hiddenLayers must be true or false hiddenLayers には true または false を指定してください +@msg hvcC hvcC +@msg images in a spot ink whose samples couldn't be read were imported in RGB サンプルを読み取れなかった特色インキの画像は RGB で読み込みました +@msg images past the most pixels one file may hold were left out 1 つのファイルに含められる最大ピクセル数を超えた画像は除外しました +@msg images too large to read were left out 大きすぎて読み込めない画像は除外しました +@msg indexes may hold at most {MAX_GUIDE_INDEXES} entries indexes に指定できるエントリは最大 {MAX_GUIDE_INDEXES} 個です +@msg indexes must be an array of guide indexes indexes にはガイドのインデックスの配列を指定してください +@msg instruction out of range 命令が範囲外です +@msg instruction {pc} ({op}) pops below the stack 命令 {pc} ({op}) がスタックの底を超えて取り出しています +@msg instruction {pc} reached with stack depths {seen} and {d} 命令 {pc} にスタックの深さ {seen} と {d} で到達しました +@msg invalid array length 配列の長さが無効です +@msg invalid group グループが無効です +@msg invalid object id {v}: expected a non-negative integer オブジェクト ID {v} が無効です: 0 以上の整数を指定してください +@msg invalid regular expression flag '{_1}' 正規表現のフラグ '{_1}' が無効です +@msg invalid regular expression: {m} 正規表現が無効です: {m} +@msg invalid time value 時刻の値が無効です +@msg is a confirm's answer, whose `value` must be true or false は confirm の回答で、`value` には true または false を指定してください +@msg is a prompt's answer, whose `value` must be a string or null は prompt の回答で、`value` には文字列または null を指定してください +@msg is an alert's answer, whose `value` must be "ok" は alert の回答で、`value` には "ok" を指定してください +@msg is longer than 16 KiB が 16 KiB を超えています +@msg it draws its image through a clipping path クリッピングパスを通して画像を描画しています +@msg it draws no image 画像を描画していません +@msg it is larger than {MAX_DICTIONARY_FILE_BYTES} bytes {MAX_DICTIONARY_FILE_BYTES} バイトを超えています +@msg it isn't a file ファイルではありません +@msg it names {_1} plates, and at most {MAX_PLATES} are read {_1} 個の版が指定されていますが、読み込めるのは最大 {MAX_PLATES} 個です +@msg its art is too long or too detailed for a head アートが長すぎるか細かすぎるため、矢印にできません +@msg its art paints nothing アートが何も描画しません +@msg its image is too large to read 画像が大きすぎて読み込めません +@msg its plates are too large: more than {MAX_SAMPLES} pixels together 版が大きすぎます: 合計で {MAX_SAMPLES} ピクセルを超えています +@msg its plates are too large: {_1} plates of {w} × {h} pixels 版が大きすぎます: {w} × {h} ピクセルの版が {_1} 個あります +@msg its plates can't be kept together 版をまとめて保持できません +@msg its shapes could not be combined into one シェイプを 1 つに結合できませんでした +@msg jump to {pc}, past the end 末尾を超えた {pc} へのジャンプです +@msg legacyNameEncoding must be one of {_1} legacyNameEncoding には {_1} のいずれかを指定してください +@msg localize: the first argument must be a localization object or a string localize: 最初の引数にはローカライズオブジェクトまたは文字列を指定してください +@msg missing `picks` `picks` がありません +@msg missing `word` `word` がありません +@msg must be an object with `kind` and `value` には `kind` と `value` を持つオブジェクトを指定してください +@msg must have `kind` alert, confirm or prompt の `kind` には alert、confirm、prompt のいずれかを指定してください +@msg must have exactly `kind` and `value` には `kind` と `value` だけを指定してください +@msg needs a closing quote after the name 名前の後に閉じ引用符が必要です +@msg needs a name 名前が必要です +@msg needs a name of at most 64 bytes 64 バイト以内の名前が必要です +@msg needs a name of letters, digits and _, or a quoted name 文字、数字、_ からなる名前、または引用符で囲んだ名前が必要です +@msg needs a name without control characters 制御文字を含まない名前が必要です +@msg nesting too deep 入れ子が深すぎます +@msg no HP-GL format HP-GL 形式はありません +@msg no New Document profile called `{shown}` ({_1}) `{shown}` という新規ドキュメントプロファイルはありません ({_1}) +@msg no SVG filter at index {k} インデックス {k} に SVG フィルターはありません +@msg no arrowheads file here ここに矢印ファイルはありません +@msg no character has code {code} コード {code} の文字はありません +@msg no custom arrowhead {name} (see stroke.arrowheads.list) カスタム矢印 {name} はありません (stroke.arrowheads.list を参照) +@msg no file to open 開くファイルがありません +@msg no instructions 命令がありません +@msg no layer to rename 名前を変更するレイヤーがありません +@msg no random numbers ({e}) 乱数を取得できません ({e}) +@msg no selected or given object has a visible 3D effect 選択または指定したオブジェクトに、表示されている 3D 効果がありません +@msg no such artboard {v} アートボード {v} はありません +@msg no symbol named `{_1}` `{_1}` という名前のシンボルはありません +@msg node {_1} already has the text variable `{_2}` ノード {_1} にはすでにテキスト変数 `{_2}` があります +@msg not a DCS file DCS ファイルではありません +@msg not a RegExp object RegExp オブジェクトではありません +@msg not a regular expression 正規表現ではありません +@msg not an action set: the text doesn't start with /version and a number アクションセットではありません: テキストが /version と数値で始まっていません +@msg nothing to repeat 繰り返す対象がありません +@msg numbers out of order in {_1} quantifier {_1} 量指定子の数値の順序が正しくありません +@msg object {_1} needs a 3D effect オブジェクト {_1} には 3D 効果が必要です +@msg object {_1}: a hollow Extrude & Bevel has no caps: turn on Cap to map a graphic オブジェクト {_1}: 中空の「押し出しとベベル」にはキャップがありません: グラフィックをマッピングするには「キャップ」をオンにしてください +@msg object {_1}: with a depth of 0 the object has one face: map its graphics onto the front オブジェクト {_1}: 奥行きが 0 のオブジェクトは面が 1 つです: グラフィックは前面にマッピングしてください +@msg object {_1}: {_2} オブジェクト {_1}: {_2} +@msg object {_1}: {e} オブジェクト {_1}: {e} +@msg object {_1}: {name} at index {index} has no lighting presets; set its lights with effect.setParams オブジェクト {_1}: インデックス {index} の {name} には照明プリセットがありません。ライトは effect.setParams で設定してください +@msg opacity must be a number opacity には数値を指定してください +@msg operand too large オペランドが大きすぎます +@msg order is a whole number from 0 to {others}, not `{v}` order には 0 から {others} までの整数を指定してください (`{v}` は指定できません) +@msg path chunks must share their boundary point パスの分割部分は境界点を共有している必要があります +@msg pdfCompatible: false needs the artboards to keep the editable artwork when useArtboards is false pdfCompatible: false の場合、useArtboards が false のときは、編集可能なアートワークを保持するためにアートボードが必要です +@msg point x must be a number 点の x には数値を指定してください +@msg point y must be a number 点の y には数値を指定してください +@msg points must be [x,y] pairs points には [x,y] の組を指定してください +@msg points must be finite canvas points points にはキャンバス上の有限の点を指定してください +@msg range out of order in character class 文字クラス内の範囲の順序が正しくありません +@msg reduce of an empty array with no initial value 初期値のない空の配列に対する reduce です +@msg regular expression flag '{_1}' given twice 正規表現のフラグ '{_1}' が 2 回指定されています +@msg sampled text would exceed the canvas (coordinates out of range) サンプリングしたテキストがキャンバスを超えます (座標が範囲外) +@msg select an SVG filter SVG フィルターを選択してください +@msg select an object with a 3D effect 3D 効果のあるオブジェクトを選択してください +@msg select an object with a 3D effect, or give its id in ids 3D 効果のあるオブジェクトを選択するか、その ID を ids に指定してください +@msg select one layer, group or object to rename 名前を変更するレイヤー、グループ、オブジェクトのいずれかを 1 つ選択してください +@msg select the art to weed カス取りするアートを選択してください +@msg select type on a path or area type パス上文字またはエリア内文字を選択してください +@msg side is left or right, not `{v}` side には left または right を指定してください (`{v}` は指定できません) +@msg source text transform is collapsed or unrepresentable 元のテキストの変形がつぶれているか、表現できません +@msg table must be true or false table には true または false を指定してください +@msg takes one name 名前を 1 つ指定してください +@msg target text transform is collapsed or unrepresentable 対象のテキストの変形がつぶれているか、表現できません +@msg that makes too many pieces (at most 100000) or dash steps: simplify the dash pattern or make the dashes longer 分割数 (最大 100000) またはダッシュの段数が多くなりすぎます: 破線パターンを単純にするか、ダッシュを長くしてください +@msg the Layers panel is not shown レイヤーパネルが表示されていません +@msg the Layers panel's search, filter or Show Layers Only hides its row レイヤーパネルの検索、フィルター、「レイヤーのみを表示」のいずれかでその行が隠れています +@msg the Objects on Path group is hidden or locked 「パス上のオブジェクト」グループが非表示またはロックされています +@msg the SVG file is larger than {MAX_IMPORT_BYTES} bytes SVG ファイルが {MAX_IMPORT_BYTES} バイトを超えています +@msg the XML operation needs an XML or XMLList value XML 操作には XML または XMLList の値が必要です +@msg the XPath expression does not evaluate to a node-set XPath 式の評価結果がノードセットではありません +@msg the XPath expression ends early XPath 式が途中で終わっています +@msg the XPath expression has an unmatched ) XPath 式に対応していない ) があります +@msg the XPath expression has an unmatched ] XPath 式に対応していない ] があります +@msg the XPath expression has an unmatched closing bracket XPath 式に対応していない閉じ括弧があります +@msg the XPath expression selects a namespace node, which is not an XML value XPath 式が名前空間ノードを選択していますが、これは XML の値ではありません +@msg the XPath expression selects the root node, which is not an XML value XPath 式がルートノードを選択していますが、これは XML の値ではありません +@msg the XPath function {name} needs a node-set XPath 関数 {name} にはノードセットが必要です +@msg the XPath function {name} takes the wrong number of arguments XPath 関数 {name} の引数の数が正しくありません +@msg the XPath name functions need a node-set XPath の名前関数にはノードセットが必要です +@msg the XPath prefix {shown} is not bound to a namespace XPath の接頭辞 {shown} は名前空間に結び付けられていません +@msg the XPath variable ${shown} is not bound XPath 変数 ${shown} は束縛されていません +@msg the argument list is not an object 引数リストがオブジェクトではありません +@msg the artwork is too large for EPS: what follows 256 MB of PostScript was left out アートワークが EPS には大きすぎます: PostScript の 256 MB より後の部分は除外しました +@msg the bitmaps hold more pixels than one file may ビットマップのピクセル数が 1 つのファイルに含められる数を超えています +@msg the code runs past its last instruction コードが最後の命令を超えて実行されます +@msg the curve tolerance must be from 0.01 to 10 points 曲線の許容値には 0.01 から 10 ポイントまでの値を指定してください +@msg the custom dictionary couldn't be saved to {_1}: {e} カスタム辞書を {_1} に保存できませんでした: {e} +@msg the custom dictionary {_1} can't be read ({why}), so it is left as it is カスタム辞書 {_1} を読み込めないため ({why})、そのまま残しました +@msg the document already has an SVG filter named {name} ドキュメントにはすでに {name} という名前の SVG フィルターがあります +@msg the document has another SVG filter named {name}: use svgFilter.apply, or svgFilter.define with `replace` to edit it ドキュメントには {name} という名前の別の SVG フィルターがあります: svgFilter.apply を使用するか、編集するには `replace` を付けて svgFilter.define を使用してください +@msg the document has no SVG filter named {name} ドキュメントに {name} という名前の SVG フィルターはありません +@msg the document has no SVG filter named {r} ドキュメントに {r} という名前の SVG フィルターはありません +@msg the document has no color swatches ドキュメントにカラースウォッチがありません +@msg the document's swatches hold {_1} colors; the document reduction takes at most 255 ドキュメントのスウォッチには {_1} 色ありますが、ドキュメント減色で使用できるのは最大 255 色です +@msg the file isn't valid SVG: {e} ファイルが有効な SVG ではありません: {e} +@msg the file names no plate ファイルに版が指定されていません +@msg the function's prototype is not an object 関数のプロトタイプがオブジェクトではありません +@msg the guide is hidden or locked ガイドが非表示またはロックされています +@msg the library's file is outside the read roots ライブラリのファイルが読み取りルートの外にあります +@msg the line is too long, or the paths it passes too many, to check 線が長すぎるか、通過するパスが多すぎるため、確認できません +@msg the method needs an XML value このメソッドには XML の値が必要です +@msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) ペイントがフリーフォームグラデーションではありません (paint.editGradient {kind} で適用してください) +@msg the parameters or body do not form one function パラメーターまたは本体が 1 つの関数になっていません +@msg the pasted SVG filter {name} draws differently from the document's filter of that name, and no free name fits it ペーストした SVG フィルター {name} は、ドキュメントにある同名のフィルターと描画結果が異なり、使用できる空き名もありません +@msg the paths are too many or too tangled to find where they cross パスが多すぎるか複雑に絡み合っているため、交差する位置を見つけられません +@msg the pen table holds more than 255 pens ペンテーブルに 255 本を超えるペンがあります +@msg the plates can't be kept 版を保持できません +@msg the position table does not match the instructions 位置テーブルが命令と一致しません +@msg the prompt's text is longer than {MAX_PROMPT_BYTES} bytes prompt のテキストが {MAX_PROMPT_BYTES} バイトを超えています +@msg the radix must be between 2 and 36 基数には 2 から 36 までの値を指定してください +@msg the rectangle or line reaches too many paths to check 長方形または線にかかるパスが多すぎるため、確認できません +@msg the right side of 'in' is not an object 'in' の右辺がオブジェクトではありません +@msg the right side of 'instanceof' is not a function 'instanceof' の右辺が関数ではありません +@msg the selected art is nested more than {MAX_DEPTH} levels deep 選択したアートの入れ子が {MAX_DEPTH} 階層を超えています +@msg the selected art is too large to measure 選択したアートが大きすぎて計測できません +@msg the selection has no outlines to weed around 選択範囲に、カス取りの対象となるアウトラインがありません +@msg the value bind was called on is not a function bind の呼び出し対象の値が関数ではありません +@msg the value is not a constructor 値がコンストラクターではありません +@msg the value is not a function 値が関数ではありません +@msg the value is not a valid XML name 値が有効な XML 名ではありません +@msg the value is not an XML attribute name 値が XML 属性名ではありません +@msg the value is not an XML name 値が XML 名ではありません +@msg the weeding lines cross the art's outlines too many times to measure; use fewer lines カス取りラインがアートのアウトラインと交差する回数が多すぎて計測できません。ラインの数を減らしてください +@msg the weeding lines pass too close to too many outline segments to measure; use fewer lines or a smaller gap カス取りラインに近すぎるアウトラインのセグメントが多すぎて計測できません。ラインの数を減らすか、間隔を小さくしてください +@msg the weeding lines would be more than {max_pieces} pieces カス取りラインが {max_pieces} 個を超えます +@msg the {_1} plate lies outside the file {_1} 版がファイルの外にあります +@msg this is a binary DXF file, which can't be read: save it from the CAD app as an ASCII DXF and open that これはバイナリ DXF ファイルのため読み込めません: CAD アプリで ASCII DXF として保存し、そのファイルを開いてください +@msg this warp's points can't be edited: use Reset with Mesh first このワープのポイントは編集できません: 先に「メッシュでリセット」を使用してください +@msg toExponential() digits must be between 0 and 20 toExponential() の桁数には 0 から 20 までの値を指定してください +@msg toFixed() digits must be between 0 and 20 toFixed() の桁数には 0 から 20 までの値を指定してください +@msg toISOString is not a function toISOString は関数ではありません +@msg toPrecision() argument must be between 1 and 21 toPrecision() の引数には 1 から 21 までの値を指定してください +@msg toSource: a getter cannot be written as source toSource: ゲッターはソースとして書き出せません +@msg toSource: an array with properties besides its elements, a property that is not enumerable or another prototype cannot be written as source toSource: 要素以外のプロパティ、列挙可能でないプロパティ、または別のプロトタイプを持つ配列は、ソースとして書き出せません +@msg toSource: an object with a property that is not enumerable, or whose prototype is not Object.prototype, cannot be written as source toSource: 列挙可能でないプロパティを持つオブジェクトや、プロトタイプが Object.prototype ではないオブジェクトは、ソースとして書き出せません +@msg toSource: the source is too long toSource: ソースが長すぎます +@msg toSource: the value contains itself toSource: 値が自身を含んでいます +@msg toSource: the value has too many entries toSource: 値のエントリが多すぎます +@msg toSource: the value is nested too deep toSource: 値の入れ子が深すぎます +@msg toString is not a function toString は関数ではありません +@msg too many arguments 引数が多すぎます +@msg too many quantifiers 量指定子が多すぎます +@msg unknown OpenType feature `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt; prefix - to turn off; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take an alternate's number as `tag=N` with N from 0 to {_1}, as `salt=2`) `{t}` は不明な OpenType 機能です (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt。オフにするには先頭に - を付けます。swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt には、`salt=2` のように `tag=N` の形式で代替字形の番号を指定できます。N は 0 から {_1} まで) +@msg unknown dither `{d}` (diffusion, pattern, noise or none) `{d}` は不明なディザの指定です (diffusion、pattern、noise、none のいずれか) +@msg unknown panel `{panel}` `{panel}` は不明なパネルです +@msg unknown parameter `{key}` `{key}` は不明なパラメーターです +@msg unknown parameter `{within}settings.{format}`; {why} `{within}settings.{format}` は不明なパラメーターです。{why} +@msg unknown parameter `{within}{key}`; {why} `{within}{key}` は不明なパラメーターです。{why} +@msg unknown reduction `{reduction}` (selective, perceptual, adaptive, web, gray, blackWhite, uniform or document) `{reduction}` は不明な減色の指定です (selective、perceptual、adaptive、web、gray、blackWhite、uniform、document のいずれか) +@msg unmatched ')' 対応していない ')' があります +@msg unterminated character class 文字クラスが閉じられていません +@msg unterminated group グループが閉じられていません +@msg wordGap and lineGap need area type in the selection wordGap と lineGap を使用するには、選択範囲にエリア内文字が必要です +@msg xpath needs its variables as an object xpath の変数にはオブジェクトを指定してください +@msg xpath needs the expression as a string xpath の式には文字列を指定してください +@msg {GRANT_NOT_REMOVED}, and its settings and cache can't be moved back from {_1} to {_2}: {e} {GRANT_NOT_REMOVED}。また、設定とキャッシュを {_1} から {_2} に戻せません: {e} +@msg {_1} is not a folder: {e} {_1} はフォルダーではありません: {e} +@msg {_1}: {_2} and {_3} are in the way {_1}: {_2} と {_3} が妨げになっています +@msg {code}: {0} {code}: {0} +@msg {dir}: {e} {dir}: {e} +@msg {file} names more than one linked JavaScript file {file} にリンクされた JavaScript ファイルが複数指定されています +@msg {k}: a custom arrowhead's path needs an area to fill and at most {most} anchors and {most} subpaths, each anchor within {far} head units of its tip {k}: カスタム矢印のパスには塗りつぶせる領域が必要で、アンカーは最大 {most} 個、サブパスは最大 {most} 個、各アンカーは先端から矢印単位で {far} 以内に収めてください +@msg {k}: bad custom arrowhead path: {e} {k}: カスタム矢印のパスが正しくありません: {e} +@msg {k}: bad custom arrowhead: {e} {k}: カスタム矢印が正しくありません: {e} +@msg {k}: custom must be a name {k}: custom には名前を指定してください +@msg {name} must be a number {name} には数値を指定してください +@msg {path}: copy takes a DCS file only when its plates are inside it; relink to it where its plate files are {path}: copy で DCS ファイルを使用できるのは、版がファイル内にある場合だけです。版ファイルのある場所でそのファイルに再リンクしてください +@msg {path}: larger than {_1} MB {path}: {_1} MB を超えています +@msg {shown} is not an XPath 1.0 function {shown} は XPath 1.0 の関数ではありません +@msg {v} names no layer or sublayer {v} に該当するレイヤーまたはサブレイヤーはありません +@msg {what} is not a function {what} は関数ではありません +@msg {what} would print more than {MAX_COPIES_PER_SHEET} copies on a sheet: scale it up {what} では 1 枚の用紙に {MAX_COPIES_PER_SHEET} 部を超えてプリントされます: 拡大してください +@msg {what} {i} out of range {what} {i} が範囲外です +@msg A profile supports one Revolve effect. Edit the existing effect's options instead. 1 つのプロファイルに適用できる回転体効果は 1 つです。既存の効果のオプションを編集してください。 +@msg Add Points at Crossings: a path went missing 交差点にポイントを追加: パスが見つからなくなりました +@msg CSS options: {e} CSS オプション: {e} +@msg CSV has a header but no data rows CSV にヘッダーはありますが、データ行がありません +@msg CSV holds NUL bytes: save it as UTF-8, or as UTF-16 with a byte-order mark CSV に NUL バイトが含まれています: UTF-8、またはバイトオーダーマーク付きの UTF-16 で保存してください +@msg CSV is empty CSV が空です +@msg CSV is larger than {MAX_CSV_BYTES} bytes CSV が {MAX_CSV_BYTES} バイトを超えています +@msg CSV is not UTF-16 CSV が UTF-16 ではありません +@msg CSV is not UTF-8 CSV が UTF-8 ではありません +@msg CSV would be larger than {MAX_CSV_BYTES} bytes CSV が {MAX_CSV_BYTES} バイトを超えます +@msg Choose original artwork, not a dimension's generated paths 寸法から生成されたパスではなく、元のアートワークを選択してください +@msg Contour: select paths or shapes 輪郭: パスまたはシェイプを選択してください +@msg Contour: the Offset Path effect is not available 輪郭: 「パスのオフセット」効果を使用できません +@msg Create needs fills, strokes or both 「作成」には塗り、線、またはその両方が必要です +@msg DXF options: {e} DXF オプション: {e} +@msg DXF scale must be a positive number up to {_1}, not {scale} DXF の拡大・縮小率には {_1} 以下の正の数値を指定してください ({scale} は指定できません) +@msg DXF {field} `{s}`: {allowed} DXF {field} `{s}`: {allowed} +@msg Dimension is locked or hidden 寸法がロックされているか非表示です +@msg Dimension mode does not match its source 寸法のモードが元のオブジェクトと一致しません +@msg Draw Inside needs exactly one selected path, compound path or text 「内側描画」を使用するには、パス、複合パス、テキストのいずれかを 1 つだけ選択してください +@msg EPS Save writes all artwork: use document.export for selected-only EPS EPS の保存ではすべてのアートワークを書き出します: 選択部分だけの EPS には document.export を使用してください +@msg EPS flattener: {e} EPS の分割・統合: {e} +@msg EPS options: {e} EPS オプション: {e} +@msg EPS {field} `{s}`: {allowed} EPS {field} `{s}`: {allowed} +@msg Export for Screens writes png, png8, jpg, webp, gif, tiff, bmp, tga, psd, svg, svgz, pdf, eps, ai or vectorcraft 「スクリーン用に書き出し」で書き出せるのは png、png8、jpg、webp、gif、tiff、bmp、tga、psd、svg、svgz、pdf、eps、ai、vectorcraft です +@msg Flare click coordinates must be finite numbers フレアのクリック座標には有限の数値を指定してください +@msg HTML Text applies to object slices of type only 「HTML テキスト」を適用できるのは文字のオブジェクトスライスだけです +@msg Identify Objects By is XML ID: the name must be a valid XML ID (start with a letter, underscore or colon; no spaces) 「オブジェクトの識別方法」が XML ID になっています: 名前には有効な XML ID を指定してください (先頭は文字、アンダースコア、コロンのいずれか。スペースは使用できません) +@msg Image Trace failed: internal error: its thread stopped (please report this bug) 画像トレースに失敗しました: 内部エラー: スレッドが停止しました (このバグを報告してください) +@msg Image Trace failed: {e} 画像トレースに失敗しました: {e} +@msg Image Trace finished, but its document was closed 画像トレースは完了しましたが、ドキュメントが閉じられています +@msg Image Trace finished, but the image or its settings changed meanwhile: trace it again 画像トレースは完了しましたが、その間に画像または設定が変更されました: もう一度トレースしてください +@msg Invalid dimension offset 寸法のオフセットが無効です +@msg Invalid point 点が無効です +@msg Join: a subpath went missing 連結: サブパスが見つからなくなりました +@msg Lock Workspace is not available in VectorCraft 「ワークスペースをロック」は VectorCraft では使用できません +@msg Move Panel to New Window is not available: floating panels stay in the main window 「パネルを新規ウィンドウに移動」は使用できません: フローティングパネルはメインウィンドウ内に表示されます +@msg Offset Path: the path is too complex to offset パスのオフセット: パスが複雑すぎてオフセットできません +@msg Offset Path: {e} パスのオフセット: {e} +@msg PDF content is incomplete or exceeds the reader's limits; no document was imported PDF の内容が不完全か、読み込み機能の上限を超えています。ドキュメントは読み込まれませんでした +@msg PDF flattener: {e} PDF の分割・統合: {e} +@msg PDF options: {e} PDF オプション: {e} +@msg Recolor Artwork is no longer open 「アートワークを再配色」はすでに閉じられています +@msg SVG is not UTF-8, UTF-16 or ISO 8859-1 SVG が UTF-8、UTF-16、ISO 8859-1 のいずれでもありません +@msg Save writes one artboard: name one, or export several with document.export 保存で書き出せるアートボードは 1 つです: 1 つ指定するか、複数の場合は document.export で書き出してください +@msg Select a dimension first 先に寸法を選択してください +@msg Select dimensions to update 更新する寸法を選択してください +@msg Select only dimensions 寸法だけを選択してください +@msg Select two or more objects, or a group 2 つ以上のオブジェクト、またはグループを選択してください +@msg Shaper needs 1–64 source paths Shaper には 1~64 個の元パスが必要です +@msg Switch x/y is for scatter graphs 「X/Y を入れ替え」は散布図用です +@msg Text options: {e} テキストオプション: {e} +@msg `align` is start, center or end `align` には start、center、end のいずれかを指定してください +@msg `anchors` must be an array of [subpath, anchor] pairs `anchors` には [subpath, anchor] の組の配列を指定してください +@msg `anchors` must list anchor indices (0, 1, 2…), not {k} `anchors` にはアンカーのインデックス (0, 1, 2…) を指定してください ({k} は指定できません) +@msg `anchors` must list anchor indices (0, 1, 2…), not {v} `anchors` にはアンカーのインデックス (0, 1, 2…) を指定してください ({v} は指定できません) +@msg `artboards` must be a list of artboard indices `artboards` にはアートボードのインデックスのリストを指定してください +@msg `asset` is the asset id (see assets.list) `asset` にはアセット ID を指定してください (assets.list を参照) +@msg `at` must be a byte offset `at` にはバイトオフセットを指定してください +@msg `autoLeading` must be a number `autoLeading` には数値を指定してください +@msg `background` must be "", "matte" or #rrggbb `background` には ""、"matte"、#rrggbb のいずれかを指定してください +@msg `burasagari` must be "none", "standard" or "forced" `burasagari` には "none"、"standard"、"forced" のいずれかを指定してください +@msg `center` must be [x, y] `center` には [x, y] を指定してください +@msg `charAlign` must be "romanBaseline", "emBoxTop", "emBoxCenter", "emBoxBottom", "icfTop" or "icfBottom" `charAlign` には "romanBaseline"、"emBoxTop"、"emBoxCenter"、"emBoxBottom"、"icfTop"、"icfBottom" のいずれかを指定してください +@msg `charDirection` must be "default", "leftToRight" or "rightToLeft" `charDirection` には "default"、"leftToRight"、"rightToLeft" のいずれかを指定してください +@msg `clearStroke` requires `stroke: false`, `ids: []` and no `stop` `clearStroke` には `stroke: false` と `ids: []` が必要で、`stop` は指定できません +@msg `clear` must be a list of type object ids, not {v} `clear` には文字オブジェクトの ID のリストを指定してください ({v} は指定できません) +@msg `clear` must list type objects; {_1} is not one `clear` には文字オブジェクトを指定してください。{_1} は文字オブジェクトではありません +@msg `clear` must not list `id` `clear` に `id` を含めることはできません +@msg `color` needs a `rule` to make the theme from `color` には、テーマの作成に使用する `rule` が必要です +@msg `colors` is empty `colors` が空です +@msg `columnType` is vertical, uniform, repeating or sliding `columnType` には vertical、uniform、repeating、sliding のいずれかを指定してください +@msg `columns` must be a whole number 1..50 `columns` には 1..50 の整数を指定してください +@msg `commands` must not be empty `commands` を空にすることはできません +@msg `contents` goes with `to` `contents` は `to` と一緒に指定してください +@msg `corners` must be sharp, round or square, not `{other}` `corners` には sharp、round、square のいずれかを指定してください (`{other}` は指定できません) +@msg `corners` must list anchor indices (0, 1, 2…), not {v} `corners` にはアンカーのインデックス (0, 1, 2…) を指定してください ({v} は指定できません) +@msg `count` must be a whole number from 1 to 100 `count` には 1 から 100 までの整数を指定してください +@msg `dataBase64` is larger than the module limit `dataBase64` がモジュールの上限を超えています +@msg `dataBase64` is not valid base64 `dataBase64` が有効な base64 ではありません +@msg `defaultsOnly` cannot be combined with `ids`, `reverse` or `append` `defaultsOnly` は `ids`、`reverse`、`append` と同時に使用できません +@msg `depth` and `childLimit` slice the summary: pass `summary: true` `depth` と `childLimit` はサマリーを絞り込みます: `summary: true` を指定してください +@msg `design` is a design name, or null for plain columns `design` にはデザイン名を指定します。通常の棒にするには null を指定します +@msg `design` is a design name, or null for the default marker `design` にはデザイン名を指定します。初期設定のマーカーにするには null を指定します +@msg `destinationFolder` is required when destination is `folder` destination が `folder` の場合は `destinationFolder` が必要です +@msg `destination` must be `none`, `saveAndClose` or `folder` `destination` には `none`、`saveAndClose`、`folder` のいずれかを指定してください +@msg `diameter` must be from 0.1 to 2500 pt `diameter` には 0.1 から 2500 pt までの値を指定してください +@msg `digits` must be one of {_1} `digits` には {_1} のいずれかを指定してください +@msg `dimImages` is a percentage or false `dimImages` にはパーセント値または false を指定してください +@msg `direction` must be "auto", "leftToRight" or "rightToLeft" `direction` には "auto"、"leftToRight"、"rightToLeft" のいずれかを指定してください +@msg `each` is the value one design stands for, more than 0 `each` にはデザイン 1 つが表す値を 0 より大きい数で指定してください +@msg `end` must be "start" or "end" `end` には "start" または "end" を指定してください +@msg `ends` applies to joining exactly two paths `ends` を使用できるのは、ちょうど 2 つのパスを連結する場合だけです +@msg `event` must be one of {_1} `event` には {_1} のいずれかを指定してください +@msg `every` must be "all", "odd" or "even", not {v} `every` には "all"、"odd"、"even" のいずれかを指定してください ({v} は指定できません) +@msg `expand` must be true or false `expand` には true または false を指定してください +@msg `files` must be 1 to 1000 paths of font files the last text.findFontFiles search found `files` には、直前の text.findFontFiles の検索で見つかったフォントファイルのパスを 1 ~ 1000 個指定してください +@msg `folder` must be an absolute folder path `folder` にはフォルダーの絶対パスを指定してください +@msg `fontAxes` must be an object of axis tags and values, such as {"wght"} `fontAxes` には、{"wght"} のような軸タグと値のオブジェクトを指定してください +@msg `format` must be a string `format` には文字列を指定してください +@msg `format` must be one of {_1} `format` には {_1} のいずれかを指定してください +@msg `fractions` is chop or scale `fractions` には chop または scale を指定してください +@msg `from` and `to` must differ `from` と `to` には異なる値を指定してください +@msg `from` has an empty frame `from` に空のフレームがあります +@msg `from` must be a non-negative integer `from` には 0 以上の整数を指定してください +@msg `from` must be area type or type on a path `from` にはエリア内文字またはパス上文字を指定してください +@msg `gid` must be a glyph id, not {v} `gid` にはグリフ ID を指定してください ({v} は指定できません) +@msg `glyphAlternate` belongs to one character, not to a character style (text.setGlyphAlternate sets it) `glyphAlternate` は 1 つの文字に設定するもので、文字スタイルには設定できません (text.setGlyphAlternate で設定します) +@msg `guide` must be a guide index (guide.list) `guide` にはガイドのインデックスを指定してください (guide.list) +@msg `hAlign` must be default, left, center or right `hAlign` には default、left、center、right のいずれかを指定してください +@msg `id` must be a node id `id` にはノード ID を指定してください +@msg `id` must be an object id, not {v} `id` にはオブジェクト ID を指定してください ({v} は指定できません) +@msg `ids` must name Objects on Path groups or objects in them `ids` には「パス上のオブジェクト」グループ、またはその中のオブジェクトを指定してください +@msg `ids` takes at most {MAX_INSPECT_IDS} ids `ids` に指定できる ID は最大 {MAX_INSPECT_IDS} 個です +@msg `imageMap` must be none, rectangle or polygon `imageMap` には none、rectangle、polygon のいずれかを指定してください +@msg `includeArtboardFill` must be true or false `includeArtboardFill` には true または false を指定してください +@msg `includeSubdirs` must be true or false `includeSubdirs` には true または false を指定してください +@msg `index` must be a point index `index` にはポイントのインデックスを指定してください +@msg `index` must be a whole number or null `index` には整数または null を指定してください +@msg `indices` must be a non-empty array of item indices `indices` には項目のインデックスを 1 つ以上含む配列を指定してください +@msg `items` is a list of {kind, item} `items` には {kind, item} のリストを指定してください +@msg `items` is empty `items` が空です +@msg `items` must be a list of {id, points} `items` には {id, points} のリストを指定してください +@msg `items` must be a list of {{id, anchors?}}, not {v} `items` には {{id, anchors?}} のリストを指定してください ({v} は指定できません) +@msg `items` must be an array of {id, anchors} `items` には {id, anchors} の配列を指定してください +@msg `items` must be an array of {{id, corners?}}, not {v} `items` には {{id, corners?}} の配列を指定してください ({v} は指定できません) +@msg `kashida` must be "none", "short", "medium", "long" or "stylistic" `kashida` には "none"、"short"、"medium"、"long"、"stylistic" のいずれかを指定してください +@msg `kind` is one of {_1} `kind` には {_1} のいずれかを指定してください +@msg `kind` must be "round", "invertedRound" or "chamfer", not {v} `kind` には "round"、"invertedRound"、"chamfer" のいずれかを指定してください ({v} は指定できません) +@msg `kind` must be `text`, `visibility`, `image` or `graph` `kind` には `text`、`visibility`、`image`、`graph` のいずれかを指定してください +@msg `kind` must be a string `kind` には文字列を指定してください +@msg `kind` must be image, noImage or htmlText `kind` には image、noImage、htmlText のいずれかを指定してください +@msg `kinsoku` must be "none", "hard" or "soft" `kinsoku` には "none"、"hard"、"soft" のいずれかを指定してください +@msg `label` must be a non-empty name of at most 200 characters `label` には 200 文字以内の空でない名前を指定してください +@msg `language` must be a language name or tag, such as "Turkish" or "tr" `language` には、"Turkish" や "tr" のような言語名またはタグを指定してください +@msg `leadingModel` must be "romanBaseline" or "emBoxTop" `leadingModel` には "romanBaseline" または "emBoxTop" を指定してください +@msg `leading` must be from 0.1 to 5000, or null for Auto `leading` には 0.1 から 5000 までの値を指定してください。自動にするには null を指定します +@msg `length` must be a number of at most 1000000 pt either way `length` には正負いずれの方向でも 1000000 pt 以内の数値を指定してください +@msg `line` must be true or false `line` には true または false を指定してください +@msg `minAngle` ({min_angle}°) can't be more than `maxAngle` ({max_angle}°) `minAngle` ({min_angle}°) を `maxAngle` ({max_angle}°) より大きくすることはできません +@msg `mode` must be "handles", "straight" or "smooth" `mode` には "handles"、"straight"、"smooth" のいずれかを指定してください +@msg `mode` must be "straight", "bezier" or "arc" `mode` には "straight"、"bezier"、"arc" のいずれかを指定してください +@msg `mode` must be one of {_1} `mode` には {_1} のいずれかを指定してください +@msg `mojikumi` must be "none", "yakumonoHankaku", "gyomatsuYakumonoHankaku", "gyomatsuYakumonoZenkaku", "yakumonoZenkaku" or "lineEndHalf" `mojikumi` には "none"、"yakumonoHankaku"、"gyomatsuYakumonoHankaku"、"gyomatsuYakumonoZenkaku"、"yakumonoZenkaku"、"lineEndHalf" のいずれかを指定してください +@msg `names` is a list of preset names `names` にはプリセット名のリストを指定してください +@msg `names` lists preset names `names` にはプリセット名を指定してください +@msg `names` must be a list of names `names` には名前のリストを指定してください +@msg `names` must be a list of swatch names `names` にはスウォッチ名のリストを指定してください +@msg `names` must be an array of style names `names` にはスタイル名の配列を指定してください +@msg `new` is a design name, or true `new` にはデザイン名または true を指定してください +@msg `path` must be a folder `path` にはフォルダーを指定してください +@msg `path` must be a path object `path` にはパスオブジェクトを指定してください +@msg `pivot` must be a whole number from 0 to 8 `pivot` には 0 から 8 までの整数を指定してください +@msg `points` must be a list of [x, y] points `points` には [x, y] の点のリストを指定してください +@msg `points` must be a list of point indexes `points` にはポイントのインデックスのリストを指定してください +@msg `points` must be an array of point indices `points` にはポイントのインデックスの配列を指定してください +@msg `points` must be point indexes `points` にはポイントのインデックスを指定してください +@msg `port` must be "in" or "out" `port` には "in" または "out" を指定してください +@msg `position` is above or below `position` には above または below を指定してください +@msg `preset` must be a string `preset` には文字列を指定してください +@msg `ratio` must be from 0.1 to 0.5 `ratio` には 0.1 から 0.5 までの値を指定してください +@msg `rect` must be [x, y, width, height] with a positive size `rect` には、サイズが正の [x, y, width, height] を指定してください +@msg `relation` must be overlap, inside or outside `relation` には overlap、inside、outside のいずれかを指定してください +@msg `reversed` must be true or false `reversed` には true または false を指定してください +@msg `rotate` must be a finite number `rotate` には有限の数値を指定してください +@msg `rule` must be nonZero or evenOdd `rule` には nonZero または evenOdd を指定してください +@msg `scale` must be a number in (0, 100] `scale` には (0, 100] の範囲の数値を指定してください +@msg `scope` must be "selection" or "document", not {other} `scope` には "selection" または "document" を指定してください ({other} は指定できません) +@msg `script` must be a string `script` には文字列を指定してください +@msg `seriesIndexes` is a non-empty list of series indexes `seriesIndexes` には系列のインデックスを 1 つ以上含むリストを指定してください +@msg `seriesIndexes` needs a `type` or a `valueAxis` `seriesIndexes` には `type` または `valueAxis` が必要です +@msg `shift` must be a number of points `shift` にはポイント単位の数値を指定してください +@msg `showCenter` must be true or false `showCenter` には true または false を指定してください +@msg `singleWordJustification` must be "fullJustify", "alignLeft", "alignCenter" or "alignRight" `singleWordJustification` には "fullJustify"、"alignLeft"、"alignCenter"、"alignRight" のいずれかを指定してください +@msg `size` is a percentage of the base text's size, 1 to 100 `size` には、親文字のサイズに対する割合を 1 から 100 までのパーセント値で指定してください +@msg `source` and `target` are the same object `source` と `target` が同じオブジェクトです +@msg `source` must be `folder` or `datasets` `source` には `folder` または `datasets` を指定してください +@msg `spacing` must be a number `spacing` には数値を指定してください +@msg `spacing` must be a number of points, 0 or more, or "auto" `spacing` には 0 以上のポイント単位の数値、または "auto" を指定してください +@msg `start` must be a finite number `start` には有限の数値を指定してください +@msg `starts` must be an array of anchor indices (or nulls) `starts` にはアンカーのインデックス (または null) の配列を指定してください +@msg `status` must be linked, embedded, missing or modified, or a list of them `status` には linked、embedded、missing、modified のいずれか、またはそのリストを指定してください +@msg `stop` must be a stop index `stop` には分岐点のインデックスを指定してください +@msg `story` styles the whole story: give no `start` or `end` `story` はストーリー全体にスタイルを設定します: `start` と `end` は指定しないでください +@msg `story` takes the whole story: give no `start` or `end` `story` はストーリー全体を対象にします: `start` と `end` は指定しないでください +@msg `strokeMode` applies to strokes (stroke: true) `strokeMode` は線に適用されます (stroke: true) +@msg `style` must be roman or japanese `style` には roman または japanese を指定してください +@msg `subpaths` must be two integer indices `subpaths` には整数のインデックスを 2 つ指定してください +@msg `symbol` must be a symbol name `symbol` にはシンボル名を指定してください +@msg `target` must be "object" or "contents", not {v} `target` には "object" または "contents" を指定してください ({v} は指定できません) +@msg `tint` applies to global and spot colours `tint` はグローバルカラーと特色に適用されます +@msg `tint` goes with a global or spot `swatch` `tint` はグローバルまたは特色の `swatch` と一緒に指定してください +@msg `tint` must be a number (%) `tint` には数値 (%) を指定してください +@msg `tint` needs a global or spot colour `tint` にはグローバルカラーまたは特色が必要です +@msg `to` is already threaded `to` はすでにスレッドされています +@msg `to` is the design's new name `to` にはデザインの新しい名前を指定してください +@msg `to` must be [x, y] `to` には [x, y] を指定してください +@msg `to` must be a closed path, area type or type on a path other than `from` `to` には、`from` 以外のクローズパス、エリア内文字、パス上文字のいずれかを指定してください +@msg `to` must be a whole number `to` には整数を指定してください +@msg `to` takes the rows of one object's stack, not aligned rows `to` には、整列した行ではなく、1 つのオブジェクトのスタック内の行を指定してください +@msg `useLab` must be true or false `useLab` には true または false を指定してください +@msg `vAlign` must be default, top, middle, baseline or bottom `vAlign` には default、top、middle、baseline、bottom のいずれかを指定してください +@msg `values` must be a list `values` にはリストを指定してください +@msg `values` must be an object `values` にはオブジェクトを指定してください +@msg `values` must name hex, rgb, cmyk, lab or gray `values` には hex、rgb、cmyk、lab、gray のいずれかを指定してください +@msg `values` names a kind twice `values` に同じ種類が 2 回指定されています +@msg `{_1}` can't be edited or removed `{_1}` は編集も削除もできません +@msg `{_1}` is built in and always listed `{_1}` は組み込みで、常に一覧に表示されます +@msg `{_1}` is not a font file the last text.findFontFiles search found `{_1}` は、直前の text.findFontFiles の検索で見つかったフォントファイルではありません +@msg `{_1}` would be overwritten by the package: choose a different folder or name `{_1}` がパッケージで上書きされます: 別のフォルダーまたは名前を選択してください +@msg `{file}` has no art to place `{file}` に配置できるアートがありません +@msg `{file}` is over {_1} MB `{file}` が {_1} MB を超えています +@msg `{f}` belongs to a VectorCraft that is running `{f}` は実行中の VectorCraft が使用しています +@msg `{f}` is the copy of a document open now `{f}` は現在開いているドキュメントのコピーです +@msg `{id}` is no writable format (see document.formats) `{id}` は書き出せる形式ではありません (document.formats を参照) +@msg `{id}` isn't a loaded library `{id}` は読み込まれているライブラリではありません +@msg `{key}` has no colours `{key}` にカラーがありません +@msg `{key}` is a design name `{key}` にはデザイン名を指定してください +@msg `{key}` is a design name or a list of them `{key}` にはデザイン名またはそのリストを指定してください +@msg `{key}` is longer than {MAX_NAME} characters `{key}` が {MAX_NAME} 文字を超えています +@msg `{key}` is out of range `{key}` が範囲外です +@msg `{key}` must be [min, desired, max] or {{min?, desired?, max?}}, in percent `{key}` には [min, desired, max] または {{min?, desired?, max?}} をパーセントで指定してください +@msg `{key}` must be a non-negative integer `{key}` には 0 以上の整数を指定してください +@msg `{key}` must be a number {_1}..{_2} `{key}` には {_1}..{_2} の数値を指定してください +@msg `{key}` must be a whole number of at least 0, not {n} `{key}` には 0 以上の整数を指定してください ({n} は指定できません) +@msg `{key}` must be an appearance item index (paint order) or null `{key}` にはアピアランス項目のインデックス (ペイント順) または null を指定してください +@msg `{key}` must be an array of asset ids (see assets.list) `{key}` にはアセット ID の配列を指定してください (assets.list を参照) +@msg `{key}` must be from 0 to 180 degrees, not {a} `{key}` には 0 から 180 度までの値を指定してください ({a} は指定できません) +@msg `{key}` must be from {_1} to {shift_max} `{key}` には {_1} から {shift_max} までの値を指定してください +@msg `{key}`: not a colour: {v} `{key}`: カラーではありません: {v} +@msg `{k}.family` is required `{k}.family` は必須です +@msg `{k}` is a number 0..1 `{k}` には 0..1 の数値を指定してください +@msg `{k}` is true or false `{k}` には true または false を指定してください +@msg `{k}` isn't an export setting: {_1} `{k}` は書き出し設定ではありません: {_1} +@msg `{k}` must be a byte offset `{k}` にはバイトオフセットを指定してください +@msg `{k}` must be a number `{k}` には数値を指定してください +@msg `{k}` must be a number of points `{k}` にはポイント単位の数値を指定してください +@msg `{k}` must be a string `{k}` には文字列を指定してください +@msg `{k}` must be a whole number `{k}` には整数を指定してください +@msg `{k}` must be from {lo} to {hi} for {key} {key} の `{k}` には {lo} から {hi} までの値を指定してください +@msg `{k}` must be {what}, not {v} `{k}` には {what} を指定してください ({v} は指定できません) +@msg `{l}` isn't a global or spot colour `{l}` はグローバルカラーでも特色でもありません +@msg `{m}` isn't a bitmap: use clipboard.importSvg, importPdf or importText `{m}` はビットマップではありません: clipboard.importSvg、importPdf、importText のいずれかを使用してください +@msg `{name}` can't be deleted `{name}` は削除できません +@msg `{name}` can't be duplicated `{name}` は複製できません +@msg `{name}` can't be edited `{name}` は編集できません +@msg `{name}` can't be edited this way `{name}` はこの方法では編集できません +@msg `{name}` can't be renamed `{name}` は名前を変更できません +@msg `{name}` can't name a folder `{name}` にフォルダーは指定できません +@msg `{name}` has no art to place `{name}` に配置できるアートがありません +@msg `{name}` has no text to place `{name}` に配置できるテキストがありません +@msg `{name}` in the Word document is not UTF-8 or UTF-16 text Word 文書内の `{name}` が UTF-8 または UTF-16 のテキストではありません +@msg `{name}` in the Word document is not well-formed XML: {e} Word 文書内の `{name}` が整形式の XML ではありません: {e} +@msg `{name}` in the Word document nests elements more than {MAX_NESTING} deep Word 文書内の `{name}` で要素の入れ子が {MAX_NESTING} 階層を超えています +@msg `{name}` is a built-in preset and is read-only: save it under another name `{name}` は組み込みのプリセットで、読み取り専用です: 別の名前で保存してください +@msg `{name}` is a built-in preset: save under another name `{name}` は組み込みのプリセットです: 別の名前で保存してください +@msg `{name}` is a built-in profile and stays `{name}` は組み込みのプロファイルのため、削除されません +@msg `{name}` is a tint of `{base}`: edit `{base}` (a tint swatch only takes a new name) `{name}` は `{base}` の濃度違いです: `{base}` を編集してください (濃度スウォッチで変更できるのは名前だけです) +@msg `{name}` is a working space: choose another with edit.colorSettings first `{name}` は作業用スペースです: 先に edit.colorSettings で別のものを選択してください +@msg `{name}` is built in and stays `{name}` は組み込みのため、削除されません +@msg `{name}` takes a paint of its own kind (colour, gradient or pattern) `{name}` には同じ種類のペイント (カラー、グラデーション、パターン) を指定してください +@msg `{n}` can't be deleted `{n}` は削除できません +@msg `{n}` can't be merged `{n}` は結合できません +@msg `{n}` can't be moved `{n}` は移動できません +@msg `{n}` is not a colour swatch `{n}` はカラースウォッチではありません +@msg `{n}` isn't a solid colour `{n}` は単色ではありません +@msg `{n}`: colour groups hold solid colours only `{n}`: カラーグループに入れられるのは単色だけです +@msg `{other}` doesn't trace an image `{other}` では画像をトレースできません +@msg `{s}`: the step's references copy in more than {_1} MB of values `{s}`: このステップの参照でコピーされる値が {_1} MB を超えています +@msg `{tag}` is not an axis tag: a tag is four characters, such as "wght" `{tag}` は軸タグではありません: タグは "wght" のような 4 文字です +@msg `{to}` is empty or already used `{to}` が空か、すでに使用されています +@msg `{what}` is longer than {MAX_TEXT} bytes `{what}` が {MAX_TEXT} バイトを超えています +@msg `{what}` must be text `{what}` にはテキストを指定してください +@msg a DXF drawing has one origin: pass useArtboards: true for one drawing per artboard DXF 図面の原点は 1 つです: アートボードごとに 1 つの図面にするには useArtboards: true を指定してください +@msg a PDF presets file with over {_1} presets PDF プリセットファイルに {_1} 個を超えるプリセットがあります +@msg a batch preview cannot switch documents バッチのプレビューではドキュメントを切り替えられません +@msg a brush named `{nn}` exists `{nn}` という名前のブラシがすでにあります +@msg a container of the listed objects is gone 指定したオブジェクトを含むコンテナがなくなりました +@msg a content stream can't be read コンテンツストリームを読み込めません +@msg a content stream isn't a stream コンテンツストリームがストリームではありません +@msg a design holds at most {_1} objects デザインに含められるオブジェクトは最大 {_1} 個です +@msg a design needs a name デザインには名前が必要です +@msg a dictionary grew too large 辞書が大きくなりすぎました +@msg a document keeps at most {_1} graph designs ドキュメントに保存できるグラフのデザインは最大 {_1} 個です +@msg a document keeps at most {_1} saved selections ドキュメントに保存できる選択範囲は最大 {_1} 個です +@msg a document keeps at most {_1} views ドキュメントに保存できる表示は最大 {_1} 個です +@msg a document links at most {MAX_SVG_SCRIPTS} JavaScript files ドキュメントにリンクできる JavaScript ファイルは最大 {MAX_SVG_SCRIPTS} 個です +@msg a feConvolveMatrix filter's order is {x}×{y}, which overflows the kernel-size multiply usvg makes feConvolveMatrix フィルターの order が {x}×{y} で、usvg が行うカーネルサイズの乗算がオーバーフローします +@msg a gradient preset is already called {n} {n} という名前のグラデーションプリセットがすでにあります +@msg a graph has at most {_1} series, so it transposes with at most that many categories グラフの系列は最大 {_1} 個のため、行と列を入れ替えられるのは項目がその数以下の場合です +@msg a layer can't be merged into its own sublayer レイヤーを自身のサブレイヤーに結合することはできません +@msg a layer's form box isn't an array レイヤーのフォームのボックスが配列ではありません +@msg a layer's form can't be read レイヤーのフォームを読み込めません +@msg a layer's form has no box レイヤーのフォームにボックスがありません +@msg a layer's form has no dictionary レイヤーのフォームに辞書がありません +@msg a legend draws at most {MAX_CHIPS} swatches 凡例に描画できるスウォッチは最大 {MAX_CHIPS} 個です +@msg a name names one asset: give multiple: false, or one object 名前で指定できるアセットは 1 つです: multiple: false を指定するか、オブジェクトを 1 つにしてください +@msg a page can't be read ページを読み込めません +@msg a page object is used by something else ページオブジェクトが別のものに使用されています +@msg a page thumbnail must be RGB pixels, 1 to {THUMBNAIL_SIZE} a side (got {w} × {h}) ページのサムネールには、1 辺が 1 から {THUMBNAIL_SIZE} までの RGB ピクセルを指定してください (指定値: {w} × {h}) +@msg a pattern layer doesn't end what it starts パターンレイヤーで、開始したものが終了していません +@msg a pattern layer's colors hold something else パターンレイヤーのカラーに別のものが含まれています +@msg a pattern named `{n}` exists `{n}` という名前のパターンがすでにあります +@msg a plug-in with id {_1} is already installed ID が {_1} のプラグインはすでにインストールされています +@msg a preset named `{n}` exists `{n}` という名前のプリセットがすでにあります +@msg a print presets file with over {_1} presets プリントプリセットファイルに {_1} 個を超えるプリセットがあります +@msg a profile is already called {n} {n} という名前のプロファイルがすでにあります +@msg a row can't go into itself 行を自身の中に入れることはできません +@msg a series goes on the left or the right value axis 系列は左または右の数値軸に割り当てます +@msg a start must be an anchor index ≥ 0 or null 開始位置には 0 以上のアンカーのインデックスまたは null を指定してください +@msg a style named `{name}` already exists `{name}` という名前のスタイルがすでにあります +@msg a style named `{to}` already exists `{to}` という名前のスタイルがすでにあります +@msg a swatch needs a colour, gradient or pattern スウォッチにはカラー、グラデーション、パターンのいずれかが必要です +@msg a symbol named `{n}` already exists `{n}` という名前のシンボルがすでにあります +@msg a theme has 1 to {THEME_SIZE} colours テーマのカラーは 1 から {THEME_SIZE} 色までです +@msg a theme is already called {name} (replace: "{name}" overwrites it) {name} という名前のテーマがすでにあります (replace: "{name}" で上書きできます) +@msg a toolbar name has at most {MAX_NAME} characters ツールバー名は {MAX_NAME} 文字以内です +@msg a view named `{_1}` exists `{_1}` という名前の表示がすでにあります +@msg a view named `{name}` exists `{name}` という名前の表示がすでにあります +@msg a workspace keeps at most {MAX} toolbars ワークスペースに保存できるツールバーは最大 {MAX} 個です +@msg a {_1} series can't go in a {_2} graph {_1} の系列は {_2} グラフに入れられません +@msg aiVersion {v}: "pdf" (PDF-compatible, the default) or "7" (legacy .ai, version 7) aiVersion {v}: "pdf" (PDF 互換、初期設定) または "7" (旧形式の .ai、バージョン 7) を指定してください +@msg already editing an opacity mask すでに不透明マスクを編集中です +@msg already editing another object's opacity mask すでに別のオブジェクトの不透明マスクを編集中です +@msg already in pattern editing mode すでにパターン編集モードです +@msg an artboard is listed twice 同じアートボードが 2 回指定されています +@msg an empty artboard has no width or height to scale to 空のアートボードには、拡大・縮小の基準となる幅も高さもありません +@msg an image is too large for DXF and was left out 画像が DXF には大きすぎるため、除外しました +@msg an image of {_1} MB, at most {_2} MB 画像が {_1} MB あります (上限は {_2} MB) +@msg an image of {declared_w} × {declared_h} pixels is too large to draw {declared_w} × {declared_h} ピクセルの画像は大きすぎて描画できません +@msg an image of {width} × {height} pixels is too large to draw {width} × {height} ピクセルの画像は大きすぎて描画できません +@msg an index must be a whole number インデックスには整数を指定してください +@msg an inline graphic has no glyphs インライングラフィックにグリフがありません +@msg an invisible text form can't be read 非表示テキストのフォームを読み込めません +@msg an object is missing オブジェクトが見つかりません +@msg an object's header is missing オブジェクトのヘッダーがありません +@msg an overprinting form can't be read オーバープリントのフォームを読み込めません +@msg an unread object has no readable bounds 未読み込みのオブジェクトに、読み取れる境界がありません +@msg an unread object holds a frame of threaded type 未読み込みのオブジェクトに、スレッドテキストのフレームが含まれています +@msg an unread object is missing from its layer 未読み込みのオブジェクトがレイヤーにありません +@msg anchor `smooth` must be true or false アンカーの `smooth` には true または false を指定してください +@msg anchor `{key}` must be [x, y] アンカーの `{key}` には [x, y] を指定してください +@msg anchor `{key}` must be a number アンカーの `{key}` には数値を指定してください +@msg angle and roundness must be finite angle と roundness には有限の値を指定してください +@msg angles must be a list as long as pins (degrees or null) angles には pins と同じ長さのリスト (度数または null) を指定してください +@msg appearance must be flat|center|edge appearance には flat|center|edge のいずれかを指定してください +@msg apply is "fill" or "stroke", not `{other}` apply には "fill" または "stroke" を指定してください (`{other}` は指定できません) +@msg area must be a closed polygon of 3 to 100000 [x, y] points area には 3 から 100000 個の [x, y] の点からなる閉じた多角形を指定してください +@msg area type needs a path that encloses an area エリア内文字には、領域を囲むパスが必要です +@msg area type {_1} is named twice エリア内文字 {_1} が 2 回指定されています +@msg arrowAlign must be extend|tip, got {o} arrowAlign には extend|tip のいずれかを指定してください (指定値: {o}) +@msg arrowScale must be [start, end] arrowScale には [start, end] を指定してください +@msg artboard is a 0-based index artboard には 0 から始まるインデックスを指定してください +@msg artboard must be a 0-based index artboard には 0 から始まるインデックスを指定してください +@msg artboard {i} doesn't print アートボード {i} はプリントされません +@msg artboardLayout must be {layout?, columns?, spacing?, rightToLeft?} artboardLayout には {layout?, columns?, spacing?, rightToLeft?} を指定してください +@msg artboardLayout.columns must be 1 or more artboardLayout.columns には 1 以上の値を指定してください +@msg artboardLayout.layout must be gridByRow, gridByColumn, row or column artboardLayout.layout には gridByRow、gridByColumn、row、column のいずれかを指定してください +@msg artboardLayout.rightToLeft must be true or false artboardLayout.rightToLeft には true または false を指定してください +@msg artboardLayout.spacing must be 0–{MAX_SPACING} pt artboardLayout.spacing には 0–{MAX_SPACING} pt を指定してください +@msg artboards must be a non-empty list artboards には空でないリストを指定してください +@msg artboards must be a number artboards には数値を指定してください +@msg asset `{_1}` has no art to export アセット `{_1}` に書き出せるアートがありません +@msg at most {MAX_KEYWORDS} keywords キーワードは最大 {MAX_KEYWORDS} 個です +@msg at most {MAX_MATCHES} matches are kept 保持される一致は最大 {MAX_MATCHES} 件です +@msg at most {MAX_POINTS} points ポイントは最大 {MAX_POINTS} 個です +@msg at most {MAX_QUEUE} files ファイルは最大 {MAX_QUEUE} 個です +@msg at must be [x, y] at には [x, y] を指定してください +@msg at/rect lie outside the canvas at/rect がキャンバスの外にあります +@msg attribute must be size|leading|tracking|kerning|baselineShift attribute には size|leading|tracking|kerning|baselineShift のいずれかを指定してください +@msg attrs must be an object attrs にはオブジェクトを指定してください +@msg automation path rejected: the folder's name isn't valid text 自動処理のパスを拒否しました: フォルダー名が有効なテキストではありません +@msg automation path rejected: {_1} isn't valid text 自動処理のパスを拒否しました: {_1} が有効なテキストではありません +@msg automation path rejected: {why}: {path} 自動処理のパスを拒否しました: {why}: {path} +@msg axis must be "vertical", "horizontal" or an angle in degrees, not `{given}` axis には "vertical"、"horizontal"、または度数の角度を指定してください (`{given}` は指定できません) +@msg backgroundContents must be transparent or white backgroundContents には transparent または white を指定してください +@msg bad AES key AES キーが正しくありません +@msg bad `runs`: {e} `runs` が正しくありません: {e} +@msg bad arrowScale arrowScale が正しくありません +@msg bad base64 base64 が正しくありません +@msg bad color {c} カラー {c} が正しくありません +@msg bad colour カラーが正しくありません +@msg bad colour in `colors` `colors` 内のカラーが正しくありません +@msg bad colour {v} カラー {v} が正しくありません +@msg bad colour {v} in groupColors groupColors 内のカラー {v} が正しくありません +@msg bad cross-reference entry 相互参照エントリが正しくありません +@msg bad cross-reference table 相互参照テーブルが正しくありません +@msg bad current colour {v} 現在のカラー {v} が正しくありません +@msg bad dataBase64 dataBase64 が正しくありません +@msg bad edit 編集内容が正しくありません +@msg bad fill {v} 塗り {v} が正しくありません +@msg bad fit: {e} fit が正しくありません: {e} +@msg bad model {other} (keep, new or document) model {other} が正しくありません (keep、new、document のいずれか) +@msg bad new colour {v} 新しいカラー {v} が正しくありません +@msg bad object オブジェクトが正しくありません +@msg bad object number オブジェクト番号が正しくありません +@msg bad offset オフセットが正しくありません +@msg bad path data: {e} パスデータが正しくありません: {e} +@msg bad point {v}: expected [x, y] or [x, y, pressure] 点 {v} が正しくありません: [x, y] または [x, y, pressure] を指定してください +@msg bad reference 参照が正しくありません +@msg bad trailer size トレーラーのサイズが正しくありません +@msg bad {k} colour {k} のカラーが正しくありません +@msg batches cannot nest バッチを入れ子にすることはできません +@msg bind something to a variable first 先に何かを変数にバインドしてください +@msg bleed must be 0–{MAX_BLEED} pt: a number, [top, bottom, left, right] or {{top, bottom, left, right}} bleed には 0–{MAX_BLEED} pt を指定してください: 数値、[top, bottom, left, right]、{{top, bottom, left, right}} のいずれか +@msg brush must be a name or null brush には名前または null を指定してください +@msg by must be a number by には数値を指定してください +@msg can't add page thumbnails: {why} ページのサムネールを追加できません: {why} +@msg can't add the editing data for other apps: {why} 他のアプリ用の編集データを追加できません: {why} +@msg can't edit the written PDF: {why} 書き出した PDF を編集できません: {why} +@msg can't encrypt the PDF: {why} PDF を暗号化できません: {why} +@msg can't linearise the PDF: {why} PDF をリニアライズできません: {why} +@msg can't open `{_1}`: {_2} `{_1}` を開けません: {_2} +@msg can't open `{_1}`: {e} `{_1}` を開けません: {e} +@msg can't open `{name}`: not a format VectorCraft reads (see document.formats) `{name}` を開けません: VectorCraft で読み込める形式ではありません (document.formats を参照) +@msg can't place `{name}`: not a format VectorCraft reads (see document.formats) `{name}` を配置できません: VectorCraft で読み込める形式ではありません (document.formats を参照) +@msg can't read back the written PDF: {e} 書き出した PDF を読み戻せません: {e} +@msg can't read this Word document: {why} この Word 文書を読み込めません: {why} +@msg can't write .{e} images: use .png, .jpg, .gif, .webp, .tif or .bmp .{e} 画像は書き出せません: .png、.jpg、.gif、.webp、.tif、.bmp のいずれかを使用してください +@msg can't write PDF layers, overprint or invisible text: {why} PDF レイヤー、オーバープリント、非表示テキストを書き出せません: {why} +@msg can't write the file's copyright: {why} ファイルの著作権情報を書き出せません: {why} +@msg can't write the file's modification date: {why} ファイルの更新日を書き出せません: {why} +@msg can't write the pages' user units: {why} ページのユーザー単位を書き出せません: {why} +@msg cannot distort a zero-size or non-finite bounding box サイズが 0 または有限でないバウンディングボックスは変形できません +@msg cannot move an object into itself オブジェクトを自身の中に移動することはできません +@msg case must be upper|lower|title|sentence case には upper|lower|title|sentence のいずれかを指定してください +@msg category `{c}`: one of {_1} category `{c}`: {_1} のいずれかを指定してください +@msg center must be [x, y] center には [x, y] を指定してください +@msg choose at least one artboard アートボードを 1 つ以上選択してください +@msg choose at least one status 状態を 1 つ以上選択してください +@msg clip must be true or false clip には true または false を指定してください +@msg clippingMask must be true or false clippingMask には true または false を指定してください +@msg closed must be a boolean closed にはブール値を指定してください +@msg collapsed must be true or false collapsed には true または false を指定してください +@msg color.profile: no RGB or CMYK profile is called “{profile}” color.profile: 「{profile}」という名前の RGB または CMYK プロファイルはありません +@msg colorMode must be rgb or cmyk, not `{m}` colorMode には rgb または cmyk を指定してください (`{m}` は指定できません) +@msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel には {own} (ドキュメントのモード)、grayscale、bitmap のいずれかを指定してください +@msg colour groups can't go into colour groups カラーグループをカラーグループに入れることはできません +@msg colour, mode and spot apply to solid-colour swatches only colour、mode、spot を適用できるのは単色のスウォッチだけです +@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read 列 {column}: `{cell}` はグラフデータファイルの `%` 列で、読み込まれません +@msg column {column}: `{cell}` names `{name}`, which is a {_1} variable 列 {column}: `{cell}` が指定している `{name}` は {_1} 変数です +@msg column {column}: `{cell}` names no variable 列 {column}: `{cell}` に該当する変数はありません +@msg column {column}: the variable name is longer than {MAX_NAME} characters 列 {column}: 変数名が {MAX_NAME} 文字を超えています +@msg column: true floats the whole column and takes no onto, above or below column: true は列全体をフローティングにするため、onto、above、below は指定できません +@msg command must be a shape.* command command には shape.* コマンドを指定してください +@msg commands[{i}]: missing `command` commands[{i}]: `command` がありません +@msg composer must be "singleLine" or "everyLine" composer には "singleLine" または "everyLine" を指定してください +@msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes 複合シェイプに含められるのは、パス、複合パス、グループ、複合シェイプ、文字、ブレンド、エンベロープです +@msg compound {_1} must contain exactly one open path to join 連結するには、複合パス {_1} にオープンパスがちょうど 1 つ含まれている必要があります +@msg connect end must be "start" or "end" connect の end には "start" または "end" を指定してください +@msg connect needs a path other than the one extended connect には、延長したパスとは別のパスが必要です +@msg connect needs id connect には id が必要です +@msg connect path has no open end connect のパスに開いた端点がありません +@msg copy needs path: the file to copy into the document's folder copy には path が必要です: ドキュメントのフォルダーにコピーするファイルを指定してください +@msg copy takes images only: relink placed documents where their files are copy を使用できるのは画像だけです: 配置したドキュメントは、ファイルのある場所で再リンクしてください +@msg copying a file isn't available on the web Web 版ではファイルをコピーできません +@msg copyrightStatus must be unknown, copyrighted or publicDomain copyrightStatus には unknown、copyrighted、publicDomain のいずれかを指定してください +@msg copyrightUrl must be a URL (no spaces, at most 2048 characters) copyrightUrl には URL を指定してください (スペースなし、2048 文字以内) +@msg corners must be 4 [x, y] points (TL, TR, BR, BL) corners には [x, y] の点を 4 つ指定してください (TL, TR, BR, BL) +@msg counterPer `{c}`: item or file counterPer `{c}`: item または file を指定してください +@msg crop `{_1}`: only PDF pages have art, trim, bleed and media boxes; use "crop" or "bounding" crop `{_1}`: アート、仕上がり、裁ち落とし、メディアの各ボックスがあるのは PDF ページだけです。"crop" または "bounding" を使用してください +@msg crop rectangle doesn't overlap the image 切り抜きの長方形が画像と重なっていません +@msg cross-reference and object streams aren't supported 相互参照ストリームとオブジェクトストリームには対応していません +@msg damaged compressed data: {e} 圧縮データが破損しています: {e} +@msg dash lengths must be numbers, got {v} ダッシュの長さには数値を指定してください (指定値: {v}) +@msg dash must be a list of lengths or null, got {v} dash には長さのリストまたは null を指定してください (指定値: {v}) +@msg data key `{k}`: letters, digits, -, _ and . (not name or vc-…) データキー `{k}`: 使用できるのは文字、数字、-、_、. です (name と vc-… は使用できません) +@msg data must be an object of key: value, not {v} data には key: value のオブジェクトを指定してください ({v} は指定できません) +@msg data set `{name}` holds a value for `{var}`, which the library doesn't declare データセット `{name}` に、ライブラリで宣言されていない `{var}` の値があります +@msg data set `{name}` holds two values for `{var}` データセット `{name}` に `{var}` の値が 2 つあります +@msg data set `{name}` is declared twice データセット `{name}` が 2 回宣言されています +@msg data takes at most {MAX_DATA} keys at once data に一度に指定できるキーは最大 {MAX_DATA} 個です +@msg dataset `{name}` already exists データセット `{name}` はすでにあります +@msg dataset `{to}` already exists データセット `{to}` はすでにあります +@msg date `{d}`: YYYY-MM-DD date `{d}`: YYYY-MM-DD の形式で指定してください +@msg decoded data is too large デコードしたデータが大きすぎます +@msg define a variable first 先に変数を定義してください +@msg detect must be true or false detect には true または false を指定してください +@msg direct-select anchor points of a path パスのアンカーポイントをダイレクト選択してください +@msg distance must be > 0 distance には 0 より大きい値を指定してください +@msg dx and dy give the arrow's direction dx と dy には矢印の方向を指定してください +@msg dx and dy must be numbers dx と dy には数値を指定してください +@msg dxf fitTo must be [width, height], positive dxf の fitTo には正の値の [width, height] を指定してください +@msg dxf must be an object of DXF import options dxf には DXF 読み込みオプションのオブジェクトを指定してください +@msg dxf scale must be a positive number up to {_1}, not {s} dxf の scale には {_1} 以下の正の数値を指定してください ({s} は指定できません) +@msg dxf unit `{u}`: a unit such as mm, cm, in or pt dxf の unit `{u}`: mm、cm、in、pt などの単位を指定してください +@msg dxf: {e} dxf: {e} +@msg each format is an object {format, scale?, suffix?} 各形式にはオブジェクト {format, scale?, suffix?} を指定してください +@msg each item needs an id 各項目には id が必要です +@msg each match needs `kind` 各一致には `kind` が必要です +@msg each match needs a `name` 各一致には `name` が必要です +@msg each of `fonts` is {family, style?}; 1 to 1000 of them `fonts` の各要素には {family, style?} を指定してください。要素数は 1 から 1000 個です +@msg each of `items` is {kind, item} `items` の各要素には {kind, item} を指定してください +@msg each of `items` is {{id, corners?}} with an object id, not {it} `items` の各要素には、オブジェクト ID を含む {{id, corners?}} を指定してください ({it} は指定できません) +@msg each row needs `from` 各行には `from` が必要です +@msg each stop needs a position 各分岐点には位置が必要です +@msg each subpath needs an anchors array 各サブパスには anchors 配列が必要です +@msg easingType must be easeIn, easeOut, easeInOut or easeOutIn easingType には easeIn、easeOut、easeInOut、easeOutIn のいずれかを指定してください +@msg editingData must be true or false editingData には true または false を指定してください +@msg editingData must be true, false or "always" editingData には true、false、"always" のいずれかを指定してください +@msg edits overlap 編集範囲が重なっています +@msg effects of objects whose appearances differ can't be moved together アピアランスが異なるオブジェクトの効果は、まとめて移動できません +@msg empty header in column {_1} 列 {_1} のヘッダーが空です +@msg encoding `{_1}`: utf8 or utf16 encoding `{_1}`: utf8 または utf16 を指定してください +@msg ends must be two of "first" and "last" ends には "first" と "last" から 2 つを指定してください +@msg every numbered name for the result is taken 結果に使用できる番号付きの名前がすべて使用されています +@msg expanded SVG styles exceed the import size limit 展開した SVG スタイルが読み込みサイズの上限を超えています +@msg export presets file is larger than {MAX_PRESET_FILE_BYTES} bytes 書き出しプリセットファイルが {MAX_PRESET_FILE_BYTES} バイトを超えています +@msg exportText must be editable or appearance exportText には editable または appearance を指定してください +@msg exportType must be movieClip or graphic, not `{s}` exportType には movieClip または graphic を指定してください (`{s}` は指定できません) +@msg extend needs id extend には id が必要です +@msg featureChanges lists at most {MAX_FEATURE_CHANGES} tags featureChanges に指定できるタグは最大 {MAX_FEATURE_CHANGES} 個です +@msg featureChanges must be a list of tags featureChanges にはタグのリストを指定してください +@msg features must be a list of tags features にはタグのリストを指定してください +@msg fidelity must be 0..100 fidelity には 0..100 の値を指定してください +@msg files must be {name, dataBase64} files には {name, dataBase64} を指定してください +@msg fit must be none|autoHeight|shrinkText|block, got {id} fit には none|autoHeight|shrinkText|block のいずれかを指定してください (指定値: {id}) +@msg flattener: {e} 分割・統合: {e} +@msg flattenerPreset `{name}`: high, medium, low or a saved one (see flattener.presets.list) flattenerPreset `{name}`: high、medium、low、または保存済みのプリセットを指定してください (flattener.presets.list を参照) +@msg flipProfile must be along|across, got {o} flipProfile には along|across のいずれかを指定してください (指定値: {o}) +@msg folders `{f}`: none, rows, format, item or itemFormat folders `{f}`: none、rows、format、item、itemFormat のいずれかを指定してください +@msg folders deeper than {MAX_BATCH_DEPTH} levels フォルダーの階層が {MAX_BATCH_DEPTH} を超えています +@msg folders deeper than {MAX_DEPTH} levels フォルダーの階層が {MAX_DEPTH} を超えています +@msg font family `{family}` is not available フォントファミリー `{family}` は使用できません +@msg font family `{tf}` is not available フォントファミリー `{tf}` は使用できません +@msg format `{f}`: pdf or postscript format `{f}`: pdf または postscript を指定してください +@msg format `{f}`: text or json format `{f}`: text または json を指定してください +@msg format is `{format}` format は `{format}` です +@msg formats must be an array of rows, not {v} formats には行の配列を指定してください ({v} は指定できません) +@msg frequency must be between 1 and 300 lines per inch frequency には 1 から 300 線/インチまでの値を指定してください +@msg from and to must be finite from と to には有限の値を指定してください +@msg from must be [x0, y0, x1, y1] from には [x0, y0, x1, y1] を指定してください +@msg give `before` or `after`, not both `before` または `after` のどちらか一方を指定してください +@msg give `colors`, or `color` and `rule` `colors`、または `color` と `rule` を指定してください +@msg give `event`, such as onclick onclick などの `event` を指定してください +@msg give `file`, the JavaScript file's path or URL `file` に JavaScript ファイルのパスまたは URL を指定してください +@msg give `fill` and/or `stroke` `fill` と `stroke` の一方または両方を指定してください +@msg give `fill`, `stroke` or both `fill`、`stroke`、またはその両方を指定してください +@msg give `folder` `folder` を指定してください +@msg give `fonts`, or open a document `fonts` を指定するか、ドキュメントを開いてください +@msg give `from` or `indices`, not both `from` または `indices` のどちらか一方を指定してください +@msg give `id` (no text is being edited) `id` を指定してください (編集中のテキストがありません) +@msg give `id` and `anchors`, or `items`, not both `id` と `anchors`、または `items` のどちらか一方を指定してください +@msg give `id` or `guide`, not both `id` または `guide` のどちらか一方を指定してください +@msg give `length` or `to` `length` または `to` を指定してください +@msg give `matches`: [{kind, name, target}] `matches` を指定してください: [{kind, name, target}] +@msg give `name` (or edit a pattern) `name` を指定してください (またはパターンを編集してください) +@msg give `name` or `names` `name` または `names` を指定してください +@msg give `path` (a .wasm file) or `dataBase64` (the module) `path` (.wasm ファイル) または `dataBase64` (モジュール) を指定してください +@msg give `path`, `data` or `dataBase64` `path`、`data`、`dataBase64` のいずれかを指定してください +@msg give `path`, `data`, `dataBase64` or `csv` `path`、`data`、`dataBase64`、`csv` のいずれかを指定してください +@msg give `path`, `xml` or `dataBase64` `path`、`xml`、`dataBase64` のいずれかを指定してください +@msg give `script`, the JavaScript the event runs ("" removes the event) `script` に、イベントで実行する JavaScript を指定してください ("" を指定するとイベントを削除します) +@msg give `text` (the reading) or `remove` `text` (読み) または `remove` を指定してください +@msg give `x` and `y` (and a `tolerance` of 0 or more) `x` と `y` (および 0 以上の `tolerance`) を指定してください +@msg give a mode or r/g/b, c/m/y/k, gray or tint adjustments mode、または r/g/b、c/m/y/k、gray、tint の調整値を指定してください +@msg give a name, or paint the active proxy with a saved preset 名前を指定するか、保存済みのプリセットでアクティブなプロキシをペイントしてください +@msg give a name, or select a stroke with a saved profile 名前を指定するか、保存済みのプロファイルが適用された線を選択してください +@msg give a pattern name or select an object painted with a pattern パターン名を指定するか、パターンでペイントしたオブジェクトを選択してください +@msg give at least one of clip, invert, disabled, linked clip、invert、disabled、linked のうち 1 つ以上を指定してください +@msg give color, none, swatch or gradient color、none、swatch、gradient のいずれかを指定してください +@msg give dataBase64 dataBase64 を指定してください +@msg give either at (a click) or area (a path drawn around the overlaps) at (クリック位置) または area (重なりを囲むように描いたパス) のどちらかを指定してください +@msg give formats or a preset, not both formats またはプリセットのどちらか一方を指定してください +@msg give newName or delete newName または delete を指定してください +@msg give offset or by offset または by を指定してください +@msg give one of `to`, `rect` or `at` `to`、`rect`、`at` のいずれかを指定してください +@msg give one of assets, layers, selection or fullDocument assets、layers、selection、fullDocument のいずれかを指定してください +@msg give only one of onto, above, below, icon and a column place onto、above、below、icon、列の位置のうち 1 つだけを指定してください +@msg give origin: [x, y], or reset: true origin: [x, y] または reset: true を指定してください +@msg give overprintFill, overprintStroke, showCenter, imageMap, url or note overprintFill、overprintStroke、showCenter、imageMap、url、note のいずれかを指定してください +@msg give path (a file) or folder path (ファイル) または folder を指定してください +@msg give path, or name and dataBase64 path、または name と dataBase64 を指定してください +@msg give paths or files paths または files を指定してください +@msg give rows, rowHeight, columns or columnWidth rows、rowHeight、columns、columnWidth のいずれかを指定してください +@msg give svg, or dataBase64 of an SVG or SVGZ file svg、または SVG か SVGZ ファイルの dataBase64 を指定してください +@msg give text text を指定してください +@msg give the asset a name アセットに名前を指定してください +@msg give the preset a `name` プリセットに `name` を指定してください +@msg give the preset a name プリセットに名前を指定してください +@msg give the preset a name (1–64 characters) プリセットに名前を指定してください (1–64 文字) +@msg give the settings to change, e.g. {"formats"}]} 変更する設定を指定してください (例: {"formats"}]}) +@msg give the style a name スタイルに名前を指定してください +@msg give two or more style `names` スタイルの `names` を 2 つ以上指定してください +@msg give two or more swatches スウォッチを 2 つ以上指定してください +@msg give x, y, or a handle's length or angle x、y、またはハンドルの length か angle を指定してください +@msg give {key, value} or {values} {key, value} または {values} を指定してください +@msg global must be true or false global には true または false を指定してください +@msg glyph {_1} is not drawn for {ch} with the character's style (such as All Caps, Small Caps or a numeral system) この文字のスタイル (オールキャップス、スモールキャップ、数字の体系など) では、{ch} にグリフ {_1} は使用されません +@msg glyph {g} is not an alternate of {ch} in {_1} {_2} グリフ {g} は {_1} {_2} における {ch} の代替字形ではありません +@msg gradient must be "objects" or "mesh" gradient には "objects" または "mesh" を指定してください +@msg grays must be "profile" or "black", not `{g}` grays には "profile" または "black" を指定してください (`{g}` は指定できません) +@msg gridColors must be a preset name or two colours gridColors にはプリセット名または 2 つのカラーを指定してください +@msg gridSize must be small, medium or large gridSize には small、medium、large のいずれかを指定してください +@msg guide {g} is not selected ガイド {g} は選択されていません +@msg handle must be 0..3 handle には 0..3 の値を指定してください +@msg hiddenObjects {v}: "layer" (the default), "omit" or "visible" hiddenObjects {v}: "layer" (初期設定)、"omit"、"visible" のいずれかを指定してください +@msg highlight a layer to merge into 結合先のレイヤーをハイライトしてください +@msg highlight two or more rows in one layer or group 1 つのレイヤーまたはグループ内の行を 2 つ以上ハイライトしてください +@msg highlight two or more rows to merge 結合する行を 2 つ以上ハイライトしてください +@msg icon docks a panel in the icon column: use window.panel.dock icon はパネルをアイコン列にドッキングします: window.panel.dock を使用してください +@msg id must be a dimension id id には寸法の ID を指定してください +@msg image has no bounds 画像に境界がありません +@msg image {_1} is linked already 画像 {_1} はすでにリンクされています +@msg imageMap `{m}`: none, client or server imageMap `{m}`: none、client、server のいずれかを指定してください +@msg index out of range インデックスが範囲外です +@msg instances must be 1..1000 instances には 1..1000 の値を指定してください +@msg invalid `color` `color` が無効です +@msg invalid anchor index {v}: expected a non-negative integer アンカーのインデックス {v} が無効です: 0 以上の整数を指定してください +@msg invalid anchor reference {v}: expected [subpath, anchor] アンカーの参照 {v} が無効です: [subpath, anchor] を指定してください +@msg invalid angle 角度が無効です +@msg invalid brush: {e} ブラシが無効です: {e} +@msg invalid color カラーが無効です +@msg invalid colour {c} カラー {c} が無効です +@msg invalid delta 差分が無効です +@msg invalid point 点が無効です +@msg invalid size サイズが無効です +@msg invalid t t が無効です +@msg invalid tolerance 許容値が無効です +@msg its artboards all lie beyond the canvas (more than {_1} pt from the origin) アートボードがすべてキャンバスの外にあります (原点から {_1} pt を超えています) +@msg its clipping masks are nested too deeply クリッピングマスクの入れ子が深すぎます +@msg its metadata has no description メタデータに説明がありません +@msg its metadata has no direct length メタデータに直接指定された長さがありません +@msg join two different paths 異なる 2 つのパスを連結してください +@msg justify must be auto|left|center|right|justifyAll justify には auto|left|center|right|justifyAll のいずれかを指定してください +@msg kbps must be a positive number, not {kbps} kbps には正の数値を指定してください ({kbps} は指定できません) +@msg keywords must be a list of words or a comma-separated string keywords には単語のリストまたはカンマ区切りの文字列を指定してください +@msg keywords must be at most {MAX_KEYWORD} characters, without control characters keywords には制御文字を含まない {MAX_KEYWORD} 文字以内の値を指定してください +@msg kind must be 1, 2 or 3, or give a preset `name` (see perspective.presets.list) kind には 1、2、3 のいずれかを指定するか、プリセットの `name` を指定してください (perspective.presets.list を参照) +@msg kind must be graphic, fillColor, strokeColor, fillGradient, strokeGradient, fillPattern, strokePattern, charStyle or paraStyle kind には graphic、fillColor、strokeColor、fillGradient、strokeGradient、fillPattern、strokePattern、charStyle、paraStyle のいずれかを指定してください +@msg knockout must be "on", "off", "neutral" or a bool, not {v} knockout には "on"、"off"、"neutral"、またはブール値を指定してください ({v} は指定できません) +@msg layer `{name}` has no art to export レイヤー `{name}` に書き出せるアートがありません +@msg layer must name a layer or sublayer layer にはレイヤーまたはサブレイヤーを指定してください +@msg layers can't be intertwined: select the objects in them レイヤーを絡み合わせることはできません: レイヤー内のオブジェクトを選択してください +@msg layers go only at the top level or in layers, objects in layers and groups レイヤーを置けるのは最上位またはレイヤー内だけで、オブジェクトを置けるのはレイヤー内とグループ内です +@msg layers must be true or false layers には true または false を指定してください +@msg layout must be gridByRow, gridByColumn, row or column layout には gridByRow、gridByColumn、row、column のいずれかを指定してください +@msg leading must be a number or "auto" leading には数値または "auto" を指定してください +@msg left/right must be non-negative widths left/right には 0 以上の幅を指定してください +@msg level `{t}`: 2 or 3 level `{t}`: 2 または 3 を指定してください +@msg line {line}: more than {MAX_CSV_COLS} columns {line} 行目: 列が {MAX_CSV_COLS} 個を超えています +@msg line {line}: unclosed quote {line} 行目: 引用符が閉じられていません +@msg line {line}: value for `{var}` must match its variable kind {line} 行目: `{var}` の値は変数の種類に合わせてください +@msg lineEndings `{other}`: lf or crlf lineEndings `{other}`: lf または crlf を指定してください +@msg loading profiles from disk isn't available in the browser ブラウザーではディスクからプロファイルを読み込めません +@msg margin: a {m} pt margin leaves no imageable area on the paper margin: マージンが {m} pt では用紙にプリント可能な領域が残りません +@msg matrix must be finite and invertible, depth finite matrix には有限で逆行列を持つ値、depth には有限の値を指定してください +@msg matte: {e} matte: {e} +@msg member is for order front, forward, backward or back member は order が front、forward、backward、back のいずれかの場合に指定します +@msg missing `artboards` `artboards` がありません +@msg missing `at` [x, y] `at` [x, y] がありません +@msg missing `attrs` `attrs` がありません +@msg missing `color` or `opacity` `color` または `opacity` がありません +@msg missing `colors` `colors` がありません +@msg missing `commands` `commands` がありません +@msg missing `destinationFolder` `destinationFolder` がありません +@msg missing `effect` id `effect` の ID がありません +@msg missing `family` `family` がありません +@msg missing `find` `find` がありません +@msg missing `gid` (a glyph id, or null for the default glyph) `gid` がありません (グリフ ID、または初期設定のグリフにする場合は null) +@msg missing `group` `group` がありません +@msg missing `id` `id` がありません +@msg missing `id`: give one, or select one type object `id` がありません: 指定するか、文字オブジェクトを 1 つ選択してください +@msg missing `index` (a point index, or null to clear) `index` がありません (ポイントのインデックス、または消去する場合は null) +@msg missing `index` (a stop index, or null to clear) `index` がありません (分岐点のインデックス、または消去する場合は null) +@msg missing `index` (an item index or null) `index` がありません (項目のインデックスまたは null) +@msg missing `item` `item` がありません +@msg missing `library` `library` がありません +@msg missing `library` (see graphicStyle.libraries) `library` がありません (graphicStyle.libraries を参照) +@msg missing `library` (see swatch.library.list) `library` がありません (swatch.library.list を参照) +@msg missing `map` (rows [{from, to}] or {current}) `map` がありません (行 [{from, to}] または {current}) +@msg missing `matrix` [a,b,c,d,e,f] `matrix` [a,b,c,d,e,f] がありません +@msg missing `name` (see gradient.presets.list) `name` がありません (gradient.presets.list を参照) +@msg missing `offset` (a distance in points) `offset` がありません (ポイント単位の距離) +@msg missing `path` `path` がありません +@msg missing `path` (a path object id) `path` がありません (パスオブジェクトの ID) +@msg missing `rule` `rule` がありません +@msg missing `source` id `source` の ID がありません +@msg missing `start` (the byte offset of a character) `start` がありません (文字のバイトオフセット) +@msg missing `status`: linked, embedded, missing or modified `status` がありません: linked、embedded、missing、modified のいずれかを指定してください +@msg missing `target` id `target` の ID がありません +@msg missing `text` `text` がありません +@msg missing `to` `to` がありません +@msg missing `to` (an index) `to` がありません (インデックス) +@msg missing `to`: a non-negative integer `to` がありません: 0 以上の整数を指定してください +@msg missing `type` `type` がありません +@msg missing `value` `value` がありません +@msg missing `{key}` `{key}` がありません +@msg missing `{k}` `{k}` がありません +@msg missing anchor anchor がありません +@msg missing anchors anchors がありません +@msg missing anchors [[subpath, anchor]…] anchors [[subpath, anchor]…] がありません +@msg missing array `{key}` 配列 `{key}` がありません +@msg missing case case がありません +@msg missing color color がありません +@msg missing commands commands がありません +@msg missing destination folder 出力先フォルダーがありません +@msg missing from from がありません +@msg missing group group がありません +@msg missing id or ids id または ids がありません +@msg missing ids ids がありません +@msg missing indexes indexes がありません +@msg missing matrix [a,b,c,d,e,f] matrix [a,b,c,d,e,f] がありません +@msg missing name name がありません +@msg missing op op がありません +@msg missing or invalid `color` `color` がないか、無効です +@msg missing or unknown `tool` `tool` がないか、不明です +@msg missing point point がありません +@msg missing point [x,y] point [x,y] がありません +@msg missing point `{key}` ([x, y]) 点 `{key}` ([x, y]) がありません +@msg missing points points がありません +@msg missing points [[x,y]…] points [[x,y]…] がありません +@msg missing segment segment がありません +@msg missing stops stops がありません +@msg missing subpaths subpaths がありません +@msg missing target target がありません +@msg missing to to がありません +@msg missing x, y x, y がありません +@msg mode is set, add or toggle, not `{other}` mode には set、add、toggle のいずれかを指定してください (`{other}` は指定できません) +@msg mode must be "cmyk" or "rgb" mode には "cmyk" または "rgb" を指定してください +@msg mode must be area|onPath, got {o} mode には area|onPath のいずれかを指定してください (指定値: {o}) +@msg more than 10000 linked files: package dependencies in smaller parts リンクファイルが 10000 個を超えています: 依存ファイルを小分けにしてパッケージしてください +@msg more than 256 commands コマンドが 256 個を超えています +@msg more than {MAX_BATCH_FILES} data sets データセットが {MAX_BATCH_FILES} 個を超えています +@msg more than {MAX_BATCH_FILES} files ファイルが {MAX_BATCH_FILES} 個を超えています +@msg more than {MAX_CSV_ROWS} data rows データ行が {MAX_CSV_ROWS} 行を超えています +@msg more than {MAX_FILES} images 画像が {MAX_FILES} 個を超えています +@msg more than {MAX_IMPORT} presets プリセットが {MAX_IMPORT} 個を超えています +@msg moved must be [[x,y]…] moved には [[x,y]…] を指定してください +@msg name (a toolbar's name) is required name (ツールバー名) は必須です +@msg name (a toolbar's name) must be a string name (ツールバー名) には文字列を指定してください +@msg name must be a toolbar's name name にはツールバー名を指定してください +@msg names is empty names が空です +@msg names must be an array of symbol names names にはシンボル名の配列を指定してください +@msg need `anchor` or `segment` + `t` `anchor`、または `segment` + `t` が必要です +@msg need at least one anchor アンカーが 1 つ以上必要です +@msg need at least one point 点が 1 つ以上必要です +@msg need at least two points 点が 2 つ以上必要です +@msg needs points 点が必要です +@msg nineSlice must be true or false nineSlice には true または false を指定してください +@msg nineSliceGuides must be [left, top, right, bottom], each -16..16, with left + right < 1 and top + bottom < 1 nineSliceGuides には [left, top, right, bottom] を指定してください。各値は -16..16 で、left + right < 1 かつ top + bottom < 1 にしてください +@msg no PDF preset named `{n}` `{n}` という名前の PDF プリセットはありません +@msg no action set is current 現在のアクションセットがありません +@msg no active data set アクティブなデータセットがありません +@msg no appearance item {index} アピアランス項目 {index} はありません +@msg no artboard {_1} アートボード {_1} はありません +@msg no artboard {artboard} (0-based; the document has {_1}) アートボード {artboard} はありません (0 から始まるインデックス。ドキュメントのアートボードは {_1} 個) +@msg no asset {id} アセット {id} はありません +@msg no asset {id} (see assets.list) アセット {id} はありません (assets.list を参照) +@msg no assets to export 書き出すアセットがありません +@msg no assets yet: collect art for export first (assets.add) アセットがまだありません: 先に書き出すアートを収集してください (assets.add) +@msg no brush named `{n}` `{n}` という名前のブラシはありません +@msg no character at byte {start} バイト {start} の位置に文字はありません +@msg no colour カラーがありません +@msg no colour group `{group}` カラーグループ `{group}` はありません +@msg no colour group `{name}` カラーグループ `{name}` はありません +@msg no data sets データセットがありません +@msg no dataset named `{from}` `{from}` という名前のデータセットはありません +@msg no dataset named `{name}` `{name}` という名前のデータセットはありません +@msg no datasets データセットがありません +@msg no design named `{name}` `{name}` という名前のデザインはありません +@msg no design named `{n}` `{n}` という名前のデザインはありません +@msg no design named `{old}` `{old}` という名前のデザインはありません +@msg no encoder for {_1} yet {_1} のエンコーダーはまだありません +@msg no export preset `{name}` (see document.exportPresets.list) 書き出しプリセット `{name}` はありません (document.exportPresets.list を参照) +@msg no folder: pass `path` or set Preferences › Plug-ins & Scratch Disks › Additional Plug-ins Folder フォルダーがありません: `path` を指定するか、「環境設定 › プラグイン & 仮想記憶ディスク › 追加プラグインフォルダー」を設定してください +@msg no fonts to look for: they are all available 検索するフォントがありません: すべて使用できます +@msg no formats to export 書き出す形式がありません +@msg no gradient preset `{name}` (see gradient.presets.list) グラデーションプリセット `{name}` はありません (gradient.presets.list を参照) +@msg no graphic style `{n}` in `{_1}` `{_1}` にグラフィックスタイル `{n}` はありません +@msg no graphic style library `{key}` (see graphicStyle.libraries) グラフィックスタイルライブラリ `{key}` はありません (graphicStyle.libraries を参照) +@msg no guide selected ガイドが選択されていません +@msg no guide selected (or give an index) ガイドが選択されていません (またはインデックスを指定してください) +@msg no guide {i} ガイド {i} はありません +@msg no images in the folder フォルダーに画像がありません +@msg no item at index {_1} インデックス {_1} に項目はありません +@msg no item at index {from} インデックス {from} に項目はありません +@msg no item at one of the indices {idx} インデックス {idx} のいずれかに項目がありません +@msg no layer レイヤーがありません +@msg no layer {id} (see layer.list) レイヤー {id} はありません (layer.list を参照) +@msg no layers to export 書き出すレイヤーがありません +@msg no library `{key}` ライブラリ `{key}` はありません +@msg no metafile format メタファイル形式はありません +@msg no object {_1} オブジェクト {_1} はありません +@msg no objects オブジェクトがありません +@msg no parent layer 親レイヤーがありません +@msg no perspective grid preset named `{b}` (see perspective.presets.list) `{b}` という名前の遠近グリッドプリセットはありません (perspective.presets.list を参照) +@msg no perspective grid preset named `{n}` `{n}` という名前の遠近グリッドプリセットはありません +@msg no point selected (give `index`) ポイントが選択されていません (`index` を指定してください) +@msg no preset called `{from}` (see file.newPresets) `{from}` というプリセットはありません (file.newPresets を参照) +@msg no preset called `{name}` (see file.newPresets) `{name}` というプリセットはありません (file.newPresets を参照) +@msg no preset named `{n}` `{n}` という名前のプリセットはありません +@msg no print preset named `{b}` (see print.presets.list) `{b}` という名前のプリントプリセットはありません (print.presets.list を参照) +@msg no print preset named `{name}` (presets: {_1}) `{name}` という名前のプリントプリセットはありません (プリセット: {_1}) +@msg no print preset named `{n}` `{n}` という名前のプリントプリセットはありません +@msg no profile named `{name}` `{name}` という名前のプロファイルはありません +@msg no readable files in the folder フォルダーに読み込めるファイルがありません +@msg no recovery copy `{f}` (see file.recovery.list) 復元用コピー `{f}` はありません (file.recovery.list を参照) +@msg no rows 行がありません +@msg no saved PDF preset named `{name}` `{name}` という名前の保存済み PDF プリセットはありません +@msg no saved export preset `{name}` 保存済みの書き出しプリセット `{name}` はありません +@msg no saved gradient preset called {name} {name} という保存済みのグラデーションプリセットはありません +@msg no saved gradient presets 保存済みのグラデーションプリセットがありません +@msg no saved preset called `{name}` `{name}` という保存済みのプリセットはありません +@msg no saved presets to export (name [Default] in `names` to export it) 書き出す保存済みプリセットがありません ([Default] を書き出すには `names` に指定してください) +@msg no saved presets to export (name built-in ones in `names`) 書き出す保存済みプリセットがありません (組み込みのプリセットは `names` に指定してください) +@msg no saved print preset named `{name}` `{name}` という名前の保存済みプリントプリセットはありません +@msg no saved profile called {name} {name} という保存済みのプロファイルはありません +@msg no saved selection `{name}` 保存した選択範囲 `{name}` はありません +@msg no saved theme called {name} (see colorTheme.list) {name} という保存済みのテーマはありません (colorTheme.list を参照) +@msg no saved views 保存した表示がありません +@msg no series {i} 系列 {i} はありません +@msg no slice {n} in the image (see slice.list) 画像にスライス {n} はありません (slice.list を参照) +@msg no source art 元のアートがありません +@msg no stop {i} (the gradient has {n}) 分岐点 {i} はありません (グラデーションの分岐点は {n} 個) +@msg no style `{name}` スタイル `{name}` はありません +@msg no such assets (see assets.list) 該当するアセットはありません (assets.list を参照) +@msg no such frame anchor, or the frame would reach past the canvas 該当するフレームのアンカーがないか、フレームがキャンバスからはみ出します +@msg no such objects 該当するオブジェクトはありません +@msg no such path anchor, or the path would reach past the canvas 該当するパスのアンカーがないか、パスがキャンバスからはみ出します +@msg no such rows 該当する行はありません +@msg no swatch `{keep}` スウォッチ `{keep}` はありません +@msg no swatch `{n}` スウォッチ `{n}` はありません +@msg no swatch `{n}` (swatches and colour groups move separately) スウォッチ `{n}` はありません (スウォッチとカラーグループは別々に移動します) +@msg no swatch library `{key}` (see swatch.library.list) スウォッチライブラリ `{key}` はありません (swatch.library.list を参照) +@msg no swatch library `{key}` (see swatch.library.list; "document": the document's swatches) スウォッチライブラリ `{key}` はありません (swatch.library.list を参照。"document" はドキュメントのスウォッチ) +@msg no swatch library `{key}` (see swatch.library.list; "{DOCUMENT_SWATCHES}": the document's swatches) スウォッチライブラリ `{key}` はありません (swatch.library.list を参照。"{DOCUMENT_SWATCHES}" はドキュメントのスウォッチ) +@msg no swatch named `{n}` `{n}` という名前のスウォッチはありません +@msg no swatch or colour group `{n}` スウォッチまたはカラーグループ `{n}` はありません +@msg no swatch or colour group `{n}` in `{_1}` `{_1}` にスウォッチまたはカラーグループ `{n}` はありません +@msg no symbol named `{name}` `{name}` という名前のシンボルはありません +@msg no text objects selected テキストオブジェクトが選択されていません +@msg no toolbar named `{_1}` `{_1}` という名前のツールバーはありません +@msg no toolbar named `{name}` `{name}` という名前のツールバーはありません +@msg no tracing preset `{preset}` (see imageTrace.presets) トレースプリセット `{preset}` はありません (imageTrace.presets を参照) +@msg no user library folder here (save with a path, or without one to get the data) ここにはユーザーライブラリフォルダーがありません (パスを指定して保存するか、パスを指定せずにデータを取得してください) +@msg no variable named `{from}` `{from}` という名前の変数はありません +@msg no variable named `{name}` `{name}` という名前の変数はありません +@msg no variable named `{var}` `{var}` という名前の変数はありません +@msg no variable named `{v}` `{v}` という名前の変数はありません +@msg no view named `{name}` `{name}` という名前の表示はありません +@msg node {_1} is not a graph ノード {_1} はグラフではありません +@msg node {_1} is not an image ノード {_1} は画像ではありません +@msg node {_1} is not type ノード {_1} は文字ではありません +@msg not a PDF presets file (format `{_1}`) PDF プリセットファイルではありません (形式 `{_1}`) +@msg not a PDF presets file: {e} PDF プリセットファイルではありません: {e} +@msg not a Word document: its WordDocument stream doesn't start with a file information block Word 文書ではありません: WordDocument ストリームがファイル情報ブロックで始まっていません +@msg not a Word document: its compound file has no WordDocument stream Word 文書ではありません: 複合ファイルに WordDocument ストリームがありません +@msg not a Word document: its main part is not a WordprocessingML document Word 文書ではありません: メインパートが WordprocessingML 文書ではありません +@msg not a Word document: its package has no main document part Word 文書ではありません: パッケージにメイン文書パートがありません +@msg not a closed path クローズパスではありません +@msg not a flattener presets file (format `{_1}`) 分割・統合プリセットファイルではありません (形式 `{_1}`) +@msg not a flattener presets file: {e} 分割・統合プリセットファイルではありません: {e} +@msg not a layer or group レイヤーでもグループでもありません +@msg not a library file: {e} ライブラリファイルではありません: {e} +@msg not a mesh envelope point メッシュエンベロープのポイントではありません +@msg not a perspective grid presets file (format `{_1}`) 遠近グリッドプリセットファイルではありません (形式 `{_1}`) +@msg not a perspective grid presets file: {e} 遠近グリッドプリセットファイルではありません: {e} +@msg not a print presets file (format `{_1}`) プリントプリセットファイルではありません (形式 `{_1}`) +@msg not a print presets file: {e} プリントプリセットファイルではありません: {e} +@msg not a stored or deflated central record 無圧縮または Deflate 圧縮のセントラルレコードではありません +@msg not a valid SVGZ file: {e} 有効な SVGZ ファイルではありません: {e} +@msg not an RTF file: it doesn't start with {\\rtf RTF ファイルではありません: {\\rtf で始まっていません +@msg not an image VectorCraft reads (see document.formats) VectorCraft で読み込める画像ではありません (document.formats を参照) +@msg not area type (text in a frame) outside perspective 遠近グリッド外のエリア内文字 (フレーム内のテキスト) ではありません +@msg not editing an opacity mask 不透明マスクを編集中ではありません +@msg not type on a path outside perspective 遠近グリッド外のパス上文字ではありません +@msg nothing prints プリントされるものがありません +@msg nothing to bind バインドする対象がありません +@msg nothing to change 変更する内容がありません +@msg nothing to change: give dx, dy, hScale, vScale or rotation 変更する内容がありません: dx、dy、hScale、vScale、rotation のいずれかを指定してください +@msg nothing to crop 切り抜く対象がありません +@msg nothing to export 書き出す対象がありません +@msg nothing to export: the document has no visible art 書き出す対象がありません: ドキュメントに表示されているアートがありません +@msg nothing to mark マークする対象がありません +@msg nothing to print: every artboard picked is blank プリントする対象がありません: 選択したアートボードがすべて空白です +@msg nothing to print: the document has no art that prints プリントする対象がありません: ドキュメントにプリントされるアートがありません +@msg object is not a path オブジェクトがパスではありません +@msg object transparency cannot be sampled onto highlighted characters; disable Transparency in Eyedropper Options or select the whole object オブジェクトの透明は、ハイライトした文字には適用できません。「スポイトオプション」の「透明」をオフにするか、オブジェクト全体を選択してください +@msg object {_1} can't be set as point type オブジェクト {_1} はポイント文字にできません +@msg object {_1} has lost its file's contents: relink it オブジェクト {_1} のファイルの内容が失われています: 再リンクしてください +@msg object {_1} has no path オブジェクト {_1} にパスがありません +@msg object {_1} has no size オブジェクト {_1} にサイズがありません +@msg object {_1} is hidden or locked, or on a locked artboard オブジェクト {_1} は非表示かロックされているか、ロックされたアートボード上にあります +@msg object {_1} is not a placed document オブジェクト {_1} は配置したドキュメントではありません +@msg object {_1} is not an Intertwine group オブジェクト {_1} は織り交ぜグループではありません +@msg object {_1} is not an image オブジェクト {_1} は画像ではありません +@msg object {_1} is not an image or a linked file オブジェクト {_1} は画像でもリンクファイルでもありません +@msg object {_1} is not an image or a placed document オブジェクト {_1} は画像でも配置したドキュメントでもありません +@msg object {_1} is not in this Intertwine group オブジェクト {_1} はこの織り交ぜグループに含まれていません +@msg object {_1} needs a 3D effect at index {index} オブジェクト {_1} にはインデックス {index} に 3D 効果が必要です +@msg object {id} has anchors 0–{_1} for `corners`, not {past} オブジェクト {id} で `corners` に指定できるアンカーは 0–{_1} です ({past} は指定できません) +@msg object {id} has {n} anchors, so no anchor {past} オブジェクト {id} のアンカーは {n} 個のため、アンカー {past} はありません +@msg objects must be none, move or copy objects には none、move、copy のいずれかを指定してください +@msg objects were left out 除外されたオブジェクトがあります +@msg offset out of range オフセットが範囲外です +@msg on must be true or false on には true または false を指定してください +@msg only groups, layers, type and images have a Contents (Characters) row 「内容 (文字)」行があるのは、グループ、レイヤー、文字、画像だけです +@msg only interior mesh lines can be deleted 削除できるのは内側のメッシュラインだけです +@msg only solid colours can be added (not gradients or patterns) 追加できるのは単色だけです (グラデーションとパターンは追加できません) +@msg only solid-colour swatches can be spot colours 特色にできるのは単色のスウォッチだけです +@msg only this Affinity file's embedded preview could be read: use File › Open to see it with its warning, or export SVG or PDF from Affinity first この Affinity ファイルは埋め込みプレビューしか読み込めませんでした: 「ファイル › 開く」で警告とともに表示するか、先に Affinity から SVG または PDF を書き出してください +@msg only this Affinity file's embedded preview could be read; use File › Open to see it with its warning この Affinity ファイルは埋め込みプレビューしか読み込めませんでした。「ファイル › 開く」で警告とともに表示できます +@msg onto, above, below, icon and a column place belong to window.panel.float and window.panel.dock onto、above、below、icon、列の位置は window.panel.float と window.panel.dock で指定します +@msg onto, above, below, icon and a column place take no anchor, side, zone or before onto、above、below、icon、列の位置を指定する場合、anchor、side、zone、before は指定できません +@msg onto, above, below, icon and a column place take no x, y, width or height onto、above、below、icon、列の位置を指定する場合、x、y、width、height は指定できません +@msg open a document to look for its linked files リンクファイルを検索するには、ドキュメントを開いてください +@msg options must be an object (see file.formatOptions) options にはオブジェクトを指定してください (file.formatOptions を参照) +@msg order must be leftToRight or rightToLeft order には leftToRight または rightToLeft を指定してください +@msg orientation must be portrait or landscape, not `{o}` orientation には portrait または landscape を指定してください (`{o}` は指定できません) +@msg outlineText {v}: true or false outlineText {v}: true または false を指定してください +@msg output intent profile: {e} 出力インテントのプロファイル: {e} +@msg output.destination: no RGB or CMYK profile is called “{name}” output.destination: 「{name}」という名前の RGB または CMYK プロファイルはありません +@msg output.destination: {_1} files are CMYK, and “{name}” is an RGB profile output.destination: {_1} ファイルは CMYK ですが、「{name}」は RGB プロファイルです +@msg output.destination: {e} output.destination: {e} +@msg output.inks: no ink is set to print output.inks: プリントするように設定されたインキがありません +@msg output.outputIntent: no profile is called “{name}”, and a {std} output intent embeds its profile output.outputIntent: 「{name}」という名前のプロファイルはありません。{std} の出力インテントにはプロファイルを埋め込みます +@msg output.outputIntent: no profile is called “{name}”: a {std} output intent embeds a profile, or names a registered printing condition (outputConditionId and registry) output.outputIntent: 「{name}」という名前のプロファイルはありません: {std} の出力インテントには、プロファイルを埋め込むか、登録済みの印刷条件 (outputConditionId と registry) を指定します +@msg output.outputIntent: {std} files print in CMYK, and “{name}” is an RGB profile output.outputIntent: {std} ファイルは CMYK でプリントされますが、「{name}」は RGB プロファイルです +@msg output.outputIntent: “{name}” is a grey profile, which can't be a {std} output intent output.outputIntent: 「{name}」はグレープロファイルのため、{std} の出力インテントにはできません +@msg overlap: {o} pt is half a tile or more overlap: {o} pt はタイルの半分以上です +@msg overlapping Shaper paths must be in the same layer or group 重なり合う Shaper パスは、同じレイヤーまたはグループ内にある必要があります +@msg overlapping edits 編集範囲が重なっています +@msg page art conflicts with image data for {key} ページのアートが {key} の画像データと一致しません +@msg page art conflicts with pattern {name} ページのアートがパターン {name} と一致しません +@msg page art conflicts with swatch {name} ページのアートがスウォッチ {name} と一致しません +@msg page art is missing image data for {key} ページのアートに {key} の画像データがありません +@msg page art is missing pattern {name} ページのアートにパターン {name} がありません +@msg page art is missing swatch {name} ページのアートにスウォッチ {name} がありません +@msg page must be a whole number from 1 page には 1 以上の整数を指定してください +@msg page thumbnail: {e} ページのサムネール: {e} +@msg page {page} of the PDF has no objects PDF の {page} ページにオブジェクトがありません +@msg page {page}: `{file}` has {n} {artboards} {page} ページ: `{file}` には {n} {artboards} あります +@msg page {page}: `{name}` has {n} {pages} {page} ページ: `{name}` には {n} {pages} あります +@msg pages must be a range such as "2-3" or a page number, not {v} pages には "2-3" のような範囲またはページ番号を指定してください ({v} は指定できません) +@msg pages: {e} pages: {e} +@msg panel position must be finite パネルの位置には有限の値を指定してください +@msg parameters must be an object parameters にはオブジェクトを指定してください +@msg params must be an object params にはオブジェクトを指定してください +@msg passwords can have up to {MAX_PASSWORD} bytes パスワードは {MAX_PASSWORD} バイト以内です +@msg path has no open end パスに開いた端点がありません +@msg paths must be strings paths には文字列を指定してください +@msg pdfCompatible: false needs every artboard to keep the editable artwork pdfCompatible: false の場合、編集可能なアートワークを保持するためにすべてのアートボードが必要です +@msg pdfs `{m}`: single or multiple pdfs `{m}`: single または multiple を指定してください +@msg pickColorFrom is "artwork" or "swatches", not {v} pickColorFrom には "artwork" または "swatches" を指定してください ({v} は指定できません) +@msg pins and moved must be non-empty lists of the same length pins と moved には、同じ長さの空でないリストを指定してください +@msg pins must be [[x,y]…] pins には [[x,y]…] を指定してください +@msg pins must be finite pins には有限の値を指定してください +@msg place is above, below or inside, not `{other}` place には above、below、inside のいずれかを指定してください (`{other}` は指定できません) +@msg plane must be left|right|ground plane には left|right|ground のいずれかを指定してください +@msg plane must be left|right|ground|none plane には left|right|ground|none のいずれかを指定してください +@msg point is outside the mesh 点がメッシュの外にあります +@msg points must be [t, left, right] with non-negative widths points には、幅が 0 以上の [t, left, right] を指定してください +@msg points must be a non-empty [[x,y,pressure?]…] list points には空でない [[x,y,pressure?]…] のリストを指定してください +@msg points must be a non-empty list of finite [x,y] points には有限の [x,y] からなる空でないリストを指定してください +@msg points must be an array or null points には配列または null を指定してください +@msg points must be finite points には有限の値を指定してください +@msg points must be finite [x,y] pairs points には有限の [x,y] の組を指定してください +@msg points must contain 1–4096 coordinates points には 1–4096 個の座標を指定してください +@msg position must be normal, superscript or subscript position には normal、superscript、subscript のいずれかを指定してください +@msg position must be topLeft, topRight, bottomLeft or bottomRight position には topLeft、topRight、bottomLeft、bottomRight のいずれかを指定してください +@msg positions must be between 0 and 100000 pt positions には 0 から 100000 pt までの値を指定してください +@msg ppi must be a positive number, not {ppi} ppi には正の数値を指定してください ({ppi} は指定できません) +@msg ppi must be between 1 and 2400 ppi には 1 から 2400 までの値を指定してください +@msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}` は transforms|bounds|fileDimensions|fit|fill のいずれでもありません +@msg preserveShape must be clippingMask|transparency preserveShape には clippingMask|transparency のいずれかを指定してください +@msg preset `{id}`: mobile or density preset `{id}`: mobile または density を指定してください +@msg preset must be standard, diffuse, topLeft or right preset には standard、diffuse、topLeft、right のいずれかを指定してください +@msg preset must be the name of a print preset preset にはプリントプリセットの名前を指定してください +@msg previewMode must be default, pixel or overprint previewMode には default、pixel、overprint のいずれかを指定してください +@msg print settings: {e} プリント設定: {e} +@msg procedures nest too deeply プロシージャの入れ子が深すぎます +@msg procedures nested too deeply プロシージャの入れ子が深すぎます +@msg quotes must be {double?, single?} quotes には {double?, single?} を指定してください +@msg quotes.{k} must be an opening and a closing quote, e.g. "“”" quotes.{k} には開き引用符と閉じ引用符を指定してください (例: "“”") +@msg rasterEffectsPpi must be 1–2400 (72 screen, 150 medium, 300 high) rasterEffectsPpi には 1–2400 を指定してください (72 がスクリーン、150 が標準、300 が高解像度) +@msg rating must be a whole number from 0 to {MAX_RATING} rating には 0 から {MAX_RATING} までの整数を指定してください +@msg rect and {k} contradict each other: give the area or the artboards rect と {k} が矛盾しています: 領域またはアートボードのどちらかを指定してください +@msg rect applies to raster formats, not {_1} rect はラスター形式に適用されます ({_1} には適用されません) +@msg rect is [x, y, width, height] in points rect には [x, y, width, height] をポイント単位で指定してください +@msg rect must be [x, y, width, height] rect には [x, y, width, height] を指定してください +@msg rect must be [x, y, width, height] with a positive width and height rect には、幅と高さが正の [x, y, width, height] を指定してください +@msg rect needs finite numbers and a positive width and height rect には有限の数値と、正の幅と高さが必要です +@msg redraw needs id redraw には id が必要です +@msg redraw within must be a finite distance of 0 or more redraw の within には 0 以上の有限の距離を指定してください +@msg registration must be 0..8 registration には 0..8 の値を指定してください +@msg release a layer or a group レイヤーまたはグループを解除してください +@msg replace keeps the replaced object's place and transform: drop template, at and rect replace では置き換えられるオブジェクトの位置と変形が保持されます: template、at、rect は指定しないでください +@msg replace: select the one object to replace replace: 置き換えるオブジェクトを 1 つ選択してください +@msg resolution must be a number or screen|medium|high resolution には数値、または screen|medium|high のいずれかを指定してください +@msg resolution must be between 1 and 2400 ppi resolution には 1 から 2400 ppi までの値を指定してください +@msg rotation must be a number of degrees rotation には度数の数値を指定してください +@msg rotation must be finite rotation には有限の値を指定してください +@msg rows and cols must be 1..50 rows と cols には 1..50 の値を指定してください +@msg rows and columns must be 1..500 rows と columns には 1..500 の値を指定してください +@msg rows of objects whose appearances differ can't be reordered together アピアランスが異なるオブジェクトの行は、まとめて並べ替えられません +@msg save the document first: Package collects a saved document 先にドキュメントを保存してください: パッケージは保存済みのドキュメントを収集します +@msg save the document first: copy puts the file in its folder 先にドキュメントを保存してください: copy はファイルをドキュメントのフォルダーに置きます +@msg savedPreset: {e} savedPreset: {e} +@msg scale `{s}`: a factor such as 2x, a width (100w), a height (100h) or a resolution (72ppi) scale `{s}`: 2x のような倍率、幅 (100w)、高さ (100h)、解像度 (72ppi) のいずれかを指定してください +@msg scale must be a number above 0, at most 64 scale には 0 より大きく 64 以下の数値を指定してください +@msg scale must be non-zero scale には 0 以外の値を指定してください +@msg scope must be selection or all (got {other}) scope には selection または all を指定してください (指定値: {other}) +@msg scribble is too long 落書きが長すぎます +@msg segment does not exist セグメントが存在しません +@msg select a Shaper group Shaper グループを選択してください +@msg select a blend to set easing or color shift イージングまたはカラーシフトを設定するブレンドを選択してください +@msg select a compound shape 複合シェイプを選択してください +@msg select a graph グラフを選択してください +@msg select a group or layer with visible, unlocked members 表示されていてロックされていないメンバーを含むグループまたはレイヤーを選択してください +@msg select a layer レイヤーを選択してください +@msg select a text object テキストオブジェクトを選択してください +@msg select an image (or an Image Trace group) 画像 (または画像トレースグループ) を選択してください +@msg select an image, or pass id 画像を選択するか、id を指定してください +@msg select an object (or pass `id`) オブジェクトを選択してください (または `id` を指定してください) +@msg select an object with a freeform gradient フリーフォームグラデーションのあるオブジェクトを選択してください +@msg select an object with an opacity mask 不透明マスクのあるオブジェクトを選択してください +@msg select area type エリア内文字を選択してください +@msg select area type (text in a frame) エリア内文字 (フレーム内のテキスト) を選択してください +@msg select area type and closed paths (at least one area type object) エリア内文字とクローズパスを選択してください (エリア内文字オブジェクトが 1 つ以上必要です) +@msg select area type whose first line can fit its frame 1 行目がフレームに収まるエリア内文字を選択してください +@msg select artwork to add its colours カラーを追加するアートワークを選択してください +@msg select artwork to make a group of its colours カラーのグループを作成するアートワークを選択してください +@msg select artwork to recolour, or give a colour `group` 再配色するアートワークを選択するか、カラーの `group` を指定してください +@msg select exactly two path ends to join 連結するパスの端点をちょうど 2 つ選択してください +@msg select members of a compound shape 複合シェイプのメンバーを選択してください +@msg select objects or give ids オブジェクトを選択するか、ids を指定してください +@msg select objects to align to the guide ガイドに整列するオブジェクトを選択してください +@msg select one Intertwine group 織り交ぜグループを 1 つ選択してください +@msg select one image or pass id 画像を 1 つ選択するか、id を指定してください +@msg select paths パスを選択してください +@msg select paths or compound paths パスまたは複合パスを選択してください +@msg select rows or objects to collect 収集する行またはオブジェクトを選択してください +@msg select something to export 書き出す対象を選択してください +@msg select something to export (or turn off selectedOnly) 書き出す対象を選択してください (または selectedOnly をオフにしてください) +@msg select text to redefine the style from スタイルの再定義に使用するテキストを選択してください +@msg select the art and, on top of it, the mask object アートと、その前面にあるマスクオブジェクトを選択してください +@msg select the art for the design デザインにするアートを選択してください +@msg select the art for the pattern tile パターンタイルにするアートを選択してください +@msg select the art to add first 先に追加するアートを選択してください +@msg select the art to collect (or give its ids) 収集するアートを選択してください (またはその ids を指定してください) +@msg select the content and a path on top 内容と、その前面にあるパスを選択してください +@msg select the images to relink, or pass ids 再リンクする画像を選択するか、ids を指定してください +@msg select the images, or pass ids 画像を選択するか、ids を指定してください +@msg select the linked images or placed documents, or pass ids リンク画像または配置したドキュメントを選択するか、ids を指定してください +@msg select the object to copy from コピー元のオブジェクトを選択してください +@msg select the objects (or give their ids) オブジェクトを選択してください (またはその ids を指定してください) +@msg select the objects to attach to the path パスに配置するオブジェクトを選択してください +@msg select the objects to bind バインドするオブジェクトを選択してください +@msg select two or more objects to intertwine 織り交ぜるオブジェクトを 2 つ以上選択してください +@msg select two or more slices to combine 結合するスライスを 2 つ以上選択してください +@msg select type on a path パス上文字を選択してください +@msg selection `{m}`: one or each selection `{m}`: one または each を指定してください +@msg settings is an object of document.exportForScreens params settings には document.exportForScreens のパラメーターのオブジェクトを指定してください +@msg settings must be an object settings にはオブジェクトを指定してください +@msg show `{show}`: all, missing, modified or embedded show `{show}`: all、missing、modified、embedded のいずれかを指定してください +@msg show must be true or false show には true または false を指定してください +@msg size must be "small", "medium", "large" or a number of points over 0 up to {_1} size には "small"、"medium"、"large"、または 0 より大きく {_1} 以下のポイント数を指定してください +@msg size must be positive size には正の値を指定してください +@msg sizeMode is "fixed" or "pressure", not `{other}` sizeMode には "fixed" または "pressure" を指定してください (`{other}` は指定できません) +@msg sizeMode is "fixed" or "pressure", not {other} sizeMode には "fixed" または "pressure" を指定してください ({other} は指定できません) +@msg sizeVariation must be 0 or more sizeVariation には 0 以上の値を指定してください +@msg smallCaps must be true or false smallCaps には true または false を指定してください +@msg sort `{x}`: name, kind or status sort `{x}`: name、kind、status のいずれかを指定してください +@msg source paths are too large for Shaper 元パスが Shaper には大きすぎます +@msg spot, mode and group apply to solid colours only spot、mode、group を適用できるのは単色だけです +@msg status `{s}`: linked, embedded, missing or modified status `{s}`: linked、embedded、missing、modified のいずれかを指定してください +@msg steps must be 1..1000 steps には 1..1000 の値を指定してください +@msg steps must be 1..{MAX_STEPS} steps には 1..{MAX_STEPS} の値を指定してください +@msg stop {i}: `plates` must be four numbers from 0 to 1 (C, M, Y, K) 分岐点 {i}: `plates` には 0 から 1 までの数値を 4 つ指定してください (C, M, Y, K) +@msg stopped before the archive was finished アーカイブが完成する前に停止しました +@msg strokeMode must be within|along|across, got {m} strokeMode には within|along|across のいずれかを指定してください (指定値: {m}) +@msg strokeOptions must be an object of stroke.set options strokeOptions には stroke.set のオプションのオブジェクトを指定してください +@msg strokeWidth must be a positive number of pixels strokeWidth には正のピクセル数を指定してください +@msg subpath {si} is not an open subpath サブパス {si} はオープンなサブパスではありません +@msg subpaths required when joining the same path 同じパスを連結する場合は subpaths が必要です +@msg swatchConflict must be "merge" or "add", not {v} swatchConflict には "merge" または "add" を指定してください ({v} は指定できません) +@msg text must be {characterSet?, platform?, removeLineReturns?, removeParagraphReturns?, replaceSpaces?} text には {characterSet?, platform?, removeLineReturns?, removeParagraphReturns?, replaceSpaces?} を指定してください +@msg text transform is collapsed or unrepresentable テキストの変形がつぶれているか、表現できません +@msg text.replaceSpaces must be a whole number from 2 to 100 text.replaceSpaces には 2 から 100 までの整数を指定してください +@msg text.{key} `{v}`: use "{_1}" or "{_2}" text.{key} `{v}`: "{_1}" または "{_2}" を使用してください +@msg textureImage: give {path} or {name, dataBase64} of an image file, or a texture as effect.list gives it textureImage: 画像ファイルの {path} または {name, dataBase64}、あるいは effect.list が返す形式のテクスチャを指定してください +@msg textureImage: {e} textureImage: {e} +@msg that makes more than {MAX_PIECES} slices スライスが {MAX_PIECES} 個を超えます +@msg that object is not in the overlap そのオブジェクトは重なりの中にありません +@msg the Affinity document has no page with a size Affinity ドキュメントにサイズのあるページがありません +@msg the CMYK image couldn't be written CMYK 画像を書き出せませんでした +@msg the PDF security settings were saved without their passwords: give openPassword or permissionsPassword again, or security without passwordRequired to export unprotected PDF のセキュリティ設定はパスワードなしで保存されています: openPassword または permissionsPassword をもう一度指定するか、保護なしで書き出すには passwordRequired のない security を指定してください +@msg the RTF file has too many paragraphs or formatting changes to place as type (at most {MAX_PARAGRAPHS} paragraphs and {MAX_RUNS} runs) RTF ファイルの段落または書式の変更が多すぎて、文字として配置できません (最大 {MAX_PARAGRAPHS} 段落、{MAX_RUNS} ラン) +@msg the RTF file is too large to place as type (at most {_1} MB) RTF ファイルが大きすぎて、文字として配置できません (最大 {_1} MB) +@msg the SVG expands to more than {0} nested SVG images SVG を展開すると、入れ子の SVG 画像が {0} 個を超えます +@msg the SVG expands to more than {0} objects SVG を展開すると、オブジェクトが {0} 個を超えます +@msg the SVG's style sheets take too long to match SVG のスタイルシートの照合に時間がかかりすぎます +@msg the SVG's styles expand to more than {0} MB SVG のスタイルを展開すると {0} MB を超えます +@msg the SVG has no drawable objects SVG に描画できるオブジェクトがありません +@msg the SVGZ file unpacks to more than {_1} MB SVGZ ファイルを展開すると {_1} MB を超えます +@msg the Word document has more than {MAX_PAGES} pages of properties, too many to place Word 文書のプロパティが {MAX_PAGES} ページを超えており、多すぎて配置できません +@msg the Word document has more than {MAX_RUNS} runs of character or paragraph properties, too many to place Word 文書の文字または段落プロパティのランが {MAX_RUNS} 個を超えており、多すぎて配置できません +@msg the Word document has more than {_1} MB of formatting properties, too many to place Word 文書の書式プロパティが {_1} MB を超えており、多すぎて配置できません +@msg the Word document has too much text or formatting to place as type (at most {MAX_PARAGRAPHS} paragraphs, {MAX_RUNS} runs and {_1} MB of text) Word 文書のテキストまたは書式が多すぎて、文字として配置できません (最大 {MAX_PARAGRAPHS} 段落、{MAX_RUNS} ラン、テキスト {_1} MB) +@msg the Word document has too much text to place as type (at most {_1} MB) Word 文書のテキストが多すぎて、文字として配置できません (最大 {_1} MB) +@msg the Word document is encrypted or protected with a password; save it without one to place it Word 文書が暗号化されているか、パスワードで保護されています。配置するには、パスワードなしで保存してください +@msg the Word document is too large to place (its {name} stream holds more than {_1} MB) Word 文書が大きすぎて配置できません ({name} ストリームが {_1} MB を超えています) +@msg the Word document was last saved with fast save, which VectorCraft doesn't read; save it again with fast save turned off Word 文書は高速保存で保存されていますが、VectorCraft はこの形式を読み込めません。高速保存をオフにして保存し直してください +@msg the Word document was saved by Word 6.0 or Word 95, which VectorCraft doesn't read; save it as a Word 97-2003 document Word 文書は Word 6.0 または Word 95 で保存されていますが、VectorCraft はこの形式を読み込めません。Word 97-2003 文書として保存してください +@msg the Word document's text is made of more than {MAX_PIECES} pieces, too many to place Word 文書のテキストが {MAX_PIECES} 個を超えるピースに分かれており、多すぎて配置できません +@msg the action set ids are not a list アクションセットの ID がリストではありません +@msg the active paint is not a gradient アクティブなペイントがグラデーションではありません +@msg the artboards don't fit on the canvas: fewer artboards, less spacing or a smaller size アートボードがキャンバスに収まりません: アートボードの数を減らすか、間隔またはサイズを小さくしてください +@msg the character's size can't be measured 文字のサイズを計測できません +@msg the compound shape is too complex to expand 複合シェイプが複雑すぎて拡張できません +@msg the container of the listed objects is gone 指定したオブジェクトを含むコンテナがなくなりました +@msg the copy `{user_id}` can't be read as a library コピー `{user_id}` をライブラリとして読み込めません +@msg the copy would leave the canvas コピーがキャンバスからはみ出します +@msg the cut cannot be made on this art: {e} このアートはカットできません: {e} +@msg the data isn't an EMF or WMF picture データが EMF または WMF の画像ではありません +@msg the data isn't an EPS or PostScript picture データが EPS または PostScript の画像ではありません +@msg the deferred paste is no longer available 遅延ペーストは使用できなくなりました +@msg the design is too big to draw at every data point of this graph デザインが大きすぎて、このグラフのすべてのデータポイントには描画できません +@msg the design is too big to draw in every column of this graph デザインが大きすぎて、このグラフのすべての棒には描画できません +@msg the dialog it was opened over is no longer open 元のダイアログはすでに閉じられています +@msg the dictionary stack overflowed 辞書スタックがオーバーフローしました +@msg the editing data's hash has no place 編集データのハッシュを書き込む場所がありません +@msg the entities the document declares expand to too much text ドキュメントで宣言されたエンティティを展開すると、テキストが多くなりすぎます +@msg the envelope's content has no bounds エンベロープの内容に境界がありません +@msg the envelope's mesh is malformed エンベロープのメッシュの形式が正しくありません +@msg the file holds no `variableSets` element ファイルに `variableSets` 要素がありません +@msg the file is larger than {_1} MB ファイルが {_1} MB を超えています +@msg the file is too large ファイルが大きすぎます +@msg the file was updated or encrypted already ファイルはすでに更新または暗号化されています +@msg the first character of a line has no character before it to kern: it moves only up and down (dy) 行の先頭の文字には、カーニングの対象となる前の文字がありません: 上下 (dy) にのみ移動します +@msg the font {_1} is not available フォント {_1} は使用できません +@msg the format has no file extension この形式にはファイル拡張子がありません +@msg the graphic can't be read: {e} グラフィックを読み込めません: {e} +@msg the graphic is empty グラフィックが空です +@msg the graphic's data is damaged グラフィックのデータが破損しています +@msg the graphic's document has no artboard グラフィックのドキュメントにアートボードがありません +@msg the header `{cell}` for `{name}` would read back as the variable `{other}`: rename one of them `{name}` のヘッダー `{cell}` は、読み戻すと変数 `{other}` として扱われます: どちらかの名前を変更してください +@msg the image `{path}` isn't followed: {r} 画像 `{path}` は参照しません: {r} +@msg the image has no embedded pixels 画像に埋め込みピクセルがありません +@msg the image is empty 画像が空です +@msg the image is fully transparent 画像が完全に透明です +@msg the image is not on an artboard; pass rect 画像がアートボード上にありません。rect を指定してください +@msg the image's pixels are missing 画像のピクセルがありません +@msg the image's pixels aren't in the document 画像のピクセルがドキュメント内にありません +@msg the image's pixels can't be read: {e} 画像のピクセルを読み込めません: {e} +@msg the image's transparency doesn't fit it 画像の透明情報が画像と合っていません +@msg the job would print more than {MAX_PAGES} pages このジョブでは {MAX_PAGES} ページを超えてプリントされます +@msg the job would print more than {_1} pages このジョブでは {_1} ページを超えてプリントされます +@msg the layers hold no art to mask レイヤーにマスクするアートがありません +@msg the layout moved レイアウトが移動しました +@msg the library has a group `{name}` already ライブラリにはすでにグループ `{name}` があります +@msg the library has no group `{name}` ライブラリにグループ `{name}` はありません +@msg the library has no item `{item}` ライブラリに項目 `{item}` はありません +@msg the library has no item `{other}` ライブラリに項目 `{other}` はありません +@msg the library holds {MAX_GROUPS} groups already ライブラリにはすでに {MAX_GROUPS} 個のグループがあります +@msg the library holds {MAX_ITEMS} items of this kind already ライブラリにはこの種類の項目がすでに {MAX_ITEMS} 個あります +@msg the name is empty 名前が空です +@msg the object has no fill, stroke or effect オブジェクトに塗り、線、効果のいずれもありません +@msg the object has no graphic style (pass `name`) オブジェクトにグラフィックスタイルがありません (`name` を指定してください) +@msg the objects don't match the plan オブジェクトが計画と一致しません +@msg the open and permissions passwords must differ 文書を開くパスワードと権限パスワードには異なるものを指定してください +@msg the operand stack overflowed オペランドスタックがオーバーフローしました +@msg the page has no area ページに面積がありません +@msg the page's type in an unread object's box isn't in its page art 未読み込みオブジェクトのボックス内にあるページの文字が、ページのアートにありません +@msg the paint behind the proxy is not a gradient プロキシのペイントがグラデーションではありません +@msg the parent must be a layer or sublayer 親にはレイヤーまたはサブレイヤーを指定してください +@msg the path can't be extended パスを延長できません +@msg the path can't be inside one of the objects to attach パスを、配置するオブジェクトの中に置くことはできません +@msg the path has no segments to measure パスに計測できるセグメントがありません +@msg the path is empty パスが空です +@msg the path is too short to shorten that much パスが短すぎて、その長さだけ短くできません +@msg the picture has no objects 画像にオブジェクトがありません +@msg the program runs too long プログラムの実行時間が長すぎます +@msg the program uses too much memory プログラムのメモリ使用量が多すぎます +@msg the rectangle must have a width and a height 長方形には幅と高さが必要です +@msg the rectangle needs a size and must lie on the canvas 長方形にはサイズが必要で、キャンバス上にある必要があります +@msg the selected art has no width 選択したアートに幅がありません +@msg the selection draws nothing 選択範囲は何も描画しません +@msg the selection has no area 選択範囲に面積がありません +@msg the selection has no art to export 選択範囲に書き出せるアートがありません +@msg the selection has no bounds 選択範囲に境界がありません +@msg the selection has no graphic style 選択範囲にグラフィックスタイルがありません +@msg the slice would leave the canvas スライスがキャンバスからはみ出します +@msg the spot colour couldn't be added 特色を追加できませんでした +@msg the subpath has no ends to extend (it is closed or a single point) サブパスに延長できる端点がありません (閉じているか、点が 1 つだけです) +@msg the symbols are nested too deeply to expand their instances シンボルの入れ子が深すぎて、インスタンスを拡張できません +@msg the text file is too large to place as type (at most {_1} MB) テキストファイルが大きすぎて、文字として配置できません (最大 {_1} MB) +@msg the text is empty テキストが空です +@msg the text is over {_1} MB テキストが {_1} MB を超えています +@msg the top object must be a path 最前面のオブジェクトはパスである必要があります +@msg the trace was cancelled トレースがキャンセルされました +@msg the trailer has no size トレーラーにサイズがありません +@msg the type object is flattened to nothing 文字オブジェクトを分割・統合すると何も残りません +@msg the value of axis `{tag}` must be a number or null 軸 `{tag}` の値には数値または null を指定してください +@msg the variable library declares more than {MAX_LIBRARY_DATASETS} data sets 変数ライブラリで宣言されているデータセットが {MAX_LIBRARY_DATASETS} 個を超えています +@msg the variable library declares more than {MAX_LIBRARY_ENTITIES} entities 変数ライブラリで宣言されているエンティティが {MAX_LIBRARY_ENTITIES} 個を超えています +@msg the variable library declares more than {MAX_LIBRARY_VARIABLES} variables 変数ライブラリで宣言されている変数が {MAX_LIBRARY_VARIABLES} 個を超えています +@msg the variable library declares no variables 変数ライブラリで変数が宣言されていません +@msg the variable library is larger than {MAX_LIBRARY_BYTES} bytes 変数ライブラリが {MAX_LIBRARY_BYTES} バイトを超えています +@msg the variable library is not UTF-8 変数ライブラリが UTF-8 ではありません +@msg the variable library is not well-formed XML: {e} 変数ライブラリが整形式の XML ではありません: {e} +@msg the variable library nests elements more than {MAX_LIBRARY_NESTING} deep 変数ライブラリの要素の入れ子が {MAX_LIBRARY_NESTING} 階層を超えています +@msg the variable library's document type declaration holds something other than entities of plain text 変数ライブラリの文書型宣言に、プレーンテキストのエンティティ以外のものが含まれています +@msg the variable library's entities expand to more than {MAX_LIBRARY_BYTES} bytes 変数ライブラリのエンティティを展開すると {MAX_LIBRARY_BYTES} バイトを超えます +@msg the window has no dock ウィンドウにドックがありません +@msg the written PDF has no catalog 書き出した PDF にカタログがありません +@msg the written PDF has no cross-reference table 書き出した PDF に相互参照テーブルがありません +@msg the written PDF's metadata can't be edited 書き出した PDF のメタデータを編集できません +@msg there are no colour swatches to draw 描画するカラースウォッチがありません +@msg there is already a design named `{name}` `{name}` という名前のデザインがすでにあります +@msg there is already a design named `{to}` `{to}` という名前のデザインがすでにあります +@msg there is already a toolbar named `{name}` `{name}` という名前のツールバーがすでにあります +@msg there is already a toolbar named `{to}` `{to}` という名前のツールバーがすでにあります +@msg there is no library: create one first ライブラリがありません: 先に作成してください +@msg these paths are too degenerate for Shaper これらのパスは縮退しているため、Shaper では使用できません +@msg thumbnail: no page {v} (the {what} has {count}) thumbnail: ページ {v} はありません ({what} のページ数は {count}) +@msg tileRange of {what}: {e} {what} の tileRange: {e} +@msg title can't be empty title を空にすることはできません +@msg to (the new name) is required to (新しい名前) は必須です +@msg to must be fill or stroke to には fill または stroke を指定してください +@msg to must be smooth or corner to には smooth または corner を指定してください +@msg too large for a zip archive: package to a folder zip アーカイブには大きすぎます: フォルダーにパッケージしてください +@msg too many Shaper edits Shaper の編集が多すぎます +@msg too many `points` (at most 100000) `points` が多すぎます (最大 100000) +@msg too many characters: at most {MAX_CHARS} 文字数が多すぎます: 最大 {MAX_CHARS} 文字 +@msg too many dots for this size: lower the frequency このサイズにはドットが多すぎます: 線数を下げてください +@msg too many filters over one file 1 つのファイルにかかるフィルターが多すぎます +@msg too many overlapping paths for Shaper 重なり合うパスが Shaper には多すぎます +@msg too many saved clips 保存されたクリップが多すぎます +@msg too many saved graphics states 保存されたグラフィックス状態が多すぎます +@msg toolbar (a toolbar's name) must be a string toolbar (ツールバー名) には文字列を指定してください +@msg toolbar name can't be empty ツールバー名を空にすることはできません +@msg transparentImages {v}: "flatten" (the default) or "omit" transparentImages {v}: "flatten" (初期設定) または "omit" を指定してください +@msg two saved selections would be named `{_1}` 保存した選択範囲のうち 2 つが `{_1}` という名前になります +@msg type dimension cannot be represented with this text transform このテキストの変形では文字の寸法を表現できません +@msg type dimension must be finite 文字の寸法には有限の値を指定してください +@msg unexpected resources 予期しないリソースがあります +@msg unknown CMYK profile `{name}` `{name}` は不明な CMYK プロファイルです +@msg unknown File Info field `{k}` `{k}` は不明なファイル情報フィールドです +@msg unknown OpenType feature `{t}` in featureChanges (the tags `features` takes) featureChanges 内の `{t}` は不明な OpenType 機能です (`features` で使用できるタグを指定してください) +@msg unknown PDF preset `{name}` (presets: {_1}) `{name}` は不明な PDF プリセットです (プリセット: {_1}) +@msg unknown Warp style 不明なワープスタイルです +@msg unknown alignToPath `{a}` `{a}` は不明な alignToPath の指定です +@msg unknown arrowhead {v} {v} は不明な矢印です +@msg unknown artboardLayout key `{k}` (layout, columns, spacing, rightToLeft) `{k}` は不明な artboardLayout のキーです (layout、columns、spacing、rightToLeft のいずれか) +@msg unknown attribute `{attribute}` `{attribute}` は不明な属性です +@msg unknown attribute `{k}` `{k}` は不明な属性です +@msg unknown axis `{other}` (vertical|horizontal|free) `{other}` は不明な軸の指定です (vertical|horizontal|free) +@msg unknown blend mode `{b}` `{b}` は不明な描画モードです +@msg unknown blend mode {b} {b} は不明な描画モードです +@msg unknown brush type `{o}` `{o}` は不明なブラシの種類です +@msg unknown category `{c}` `{c}` は不明なカテゴリです +@msg unknown category `{c}` ({_1}) `{c}` は不明なカテゴリです ({_1}) +@msg unknown character `{c}` `{c}` は不明な文字です +@msg unknown character style number field 文字スタイルの数値フィールドが不明です +@msg unknown effect `{e}` `{e}` は不明な効果です +@msg unknown end {e} {e} は不明な end の指定です +@msg unknown flattenerPreset `{name}` (High Resolution, Medium Resolution, Low Resolution or a saved one: see flattener.presets.list) `{name}` は不明な flattenerPreset です (High Resolution、Medium Resolution、Low Resolution、または保存済みのプリセット: flattener.presets.list を参照) +@msg unknown format `{f}` (vcswatches, gpl, ase or css) `{f}` は不明な形式です (vcswatches、gpl、ase、css のいずれか) +@msg unknown from {f} {f} は不明な from の指定です +@msg unknown graph type `{t}` `{t}` は不明なグラフの種類です +@msg unknown grid colours `{name}` (one of {_1}) `{name}` は不明なグリッドカラーです ({_1} のいずれか) +@msg unknown gridType `{t}` `{t}` は不明な gridType です +@msg unknown highlight `{v}` `{v}` は不明なハイライトの指定です +@msg unknown intent `{i}` `{i}` は不明なインテントです +@msg unknown issue kind {id} {id} は不明な問題の種類です +@msg unknown issue kind {v} {v} は不明な問題の種類です +@msg unknown knockout state {k} {k} は不明な抜きの状態です +@msg unknown language `{language}` (one of {_1}) `{language}` は不明な言語です ({_1} のいずれか) +@msg unknown language `{l}` (one of {_1}) `{l}` は不明な言語です ({_1} のいずれか) +@msg unknown method `{m}` ({_1}) `{m}` は不明な方法です ({_1}) +@msg unknown mode `{other}` (gray, rgb, hsb, lab, cmyk or web) `{other}` は不明なモードです (gray、rgb、hsb、lab、cmyk、web のいずれか) +@msg unknown mode `{other}` (mono|cmyk) `{other}` は不明なモードです (mono|cmyk) +@msg unknown mode `{other}` (rgb|cmyk|gray|global) `{other}` は不明なモードです (rgb|cmyk|gray|global) +@msg unknown mode `{other}` (set, add, subtract) `{other}` は不明なモードです (set、add、subtract のいずれか) +@msg unknown mode `{o}` `{o}` は不明なモードです +@msg unknown mode {m} {m} は不明なモードです +@msg unknown model `{other}` `{other}` は不明な model です +@msg unknown model `{other}` (keep, new or document) `{other}` は不明な model です (keep、new、document のいずれか) +@msg unknown op {o} {o} は不明な op です +@msg unknown order `{o}`: toggle, front, forward, backward or back `{o}` は不明な order です: toggle、front、forward、backward、back のいずれかを指定してください +@msg unknown overprints `{v}` (preserve, simulate or discard) `{v}` は不明な overprints の指定です (preserve、simulate、discard のいずれか) +@msg unknown panel 不明なパネルです +@msg unknown pieLegend `{v}` (none, standard or wedges) `{v}` は不明な pieLegend の指定です (none、standard、wedges のいずれか) +@msg unknown piePosition `{v}` (even, ratio or stacked) `{v}` は不明な piePosition の指定です (even、ratio、stacked のいずれか) +@msg unknown pieSort `{v}` (none, all or first) `{v}` は不明な pieSort の指定です (none、all、first のいずれか) +@msg unknown plate `{n}` `{n}` は不明な版です +@msg unknown preference `{k}` `{k}` は不明な環境設定です +@msg unknown profile {id} (see stroke.widthProfile.list) {id} は不明なプロファイルです (stroke.widthProfile.list を参照) +@msg unknown proof target `{t}` `{t}` は不明な校正ターゲットです +@msg unknown quotes key `{k}` (double, single) `{k}` は不明な quotes のキーです (double、single のいずれか) +@msg unknown resolution `{v}` `{v}` は不明な解像度です +@msg unknown rule `{rule}` ({_1}) `{rule}` は不明なルールです ({_1}) +@msg unknown rule `{r}` (see color.harmony) `{r}` は不明なルールです (color.harmony を参照) +@msg unknown setting `{k}` `{k}` は不明な設定です +@msg unknown shape `{v}` (circle|ellipse|square|diamond|line) `{v}` は不明なシェイプです (circle|ellipse|square|diamond|line) +@msg unknown spacing `{o}` (smooth|steps|distance) `{o}` は不明な間隔の指定です (smooth|steps|distance) +@msg unknown tileType `{t}` ({_1}) `{t}` は不明な tileType です ({_1}) +@msg unknown units 不明な単位です +@msg unknown units `{u}` `{u}` は不明な単位です +@msg unknown value axis `{v}` (left, right or both) `{v}` は不明な数値軸の指定です (left、right、both のいずれか) +@msg unknown variation `{v}` (tintsShades|warmCool|vividMuted) `{v}` は不明なバリエーションです (tintsShades|warmCool|vividMuted) +@msg unknown warp style `{s}` `{s}` は不明なワープスタイルです +@msg unknown {key} `{v}` (none, short or full) `{v}` は不明な {key} の指定です (none、short、full のいずれか) +@msg unknown {key} profile `{n}` `{n}` は不明な {key} プロファイルです +@msg unknown {k} key `{key}` (size, position) `{key}` は不明な {k} のキーです (size、position のいずれか) +@msg unreadable object 読み込めないオブジェクトです +@msg unsafe destination file name 出力先のファイル名が安全ではありません +@msg use paths or compound paths パスまたは複合パスを使用してください +@msg useArtboards must be true or false, not {v} useArtboards には true または false を指定してください ({v} は指定できません) +@msg value for `{var}` must match its variable kind `{var}` の値は変数の種類に合わせてください +@msg variable `{_1}` is already defined 変数 `{_1}` はすでに定義されています +@msg variable `{name}` has no `trait` 変数 `{name}` に `trait` がありません +@msg variable `{name}` is already defined 変数 `{name}` はすでに定義されています +@msg variable `{name}` is declared twice 変数 `{name}` が 2 回宣言されています +@msg variable `{to}` already exists 変数 `{to}` はすでにあります +@msg view is required view は必須です +@msg view must be one of {_1} view には {_1} のいずれかを指定してください +@msg warpStyle can only edit an applied Warp effect warpStyle で編集できるのは、適用済みのワープ効果だけです +@msg width and height must be more than 0 and at most {limit} width と height には 0 より大きく {limit} 以下の値を指定してください +@msg width factors must be finite 幅の係数には有限の値を指定してください +@msg width must be positive width には正の値を指定してください +@msg width out of range 幅が範囲外です +@msg width/height must be > 0 width/height には 0 より大きい値を指定してください +@msg x and y must be finite numbers x と y には有限の数値を指定してください +@msg x and y must be given together x と y は一緒に指定してください +@msg zone needs an anchor: dock beside a panel with anchor, or in a new dock column with side (Start or End) zone には anchor が必要です: anchor でパネルの横にドッキングするか、side (Start または End) で新しいドック列にドッキングしてください +@msg zoom must be positive zoom には正の値を指定してください +@msg {C}: no effect at index {list} {C}: インデックス {list} に効果はありません +@msg {DEFAULT_PRESET} is protected and stays {DEFAULT_PRESET} は保護されているため、削除されません +@msg {DEFAULT_PRESET} is protected: save the settings under another name {DEFAULT_PRESET} は保護されています: 設定を別の名前で保存してください +@msg {LABEL} produced an empty result {LABEL} の結果が空になりました +@msg {_1} MB of document, at most {_2} MB ドキュメントが {_1} MB あります (上限は {_2} MB) +@msg {_1} MB of images, at most {_2} MB 画像が {_1} MB あります (上限は {_2} MB) +@msg {_1} bytes of RGBA data for a {width} × {height} image {width} × {height} の画像に対して RGBA データが {_1} バイトあります +@msg {_1} can't be read, or changed since it was read: relink or update it first {_1} を読み込めないか、読み込み後に変更されています: 先に再リンクまたは更新してください +@msg {_1} can't go into {into} {_1} を {into} に入れることはできません +@msg {_1} can't limit printing to low resolution: choose PDF 1.4 or later, or allow high-resolution printing {_1} ではプリントを低解像度に制限できません: PDF 1.4 以降を選択するか、高解像度プリントを許可してください +@msg {_1} files can't be opened yet {_1} ファイルはまだ開けません +@msg {_1} files can't be password-protected: remove the passwords or choose no standard {_1} ファイルはパスワードで保護できません: パスワードを削除するか、規格なしを選択してください +@msg {_1} files can't be {_2} {_1} ファイルは {_2} にできません +@msg {_1} files can't carry editing data: turn off preserveEditing {_1} ファイルには編集データを含められません: preserveEditing をオフにしてください +@msg {_1} files can't have PDF layers: turn off createLayers {_1} ファイルには PDF レイヤーを含められません: createLayers をオフにしてください +@msg {_1} files need a creation date, and this platform has no clock to give one {_1} ファイルには作成日が必要ですが、このプラットフォームには日時を取得できる時計がありません +@msg {_1} isn't a path {_1} はパスではありません +@msg {_1} options: {e} {_1} オプション: {e} +@msg {_1} paints nothing to rasterize {_1} にはラスタライズできる描画内容がありません +@msg {_1} passwords can have up to {MAX_LEGACY_PASSWORD} ASCII characters (PDF 1.7 and later take any) {_1} のパスワードは ASCII 文字で {MAX_LEGACY_PASSWORD} 文字以内です (PDF 1.7 以降では任意の文字を使用できます) +@msg {_1} with linked images or an image map writes several files: use document.export リンク画像またはイメージマップのある {_1} は複数のファイルを書き出します: document.export を使用してください +@msg {_1} writes one file per artboard here: use document.export, or name one artboard ここでは {_1} はアートボードごとに 1 つのファイルを書き出します: document.export を使用するか、アートボードを 1 つ指定してください +@msg {_1} × {_2} pixels is too large for {_3} (at most {max} pixels a side): lower the scale {_1} × {_2} ピクセルは {_3} には大きすぎます (1 辺あたり最大 {max} ピクセル): 拡大・縮小率を下げてください +@msg {_1}: belongs to another account {_1}: 別のアカウントのものです +@msg {_1}: not a folder of its own {_1}: 専用のフォルダーではありません +@msg {_1}: not a plain file {_1}: 通常のファイルではありません +@msg {dest}: {e} {dest}: {e} +@msg {doc} has no folder {doc} にフォルダーがありません +@msg {file} isn't linked {file} はリンクされていません +@msg {folder} is not a package folder {folder} はパッケージフォルダーではありません +@msg {folder}: more than {max} files and folders {folder}: ファイルとフォルダーが {max} 個を超えています +@msg {folder}: {e} {folder}: {e} +@msg {g} is not a Live Paint group {g} はライブペイントグループではありません +@msg {id} is not a slice {id} はスライスではありません +@msg {key} must be 0–{MAX_ADD_AROUND} pt {key} には 0–{MAX_ADD_AROUND} pt を指定してください +@msg {key} must be [x,y] {key} には [x,y] を指定してください +@msg {key} must be a percentage {min}..100 {key} には {min}..100 のパーセント値を指定してください +@msg {key} must be a positive number, not {n} {key} には正の数値を指定してください ({n} は指定できません) +@msg {key} must be a positive number, not {v} {key} には正の数値を指定してください ({v} は指定できません) +@msg {key} must be one of {_1} {key} には {_1} のいずれかを指定してください +@msg {key} must be {_1}, got {s} {key} には {_1} を指定してください (指定値: {s}) +@msg {key} must name a floating panel {key} にはフローティングパネルを指定してください +@msg {key} must name a panel in another group {key} には別のグループにあるパネルを指定してください +@msg {key} must name a panel that shows {key} には表示されているパネルを指定してください +@msg {key} must name a registered panel {key} には登録済みのパネルを指定してください +@msg {kind} files have no transparency, and the file would have {what}: flatten it first (object.flattenTransparency) {kind} ファイルは透明に対応していませんが、ファイルに {what} が含まれます: 先に分割・統合してください (object.flattenTransparency) +@msg {kind} images can't be opened (see document.formats) {kind} 画像は開けません (document.formats を参照) +@msg {k} `{v}` is not one of the choices {k} `{v}` は選択肢にありません +@msg {k} has control characters{_1} {k} に制御文字{_1} が含まれています +@msg {k} is too long (at most {MAX_TEXT} characters) {k} が長すぎます (最大 {MAX_TEXT} 文字) +@msg {k} must be > 0 {k} には 0 より大きい値を指定してください +@msg {k} must be a number (pt) or a length such as "210 mm" {k} には数値 (pt)、または "210 mm" のような長さを指定してください +@msg {k} must be a number from {min} to {max} {k} には {min} から {max} までの数値を指定してください +@msg {k} must be a number or "auto" {k} には数値または "auto" を指定してください +@msg {k} must be a string {k} には文字列を指定してください +@msg {k} must be text {k} にはテキストを指定してください +@msg {k} must be true or false {k} には true または false を指定してください +@msg {k} must be {{size?, position?}} {k} には {{size?, position?}} を指定してください +@msg {k}: can't read `{s}` as a length {k}: `{s}` を長さとして読み取れません +@msg {label} must be a number at most {max} {label} には {max} 以下の数値を指定してください +@msg {label} must be a number from -1296 to 1296 {label} には -1296 から 1296 までの数値を指定してください +@msg {label} must be a number from 1 to 10000 {label} には 1 から 10000 までの数値を指定してください +@msg {name} `{s}`: {ids} {name} `{s}`: {ids} +@msg {name} is built in and can't be deleted {name} は組み込みのため、削除できません +@msg {name} must be {lo}–{hi}{unit} (got {v}) {name} には {lo}–{hi}{unit} を指定してください (指定値: {v}) +@msg {name}: CRC or size mismatch {name}: CRC またはサイズが一致しません +@msg {name}: only this Affinity file's embedded preview could be read; use File › Open to see it with its warning, or export SVG or PDF from Affinity before placing {name}: この Affinity ファイルは埋め込みプレビューしか読み込めませんでした。「ファイル › 開く」で警告とともに表示するか、配置する前に Affinity から SVG または PDF を書き出してください +@msg {name}: {e} {name}: {e} +@msg {native}; its embedded preview can't be read either ({e}) {native}。埋め込みプレビューも読み込めません ({e}) +@msg {std} files are CMYK, and the file would have colours in {_1} {std} ファイルは CMYK ですが、ファイルに {_1} のカラーが含まれます +@msg {std} files embed their fonts, and the file would have one that isn't {std} ファイルにはフォントを埋め込みますが、ファイルに埋め込まれないフォントが含まれます +@msg {target} is the file this document was read from, and reading it left things out ({what}): writing over it would lose them for good. Write another file instead, or pass acknowledgeLoss: true to replace it anyway {target} はこのドキュメントの読み込み元のファイルで、読み込み時に除外された内容があります ({what}): 上書きすると、それらは完全に失われます。別のファイルに書き出すか、それでも置き換える場合は acknowledgeLoss: true を指定してください +@msg {ty} brushes need selected art (or params.{k}) {ty} ブラシには選択したアート (または params.{k}) が必要です +@msg {v} is not an asset id {v} はアセット ID ではありません +@msg {what} can't be intertwined {what} は織り交ぜられません +@msg {what} doesn't fit the paper with its bleed and marks {what} は、裁ち落としとトンボを含めると用紙に収まりません +@msg {what} would print on more than {MAX_TILES} tiles: scale it down {what} は {MAX_TILES} 枚を超えるタイルにプリントされます: 縮小してください Playback Options 再生オプション Accelerated 高速 Step by Step ステップ実行 @@ -6366,7 +8193,7 @@ axis Y Axis Y 軸 @plural Result: {n}|Results: {n} 結果: {n} @msg select one object オブジェクトを 1 つ選択してください @msg Global Edit works on paths, compound paths, symbol instances and groups of them グローバル編集はパス、複合パス、シンボルインスタンスとそれらのグループに使用できます -@msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again 類似するオブジェクトが見つかりません(回転または反転したコピーは一致しません)。グローバル編集オプションを変更してもう一度試してください +@msg no similar objects found (reflected copies are not matched); change the Global Edit Options and try again 類似するオブジェクトが見つかりません(反転したコピーは一致しません)。グローバル編集オプションを変更してもう一度試してください @msg Global Edit is off グローバル編集はオフです @msg only an object of the Global Edit other than the one it started from can be left out 除外できるのは、グローバル編集を開始したオブジェクト以外のオブジェクトだけです @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all または 1, 3-5 のような範囲を指定してください ({v} ではなく) @@ -7163,11 +8990,20 @@ breakText Glyphs 字形 Open Tutorial Sample チュートリアルのサンプルを開く Finish Tutorial チュートリアルを完了 Next Tutorial 次のチュートリアル + Show Learn Tab 学ぶのタブを表示 + Show Skill スキルを表示 + Back One Level 1 つ上の階層に戻る Back to Skills スキルに戻る @msg tutorial `{id}` has no practice sample チュートリアル `{id}` には練習用サンプルがありません @msg open the practice sample of `{id}` first (see learn.openSample) 先に `{id}` の練習用サンプルを開いてください (learn.openSample を参照) @msg finish `{id}` first (see learn.finish) 先に `{id}` を完了してください (learn.finish を参照) @msg `{id}` is the last tutorial in its skill `{id}` はこのスキルの最後のチュートリアルです + Reset progress 進行状況をリセット + Mark Tutorial Step チュートリアルの手順をマーク + Reset Learn Progress 学習の進行状況をリセット +@msg missing `step` (see learn.show) `step` が指定されていません (learn.show を参照) +@msg `step` must be a step number from 0 to {last} `step` は 0 から {last} までの手順番号にしてください +@msg `{id}` is finished (see learn.resetProgress) `{id}` は完了しています (learn.resetProgress を参照) # Deferred plug-in effects Refresh Deferred Effects 保留中の効果を更新 @@ -7197,3 +9033,134 @@ breakText Glyphs 字形 Grommets ハトメ Grommet Inset 端からハトメまでの距離 Diameter 直径 + Nest Shapes… 図形のネスティング… + Nest Shapes 図形のネスティング + Roll ロール + +# Messages no catalog translated yet: image export and color profiles, color books and swatch exchange files, 3D and Revolve, and script, zip, line and file errors. +@msg 3D effects require finite coordinates within 100 million points 3D 効果には 1 億ポイント以内の有限の座標が必要です +@msg 3D effects require one to ten lights 3D 効果にはライトが 1~10 個必要です +@msg BMP depth {_1}: 1, 4, 8, 16, 24 or 32 bits per pixel BMP の色深度 {_1}: 1、4、8、16、24、32 ビット/ピクセルのいずれかにしてください +@msg BMP encoding failed: {width} × {height} pixels doesn't fit the format or the pixel buffer BMP のエンコードに失敗しました: {width} × {height} ピクセルは形式またはピクセルバッファーに収まりません +@msg GIF encoding failed: the palette image is malformed GIF のエンコードに失敗しました: パレット画像の形式が正しくありません +@msg GIF encoding failed: {e} GIF のエンコードに失敗しました: {e} +@msg JPEG colour profile: {e} JPEG のカラープロファイル: {e} +@msg JPEG encoding failed: pixel buffer doesn't match the image size JPEG のエンコードに失敗しました: ピクセルバッファーが画像サイズと一致しません +@msg JPEG encoding failed: {e} JPEG のエンコードに失敗しました: {e} +@msg PNG encoding failed: pixel buffer doesn't match the image size PNG のエンコードに失敗しました: ピクセルバッファーが画像サイズと一致しません +@msg PNG encoding failed: the palette image is malformed PNG のエンコードに失敗しました: パレット画像の形式が正しくありません +@msg PNG encoding failed: {e} PNG のエンコードに失敗しました: {e} +@msg PNG encoding failed: {width} × {height} pixels is not a valid image size PNG のエンコードに失敗しました: {width} × {height} ピクセルは有効な画像サイズではありません +@msg PSD colour profile: {e} PSD のカラープロファイル: {e} +@msg PSD encoding failed: the pixel buffer doesn't match the image size PSD のエンコードに失敗しました: ピクセルバッファーが画像サイズと一致しません +@msg Revolve profile contains invalid coordinates 回転体のプロファイルに無効な座標が含まれています +@msg Revolve profile is too complex 回転体のプロファイルが複雑すぎます +@msg Revolve projection is not finite 回転体の投影が有限ではありません +@msg Revolve requires finite profile coordinates within 100 million points 回転体には 1 億ポイント以内の有限のプロファイル座標が必要です +@msg Revolve surface is too complex; reduce Segments or simplify the profile 回転体のサーフェスが複雑すぎます。分割数を減らすか、プロファイルを単純化してください +@msg Revolve surface is too complex; simplify the profile 回転体のサーフェスが複雑すぎます。プロファイルを単純化してください +@msg Revolve visibility cannot split the projected boundary 回転体の可視判定で投影された境界線を分割できません +@msg Revolve visibility creates too many fragments 回転体の可視判定で生成される断片が多すぎます +@msg Revolve visibility creates too many vector anchors 回転体の可視判定で生成されるベクトルのアンカーポイントが多すぎます +@msg Revolve visibility exceeds its geometry work limit 回転体の可視判定がジオメトリ計算の上限を超えています +@msg Revolve visibility exceeds its spatial index limit 回転体の可視判定が空間インデックスの上限を超えています +@msg Revolve visibility has too many boundary crossings 回転体の可視判定で境界線の交差が多すぎます +@msg Revolve visibility has too many input anchors 回転体の可視判定に入力されるアンカーポイントが多すぎます +@msg Revolve visibility requires convex cap sectors 回転体の可視判定には凸状のキャップのセクターが必要です +@msg Revolve visibility requires finite projected faces 回転体の可視判定には有限の投影面が必要です +@msg SVG options: {e} SVG オプション: {e} +@msg Save for Web settings: {e} Web 用に保存の設定: {e} +@msg TIFF colour profile: {e} TIFF のカラープロファイル: {e} +@msg TIFF encoding failed: the pixel buffer doesn't match the image size TIFF のエンコードに失敗しました: ピクセルバッファーが画像サイズと一致しません +@msg TIFF encoding failed: {e} TIFF のエンコードに失敗しました: {e} +@msg Targa depth {_1}: 16, 24 or 32 bits per pixel Targa の色深度 {_1}: 16、24、32 ビット/ピクセルのいずれかにしてください +@msg Targa encoding failed: the pixel buffer doesn't match the image size Targa のエンコードに失敗しました: ピクセルバッファーが画像サイズと一致しません +@msg The 3D projection is not finite 3D の投影が有限ではありません +@msg The 3D shadow is too complex; turn Shadows off or simplify the art 3D のシャドウが複雑すぎます。シャドウをオフにするか、アートを単純化してください +@msg The shape contains invalid coordinates シェイプに無効な座標が含まれています +@msg Too many Revolve faces for visibility evaluation 可視判定を行うには回転体の面が多すぎます +@msg VectorCraft reads at most {ASE_MAX_ENTRIES} colors and groups from a swatch exchange file, and this library has {entries} VectorCraft がスウォッチ交換ファイルから読み込めるカラーとグループは {ASE_MAX_ENTRIES} 個までですが、このライブラリには {entries} 個あります +@msg WebP encoding failed: {e} WebP のエンコードに失敗しました: {e} +@msg [{j}] `{_1}`: {why} [{j}] `{_1}`: {why} +@msg `answers[{i}]` {e} `answers[{i}]` {e} +@msg `view` is smallThumb, mediumThumb, largeThumb, smallList or largeList `view` には smallThumb、mediumThumb、largeThumb、smallList、largeList のいずれかを指定してください +@msg a line can't run from a point to itself ラインの始点と終点に同じポイントは指定できません +@msg a line needs at least two points ラインには少なくとも 2 つのポイントが必要です +@msg a number cannot be read 数値を読み取れません +@msg a swatch exchange block is too long スウォッチ交換ファイルのブロックが長すぎます +@msg a swatch exchange name is too long スウォッチ交換ファイルの名前が長すぎます +@msg a {sw} × {sh} image can't be resized to {width} × {height} pixels {sw} × {sh} の画像を {width} × {height} ピクセルにサイズ変更できません +@msg a {width} × {height} image is too large {width} × {height} の画像は大きすぎます +@msg a {width} × {height} image: {e} {width} × {height} の画像: {e} +@msg an image could not be written: {e} 画像を書き出せませんでした: {e} +@msg an image that couldn't be read was left out 読み込めなかった画像は除外されました +@msg can't open “{name}”: {e} 「{name}」を開けません: {e} +@msg cannot align zip entries to {align} bytes ZIP のエントリを {align} バイト境界に揃えられません +@msg cannot open the automation {kind} root `{_1}`: {e} 自動化の {kind} ルート `{_1}` を開けません: {e} +@msg cannot read profile: {0} プロファイルを読み込めません: {0} +@msg color book version {version} isn't supported (only 1) カラーブックのバージョン {version} には対応していません (対応しているのは 1 のみ) +@msg color books in color space {other} aren't supported (only RGB, CMYK and Lab) 色空間 {other} のカラーブックには対応していません (対応しているのは RGB、CMYK、Lab のみ) +@msg file name too long to zip: {_1} ファイル名が長すぎて ZIP に格納できません: {_1} +@msg file name too long to zip: {name} ファイル名が長すぎて ZIP に格納できません: {name} +@msg freeform line {i}: {e} フリーフォームのライン {i}: {e} +@msg freeform point {i}: {e} フリーフォームのポイント {i}: {e} +@msg give `{key}` or `{other}`, not both `{key}` と `{other}` のどちらか一方を指定してください (両方は指定できません) +@msg grayscale profiles can't be working spaces yet グレースケールのプロファイルはまだ作業用スペースにできません +@msg input contains NaN or infinite coordinates 入力に NaN または無限大の座標が含まれています +@msg input path could not be closed 入力パスを閉じられませんでした +@msg invalid ICC profile: {0} 無効な ICC プロファイル: {0} +@msg invalid scale {scale} 倍率 {scale} は無効です +@msg its localized names take more than {_1} KB ローカライズされた名前が {_1} KB を超えています +@msg its objects are nested too deep ({e}) オブジェクトの入れ子が深すぎます ({e}) +@msg its tag table lists the `{_1}` tag more than once タグテーブルに `{_1}` タグが複数回記載されています +@msg not a graphic style library: {e} グラフィックスタイルライブラリではありません: {e} +@msg not a swatch library (.vcswatches or .gpl) スウォッチライブラリではありません (.vcswatches または .gpl) +@msg not a swatch library (format `{_1}`) スウォッチライブラリではありません (形式: `{_1}`) +@msg not a swatch library: {e} スウォッチライブラリではありません: {e} +@msg not an action set file ({e}) アクションセットファイルではありません ({e}) +@msg profile colour space {other} is not RGB, CMYK or Gray プロファイルの色空間 {other} は RGB、CMYK、グレースケールのいずれでもありません +@msg regular expression too large 正規表現が大きすぎます +@msg script file is not UTF-8 text: {value} スクリプトファイルは UTF-8 テキストではありません: {value} +@msg stop {i}: {e} 分岐点 {i}: {e} +@msg swatch exchange version {major}.{minor} isn't supported (only 1.x) スウォッチ交換ファイルのバージョン {major}.{minor} には対応していません (対応しているのは 1.x のみ) +@msg the color book holds more than {ASE_MAX_ENTRIES} colors カラーブックのカラーが {ASE_MAX_ENTRIES} 色を超えています +@msg the color book is cut short カラーブックが途中で切れています +@msg the color book's names take more than {_1} MB カラーブックの名前が {_1} MB を超えています +@msg the image would be {w} × {h} pixels; raster exports are limited to {MAX_RASTER_SIDE} pixels per side and {_1} megapixels: lower the scale or resolution 画像が {w} × {h} ピクセルになります。ラスター書き出しの上限は 1 辺 {MAX_RASTER_SIDE} ピクセル、{_1} メガピクセルです: 倍率または解像度を下げてください +@msg the optimised image can't be read back: {e} 最適化した画像を読み戻せません: {e} +@msg the pixel buffer doesn't match the image size ピクセルバッファーが画像サイズと一致しません +@msg the preview: {e} プレビュー: {e} +@msg the request may not read the New Document profiles folder このリクエストには新規ドキュメントプロファイルのフォルダーを読み込む権限がありません +@msg the shapes are too degenerate to combine シェイプの形状がつぶれすぎていて結合できません +@msg the shapes cross themselves and each other too often to combine シェイプ自身やシェイプ同士の交差が多すぎて結合できません +@msg the swatch exchange file holds more than {ASE_MAX_ENTRIES} colors and groups スウォッチ交換ファイルのカラーとグループが {ASE_MAX_ENTRIES} 個を超えています +@msg the swatch exchange file is cut short スウォッチ交換ファイルが途中で切れています +@msg the {_1} plate can't be read: {e} {_1} 版を読み込めません: {e} +@msg this binary DXF file is damaged or cut short このバイナリ DXF ファイルは壊れているか途中で切れています +@msg this is a DWG drawing, which can't be read: save it from the CAD app as a DXF and open that DWG 図面は読み込めません: CAD アプリで DXF として保存し、そのファイルを開いてください +@msg too many classes 文字クラスが多すぎます +@msg too many groups グループが多すぎます +@msg too many layers for PSD (at most 32767) PSD にはレイヤーが多すぎます (最大 32767) +@msg too many swatch exchange blocks スウォッチ交換ファイルのブロックが多すぎます +@msg unknown colour profile: {0} 不明なカラープロファイル: {0} +@msg {_1} clashes with a built-in profile name {_1} は組み込みのプロファイル名と重複しています +@msg {_1} × {_2} pixels is too large for GIF (at most 65535 pixels a side): lower the resolution {_1} × {_2} ピクセルは GIF には大きすぎます (1 辺最大 65535 ピクセル): 解像度を下げてください +@msg {_1}: no usable transform to/from sRGB {_1}: sRGB との間で使用できる変換がありません +@msg {name} is not a CMYK profile {name} は CMYK プロファイルではありません +@msg {name} is not an RGB profile {name} は RGB プロファイルではありません +@msg {path}: could not be read {path}: 読み込めませんでした +@msg {width} × {height} pixels is too large for JPEG (at most 65535 pixels a side): lower the resolution {width} × {height} ピクセルは JPEG には大きすぎます (1 辺最大 65535 ピクセル): 解像度を下げてください +@msg {width} × {height} pixels is too large for Targa (at most 65535 pixels a side): lower the resolution {width} × {height} ピクセルは Targa には大きすぎます (1 辺最大 65535 ピクセル): 解像度を下げてください +@msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} ピクセルは PSD には大きすぎます (1 辺最大 {MAX_SIDE} ピクセル): 解像度を下げてください + +# Messages other catalogs translate and Japanese did not: Banner Hems and Grommets, a parameter range and the recovery save. +@msg `{key}` must be from 0.01 to 1000 pt `{key}` は 0.01~1000 pt にしてください +@msg select the banner, or mark every artboard バナーを選択するか、すべてのアートボードにマークを付けてください +@msg the banner has no width or height バナーに幅または高さがありません +@msg the grommet inset is too large for the banner 端からハトメまでの距離がバナーに対して大きすぎます +@msg the hem is too deep for the banner 折り返しがバナーに対して深すぎます +@msg the spacing makes more than {MAX_GROMMETS} grommets この間隔ではハトメが {MAX_GROMMETS} 個を超えます +@msg there is no banner to mark マークを付けるバナーがありません +@msg turn on at least one side 少なくとも 1 つの辺をオンにしてください +@msg with no hem and no grommets there is nothing to mark 折り返しもハトメもないため、マークを付けるものがありません +@msg {saving} failed: {e} {saving} に失敗しました: {e} diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index f2d20fc031..007237997b 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -354,6 +354,18 @@ Title Case სათაურის რეგისტრი Sentence case წინადადების რეგისტრი Smart Punctuation… ჭკვიანი პუნქტუაცია… + Smart Punctuation ჭკვიანი პუნქტუაცია + ff, fi, ffi Ligatures ლიგატურები ff, fi, ffi + ff, fl, ffl Ligatures ლიგატურები ff, fl, ffl + Smart Quotes ჭკვიანი ბრჭყალები + Smart Spaces ჭკვიანი ჰარები + En, Em Dashes მოკლე და გრძელი ტირეები + Ellipses მრავალწერტილები + Expert Fractions ექსპერტული წილადები + Replace In ჩანაცვლების არე + Selected Text Only მხოლოდ მონიშნული ტექსტი + Entire Document მთელი დოკუმენტი + Report Results შედეგების ანგარიში Create Outlines კონტურებად გარდაქმნა Optical Margin Alignment ოპტიკური არშიის სწორება Dynamic Text დინამიკური ტექსტი @@ -867,6 +879,7 @@ Free Transform თავისუფალი გარდაქმნა Perspective Distort პერსპექტიული დეფორმაცია Radial Blur… რადიალური გაბუნდოვნება… + Blur Center გაბუნდოვნების ცენტრი Smart Blur… ჭკვიანი გაბუნდოვნება… Sharpen გამკვეთრება Unsharp Mask… არამკვეთრი ნიღაბი… @@ -1574,6 +1587,9 @@ digits Malayalam მალაიალამური The selected character's font is not available. მონიშნული სიმბოლოს შრიფტი მიუწვდომელია. No alternates for the selected character. მონიშნულ სიმბოლოს ალტერნატივები არ აქვს. Double-click to replace ორჯერ დაწკაპეთ ჩასანაცვლებლად + Click to replace დაწკაპეთ ჩასანაცვლებლად + Show all alternates in the Glyphs panel ყველა ალტერნატივის ჩვენება გლიფების პანელში + Show Character Alternates სიმბოლოს ალტერნატივების ჩვენება Select one character with the Type tool first. ჯერ ტექსტის ხელსაწყოთი მონიშნეთ ერთი სიმბოლო. {glyph} is a glyph of {font}, not of the font the selected text is set in ({text_font}). {glyph} არის {font}-ის გლიფი და არა იმ შრიფტისა, რომლითაც მონიშნული ტექსტია დაწყობილი ({text_font}). {glyph} belongs to {base} (U+{base_code}) {place}; your selection is {sel} (U+{code}). {glyph} ეკუთვნის სიმბოლოს {base} (U+{base_code}) {place}; თქვენი მონიშნულია {sel} (U+{code}). @@ -2005,6 +2021,7 @@ digits Malayalam მალაიალამური @msg paths entry {i} needs path and ids (object ids no other entry has) paths-ის ჩანაწერს {i} სჭირდება path და ids (ობიექტის ID-ები, რომლებიც სხვა ჩანაწერს არ აქვს) @msg scope missingInFolder takes path: the folder of that file is searched for the other missing links scope missingInFolder იღებს path-ს: სხვა დაკარგული ბმულები ამ ფაილის საქაღალდეში იძებნება Show Missing დაკარგულების ჩვენება + Sort by Size ზომის მიხედვით სორტირება Sort by Status სტატუსის მიხედვით სორტირება Clear Overrides ცვლილებების გასუფთავება Create New {kind} Style ახალი სტილის შექმნა ({kind}) @@ -2252,6 +2269,7 @@ digits Malayalam მალაიალამური Export Asset რესურსის ექსპორტირება Export to: ექსპორტის ადგილი: Format Settings ფორმატის პარამეტრები + Format Settings… ფორმატის პარამეტრები… Formats: ფორმატები: Full Document მთელი დოკუმენტი Include Bleed ჭრისპირა არის ჩართვა @@ -2339,6 +2357,7 @@ digits Malayalam მალაიალამური e.g. 1-3, 5 მაგ. 1-3, 5 First Page პირველი გვერდი Import PDF PDF-ის იმპორტი + Import PDF pages as links PDF-ის გვერდების იმპორტი ბმულებად Last Page ბოლო გვერდი Next Page შემდეგი გვერდი of {count} / {count} @@ -2420,6 +2439,7 @@ digits Malayalam მალაიალამური Transparent Background გამჭვირვალე ფონი Choose… არჩევა… Copy Fonts Used in the Document დოკუმენტში გამოყენებული შრიფტების კოპირება + Copy Info ინფორმაციის კოპირება Copy Links ბმულების კოპირება Create Report ანგარიშის შექმნა Fonts whose licence doesn't allow embedding are not copied. შრიფტები, რომელთა ლიცენზია ჩაშენების უფლებას არ იძლევა, არ კოპირდება. @@ -5598,6 +5618,7 @@ imageTrace Outline კონტური @msg there is no script engine named {name} სკრიპტის ძრავა სახელით {name} არ არსებობს @msg Running a script სკრიპტი მუშაობს @msg Copied the script report კოპირებულია სკრიპტის ანგარიში +@msg Copied the link info კოპირებულია ბმულის ინფორმაცია @msg Offset Path: the offset leaves nothing of the selected paths (an inset larger than the shapes) ტრაექტორიის წანაცვლება: წანაცვლების შემდეგ მონიშნული ტრაექტორიებიდან არაფერი რჩება (შიგნით წანაცვლება ფიგურებზე დიდია) @msg {path}: not a file {path}: ფაილი არ არის Load EPS into Clipboard EPS-ის ბუფერში ჩატვირთვა @@ -5678,6 +5699,8 @@ imageTrace Outline კონტური @msg object has no weighted stroke ობიექტს ცვლადი სისქის კონტური არ აქვს @msg objects can't be nested more than 32 deep ობიექტების ჩადგმის სიღრმე 32-ს ვერ გადააჭარბებს @msg the SVG's elements are nested more than {0} deep SVG-ის ელემენტების ჩადგმის სიღრმე {0}-ს აჭარბებს +@msg the SVG's style sheets take too long to match SVG-ის სტილის ფურცლების შედარებას ძალიან დიდი დრო სჭირდება +@msg the SVG's styles expand to more than {0} MB SVG-ის სტილები გაშლისას {0} MB-ს აჭარბებს @msg unknown control `{name}`: fillStroke, coloring, drawMode or screenMode უცნობი control `{name}`: fillStroke, coloring, drawMode ან screenMode @plural agrees with {n} default shortcut|agrees with {n} default shortcuts ემთხვევა ნაგულისხმევ მალსახმობებს: {n}|ემთხვევა ნაგულისხმევ მალსახმობებს: {n} @plural {n} part of the file wasn't read|{n} parts of the file weren't read ფაილის წაუკითხავი ნაწილები: {n}|ფაილის წაუკითხავი ნაწილები: {n} @@ -6625,7 +6648,7 @@ axis Y Axis Y ღერძი @plural Result: {n}|Results: {n} შედეგი: {n} @msg select one object მონიშნეთ ერთი ობიექტი @msg Global Edit works on paths, compound paths, symbol instances and groups of them გლობალური რედაქტირება მუშაობს ტრაექტორიებზე, შედგენილ ტრაექტორიებზე, სიმბოლოს ეგზემპლარებსა და მათ ჯგუფებზე -@msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again მსგავსი ობიექტები ვერ მოიძებნა (შემობრუნებული ან არეკლილი ასლები არ ემთხვევა); შეცვალეთ გლობალური რედაქტირების პარამეტრები და სცადეთ ხელახლა +@msg no similar objects found (reflected copies are not matched); change the Global Edit Options and try again მსგავსი ობიექტები ვერ მოიძებნა (არეკლილი ასლები არ ემთხვევა); შეცვალეთ გლობალური რედაქტირების პარამეტრები და სცადეთ ხელახლა @msg Global Edit is off გლობალური რედაქტირება გამორთულია @msg only an object of the Global Edit other than the one it started from can be left out გლობალური რედაქტირებიდან შეიძლება გამოირიცხოს მხოლოდ ობიექტი, რომლითაც ის არ დაწყებულა @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all ან დიაპაზონი, მაგალითად 1, 3-5, და არა {v} @@ -7581,11 +7604,20 @@ font-script Japanese იაპონური Open Tutorial Sample გაკვეთილის ნიმუშის გახსნა Finish Tutorial გაკვეთილის დასრულება Next Tutorial შემდეგი გაკვეთილი + Show Learn Tab სწავლის ჩანართის ჩვენება + Show Skill უნარის ჩვენება + Back One Level ერთი დონით უკან Back to Skills უნარებზე დაბრუნება @msg tutorial `{id}` has no practice sample გაკვეთილს `{id}` არ აქვს სავარჯიშო ნიმუში @msg open the practice sample of `{id}` first (see learn.openSample) ჯერ გახსენით `{id}` გაკვეთილის სავარჯიშო ნიმუში (იხ. learn.openSample) @msg finish `{id}` first (see learn.finish) ჯერ დაასრულეთ `{id}` (იხ. learn.finish) @msg `{id}` is the last tutorial in its skill `{id}` თავისი უნარის ბოლო გაკვეთილია + Reset progress პროგრესის ჩამოყრა + Mark Tutorial Step გაკვეთილის ნაბიჯის მონიშვნა + Reset Learn Progress სწავლის პროგრესის ჩამოყრა +@msg missing `step` (see learn.show) აკლია `step` (იხ. learn.show) +@msg `step` must be a step number from 0 to {last} `step` უნდა იყოს ნაბიჯის ნომერი 0-დან {last}-მდე +@msg `{id}` is finished (see learn.resetProgress) `{id}` დასრულებულია (იხ. learn.resetProgress) # Deferred plug-in effects Refresh Deferred Effects გადადებული ეფექტების განახლება @@ -7615,3 +7647,6 @@ font-script Japanese იაპონური Grommets ლუვერები Grommet Inset ლუვერების დაშორება კიდიდან Diameter დიამეტრი + Nest Shapes… ფორმების განლაგება… + Nest Shapes ფორმების განლაგება + Roll რულონი diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 8af8d3f53d..421d4ec4bd 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -456,6 +456,18 @@ digits Malayalam 말라얄람어 Title Case 제목 대소문자 Sentence case 문장 대소문자 Smart Punctuation… 스마트 문장 부호… + Smart Punctuation 스마트 문장 부호 + ff, fi, ffi Ligatures ff, fi, ffi 합자 + ff, fl, ffl Ligatures ff, fl, ffl 합자 + Smart Quotes 스마트 따옴표 + Smart Spaces 스마트 공백 + En, Em Dashes 엔 대시 및 엠 대시 + Ellipses 줄임표 + Expert Fractions 전문가 분수 + Replace In 바꿀 범위 + Selected Text Only 선택한 텍스트만 + Entire Document 전체 문서 + Report Results 결과 보고 Create Outlines 윤곽선 만들기 Optical Margin Alignment 시각적 여백 정렬 Dynamic Text 동적 텍스트 @@ -1547,6 +1559,9 @@ antiAlias Sharp 날카롭게 The selected character's font is not available. 선택한 문자의 글꼴을 사용할 수 없습니다. No alternates for the selected character. 선택한 문자의 대체 글리프가 없습니다. Double-click to replace 더블클릭하여 바꾸기 + Click to replace 클릭하여 바꾸기 + Show all alternates in the Glyphs panel 글리프 패널에서 모든 대체 글리프 표시 + Show Character Alternates 문자의 대체 글리프 표시 Select one character with the Type tool first. 먼저 문자 도구로 문자 하나를 선택하세요. {glyph} is a glyph of {font}, not of the font the selected text is set in ({text_font}). {glyph}은(는) {font}의 글리프이며, 선택한 텍스트의 글꼴({text_font})의 것이 아닙니다. {glyph} belongs to {base} (U+{base_code}) {place}; your selection is {sel} (U+{code}). {glyph}은(는) {base}(U+{base_code})의 {place} 글리프입니다. 선택한 문자는 {sel}(U+{code})입니다. @@ -1824,6 +1839,7 @@ antiAlias Sharp 날카롭게 Format 형식 Format Options 형식 옵션 Format Settings 형식 설정 + Format Settings… 형식 설정… Format: 형식: Formats: 형식: Fractions 분수 @@ -2061,6 +2077,7 @@ antiAlias Sharp 날카롭게 Images: 이미지: Import Keyboard Shortcuts… 단축키 가져오기… Import PDF PDF 가져오기 + Import PDF pages as links PDF 페이지를 링크로 가져오기 Import PDF Presets PDF 프리셋 가져오기 Import Perspective Grid Presets 원근 격자 프리셋 가져오기 Import Print Presets 인쇄 프리셋 가져오기 @@ -3746,6 +3763,7 @@ gradient-kind Radial 방사형 Convert To Outlines 윤곽선으로 변환 Copy All Objects 모든 개체 복사 Copy Fonts Used in the Document 문서에 사용된 글꼴 복사 + Copy Info 정보 복사 Copy Links 링크 복사 Couldn't copy to the system clipboard: {e} 시스템 클립보드로 복사할 수 없습니다: {e} Couldn't paste from the clipboard: {e} 클립보드에서 붙여넣을 수 없습니다: {e} @@ -4011,6 +4029,7 @@ file-filter Templates 템플릿 Small Thumbnails 작은 축소판 Smooth Color 부드러운 색상 Social Square Post 1080×1080 소셜 정사각형 게시물 1080×1080 + Sort by Size 크기순 정렬 Sort by Status 상태순 정렬 Specified Distance 지정 거리 Specified Steps 지정 단계 @@ -4227,6 +4246,7 @@ theme Appearance 외관 Free Transform 자유 변형 Perspective Distort 원근 왜곡 Radial Blur… 방사형 흐림… + Blur Center 흐림 중심 Smart Blur… 스마트 흐림… Sharpen 선명하게 Unsharp Mask… 언샤프 마스크… @@ -5118,6 +5138,7 @@ theme Appearance 외관 @msg there is no script engine named {name} 이름이 {name}인 스크립트 엔진이 없습니다 @msg Running a script 스크립트 실행 중 @msg Copied the script report 스크립트 보고서를 복사했습니다 +@msg Copied the link info 링크 정보를 복사했습니다 @msg Exported {path} {path}을(를) 내보냈습니다 @msg no CSS to copy: select objects with CSS of their own 복사할 CSS가 없습니다: 자체 CSS가 있는 개체를 선택하세요 @msg unknown highlight `{h}` 알 수 없는 강조 `{h}` @@ -6261,7 +6282,7 @@ axis Y Axis Y축 @plural Result: {n}|Results: {n} 결과: {n} @msg select one object 개체 하나를 선택하십시오 @msg Global Edit works on paths, compound paths, symbol instances and groups of them 전체 편집은 패스, 컴파운드 패스, 심볼 인스턴스 및 이들의 그룹에서 작동합니다 -@msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again 유사한 개체를 찾을 수 없습니다(회전하거나 반사한 복사본은 일치하지 않습니다). 전체 편집 옵션을 변경한 후 다시 시도하십시오 +@msg no similar objects found (reflected copies are not matched); change the Global Edit Options and try again 유사한 개체를 찾을 수 없습니다(반사한 복사본은 일치하지 않습니다). 전체 편집 옵션을 변경한 후 다시 시도하십시오 @msg Global Edit is off 전체 편집이 꺼져 있습니다 @msg only an object of the Global Edit other than the one it started from can be left out 전체 편집을 시작한 개체가 아닌 전체 편집의 개체만 제외할 수 있습니다 @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all 또는 1, 3-5 같은 범위여야 합니다({v}이(가) 아님) @@ -7058,11 +7079,20 @@ breakText Glyphs 글리프 Open Tutorial Sample 튜토리얼 샘플 열기 Finish Tutorial 튜토리얼 완료 Next Tutorial 다음 튜토리얼 + Show Learn Tab 학습 탭 표시 + Show Skill 기술 표시 + Back One Level 한 단계 뒤로 Back to Skills 기술로 돌아가기 @msg tutorial `{id}` has no practice sample 튜토리얼 `{id}`에 연습용 샘플이 없습니다 @msg open the practice sample of `{id}` first (see learn.openSample) 먼저 `{id}`의 연습용 샘플을 여세요(learn.openSample 참조) @msg finish `{id}` first (see learn.finish) 먼저 `{id}`을(를) 완료하세요(learn.finish 참조) @msg `{id}` is the last tutorial in its skill `{id}`은(는) 해당 기술의 마지막 튜토리얼입니다 + Reset progress 진행률 재설정 + Mark Tutorial Step 튜토리얼 단계 표시 + Reset Learn Progress 학습 진행률 재설정 +@msg missing `step` (see learn.show) `step`이 없습니다(learn.show 참조) +@msg `step` must be a step number from 0 to {last} `step`은 0에서 {last} 사이의 단계 번호여야 합니다 +@msg `{id}` is finished (see learn.resetProgress) `{id}`은(는) 완료되었습니다(learn.resetProgress 참조) # Deferred plug-in effects Refresh Deferred Effects 보류된 효과 새로 고침 @@ -7092,6 +7122,128 @@ breakText Glyphs 글리프 Grommets 아일렛 Grommet Inset 가장자리에서 아일렛까지 거리 Diameter 지름 + Nest Shapes… 도형 네스팅… + Nest Shapes 도형 네스팅 + Roll 롤 + +# Messages of the 3D effects, image export, color profiles, swatch exchange files, color books, DXF import, +# path operations, libraries, scripts and zip files. +@msg 3D effects require finite coordinates within 100 million points 3D 효과에는 1억 포인트 이내의 유한한 좌표가 필요합니다 +@msg 3D effects require one to ten lights 3D 효과에는 광원이 1개에서 10개까지 필요합니다 +@msg BMP depth {_1}: 1, 4, 8, 16, 24 or 32 bits per pixel BMP 비트 심도 {_1}: 픽셀당 1, 4, 8, 16, 24 또는 32비트여야 합니다 +@msg BMP encoding failed: {width} × {height} pixels doesn't fit the format or the pixel buffer BMP 인코딩 실패: {width} × {height}픽셀이 형식이나 픽셀 버퍼에 맞지 않습니다 +@msg GIF encoding failed: the palette image is malformed GIF 인코딩 실패: 팔레트 이미지의 형식이 잘못되었습니다 +@msg GIF encoding failed: {e} GIF 인코딩 실패: {e} +@msg JPEG colour profile: {e} JPEG 색상 프로파일: {e} +@msg JPEG encoding failed: pixel buffer doesn't match the image size JPEG 인코딩 실패: 픽셀 버퍼가 이미지 크기와 맞지 않습니다 +@msg JPEG encoding failed: {e} JPEG 인코딩 실패: {e} +@msg PNG encoding failed: pixel buffer doesn't match the image size PNG 인코딩 실패: 픽셀 버퍼가 이미지 크기와 맞지 않습니다 +@msg PNG encoding failed: the palette image is malformed PNG 인코딩 실패: 팔레트 이미지의 형식이 잘못되었습니다 +@msg PNG encoding failed: {e} PNG 인코딩 실패: {e} +@msg PNG encoding failed: {width} × {height} pixels is not a valid image size PNG 인코딩 실패: {width} × {height}픽셀은 올바른 이미지 크기가 아닙니다 +@msg PSD colour profile: {e} PSD 색상 프로파일: {e} +@msg PSD encoding failed: the pixel buffer doesn't match the image size PSD 인코딩 실패: 픽셀 버퍼가 이미지 크기와 맞지 않습니다 +@msg Revolve profile contains invalid coordinates 회전체 프로파일에 잘못된 좌표가 있습니다 +@msg Revolve profile is too complex 회전체 프로파일이 너무 복잡합니다 +@msg Revolve projection is not finite 회전체 투영이 유한하지 않습니다 +@msg Revolve requires finite profile coordinates within 100 million points 회전체에는 1억 포인트 이내의 유한한 프로파일 좌표가 필요합니다 +@msg Revolve surface is too complex; reduce Segments or simplify the profile 회전체 표면이 너무 복잡합니다. 세그먼트를 줄이거나 프로파일을 단순화하십시오 +@msg Revolve surface is too complex; simplify the profile 회전체 표면이 너무 복잡합니다. 프로파일을 단순화하십시오 +@msg Revolve visibility cannot split the projected boundary 회전체 가시성 계산에서 투영된 경계를 분할할 수 없습니다 +@msg Revolve visibility creates too many fragments 회전체 가시성 계산에서 조각이 너무 많이 생깁니다 +@msg Revolve visibility creates too many vector anchors 회전체 가시성 계산에서 벡터 고정점이 너무 많이 생깁니다 +@msg Revolve visibility exceeds its geometry work limit 회전체 가시성 계산이 기하 연산 한도를 넘습니다 +@msg Revolve visibility exceeds its spatial index limit 회전체 가시성 계산이 공간 인덱스 한도를 넘습니다 +@msg Revolve visibility has too many boundary crossings 회전체 가시성 계산에 경계 교차가 너무 많습니다 +@msg Revolve visibility has too many input anchors 회전체 가시성 계산의 입력 고정점이 너무 많습니다 +@msg Revolve visibility requires convex cap sectors 회전체 가시성 계산에는 볼록한 캡 부채꼴이 필요합니다 +@msg Revolve visibility requires finite projected faces 회전체 가시성 계산에는 유한한 투영 면이 필요합니다 +@msg SVG options: {e} SVG 옵션: {e} +@msg Save for Web settings: {e} 웹용 저장 설정: {e} +@msg TIFF colour profile: {e} TIFF 색상 프로파일: {e} +@msg TIFF encoding failed: the pixel buffer doesn't match the image size TIFF 인코딩 실패: 픽셀 버퍼가 이미지 크기와 맞지 않습니다 +@msg TIFF encoding failed: {e} TIFF 인코딩 실패: {e} +@msg Targa depth {_1}: 16, 24 or 32 bits per pixel Targa 비트 심도 {_1}: 픽셀당 16, 24 또는 32비트여야 합니다 +@msg Targa encoding failed: the pixel buffer doesn't match the image size Targa 인코딩 실패: 픽셀 버퍼가 이미지 크기와 맞지 않습니다 +@msg The 3D projection is not finite 3D 투영이 유한하지 않습니다 +@msg The 3D shadow is too complex; turn Shadows off or simplify the art 3D 그림자가 너무 복잡합니다. 그림자를 끄거나 아트를 단순화하십시오 +@msg The shape contains invalid coordinates 모양에 잘못된 좌표가 있습니다 +@msg Too many Revolve faces for visibility evaluation 회전체의 면이 너무 많아 가시성을 계산할 수 없습니다 +@msg VectorCraft reads at most {ASE_MAX_ENTRIES} colors and groups from a swatch exchange file, and this library has {entries} VectorCraft는 견본 교환 파일에서 색상과 그룹을 최대 {ASE_MAX_ENTRIES}개까지 읽는데, 이 라이브러리에는 {entries}개가 있습니다 +@msg WebP encoding failed: {e} WebP 인코딩 실패: {e} +@msg [{j}] `{_1}`: {why} [{j}] `{_1}`: {why} +@msg `answers[{i}]` {e} `answers[{i}]` {e} +@msg `index` must be a whole number `index`은(는) 정수여야 합니다 +@msg `view` is smallThumb, mediumThumb, largeThumb, smallList or largeList `view`는 smallThumb, mediumThumb, largeThumb, smallList 또는 largeList여야 합니다 +@msg a line can't run from a point to itself 선은 한 점에서 같은 점으로 이어질 수 없습니다 +@msg a line needs at least two points 선에는 점이 두 개 이상 필요합니다 +@msg a number cannot be read 숫자를 읽을 수 없습니다 +@msg a swatch exchange block is too long 견본 교환 블록이 너무 깁니다 +@msg a swatch exchange name is too long 견본 교환 이름이 너무 깁니다 +@msg a {sw} × {sh} image can't be resized to {width} × {height} pixels {sw} × {sh} 이미지를 {width} × {height}픽셀로 크기 조정할 수 없습니다 +@msg a {width} × {height} image is too large {width} × {height} 이미지가 너무 큽니다 +@msg a {width} × {height} image: {e} {width} × {height} 이미지: {e} +@msg an image could not be written: {e} 이미지를 기록할 수 없습니다: {e} +@msg an image that couldn't be read was left out 읽을 수 없는 이미지를 제외했습니다 +@msg can't open “{name}”: {e} “{name}”을(를) 열 수 없습니다: {e} +@msg cannot align zip entries to {align} bytes zip 항목을 {align}바이트 단위로 정렬할 수 없습니다 +@msg cannot open the automation {kind} root `{_1}`: {e} 자동화 {kind} 루트 `{_1}`을(를) 열 수 없습니다: {e} +@msg cannot read profile: {0} 프로파일을 읽을 수 없습니다: {0} +@msg color book version {version} isn't supported (only 1) 색상 견본집 버전 {version}은(는) 지원되지 않습니다(1만 지원) +@msg color books in color space {other} aren't supported (only RGB, CMYK and Lab) 색상 공간이 {other}인 색상 견본집은 지원되지 않습니다(RGB, CMYK, Lab만 지원) +@msg file name too long to zip: {_1} 파일 이름이 너무 길어 zip에 넣을 수 없습니다: {_1} +@msg file name too long to zip: {name} 파일 이름이 너무 길어 zip에 넣을 수 없습니다: {name} +@msg freeform line {i}: {e} 자유형 선 {i}: {e} +@msg freeform point {i}: {e} 자유형 점 {i}: {e} +@msg give `{key}` or `{other}`, not both `{key}`와 `{other}` 중 하나만 지정하세요 +@msg grayscale profiles can't be working spaces yet 그레이스케일 프로파일은 아직 작업 공간으로 사용할 수 없습니다 +@msg input contains NaN or infinite coordinates 입력에 NaN 또는 무한대 좌표가 있습니다 +@msg input path could not be closed 입력 패스를 닫을 수 없습니다 +@msg invalid ICC profile: {0} 잘못된 ICC 프로파일: {0} +@msg invalid scale {scale} 잘못된 비율 {scale} +@msg its localized names take more than {_1} KB 지역화된 이름이 {_1} KB를 넘습니다 +@msg its objects are nested too deep ({e}) 개체가 너무 깊이 중첩되어 있습니다({e}) +@msg its tag table lists the `{_1}` tag more than once 태그 표에 `{_1}` 태그가 두 번 이상 나열되어 있습니다 +@msg not a graphic style library: {e} 그래픽 스타일 라이브러리가 아닙니다: {e} +@msg not a swatch library (.vcswatches or .gpl) 견본 라이브러리가 아닙니다(.vcswatches 또는 .gpl) +@msg not a swatch library (format `{_1}`) 견본 라이브러리가 아닙니다(형식 `{_1}`) +@msg not a swatch library: {e} 견본 라이브러리가 아닙니다: {e} +@msg not an action set file ({e}) 액션 세트 파일이 아닙니다({e}) +@msg profile colour space {other} is not RGB, CMYK or Gray 프로파일의 색상 공간 {other}은(는) RGB, CMYK 또는 Gray가 아닙니다 +@msg regular expression too large 정규식이 너무 큽니다 +@msg script file is not UTF-8 text: {value} 스크립트 파일이 UTF-8 텍스트가 아닙니다: {value} +@msg stop {i}: {e} 정지점 {i}: {e} +@msg swatch exchange version {major}.{minor} isn't supported (only 1.x) 견본 교환 버전 {major}.{minor}은(는) 지원되지 않습니다(1.x만 지원) +@msg the color book holds more than {ASE_MAX_ENTRIES} colors 색상 견본집의 색상이 {ASE_MAX_ENTRIES}개를 넘습니다 +@msg the color book is cut short 색상 견본집이 중간에 잘려 있습니다 +@msg the color book's names take more than {_1} MB 색상 견본집의 이름이 {_1} MB를 넘습니다 +@msg the image would be {w} × {h} pixels; raster exports are limited to {MAX_RASTER_SIDE} pixels per side and {_1} megapixels: lower the scale or resolution 이미지가 {w} × {h}픽셀이 됩니다. 래스터 내보내기는 한 변에 {MAX_RASTER_SIDE}픽셀, {_1}메가픽셀로 제한됩니다. 비율이나 해상도를 낮추세요 +@msg the optimised image can't be read back: {e} 최적화된 이미지를 다시 읽을 수 없습니다: {e} +@msg the pixel buffer doesn't match the image size 픽셀 버퍼가 이미지 크기와 맞지 않습니다 +@msg the preview: {e} 미리 보기: {e} +@msg the request may not read the New Document profiles folder 이 요청은 새 문서 프로파일 폴더를 읽을 수 없습니다 +@msg the shapes are too degenerate to combine 모양이 너무 퇴화되어 결합할 수 없습니다 +@msg the shapes cross themselves and each other too often to combine 모양이 자기 자신 및 서로와 너무 자주 교차하여 결합할 수 없습니다 +@msg the swatch exchange file holds more than {ASE_MAX_ENTRIES} colors and groups 견본 교환 파일의 색상과 그룹이 {ASE_MAX_ENTRIES}개를 넘습니다 +@msg the swatch exchange file is cut short 견본 교환 파일이 중간에 잘려 있습니다 +@msg the {_1} plate can't be read: {e} {_1} 분판을 읽을 수 없습니다: {e} +@msg this binary DXF file is damaged or cut short 이 바이너리 DXF 파일이 손상되었거나 중간에 잘려 있습니다 +@msg this is a DWG drawing, which can't be read: save it from the CAD app as a DXF and open that DWG 도면은 읽을 수 없습니다. CAD 앱에서 DXF로 저장한 후 여세요 +@msg too many classes 문자 클래스가 너무 많습니다 +@msg too many groups 그룹이 너무 많습니다 +@msg too many layers for PSD (at most 32767) PSD에 비해 레이어가 너무 많습니다(최대 32767개) +@msg too many swatch exchange blocks 견본 교환 블록이 너무 많습니다 +@msg unknown colour profile: {0} 알 수 없는 색상 프로파일: {0} +@msg {_1} clashes with a built-in profile name {_1}이(가) 기본 제공 프로파일 이름과 겹칩니다 +@msg {_1} × {_2} pixels is too large for GIF (at most 65535 pixels a side): lower the resolution {_1} × {_2}픽셀은 GIF에 비해 너무 큽니다(한 변 최대 65535픽셀). 해상도를 낮추세요 +@msg {_1}: no usable transform to/from sRGB {_1}: sRGB와 주고받을 수 있는 변환이 없습니다 +@msg {name} is not a CMYK profile {name}은(는) CMYK 프로파일이 아닙니다 +@msg {name} is not an RGB profile {name}은(는) RGB 프로파일이 아닙니다 +@msg {path}: could not be read {path}: 읽을 수 없습니다 +@msg {width} × {height} pixels is too large for JPEG (at most 65535 pixels a side): lower the resolution {width} × {height}픽셀은 JPEG에 비해 너무 큽니다(한 변 최대 65535픽셀). 해상도를 낮추세요 +@msg {width} × {height} pixels is too large for Targa (at most 65535 pixels a side): lower the resolution {width} × {height}픽셀은 Targa에 비해 너무 큽니다(한 변 최대 65535픽셀). 해상도를 낮추세요 +@msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h}픽셀은 PSD에 비해 너무 큽니다(한 변 최대 {MAX_SIDE}픽셀). 해상도를 낮추세요 + # Status and error messages of commands, scripts, file import and export, and plug-ins. @msg 'caller', 'callee' and 'arguments' cannot be used on strict mode functions 엄격 모드 함수에서는 'caller', 'callee', 'arguments'를 사용할 수 없습니다 @msg A profile supports one Revolve effect. Edit the existing effect's options instead. 프로파일 하나에는 회전체 효과를 하나만 쓸 수 있습니다. 기존 효과의 옵션을 편집하세요. @@ -8480,6 +8632,8 @@ breakText Glyphs 글리프 @msg the RTF file is too large to place as type (at most {_1} MB) RTF 파일이 너무 커서 문자로 가져올 수 없습니다(최대 {_1} MB) @msg the SVG expands to more than {0} nested SVG images SVG를 확장하면 중첩된 SVG 이미지가 {0}개보다 많아집니다 @msg the SVG expands to more than {0} objects SVG를 확장하면 개체가 {0}개보다 많아집니다 +@msg the SVG's style sheets take too long to match SVG의 스타일 시트를 대조하는 데 시간이 너무 오래 걸립니다 +@msg the SVG's styles expand to more than {0} MB SVG의 스타일을 확장하면 {0}MB를 넘습니다 @msg the SVG file is larger than {MAX_IMPORT_BYTES} bytes SVG 파일이 {MAX_IMPORT_BYTES}바이트보다 큽니다 @msg the SVG has no drawable objects SVG에 그릴 수 있는 개체가 없습니다 @msg the SVGZ file unpacks to more than {_1} MB SVGZ 파일의 압축을 풀면 {_1} MB를 넘습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index c8b777d01b..667c7feb54 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -475,7 +475,7 @@ @msg “{name}” › {label}: {e} „{name}” › {label}: {e} @msg the module doesn't have the SHA-256 `hash` gives: nothing was installed de module heeft niet de SHA-256 die `hash` opgeeft: er is niets geïnstalleerd @msg select one object selecteer één object -@msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again geen vergelijkbare objecten gevonden (gedraaide of gespiegelde kopieën worden niet herkend); wijzig de Opties voor globale bewerking en probeer het opnieuw +@msg no similar objects found (reflected copies are not matched); change the Global Edit Options and try again geen vergelijkbare objecten gevonden (gespiegelde kopieën worden niet herkend); wijzig de Opties voor globale bewerking en probeer het opnieuw @msg Global Edit is off Globale bewerking staat uit @msg only an object of the Global Edit other than the one it started from can be left out alleen een ander object van de globale bewerking dan het object waarmee die begon, kan worden weggelaten @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all of een bereik zoals 1, 3-5, niet {v} @@ -907,6 +907,18 @@ Title Case Koptitel Sentence case Zinsvorm Smart Punctuation… Slimme interpunctie… + Smart Punctuation Slimme interpunctie + ff, fi, ffi Ligatures Ligaturen ff, fi, ffi + ff, fl, ffl Ligatures Ligaturen ff, fl, ffl + Smart Quotes Slimme aanhalingstekens + Smart Spaces Slimme spaties + En, Em Dashes Halve en hele gedachtestreepjes + Ellipses Beletseltekens + Expert Fractions Expertbreuken + Replace In Vervangen in + Selected Text Only Alleen geselecteerde tekst + Entire Document Hele document + Report Results Resultaten rapporteren Create Outlines Omzetten in curven Optical Margin Alignment Optische marge-uitlijning Dynamic Text Dynamische tekst @@ -1419,6 +1431,7 @@ Free Transform Vrij transformeren Perspective Distort Perspectief vervormen Radial Blur… Radiaal vervagen… + Blur Center Middelpunt van vervaging Smart Blur… Slim vervagen… Sharpen Verscherpen Unsharp Mask… Onscherp maskeren… @@ -2154,6 +2167,9 @@ digits Malayalam Malayalam The selected character's font is not available. Het lettertype van het geselecteerde teken is niet beschikbaar. No alternates for the selected character. Geen alternatieven voor het geselecteerde teken. Double-click to replace Dubbelklik om te vervangen + Click to replace Klik om te vervangen + Show all alternates in the Glyphs panel Alle alternatieven tonen in het paneel Glyphs + Show Character Alternates Tekenalternatieven tonen Select one character with the Type tool first. Selecteer eerst één teken met het Type-gereedschap. {glyph} is a glyph of {font}, not of the font the selected text is set in ({text_font}). {glyph} is een glyph van {font}, niet van het lettertype van de geselecteerde tekst ({text_font}). {glyph} belongs to {base} (U+{base_code}) {place}; your selection is {sel} (U+{code}). {glyph} hoort bij {base} (U+{base_code}) {place}; uw selectie is {sel} (U+{code}). @@ -2595,6 +2611,7 @@ digits Malayalam Malayalam @msg paths entry {i} needs path and ids (object ids no other entry has) item {i} van paths heeft path en ids nodig (object-id's die geen ander item heeft) @msg scope missingInFolder takes path: the folder of that file is searched for the other missing links scope missingInFolder neemt path: in de map van dat bestand wordt naar de andere ontbrekende koppelingen gezocht Show Missing Ontbrekende weergeven + Sort by Size Sorteren op grootte Sort by Status Sorteren op status Clear Overrides Onderdrukkingen wissen Create New {kind} Style Nieuwe {kind}stijl maken @@ -2844,6 +2861,7 @@ digits Malayalam Malayalam Export Asset Asset exporteren Export to: Exporteren naar: Format Settings Indelingsinstellingen + Format Settings… Indelingsinstellingen… Formats: Indelingen: Full Document Volledig document Include Bleed Afrulling opnemen @@ -2933,6 +2951,7 @@ digits Malayalam Malayalam e.g. 1-3, 5 bijv. 1-3, 5 First Page Eerste pagina Import PDF PDF importeren + Import PDF pages as links PDF-pagina's importeren als koppelingen Last Page Laatste pagina Next Page Volgende pagina of {count} van {count} @@ -3016,6 +3035,7 @@ digits Malayalam Malayalam Transparent Background Transparante achtergrond Choose… Kies… Copy Fonts Used in the Document In het document gebruikte lettertypen kopiëren + Copy Info Info kopiëren Copy Links Koppelingen kopiëren Create Report Rapport maken Fonts whose licence doesn't allow embedding are not copied. Lettertypen waarvan de licentie insluiten niet toestaat, worden niet gekopieerd. @@ -4798,6 +4818,7 @@ imageTrace Outline Contour Stop the script and undo what it did? Then quit again. Het script stoppen en de wijzigingen ervan ongedaan maken? Sluit daarna opnieuw af. This script has added a great many objects. Continue, or stop it and undo what it did? Dit script heeft heel veel objecten toegevoegd. Doorgaan, of het stoppen en de wijzigingen ervan ongedaan maken? @msg Copied the script report Scriptrapport gekopieerd +@msg Copied the link info Koppelingsinfo gekopieerd @msg Corners edits the corners of a path Hoeken bewerkt de hoeken van een pad @msg Couldn't copy to the system clipboard: {e} Kon niet naar het systeemklembord kopiëren: {e} @msg Couldn't open {name}: {e} Kon {name} niet openen: {e} @@ -6957,6 +6978,8 @@ imageTrace Outline Contour @msg the RTF file is too large to place as type (at most {_1} MB) het RTF-bestand is te groot om als tekst te plaatsen (maximaal {_1} MB) @msg the SVG expands to more than {0} nested SVG images de SVG wordt uitgevouwen tot meer dan {0} geneste SVG-afbeeldingen @msg the SVG expands to more than {0} objects de SVG wordt uitgevouwen tot meer dan {0} objecten +@msg the SVG's style sheets take too long to match het vergelijken van de stijlbladen van de SVG duurt te lang +@msg the SVG's styles expand to more than {0} MB de stijlen van de SVG worden uitgevouwen tot meer dan {0} MB @msg the SVG file is larger than {MAX_IMPORT_BYTES} bytes het SVG-bestand is groter dan {MAX_IMPORT_BYTES} bytes @msg the SVG has no drawable objects de SVG heeft geen tekenbare objecten @msg the SVGZ file unpacks to more than {_1} MB het SVGZ-bestand wordt uitgepakt tot meer dan {_1} MB @@ -9318,11 +9341,20 @@ breakText Glyphs Glyphs Open Tutorial Sample Oefenbestand van tutorial openen Finish Tutorial Tutorial voltooien Next Tutorial Volgende tutorial + Show Learn Tab Tabblad van Leren tonen + Show Skill Vaardigheid tonen + Back One Level Eén niveau terug Back to Skills Terug naar vaardigheden @msg tutorial `{id}` has no practice sample tutorial `{id}` heeft geen oefenbestand @msg open the practice sample of `{id}` first (see learn.openSample) open eerst het oefenbestand van `{id}` (zie learn.openSample) @msg finish `{id}` first (see learn.finish) voltooi eerst `{id}` (zie learn.finish) @msg `{id}` is the last tutorial in its skill `{id}` is de laatste tutorial van zijn vaardigheid + Reset progress Voortgang opnieuw instellen + Mark Tutorial Step Stap van tutorial markeren + Reset Learn Progress Leervoortgang opnieuw instellen +@msg missing `step` (see learn.show) `step` ontbreekt (zie learn.show) +@msg `step` must be a step number from 0 to {last} `step` moet een stapnummer van 0 tot en met {last} zijn +@msg `{id}` is finished (see learn.resetProgress) `{id}` is voltooid (zie learn.resetProgress) # Deferred plug-in effects Refresh Deferred Effects Uitgestelde effecten vernieuwen @@ -9346,3 +9378,124 @@ breakText Glyphs Glyphs Grommets Zeilringen Grommet Inset Afstand van zeilringen tot de rand Diameter Diameter + Nest Shapes… Vormen nesten… + Nest Shapes Vormen nesten + Roll Rol + +# Status and error messages: 3D effects and Revolve, image export, color profiles, swatch exchange files and +# color books, regular expressions in scripts, whole-number parameters, and DXF and DWG files. +@msg 3D effects require finite coordinates within 100 million points 3D-effecten vereisen eindige coördinaten binnen 100 miljoen punten +@msg 3D effects require one to ten lights 3D-effecten vereisen één tot tien lichten +@msg BMP depth {_1}: 1, 4, 8, 16, 24 or 32 bits per pixel BMP-diepte {_1}: 1, 4, 8, 16, 24 of 32 bits per pixel +@msg BMP encoding failed: {width} × {height} pixels doesn't fit the format or the pixel buffer BMP-codering mislukt: {width} × {height} pixels past niet in het formaat of in de pixelbuffer +@msg GIF encoding failed: the palette image is malformed GIF-codering mislukt: de paletafbeelding is ongeldig +@msg GIF encoding failed: {e} GIF-codering mislukt: {e} +@msg JPEG colour profile: {e} JPEG-kleurprofiel: {e} +@msg JPEG encoding failed: pixel buffer doesn't match the image size JPEG-codering mislukt: de pixelbuffer komt niet overeen met de afbeeldingsgrootte +@msg JPEG encoding failed: {e} JPEG-codering mislukt: {e} +@msg PNG encoding failed: pixel buffer doesn't match the image size PNG-codering mislukt: de pixelbuffer komt niet overeen met de afbeeldingsgrootte +@msg PNG encoding failed: the palette image is malformed PNG-codering mislukt: de paletafbeelding is ongeldig +@msg PNG encoding failed: {e} PNG-codering mislukt: {e} +@msg PNG encoding failed: {width} × {height} pixels is not a valid image size PNG-codering mislukt: {width} × {height} pixels is geen geldige afbeeldingsgrootte +@msg PSD colour profile: {e} PSD-kleurprofiel: {e} +@msg PSD encoding failed: the pixel buffer doesn't match the image size PSD-codering mislukt: de pixelbuffer komt niet overeen met de afbeeldingsgrootte +@msg Revolve profile contains invalid coordinates Het profiel van Draaien bevat ongeldige coördinaten +@msg Revolve profile is too complex Het profiel van Draaien is te complex +@msg Revolve projection is not finite De projectie van Draaien is niet eindig +@msg Revolve requires finite profile coordinates within 100 million points Draaien vereist eindige profielcoördinaten binnen 100 miljoen punten +@msg Revolve surface is too complex; reduce Segments or simplify the profile Het oppervlak van Draaien is te complex; verlaag Segmenten of vereenvoudig het profiel +@msg Revolve surface is too complex; simplify the profile Het oppervlak van Draaien is te complex; vereenvoudig het profiel +@msg Revolve visibility cannot split the projected boundary De zichtbaarheid van Draaien kan de geprojecteerde rand niet splitsen +@msg Revolve visibility creates too many fragments De zichtbaarheid van Draaien maakt te veel fragmenten +@msg Revolve visibility creates too many vector anchors De zichtbaarheid van Draaien maakt te veel vectorankerpunten +@msg Revolve visibility exceeds its geometry work limit De zichtbaarheid van Draaien overschrijdt de werklimiet voor geometrie +@msg Revolve visibility exceeds its spatial index limit De zichtbaarheid van Draaien overschrijdt de limiet van de ruimtelijke index +@msg Revolve visibility has too many boundary crossings De zichtbaarheid van Draaien heeft te veel randkruisingen +@msg Revolve visibility has too many input anchors De zichtbaarheid van Draaien heeft te veel invoerankerpunten +@msg Revolve visibility requires convex cap sectors De zichtbaarheid van Draaien vereist convexe kapsectoren +@msg Revolve visibility requires finite projected faces De zichtbaarheid van Draaien vereist eindige geprojecteerde vlakken +@msg SVG options: {e} SVG-opties: {e} +@msg Save for Web settings: {e} Instellingen van Opslaan voor web: {e} +@msg TIFF colour profile: {e} TIFF-kleurprofiel: {e} +@msg TIFF encoding failed: the pixel buffer doesn't match the image size TIFF-codering mislukt: de pixelbuffer komt niet overeen met de afbeeldingsgrootte +@msg TIFF encoding failed: {e} TIFF-codering mislukt: {e} +@msg Targa depth {_1}: 16, 24 or 32 bits per pixel Targa-diepte {_1}: 16, 24 of 32 bits per pixel +@msg Targa encoding failed: the pixel buffer doesn't match the image size Targa-codering mislukt: de pixelbuffer komt niet overeen met de afbeeldingsgrootte +@msg The 3D projection is not finite De 3D-projectie is niet eindig +@msg The 3D shadow is too complex; turn Shadows off or simplify the art De 3D-schaduw is te complex; zet Schaduwen uit of vereenvoudig de illustratie +@msg The shape contains invalid coordinates De vorm bevat ongeldige coördinaten +@msg Too many Revolve faces for visibility evaluation Te veel vlakken van Draaien om de zichtbaarheid te bepalen +@msg VectorCraft reads at most {ASE_MAX_ENTRIES} colors and groups from a swatch exchange file, and this library has {entries} VectorCraft leest maximaal {ASE_MAX_ENTRIES} kleuren en groepen uit een uitwisselingsbestand voor stalen, en deze bibliotheek heeft er {entries} +@msg WebP encoding failed: {e} WebP-codering mislukt: {e} +@msg [{j}] `{_1}`: {why} [{j}] `{_1}`: {why} +@msg `answers[{i}]` {e} `answers[{i}]` {e} +@msg `index` must be a whole number `index` moet een geheel getal zijn +@msg `view` is smallThumb, mediumThumb, largeThumb, smallList or largeList `view` moet smallThumb, mediumThumb, largeThumb, smallList of largeList zijn +@msg a line can't run from a point to itself een lijn kan niet van een punt naar zichzelf lopen +@msg a line needs at least two points een lijn heeft minstens twee punten nodig +@msg a number cannot be read een getal kan niet worden gelezen +@msg a swatch exchange block is too long een blok van een uitwisselingsbestand voor stalen is te lang +@msg a swatch exchange name is too long een naam in een uitwisselingsbestand voor stalen is te lang +@msg a {sw} × {sh} image can't be resized to {width} × {height} pixels een afbeelding van {sw} × {sh} kan niet worden geschaald naar {width} × {height} pixels +@msg a {width} × {height} image is too large een afbeelding van {width} × {height} is te groot +@msg a {width} × {height} image: {e} een afbeelding van {width} × {height}: {e} +@msg an image could not be written: {e} een afbeelding kon niet worden geschreven: {e} +@msg an image that couldn't be read was left out een afbeelding die niet gelezen kon worden, is weggelaten +@msg can't open “{name}”: {e} kan „{name}” niet openen: {e} +@msg cannot align zip entries to {align} bytes zip-items kunnen niet op {align} bytes worden uitgelijnd +@msg cannot open the automation {kind} root `{_1}`: {e} kan de hoofdmap voor automatisering ({kind}) `{_1}` niet openen: {e} +@msg cannot read profile: {0} kan het profiel niet lezen: {0} +@msg color book version {version} isn't supported (only 1) kleurenboekversie {version} wordt niet ondersteund (alleen 1) +@msg color books in color space {other} aren't supported (only RGB, CMYK and Lab) kleurenboeken in kleurruimte {other} worden niet ondersteund (alleen RGB, CMYK en Lab) +@msg file name too long to zip: {_1} bestandsnaam te lang om te zippen: {_1} +@msg file name too long to zip: {name} bestandsnaam te lang om te zippen: {name} +@msg freeform line {i}: {e} lijn in vrije vorm {i}: {e} +@msg freeform point {i}: {e} punt in vrije vorm {i}: {e} +@msg give `{key}` or `{other}`, not both geef `{key}` of `{other}`, niet beide +@msg grayscale profiles can't be working spaces yet grijswaardenprofielen kunnen nog geen werkruimte zijn +@msg input contains NaN or infinite coordinates de invoer bevat NaN of oneindige coördinaten +@msg input path could not be closed het invoerpad kon niet worden gesloten +@msg invalid ICC profile: {0} ongeldig ICC-profiel: {0} +@msg invalid scale {scale} ongeldige schaal {scale} +@msg its localized names take more than {_1} KB de gelokaliseerde namen ervan nemen meer dan {_1} KB in beslag +@msg its objects are nested too deep ({e}) de objecten ervan zijn te diep genest ({e}) +@msg its tag table lists the `{_1}` tag more than once de tagtabel ervan vermeldt de tag `{_1}` meer dan eens +@msg not a graphic style library: {e} geen bibliotheek met grafische stijlen: {e} +@msg not a swatch library (.vcswatches or .gpl) geen staalbibliotheek (.vcswatches of .gpl) +@msg not a swatch library (format `{_1}`) geen staalbibliotheek (indeling `{_1}`) +@msg not a swatch library: {e} geen staalbibliotheek: {e} +@msg not an action set file ({e}) geen actiesetbestand ({e}) +@msg profile colour space {other} is not RGB, CMYK or Gray profielkleurruimte {other} is geen RGB, CMYK of grijs +@msg regular expression too large reguliere expressie te groot +@msg script file is not UTF-8 text: {value} scriptbestand is geen UTF-8-tekst: {value} +@msg stop {i}: {e} stop {i}: {e} +@msg swatch exchange version {major}.{minor} isn't supported (only 1.x) versie {major}.{minor} van uitwisselingsbestanden voor stalen wordt niet ondersteund (alleen 1.x) +@msg the color book holds more than {ASE_MAX_ENTRIES} colors het kleurenboek bevat meer dan {ASE_MAX_ENTRIES} kleuren +@msg the color book is cut short het kleurenboek is afgebroken +@msg the color book's names take more than {_1} MB de namen in het kleurenboek nemen meer dan {_1} MB in beslag +@msg the image would be {w} × {h} pixels; raster exports are limited to {MAX_RASTER_SIDE} pixels per side and {_1} megapixels: lower the scale or resolution de afbeelding zou {w} × {h} pixels worden; rasterexports zijn beperkt tot {MAX_RASTER_SIDE} pixels per zijde en {_1} megapixels: verlaag de schaal of de resolutie +@msg the optimised image can't be read back: {e} de geoptimaliseerde afbeelding kan niet worden teruggelezen: {e} +@msg the pixel buffer doesn't match the image size de pixelbuffer komt niet overeen met de afbeeldingsgrootte +@msg the preview: {e} de voorvertoning: {e} +@msg the request may not read the New Document profiles folder het verzoek mag de map met profielen voor nieuwe documenten niet lezen +@msg the shapes are too degenerate to combine de vormen zijn te gedegenereerd om te combineren +@msg the shapes cross themselves and each other too often to combine de vormen kruisen zichzelf en elkaar te vaak om te combineren +@msg the swatch exchange file holds more than {ASE_MAX_ENTRIES} colors and groups het uitwisselingsbestand voor stalen bevat meer dan {ASE_MAX_ENTRIES} kleuren en groepen +@msg the swatch exchange file is cut short het uitwisselingsbestand voor stalen is afgebroken +@msg the {_1} plate can't be read: {e} de drukplaat {_1} kan niet worden gelezen: {e} +@msg this binary DXF file is damaged or cut short dit binaire DXF-bestand is beschadigd of afgebroken +@msg this is a DWG drawing, which can't be read: save it from the CAD app as a DXF and open that dit is een DWG-tekening, die niet gelezen kan worden: sla hem in de CAD-app op als DXF en open die +@msg too many classes te veel tekenklassen +@msg too many groups te veel groepen +@msg too many layers for PSD (at most 32767) te veel lagen voor PSD (maximaal 32767) +@msg too many swatch exchange blocks te veel blokken in het uitwisselingsbestand voor stalen +@msg unknown colour profile: {0} onbekend kleurprofiel: {0} +@msg {_1} clashes with a built-in profile name {_1} botst met een ingebouwde profielnaam +@msg {_1} × {_2} pixels is too large for GIF (at most 65535 pixels a side): lower the resolution {_1} × {_2} pixels is te groot voor GIF (maximaal 65535 pixels per zijde): verlaag de resolutie +@msg {_1}: no usable transform to/from sRGB {_1}: geen bruikbare transformatie van of naar sRGB +@msg {name} is not a CMYK profile {name} is geen CMYK-profiel +@msg {name} is not an RGB profile {name} is geen RGB-profiel +@msg {path}: could not be read {path}: kon niet worden gelezen +@msg {width} × {height} pixels is too large for JPEG (at most 65535 pixels a side): lower the resolution {width} × {height} pixels is te groot voor JPEG (maximaal 65535 pixels per zijde): verlaag de resolutie +@msg {width} × {height} pixels is too large for Targa (at most 65535 pixels a side): lower the resolution {width} × {height} pixels is te groot voor Targa (maximaal 65535 pixels per zijde): verlaag de resolutie +@msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} pixels is te groot voor PSD (maximaal {MAX_SIDE} pixels per zijde): verlaag de resolutie diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 1c49a7327a..66a2c432d6 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -387,6 +387,18 @@ Title Case Jak W Tytule Sentence case Jak w zdaniu Smart Punctuation… Inteligentna interpunkcja… + Smart Punctuation Inteligentna interpunkcja + ff, fi, ffi Ligatures Ligatury ff, fi, ffi + ff, fl, ffl Ligatures Ligatury ff, fl, ffl + Smart Quotes Inteligentne cudzysłowy + Smart Spaces Inteligentne spacje + En, Em Dashes Półpauzy i pauzy + Ellipses Wielokropki + Expert Fractions Ułamki eksperckie + Replace In Zastąp w + Selected Text Only Tylko zaznaczony tekst + Entire Document Cały dokument + Report Results Raportuj wyniki Create Outlines Utwórz kontury Optical Margin Alignment Optyczne wyrównanie marginesów Dynamic Text Tekst dynamiczny @@ -919,6 +931,7 @@ Free Transform Swobodne przekształcanie Perspective Distort Zniekształcenie perspektywiczne Radial Blur… Rozmycie promieniste… + Blur Center Środek rozmycia Smart Blur… Inteligentne rozmycie… Sharpen Wyostrzanie Unsharp Mask… Maska wyostrzająca… @@ -1642,6 +1655,9 @@ digits Malayalam Malajalam The selected character's font is not available. Czcionka zaznaczonego znaku jest niedostępna. No alternates for the selected character. Brak alternatyw dla zaznaczonego znaku. Double-click to replace Kliknij dwukrotnie, aby zastąpić + Click to replace Kliknij, aby zastąpić + Show all alternates in the Glyphs panel Pokaż wszystkie alternatywy w panelu Glify + Show Character Alternates Pokaż alternatywy znaku Select one character with the Type tool first. Najpierw zaznacz jeden znak narzędziem Tekst. {glyph} is a glyph of {font}, not of the font the selected text is set in ({text_font}). {glyph} to glif czcionki {font}, a nie czcionki zaznaczonego tekstu ({text_font}). {glyph} belongs to {base} (U+{base_code}) {place}; your selection is {sel} (U+{code}). {glyph} należy do znaku {base} (U+{base_code}) {place}; Twoje zaznaczenie to {sel} (U+{code}). @@ -2196,6 +2212,7 @@ digits Malayalam Malajalam @msg paths entry {i} needs path and ids (object ids no other entry has) wpis {i} w paths wymaga path i ids (identyfikatorów obiektów, których nie ma żaden inny wpis) @msg scope missingInFolder takes path: the folder of that file is searched for the other missing links scope missingInFolder przyjmuje path: w folderze tego pliku szukane są pozostałe brakujące łącza Show Missing Pokaż brakujące + Sort by Size Sortuj według rozmiaru Sort by Status Sortuj według stanu Clear Overrides Wyczyść zastąpienia Create New {kind} Style Utwórz nowy styl: {kind} @@ -2448,6 +2465,7 @@ digits Malayalam Malajalam Export Asset Eksportuj zasób Export to: Eksportuj do: Format Settings Ustawienia formatu + Format Settings… Ustawienia formatu… Formats: Formaty: Full Document Cały dokument Include Bleed Uwzględnij spad @@ -2548,6 +2566,7 @@ digits Malayalam Malajalam e.g. 1-3, 5 np. 1-3, 5 First Page Pierwsza strona Import PDF Importuj PDF + Import PDF pages as links Importuj strony PDF jako łącza Last Page Ostatnia strona Next Page Następna strona of {count} z {count} @@ -2629,6 +2648,7 @@ digits Malayalam Malajalam Transparent Background Przezroczyste tło Choose… Wybierz… Copy Fonts Used in the Document Kopiuj czcionki użyte w dokumencie + Copy Info Kopiuj informacje Copy Links Kopiuj łącza Create Report Utwórz raport Fonts whose licence doesn't allow embedding are not copied. Czcionki, których licencja nie zezwala na osadzanie, nie są kopiowane. @@ -4509,6 +4529,7 @@ imageTrace Outline Kontur @msg there is no script engine named {name} nie ma silnika skryptów o nazwie {name} @msg Running a script Uruchamianie skryptu @msg Copied the script report Skopiowano raport skryptu +@msg Copied the link info Skopiowano informacje o łączu @msg Corners edits the corners of a path Narożniki edytuje narożniki ścieżki @msg Couldn't copy to the system clipboard: {e} Nie udało się skopiować do schowka systemowego: {e} @msg Couldn't open {name}: {e} Nie udało się otworzyć {name}: {e} @@ -6529,7 +6550,7 @@ axis Y Axis Oś Y @plural Result: {n}|Results: {n} Wynik: {n}|Wyniki: {n}|Wyniki: {n} @msg select one object zaznacz jeden obiekt @msg Global Edit works on paths, compound paths, symbol instances and groups of them Edycja globalna działa na ścieżkach, ścieżkach złożonych, wystąpieniach symboli i ich grupach -@msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again nie znaleziono podobnych obiektów (obrócone i odbite kopie nie są dopasowywane); zmień opcje edycji globalnej i spróbuj ponownie +@msg no similar objects found (reflected copies are not matched); change the Global Edit Options and try again nie znaleziono podobnych obiektów (odbite kopie nie są dopasowywane); zmień opcje edycji globalnej i spróbuj ponownie @msg Global Edit is off Edycja globalna jest wyłączona @msg only an object of the Global Edit other than the one it started from can be left out z edycji globalnej można wykluczyć tylko obiekt inny niż ten, od którego się zaczęła @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all lub zakres, np. 1, 3-5, a nie {v} @@ -7324,11 +7345,20 @@ breakText Glyphs Glify Open Tutorial Sample Otwórz przykład samouczka Finish Tutorial Zakończ samouczek Next Tutorial Następny samouczek + Show Learn Tab Pokaż kartę panelu Nauka + Show Skill Pokaż umiejętność + Back One Level Wróć o jeden poziom Back to Skills Powrót do umiejętności @msg tutorial `{id}` has no practice sample samouczek `{id}` nie ma przykładu do ćwiczeń @msg open the practice sample of `{id}` first (see learn.openSample) najpierw otwórz przykład do ćwiczeń samouczka `{id}` (patrz learn.openSample) @msg finish `{id}` first (see learn.finish) najpierw zakończ `{id}` (patrz learn.finish) @msg `{id}` is the last tutorial in its skill `{id}` to ostatni samouczek swojej umiejętności + Reset progress Resetuj postępy + Mark Tutorial Step Oznacz krok samouczka + Reset Learn Progress Resetuj postępy nauki +@msg missing `step` (see learn.show) brak `step` (patrz learn.show) +@msg `step` must be a step number from 0 to {last} `step` musi być numerem kroku od 0 do {last} +@msg `{id}` is finished (see learn.resetProgress) `{id}` jest zakończony (patrz learn.resetProgress) # Deferred plug-in effects Refresh Deferred Effects Odśwież odroczone efekty @@ -8856,6 +8886,8 @@ breakText Glyphs Glify @msg the RTF file is too large to place as type (at most {_1} MB) plik RTF jest zbyt duży, aby umieścić go jako tekst (najwyżej {_1} MB) @msg the SVG expands to more than {0} nested SVG images SVG rozwija się do ponad {0} zagnieżdżonych obrazów SVG @msg the SVG expands to more than {0} objects SVG rozwija się do ponad {0} obiektów +@msg the SVG's style sheets take too long to match dopasowanie arkuszy stylów SVG trwa zbyt długo +@msg the SVG's styles expand to more than {0} MB style SVG rozwijają się do ponad {0} MB @msg the SVG has no drawable objects SVG nie zawiera obiektów, które można narysować @msg the SVGZ file unpacks to more than {_1} MB plik SVGZ po rozpakowaniu ma ponad {_1} MB @msg the Word document has more than {MAX_PAGES} pages of properties, too many to place dokument Word ma ponad {MAX_PAGES} stron właściwości, zbyt wiele, aby go umieścić @@ -9168,3 +9200,122 @@ breakText Glyphs Glify @msg {what} can't be intertwined {what} nie można przeplatać @msg {what} doesn't fit the paper with its bleed and marks {what} nie mieści się na papierze wraz ze spadem i znacznikami @msg {what} would print on more than {MAX_TILES} tiles: scale it down {what}: wydruk zająłby ponad {MAX_TILES} kafelków: zmniejsz skalę + Nest Shapes… Rozmieść kształty… + Nest Shapes Rozmieść kształty + Roll Rolka + +# Messages of the effects, 3D, image export, color profiles, swatch exchange files, color books and DXF import. +@msg 3D effects require finite coordinates within 100 million points Efekty 3D wymagają skończonych współrzędnych w zakresie 100 milionów punktów +@msg 3D effects require one to ten lights Efekty 3D wymagają od jednego do dziesięciu świateł +@msg BMP depth {_1}: 1, 4, 8, 16, 24 or 32 bits per pixel Głębia BMP {_1}: 1, 4, 8, 16, 24 lub 32 bity na piksel +@msg BMP encoding failed: {width} × {height} pixels doesn't fit the format or the pixel buffer Kodowanie BMP nie powiodło się: {width} × {height} pikseli nie mieści się w formacie ani w buforze pikseli +@msg GIF encoding failed: the palette image is malformed Kodowanie GIF nie powiodło się: obraz z paletą jest nieprawidłowy +@msg GIF encoding failed: {e} Kodowanie GIF nie powiodło się: {e} +@msg JPEG colour profile: {e} Profil kolorów JPEG: {e} +@msg JPEG encoding failed: pixel buffer doesn't match the image size Kodowanie JPEG nie powiodło się: bufor pikseli nie odpowiada rozmiarowi obrazu +@msg JPEG encoding failed: {e} Kodowanie JPEG nie powiodło się: {e} +@msg PNG encoding failed: pixel buffer doesn't match the image size Kodowanie PNG nie powiodło się: bufor pikseli nie odpowiada rozmiarowi obrazu +@msg PNG encoding failed: the palette image is malformed Kodowanie PNG nie powiodło się: obraz z paletą jest nieprawidłowy +@msg PNG encoding failed: {e} Kodowanie PNG nie powiodło się: {e} +@msg PNG encoding failed: {width} × {height} pixels is not a valid image size Kodowanie PNG nie powiodło się: {width} × {height} pikseli to nieprawidłowy rozmiar obrazu +@msg PSD colour profile: {e} Profil kolorów PSD: {e} +@msg PSD encoding failed: the pixel buffer doesn't match the image size Kodowanie PSD nie powiodło się: bufor pikseli nie odpowiada rozmiarowi obrazu +@msg Revolve profile contains invalid coordinates Profil efektu Obrót zawiera nieprawidłowe współrzędne +@msg Revolve profile is too complex Profil efektu Obrót jest zbyt złożony +@msg Revolve projection is not finite Rzut efektu Obrót nie jest skończony +@msg Revolve requires finite profile coordinates within 100 million points Efekt Obrót wymaga skończonych współrzędnych profilu w zakresie 100 milionów punktów +@msg Revolve surface is too complex; reduce Segments or simplify the profile Powierzchnia efektu Obrót jest zbyt złożona; zmniejsz Segmenty lub uprość profil +@msg Revolve surface is too complex; simplify the profile Powierzchnia efektu Obrót jest zbyt złożona; uprość profil +@msg Revolve visibility cannot split the projected boundary Obliczanie widoczności efektu Obrót nie może podzielić rzutowanej granicy +@msg Revolve visibility creates too many fragments Obliczanie widoczności efektu Obrót tworzy zbyt wiele fragmentów +@msg Revolve visibility creates too many vector anchors Obliczanie widoczności efektu Obrót tworzy zbyt wiele wektorowych punktów kontrolnych +@msg Revolve visibility exceeds its geometry work limit Obliczanie widoczności efektu Obrót przekracza swój limit obliczeń geometrycznych +@msg Revolve visibility exceeds its spatial index limit Obliczanie widoczności efektu Obrót przekracza swój limit indeksu przestrzennego +@msg Revolve visibility has too many boundary crossings Obliczanie widoczności efektu Obrót napotyka zbyt wiele przecięć granicy +@msg Revolve visibility has too many input anchors Obliczanie widoczności efektu Obrót otrzymuje zbyt wiele wejściowych punktów kontrolnych +@msg Revolve visibility requires convex cap sectors Obliczanie widoczności efektu Obrót wymaga wypukłych sektorów zakończenia +@msg Revolve visibility requires finite projected faces Obliczanie widoczności efektu Obrót wymaga skończonych rzutowanych ścian +@msg SVG options: {e} Opcje SVG: {e} +@msg Save for Web settings: {e} Ustawienia Zapisz dla Internetu: {e} +@msg TIFF colour profile: {e} Profil kolorów TIFF: {e} +@msg TIFF encoding failed: the pixel buffer doesn't match the image size Kodowanie TIFF nie powiodło się: bufor pikseli nie odpowiada rozmiarowi obrazu +@msg TIFF encoding failed: {e} Kodowanie TIFF nie powiodło się: {e} +@msg Targa depth {_1}: 16, 24 or 32 bits per pixel Głębia Targa {_1}: 16, 24 lub 32 bity na piksel +@msg Targa encoding failed: the pixel buffer doesn't match the image size Kodowanie Targa nie powiodło się: bufor pikseli nie odpowiada rozmiarowi obrazu +@msg The 3D projection is not finite Rzut 3D nie jest skończony +@msg The 3D shadow is too complex; turn Shadows off or simplify the art Cień 3D jest zbyt złożony; wyłącz Cienie lub uprość grafikę +@msg The shape contains invalid coordinates Kształt zawiera nieprawidłowe współrzędne +@msg Too many Revolve faces for visibility evaluation Zbyt wiele ścian efektu Obrót do obliczenia widoczności +@msg VectorCraft reads at most {ASE_MAX_ENTRIES} colors and groups from a swatch exchange file, and this library has {entries} VectorCraft odczytuje z pliku wymiany próbek najwyżej {ASE_MAX_ENTRIES} kolorów i grup, a ta biblioteka ma ich {entries} +@msg WebP encoding failed: {e} Kodowanie WebP nie powiodło się: {e} +@msg [{j}] `{_1}`: {why} [{j}] `{_1}`: {why} +@msg `answers[{i}]` {e} `answers[{i}]` {e} +@msg `view` is smallThumb, mediumThumb, largeThumb, smallList or largeList `view` ma wartość smallThumb, mediumThumb, largeThumb, smallList lub largeList +@msg a line can't run from a point to itself linia nie może prowadzić od punktu do niego samego +@msg a line needs at least two points linia wymaga co najmniej dwóch punktów +@msg a number cannot be read nie można odczytać liczby +@msg a swatch exchange block is too long blok pliku wymiany próbek jest zbyt długi +@msg a swatch exchange name is too long nazwa w pliku wymiany próbek jest zbyt długa +@msg a {sw} × {sh} image can't be resized to {width} × {height} pixels nie można zmienić rozmiaru obrazu {sw} × {sh} na {width} × {height} pikseli +@msg a {width} × {height} image is too large obraz {width} × {height} jest zbyt duży +@msg a {width} × {height} image: {e} obraz {width} × {height}: {e} +@msg an image could not be written: {e} nie udało się zapisać obrazu: {e} +@msg an image that couldn't be read was left out pominięto obraz, którego nie udało się odczytać +@msg can't open “{name}”: {e} nie można otworzyć „{name}”: {e} +@msg cannot align zip entries to {align} bytes nie można wyrównać wpisów zip do {align} bajtów +@msg cannot open the automation {kind} root `{_1}`: {e} nie można otworzyć katalogu głównego automatyzacji ({kind}) `{_1}`: {e} +@msg cannot read profile: {0} nie można odczytać profilu: {0} +@msg color book version {version} isn't supported (only 1) wersja księgi kolorów {version} nie jest obsługiwana (tylko 1) +@msg color books in color space {other} aren't supported (only RGB, CMYK and Lab) księgi kolorów w przestrzeni kolorów {other} nie są obsługiwane (tylko RGB, CMYK i Lab) +@msg file name too long to zip: {_1} nazwa pliku jest zbyt długa dla archiwum zip: {_1} +@msg file name too long to zip: {name} nazwa pliku jest zbyt długa dla archiwum zip: {name} +@msg freeform line {i}: {e} dowolna linia {i}: {e} +@msg freeform point {i}: {e} dowolny punkt {i}: {e} +@msg give `{key}` or `{other}`, not both podaj `{key}` lub `{other}`, nie oba naraz +@msg grayscale profiles can't be working spaces yet profile w skali szarości nie mogą jeszcze być przestrzeniami roboczymi +@msg input contains NaN or infinite coordinates dane wejściowe zawierają współrzędne NaN lub nieskończone +@msg input path could not be closed nie udało się zamknąć ścieżki wejściowej +@msg invalid ICC profile: {0} nieprawidłowy profil ICC: {0} +@msg invalid scale {scale} nieprawidłowa skala {scale} +@msg its localized names take more than {_1} KB jego zlokalizowane nazwy zajmują ponad {_1} KB +@msg its objects are nested too deep ({e}) jego obiekty są zagnieżdżone zbyt głęboko ({e}) +@msg its tag table lists the `{_1}` tag more than once jego tablica znaczników wymienia znacznik `{_1}` więcej niż raz +@msg not a graphic style library: {e} to nie jest biblioteka stylów graficznych: {e} +@msg not a swatch library (.vcswatches or .gpl) to nie jest biblioteka próbek (.vcswatches lub .gpl) +@msg not a swatch library (format `{_1}`) to nie jest biblioteka próbek (format `{_1}`) +@msg not a swatch library: {e} to nie jest biblioteka próbek: {e} +@msg not an action set file ({e}) to nie jest plik zestawu operacji ({e}) +@msg profile colour space {other} is not RGB, CMYK or Gray przestrzeń kolorów profilu {other} nie jest RGB, CMYK ani skalą szarości +@msg regular expression too large wyrażenie regularne jest zbyt duże +@msg script file is not UTF-8 text: {value} plik skryptu nie jest tekstem UTF-8: {value} +@msg stop {i}: {e} punkt koloru {i}: {e} +@msg swatch exchange version {major}.{minor} isn't supported (only 1.x) wersja pliku wymiany próbek {major}.{minor} nie jest obsługiwana (tylko 1.x) +@msg the color book holds more than {ASE_MAX_ENTRIES} colors księga kolorów zawiera ponad {ASE_MAX_ENTRIES} kolorów +@msg the color book is cut short księga kolorów jest ucięta +@msg the color book's names take more than {_1} MB nazwy w księdze kolorów zajmują ponad {_1} MB +@msg the image would be {w} × {h} pixels; raster exports are limited to {MAX_RASTER_SIDE} pixels per side and {_1} megapixels: lower the scale or resolution obraz miałby {w} × {h} pikseli; eksport rastrowy jest ograniczony do {MAX_RASTER_SIDE} pikseli na bok i {_1} megapikseli: zmniejsz skalę lub rozdzielczość +@msg the optimised image can't be read back: {e} nie można ponownie odczytać zoptymalizowanego obrazu: {e} +@msg the pixel buffer doesn't match the image size bufor pikseli nie odpowiada rozmiarowi obrazu +@msg the preview: {e} podgląd: {e} +@msg the request may not read the New Document profiles folder żądanie nie ma uprawnień do odczytu folderu profili nowego dokumentu +@msg the shapes are too degenerate to combine kształty są zbyt zdegenerowane, aby je połączyć +@msg the shapes cross themselves and each other too often to combine kształty zbyt często przecinają same siebie i siebie nawzajem, aby je połączyć +@msg the swatch exchange file holds more than {ASE_MAX_ENTRIES} colors and groups plik wymiany próbek zawiera ponad {ASE_MAX_ENTRIES} kolorów i grup +@msg the swatch exchange file is cut short plik wymiany próbek jest ucięty +@msg the {_1} plate can't be read: {e} nie można odczytać płyty {_1}: {e} +@msg this binary DXF file is damaged or cut short ten binarny plik DXF jest uszkodzony lub ucięty +@msg this is a DWG drawing, which can't be read: save it from the CAD app as a DXF and open that to rysunek DWG, którego nie można odczytać: zapisz go w programie CAD jako DXF i otwórz ten plik +@msg too many classes zbyt wiele klas +@msg too many groups zbyt wiele grup +@msg too many layers for PSD (at most 32767) zbyt wiele warstw dla formatu PSD (najwyżej 32767) +@msg too many swatch exchange blocks zbyt wiele bloków pliku wymiany próbek +@msg unknown colour profile: {0} nieznany profil kolorów: {0} +@msg {_1} clashes with a built-in profile name {_1} koliduje z nazwą wbudowanego profilu +@msg {_1} × {_2} pixels is too large for GIF (at most 65535 pixels a side): lower the resolution {_1} × {_2} pikseli to za dużo dla formatu GIF (najwyżej 65535 pikseli na bok): zmniejsz rozdzielczość +@msg {_1}: no usable transform to/from sRGB {_1}: brak użytecznej transformacji do lub z sRGB +@msg {name} is not a CMYK profile {name} nie jest profilem CMYK +@msg {name} is not an RGB profile {name} nie jest profilem RGB +@msg {path}: could not be read {path}: nie udało się odczytać +@msg {width} × {height} pixels is too large for JPEG (at most 65535 pixels a side): lower the resolution {width} × {height} pikseli to za dużo dla formatu JPEG (najwyżej 65535 pikseli na bok): zmniejsz rozdzielczość +@msg {width} × {height} pixels is too large for Targa (at most 65535 pixels a side): lower the resolution {width} × {height} pikseli to za dużo dla formatu Targa (najwyżej 65535 pikseli na bok): zmniejsz rozdzielczość +@msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} pikseli to za dużo dla formatu PSD (najwyżej {MAX_SIDE} pikseli na bok): zmniejsz rozdzielczość diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 12647b2884..913cb4089a 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -814,6 +814,9 @@ antiAlias Sharp Nítido The selected character's font is not available. A fonte do caractere selecionado não está disponível. No alternates for the selected character. Nenhuma alternativa para o caractere selecionado. Double-click to replace Clique duplo para substituir + Click to replace Clique para substituir + Show all alternates in the Glyphs panel Mostrar todas as alternativas no painel Glifos + Show Character Alternates Mostrar Alternativas de Caractere Select one character with the Type tool first. Primeiro selecione um caractere com a ferramenta Texto. {glyph} is a glyph of {font}, not of the font the selected text is set in ({text_font}). {glyph} é um glifo de {font}, não da fonte do texto selecionado ({text_font}). {glyph} belongs to {base} (U+{base_code}) {place}; your selection is {sel} (U+{code}). {glyph} pertence a {base} (U+{base_code}) {place}; sua seleção é {sel} (U+{code}). @@ -1200,6 +1203,7 @@ antiAlias Sharp Nítido Format Formato Format Options Opções de Formato Format Settings Configurações de Formato + Format Settings… Configurações de Formato… Format: Formato: Formats: Formatos: Fractions Frações @@ -1483,6 +1487,7 @@ antiAlias Sharp Nítido Import Keyboard Shortcuts… Importar Atalhos de Teclado… Import Data Sets… Importar Conjuntos de Dados… Import PDF Importar PDF + Import PDF pages as links Importar páginas do PDF como links Import PDF Presets Importar Predefinidos de PDF Import Perspective Grid Presets Importar Predefinidos de Grade de Perspectiva Import Print Presets Importar Predefinidos de Impressão @@ -2394,8 +2399,8 @@ digits Malayalam Malaiala Release Opacity Mask Liberar Máscara de Opacidade Release Selection Liberar Seleção Release with Perspective Liberar com Perspectiva - Relink Revinculcar - Relink to Folder… Revinculcar Pasta… + Relink Revincular + Relink to Folder… Revincular Pasta… Each Link Separately Cada Vínculo Separadamente Selected Instances Instâncias Selecionadas All Instances Todas as Instâncias @@ -2404,7 +2409,7 @@ digits Malayalam Malaiala @msg scope each and paths go together: paths lists entries of ids and path, in place of ids, path and folder scope each e paths andam juntos: paths lista entradas com ids e path, no lugar de ids, path e folder @msg paths entry {i} needs path and ids (object ids no other entry has) a entrada {i} de paths precisa de path e ids (ids de objeto que nenhuma outra entrada tenha) @msg scope missingInFolder takes path: the folder of that file is searched for the other missing links scope missingInFolder recebe path: os outros vínculos ausentes são procurados na pasta desse arquivo - Relink… Revinculcar… + Relink… Revincular… Reload Plug-ins Recarregar Plug-ins Remove Remover Remove Anchor Points Remover Pontos de Ancoragem @@ -2909,6 +2914,18 @@ digits Malayalam Malaiala Smart Guides (View → Smart Guides) Guias Inteligentes (Exibir → Guias Inteligentes) Smart Guides (⌘U) Guias Inteligentes (⌘U) Smart Punctuation… Pontuação Inteligente… + Smart Punctuation Pontuação Inteligente + ff, fi, ffi Ligatures Ligações ff, fi, ffi + ff, fl, ffl Ligatures Ligações ff, fl, ffl + Smart Quotes Aspas Inteligentes + Smart Spaces Espaços Inteligentes + En, Em Dashes Travessões En e Em + Ellipses Reticências + Expert Fractions Frações Especiais + Replace In Substituir Em + Selected Text Only Somente Texto Selecionado + Entire Document Documento Inteiro + Report Results Relatar Resultados Smooth Suavizar Smooth Tool Ferramenta Suavizar Snap Curves To Lines Ajustar Curvas às Linhas @@ -3469,6 +3486,7 @@ imageTrace Outline Contorno Free Transform Transformação Livre Perspective Distort Distorção de Perspectiva Radial Blur… Desfoque Radial… + Blur Center Centro do Desfoque Smart Blur… Desfoque Inteligente… Sharpen Nitidez Unsharp Mask… Máscara de Nitidez… @@ -3963,10 +3981,10 @@ axis Both Ambos @msg `{k}` must be [x, y] `{k}` deve ser [x, y] @msg `{name}` has no options `{name}` não tem opções @msg `{name}` is a built-in workspace; choose another name `{name}` é um espaço de trabalho integrado; escolha outro nome -@msg `{name}` is a process colour: tints apply to global and spot colours `{name}` é uma cor de seleção: os matizes se aplicam a cores globais e especiais +@msg `{name}` is a process colour: tints apply to global and spot colours `{name}` é uma cor de processo: os matizes se aplicam a cores globais e especiais @msg `{name}` is no recovery entry name `{name}` não é o nome de uma entrada de recuperação @msg `{name}` isn't a colour swatch `{name}` não é uma amostra de cor -@msg a process color can't colorize a grayscale image with transparency: use a spot color, black or white uma cor de seleção não pode colorir uma imagem em escala de cinza com transparência: use uma cor especial, preto ou branco +@msg a process color can't colorize a grayscale image with transparency: use a spot color, black or white uma cor de processo não pode colorir uma imagem em escala de cinza com transparência: use uma cor especial, preto ou branco @msg `{path}` must be a bool or an object of bools `{path}` deve ser um booleano ou um objeto de booleanos @msg `{s}` is not a colour (#rrggbb or a preset name) `{s}` não é uma cor (#rrggbb ou o nome de uma predefinição) @msg `{tool}` isn't a Liquify tool `{tool}` não é uma ferramenta de Liquidificar @@ -4889,6 +4907,7 @@ axis Both Ambos Convert To Outlines Converter em Contornos Copy All Objects Copiar Todos os Objetos Copy Fonts Used in the Document Copiar Fontes Usadas no Documento + Copy Info Copiar Informações Copy Links Copiar Links Descender Descendente Flip Virar @@ -5201,6 +5220,7 @@ axis Both Ambos Corner Canto Smooth Color Cor Suave Social Square Post 1080×1080 Post Social Quadrado 1080×1080 + Sort by Size Ordenar por Tamanho Sort by Status Ordenar por Status Source Sans 3 Source Sans 3 Specified Distance Distância Especificada @@ -5407,6 +5427,7 @@ axis Both Ambos @msg there is no script engine named {name} não há nenhum mecanismo de script chamado {name} @msg Running a script Executando um script @msg Copied the script report Relatório do script copiado +@msg Copied the link info Informações do link copiadas @msg This shortcut file is in a form VectorCraft can't read. Este arquivo de atalhos está em um formato que o VectorCraft não consegue ler. @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` axis deve ser "vertical", "horizontal" ou um ângulo em graus, não `{v}` @msg give corners of the path: anchors where its sides meet at an angle informe os cantos do caminho: pontos de ancoragem onde os lados se encontram em ângulo @@ -6589,7 +6610,7 @@ axis Y Axis Eixo Y @plural Result: {n}|Results: {n} Resultado: {n}|Resultados: {n} @msg select one object selecione um objeto @msg Global Edit works on paths, compound paths, symbol instances and groups of them A edição global funciona com demarcadores, demarcadores compostos, instâncias de símbolos e grupos deles -@msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again nenhum objeto semelhante encontrado (cópias giradas ou refletidas não são correspondidas); altere as opções de edição global e tente novamente +@msg no similar objects found (reflected copies are not matched); change the Global Edit Options and try again nenhum objeto semelhante encontrado (cópias refletidas não são correspondidas); altere as opções de edição global e tente novamente @msg Global Edit is off A edição global está desativada @msg only an object of the Global Edit other than the one it started from can be left out só é possível deixar fora da edição global um objeto diferente daquele com que ela começou @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all ou um intervalo como 1, 3-5, não {v} @@ -7051,6 +7072,122 @@ breakText Glyphs Glifos @msg save the document with Save As before Save and Close salve o documento com Salvar Como antes de Salvar e fechar @msg no free data set file name in destination folder Não há nome de arquivo livre para o conjunto de dados na pasta de destino +# Messages of the effects, 3D, image export, color profiles, swatch exchange files, color books and DXF import. +@msg 3D effects require finite coordinates within 100 million points Os efeitos 3D exigem coordenadas finitas de até 100 milhões de pontos +@msg 3D effects require one to ten lights Os efeitos 3D exigem de uma a dez luzes +@msg BMP depth {_1}: 1, 4, 8, 16, 24 or 32 bits per pixel Profundidade BMP {_1}: 1, 4, 8, 16, 24 ou 32 bits por pixel +@msg BMP encoding failed: {width} × {height} pixels doesn't fit the format or the pixel buffer Falha na codificação BMP: {width} × {height} pixels não cabem no formato ou no buffer de pixels +@msg GIF encoding failed: the palette image is malformed Falha na codificação GIF: a imagem de paleta está malformada +@msg GIF encoding failed: {e} Falha na codificação GIF: {e} +@msg JPEG colour profile: {e} Perfil de cor JPEG: {e} +@msg JPEG encoding failed: pixel buffer doesn't match the image size Falha na codificação JPEG: o buffer de pixels não corresponde ao tamanho da imagem +@msg JPEG encoding failed: {e} Falha na codificação JPEG: {e} +@msg PNG encoding failed: pixel buffer doesn't match the image size Falha na codificação PNG: o buffer de pixels não corresponde ao tamanho da imagem +@msg PNG encoding failed: the palette image is malformed Falha na codificação PNG: a imagem de paleta está malformada +@msg PNG encoding failed: {e} Falha na codificação PNG: {e} +@msg PNG encoding failed: {width} × {height} pixels is not a valid image size Falha na codificação PNG: {width} × {height} pixels não é um tamanho de imagem válido +@msg PSD colour profile: {e} Perfil de cor PSD: {e} +@msg PSD encoding failed: the pixel buffer doesn't match the image size Falha na codificação PSD: o buffer de pixels não corresponde ao tamanho da imagem +@msg Revolve profile contains invalid coordinates O perfil de Revolver contém coordenadas inválidas +@msg Revolve profile is too complex O perfil de Revolver é complexo demais +@msg Revolve projection is not finite A projeção de Revolver não é finita +@msg Revolve requires finite profile coordinates within 100 million points Revolver exige coordenadas de perfil finitas de até 100 milhões de pontos +@msg Revolve surface is too complex; reduce Segments or simplify the profile A superfície de Revolver é complexa demais; reduza Segmentos ou simplifique o perfil +@msg Revolve surface is too complex; simplify the profile A superfície de Revolver é complexa demais; simplifique o perfil +@msg Revolve visibility cannot split the projected boundary A visibilidade de Revolver não consegue dividir o contorno projetado +@msg Revolve visibility creates too many fragments A visibilidade de Revolver cria fragmentos demais +@msg Revolve visibility creates too many vector anchors A visibilidade de Revolver cria pontos de ancoragem vetoriais demais +@msg Revolve visibility exceeds its geometry work limit A visibilidade de Revolver excede seu limite de trabalho geométrico +@msg Revolve visibility exceeds its spatial index limit A visibilidade de Revolver excede seu limite de índice espacial +@msg Revolve visibility has too many boundary crossings A visibilidade de Revolver tem cruzamentos de contorno demais +@msg Revolve visibility has too many input anchors A visibilidade de Revolver tem pontos de ancoragem de entrada demais +@msg Revolve visibility requires convex cap sectors A visibilidade de Revolver exige setores de tampa convexos +@msg Revolve visibility requires finite projected faces A visibilidade de Revolver exige faces projetadas finitas +@msg SVG options: {e} Opções SVG: {e} +@msg Save for Web settings: {e} Configurações de Salvar para a Web: {e} +@msg TIFF colour profile: {e} Perfil de cor TIFF: {e} +@msg TIFF encoding failed: the pixel buffer doesn't match the image size Falha na codificação TIFF: o buffer de pixels não corresponde ao tamanho da imagem +@msg TIFF encoding failed: {e} Falha na codificação TIFF: {e} +@msg Targa depth {_1}: 16, 24 or 32 bits per pixel Profundidade Targa {_1}: 16, 24 ou 32 bits por pixel +@msg Targa encoding failed: the pixel buffer doesn't match the image size Falha na codificação Targa: o buffer de pixels não corresponde ao tamanho da imagem +@msg The 3D projection is not finite A projeção 3D não é finita +@msg The 3D shadow is too complex; turn Shadows off or simplify the art A sombra 3D é complexa demais; desative Sombras ou simplifique a arte +@msg The shape contains invalid coordinates A forma contém coordenadas inválidas +@msg Too many Revolve faces for visibility evaluation Faces de Revolver demais para avaliar a visibilidade +@msg VectorCraft reads at most {ASE_MAX_ENTRIES} colors and groups from a swatch exchange file, and this library has {entries} O VectorCraft lê no máximo {ASE_MAX_ENTRIES} cores e grupos de um arquivo de intercâmbio de amostras, e esta biblioteca tem {entries} +@msg WebP encoding failed: {e} Falha na codificação WebP: {e} +@msg [{j}] `{_1}`: {why} [{j}] `{_1}`: {why} +@msg `answers[{i}]` {e} `answers[{i}]` {e} +@msg `view` is smallThumb, mediumThumb, largeThumb, smallList or largeList `view` é smallThumb, mediumThumb, largeThumb, smallList ou largeList +@msg a line can't run from a point to itself uma linha não pode ir de um ponto até ele mesmo +@msg a line needs at least two points uma linha precisa de pelo menos dois pontos +@msg a number cannot be read um número não pode ser lido +@msg a swatch exchange block is too long um bloco de intercâmbio de amostras é longo demais +@msg a swatch exchange name is too long um nome de intercâmbio de amostras é longo demais +@msg a {sw} × {sh} image can't be resized to {width} × {height} pixels uma imagem de {sw} × {sh} não pode ser redimensionada para {width} × {height} pixels +@msg a {width} × {height} image is too large uma imagem de {width} × {height} é grande demais +@msg a {width} × {height} image: {e} uma imagem de {width} × {height}: {e} +@msg an image could not be written: {e} não foi possível gravar uma imagem: {e} +@msg an image that couldn't be read was left out uma imagem que não pôde ser lida foi omitida +@msg can't open “{name}”: {e} não é possível abrir “{name}”: {e} +@msg cannot align zip entries to {align} bytes não é possível alinhar as entradas do zip a {align} bytes +@msg cannot open the automation {kind} root `{_1}`: {e} não é possível abrir a raiz de {kind} da automação `{_1}`: {e} +@msg cannot read profile: {0} não é possível ler o perfil: {0} +@msg color book version {version} isn't supported (only 1) a versão {version} do livro de cores não tem suporte (somente 1) +@msg color books in color space {other} aren't supported (only RGB, CMYK and Lab) livros de cores no espaço de cores {other} não têm suporte (somente RGB, CMYK e Lab) +@msg file name too long to zip: {_1} nome de arquivo longo demais para o zip: {_1} +@msg file name too long to zip: {name} nome de arquivo longo demais para o zip: {name} +@msg freeform line {i}: {e} linha {i} de forma livre: {e} +@msg freeform point {i}: {e} ponto {i} de forma livre: {e} +@msg give `{key}` or `{other}`, not both informe `{key}` ou `{other}`, não ambos +@msg grayscale profiles can't be working spaces yet perfis em escala de cinza ainda não podem ser espaços de trabalho de cores +@msg input contains NaN or infinite coordinates a entrada contém coordenadas NaN ou infinitas +@msg input path could not be closed não foi possível fechar o caminho de entrada +@msg invalid ICC profile: {0} perfil ICC inválido: {0} +@msg invalid scale {scale} escala inválida {scale} +@msg its localized names take more than {_1} KB seus nomes localizados ocupam mais de {_1} KB +@msg its objects are nested too deep ({e}) seus objetos estão aninhados profundamente demais ({e}) +@msg its tag table lists the `{_1}` tag more than once sua tabela de tags lista a tag `{_1}` mais de uma vez +@msg not a graphic style library: {e} não é uma biblioteca de estilos gráficos: {e} +@msg not a swatch library (.vcswatches or .gpl) não é uma biblioteca de amostras (.vcswatches ou .gpl) +@msg not a swatch library (format `{_1}`) não é uma biblioteca de amostras (formato `{_1}`) +@msg not a swatch library: {e} não é uma biblioteca de amostras: {e} +@msg not an action set file ({e}) não é um arquivo de conjunto de ações ({e}) +@msg profile colour space {other} is not RGB, CMYK or Gray o espaço de cores do perfil, {other}, não é RGB, CMYK ou Cinza +@msg regular expression too large expressão regular grande demais +@msg script file is not UTF-8 text: {value} o arquivo de script não é texto UTF-8: {value} +@msg stop {i}: {e} parada {i}: {e} +@msg swatch exchange version {major}.{minor} isn't supported (only 1.x) a versão {major}.{minor} de intercâmbio de amostras não tem suporte (somente 1.x) +@msg the color book holds more than {ASE_MAX_ENTRIES} colors o livro de cores contém mais de {ASE_MAX_ENTRIES} cores +@msg the color book is cut short o livro de cores está incompleto +@msg the color book's names take more than {_1} MB os nomes do livro de cores ocupam mais de {_1} MB +@msg the image would be {w} × {h} pixels; raster exports are limited to {MAX_RASTER_SIDE} pixels per side and {_1} megapixels: lower the scale or resolution a imagem teria {w} × {h} pixels; as exportações raster são limitadas a {MAX_RASTER_SIDE} pixels por lado e {_1} megapixels: reduza a escala ou a resolução +@msg the optimised image can't be read back: {e} a imagem otimizada não pode ser lida de volta: {e} +@msg the pixel buffer doesn't match the image size o buffer de pixels não corresponde ao tamanho da imagem +@msg the preview: {e} a visualização: {e} +@msg the request may not read the New Document profiles folder a solicitação não tem permissão para ler a pasta de perfis de Novo Documento +@msg the shapes are too degenerate to combine as formas são degeneradas demais para combinar +@msg the shapes cross themselves and each other too often to combine as formas se cruzam consigo mesmas e entre si vezes demais para combinar +@msg the swatch exchange file holds more than {ASE_MAX_ENTRIES} colors and groups o arquivo de intercâmbio de amostras contém mais de {ASE_MAX_ENTRIES} cores e grupos +@msg the swatch exchange file is cut short o arquivo de intercâmbio de amostras está incompleto +@msg the {_1} plate can't be read: {e} a chapa {_1} não pode ser lida: {e} +@msg this binary DXF file is damaged or cut short este arquivo DXF binário está danificado ou incompleto +@msg this is a DWG drawing, which can't be read: save it from the CAD app as a DXF and open that este é um desenho DWG, que não pode ser lido: salve-o no aplicativo de CAD como DXF e abra esse arquivo +@msg too many classes classes demais +@msg too many groups grupos demais +@msg too many layers for PSD (at most 32767) camadas demais para PSD (no máximo 32767) +@msg too many swatch exchange blocks blocos de intercâmbio de amostras demais +@msg unknown colour profile: {0} perfil de cor desconhecido: {0} +@msg {_1} clashes with a built-in profile name {_1} coincide com o nome de um perfil integrado +@msg {_1} × {_2} pixels is too large for GIF (at most 65535 pixels a side): lower the resolution {_1} × {_2} pixels é grande demais para GIF (no máximo 65535 pixels por lado): reduza a resolução +@msg {_1}: no usable transform to/from sRGB {_1}: nenhuma transformação utilizável de/para sRGB +@msg {name} is not a CMYK profile {name} não é um perfil CMYK +@msg {name} is not an RGB profile {name} não é um perfil RGB +@msg {path}: could not be read {path}: não foi possível ler +@msg {width} × {height} pixels is too large for JPEG (at most 65535 pixels a side): lower the resolution {width} × {height} pixels é grande demais para JPEG (no máximo 65535 pixels por lado): reduza a resolução +@msg {width} × {height} pixels is too large for Targa (at most 65535 pixels a side): lower the resolution {width} × {height} pixels é grande demais para Targa (no máximo 65535 pixels por lado): reduza a resolução +@msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} pixels é grande demais para PSD (no máximo {MAX_SIDE} pixels por lado): reduza a resolução + # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Distance Distância Mode Modo @@ -7540,11 +7677,20 @@ swatch Yellow Green Verde-amarelado Open Tutorial Sample Abrir Amostra do Tutorial Finish Tutorial Concluir Tutorial Next Tutorial Próximo Tutorial + Show Learn Tab Mostrar Guia de Aprender + Show Skill Mostrar Habilidade + Back One Level Voltar um Nível Back to Skills Voltar às Habilidades @msg tutorial `{id}` has no practice sample o tutorial `{id}` não tem amostra de prática @msg open the practice sample of `{id}` first (see learn.openSample) abra primeiro a amostra de prática de `{id}` (veja learn.openSample) @msg finish `{id}` first (see learn.finish) conclua primeiro `{id}` (veja learn.finish) @msg `{id}` is the last tutorial in its skill `{id}` é o último tutorial da sua habilidade + Reset progress Redefinir progresso + Mark Tutorial Step Marcar Etapa do Tutorial + Reset Learn Progress Redefinir Progresso de Aprendizagem +@msg missing `step` (see learn.show) falta `step` (veja learn.show) +@msg `step` must be a step number from 0 to {last} `step` deve ser um número de etapa de 0 a {last} +@msg `{id}` is finished (see learn.resetProgress) `{id}` está concluído (veja learn.resetProgress) # Deferred plug-in effects Refresh Deferred Effects Atualizar Efeitos Adiados @@ -8952,6 +9098,8 @@ swatch Yellow Green Verde-amarelado @msg the RTF file is too large to place as type (at most {_1} MB) o arquivo RTF é grande demais para ser colocado como texto (no máximo {_1} MB) @msg the SVG expands to more than {0} nested SVG images o SVG se expande em mais de {0} imagens SVG aninhadas @msg the SVG expands to more than {0} objects o SVG se expande em mais de {0} objetos +@msg the SVG's style sheets take too long to match a correspondência das folhas de estilo do SVG demora demais +@msg the SVG's styles expand to more than {0} MB os estilos do SVG se expandem para mais de {0} MB @msg the SVG file is larger than {MAX_IMPORT_BYTES} bytes o arquivo SVG tem mais de {MAX_IMPORT_BYTES} bytes @msg the SVG has no drawable objects o SVG não tem objetos desenháveis @msg the SVGZ file unpacks to more than {_1} MB o arquivo SVGZ é descompactado em mais de {_1} MB @@ -9386,3 +9534,6 @@ swatch Yellow Green Verde-amarelado @msg turn on at least one side ative pelo menos um lado @msg with no hem and no grommets there is nothing to mark sem bainha e sem ilhoses não há nada para marcar @msg {saving} failed: {e} {saving} falhou: {e} + Nest Shapes… Aninhar formas… + Nest Shapes Aninhar formas + Roll Rolo diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index b3ec6a7684..741d29481d 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -16,6 +16,7 @@ Edge Brightness Яркость края Smoothness Сглаживание Radial Blur… Радиальное размытие… + Blur Center Центр размытия Smart Blur… Умное размытие… Sharpen Резкость Unsharp Mask… Нерезкая маска… @@ -643,6 +644,7 @@ font-technology Variable Вариативные Copy All Styles Копировать все стили Copy Color Value (Hex) Копировать значение цвета (hex) Copy Fonts Used in the Document Копировать шрифты, использованные в документе + Copy Info Копировать сведения Copy Links Копировать связи Copy Selected Style Копировать выбранный стиль Copy to User Defined Копировать в «Пользовательский» @@ -902,6 +904,9 @@ font-technology Variable Вариативные The selected character's font is not available. Шрифт выделенного символа недоступен. No alternates for the selected character. У выделенного символа нет альтернатив. Double-click to replace Дважды щёлкните для замены + Click to replace Щёлкните для замены + Show all alternates in the Glyphs panel Показать все альтернативы в панели «Глифы» + Show Character Alternates Показывать альтернативы символа Select one character with the Type tool first. Сначала выделите один символ инструментом «Текст». {glyph} is a glyph of {font}, not of the font the selected text is set in ({text_font}). {glyph} — глиф шрифта {font}, а не шрифта выделенного текста ({text_font}). {glyph} belongs to {base} (U+{base_code}) {place}; your selection is {sel} (U+{code}). {glyph} относится к символу {base} (U+{base_code}) {place}; выделен символ {sel} (U+{code}). @@ -1348,6 +1353,7 @@ file-filter Templates Шаблоны Format Формат Format Options Параметры формата Format Settings Параметры формата + Format Settings… Параметры формата… Format: Формат: Formats: Форматы: Fractional Widths Дробные ширины @@ -1709,6 +1715,7 @@ file-filter Templates Шаблоны Images: Изображения: Import Keyboard Shortcuts… Импортировать сочетания клавиш… Import PDF Импортировать PDF + Import PDF pages as links Импортировать страницы PDF как связи Import PDF Presets Импортировать наборы PDF Import Perspective Grid Presets Импортировать наборы сетки перспективы Import Print Presets Импортировать наборы печати @@ -3473,6 +3480,18 @@ digits Malayalam Малаялам Smart Guides (View → Smart Guides) Умные направляющие (Просмотр → Умные направляющие) Smart Guides (⌘U) Умные направляющие (⌘U) Smart Punctuation… Умная пунктуация… + Smart Punctuation Умная пунктуация + ff, fi, ffi Ligatures Лигатуры ff, fi, ffi + ff, fl, ffl Ligatures Лигатуры ff, fl, ffl + Smart Quotes Умные кавычки + Smart Spaces Умные пробелы + En, Em Dashes Средние и длинные тире + Ellipses Многоточия + Expert Fractions Экспертные дроби + Replace In Заменить в + Selected Text Only Только выделенный текст + Entire Document Весь документ + Report Results Отчёт о результатах Smooth Сгладить Corner Угол Relative Относительно @@ -3503,6 +3522,7 @@ digits Malayalam Малаялам Solid Сплошной Sort by Kind Сортировать по типу Sort by Name Сортировать по имени + Sort by Size Сортировать по размеру Sort by Status Сортировать по состоянию Source code on GitHub Исходный код на GitHub Source Sans 3 Source Sans 3 @@ -4411,6 +4431,7 @@ axis Both Оба @msg there is no script engine named {name} движка скриптов с именем {name} нет @msg Running a script Выполняется скрипт @msg Copied the script report Отчёт о сценарии скопирован +@msg Copied the link info Сведения о связи скопированы @msg Corners edits the corners of a path «Углы» редактирует углы контура @msg Couldn't copy to the system clipboard: {e} Не удалось скопировать в системный буфер обмена: {e} @msg Couldn't open {name}: {e} Не удалось открыть {name}: {e} @@ -4883,6 +4904,8 @@ axis Both Оба @msg result would exceed the canvas (coordinates out of range) результат превысил бы холст (координаты вне диапазона) @msg objects can't be nested more than 32 deep объекты нельзя вкладывать глубже 32 уровней @msg the SVG's elements are nested more than {0} deep элементы SVG вложены глубже {0} уровней +@msg the SVG's style sheets take too long to match сопоставление таблиц стилей SVG занимает слишком много времени +@msg the SVG's styles expand to more than {0} MB после развёртывания стили SVG занимают более {0} МБ @msg scale must be a number from {_1} to {_2}, not {_3} scale должен быть числом от {_1} до {_2}, а не {_3} @msg scale must be a number from {_1} to {_2}, not {s} scale должен быть числом от {_1} до {_2}, а не {s} @msg select (or target) objects whose appearance isn't basic выделите (или укажите как объект) объекты, оформление которых не является основным @@ -6285,7 +6308,7 @@ axis Y Axis Ось Y @plural Result: {n}|Results: {n} Результат: {n}|Результаты: {n}|Результаты: {n} @msg select one object выберите один объект @msg Global Edit works on paths, compound paths, symbol instances and groups of them Глобальное редактирование работает с контурами, составными контурами, экземплярами символов и их группами -@msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again похожие объекты не найдены (повёрнутые или отражённые копии не учитываются); измените параметры глобального редактирования и повторите попытку +@msg no similar objects found (reflected copies are not matched); change the Global Edit Options and try again похожие объекты не найдены (отражённые копии не учитываются); измените параметры глобального редактирования и повторите попытку @msg Global Edit is off Глобальное редактирование выключено @msg only an object of the Global Edit other than the one it started from can be left out исключить из глобального редактирования можно только объект, отличный от того, с которого оно началось @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all или диапазон, например 1, 3-5, а не {v} @@ -7556,11 +7579,20 @@ shape Open Открытый Open Tutorial Sample Открыть пример урока Finish Tutorial Завершить урок Next Tutorial Следующий урок + Show Learn Tab Показать вкладку панели «Обучение» + Show Skill Показать навык + Back One Level На уровень назад Back to Skills Назад к навыкам @msg tutorial `{id}` has no practice sample у урока `{id}` нет учебного примера @msg open the practice sample of `{id}` first (see learn.openSample) сначала откройте учебный пример урока `{id}` (см. learn.openSample) @msg finish `{id}` first (see learn.finish) сначала завершите `{id}` (см. learn.finish) @msg `{id}` is the last tutorial in its skill `{id}` является последним уроком своего навыка + Reset progress Сбросить прогресс + Mark Tutorial Step Отметить шаг урока + Reset Learn Progress Сбросить прогресс обучения +@msg missing `step` (see learn.show) отсутствует `step` (см. learn.show) +@msg `step` must be a step number from 0 to {last} `step` должен быть номером шага от 0 до {last} +@msg `{id}` is finished (see learn.resetProgress) урок `{id}` завершён (см. learn.resetProgress) # Deferred plug-in effects Refresh Deferred Effects Обновить отложенные эффекты @@ -7590,6 +7622,9 @@ shape Open Открытый Grommets Люверсы Grommet Inset Отступ люверсов от края Diameter Диаметр + Nest Shapes… Раскладка фигур… + Nest Shapes Раскладка фигур + Roll Рулон # Messages of the effects, 3D, image export, color profiles, swatch exchange files, color books and DXF import. @msg 3D effects require finite coordinates within 100 million points 3D-эффектам нужны конечные координаты в пределах 100 миллионов пунктов diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index e16a0cb6e1..c3258b0a2d 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -15,6 +15,7 @@ Edge Brightness Kantljusstyrka Smoothness Mjukhet Radial Blur… Radiell oskärpa… + Blur Center Oskärpans mittpunkt Smart Blur… Smart oskärpa… Sharpen Skärpa Unsharp Mask… Oskarp mask… @@ -632,6 +633,7 @@ font-technology Variable Variabla Copy All Styles Kopiera alla stilar Copy Color Value (Hex) Kopiera färgvärde (hex) Copy Fonts Used in the Document Kopiera typsnitt som används i dokumentet + Copy Info Kopiera info Copy Links Kopiera länkar Copy Selected Style Kopiera markerad stil Copy to User Defined Kopiera till användardefinierade @@ -891,6 +893,9 @@ font-technology Variable Variabla The selected character's font is not available. Typsnittet för det markerade tecknet är inte tillgängligt. No alternates for the selected character. Inga alternativ för det markerade tecknet. Double-click to replace Dubbelklicka för att ersätta + Click to replace Klicka för att ersätta + Show all alternates in the Glyphs panel Visa alla alternativ i panelen Glyfer + Show Character Alternates Visa teckenalternativ Select one character with the Type tool first. Markera först ett tecken med textverktyget. {glyph} is a glyph of {font}, not of the font the selected text is set in ({text_font}). {glyph} är en glyf i {font}, inte i det typsnitt den markerade texten är satt i ({text_font}). {glyph} belongs to {base} (U+{base_code}) {place}; your selection is {sel} (U+{code}). {glyph} hör till {base} (U+{base_code}) {place}; din markering är {sel} (U+{code}). @@ -1297,6 +1302,7 @@ font-technology Variable Variabla Format Format Format Options Formatalternativ Format Settings Formatinställningar + Format Settings… Formatinställningar… Format: Format: Formats: Format: Fractional Widths Bråkdelsbredder @@ -1643,6 +1649,7 @@ font-technology Variable Variabla Images: Bilder: Import Keyboard Shortcuts… Importera kortkommandon… Import PDF Importera PDF + Import PDF pages as links Importera PDF-sidor som länkar Import PDF Presets Importera PDF-förinställningar Import Perspective Grid Presets Importera förinställningar för perspektivrutnät Import Print Presets Importera utskriftsförinställningar @@ -3363,6 +3370,18 @@ digits Malayalam Malayalam Smart Guides (View → Smart Guides) Smarta stödlinjer (Visa → Smarta stödlinjer) Smart Guides (⌘U) Smarta stödlinjer (⌘U) Smart Punctuation… Smarta skiljetecken… + Smart Punctuation Smarta skiljetecken + ff, fi, ffi Ligatures Ligaturer ff, fi, ffi + ff, fl, ffl Ligatures Ligaturer ff, fl, ffl + Smart Quotes Smarta citattecken + Smart Spaces Smarta blanksteg + En, Em Dashes Korta och långa tankstreck + Ellipses Ellipser + Expert Fractions Expertbråk + Replace In Ersätt i + Selected Text Only Endast markerad text + Entire Document Hela dokumentet + Report Results Rapportera resultat Smooth Mjuk Corner Hörn Relative Relativ @@ -3393,6 +3412,7 @@ digits Malayalam Malayalam Solid Enfärgad Sort by Kind Sortera efter typ Sort by Name Sortera efter namn + Sort by Size Sortera efter storlek Sort by Status Sortera efter status Source code on GitHub Källkod på GitHub Source Sans 3 Source Sans 3 @@ -4284,6 +4304,7 @@ axis Both Båda @msg there is no script engine named {name} det finns ingen skriptmotor med namnet {name} @msg Running a script Kör ett skript @msg Copied the script report Kopierade skriptrapporten +@msg Copied the link info Kopierade länkinfo @msg Corners edits the corners of a path Hörn redigerar hörnen på en bana @msg Couldn't copy to the system clipboard: {e} Kunde inte kopiera till systemets urklipp: {e} @msg Couldn't open {name}: {e} Kunde inte öppna {name}: {e} @@ -6654,7 +6675,7 @@ axis Y Axis Y-axel @plural Result: {n}|Results: {n} Resultat: {n}|Resultat: {n} @msg select one object markera ett objekt @msg Global Edit works on paths, compound paths, symbol instances and groups of them Global redigering fungerar på banor, sammansatta banor, symbolinstanser och grupper av dem -@msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again inga liknande objekt hittades (roterade eller speglade kopior matchas inte); ändra alternativen för global redigering och försök igen +@msg no similar objects found (reflected copies are not matched); change the Global Edit Options and try again inga liknande objekt hittades (speglade kopior matchas inte); ändra alternativen för global redigering och försök igen @msg Global Edit is off Global redigering är inte aktiv @msg only an object of the Global Edit other than the one it started from can be left out bara ett annat objekt än det som den globala redigeringen började med kan uteslutas @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all eller ett intervall som 1, 3-5, inte {v} @@ -8650,6 +8671,8 @@ digits Hindi Hindi @msg the subpath has no ends to extend (it is closed or a single point) delbanan har inga ändar att förlänga (den är stängd eller en enkel punkt) @msg the SVG expands to more than {0} nested SVG images SVG-filen expanderar till fler än {0} kapslade SVG-bilder @msg the SVG expands to more than {0} objects SVG-filen expanderar till fler än {0} objekt +@msg the SVG's style sheets take too long to match matchningen av SVG-filens formatmallar tar för lång tid +@msg the SVG's styles expand to more than {0} MB SVG-filens stilar expanderar till mer än {0} MB @msg the SVG has no drawable objects SVG-filen har inga ritbara objekt @msg the SVGZ file unpacks to more than {_1} MB SVGZ-filen packas upp till mer än {_1} MB @msg the symbols are nested too deeply to expand their instances symbolerna är kapslade för djupt för att deras instanser ska kunna expanderas @@ -8905,11 +8928,20 @@ digits Hindi Hindi Open Tutorial Sample Öppna övningsexempel för självstudie Finish Tutorial Slutför självstudie Next Tutorial Nästa självstudie + Show Learn Tab Visa flik i Lär dig + Show Skill Visa färdighet + Back One Level En nivå tillbaka Back to Skills Tillbaka till färdigheter @msg tutorial `{id}` has no practice sample självstudien `{id}` har inget övningsexempel @msg open the practice sample of `{id}` first (see learn.openSample) öppna först övningsexemplet för `{id}` (se learn.openSample) @msg finish `{id}` first (see learn.finish) slutför först `{id}` (se learn.finish) @msg `{id}` is the last tutorial in its skill `{id}` är den sista självstudien i sin färdighet + Reset progress Återställ framsteg + Mark Tutorial Step Markera steg i självstudie + Reset Learn Progress Återställ inlärningsframsteg +@msg missing `step` (see learn.show) `step` saknas (se learn.show) +@msg `step` must be a step number from 0 to {last} `step` måste vara ett stegnummer från 0 till {last} +@msg `{id}` is finished (see learn.resetProgress) `{id}` är slutförd (se learn.resetProgress) # Deferred plug-in effects Refresh Deferred Effects Uppdatera uppskjutna effekter @@ -8976,3 +9008,122 @@ digits Hindi Hindi Grommets Öljetter Grommet Inset Öljetternas avstånd från kanten Diameter Diameter + Nest Shapes… Packa former… + Nest Shapes Packa former + Roll Rulle + +# Messages of the effects, 3D, image export, color profiles, swatch exchange files, color books and DXF import. +@msg 3D effects require finite coordinates within 100 million points 3D-effekter kräver ändliga koordinater inom 100 miljoner punkter +@msg 3D effects require one to ten lights 3D-effekter kräver en till tio ljuskällor +@msg BMP depth {_1}: 1, 4, 8, 16, 24 or 32 bits per pixel BMP-djup {_1}: 1, 4, 8, 16, 24 eller 32 bitar per pixel +@msg BMP encoding failed: {width} × {height} pixels doesn't fit the format or the pixel buffer BMP-kodningen misslyckades: {width} × {height} pixlar passar inte formatet eller pixelbufferten +@msg GIF encoding failed: the palette image is malformed GIF-kodningen misslyckades: palettbilden är felaktigt uppbyggd +@msg GIF encoding failed: {e} GIF-kodningen misslyckades: {e} +@msg JPEG colour profile: {e} JPEG-färgprofil: {e} +@msg JPEG encoding failed: pixel buffer doesn't match the image size JPEG-kodningen misslyckades: pixelbufferten stämmer inte med bildens storlek +@msg JPEG encoding failed: {e} JPEG-kodningen misslyckades: {e} +@msg PNG encoding failed: pixel buffer doesn't match the image size PNG-kodningen misslyckades: pixelbufferten stämmer inte med bildens storlek +@msg PNG encoding failed: the palette image is malformed PNG-kodningen misslyckades: palettbilden är felaktigt uppbyggd +@msg PNG encoding failed: {e} PNG-kodningen misslyckades: {e} +@msg PNG encoding failed: {width} × {height} pixels is not a valid image size PNG-kodningen misslyckades: {width} × {height} pixlar är inte en giltig bildstorlek +@msg PSD colour profile: {e} PSD-färgprofil: {e} +@msg PSD encoding failed: the pixel buffer doesn't match the image size PSD-kodningen misslyckades: pixelbufferten stämmer inte med bildens storlek +@msg Revolve profile contains invalid coordinates Profilen för Rotera runt axel innehåller ogiltiga koordinater +@msg Revolve profile is too complex Profilen för Rotera runt axel är för komplex +@msg Revolve projection is not finite Projektionen för Rotera runt axel är inte ändlig +@msg Revolve requires finite profile coordinates within 100 million points Rotera runt axel kräver ändliga profilkoordinater inom 100 miljoner punkter +@msg Revolve surface is too complex; reduce Segments or simplify the profile Ytan för Rotera runt axel är för komplex; minska Segment eller förenkla profilen +@msg Revolve surface is too complex; simplify the profile Ytan för Rotera runt axel är för komplex; förenkla profilen +@msg Revolve visibility cannot split the projected boundary Synlighetsberäkningen för Rotera runt axel kan inte dela den projicerade gränsen +@msg Revolve visibility creates too many fragments Synlighetsberäkningen för Rotera runt axel skapar för många fragment +@msg Revolve visibility creates too many vector anchors Synlighetsberäkningen för Rotera runt axel skapar för många vektorankarpunkter +@msg Revolve visibility exceeds its geometry work limit Synlighetsberäkningen för Rotera runt axel överskrider sin gräns för geometriarbete +@msg Revolve visibility exceeds its spatial index limit Synlighetsberäkningen för Rotera runt axel överskrider sin gräns för det rumsliga indexet +@msg Revolve visibility has too many boundary crossings Synlighetsberäkningen för Rotera runt axel har för många gränskorsningar +@msg Revolve visibility has too many input anchors Synlighetsberäkningen för Rotera runt axel har för många inkommande ankarpunkter +@msg Revolve visibility requires convex cap sectors Synlighetsberäkningen för Rotera runt axel kräver konvexa sektorer i locken +@msg Revolve visibility requires finite projected faces Synlighetsberäkningen för Rotera runt axel kräver ändliga projicerade ytor +@msg SVG options: {e} SVG-alternativ: {e} +@msg Save for Web settings: {e} Inställningar för Spara för webben: {e} +@msg TIFF colour profile: {e} TIFF-färgprofil: {e} +@msg TIFF encoding failed: the pixel buffer doesn't match the image size TIFF-kodningen misslyckades: pixelbufferten stämmer inte med bildens storlek +@msg TIFF encoding failed: {e} TIFF-kodningen misslyckades: {e} +@msg Targa depth {_1}: 16, 24 or 32 bits per pixel Targa-djup {_1}: 16, 24 eller 32 bitar per pixel +@msg Targa encoding failed: the pixel buffer doesn't match the image size Targa-kodningen misslyckades: pixelbufferten stämmer inte med bildens storlek +@msg The 3D projection is not finite 3D-projektionen är inte ändlig +@msg The 3D shadow is too complex; turn Shadows off or simplify the art 3D-skuggan är för komplex; stäng av Skuggor eller förenkla grafiken +@msg The shape contains invalid coordinates Formen innehåller ogiltiga koordinater +@msg Too many Revolve faces for visibility evaluation För många ytor i Rotera runt axel för synlighetsberäkningen +@msg VectorCraft reads at most {ASE_MAX_ENTRIES} colors and groups from a swatch exchange file, and this library has {entries} VectorCraft läser högst {ASE_MAX_ENTRIES} färger och grupper från en fil för färgruteutbyte, och det här biblioteket har {entries} +@msg WebP encoding failed: {e} WebP-kodningen misslyckades: {e} +@msg [{j}] `{_1}`: {why} [{j}] `{_1}`: {why} +@msg `index` must be a whole number `index` måste vara ett heltal +@msg `view` is smallThumb, mediumThumb, largeThumb, smallList or largeList `view` är smallThumb, mediumThumb, largeThumb, smallList eller largeList +@msg a line can't run from a point to itself en linje kan inte gå från en punkt till sig själv +@msg a line needs at least two points en linje behöver minst två punkter +@msg a number cannot be read ett tal kan inte läsas +@msg a swatch exchange block is too long ett block i en fil för färgruteutbyte är för långt +@msg a swatch exchange name is too long ett namn i en fil för färgruteutbyte är för långt +@msg a {sw} × {sh} image can't be resized to {width} × {height} pixels en bild på {sw} × {sh} kan inte skalas om till {width} × {height} pixlar +@msg a {width} × {height} image is too large en bild på {width} × {height} är för stor +@msg a {width} × {height} image: {e} en bild på {width} × {height}: {e} +@msg an image could not be written: {e} en bild kunde inte skrivas: {e} +@msg an image that couldn't be read was left out en bild som inte kunde läsas utelämnades +@msg can't open “{name}”: {e} kan inte öppna ”{name}”: {e} +@msg cannot align zip entries to {align} bytes kan inte justera zip-posterna till {align} byte +@msg cannot open the automation {kind} root `{_1}`: {e} kan inte öppna automatiseringens rotmapp ({kind}) `{_1}`: {e} +@msg cannot read profile: {0} kan inte läsa profilen: {0} +@msg color book version {version} isn't supported (only 1) färgboksversion {version} stöds inte (endast 1) +@msg color books in color space {other} aren't supported (only RGB, CMYK and Lab) färgböcker i färgrymden {other} stöds inte (endast RGB, CMYK och Lab) +@msg file name too long to zip: {_1} filnamnet är för långt för att zippas: {_1} +@msg file name too long to zip: {name} filnamnet är för långt för att zippas: {name} +@msg freeform line {i}: {e} fri linje {i}: {e} +@msg freeform point {i}: {e} fri punkt {i}: {e} +@msg give `{key}` or `{other}`, not both ange `{key}` eller `{other}`, inte båda +@msg grayscale profiles can't be working spaces yet gråskaleprofiler kan inte vara arbetsfärgrymder än +@msg input contains NaN or infinite coordinates indata innehåller NaN eller oändliga koordinater +@msg input path could not be closed den inkommande banan kunde inte slutas +@msg invalid ICC profile: {0} ogiltig ICC-profil: {0} +@msg invalid scale {scale} ogiltig skala {scale} +@msg its localized names take more than {_1} KB dess lokaliserade namn tar mer än {_1} KB +@msg its objects are nested too deep ({e}) dess objekt är kapslade för djupt ({e}) +@msg its tag table lists the `{_1}` tag more than once dess taggtabell listar taggen `{_1}` mer än en gång +@msg not a graphic style library: {e} inte ett bibliotek med grafiska stilar: {e} +@msg not a swatch library (.vcswatches or .gpl) inte ett färgrutebibliotek (.vcswatches eller .gpl) +@msg not a swatch library (format `{_1}`) inte ett färgrutebibliotek (format `{_1}`) +@msg not a swatch library: {e} inte ett färgrutebibliotek: {e} +@msg not an action set file ({e}) inte en fil med åtgärdsuppsättning ({e}) +@msg profile colour space {other} is not RGB, CMYK or Gray profilens färgrymd {other} är inte RGB, CMYK eller Gray +@msg regular expression too large det reguljära uttrycket är för stort +@msg script file is not UTF-8 text: {value} skriptfilen är inte UTF-8-text: {value} +@msg stop {i}: {e} stopp {i}: {e} +@msg swatch exchange version {major}.{minor} isn't supported (only 1.x) version {major}.{minor} av filer för färgruteutbyte stöds inte (endast 1.x) +@msg the color book holds more than {ASE_MAX_ENTRIES} colors färgboken innehåller fler än {ASE_MAX_ENTRIES} färger +@msg the color book is cut short färgboken är avkortad +@msg the color book's names take more than {_1} MB färgbokens namn tar mer än {_1} MB +@msg the image would be {w} × {h} pixels; raster exports are limited to {MAX_RASTER_SIDE} pixels per side and {_1} megapixels: lower the scale or resolution bilden skulle bli {w} × {h} pixlar; rasterexporter är begränsade till {MAX_RASTER_SIDE} pixlar per sida och {_1} megapixel: sänk skalan eller upplösningen +@msg the optimised image can't be read back: {e} den optimerade bilden kan inte läsas tillbaka: {e} +@msg the pixel buffer doesn't match the image size pixelbufferten stämmer inte med bildens storlek +@msg the preview: {e} förhandsgranskningen: {e} +@msg the request may not read the New Document profiles folder begäran får inte läsa mappen med profiler för nytt dokument +@msg the shapes are too degenerate to combine formerna är för degenererade för att kombineras +@msg the shapes cross themselves and each other too often to combine formerna korsar sig själva och varandra för ofta för att kombineras +@msg the swatch exchange file holds more than {ASE_MAX_ENTRIES} colors and groups filen för färgruteutbyte innehåller fler än {ASE_MAX_ENTRIES} färger och grupper +@msg the swatch exchange file is cut short filen för färgruteutbyte är avkortad +@msg the {_1} plate can't be read: {e} plåten {_1} kan inte läsas: {e} +@msg this binary DXF file is damaged or cut short den här binära DXF-filen är skadad eller avkortad +@msg this is a DWG drawing, which can't be read: save it from the CAD app as a DXF and open that det här är en DWG-ritning, som inte kan läsas: spara den från CAD-appen som DXF och öppna den +@msg too many classes för många klasser +@msg too many groups för många grupper +@msg too many layers for PSD (at most 32767) för många lager för PSD (högst 32767) +@msg too many swatch exchange blocks för många block i filen för färgruteutbyte +@msg unknown colour profile: {0} okänd färgprofil: {0} +@msg {_1} clashes with a built-in profile name {_1} krockar med namnet på en inbyggd profil +@msg {_1} × {_2} pixels is too large for GIF (at most 65535 pixels a side): lower the resolution {_1} × {_2} pixlar är för stort för GIF (högst 65535 pixlar per sida): sänk upplösningen +@msg {_1}: no usable transform to/from sRGB {_1}: ingen användbar transformering till/från sRGB +@msg {name} is not a CMYK profile {name} är inte en CMYK-profil +@msg {name} is not an RGB profile {name} är inte en RGB-profil +@msg {path}: could not be read {path}: kunde inte läsas +@msg {width} × {height} pixels is too large for JPEG (at most 65535 pixels a side): lower the resolution {width} × {height} pixlar är för stort för JPEG (högst 65535 pixlar per sida): sänk upplösningen +@msg {width} × {height} pixels is too large for Targa (at most 65535 pixels a side): lower the resolution {width} × {height} pixlar är för stort för Targa (högst 65535 pixlar per sida): sänk upplösningen +@msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} pixlar är för stort för PSD (högst {MAX_SIDE} pixlar per sida): sänk upplösningen diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index c303810eb9..c985f77d6c 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -49,6 +49,9 @@ fn hindi_resolves_locales_and_uses_zero_one_plurals() { /// Every Hindi row uses the terms `docs/localization-hi.md` sets for what its English names: /// सेव for saving, स्वॉच for a swatch, क्रॉप for cropping, रिज़ॉल्यूशन for a resolution and पाथ for /// a path, never पाठ (a reading), and a number of points is a number (संख्या) in points (पॉइंट). +/// Rows also never use a word's unrelated sense: a ruler is not शासक (a sovereign), a text character +/// is not चरित्र (a personality), a vector point or a printer's mark is not अंक (a digit), fills are +/// not भरता (the verb), Desired is not देसी (local), Even is not शाम (evening), and so on. #[test] fn hindi_rows_use_the_glossary_term_for_what_their_english_names() { let hi = Lang::from_code("hi").expect("hi registered"); @@ -57,15 +60,35 @@ fn hindi_rows_use_the_glossary_term_for_what_their_english_names() { for (_, src, translation) in &entries { let english = src.to_lowercase(); let names = |words: &[&str]| english.split(|c: char| !c.is_ascii_alphabetic()).any(|w| words.contains(&w)); - let banned: [(bool, &[&str]); 6] = [ - (names(&["save", "saves", "saved", "saving"]), &["बचा", "सहेज"]), + let banned: &[(bool, &[&str])] = &[ + (names(&["save", "saves", "saved", "saving"]), &["बचा", "बचत", "सहेज"]), (names(&["swatch", "swatches"]), &["घड़ी"]), (names(&["crop"]), &["फसल"]), (names(&["resolution", "resolutions"]), &["संकल्प"]), (names(&["path", "paths"]), &["पथ"]), (true, &["पाठ", "कई अंक"]), + (names(&["ruler", "rulers"]), &["शासक"]), + (names(&["character", "characters"]), &["चरित्र"]), + (names(&["point", "points", "mark", "marks"]), &["अंक"]), + (names(&["fill", "fills"]), &["भरता"]), + (names(&["desired"]), &["देसी", "इच्छा"]), + (names(&["even"]), &["शाम"]), + (names(&["force", "forced"]), &["सेना"]), + (names(&["same"]), &["समीर"]), + (names(&["thumbnail", "thumbnails"]), &["हिंदुस्तान"]), + (names(&["contrast"]), &["न्यायालय"]), + (names(&["function"]), &["समारोह"]), + (names(&["kern"]), &["बर्न"]), + (names(&["imageable"]), &["कल्पनाशील"]), + (names(&["constrain"]), &["कंस्ट्रक्शन"]), + (names(&["complement"]), &["संगम"]), + (names(&["concave"]), &["अवतरण"]), + (names(&["triad"]), &["त्रिद"]), + (names(&["trapped", "traps"]), &["निशानेबाज़", "जाल"]), + (names(&["alternate", "alternates"]), &["अल्टरनेटर"]), + (names(&["highlight"]), &["उच्च प्रकाश"]), ]; - for (applies, words) in banned { + for &(applies, words) in banned { if let Some(word) = words.iter().find(|w| applies && translation.contains(**w)) { wrong.push(format!("{word} in {src:?} -> {translation:?}")); } @@ -135,6 +158,10 @@ fn hindi_rows_keep_the_meaning_of_their_english() { "पेज थंबनेल RGB पिक्सल का होना चाहिए, हर तरफ़ 1 से 256 (मिला 0 × 4)" ); assert_eq!(message(hi, "invalid angle"), "अमान्य कोण"); + assert_eq!(tr(hi, "Desired"), "वांछित"); + let range = "न्यूनतम, वांछित से अधिक नहीं होना चाहिए और वांछित, अधिकतम से अधिक नहीं होना चाहिए"; + assert_eq!(tr(hi, "Minimum must not exceed Desired, nor Desired Maximum."), format!("{range}।")); + assert_eq!(message(hi, "`wordSpacing`: Minimum must not exceed Desired, nor Desired Maximum"), format!("`wordSpacing`: {range}")); } /// Hindi messages keep every `a|b|c` list of accepted values exactly as their English writes it. @@ -334,6 +361,27 @@ fn catalan_reads_as_catalan() { assert_eq!(message(ca, nested), "l’ordre `object.group` no està disponible ara mateix: no hi ha res seleccionat"); } +/// Brazilian Portuguese spells Relink "Revincular", and no row calls a process color a +/// selection color ("cor de seleção"). +#[test] +fn brazilian_portuguese_spells_relink_and_process_color() { + let pt = Lang::from_code("pt-br").expect("pt-br registered"); + let (entries, _) = parse_entries(pt.0.source); + let mut wrong = Vec::new(); + for (_, src, translation) in &entries { + let portuguese = translation.to_lowercase(); + if portuguese.contains("revinculcar") { + wrong.push(format!("Relink in {src:?} -> {translation:?}")); + } + if src.to_lowercase().contains("process colo") && (portuguese.contains("cor de seleção") || portuguese.contains("cores de seleção")) { + wrong.push(format!("process color in {src:?} -> {translation:?}")); + } + } + assert!(wrong.is_empty(), "{} Brazilian Portuguese rows are wrong:\n{}", wrong.len(), wrong.join("\n")); + assert_eq!(tr(pt, "Relink…"), "Revincular…"); + assert!(message(pt, "`{name}` is a process colour: tints apply to global and spot colours").to_lowercase().contains("cor de processo")); +} + #[test] fn font_height_reference_labels_are_in_complete_catalogs() { for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { @@ -1902,6 +1950,43 @@ fn ukrainian_plurals_have_three_forms() { assert!(count >= 13, "Ukrainian plural rows missing"); } +/// Ukrainian shows the image encoders', color profiles', swatch exchange files', Revolve's, DXF +/// import's, the script engine's and the parameter checks' errors in Ukrainian, with their values, +/// backticked names and accepted values kept as the English writes them. +#[test] +fn ukrainian_translates_encoder_profile_swatch_revolve_and_parameter_errors() { + for (english, ukrainian) in [ + ( + "PNG encoding failed: 0 × 0 pixels is not a valid image size", + "Не вдалося закодувати PNG: 0 × 0 пікселів не є допустимим розміром зображення", + ), + ( + "70000 × 10 pixels is too large for GIF (at most 65535 pixels a side): lower the resolution", + "розмір 70000 × 10 пікселів завеликий для GIF (не більше 65535 пікселів на сторону): зменште роздільну здатність", + ), + ("profile colour space XYZ is not RGB, CMYK or Gray", "колірний простір профілю XYZ не є RGB, CMYK чи Gray"), + ( + "color books in color space HSB aren't supported (only RGB, CMYK and Lab)", + "книги кольорів у колірному просторі HSB не підтримуються (лише RGB, CMYK і Lab)", + ), + ("the swatch exchange file holds more than 65536 colors and groups", "файл обміну зразками містить понад 65536 кольорів і груп"), + ( + "Revolve surface is too complex; reduce Segments or simplify the profile", + "Обертання: поверхня надто складна; зменште «Сегменти» або спростіть профіль", + ), + ("regular expression too large", "регулярний вираз завеликий"), + ("this binary DXF file is damaged or cut short", "цей двійковий файл DXF пошкоджено або обрізано"), + ( + "`view` is smallThumb, mediumThumb, largeThumb, smallList or largeList", + "`view` має бути smallThumb, mediumThumb, largeThumb, smallList або largeList", + ), + ("give `fill` or `stroke`, not both", "укажіть `fill` або `stroke`, але не обидва"), + ("stop 2: oops", "точка переходу 2: oops"), + ] { + assert_eq!(message(uk(), english), ukrainian); + } +} + /// Catalogs written with spaces between words keep a fragment's leading and trailing spaces: the /// hint bar and a few labels are joined from pieces (" to finish", "Press "). #[test] @@ -2061,6 +2146,44 @@ fn recolor_notes_on_objects_left_unchanged_translate_with_their_counts() { } } +/// Spanish shows the image encoders', color profiles', swatch exchange files', Revolve's, DXF +/// import's, the script engine's and the parameter checks' errors in Spanish, with their values, +/// backticked names and accepted values kept as the English writes them. +#[test] +fn spanish_translates_encoder_profile_swatch_revolve_and_parameter_errors() { + let es = Lang::from_code("es").expect("registered"); + for (english, spanish) in [ + ("PNG encoding failed: 0 × 0 pixels is not a valid image size", "Error al codificar PNG: 0 × 0 píxeles no es un tamaño de imagen válido"), + ( + "70000 × 10 pixels is too large for GIF (at most 65535 pixels a side): lower the resolution", + "70000 × 10 píxeles es demasiado grande para GIF (como máximo 65535 píxeles por lado): baja la resolución", + ), + ("profile colour space XYZ is not RGB, CMYK or Gray", "el espacio de color XYZ del perfil no es RGB, CMYK ni Gray"), + ( + "color books in color space HSB aren't supported (only RGB, CMYK and Lab)", + "no se admiten libros de colores en el espacio de color HSB (solo RGB, CMYK y Lab)", + ), + ( + "the swatch exchange file holds more than 65536 colors and groups", + "el archivo de intercambio de muestras contiene más de 65536 colores y grupos", + ), + ( + "Revolve surface is too complex; reduce Segments or simplify the profile", + "La superficie de Revolución es demasiado compleja; reduce Segmentos o simplifica el perfil", + ), + ("regular expression too large", "expresión regular demasiado grande"), + ("this binary DXF file is damaged or cut short", "este archivo DXF binario está dañado o truncado"), + ( + "`view` is smallThumb, mediumThumb, largeThumb, smallList or largeList", + "`view` es smallThumb, mediumThumb, largeThumb, smallList o largeList", + ), + ("give `fill` or `stroke`, not both", "indica `fill` o `stroke`, no ambos"), + ("stop 2: oops", "parada 2: oops"), + ] { + assert_eq!(message(es, english), spanish); + } +} + #[test] fn package_status_message_templates_parse() { let c = Catalog::parse(concat!( @@ -4200,7 +4323,7 @@ fn translated_messages_keep_the_field_names_and_values_their_english_lists() { /// the messages each one lacks. const COMPLETE_MESSAGES: &[&str] = &[ "cs", "de", "el", "es", "fr", "hi", "hu", "it", "ja", "ka", "ko", "pl", "pt-br", "ru", "sv", "uk", "vi", "zh-hans", "zh-hant", "fi", "tr", "ca", - "nl", + "nl", "da", ]; /// Crates whose error and status messages reach the status bar, the crates whose errors the diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 26822bf63e..4a6b37a170 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -15,6 +15,7 @@ Edge Brightness Kenar Parlaklığı Smoothness Pürüzsüzlük Radial Blur… Radyal Bulanıklık… + Blur Center Bulanıklık Merkezi Smart Blur… Akıllı Bulanıklaştırma… Sharpen Keskinleştir Unsharp Mask… Keskinliği Azaltma Maskesi… @@ -624,6 +625,7 @@ font-technology Variable Değişken Copy All Styles Tüm Stilleri Kopyala Copy Color Value (Hex) Renk Değerini Kopyala (Hex) Copy Fonts Used in the Document Belgede Kullanılan Yazı Tiplerini Kopyala + Copy Info Bilgiyi Kopyala Copy Links Bağlantıları Kopyala Copy Selected Style Seçilen Stili Kopyala Copy to User Defined Kullanıcı Tanımlıya Kopyala @@ -883,6 +885,9 @@ font-technology Variable Değişken The selected character's font is not available. Seçili karakterin yazı tipi kullanılamıyor. No alternates for the selected character. Seçili karakter için alternatif yok. Double-click to replace Değiştirmek için çift tıklayın + Click to replace Değiştirmek için tıklayın + Show all alternates in the Glyphs panel Tüm alternatifleri Glifler panelinde göster + Show Character Alternates Karakter Alternatiflerini Göster Select one character with the Type tool first. Önce Yazım aracıyla bir karakter seçin. {glyph} is a glyph of {font}, not of the font the selected text is set in ({text_font}). {glyph}, seçili metnin yazı tipine ({text_font}) değil, {font} yazı tipine ait bir glif. {glyph} belongs to {base} (U+{base_code}) {place}; your selection is {sel} (U+{code}). {glyph}, {base} (U+{base_code}) karakterine aittir ({place}); seçiminiz {sel} (U+{code}). @@ -1290,6 +1295,7 @@ font-technology Variable Değişken Format Biçim Format Options Biçim Seçenekleri Format Settings Biçim Ayarları + Format Settings… Biçim Ayarları… Format: Biçim: Formats: Formatlar: Fractional Widths Kesirli Genişlikler @@ -1521,6 +1527,7 @@ font-technology Variable Değişken Images: Görseller: Import Keyboard Shortcuts… Klavye Kısayollarını İçe Aktar… Import PDF PDF'yi içe aktar + Import PDF pages as links PDF sayfalarını bağlantı olarak içe aktar Import PDF Presets PDF Hazır Ayarlarını İçe Aktar Import Perspective Grid Presets Perspektif Izgarası Ön Ayarlarını İçe Aktar Import Print Presets Yazdırma Ön Ayarlarını İçe Aktar @@ -3239,6 +3246,18 @@ digits Malayalam Malayalam Smart Guides (View → Smart Guides) Akıllı Kılavuzlar (Görünüm → Akıllı Kılavuzlar) Smart Guides (⌘U) Akıllı Kılavuzlar (⌘U) Smart Punctuation… Akıllı Noktalama… + Smart Punctuation Akıllı Noktalama + ff, fi, ffi Ligatures ff, fi, ffi Bitişik Harfleri + ff, fl, ffl Ligatures ff, fl, ffl Bitişik Harfleri + Smart Quotes Akıllı Tırnaklar + Smart Spaces Akıllı Boşluklar + En, Em Dashes En ve Em Tireler + Ellipses Üç Noktalar + Expert Fractions Uzman Kesirleri + Replace In Değiştirilecek Yer + Selected Text Only Yalnızca Seçili Metin + Entire Document Tüm Belge + Report Results Sonuçları Bildir Smooth Pürüzsüz Corner Köşe Relative akraba @@ -3267,6 +3286,7 @@ digits Malayalam Malayalam Solid Katı Sort by Kind Türe göre sırala Sort by Name Ada Göre Sırala + Sort by Size Boyuta göre sırala Sort by Status Duruma göre sırala Source code on GitHub GitHub'daki kaynak kodu Source Sans 3 Kaynak Sans 3 @@ -4049,6 +4069,14 @@ axis Both Her İkisi @msg a script is running: stop it or wait for it to finish bir betik çalışıyor: durdurun veya bitmesini bekleyin @msg this is a compiled script, which cannot be run; use its source text bu derlenmiş bir betik, çalıştırılamaz; kaynak metnini kullanın @msg the script is not UTF-8 text betik UTF-8 metni değil +@msg script file is not UTF-8 text: {value} betik dosyası UTF-8 metni değil: {value} +@msg a number cannot be read bir sayı okunamıyor +@msg regular expression too large düzenli ifade çok büyük +@msg too many classes çok fazla karakter sınıfı +@msg too many groups çok fazla grup +@msg `answers[{i}]` {e} `answers[{i}]` {e} +@msg [{j}] `{_1}`: {why} [{j}] `{_1}`: {why} +@msg `view` is smallThumb, mediumThumb, largeThumb, smallList or largeList `view` smallThumb, mediumThumb, largeThumb, smallList veya largeList olmalıdır @msg the script is too large to run betik çalıştırılamayacak kadar büyük @msg a drag or an undo group is open; finish it before running a script bir sürükleme veya geri alma grubu açık; betiği çalıştırmadan önce tamamlayın @msg the script left a document that cannot be kept betik, saklanamayan bir belge bıraktı @@ -4139,6 +4167,7 @@ axis Both Her İkisi @msg there is no script engine named {name} {name} adlı bir betik motoru yok @msg Running a script Betik çalıştırılıyor @msg Copied the script report Komut dosyası raporu kopyalandı +@msg Copied the link info Bağlantı bilgisi kopyalandı @msg Corners edits the corners of a path Köşeler bir yolun köşelerini düzenler @msg Couldn't copy to the system clipboard: {e} Sistem panosuna kopyalanamadı: {e} @msg Couldn't open {name}: {e} {name} açılamadı: {e} @@ -4241,6 +4270,7 @@ axis Both Her İkisi @msg `{key}` must be a string `{key}` bir dize olmalıdır @msg `{key}` must be a profile name or null `{key}` bir profil adı ya da null olmalıdır @msg `{key}` must be a whole number `{key}` bir tam sayı olmalıdır +@msg `index` must be a whole number `index` bir tam sayı olmalıdır @msg `{key}` must be a whole number between {min} and {max} (got {x}) `{key}`, {min} ile {max} arasında bir tam sayı olmalıdır ({x}'yi aldı) @msg `{key}` must be between {min} and {max} (got {x}) `{key}`, {min} ile {max} arasında olmalıdır ({x}'yi aldı) @msg `{key}` must be one of {_1} `{key}`, {_1}'den biri olmalıdır @@ -4355,6 +4385,12 @@ axis Both Her İkisi @msg file version {0} is newer than this VectorCraft supports ({VERSION}) dosya sürümü {0}, VectorCraft'ın desteklediğinden daha yenidir ({VERSION}) @msg freeform point {i} needs `at` [x, y] and a valid `color` serbest biçimli nokta {i} için `at` [x, y] ve geçerli bir `color` gerekir @msg freeform line {i} must be an array of point indices Serbest biçimli çizgi {i}, bir nokta indeks dizisi olmalıdır +@msg freeform line {i}: {e} serbest biçimli çizgi {i}: {e} +@msg freeform point {i}: {e} serbest biçimli nokta {i}: {e} +@msg a line can't run from a point to itself bir çizgi bir noktadan aynı noktaya uzanamaz +@msg a line needs at least two points bir çizgi en az iki nokta gerektirir +@msg stop {i}: {e} durak {i}: {e} +@msg give `{key}` or `{other}`, not both `{key}` veya `{other}` verin, ikisini birden değil @msg give both `start` and `end` [x, y] (or neither) hem `start` hem de `end` [x, y] verin (ya da hiçbirini) @msg give corners of the path: anchors where its sides meet at an angle yolun köşelerini verin: kenarlarının belli bir açıyla buluştuğu noktalara sabitleyin @msg give horizontal or vertical yatay veya dikey ver @@ -4481,6 +4517,7 @@ axis Both Her İkisi @msgplural Loaded “{name}”: {n} step was left out|Loaded “{name}”: {n} steps were left out “{name}” yüklendi: {n} adım atlandı @msgplural Loaded “{name}”: {n} step has an unknown command and was kept: “{action}”, step {step}, `{command}`|Loaded “{name}”: {n} steps have unknown commands and were kept; the first: “{action}”, step {step}, `{command}` “{name}” yüklendi: bilinmeyen komutlu {n} adım korundu; ilki: “{action}”, adım {step}, `{command}` @msg not an action set file bir eylem seti dosyası değil +@msg not an action set file ({e}) bir eylem seti dosyası değil ({e}) @msg the action set file is larger than 8 MiB eylem seti dosyası 8 MiB'den büyük @msg `{ID}`: the reference would be larger than {MAX_BYTES} bytes `{ID}`: başvuru {MAX_BYTES} bayttan büyük olur @msg the action set file holds more than 1,000 actions eylem seti dosyası 1.000'den fazla eylem içeriyor @@ -4514,6 +4551,34 @@ axis Both Her İkisi @msg not a VectorCraft file: {0} bir VectorCraft dosyası değil: {0} @msg not a VectorCraft shortcut set (missing `overrides`) VectorCraft kısayol seti değil (`overrides` eksik) @msg not a graphic style library (format `{_1}`) grafik stili kitaplığı değil (`{_1}` biçimi) +@msg not a graphic style library: {e} grafik stili kitaplığı değil: {e} +@msg not a swatch library (.vcswatches or .gpl) renk örneği kitaplığı değil (.vcswatches veya .gpl) +@msg not a swatch library (format `{_1}`) renk örneği kitaplığı değil (`{_1}` biçimi) +@msg not a swatch library: {e} renk örneği kitaplığı değil: {e} +# Swatch exchange files, color books and color profiles. +@msg VectorCraft reads at most {ASE_MAX_ENTRIES} colors and groups from a swatch exchange file, and this library has {entries} VectorCraft bir renk örneği değişim dosyasından en fazla {ASE_MAX_ENTRIES} renk ve grup okur; bu kitaplıkta {entries} tane var +@msg a swatch exchange block is too long bir renk örneği değişim bloğu çok uzun +@msg a swatch exchange name is too long bir renk örneği değişim adı çok uzun +@msg swatch exchange version {major}.{minor} isn't supported (only 1.x) renk örneği değişim sürümü {major}.{minor} desteklenmiyor (yalnızca 1.x) +@msg the swatch exchange file holds more than {ASE_MAX_ENTRIES} colors and groups renk örneği değişim dosyası {ASE_MAX_ENTRIES} renk ve gruptan fazlasını içeriyor +@msg the swatch exchange file is cut short renk örneği değişim dosyası kısa kesildi +@msg too many swatch exchange blocks çok fazla renk örneği değişim bloğu +@msg color book version {version} isn't supported (only 1) renk kitabı sürümü {version} desteklenmiyor (yalnızca 1) +@msg color books in color space {other} aren't supported (only RGB, CMYK and Lab) {other} renk alanındaki renk kitapları desteklenmiyor (yalnızca RGB, CMYK ve Lab) +@msg the color book holds more than {ASE_MAX_ENTRIES} colors renk kitabı {ASE_MAX_ENTRIES} renkten fazlasını içeriyor +@msg the color book is cut short renk kitabı kısa kesildi +@msg the color book's names take more than {_1} MB renk kitabının adları {_1} MB'tan fazla yer kaplıyor +@msg cannot read profile: {0} profil okunamıyor: {0} +@msg invalid ICC profile: {0} geçersiz ICC profili: {0} +@msg unknown colour profile: {0} bilinmeyen renk profili: {0} +@msg its localized names take more than {_1} KB yerelleştirilmiş adları {_1} KB'tan fazla yer kaplıyor +@msg its tag table lists the `{_1}` tag more than once etiket tablosu `{_1}` etiketini birden fazla kez listeliyor +@msg profile colour space {other} is not RGB, CMYK or Gray profil renk alanı {other}; RGB, CMYK veya Gray değil +@msg grayscale profiles can't be working spaces yet gri tonlamalı profiller henüz çalışma alanı olarak kullanılamaz +@msg {_1} clashes with a built-in profile name {_1}, yerleşik bir profil adıyla çakışıyor +@msg {_1}: no usable transform to/from sRGB {_1}: sRGB'ye veya sRGB'den kullanılabilir bir dönüşüm yok +@msg {name} is not a CMYK profile {name} bir CMYK profili değil +@msg {name} is not an RGB profile {name} bir RGB profili değil @msg not a shortcut set: the text doesn't start with a slash name and an opening brace bir kısayol seti değil: metin eğik çizgi adı ve açılış paranteziyle başlamıyor @msg not a stored central record saklanan merkezi bir kayıt değil @msg not a valid plug-in module: {0} geçerli bir eklenti modülü değil: {0} @@ -4572,6 +4637,8 @@ axis Both Her İkisi @msg result would exceed the canvas (coordinates out of range) sonuç tuvali aşacaktır (koordinatlar aralık dışındadır) @msg objects can't be nested more than 32 deep nesneler 32'den fazla derinliğe yerleştirilemez @msg the SVG's elements are nested more than {0} deep SVG'nin öğeleri {0} derinliğinden daha fazla yuvalanmıştır +@msg the SVG's style sheets take too long to match SVG'nin stil sayfalarının eşleştirilmesi çok uzun sürüyor +@msg the SVG's styles expand to more than {0} MB SVG'nin stilleri genişletildiğinde {0} MB'tan fazla yer kaplıyor @msg scale must be a number from {_1} to {_2}, not {_3} scale {_1} ile {_2} arasında bir sayı olmalıdır, {_3} değil @msg scale must be a number from {_1} to {_2}, not {s} scale {_1} ile {_2} arasında bir sayı olmalıdır, {s} değil @msg select (or target) objects whose appearance isn't basic Görünümü temel olmayan nesneleri seçin (veya hedefleyin) @@ -4698,6 +4765,8 @@ axis Both Her İkisi @msg this file's PostScript couldn't be read ({why}): {what} bu dosyanın PostScript'i okunamadı ({why}): {what} @msg this format holds one artboard: export several as PDF or with document.exportForScreens bu formatta bir çalışma yüzeyi bulunur: birkaçını PDF olarak veya document.exportForScreens ile dışa aktarın @msg this is a DWG drawing, which can't be read: save it from the CAD app as an ASCII DXF and open that bu okunamayan bir DWG çizimidir: CAD uygulamasından ASCII DXF olarak kaydedin ve açın. +@msg this is a DWG drawing, which can't be read: save it from the CAD app as a DXF and open that bu okunamayan bir DWG çizimidir: CAD uygulamasından DXF olarak kaydedin ve onu açın +@msg this binary DXF file is damaged or cut short bu ikili DXF dosyası hasarlı veya kısa kesilmiş @msg this is a PostScript file (an .ai saved in an older format or without PDF compatibility, or an EPS file), not a PDF: File › Open and File › Place read it as EPS bu bir PostScript dosyasıdır (eski bir formatta kaydedilmiş veya PDF uyumluluğu olmayan bir .ai veya bir EPS dosyası), PDF değil: Dosya › Aç ve Dosya › Yerleştir, EPS olarak oku @msg this is not a PostScript file bu bir PostScript dosyası değil @msg tool shortcuts must be a single key (optionally with Shift) araç kısayolları tek tuş olmalıdır (isteğe bağlı olarak Shift ile) @@ -4747,6 +4816,7 @@ axis Both Her İkisi @msg workspace name can't be empty çalışma alanı adı boş olamaz @msg {C}: no effect at index {from} {C}: {from} endeksinde etkisi yok @msg {_1} failed: {e} {_1} başarısız oldu: {e} +@msg {saving} failed: {e} {saving} başarısız oldu: {e} @msg {_1} files can be opened but not written (see document.formats) {_1} dosyaları açılabilir ancak yazılamaz (bkz. document.formats) @msg {_1} font families available {_1} yazı tipi aileleri mevcut @msg {_1} is a live effect (Effect › Plug-ins) {_1} canlı bir efekttir (Efekt › Eklentiler) @@ -4954,6 +5024,16 @@ axis Both Her İkisi @msg automation path rejected: cannot resolve {path}: {e} otomasyon yolu reddedildi: {path} çözülemiyor: {e} @msg automation path rejected: parent traversal below a folder that doesn't exist: {path} otomasyon yolu reddedildi: var olmayan bir klasörün altında üst öğe geçişi: {path} @msg automation path rejected: reserved device names are not allowed: {path} otomasyon yolu reddedildi: ayrılmış cihaz adlarına izin verilmiyor: {path} +@msg cannot open the automation {kind} root `{_1}`: {e} otomasyon {kind} kökü `{_1}` açılamıyor: {e} +@msg cannot align zip entries to {align} bytes zip girdileri {align} bayta hizalanamıyor +@msg file name too long to zip: {_1} dosya adı zip için çok uzun: {_1} +@msg file name too long to zip: {name} dosya adı zip için çok uzun: {name} +@msg can't open “{name}”: {e} “{name}” açılamıyor: {e} +@msg {path}: could not be read {path}: okunamadı +@msg the request may not read the New Document profiles folder isteğin Yeni Belge profilleri klasörünü okuma izni yok +@msg its objects are nested too deep ({e}) nesneleri çok derin iç içe geçmiş ({e}) +@msg an image that couldn't be read was left out okunamayan bir görüntü dışarıda bırakıldı +@msg the {_1} plate can't be read: {e} {_1} baskı plakası okunamıyor: {e} @msg Multichannel PSD files can't be read: save it in RGB, CMYK or Grayscale mode Çok kanallı PSD dosyaları okunamıyor: RGB, CMYK veya Gri Tonlama modunda kaydedin @msg not a PSD file PSD dosyası değil @msg the PSD file has an unknown colour mode ({m}) PSD dosyasında bilinmeyen bir renk modu var ({m}) @@ -4985,6 +5065,42 @@ axis Both Her İkisi @msg the JPEG XL container is too large to read JPEG XL kapsayıcısı okunamayacak kadar büyük @msg CMYK JPEG XL images can't be read CMYK JPEG XL görüntüleri okunamıyor @msg the JPEG XL file can't be read: {e} JPEG XL dosyası okunamıyor: {e} +# Image export: encoders, sizes and options. +@msg BMP depth {_1}: 1, 4, 8, 16, 24 or 32 bits per pixel BMP derinliği {_1}: piksel başına 1, 4, 8, 16, 24 veya 32 bit olmalıdır +@msg BMP encoding failed: {width} × {height} pixels doesn't fit the format or the pixel buffer BMP kodlaması başarısız oldu: {width} × {height} piksel biçime veya piksel arabelleğine sığmıyor +@msg GIF encoding failed: the palette image is malformed GIF kodlaması başarısız oldu: palet görüntüsü bozuk biçimli +@msg GIF encoding failed: {e} GIF kodlaması başarısız oldu: {e} +@msg JPEG colour profile: {e} JPEG renk profili: {e} +@msg JPEG encoding failed: pixel buffer doesn't match the image size JPEG kodlaması başarısız oldu: piksel arabelleği görüntü boyutuyla eşleşmiyor +@msg JPEG encoding failed: {e} JPEG kodlaması başarısız oldu: {e} +@msg PNG encoding failed: pixel buffer doesn't match the image size PNG kodlaması başarısız oldu: piksel arabelleği görüntü boyutuyla eşleşmiyor +@msg PNG encoding failed: the palette image is malformed PNG kodlaması başarısız oldu: palet görüntüsü bozuk biçimli +@msg PNG encoding failed: {e} PNG kodlaması başarısız oldu: {e} +@msg PNG encoding failed: {width} × {height} pixels is not a valid image size PNG kodlaması başarısız oldu: {width} × {height} piksel geçerli bir görüntü boyutu değil +@msg PSD colour profile: {e} PSD renk profili: {e} +@msg PSD encoding failed: the pixel buffer doesn't match the image size PSD kodlaması başarısız oldu: piksel arabelleği görüntü boyutuyla eşleşmiyor +@msg TIFF colour profile: {e} TIFF renk profili: {e} +@msg TIFF encoding failed: the pixel buffer doesn't match the image size TIFF kodlaması başarısız oldu: piksel arabelleği görüntü boyutuyla eşleşmiyor +@msg TIFF encoding failed: {e} TIFF kodlaması başarısız oldu: {e} +@msg Targa depth {_1}: 16, 24 or 32 bits per pixel Targa derinliği {_1}: piksel başına 16, 24 veya 32 bit olmalıdır +@msg Targa encoding failed: the pixel buffer doesn't match the image size Targa kodlaması başarısız oldu: piksel arabelleği görüntü boyutuyla eşleşmiyor +@msg WebP encoding failed: {e} WebP kodlaması başarısız oldu: {e} +@msg the pixel buffer doesn't match the image size piksel arabelleği görüntü boyutuyla eşleşmiyor +@msg too many layers for PSD (at most 32767) PSD için çok fazla katman (en fazla 32767) +@msg {_1} × {_2} pixels is too large for GIF (at most 65535 pixels a side): lower the resolution {_1} × {_2} piksel GIF için çok büyük (kenar başına en fazla 65535 piksel): çözünürlüğü düşürün +@msg {width} × {height} pixels is too large for JPEG (at most 65535 pixels a side): lower the resolution {width} × {height} piksel JPEG için çok büyük (kenar başına en fazla 65535 piksel): çözünürlüğü düşürün +@msg {width} × {height} pixels is too large for Targa (at most 65535 pixels a side): lower the resolution {width} × {height} piksel Targa için çok büyük (kenar başına en fazla 65535 piksel): çözünürlüğü düşürün +@msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} piksel PSD için çok büyük (kenar başına en fazla {MAX_SIDE} piksel): çözünürlüğü düşürün +@msg the image would be {w} × {h} pixels; raster exports are limited to {MAX_RASTER_SIDE} pixels per side and {_1} megapixels: lower the scale or resolution görüntü {w} × {h} piksel olurdu; raster dışa aktarmalar kenar başına {MAX_RASTER_SIDE} piksel ve {_1} megapiksel ile sınırlıdır: ölçeği veya çözünürlüğü düşürün +@msg a {sw} × {sh} image can't be resized to {width} × {height} pixels {sw} × {sh} boyutundaki bir görüntü {width} × {height} piksele yeniden boyutlandırılamaz +@msg a {width} × {height} image is too large {width} × {height} boyutundaki bir görüntü çok büyük +@msg a {width} × {height} image: {e} {width} × {height} boyutundaki bir görüntü: {e} +@msg an image could not be written: {e} bir görüntü yazılamadı: {e} +@msg invalid scale {scale} geçersiz ölçek {scale} +@msg SVG options: {e} SVG seçenekleri: {e} +@msg Save for Web settings: {e} Web için Kaydet ayarları: {e} +@msg the optimised image can't be read back: {e} en iyileştirilmiş görüntü geri okunamıyor: {e} +@msg the preview: {e} önizleme: {e} Video video De-Interlace… Taramasızlaştırma… De-Interlace Taramasızlaştırma @@ -5272,6 +5388,31 @@ lighting Light Işık @msg {label} draws no faces for this object {label} bu nesne için hiçbir yüz çizmez @msg the wireframe has more than {MAX_WIRE_EDGES} edges tel kafeste {MAX_WIRE_EDGES} kenardan fazla var @msg The 3D surface is too complex; simplify the shape 3 boyutlu yüzey çok karmaşık; şekli basitleştir +@msg 3D effects require finite coordinates within 100 million points 3D efektleri 100 milyon pt sınırı içinde sonlu koordinatlar gerektirir +@msg 3D effects require one to ten lights 3D efektleri bir ile on arasında ışık gerektirir +@msg The 3D projection is not finite 3D izdüşümü sonlu değil +@msg The 3D shadow is too complex; turn Shadows off or simplify the art 3D gölgesi çok karmaşık; Gölgeler'i kapatın veya resmi basitleştirin +@msg The shape contains invalid coordinates Şekil geçersiz koordinatlar içeriyor +@msg Revolve profile contains invalid coordinates Döndür profili geçersiz koordinatlar içeriyor +@msg Revolve profile is too complex Döndür profili çok karmaşık +@msg Revolve projection is not finite Döndür izdüşümü sonlu değil +@msg Revolve requires finite profile coordinates within 100 million points Döndür, 100 milyon pt sınırı içinde sonlu profil koordinatları gerektirir +@msg Revolve surface is too complex; reduce Segments or simplify the profile Döndür yüzeyi çok karmaşık; Segmentler değerini azaltın veya profili basitleştirin +@msg Revolve surface is too complex; simplify the profile Döndür yüzeyi çok karmaşık; profili basitleştirin +@msg Revolve visibility cannot split the projected boundary Döndür görünürlüğü izdüşümü alınan sınırı bölemiyor +@msg Revolve visibility creates too many fragments Döndür görünürlüğü çok fazla parça oluşturuyor +@msg Revolve visibility creates too many vector anchors Döndür görünürlüğü çok fazla vektör bağlantı noktası oluşturuyor +@msg Revolve visibility exceeds its geometry work limit Döndür görünürlüğü geometri işlem sınırını aşıyor +@msg Revolve visibility exceeds its spatial index limit Döndür görünürlüğü uzamsal dizin sınırını aşıyor +@msg Revolve visibility has too many boundary crossings Döndür görünürlüğünde çok fazla sınır kesişimi var +@msg Revolve visibility has too many input anchors Döndür görünürlüğünde çok fazla girdi bağlantı noktası var +@msg Revolve visibility requires convex cap sectors Döndür görünürlüğü dışbükey kapak dilimleri gerektirir +@msg Revolve visibility requires finite projected faces Döndür görünürlüğü sonlu izdüşüm yüzleri gerektirir +@msg Too many Revolve faces for visibility evaluation Görünürlük değerlendirmesi için çok fazla Döndür yüzü var +@msg input contains NaN or infinite coordinates girdi NaN veya sonsuz koordinatlar içeriyor +@msg input path could not be closed girdi yolu kapatılamadı +@msg the shapes are too degenerate to combine şekiller birleştirilemeyecek kadar yozlaşmış +@msg the shapes cross themselves and each other too often to combine şekiller kendilerini ve birbirlerini birleştirilemeyecek kadar sık kesiyor Transform Objects Nesneleri Dönüştür @msg unknown parameter `{key}`; did you mean `{near}`? bilinmeyen parametre `{key}`; `{near}` mi demek istediniz? @msg unknown parameter `{key}`; the command takes no parameters bilinmeyen parametre `{key}`; komut hiçbir parametre almaz @@ -6607,6 +6748,1808 @@ axis Y Axis Y ekseni @msg no menu item that can be inserted runs this command eklenebilen hiçbir menü öğesi bu komutu çalıştırmaz @msg the action already has 10,000 steps eylemde zaten 10.000 adım var @msg the action set would be larger than 8 MiB eylem seti 8 MiB'tan büyük olurdu +# Status and error messages of commands and their parameter checks, scripts, file import and export, printing and plug-ins. +@msg 'caller', 'callee' and 'arguments' cannot be used on strict mode functions katı kip işlevlerinde 'caller', 'callee' ve 'arguments' kullanılamaz +@msg Alignment must be one of the choices Hizalama, seçeneklerden biri olmalıdır +@msg Boolean.prototype.{name} was called on a value that is not a Boolean Boolean.prototype.{name}, Boolean olmayan bir değer üzerinde çağrıldı +@msg CMYK images whose samples couldn't be read in CMYK were imported in RGB Örnekleri CMYK olarak okunamayan CMYK görüntüler RGB olarak içe aktarıldı +@msg Cannot write to the location of “{name}”; choose where to save it “{name}” konumuna yazılamıyor; nereye kaydedileceğini seçin +@msg DCS files can only be placed linked: use File › Place with Link on DCS dosyaları yalnızca bağlantılı olarak yerleştirilebilir: Dosya › Yerleştir komutunu Bağlantı açıkken kullanın +@msg Date.prototype method called on a value that is not a Date object Date.prototype yöntemi, Date nesnesi olmayan bir değer üzerinde çağrıldı +@msg Error.prototype.toString was called on a value that is not an object Error.prototype.toString, nesne olmayan bir değer üzerinde çağrıldı +@msg Function.prototype.toString was called on a value that is not a function Function.prototype.toString, işlev olmayan bir değer üzerinde çağrıldı +@msg Import SVG Filter reads SVG files, not SVGZ SVG Filtresini İçe Aktar, SVGZ dosyalarını okumaz; SVG dosyalarını okur +@msg JSON.parse: {why} (at offset {at}) JSON.parse: {why} (konum: {at}) +@msg JSON.stringify cannot write a structure that contains itself JSON.stringify kendini içeren bir yapıyı yazamaz +@msg Line Gap must be a number Satır Boşluğu bir sayı olmalıdır +@msg Namespace.prototype.toString needs a Namespace Namespace.prototype.toString için bir Namespace gerekir +@msg New Document profiles need the preferences folder, which this run doesn't have Yeni Belge profilleri için tercihler klasörü gerekir; bu çalıştırmada o klasör yok +@msg Number.prototype.{name} was called on a value that is not a number Number.prototype.{name}, sayı olmayan bir değer üzerinde çağrıldı +@msg Object.create's prototype must be an object or null Object.create için prototip bir nesne veya null olmalıdır +@msg Object.{function} was given a value that is not an object Object.{function} işlevine nesne olmayan bir değer verildi +@msg QName.prototype.toString needs a QName QName.prototype.toString için bir QName gerekir +@msg RegExp.prototype.{name} was called on a value that is not a RegExp object RegExp.prototype.{name}, RegExp nesnesi olmayan bir değer üzerinde çağrıldı +@msg Stencil Bridges: the selected art is too large or too detailed to bridge Şablon Köprüleri: seçili resim köprülenemeyecek kadar büyük veya ayrıntılı +@msg String.prototype.toString was called on a value that is not a string String.prototype.toString, dize olmayan bir değer üzerinde çağrıldı +@msg The {name} profile could not be read, so the new document has the default settings: {reason} {name} profili okunamadı, bu yüzden yeni belge varsayılan ayarları kullanıyor: {reason} +@msg Trap: more than {_1} pairs of objects lie close enough to trap, or too many objects share a horizontal range; trap fewer objects at a time Tuzak: {_1} çiftten fazla nesne tuzaklanacak kadar yakın duruyor veya çok fazla nesne aynı yatay aralığı paylaşıyor; bir seferde daha az nesne tuzaklayın +@msg Weed Box and Lines: no weeding line fits outside the art, and the weed box is off Ayıklama Kutusu ve Çizgileri: resmin dışına sığan bir ayıklama çizgisi yok ve ayıklama kutusu kapalı +@msg \\ at end of pattern desenin sonunda \\ +@msg `alignOn` cannot be empty `alignOn` boş olamaz +@msg `alignOn` must be a string `alignOn` bir dize olmalıdır +@msg `align` must be a string `align` bir dize olmalıdır +@msg `answer` for this {kind} dialog must be one of: {_1} bu {kind} iletişim kutusu için `answer` şunlardan biri olmalıdır: {_1} +@msg `answers` has more than {MAX_ANSWERS} answers `answers` içinde {MAX_ANSWERS} taneden fazla yanıt var +@msg `answers` is larger than 1 MiB `answers` 1 MiB'tan büyük +@msg `answers` must be a list of answers `answers` bir yanıt listesi olmalıdır +@msg `artboard` must be the index of an artboard of the document `artboard`, belgedeki bir çalışma yüzeyinin dizini olmalıdır +@msg `artboardsAt` must be [x, y] `artboardsAt` [x, y] olmalıdır +@msg `artboards` names an artboard the document does not have `artboards`, belgede olmayan bir çalışma yüzeyini belirtiyor +@msg `artboards` names an artboard twice `artboards` bir çalışma yüzeyini iki kez belirtiyor +@msg `at` must be [x, y] (got {at}) `at` [x, y] olmalıdır (verilen: {at}) +@msg `at` must be a point [x, y] `at` bir [x, y] noktası olmalıdır +@msg `beside` needs `side` `beside` için `side` gerekir +@msg `code` must be a whole number `code` bir tam sayı olmalıdır +@msg `colorMode` must be one of rgb, cmyk `colorMode` şunlardan biri olmalıdır: rgb, cmyk +@msg `colors` does not apply to the {name} reduction `colors`, {name} azaltması için geçerli değildir +@msg `colors` must be a whole number from 2 to 256 `colors` 2 ile 256 arasında bir tam sayı olmalıdır +@msg `colors` must be at least 9 for the uniform reduction tekdüze azaltma için `colors` en az 9 olmalıdır +@msg `colors` must be between 1 and {MAX_THEME_COLORS} (got {n}) `colors` 1 ile {MAX_THEME_COLORS} arasında olmalıdır (verilen: {n}) +@msg `count` must be a whole number from 0 to {MAX_COUNT} `count` 0 ile {MAX_COUNT} arasında bir tam sayı olmalıdır +@msg `ditherAmount` must be a number from 0 to 100 `ditherAmount` 0 ile 100 arasında bir sayı olmalıdır +@msg `fidelity` must be from {lo} to {hi} pt `fidelity` {lo} ile {hi} pt arasında olmalıdır +@msg `focal` and `radius` cannot be used together `focal` ve `radius` birlikte kullanılamaz +@msg `focal` must be an array of [subpath, anchor] pairs `focal`, [subpath, anchor] çiftlerinden oluşan bir dizi olmalıdır +@msg `focal` names [{si}, {ai}], which is not an anchor of the path `focal`, yolun bir bağlantı noktası olmayan [{si}, {ai}] çiftini belirtiyor +@msg `glyphAlternate` takes only null, which takes a glyph choice away (text.setGlyphAlternate makes one) `glyphAlternate` yalnızca null alır; null bir glif seçimini kaldırır (seçimi text.setGlyphAlternate yapar) +@msg `group` must be one of {_1} `group` şunlardan biri olmalıdır: {_1} +@msg `group` must be the Objects on Path group of `member` and `target` `group`, `member` ve `target` nesnelerinin Yol Üzerindeki Nesneler grubu olmalıdır +@msg `id` is an object id, not {v} `id` bir nesne kimliğidir, {v} değil +@msg `item` needs `index` `item` için `index` gerekir +@msg `kerningBefore` belongs to a line's first character, not to a character style (text.setRangeStyle sets it) `kerningBefore` bir karakter stiline değil, satırın ilk karakterine aittir (text.setRangeStyle ayarlar) +@msg `kinsokuType` must be "pushInFirst", "pushOutFirst" or "pushOutOnly" `kinsokuType` "pushInFirst", "pushOutFirst" veya "pushOutOnly" olmalıdır +@msg `leader` must be a string `leader` bir dize olmalıdır +@msg `max` must be 1 to {MAX_SUGGESTIONS} `max` 1 ile {MAX_SUGGESTIONS} arasında olmalıdır +@msg `name` must be a name that is not empty `name` boş olmayan bir ad olmalıdır +@msg `name` must not be empty `name` boş olmamalıdır +@msg `origin` must be [x, y] in points `origin` punto cinsinden [x, y] olmalıdır +@msg `picks` must be an array (got {v}) `picks` bir dizi olmalıdır (verilen: {v}) +@msg `picks` must hold 1 to {MAX_PICKS} picks (got {_1}) `picks` 1 ile {MAX_PICKS} arasında seçim içermelidir (verilen: {_1}) +@msg `points` must hold from 2 to 100000 points `points` 2 ile 100000 arasında nokta içermelidir +@msg `radius` must be 0 or more `radius` 0 veya daha büyük olmalıdır +@msg `rect` must be [x, y, width, height] `rect` [x, y, width, height] olmalıdır +@msg `rect` must be [x0, y0, x1, y1] (got {r}) `rect` [x0, y0, x1, y1] olmalıdır (verilen: {r}) +@msg `replace` must be a string `replace` bir dize olmalıdır +@msg `rows` must be lists of numbers or nulls, not {r} `rows`, sayı veya null listeleri olmalıdır, {r} değil +@msg `scale` must be a number from 0.001 to 1000 `scale` 0.001 ile 1000 arasında bir sayı olmalıdır +@msg `scope.{key}` must be a non-empty array `scope.{key}` boş olmayan bir dizi olmalıdır +@msg `scope` must be "document", {artboards} or {layers} `scope` "document", {artboards} veya {layers} olmalıdır +@msg `side` must be "left", "right", "top" or "bottom" `side` "left", "right", "top" veya "bottom" olmalıdır +@msg `side` places the artboard: leave out x, y, width and height `side` çalışma yüzeyini yerleştirir: x, y, width ve height değerlerini vermeyin +@msg `source` is the only path in series group `target` `source`, `target` seri grubundaki tek yoldur +@msg `spacing` makes more than {MAX_COUNT} lines across the box `spacing`, kutu boyunca {MAX_COUNT} taneden fazla çizgi oluşturuyor +@msg `spacing` must be more than 0 and at most {MAX_DISTANCE} pt `spacing` 0'dan büyük ve en fazla {MAX_DISTANCE} pt olmalıdır +@msg `target` must be an object of the same Objects on Path group as `member` `target`, `member` ile aynı Yol Üzerindeki Nesneler grubundaki bir nesne olmalıdır +@msg `tolerance` must be from 0 to 100 pt `tolerance` 0 ile 100 pt arasında olmalıdır +@msg `version` must be 0 or {_1} `version` 0 veya {_1} olmalıdır +@msg `version` must be 0 or {newest} `version` 0 veya {newest} olmalıdır +@msg `warichuAlign` must be one of {_1} `warichuAlign` şunlardan biri olmalıdır: {_1} +@msg `warichuLines` must be a whole number from {_1} to {_2} `warichuLines` {_1} ile {_2} arasında bir tam sayı olmalıdır +@msg `weight` must be from 0.01 to 1000 pt `weight` 0.01 ile 1000 pt arasında olmalıdır +@msg `weights` must be a list of {_1} numbers, one per row (got {v}) `weights`, her satır için bir tane olmak üzere {_1} sayıdan oluşan bir liste olmalıdır (verilen: {v}) +@msg `xml` must be a string `xml` bir dize olmalıdır +@msg `{KEY}` entry {n} gives the paragraph at byte {start} of {_1} other indents than an entry before it `{KEY}` içindeki {n} numaralı girdi, {_1} nesnesinin {start} numaralı baytındaki paragrafa önceki bir girdiden farklı girintiler veriyor +@msg `{KEY}` entry {n} must be an object `{KEY}` içindeki {n} numaralı girdi bir nesne olmalıdır +@msg `{KEY}` entry {n} sets neither `leftIndent` nor `firstLineIndent` `{KEY}` içindeki {n} numaralı girdi ne `leftIndent` ne de `firstLineIndent` ayarlıyor +@msg `{KEY}` entry {n}: `id` must be an object id `{KEY}` girdi {n}: `id` bir nesne kimliği olmalıdır +@msg `{KEY}` entry {n}: `start` must be a byte offset `{KEY}` girdi {n}: `start` bir bayt konumu olmalıdır +@msg `{KEY}` entry {n}: `{k}` must be a number from -{MAX_PARA} to {MAX_PARA} pt `{KEY}` girdi {n}: `{k}` -{MAX_PARA} ile {MAX_PARA} pt arasında bir sayı olmalıdır +@msg `{KEY}` entry {n}: no paragraph of {_1} starts at byte {start} `{KEY}` girdi {n}: {_1} nesnesinin hiçbir paragrafı {start} numaralı baytta başlamıyor +@msg `{KEY}` entry {n}: unknown key `{k}` `{KEY}` girdi {n}: bilinmeyen anahtar `{k}` +@msg `{KEY}` entry {n}: {_1} is not a type object `{KEY}` girdi {n}: {_1} bir metin nesnesi değil +@msg `{KEY}` is empty `{KEY}` boş +@msg `{KEY}` must be a list `{KEY}` bir liste olmalıdır +@msg `{KEY}` takes at most {MAX_PARAGRAPH_INDENTS} entries (got {_1}) `{KEY}` en fazla {MAX_PARAGRAPH_INDENTS} girdi alır (verilen: {_1}) +@msg `{KEY}` takes no `{other}` beside it `{KEY}` yanında `{other}` alamaz +@msg `{base}` is larger than {_1} MB `{base}` {_1} MB'tan büyük +@msg `{base}` is not in the DCS file's folder `{base}` DCS dosyasının klasöründe değil +@msg `{key}` holds more than {MAX_EDIT_WORDS} words `{key}` {MAX_EDIT_WORDS} taneden fazla sözcük içeriyor +@msg `{key}` must be 0 or more `{key}` 0 veya daha büyük olmalıdır +@msg `{key}` must be [x, y] numbers `{key}` [x, y] sayıları olmalıdır +@msg `{key}` must be a list of words `{key}` bir sözcük listesi olmalıdır +@msg `{key}` must be a list, not {v} `{key}` bir liste olmalıdır, {v} değil +@msg `{key}` must be a number or null, not {v} `{key}` bir sayı veya null olmalıdır, {v} değil +@msg `{key}` must be a whole number of 0 or more `{key}` 0 veya daha büyük bir tam sayı olmalıdır +@msg `{key}` must be from 0 to {MAX_DISTANCE} pt `{key}` 0 ile {MAX_DISTANCE} pt arasında olmalıdır +@msg `{key}` must be from {lo} to {hi}, not {v} `{key}` {lo} ile {hi} arasında olmalıdır, {v} değil +@msg `{key}` must be one of auto, always, never `{key}` şunlardan biri olmalıdır: auto, always, never +@msg `{key}` must be one of miter, round, bevel `{key}` şunlardan biri olmalıdır: miter, round, bevel +@msg `{key}` must be one word of at most {_1} characters `{key}` en fazla {_1} karakterlik tek bir sözcük olmalıdır +@msg `{key}` must hold single words of at most {_1} characters `{key}` en fazla {_1} karakterlik tek sözcükler içermelidir +@msg `{key}` must name an object attached to the path of an Objects on Path group `{key}`, bir Yol Üzerindeki Nesneler grubunun yoluna iliştirilmiş bir nesneyi belirtmelidir +@msg `{key}` names an object that is hidden or locked `{key}` gizli veya kilitli bir nesneyi belirtiyor +@msg `{name}` is a file of its own, which can only be found next to the DCS file's path `{name}` ayrı bir dosyadır ve yalnızca DCS dosyasının yolunun yanında bulunabilir +@msg `{name}`: {_1}: {e} `{name}`: {_1}: {e} +@msg `{u}` is no Unicode character `{u}` bir Unicode karakteri değil +@msg `{word}` isn't in the custom dictionary `{word}` özel sözlükte yok +@msg a CMap has too many mappings bir CMap çok fazla eşleme içeriyor +@msg a \\u escape needs four hexadecimal digits bir \\u kaçışı için dört onaltılık basamak gerekir +@msg a comma in an XPath expression must separate function arguments XPath ifadesindeki bir virgül, işlev bağımsız değişkenlerini ayırmalıdır +@msg a document holds at most {_1} SVG filters bir belge en fazla {_1} SVG filtresi içerir +@msg a document with unsaved changes has no recovery copy kaydedilmemiş değişiklikleri olan bir belgenin kurtarma kopyası yok +@msg a font's data is too large bir yazı tipinin verileri çok büyük +@msg a font's subroutines are too large bir yazı tipinin alt yordamları çok büyük +@msg a function declaration without a name adı olmayan bir işlev bildirimi +@msg a host value has too many entries bir ana bilgisayar değeri çok fazla girdi içeriyor +@msg a host value is nested too deep bir ana bilgisayar değeri çok derin iç içe geçmiş +@msg a namespace declaration uses a reserved prefix or URI bir ad alanı bildirimi ayrılmış bir önek veya URI kullanıyor +@msg a namespace qualifier is undefined bir ad alanı niteleyicisi tanımlı değil +@msg a namespace with an empty URI cannot have a prefix URI'si boş olan bir ad alanının öneki olamaz +@msg a number has no digits bir sayının rakamı yok +@msg a number's exponent has no digits bir sayının üssünde rakam yok +@msg a number's fraction has no digits bir sayının kesir kısmında rakam yok +@msg a property descriptor cannot have both a value or writable and a get or set bir özellik tanımlayıcısı hem value veya writable hem de get veya set içeremez +@msg a property descriptor must be an object bir özellik tanımlayıcısı bir nesne olmalıdır +@msg a property's {name} must be a function or undefined bir özelliğin {name} değeri bir işlev veya undefined olmalıdır +@msg a stream in it would decode to more than 256 MB, or its decode parameters can't be applied içindeki bir akışın kodu çözülünce 256 MB'ı aşıyor veya kod çözme parametreleri uygulanamıyor +@msg a string holds a control character bir dize denetim karakteri içeriyor +@msg a string holds an escape sequence JSON does not have bir dize JSON'da olmayan bir kaçış dizisi içeriyor +@msg a string is not closed bir dize kapatılmamış +@msg an SVG filter is named by its id: give `xml` with `name` bir SVG filtresi kimliğiyle adlandırılır: `xml` değerini `name` ile birlikte verin +@msg an XML element has two attributes with the same name bir XML öğesinde aynı ada sahip iki öznitelik var +@msg an XML value cannot be inserted into itself or its descendants bir XML değeri kendisine veya alt öğelerine eklenemez +@msg an XML value's children cannot be assigned by position bir XML değerinin alt öğeleri konuma göre atanamaz +@msg an XML value's children cannot be deleted by position bir XML değerinin alt öğeleri konuma göre silinemez +@msg an XMLList converts to XML only when it has one item bir XMLList yalnızca tek öğesi olduğunda XML'e dönüşür +@msg an XPath node test is missing bir XPath düğüm testi eksik +@msg an XPath operand is missing bir XPath işleneni eksik +@msg an XPath operator is missing bir XPath işleci eksik +@msg an XPath predicate or step cannot follow here burada bir XPath yüklemi veya adımı gelemez +@msg an XPath predicate or step follows a value that is not a node-set bir XPath yüklemi veya adımı, düğüm kümesi olmayan bir değerin ardından geliyor +@msg an XPath step is missing bir XPath adımı eksik +@msg an image couldn't be decoded and is missing from the picture bir görüntünün kodu çözülemedi ve resimde eksik +@msg an image of {w} × {h} pixels is too large to convert (at most {_1} pixels) {w} × {h} piksellik bir görüntü dönüştürülemeyecek kadar büyük (en fazla {_1} piksel) +@msg apply was called on a value that is not a function apply, işlev olmayan bir değer üzerinde çağrıldı +@msg area type in a thread cannot use Dynamic Text: {frames} zincirli metindeki alan metni Dinamik Metin kullanamaz: {frames} +@msg array literal too long dizi değişmezi çok uzun +@msg assignment to a constant binding sabit bir bağlamaya atama +@msg at least one row that isn't excluded needs a weight above 0 hariç tutulmayan en az bir satırın ağırlığı 0'dan büyük olmalıdır +@msg bad point {v}: expected [x, y] hatalı nokta {v}: [x, y] bekleniyordu +@msg blend must be a mode name blend bir mod adı olmalıdır +@msg both sides of an XPath | must select nodes bir XPath | işlecinin iki tarafı da düğüm seçmelidir +@msg canceled iptal edildi +@msg cannot convert the object to a primitive value nesne ilkel bir değere dönüştürülemiyor +@msg cannot convert undefined or null to an object undefined veya null bir nesneye dönüştürülemez +@msg character dimensions cannot be represented with the source text transform karakter boyutları kaynak metin dönüşümüyle ifade edilemiyor +@msg character dimensions cannot be represented with the target text transform karakter boyutları hedef metin dönüşümüyle ifade edilemiyor +@msg continuation must be an array of path chunks continuation, yol parçalarından oluşan bir dizi olmalıdır +@msg continuation requires points continuation için points gerekir +@msg each path chunk must contain 1 to 4096 points her yol parçası 1 ile 4096 arasında nokta içermelidir +@msg each pick is {{at: [x, y]}} or {{rect: [x0, y0, x1, y1]}} (got {v}) her seçim {{at: [x, y]}} veya {{rect: [x0, y0, x1, y1]}} biçimindedir (verilen: {v}) +@msg each weight must be a number of 0 or more (got {v}) her ağırlık 0 veya daha büyük bir sayı olmalıdır (verilen: {v}) +@msg finally table {t} out of range finally tablosu {t} aralık dışında +@msg flags cannot be given with a RegExp object RegExp nesnesiyle birlikte bayrak verilemez +@msg function declaration index out of range işlev bildirimi dizini aralık dışında +@msg give `char`, `text`, `code` or `unicode` `char`, `text`, `code` veya `unicode` verin +@msg give `count` or `spacing`, not both `count` veya `spacing` verin, ikisini birden değil +@msg give `name`, an SVG filter's name bir SVG filtresinin adı olan `name` değerini verin +@msg give `path`, an SVG file, or `svg`, SVG text bir SVG dosyası olan `path` veya SVG metni olan `svg` verin +@msg give `xml`, one SVG element tek bir SVG öğesi olan `xml` değerini verin +@msg give exactly one of `at`, `rect` and `points` `at`, `rect` ve `points` değerlerinden tam olarak birini verin +@msg give exactly one of `path`, `data` and `dataBase64` `path`, `data` ve `dataBase64` değerlerinden tam olarak birini verin +@msg give index or indexes, not both index veya indexes verin, ikisini birden değil +@msg give one element tek bir öğesi verin +@msg give opacity or blend opacity veya blend verin +@msg handler at {_1} expects {_2} values but its range starts with {d} {_1} konumundaki işleyici {_2} değer bekliyor, ancak aralığı {d} ile başlıyor +@msg handler depth too large işleyici derinliği çok büyük +@msg handler range {_1}..{_2} out of range işleyici aralığı {_1}..{_2} aralık dışında +@msg hiddenLayers must be true or false hiddenLayers true veya false olmalıdır +@msg hvcC hvcC +@msg images in a spot ink whose samples couldn't be read were imported in RGB örnekleri okunamayan spot mürekkepli görüntüler RGB olarak içe aktarıldı +@msg images past the most pixels one file may hold were left out bir dosyanın tutabileceği en fazla piksel sayısını aşan görüntüler dışarıda bırakıldı +@msg images too large to read were left out okunamayacak kadar büyük görüntüler dışarıda bırakıldı +@msg indexes may hold at most {MAX_GUIDE_INDEXES} entries indexes en fazla {MAX_GUIDE_INDEXES} girdi içerebilir +@msg indexes must be an array of guide indexes indexes, kılavuz dizinlerinden oluşan bir dizi olmalıdır +@msg instruction out of range yönerge aralık dışında +@msg instruction {pc} ({op}) pops below the stack {pc} numaralı yönerge ({op}) yığının altına iniyor +@msg instruction {pc} reached with stack depths {seen} and {d} {pc} numaralı yönergeye {seen} ve {d} yığın derinlikleriyle ulaşıldı +@msg invalid array length geçersiz dizi uzunluğu +@msg invalid group geçersiz grup +@msg invalid object id {v}: expected a non-negative integer geçersiz nesne kimliği {v}: negatif olmayan bir tam sayı bekleniyordu +@msg invalid regular expression flag '{_1}' geçersiz düzenli ifade bayrağı '{_1}' +@msg invalid regular expression: {m} geçersiz düzenli ifade: {m} +@msg invalid time value geçersiz zaman değeri +@msg is a confirm's answer, whose `value` must be true or false bir confirm yanıtıdır ve `value` değeri true veya false olmalıdır +@msg is a prompt's answer, whose `value` must be a string or null bir prompt yanıtıdır ve `value` değeri bir dize veya null olmalıdır +@msg is an alert's answer, whose `value` must be "ok" bir alert yanıtıdır ve `value` değeri "ok" olmalıdır +@msg is longer than 16 KiB 16 KiB'tan uzun +@msg it draws its image through a clipping path görüntüsünü bir kırpma yolu içinden çiziyor +@msg it draws no image hiçbir görüntü çizmiyor +@msg it is larger than {MAX_DICTIONARY_FILE_BYTES} bytes {MAX_DICTIONARY_FILE_BYTES} bayttan büyük +@msg it isn't a file bir dosya değil +@msg it names {_1} plates, and at most {MAX_PLATES} are read {_1} kalıp belirtiyor ve en fazla {MAX_PLATES} tanesi okunuyor +@msg its art is too long or too detailed for a head resmi bir ok ucu için çok uzun veya çok ayrıntılı +@msg its art paints nothing resmi hiçbir şey boyamıyor +@msg its image is too large to read görüntüsü okunamayacak kadar büyük +@msg its plates are too large: more than {MAX_SAMPLES} pixels together kalıpları çok büyük: toplamda {MAX_SAMPLES} pikselden fazla +@msg its plates are too large: {_1} plates of {w} × {h} pixels kalıpları çok büyük: {w} × {h} piksellik {_1} kalıp +@msg its plates can't be kept together kalıpları bir arada tutulamıyor +@msg its shapes could not be combined into one şekilleri tek bir şekilde birleştirilemedi +@msg jump to {pc}, past the end sonun ötesindeki {pc} konumuna atlama +@msg legacyNameEncoding must be one of {_1} legacyNameEncoding şunlardan biri olmalıdır: {_1} +@msg localize: the first argument must be a localization object or a string localize: ilk bağımsız değişken bir yerelleştirme nesnesi veya bir dize olmalıdır +@msg missing `picks` `picks` eksik +@msg missing `word` `word` eksik +@msg must be an object with `kind` and `value` `kind` ve `value` içeren bir nesne olmalıdır +@msg must have `kind` alert, confirm or prompt `kind` değeri alert, confirm veya prompt olmalıdır +@msg must have exactly `kind` and `value` yalnızca `kind` ve `value` içermelidir +@msg needs a closing quote after the name addan sonra bir kapanış tırnağı gerekir +@msg needs a name bir ad gerekir +@msg needs a name of at most 64 bytes en fazla 64 baytlık bir ad gerekir +@msg needs a name of letters, digits and _, or a quoted name harf, rakam ve _ karakterlerinden oluşan bir ad veya tırnak içinde bir ad gerekir +@msg needs a name without control characters denetim karakteri içermeyen bir ad gerekir +@msg nesting too deep iç içe geçme çok derin +@msg no HP-GL format HP-GL biçimi yok +@msg no New Document profile called `{shown}` ({_1}) `{shown}` adlı bir Yeni Belge profili yok ({_1}) +@msg no SVG filter at index {k} {k} dizininde SVG filtresi yok +@msg no arrowheads file here burada ok uçları dosyası yok +@msg no character has code {code} hiçbir karakterin kodu {code} değil +@msg no custom arrowhead {name} (see stroke.arrowheads.list) {name} adlı özel ok ucu yok (bkz. stroke.arrowheads.list) +@msg no file to open açılacak dosya yok +@msg no instructions yönerge yok +@msg no layer to rename yeniden adlandırılacak katman yok +@msg no random numbers ({e}) rastgele sayı yok ({e}) +@msg no selected or given object has a visible 3D effect seçili veya verilen nesnelerin hiçbirinde görünür bir 3D efekti yok +@msg no such artboard {v} böyle bir çalışma yüzeyi yok: {v} +@msg no symbol named `{_1}` `{_1}` adlı bir sembol yok +@msg node {_1} already has the text variable `{_2}` {_1} düğümünde `{_2}` metin değişkeni zaten var +@msg not a DCS file bir DCS dosyası değil +@msg not a RegExp object bir RegExp nesnesi değil +@msg not a regular expression bir düzenli ifade değil +@msg not an action set: the text doesn't start with /version and a number bir eylem seti değil: metin /version ve bir sayıyla başlamıyor +@msg nothing to repeat yinelenecek bir şey yok +@msg numbers out of order in {_1} quantifier {_1} niceleyicisinde sayılar sırasız +@msg object {_1} needs a 3D effect {_1} nesnesinde bir 3D efekti olmalıdır +@msg object {_1}: a hollow Extrude & Bevel has no caps: turn on Cap to map a graphic nesne {_1}: içi boş bir Kalıp Çıkarma ve Eğim efektinin kapakları yoktur: bir grafik eşlemek için Kapak seçeneğini açın +@msg object {_1}: with a depth of 0 the object has one face: map its graphics onto the front nesne {_1}: derinlik 0 olduğunda nesnenin tek yüzü vardır: grafiklerini ön yüze eşleyin +@msg object {_1}: {_2} nesne {_1}: {_2} +@msg object {_1}: {e} nesne {_1}: {e} +@msg object {_1}: {name} at index {index} has no lighting presets; set its lights with effect.setParams nesne {_1}: {index} dizinindeki {name} için ışık ön ayarı yok; ışıklarını effect.setParams ile ayarlayın +@msg opacity must be a number opacity bir sayı olmalıdır +@msg operand too large işlenen çok büyük +@msg order is a whole number from 0 to {others}, not `{v}` order 0 ile {others} arasında bir tam sayıdır, `{v}` değil +@msg path chunks must share their boundary point yol parçaları sınır noktalarını paylaşmalıdır +@msg pdfCompatible: false needs the artboards to keep the editable artwork when useArtboards is false pdfCompatible: false, useArtboards false olduğunda düzenlenebilir resmi korumak için çalışma yüzeylerine ihtiyaç duyar +@msg point x must be a number noktanın x değeri bir sayı olmalıdır +@msg point y must be a number noktanın y değeri bir sayı olmalıdır +@msg points must be [x,y] pairs points [x,y] çiftleri olmalıdır +@msg points must be finite canvas points points sonlu tuval noktaları olmalıdır +@msg range out of order in character class karakter sınıfında aralık sırasız +@msg reduce of an empty array with no initial value başlangıç değeri olmadan boş bir dizide reduce +@msg regular expression flag '{_1}' given twice düzenli ifade bayrağı '{_1}' iki kez verildi +@msg sampled text would exceed the canvas (coordinates out of range) örneklenen metin tuvali aşacaktır (koordinatlar aralık dışındadır) +@msg select an SVG filter bir SVG filtresi seçin +@msg select an object with a 3D effect 3D efekti olan bir nesne seçin +@msg select an object with a 3D effect, or give its id in ids 3D efekti olan bir nesne seçin veya kimliğini ids içinde verin +@msg select one layer, group or object to rename yeniden adlandırmak için tek bir katman, grup veya nesne seçin +@msg select the art to weed ayıklanacak resmi seçin +@msg select type on a path or area type yol üzerindeki yazıyı veya alan metnini seçin +@msg side is left or right, not `{v}` side left veya right olur, `{v}` değil +@msg source text transform is collapsed or unrepresentable kaynak metin dönüşümü çökmüş veya ifade edilemiyor +@msg table must be true or false table true veya false olmalıdır +@msg takes one name tek bir ad alır +@msg target text transform is collapsed or unrepresentable hedef metin dönüşümü çökmüş veya ifade edilemiyor +@msg that makes too many pieces (at most 100000) or dash steps: simplify the dash pattern or make the dashes longer bu çok fazla parça (en fazla 100000) veya kesik çizgi adımı oluşturuyor: çizgi desenini basitleştirin veya kesik çizgileri uzatın +@msg the Layers panel is not shown Katmanlar paneli gösterilmiyor +@msg the Layers panel's search, filter or Show Layers Only hides its row Katmanlar panelinin araması, filtresi veya Yalnızca Katmanları Göster seçeneği bu satırı gizliyor +@msg the Objects on Path group is hidden or locked Yol Üzerindeki Nesneler grubu gizli veya kilitli +@msg the SVG file is larger than {MAX_IMPORT_BYTES} bytes SVG dosyası {MAX_IMPORT_BYTES} bayttan büyük +@msg the XML operation needs an XML or XMLList value XML işlemi için bir XML veya XMLList değeri gerekir +@msg the XPath expression does not evaluate to a node-set XPath ifadesinin sonucu bir düğüm kümesi değil +@msg the XPath expression ends early XPath ifadesi erken bitiyor +@msg the XPath expression has an unmatched ) XPath ifadesinde eşleşmeyen bir ) var +@msg the XPath expression has an unmatched ] XPath ifadesinde eşleşmeyen bir ] var +@msg the XPath expression has an unmatched closing bracket XPath ifadesinde eşleşmeyen bir kapanış ayracı var +@msg the XPath expression selects a namespace node, which is not an XML value XPath ifadesi bir ad alanı düğümü seçiyor; bu bir XML değeri değildir +@msg the XPath expression selects the root node, which is not an XML value XPath ifadesi kök düğümü seçiyor; bu bir XML değeri değildir +@msg the XPath function {name} needs a node-set {name} XPath işlevi için bir düğüm kümesi gerekir +@msg the XPath function {name} takes the wrong number of arguments {name} XPath işlevine yanlış sayıda bağımsız değişken verildi +@msg the XPath name functions need a node-set XPath ad işlevleri için bir düğüm kümesi gerekir +@msg the XPath prefix {shown} is not bound to a namespace {shown} XPath öneki bir ad alanına bağlı değil +@msg the XPath variable ${shown} is not bound ${shown} XPath değişkeni bağlı değil +@msg the argument list is not an object bağımsız değişken listesi bir nesne değil +@msg the art of a graph design in a graph series is drawn again from the design: edit the design to change it bir grafik serisindeki grafik tasarımının çizimi tasarımdan yeniden çizilir: değiştirmek için tasarımı düzenleyin +@msg the artwork is too large for EPS: what follows 256 MB of PostScript was left out resim EPS için çok büyük: 256 MB'lık PostScript'ten sonrası dışarıda bırakıldı +@msg the bitmaps hold more pixels than one file may bitmapler bir dosyanın tutabileceğinden fazla piksel içeriyor +@msg the code runs past its last instruction kod son yönergesinin ötesine geçiyor +@msg the curve tolerance must be from 0.01 to 10 points eğri toleransı 0.01 ile 10 punto arasında olmalıdır +@msg the custom dictionary couldn't be saved to {_1}: {e} özel sözlük şuraya kaydedilemedi: {_1}: {e} +@msg the custom dictionary {_1} can't be read ({why}), so it is left as it is özel sözlük {_1} okunamıyor ({why}), bu yüzden olduğu gibi bırakıldı +@msg the document already has an SVG filter named {name} belgede {name} adlı bir SVG filtresi zaten var +@msg the document has another SVG filter named {name}: use svgFilter.apply, or svgFilter.define with `replace` to edit it belgede {name} adlı başka bir SVG filtresi var: svgFilter.apply kullanın veya düzenlemek için svgFilter.define komutunu `replace` ile kullanın +@msg the document has no SVG filter named {name} belgede {name} adlı bir SVG filtresi yok +@msg the document has no SVG filter named {r} belgede {r} adlı bir SVG filtresi yok +@msg the document has no color swatches belgede renk örneği yok +@msg the document's swatches hold {_1} colors; the document reduction takes at most 255 belgenin renk örnekleri {_1} renk içeriyor; belge azaltması en fazla 255 renk alır +@msg the file isn't valid SVG: {e} dosya geçerli bir SVG değil: {e} +@msg the file names no plate dosya hiçbir kalıp belirtmiyor +@msg the function's prototype is not an object işlevin prototipi bir nesne değil +@msg the guide is hidden or locked kılavuz gizli veya kilitli +@msg the library's file is outside the read roots kütüphanenin dosyası okuma köklerinin dışında +@msg a linked JavaScript file is outside the read roots bağlantılı bir JavaScript dosyası okuma köklerinin dışında +@msg the line is too long, or the paths it passes too many, to check çizgi denetlenemeyecek kadar uzun veya geçtiği yollar çok fazla +@msg the method needs an XML value yöntem için bir XML değeri gerekir +@msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) boya bir serbest biçimli degrade değil (paint.editGradient {kind} ile bir tane uygulayın) +@msg the parameters or body do not form one function parametreler veya gövde tek bir işlev oluşturmuyor +@msg the pasted SVG filter {name} draws differently from the document's filter of that name, and no free name fits it yapıştırılan {name} SVG filtresi belgedeki aynı adlı filtreden farklı çiziyor ve ona uyan boş bir ad yok +@msg the paths are too many or too tangled to find where they cross yollar, kesiştikleri yerler bulunamayacak kadar çok veya karışık +@msg the pen table holds more than 255 pens kalem tablosu 255 taneden fazla kalem içeriyor +@msg the plates can't be kept kalıplar korunamıyor +@msg the position table does not match the instructions konum tablosu yönergelerle eşleşmiyor +@msg the prompt's text is longer than {MAX_PROMPT_BYTES} bytes istem metni {MAX_PROMPT_BYTES} bayttan uzun +@msg the radix must be between 2 and 36 taban 2 ile 36 arasında olmalıdır +@msg the rectangle or line reaches too many paths to check dikdörtgen veya çizgi denetlenemeyecek kadar çok yola ulaşıyor +@msg the right side of 'in' is not an object 'in' işlecinin sağ tarafı bir nesne değil +@msg the right side of 'instanceof' is not a function 'instanceof' işlecinin sağ tarafı bir işlev değil +@msg the selected art is nested more than {MAX_DEPTH} levels deep seçili resim {MAX_DEPTH} düzeyden daha derin iç içe geçmiş +@msg the selected art is too large to measure seçili resim ölçülemeyecek kadar büyük +@msg the selection has no outlines to weed around seçimde çevresi ayıklanacak anahat yok +@msg the value bind was called on is not a function bind'ın çağrıldığı değer bir işlev değil +@msg the value is not a constructor değer bir oluşturucu değil +@msg the value is not a function değer bir işlev değil +@msg the value is not a valid XML name değer geçerli bir XML adı değil +@msg the value is not an XML attribute name değer bir XML öznitelik adı değil +@msg the value is not an XML name değer bir XML adı değil +@msg the weeding lines cross the art's outlines too many times to measure; use fewer lines ayıklama çizgileri resmin anahatlarını ölçülemeyecek kadar çok kez kesiyor; daha az çizgi kullanın +@msg the weeding lines pass too close to too many outline segments to measure; use fewer lines or a smaller gap ayıklama çizgileri ölçülemeyecek kadar çok anahat parçasının çok yakınından geçiyor; daha az çizgi veya daha küçük bir boşluk kullanın +@msg the weeding lines would be more than {max_pieces} pieces ayıklama çizgileri {max_pieces} parçadan fazla olurdu +@msg the {_1} plate lies outside the file {_1} kalıbı dosyanın dışında +@msg this is a binary DXF file, which can't be read: save it from the CAD app as an ASCII DXF and open that bu ikili bir DXF dosyası ve okunamıyor: CAD uygulamasından ASCII DXF olarak kaydedip onu açın +@msg this warp's points can't be edited: use Reset with Mesh first bu çarpıtmanın noktaları düzenlenemez: önce Ağ ile Sıfırla komutunu kullanın +@msg toExponential() digits must be between 0 and 20 toExponential() basamak sayısı 0 ile 20 arasında olmalıdır +@msg toFixed() digits must be between 0 and 20 toFixed() basamak sayısı 0 ile 20 arasında olmalıdır +@msg toISOString is not a function toISOString bir işlev değil +@msg toPrecision() argument must be between 1 and 21 toPrecision() bağımsız değişkeni 1 ile 21 arasında olmalıdır +@msg toSource: a getter cannot be written as source toSource: bir alıcı kaynak olarak yazılamaz +@msg toSource: an array with properties besides its elements, a property that is not enumerable or another prototype cannot be written as source toSource: öğelerinin yanında özellikleri, numaralandırılamayan bir özelliği veya başka bir prototipi olan bir dizi kaynak olarak yazılamaz +@msg toSource: an object with a property that is not enumerable, or whose prototype is not Object.prototype, cannot be written as source toSource: numaralandırılamayan bir özelliği olan veya prototipi Object.prototype olmayan bir nesne kaynak olarak yazılamaz +@msg toSource: the source is too long toSource: kaynak çok uzun +@msg toSource: the value contains itself toSource: değer kendini içeriyor +@msg toSource: the value has too many entries toSource: değer çok fazla girdi içeriyor +@msg toSource: the value is nested too deep toSource: değer çok derin iç içe geçmiş +@msg toString is not a function toString bir işlev değil +@msg too many arguments çok fazla bağımsız değişken +@msg too many quantifiers çok fazla niceleyici +@msg unknown OpenType feature `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt; prefix - to turn off; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take an alternate's number as `tag=N` with N from 0 to {_1}, as `salt=2`) bilinmeyen OpenType özelliği `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt; kapatmak için başına - koyun; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom ve aalt bir alternatifin numarasını `tag=N` biçiminde alır, N 0 ile {_1} arasındadır, örneğin `salt=2`) +@msg unknown dither `{d}` (diffusion, pattern, noise or none) bilinmeyen renk taklidi `{d}` (diffusion, pattern, noise veya none) +@msg unknown panel `{panel}` bilinmeyen panel `{panel}` +@msg unknown parameter `{key}` bilinmeyen parametre `{key}` +@msg unknown reduction `{reduction}` (selective, perceptual, adaptive, web, gray, blackWhite, uniform or document) bilinmeyen azaltma `{reduction}` (selective, perceptual, adaptive, web, gray, blackWhite, uniform veya document) +@msg unmatched ')' eşleşmeyen ')' +@msg unterminated character class sonlandırılmamış karakter sınıfı +@msg unterminated group sonlandırılmamış grup +@msg wordGap and lineGap need area type in the selection wordGap ve lineGap için seçimde alan metni olmalıdır +@msg xpath needs its variables as an object xpath, değişkenlerini bir nesne olarak ister +@msg xpath needs the expression as a string xpath, ifadeyi bir dize olarak ister +@msg {GRANT_NOT_REMOVED}, and its settings and cache can't be moved back from {_1} to {_2}: {e} {GRANT_NOT_REMOVED}; ayrıca ayarları ve önbelleği {_1} konumundan {_2} konumuna geri taşınamıyor: {e} +@msg {_1} is not a folder: {e} {_1} bir klasör değil: {e} +@msg {_1}: {_2} and {_3} are in the way {_1}: {_2} ve {_3} engel oluyor +@msg {code}: {0} {code}: {0} +@msg {dir}: {e} {dir}: {e} +@msg {file} names more than one linked JavaScript file {file} birden fazla bağlantılı JavaScript dosyası belirtiyor +@msg {k}: a custom arrowhead's path needs an area to fill and at most {most} anchors and {most} subpaths, each anchor within {far} head units of its tip {k}: özel bir ok ucunun yolunda doldurulacak bir alan, en fazla {most} bağlantı noktası ve {most} alt yol olmalı, her bağlantı noktası ucundan en fazla {far} ok ucu birimi uzakta bulunmalıdır +@msg {k}: bad custom arrowhead path: {e} {k}: hatalı özel ok ucu yolu: {e} +@msg {k}: bad custom arrowhead: {e} {k}: hatalı özel ok ucu: {e} +@msg {k}: custom must be a name {k}: custom bir ad olmalıdır +@msg {name} must be a number {name} bir sayı olmalıdır +@msg {path}: copy takes a DCS file only when its plates are inside it; relink to it where its plate files are {path}: copy bir DCS dosyasını yalnızca kalıpları içindeyse alır; kalıp dosyalarının bulunduğu yerde ona yeniden bağlayın +@msg {path}: larger than {_1} MB {path}: {_1} MB'tan büyük +@msg {shown} is not an XPath 1.0 function {shown} bir XPath 1.0 işlevi değil +@msg {v} names no layer or sublayer {v} hiçbir katmanı veya alt katmanı belirtmiyor +@msg {what} is not a function {what} bir işlev değil +@msg {what} would print more than {MAX_COPIES_PER_SHEET} copies on a sheet: scale it up {what} bir yaprağa {MAX_COPIES_PER_SHEET} taneden fazla kopya yazdırırdı: ölçeğini büyütün +@msg {what} {i} out of range {what} {i} aralık dışında +@msg A profile supports one Revolve effect. Edit the existing effect's options instead. Bir profil tek bir Döndürme efektini destekler. Bunun yerine mevcut efektin seçeneklerini düzenleyin. +@msg Add Points at Crossings: a path went missing Kesişimlere Nokta Ekle: bir yol kayboldu +@msg CSS options: {e} CSS seçenekleri: {e} +@msg CSV has a header but no data rows CSV'de bir başlık var ama veri satırı yok +@msg CSV holds NUL bytes: save it as UTF-8, or as UTF-16 with a byte-order mark CSV, NUL baytları içeriyor: UTF-8 olarak veya bayt sırası işaretiyle UTF-16 olarak kaydedin +@msg CSV is empty CSV boş +@msg CSV is larger than {MAX_CSV_BYTES} bytes CSV {MAX_CSV_BYTES} bayttan büyük +@msg CSV is not UTF-16 CSV, UTF-16 değil +@msg CSV is not UTF-8 CSV, UTF-8 değil +@msg CSV would be larger than {MAX_CSV_BYTES} bytes CSV {MAX_CSV_BYTES} bayttan büyük olurdu +@msg Choose original artwork, not a dimension's generated paths Bir boyutun oluşturduğu yolları değil, özgün resmi seçin +@msg Contour: select paths or shapes Kontur: yolları veya şekilleri seçin +@msg Contour: the Offset Path effect is not available Kontur: Ofset Yolu efekti kullanılamıyor +@msg Create needs fills, strokes or both Oluştur için dolgular, konturlar veya her ikisi gerekir +@msg DXF options: {e} DXF seçenekleri: {e} +@msg DXF scale must be a positive number up to {_1}, not {scale} DXF ölçeği en fazla {_1} olan pozitif bir sayı olmalıdır, {scale} değil +@msg DXF {field} `{s}`: {allowed} DXF {field} `{s}`: {allowed} +@msg Dimension is locked or hidden Boyut kilitli veya gizli +@msg Dimension mode does not match its source Boyut modu kaynağıyla eşleşmiyor +@msg Draw Inside needs exactly one selected path, compound path or text İçine Çiz için tam olarak bir seçili yol, bileşik yol veya metin gerekir +@msg EPS Save writes all artwork: use document.export for selected-only EPS EPS Kaydet tüm resmi yazar: yalnızca seçili resmi içeren EPS için document.export kullanın +@msg EPS flattener: {e} EPS düzleştirici: {e} +@msg EPS options: {e} EPS seçenekleri: {e} +@msg EPS {field} `{s}`: {allowed} EPS {field} `{s}`: {allowed} +@msg Export for Screens writes png, png8, jpg, webp, gif, tiff, bmp, tga, psd, svg, svgz, pdf, eps, ai or vectorcraft Ekranlar için Dışa Aktar şunları yazar: png, png8, jpg, webp, gif, tiff, bmp, tga, psd, svg, svgz, pdf, eps, ai veya vectorcraft +@msg Flare click coordinates must be finite numbers Mercek parlaması tıklama koordinatları sonlu sayılar olmalıdır +@msg HTML Text applies to object slices of type only HTML Metni yalnızca metin nesnesi dilimlerine uygulanır +@msg Identify Objects By is XML ID: the name must be a valid XML ID (start with a letter, underscore or colon; no spaces) Nesneleri Tanımlama Ölçütü XML Kimliği: ad geçerli bir XML kimliği olmalıdır (harf, alt çizgi veya iki nokta ile başlar; boşluk içermez) +@msg Image Trace failed: internal error: its thread stopped (please report this bug) Görüntü İzleme başarısız oldu: iç hata: iş parçacığı durdu (lütfen bu hatayı bildirin) +@msg Image Trace failed: {e} Görüntü İzleme başarısız oldu: {e} +@msg Image Trace finished, but its document was closed Görüntü İzleme tamamlandı, ancak belgesi kapatılmıştı +@msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Görüntü İzleme tamamlandı, ancak bu sırada görüntü veya ayarları değişti: yeniden izleyin +@msg Invalid dimension offset Geçersiz boyut ofseti +@msg Invalid point Geçersiz nokta +@msg Join: a subpath went missing Birleştir: bir alt yol kayboldu +@msg Lock Workspace is not available in VectorCraft Çalışma Alanını Kilitle, VectorCraft'ta kullanılamaz +@msg Move Panel to New Window is not available: floating panels stay in the main window Paneli Yeni Pencereye Taşı kullanılamaz: yüzen paneller ana pencerede kalır +@msg Offset Path: the path is too complex to offset Ofset Yolu: yol ofsetlenemeyecek kadar karmaşık +@msg Offset Path: {e} Ofset Yolu: {e} +@msg PDF content is incomplete or exceeds the reader's limits; no document was imported PDF içeriği eksik veya okuyucunun sınırlarını aşıyor; hiçbir belge içe aktarılmadı +@msg PDF flattener: {e} PDF düzleştirici: {e} +@msg PDF options: {e} PDF seçenekleri: {e} +@msg Recolor Artwork is no longer open Resmi Yeniden Renklendir artık açık değil +@msg SVG is not UTF-8, UTF-16 or ISO 8859-1 SVG; UTF-8, UTF-16 veya ISO 8859-1 değil +@msg Save writes one artboard: name one, or export several with document.export Kaydet tek bir çalışma yüzeyi yazar: birini belirtin veya birkaçını document.export ile dışa aktarın +@msg Select a dimension first Önce bir boyut seçin +@msg Select dimensions to update Güncellenecek boyutları seçin +@msg Select only dimensions Yalnızca boyutları seçin +@msg Select two or more objects, or a group İki veya daha fazla nesne ya da bir grup seçin +@msg Shaper needs 1–64 source paths Şekillendirici için 1–64 kaynak yol gerekir +@msg Switch x/y is for scatter graphs x/y Değiştir dağılım grafikleri içindir +@msg Text options: {e} Metin seçenekleri: {e} +@msg `align` is start, center or end `align` start, center veya end olur +@msg `anchors` must be an array of [subpath, anchor] pairs `anchors`, [subpath, anchor] çiftlerinden oluşan bir dizi olmalıdır +@msg `anchors` must list anchor indices (0, 1, 2…), not {k} `anchors` bağlantı noktası dizinlerini (0, 1, 2…) listelemelidir, {k} değil +@msg `anchors` must list anchor indices (0, 1, 2…), not {v} `anchors` bağlantı noktası dizinlerini (0, 1, 2…) listelemelidir, {v} değil +@msg `artboards` must be a list of artboard indices `artboards` bir çalışma yüzeyi dizinleri listesi olmalıdır +@msg `asset` is the asset id (see assets.list) `asset` varlık kimliğidir (bkz. assets.list) +@msg `at` must be a byte offset `at` bir bayt konumu olmalıdır +@msg `autoLeading` must be a number `autoLeading` bir sayı olmalıdır +@msg `background` must be "", "matte" or #rrggbb `background` "", "matte" veya #rrggbb olmalıdır +@msg `burasagari` must be "none", "standard" or "forced" `burasagari` "none", "standard" veya "forced" olmalıdır +@msg `center` must be [x, y] `center` [x, y] olmalıdır +@msg `charAlign` must be "romanBaseline", "emBoxTop", "emBoxCenter", "emBoxBottom", "icfTop" or "icfBottom" `charAlign` "romanBaseline", "emBoxTop", "emBoxCenter", "emBoxBottom", "icfTop" veya "icfBottom" olmalıdır +@msg `charDirection` must be "default", "leftToRight" or "rightToLeft" `charDirection` "default", "leftToRight" veya "rightToLeft" olmalıdır +@msg `clearStroke` requires `stroke: false`, `ids: []` and no `stop` `clearStroke` için `stroke: false`, `ids: []` gerekir ve `stop` verilmemelidir +@msg `clear` must be a list of type object ids, not {v} `clear` bir metin nesnesi kimlikleri listesi olmalıdır, {v} değil +@msg `clear` must list type objects; {_1} is not one `clear` metin nesnelerini listelemelidir; {_1} bir metin nesnesi değil +@msg `clear` must not list `id` `clear` içinde `id` yer almamalıdır +@msg `color` needs a `rule` to make the theme from `color` için temanın oluşturulacağı bir `rule` gerekir +@msg `colors` is empty `colors` boş +@msg `columnType` is vertical, uniform, repeating or sliding `columnType` vertical, uniform, repeating veya sliding olur +@msg `columns` must be a whole number 1..50 `columns` 1..50 arasında bir tam sayı olmalıdır +@msg `commands` must not be empty `commands` boş olmamalıdır +@msg `contents` goes with `to` `contents`, `to` ile birlikte kullanılır +@msg `corners` must be sharp, round or square, not `{other}` `corners` sharp, round veya square olmalıdır, `{other}` değil +@msg `corners` must list anchor indices (0, 1, 2…), not {v} `corners` bağlantı noktası dizinlerini (0, 1, 2…) listelemelidir, {v} değil +@msg `count` must be a whole number from 1 to 100 `count` 1 ile 100 arasında bir tam sayı olmalıdır +@msg `dataBase64` is larger than the module limit `dataBase64` modül sınırından büyük +@msg `dataBase64` is not valid base64 `dataBase64` geçerli bir base64 değil +@msg `defaultsOnly` cannot be combined with `ids`, `reverse` or `append` `defaultsOnly`; `ids`, `reverse` veya `append` ile birleştirilemez +@msg `depth` and `childLimit` slice the summary: pass `summary: true` `depth` ve `childLimit` özeti dilimler: `summary: true` verin +@msg `design` is a design name, or null for plain columns `design` bir tasarım adıdır veya düz sütunlar için null olur +@msg `design` is a design name, or null for the default marker `design` bir tasarım adıdır veya varsayılan işaretçi için null olur +@msg `destinationFolder` is required when destination is `folder` destination `folder` olduğunda `destinationFolder` gereklidir +@msg `destination` must be `none`, `saveAndClose` or `folder` `destination` `none`, `saveAndClose` veya `folder` olmalıdır +@msg `diameter` must be from 0.1 to 2500 pt `diameter` 0.1 ile 2500 pt arasında olmalıdır +@msg `digits` must be one of {_1} `digits` şunlardan biri olmalıdır: {_1} +@msg `dimImages` is a percentage or false `dimImages` bir yüzde veya false olur +@msg `direction` must be "auto", "leftToRight" or "rightToLeft" `direction` "auto", "leftToRight" veya "rightToLeft" olmalıdır +@msg `each` is the value one design stands for, more than 0 `each`, bir tasarımın temsil ettiği değerdir ve 0'dan büyüktür +@msg `end` must be "start" or "end" `end` "start" veya "end" olmalıdır +@msg `ends` applies to joining exactly two paths `ends` tam olarak iki yolun birleştirilmesi için geçerlidir +@msg `event` must be one of {_1} `event` şunlardan biri olmalıdır: {_1} +@msg `every` must be "all", "odd" or "even", not {v} `every` "all", "odd" veya "even" olmalıdır, {v} değil +@msg `expand` must be true or false `expand` true veya false olmalıdır +@msg `files` must be 1 to 1000 paths of font files the last text.findFontFiles search found `files`, son text.findFontFiles aramasının bulduğu yazı tipi dosyalarının 1 ile 1000 arasında yolu olmalıdır +@msg `folder` must be an absolute folder path `folder` mutlak bir klasör yolu olmalıdır +@msg `fontAxes` must be an object of axis tags and values, such as {"wght"} `fontAxes`, eksen etiketleri ve değerlerinden oluşan bir nesne olmalıdır, örneğin {"wght"} +@msg `format` must be a string `format` bir dize olmalıdır +@msg `format` must be one of {_1} `format` şunlardan biri olmalıdır: {_1} +@msg `fractions` is chop or scale `fractions` chop veya scale olur +@msg `from` and `to` must differ `from` ve `to` farklı olmalıdır +@msg `from` has an empty frame `from` boş bir çerçeveye sahip +@msg `from` must be a non-negative integer `from` negatif olmayan bir tam sayı olmalıdır +@msg `from` must be area type or type on a path `from` alan metni veya yol üzerindeki yazı olmalıdır +@msg `gid` must be a glyph id, not {v} `gid` bir glif kimliği olmalıdır, {v} değil +@msg `glyphAlternate` belongs to one character, not to a character style (text.setGlyphAlternate sets it) `glyphAlternate` bir karakter stiline değil, tek bir karaktere aittir (text.setGlyphAlternate ayarlar) +@msg `guide` must be a guide index (guide.list) `guide` bir kılavuz dizini olmalıdır (guide.list) +@msg `hAlign` must be default, left, center or right `hAlign` default, left, center veya right olmalıdır +@msg `id` must be a node id `id` bir düğüm kimliği olmalıdır +@msg `id` must be an object id, not {v} `id` bir nesne kimliği olmalıdır, {v} değil +@msg `ids` must name Objects on Path groups or objects in them `ids`, Yol Üzerindeki Nesneler gruplarını veya bunların içindeki nesneleri belirtmelidir +@msg `ids` takes at most {MAX_INSPECT_IDS} ids `ids` en fazla {MAX_INSPECT_IDS} kimlik alır +@msg `imageMap` must be none, rectangle or polygon `imageMap` none, rectangle veya polygon olmalıdır +@msg `includeArtboardFill` must be true or false `includeArtboardFill` true veya false olmalıdır +@msg `includeSubdirs` must be true or false `includeSubdirs` true veya false olmalıdır +@msg `index` must be a point index `index` bir nokta dizini olmalıdır +@msg `index` must be a whole number or null `index` bir tam sayı veya null olmalıdır +@msg `indices` must be a non-empty array of item indices `indices`, öğe dizinlerinden oluşan boş olmayan bir dizi olmalıdır +@msg `items` is a list of {kind, item} `items` bir {kind, item} listesidir +@msg `items` is empty `items` boş +@msg `items` must be a list of {id, points} `items` bir {id, points} listesi olmalıdır +@msg `items` must be a list of {{id, anchors?}}, not {v} `items` bir {{id, anchors?}} listesi olmalıdır, {v} değil +@msg `items` must be an array of {id, anchors} `items` bir {id, anchors} dizisi olmalıdır +@msg `items` must be an array of {{id, corners?}}, not {v} `items` bir {{id, corners?}} dizisi olmalıdır, {v} değil +@msg `kashida` must be "none", "short", "medium", "long" or "stylistic" `kashida` "none", "short", "medium", "long" veya "stylistic" olmalıdır +@msg `kind` is one of {_1} `kind` şunlardan biridir: {_1} +@msg `kind` must be "round", "invertedRound" or "chamfer", not {v} `kind` "round", "invertedRound" veya "chamfer" olmalıdır, {v} değil +@msg `kind` must be `text`, `visibility`, `image` or `graph` `kind` `text`, `visibility`, `image` veya `graph` olmalıdır +@msg `kind` must be a string `kind` bir dize olmalıdır +@msg `kind` must be image, noImage or htmlText `kind` image, noImage veya htmlText olmalıdır +@msg `kinsoku` must be "none", "hard" or "soft" `kinsoku` "none", "hard" veya "soft" olmalıdır +@msg `label` must be a non-empty name of at most 200 characters `label` en fazla 200 karakterlik, boş olmayan bir ad olmalıdır +@msg `language` must be a language name or tag, such as "Turkish" or "tr" `language` bir dil adı veya etiketi olmalıdır, örneğin "Turkish" veya "tr" +@msg `leadingModel` must be "romanBaseline" or "emBoxTop" `leadingModel` "romanBaseline" veya "emBoxTop" olmalıdır +@msg `leading` must be from 0.1 to 5000, or null for Auto `leading` 0.1 ile 5000 arasında veya Otomatik için null olmalıdır +@msg `length` must be a number of at most 1000000 pt either way `length` her iki yönde en fazla 1000000 pt olan bir sayı olmalıdır +@msg `line` must be true or false `line` true veya false olmalıdır +@msg `minAngle` ({min_angle}°) can't be more than `maxAngle` ({max_angle}°) `minAngle` ({min_angle}°), `maxAngle` ({max_angle}°) değerinden büyük olamaz +@msg `mode` must be "handles", "straight" or "smooth" `mode` "handles", "straight" veya "smooth" olmalıdır +@msg `mode` must be "straight", "bezier" or "arc" `mode` "straight", "bezier" veya "arc" olmalıdır +@msg `mode` must be one of {_1} `mode` şunlardan biri olmalıdır: {_1} +@msg `mojikumi` must be "none", "yakumonoHankaku", "gyomatsuYakumonoHankaku", "gyomatsuYakumonoZenkaku", "yakumonoZenkaku" or "lineEndHalf" `mojikumi` "none", "yakumonoHankaku", "gyomatsuYakumonoHankaku", "gyomatsuYakumonoZenkaku", "yakumonoZenkaku" veya "lineEndHalf" olmalıdır +@msg `names` is a list of preset names `names` bir ön ayar adları listesidir +@msg `names` lists preset names `names` ön ayar adlarını listeler +@msg `names` must be a list of names `names` bir ad listesi olmalıdır +@msg `names` must be a list of swatch names `names` bir renk örneği adları listesi olmalıdır +@msg `names` must be an array of style names `names` bir stil adları dizisi olmalıdır +@msg `new` is a design name, or true `new` bir tasarım adı veya true olur +@msg `path` must be a folder `path` bir klasör olmalıdır +@msg `path` must be a path object `path` bir yol nesnesi olmalıdır +@msg `pivot` must be a whole number from 0 to 8 `pivot` 0 ile 8 arasında bir tam sayı olmalıdır +@msg `points` must be a list of [x, y] points `points` bir [x, y] noktaları listesi olmalıdır +@msg `points` must be a list of point indexes `points` bir nokta dizinleri listesi olmalıdır +@msg `points` must be an array of point indices `points` bir nokta dizinleri dizisi olmalıdır +@msg `points` must be point indexes `points` nokta dizinleri olmalıdır +@msg `port` must be "in" or "out" `port` "in" veya "out" olmalıdır +@msg `position` is above or below `position` above veya below olur +@msg `preset` must be a string `preset` bir dize olmalıdır +@msg `ratio` must be from 0.1 to 0.5 `ratio` 0.1 ile 0.5 arasında olmalıdır +@msg `rect` must be [x, y, width, height] with a positive size `rect` pozitif boyutlu [x, y, width, height] olmalıdır +@msg `relation` must be overlap, inside or outside `relation` overlap, inside veya outside olmalıdır +@msg `reversed` must be true or false `reversed` true veya false olmalıdır +@msg `rotate` must be a finite number `rotate` sonlu bir sayı olmalıdır +@msg `rule` must be nonZero or evenOdd `rule` nonZero veya evenOdd olmalıdır +@msg `scale` must be a number in (0, 100] `scale` (0, 100] aralığında bir sayı olmalıdır +@msg `scope` must be "selection" or "document", not {other} `scope` "selection" veya "document" olmalıdır, {other} değil +@msg `script` must be a string `script` bir dize olmalıdır +@msg `seriesIndexes` is a non-empty list of series indexes `seriesIndexes`, seri dizinlerinden oluşan boş olmayan bir listedir +@msg `seriesIndexes` needs a `type` or a `valueAxis` `seriesIndexes` için bir `type` veya bir `valueAxis` gerekir +@msg `shift` must be a number of points `shift` punto cinsinden bir sayı olmalıdır +@msg `showCenter` must be true or false `showCenter` true veya false olmalıdır +@msg `singleWordJustification` must be "fullJustify", "alignLeft", "alignCenter" or "alignRight" `singleWordJustification` "fullJustify", "alignLeft", "alignCenter" veya "alignRight" olmalıdır +@msg `size` is a percentage of the base text's size, 1 to 100 `size`, temel metnin boyutunun yüzdesidir ve 1 ile 100 arasındadır +@msg `source` and `target` are the same object `source` ve `target` aynı nesne +@msg `source` must be `folder` or `datasets` `source` `folder` veya `datasets` olmalıdır +@msg `spacing` must be a number `spacing` bir sayı olmalıdır +@msg `spacing` must be a number of points, 0 or more, or "auto" `spacing` punto cinsinden 0 veya daha büyük bir sayı ya da "auto" olmalıdır +@msg `start` must be a finite number `start` sonlu bir sayı olmalıdır +@msg `starts` must be an array of anchor indices (or nulls) `starts`, bağlantı noktası dizinlerinden (veya null değerlerinden) oluşan bir dizi olmalıdır +@msg `status` must be linked, embedded, missing or modified, or a list of them `status` linked, embedded, missing veya modified ya da bunların bir listesi olmalıdır +@msg `stop` must be a stop index `stop` bir durak dizini olmalıdır +@msg `story` styles the whole story: give no `start` or `end` `story` tüm metin akışına stil verir: `start` veya `end` vermeyin +@msg `story` takes the whole story: give no `start` or `end` `story` tüm metin akışını alır: `start` veya `end` vermeyin +@msg `strokeMode` applies to strokes (stroke: true) `strokeMode` konturlar için geçerlidir (stroke: true) +@msg `style` must be roman or japanese `style` roman veya japanese olmalıdır +@msg `subpaths` must be two integer indices `subpaths` iki tam sayı dizini olmalıdır +@msg `symbol` must be a symbol name `symbol` bir sembol adı olmalıdır +@msg `target` must be "object" or "contents", not {v} `target` "object" veya "contents" olmalıdır, {v} değil +@msg `tint` applies to global and spot colours `tint` genel ve spot renkler için geçerlidir +@msg `tint` goes with a global or spot `swatch` `tint`, genel veya spot bir `swatch` ile birlikte kullanılır +@msg `tint` must be a number (%) `tint` bir sayı (%) olmalıdır +@msg `tint` needs a global or spot colour `tint` için genel veya spot bir renk gerekir +@msg `to` is already threaded `to` zaten zincirlenmiş +@msg `to` is the design's new name `to` tasarımın yeni adıdır +@msg `to` must be [x, y] `to` [x, y] olmalıdır +@msg `to` must be a closed path, area type or type on a path other than `from` `to`, `from` dışında kapalı bir yol, alan metni veya yol üzerindeki yazı olmalıdır +@msg `to` must be a whole number `to` bir tam sayı olmalıdır +@msg `to` takes the rows of one object's stack, not aligned rows `to` hizalanmış satırları değil, tek bir nesnenin yığınındaki satırları alır +@msg `useLab` must be true or false `useLab` true veya false olmalıdır +@msg `vAlign` must be default, top, middle, baseline or bottom `vAlign` default, top, middle, baseline veya bottom olmalıdır +@msg `values` must be a list `values` bir liste olmalıdır +@msg `values` must be an object `values` bir nesne olmalıdır +@msg `values` must name hex, rgb, cmyk, lab or gray `values` hex, rgb, cmyk, lab veya gray belirtmelidir +@msg `values` names a kind twice `values` bir türü iki kez belirtiyor +@msg `{_1}` can't be edited or removed `{_1}` düzenlenemez veya kaldırılamaz +@msg `{_1}` is built in and always listed `{_1}` yerleşiktir ve her zaman listelenir +@msg `{_1}` is not a font file the last text.findFontFiles search found `{_1}`, son text.findFontFiles aramasının bulduğu bir yazı tipi dosyası değil +@msg `{_1}` would be overwritten by the package: choose a different folder or name paket `{_1}` üzerine yazardı: farklı bir klasör veya ad seçin +@msg `{file}` has no art to place `{file}` içinde yerleştirilecek resim yok +@msg `{file}` is over {_1} MB `{file}` {_1} MB'tan büyük +@msg `{f}` belongs to a VectorCraft that is running `{f}` çalışmakta olan bir VectorCraft'a ait +@msg `{f}` is the copy of a document open now `{f}` şu anda açık olan bir belgenin kopyası +@msg `{id}` is no writable format (see document.formats) `{id}` yazılabilir bir biçim değil (bkz. document.formats) +@msg `{id}` isn't a loaded library `{id}` yüklenmiş bir kütüphane değil +@msg `{key}` has no colours `{key}` renk içermiyor +@msg `{key}` is a design name `{key}` bir tasarım adıdır +@msg `{key}` is a design name or a list of them `{key}` bir tasarım adı veya tasarım adları listesidir +@msg `{key}` is longer than {MAX_NAME} characters `{key}` {MAX_NAME} karakterden uzun +@msg `{key}` is out of range `{key}` aralık dışında +@msg `{key}` must be [min, desired, max] or {{min?, desired?, max?}}, in percent `{key}` yüzde cinsinden [min, desired, max] veya {{min?, desired?, max?}} olmalıdır +@msg `{key}` must be a non-negative integer `{key}` negatif olmayan bir tam sayı olmalıdır +@msg `{key}` must be a number {_1}..{_2} `{key}` {_1}..{_2} aralığında bir sayı olmalıdır +@msg `{key}` must be a whole number of at least 0, not {n} `{key}` en az 0 olan bir tam sayı olmalıdır, {n} değil +@msg `{key}` must be an appearance item index (paint order) or null `{key}` bir görünüm öğesi dizini (boyama sırası) veya null olmalıdır +@msg `{key}` must be an array of asset ids (see assets.list) `{key}` bir varlık kimlikleri dizisi olmalıdır (bkz. assets.list) +@msg `{key}` must be from 0 to 180 degrees, not {a} `{key}` 0 ile 180 derece arasında olmalıdır, {a} değil +@msg `{key}` must be from {_1} to {shift_max} `{key}` {_1} ile {shift_max} arasında olmalıdır +@msg `{key}`: not a colour: {v} `{key}`: bir renk değil: {v} +@msg `{k}.family` is required `{k}.family` gereklidir +@msg `{k}` is a number 0..1 `{k}` 0..1 aralığında bir sayıdır +@msg `{k}` is true or false `{k}` true veya false olur +@msg `{k}` isn't an export setting: {_1} `{k}` bir dışa aktarma ayarı değil: {_1} +@msg `{k}` must be a byte offset `{k}` bir bayt konumu olmalıdır +@msg `{k}` must be a number `{k}` bir sayı olmalıdır +@msg `{k}` must be a number of points `{k}` punto cinsinden bir sayı olmalıdır +@msg `{k}` must be a string `{k}` bir dize olmalıdır +@msg `{k}` must be a whole number `{k}` bir tam sayı olmalıdır +@msg `{k}` must be from {lo} to {hi} for {key} {key} için `{k}` {lo} ile {hi} arasında olmalıdır +@msg `{k}` must be {what}, not {v} `{k}` {what} olmalıdır, {v} değil +@msg `{l}` isn't a global or spot colour `{l}` genel veya spot bir renk değil +@msg `{m}` isn't a bitmap: use clipboard.importSvg, importPdf or importText `{m}` bir bitmap değil: clipboard.importSvg, importPdf veya importText kullanın +@msg `{name}` can't be deleted `{name}` silinemez +@msg `{name}` can't be duplicated `{name}` çoğaltılamaz +@msg `{name}` can't be edited `{name}` düzenlenemez +@msg `{name}` can't be edited this way `{name}` bu şekilde düzenlenemez +@msg `{name}` can't be renamed `{name}` yeniden adlandırılamaz +@msg `{name}` can't name a folder `{name}` bir klasörü belirtemez +@msg `{name}` has no art to place `{name}` içinde yerleştirilecek resim yok +@msg `{name}` has no text to place `{name}` içinde yerleştirilecek metin yok +@msg `{name}` in the Word document is not UTF-8 or UTF-16 text Word belgesindeki `{name}`, UTF-8 veya UTF-16 metni değil +@msg `{name}` in the Word document is not well-formed XML: {e} Word belgesindeki `{name}` iyi biçimlendirilmiş bir XML değil: {e} +@msg `{name}` in the Word document nests elements more than {MAX_NESTING} deep Word belgesindeki `{name}`, öğeleri {MAX_NESTING} düzeyden daha derin iç içe yerleştiriyor +@msg `{name}` is a built-in preset and is read-only: save it under another name `{name}` yerleşik bir ön ayardır ve salt okunurdur: başka bir adla kaydedin +@msg `{name}` is a built-in preset: save under another name `{name}` yerleşik bir ön ayardır: başka bir adla kaydedin +@msg `{name}` is a built-in profile and stays `{name}` yerleşik bir profildir ve kalır +@msg `{name}` is a tint of `{base}`: edit `{base}` (a tint swatch only takes a new name) `{name}`, `{base}` renginin bir tonudur: `{base}` örneğini düzenleyin (bir ton renk örneği yalnızca yeni bir ad alır) +@msg `{name}` is a working space: choose another with edit.colorSettings first `{name}` bir çalışma alanıdır: önce edit.colorSettings ile başka birini seçin +@msg `{name}` is built in and stays `{name}` yerleşiktir ve kalır +@msg `{name}` takes a paint of its own kind (colour, gradient or pattern) `{name}` kendi türünde bir boya alır (renk, degrade veya desen) +@msg `{n}` can't be deleted `{n}` silinemez +@msg `{n}` can't be merged `{n}` birleştirilemez +@msg `{n}` can't be moved `{n}` taşınamaz +@msg `{n}` is not a colour swatch `{n}` bir renk örneği değil +@msg `{n}` isn't a solid colour `{n}` düz bir renk değil +@msg `{n}`: colour groups hold solid colours only `{n}`: renk grupları yalnızca düz renkler içerir +@msg `{other}` doesn't trace an image `{other}` bir görüntüyü izlemez +@msg `{s}`: the step's references copy in more than {_1} MB of values `{s}`: adımın başvuruları {_1} MB'tan fazla değer kopyalıyor +@msg `{tag}` is not an axis tag: a tag is four characters, such as "wght" `{tag}` bir eksen etiketi değil: bir etiket dört karakterdir, örneğin "wght" +@msg `{to}` is empty or already used `{to}` boş veya zaten kullanılıyor +@msg `{what}` is longer than {MAX_TEXT} bytes `{what}` {MAX_TEXT} bayttan uzun +@msg `{what}` must be text `{what}` metin olmalıdır +@msg a DXF drawing has one origin: pass useArtboards: true for one drawing per artboard bir DXF çiziminin tek bir başlangıç noktası vardır: çalışma yüzeyi başına bir çizim için useArtboards: true verin +@msg a PDF presets file with over {_1} presets {_1} taneden fazla ön ayar içeren bir PDF ön ayarları dosyası +@msg a batch preview cannot switch documents bir toplu önizleme belge değiştiremez +@msg a brush named `{nn}` exists `{nn}` adlı bir fırça var +@msg a container of the listed objects is gone listelenen nesnelerin bir kapsayıcısı artık yok +@msg a content stream can't be read bir içerik akışı okunamıyor +@msg a content stream isn't a stream bir içerik akışı bir akış değil +@msg a design holds at most {_1} objects bir tasarım en fazla {_1} nesne içerir +@msg a design needs a name bir tasarımın adı olmalıdır +@msg a dictionary grew too large bir sözlük çok büyüdü +@msg a document keeps at most {_1} graph designs bir belge en fazla {_1} grafik tasarımı tutar +@msg a document keeps at most {_1} saved selections bir belge en fazla {_1} kayıtlı seçim tutar +@msg a document keeps at most {_1} views bir belge en fazla {_1} görünüm tutar +@msg a document links at most {MAX_SVG_SCRIPTS} JavaScript files bir belge en fazla {MAX_SVG_SCRIPTS} JavaScript dosyasına bağlanır +@msg a feConvolveMatrix filter's order is {x}×{y}, which overflows the kernel-size multiply usvg makes bir feConvolveMatrix filtresinin order değeri {x}×{y}; bu, usvg'nin yaptığı çekirdek boyutu çarpımını taşırıyor +@msg a gradient preset is already called {n} {n} adlı bir degrade ön ayarı zaten var +@msg a graph has at most {_1} series, so it transposes with at most that many categories bir grafikte en fazla {_1} seri bulunur, bu yüzden en fazla o kadar kategoriyle yer değiştirir +@msg a layer can't be merged into its own sublayer bir katman kendi alt katmanıyla birleştirilemez +@msg a layer's form box isn't an array bir katmanın form kutusu bir dizi değil +@msg a layer's form can't be read bir katmanın formu okunamıyor +@msg a layer's form has no box bir katmanın formunda kutu yok +@msg a layer's form has no dictionary bir katmanın formunda sözlük yok +@msg a legend draws at most {MAX_CHIPS} swatches bir gösterge en fazla {MAX_CHIPS} renk örneği çizer +@msg a name names one asset: give multiple: false, or one object bir ad tek bir varlığı belirtir: multiple: false veya tek bir nesne verin +@msg a page can't be read bir sayfa okunamıyor +@msg a page object is used by something else bir sayfa nesnesi başka bir şey tarafından kullanılıyor +@msg a page thumbnail must be RGB pixels, 1 to {THUMBNAIL_SIZE} a side (got {w} × {h}) bir sayfa küçük resmi, kenar başına 1 ile {THUMBNAIL_SIZE} arasında RGB pikseller olmalıdır (verilen: {w} × {h}) +@msg a pattern layer doesn't end what it starts bir desen katmanı başlattığını bitirmiyor +@msg a pattern layer's colors hold something else bir desen katmanının renkleri başka bir şey içeriyor +@msg a pattern named `{n}` exists `{n}` adlı bir desen var +@msg a plug-in with id {_1} is already installed {_1} kimlikli bir eklenti zaten kurulu +@msg a preset named `{n}` exists `{n}` adlı bir ön ayar var +@msg a print presets file with over {_1} presets {_1} taneden fazla ön ayar içeren bir yazdırma ön ayarları dosyası +@msg a profile is already called {n} {n} adlı bir profil zaten var +@msg a row can't go into itself bir satır kendi içine giremez +@msg a series goes on the left or the right value axis bir seri sol veya sağ değer eksenine yerleşir +@msg a start must be an anchor index ≥ 0 or null bir başlangıç, ≥ 0 olan bir bağlantı noktası dizini veya null olmalıdır +@msg a style named `{name}` already exists `{name}` adlı bir stil zaten var +@msg a style named `{to}` already exists `{to}` adlı bir stil zaten var +@msg a swatch needs a colour, gradient or pattern bir renk örneği için renk, degrade veya desen gerekir +@msg a symbol named `{n}` already exists `{n}` adlı bir sembol zaten var +@msg a theme has 1 to {THEME_SIZE} colours bir temada 1 ile {THEME_SIZE} arasında renk bulunur +@msg a theme is already called {name} (replace: "{name}" overwrites it) {name} adlı bir tema zaten var (replace: "{name}" üzerine yazar) +@msg a toolbar name has at most {MAX_NAME} characters bir araç çubuğu adı en fazla {MAX_NAME} karakter içerir +@msg a view named `{_1}` exists `{_1}` adlı bir görünüm var +@msg a view named `{name}` exists `{name}` adlı bir görünüm var +@msg a workspace keeps at most {MAX} toolbars bir çalışma alanı en fazla {MAX} araç çubuğu tutar +@msg a {_1} series can't go in a {_2} graph {_1} türünde bir seri {_2} türünde bir grafiğe konulamaz +@msg aiVersion {v}: "pdf" (PDF-compatible, the default) or "7" (legacy .ai, version 7) aiVersion {v}: "pdf" (PDF uyumlu, varsayılan) veya "7" (eski .ai, sürüm 7) +@msg already editing an opacity mask zaten bir opaklık maskesi düzenleniyor +@msg already editing another object's opacity mask zaten başka bir nesnenin opaklık maskesi düzenleniyor +@msg already in pattern editing mode zaten desen düzenleme modunda +@msg an artboard is listed twice bir çalışma yüzeyi iki kez listelenmiş +@msg an empty artboard has no width or height to scale to boş bir çalışma yüzeyinin ölçeklenecek genişliği veya yüksekliği yoktur +@msg an image is too large for DXF and was left out bir görüntü DXF için çok büyük olduğundan dışarıda bırakıldı +@msg an image of {_1} MB, at most {_2} MB {_1} MB'lık bir görüntü, en fazla {_2} MB +@msg an image of {declared_w} × {declared_h} pixels is too large to draw {declared_w} × {declared_h} piksellik bir görüntü çizilemeyecek kadar büyük +@msg an image of {width} × {height} pixels is too large to draw {width} × {height} piksellik bir görüntü çizilemeyecek kadar büyük +@msg an index must be a whole number bir dizin tam sayı olmalıdır +@msg an inline graphic has no glyphs satır içi bir grafikte glif yok +@msg an invisible text form can't be read görünmez bir metin formu okunamıyor +@msg an object is missing bir nesne eksik +@msg an object's header is missing bir nesnenin üst bilgisi eksik +@msg an overprinting form can't be read üst baskılı bir form okunamıyor +@msg an unread object has no readable bounds okunmamış bir nesnenin okunabilir sınırları yok +@msg an unread object holds a frame of threaded type okunmamış bir nesne zincirli metnin bir çerçevesini içeriyor +@msg an unread object is missing from its layer okunmamış bir nesne katmanında eksik +@msg anchor `smooth` must be true or false bağlantı noktasının `smooth` değeri true veya false olmalıdır +@msg anchor `{key}` must be [x, y] bağlantı noktasının `{key}` değeri [x, y] olmalıdır +@msg anchor `{key}` must be a number bağlantı noktasının `{key}` değeri bir sayı olmalıdır +@msg angle and roundness must be finite açı ve yuvarlaklık sonlu olmalıdır +@msg angles must be a list as long as pins (degrees or null) angles, pins ile aynı uzunlukta bir liste olmalıdır (derece veya null) +@msg appearance must be flat|center|edge appearance flat|center|edge olmalıdır +@msg apply is "fill" or "stroke", not `{other}` apply "fill" veya "stroke" olur, `{other}` değil +@msg area must be a closed polygon of 3 to 100000 [x, y] points area, 3 ile 100000 arasında [x, y] noktasından oluşan kapalı bir çokgen olmalıdır +@msg area type needs a path that encloses an area alan metni için bir alanı çevreleyen bir yol gerekir +@msg area type {_1} is named twice alan metni {_1} iki kez belirtilmiş +@msg arrowAlign must be extend|tip, got {o} arrowAlign extend|tip olmalıdır, verilen: {o} +@msg arrowScale must be [start, end] arrowScale [start, end] olmalıdır +@msg artboard is a 0-based index artboard 0 tabanlı bir dizindir +@msg artboard must be a 0-based index artboard 0 tabanlı bir dizin olmalıdır +@msg artboard {i} doesn't print {i} numaralı çalışma yüzeyi yazdırılmıyor +@msg artboardLayout must be {layout?, columns?, spacing?, rightToLeft?} artboardLayout {layout?, columns?, spacing?, rightToLeft?} olmalıdır +@msg artboardLayout.columns must be 1 or more artboardLayout.columns 1 veya daha büyük olmalıdır +@msg artboardLayout.layout must be gridByRow, gridByColumn, row or column artboardLayout.layout gridByRow, gridByColumn, row veya column olmalıdır +@msg artboardLayout.rightToLeft must be true or false artboardLayout.rightToLeft true veya false olmalıdır +@msg artboardLayout.spacing must be 0–{MAX_SPACING} pt artboardLayout.spacing 0–{MAX_SPACING} pt olmalıdır +@msg artboards must be a non-empty list artboards boş olmayan bir liste olmalıdır +@msg artboards must be a number artboards bir sayı olmalıdır +@msg asset `{_1}` has no art to export `{_1}` varlığında dışa aktarılacak resim yok +@msg at most {MAX_KEYWORDS} keywords en fazla {MAX_KEYWORDS} anahtar sözcük +@msg at most {MAX_MATCHES} matches are kept en fazla {MAX_MATCHES} eşleşme tutulur +@msg at most {MAX_POINTS} points en fazla {MAX_POINTS} nokta +@msg at most {MAX_QUEUE} files en fazla {MAX_QUEUE} dosya +@msg at must be [x, y] at [x, y] olmalıdır +@msg at/rect lie outside the canvas at/rect tuvalin dışında kalıyor +@msg attribute must be size|leading|tracking|kerning|baselineShift attribute size|leading|tracking|kerning|baselineShift olmalıdır +@msg attrs must be an object attrs bir nesne olmalıdır +@msg automation path rejected: the folder's name isn't valid text otomasyon yolu reddedildi: klasörün adı geçerli bir metin değil +@msg automation path rejected: {_1} isn't valid text otomasyon yolu reddedildi: {_1} geçerli bir metin değil +@msg automation path rejected: {why}: {path} otomasyon yolu reddedildi: {why}: {path} +@msg axis must be "vertical", "horizontal" or an angle in degrees, not `{given}` axis "vertical", "horizontal" veya derece cinsinden bir açı olmalıdır, `{given}` değil +@msg backgroundContents must be transparent or white backgroundContents transparent veya white olmalıdır +@msg bad AES key hatalı AES anahtarı +@msg bad `runs`: {e} hatalı `runs`: {e} +@msg bad arrowScale hatalı arrowScale +@msg bad base64 hatalı base64 +@msg bad color {c} hatalı renk {c} +@msg bad colour hatalı renk +@msg bad colour in `colors` `colors` içinde hatalı renk +@msg bad colour {v} hatalı renk {v} +@msg bad colour {v} in groupColors groupColors içinde hatalı renk {v} +@msg bad cross-reference entry hatalı çapraz başvuru girdisi +@msg bad cross-reference table hatalı çapraz başvuru tablosu +@msg bad current colour {v} hatalı geçerli renk {v} +@msg bad dataBase64 hatalı dataBase64 +@msg bad edit hatalı düzenleme +@msg bad fill {v} hatalı dolgu {v} +@msg bad fit: {e} hatalı fit: {e} +@msg bad model {other} (keep, new or document) hatalı model {other} (keep, new veya document) +@msg bad new colour {v} hatalı yeni renk {v} +@msg bad object hatalı nesne +@msg bad object number hatalı nesne numarası +@msg bad offset hatalı konum +@msg bad path data: {e} hatalı yol verisi: {e} +@msg bad point {v}: expected [x, y] or [x, y, pressure] hatalı nokta {v}: [x, y] veya [x, y, pressure] bekleniyordu +@msg bad reference hatalı başvuru +@msg bad trailer size hatalı trailer boyutu +@msg bad {k} colour hatalı {k} rengi +@msg batches cannot nest toplu işlemler iç içe olamaz +@msg bind something to a variable first önce bir şeyi bir değişkene bağlayın +@msg bleed must be 0–{MAX_BLEED} pt: a number, [top, bottom, left, right] or {{top, bottom, left, right}} bleed 0–{MAX_BLEED} pt olmalıdır: bir sayı, [top, bottom, left, right] veya {{top, bottom, left, right}} +@msg brush must be a name or null brush bir ad veya null olmalıdır +@msg by must be a number by bir sayı olmalıdır +@msg can't add page thumbnails: {why} sayfa küçük resimleri eklenemiyor: {why} +@msg can't add the editing data for other apps: {why} diğer uygulamalar için düzenleme verileri eklenemiyor: {why} +@msg can't edit the written PDF: {why} yazılan PDF düzenlenemiyor: {why} +@msg can't encrypt the PDF: {why} PDF şifrelenemiyor: {why} +@msg can't linearise the PDF: {why} PDF doğrusallaştırılamıyor: {why} +@msg can't open `{_1}`: {_2} `{_1}` açılamıyor: {_2} +@msg can't open `{_1}`: {e} `{_1}` açılamıyor: {e} +@msg can't open `{name}`: not a format VectorCraft reads (see document.formats) `{name}` açılamıyor: VectorCraft'ın okuduğu bir biçim değil (bkz. document.formats) +@msg can't place `{name}`: not a format VectorCraft reads (see document.formats) `{name}` yerleştirilemiyor: VectorCraft'ın okuduğu bir biçim değil (bkz. document.formats) +@msg can't read back the written PDF: {e} yazılan PDF geri okunamıyor: {e} +@msg can't read this Word document: {why} bu Word belgesi okunamıyor: {why} +@msg can't write .{e} images: use .png, .jpg, .gif, .webp, .tif or .bmp .{e} görüntüleri yazılamıyor: .png, .jpg, .gif, .webp, .tif veya .bmp kullanın +@msg can't write PDF layers, overprint or invisible text: {why} PDF katmanları, üst baskı veya görünmez metin yazılamıyor: {why} +@msg can't write the file's copyright: {why} dosyanın telif hakkı yazılamıyor: {why} +@msg can't write the file's modification date: {why} dosyanın değiştirilme tarihi yazılamıyor: {why} +@msg can't write the pages' user units: {why} sayfaların kullanıcı birimleri yazılamıyor: {why} +@msg cannot distort a zero-size or non-finite bounding box sıfır boyutlu veya sonlu olmayan bir sınırlayıcı kutu çarpıtılamaz +@msg cannot move an object into itself bir nesne kendi içine taşınamaz +@msg case must be upper|lower|title|sentence case upper|lower|title|sentence olmalıdır +@msg category `{c}`: one of {_1} kategori `{c}`: şunlardan biri: {_1} +@msg center must be [x, y] center [x, y] olmalıdır +@msg choose at least one artboard en az bir çalışma yüzeyi seçin +@msg choose at least one status en az bir durum seçin +@msg clip must be true or false clip true veya false olmalıdır +@msg clippingMask must be true or false clippingMask true veya false olmalıdır +@msg closed must be a boolean closed bir mantıksal değer olmalıdır +@msg collapsed must be true or false collapsed true veya false olmalıdır +@msg color.profile: no RGB or CMYK profile is called “{profile}” color.profile: “{profile}” adlı bir RGB veya CMYK profili yok +@msg colorMode must be rgb or cmyk, not `{m}` colorMode rgb veya cmyk olmalıdır, `{m}` değil +@msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel {own} (belgenin modu), grayscale veya bitmap olmalıdır +@msg colour groups can't go into colour groups renk grupları renk gruplarının içine konulamaz +@msg colour, mode and spot apply to solid-colour swatches only colour, mode ve spot yalnızca düz renkli renk örnekleri için geçerlidir +@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read sütun {column}: `{cell}`, grafik veri dosyalarının bir `%` sütunudur ve bu dosyalar okunmaz +@msg column {column}: `{cell}` names `{name}`, which is a {_1} variable sütun {column}: `{cell}`, {_1} türünde bir değişken olan `{name}` değişkenini belirtiyor +@msg column {column}: `{cell}` names no variable sütun {column}: `{cell}` hiçbir değişkeni belirtmiyor +@msg column {column}: the variable name is longer than {MAX_NAME} characters sütun {column}: değişken adı {MAX_NAME} karakterden uzun +@msg column: true floats the whole column and takes no onto, above or below column: true tüm sütunu yüzdürür ve onto, above veya below almaz +@msg command must be a shape.* command command bir shape.* komutu olmalıdır +@msg commands[{i}]: missing `command` commands[{i}]: `command` eksik +@msg composer must be "singleLine" or "everyLine" composer "singleLine" veya "everyLine" olmalıdır +@msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes bileşik şekiller yolları, bileşik yolları, grupları, bileşik şekilleri, metni, karışımları ve zarfları alır +@msg compound {_1} must contain exactly one open path to join bileşik {_1}, birleştirilecek tam olarak bir açık yol içermelidir +@msg connect needs a path other than the one extended connect için uzatılan yoldan başka bir yol gerekir +@msg connect needs id connect için id gerekir +@msg connect path has no open end connect yolunun açık ucu yok +@msg copy needs path: the file to copy into the document's folder copy için path gerekir: belgenin klasörüne kopyalanacak dosya +@msg copy takes images only: relink placed documents where their files are copy yalnızca görüntüleri alır: yerleştirilmiş belgeleri dosyalarının bulunduğu yerde yeniden bağlayın +@msg copying a file isn't available on the web dosya kopyalama web'de kullanılamaz +@msg copyrightStatus must be unknown, copyrighted or publicDomain copyrightStatus unknown, copyrighted veya publicDomain olmalıdır +@msg copyrightUrl must be a URL (no spaces, at most 2048 characters) copyrightUrl bir URL olmalıdır (boşluksuz, en fazla 2048 karakter) +@msg corners must be 4 [x, y] points (TL, TR, BR, BL) corners 4 adet [x, y] noktası olmalıdır (TL, TR, BR, BL) +@msg counterPer `{c}`: item or file counterPer `{c}`: item veya file +@msg crop `{_1}`: only PDF pages have art, trim, bleed and media boxes; use "crop" or "bounding" crop `{_1}`: yalnızca PDF sayfalarında art, trim, bleed ve media kutuları bulunur; "crop" veya "bounding" kullanın +@msg crop rectangle doesn't overlap the image kırpma dikdörtgeni görüntüyle örtüşmüyor +@msg cross-reference and object streams aren't supported çapraz başvuru ve nesne akışları desteklenmiyor +@msg damaged compressed data: {e} hasarlı sıkıştırılmış veri: {e} +@msg dash lengths must be numbers, got {v} kesik çizgi uzunlukları sayı olmalıdır, verilen: {v} +@msg dash must be a list of lengths or null, got {v} dash bir uzunluk listesi veya null olmalıdır, verilen: {v} +@msg data key `{k}`: letters, digits, -, _ and . (not name or vc-…) veri anahtarı `{k}`: harfler, rakamlar, -, _ ve . (name veya vc-… olamaz) +@msg data must be an object of key: value, not {v} data bir key: value nesnesi olmalıdır, {v} değil +@msg data set `{name}` holds a value for `{var}`, which the library doesn't declare `{name}` veri kümesi, kütüphanenin bildirmediği `{var}` için bir değer içeriyor +@msg data set `{name}` holds two values for `{var}` `{name}` veri kümesi `{var}` için iki değer içeriyor +@msg data set `{name}` is declared twice `{name}` veri kümesi iki kez bildirilmiş +@msg data takes at most {MAX_DATA} keys at once data bir seferde en fazla {MAX_DATA} anahtar alır +@msg dataset `{name}` already exists `{name}` veri kümesi zaten var +@msg dataset `{to}` already exists `{to}` veri kümesi zaten var +@msg date `{d}`: YYYY-MM-DD tarih `{d}`: YYYY-MM-DD +@msg decoded data is too large kodu çözülen veri çok büyük +@msg define a variable first önce bir değişken tanımlayın +@msg detect must be true or false detect true veya false olmalıdır +@msg direct-select anchor points of a path bir yolun bağlantı noktalarını doğrudan seçin +@msg distance must be > 0 distance > 0 olmalıdır +@msg dx and dy give the arrow's direction dx ve dy okun yönünü verir +@msg dx and dy must be numbers dx ve dy sayı olmalıdır +@msg dxf fitTo must be [width, height], positive dxf fitTo pozitif [width, height] olmalıdır +@msg dxf must be an object of DXF import options dxf, DXF içe aktarma seçeneklerinden oluşan bir nesne olmalıdır +@msg dxf scale must be a positive number up to {_1}, not {s} dxf scale en fazla {_1} olan pozitif bir sayı olmalıdır, {s} değil +@msg dxf unit `{u}`: a unit such as mm, cm, in or pt dxf unit `{u}`: mm, cm, in veya pt gibi bir birim +@msg dxf: {e} dxf: {e} +@msg each format is an object {format, scale?, suffix?} her biçim bir {format, scale?, suffix?} nesnesidir +@msg each item needs an id her öğe için bir id gerekir +@msg each match needs `kind` her eşleşme için `kind` gerekir +@msg each match needs a `name` her eşleşme için bir `name` gerekir +@msg each of `fonts` is {family, style?}; 1 to 1000 of them `fonts` öğelerinin her biri {family, style?} biçimindedir; 1 ile 1000 arasında öğe +@msg each of `items` is {kind, item} `items` öğelerinin her biri {kind, item} biçimindedir +@msg each of `items` is {{id, corners?}} with an object id, not {it} `items` öğelerinin her biri nesne kimliği içeren {{id, corners?}} biçimindedir, {it} değil +@msg each row needs `from` her satır için `from` gerekir +@msg each stop needs a position her durak için bir konum gerekir +@msg each subpath needs an anchors array her alt yol için bir anchors dizisi gerekir +@msg easingType must be easeIn, easeOut, easeInOut or easeOutIn easingType easeIn, easeOut, easeInOut veya easeOutIn olmalıdır +@msg editingData must be true or false editingData true veya false olmalıdır +@msg editingData must be true, false or "always" editingData true, false veya "always" olmalıdır +@msg edits overlap düzenlemeler çakışıyor +@msg effects of objects whose appearances differ can't be moved together görünümleri farklı olan nesnelerin efektleri birlikte taşınamaz +@msg empty header in column {_1} {_1} sütununda boş başlık +@msg encoding `{_1}`: utf8 or utf16 encoding `{_1}`: utf8 veya utf16 +@msg ends must be two of "first" and "last" ends, "first" ve "last" değerlerinden iki tane olmalıdır +@msg every numbered name for the result is taken sonuç için numaralı adların tümü kullanılıyor +@msg expanded SVG styles exceed the import size limit genişletilmiş SVG stilleri içe aktarma boyut sınırını aşıyor +@msg export presets file is larger than {MAX_PRESET_FILE_BYTES} bytes dışa aktarma ön ayarları dosyası {MAX_PRESET_FILE_BYTES} bayttan büyük +@msg exportText must be editable or appearance exportText editable veya appearance olmalıdır +@msg exportType must be movieClip or graphic, not `{s}` exportType movieClip veya graphic olmalıdır, `{s}` değil +@msg extend needs id extend için id gerekir +@msg featureChanges lists at most {MAX_FEATURE_CHANGES} tags featureChanges en fazla {MAX_FEATURE_CHANGES} etiket listeler +@msg featureChanges must be a list of tags featureChanges bir etiket listesi olmalıdır +@msg features must be a list of tags features bir etiket listesi olmalıdır +@msg fidelity must be 0..100 fidelity 0..100 olmalıdır +@msg files must be {name, dataBase64} files {name, dataBase64} olmalıdır +@msg fit must be none|autoHeight|shrinkText|block, got {id} fit none|autoHeight|shrinkText|block olmalıdır, verilen: {id} +@msg flattener: {e} düzleştirici: {e} +@msg flattenerPreset `{name}`: high, medium, low or a saved one (see flattener.presets.list) flattenerPreset `{name}`: high, medium, low veya kayıtlı bir ön ayar (bkz. flattener.presets.list) +@msg flipProfile must be along|across, got {o} flipProfile along|across olmalıdır, verilen: {o} +@msg folders `{f}`: none, rows, format, item or itemFormat folders `{f}`: none, rows, format, item veya itemFormat +@msg folders deeper than {MAX_BATCH_DEPTH} levels {MAX_BATCH_DEPTH} düzeyden daha derin klasörler +@msg folders deeper than {MAX_DEPTH} levels {MAX_DEPTH} düzeyden daha derin klasörler +@msg font family `{family}` is not available `{family}` yazı tipi ailesi kullanılamıyor +@msg font family `{tf}` is not available `{tf}` yazı tipi ailesi kullanılamıyor +@msg format `{f}`: pdf or postscript format `{f}`: pdf veya postscript +@msg format `{f}`: text or json format `{f}`: text veya json +@msg format is `{format}` format `{format}` +@msg formats must be an array of rows, not {v} formats bir satır dizisi olmalıdır, {v} değil +@msg frequency must be between 1 and 300 lines per inch frequency inç başına 1 ile 300 çizgi arasında olmalıdır +@msg from and to must be finite from ve to sonlu olmalıdır +@msg from must be [x0, y0, x1, y1] from [x0, y0, x1, y1] olmalıdır +@msg give `before` or `after`, not both `before` veya `after` verin, ikisini birden değil +@msg give `colors`, or `color` and `rule` `colors` verin ya da `color` ve `rule` verin +@msg give `event`, such as onclick onclick gibi bir `event` verin +@msg give `file`, the JavaScript file's path or URL JavaScript dosyasının yolu veya URL'si olan `file` değerini verin +@msg give `fill` and/or `stroke` `fill` ve/veya `stroke` verin +@msg give `fill`, `stroke` or both `fill`, `stroke` veya her ikisini verin +@msg give `folder` `folder` verin +@msg give `fonts`, or open a document `fonts` verin veya bir belge açın +@msg give `from` or `indices`, not both `from` veya `indices` verin, ikisini birden değil +@msg give `id` (no text is being edited) `id` verin (düzenlenen bir metin yok) +@msg give `id` and `anchors`, or `items`, not both `id` ve `anchors` ya da `items` verin, ikisini birden değil +@msg give `id` or `guide`, not both `id` veya `guide` verin, ikisini birden değil +@msg give `length` or `to` `length` veya `to` verin +@msg give `matches`: [{kind, name, target}] `matches` verin: [{kind, name, target}] +@msg give `name` (or edit a pattern) `name` verin (veya bir deseni düzenleyin) +@msg give `name` or `names` `name` veya `names` verin +@msg give `path` (a .wasm file) or `dataBase64` (the module) `path` (bir .wasm dosyası) veya `dataBase64` (modül) verin +@msg give `path`, `data` or `dataBase64` `path`, `data` veya `dataBase64` verin +@msg give `path`, `data`, `dataBase64` or `csv` `path`, `data`, `dataBase64` veya `csv` verin +@msg give `path`, `xml` or `dataBase64` `path`, `xml` veya `dataBase64` verin +@msg give `script`, the JavaScript the event runs ("" removes the event) olayın çalıştırdığı JavaScript olan `script` değerini verin ("" olayı kaldırır) +@msg give `text` (the reading) or `remove` `text` (okunuş) veya `remove` verin +@msg give `x` and `y` (and a `tolerance` of 0 or more) `x` ve `y` verin (ve 0 veya daha büyük bir `tolerance`) +@msg give a mode or r/g/b, c/m/y/k, gray or tint adjustments bir mod ya da r/g/b, c/m/y/k, gray veya tint ayarlamaları verin +@msg give a name, or paint the active proxy with a saved preset bir ad verin veya etkin vekili kayıtlı bir ön ayarla boyayın +@msg give a name, or select a stroke with a saved profile bir ad verin veya kayıtlı profili olan bir kontur seçin +@msg give a pattern name or select an object painted with a pattern bir desen adı verin veya desenle boyanmış bir nesne seçin +@msg give at least one of clip, invert, disabled, linked şunlardan en az birini verin: clip, invert, disabled, linked +@msg give color, none, swatch or gradient color, none, swatch veya gradient verin +@msg give dataBase64 dataBase64 verin +@msg give either at (a click) or area (a path drawn around the overlaps) at (bir tıklama) veya area (çakışmaların çevresine çizilen bir yol) verin +@msg give formats or a preset, not both formats veya bir ön ayar verin, ikisini birden değil +@msg give newName or delete newName veya delete verin +@msg give offset or by offset veya by verin +@msg give one of `to`, `rect` or `at` `to`, `rect` veya `at` değerlerinden birini verin +@msg give one of assets, layers, selection or fullDocument assets, layers, selection veya fullDocument değerlerinden birini verin +@msg give only one of onto, above, below, icon and a column place onto, above, below, icon ve bir sütun yerinden yalnızca birini verin +@msg give origin: [x, y], or reset: true origin: [x, y] veya reset: true verin +@msg give overprintFill, overprintStroke, showCenter, imageMap, url or note overprintFill, overprintStroke, showCenter, imageMap, url veya note verin +@msg give path (a file) or folder path (bir dosya) veya folder verin +@msg give path, or name and dataBase64 path ya da name ve dataBase64 verin +@msg give paths or files paths veya files verin +@msg give rows, rowHeight, columns or columnWidth rows, rowHeight, columns veya columnWidth verin +@msg give svg, or dataBase64 of an SVG or SVGZ file svg ya da bir SVG veya SVGZ dosyasının dataBase64 değerini verin +@msg give text text verin +@msg give the asset a name varlığa bir ad verin +@msg give the preset a `name` ön ayara bir `name` verin +@msg give the preset a name ön ayara bir ad verin +@msg give the preset a name (1–64 characters) ön ayara bir ad verin (1–64 karakter) +@msg give the settings to change, e.g. {"formats"}]} değiştirilecek ayarları verin, örneğin {"formats"}]} +@msg give the style a name stile bir ad verin +@msg give two or more style `names` iki veya daha fazla stil için `names` verin +@msg give two or more swatches iki veya daha fazla renk örneği verin +@msg give x, y, or a handle's length or angle x, y ya da bir tutamacın uzunluğunu veya açısını verin +@msg give {key, value} or {values} {key, value} veya {values} verin +@msg global must be true or false global true veya false olmalıdır +@msg glyph {_1} is not drawn for {ch} with the character's style (such as All Caps, Small Caps or a numeral system) {_1} glifi, karakterin stiliyle (Tümü Büyük Harf, Küçük Büyük Harf veya bir rakam sistemi gibi) {ch} için çizilmiyor +@msg glyph {g} is not an alternate of {ch} in {_1} {_2} {g} glifi, {_1} {_2} içinde {ch} karakterinin bir alternatifi değil +@msg gradient must be "objects" or "mesh" gradient "objects" veya "mesh" olmalıdır +@msg grays must be "profile" or "black", not `{g}` grays "profile" veya "black" olmalıdır, `{g}` değil +@msg gridColors must be a preset name or two colours gridColors bir ön ayar adı veya iki renk olmalıdır +@msg gridSize must be small, medium or large gridSize small, medium veya large olmalıdır +@msg guide {g} is not selected {g} numaralı kılavuz seçili değil +@msg handle must be 0..3 handle 0..3 olmalıdır +@msg hiddenObjects {v}: "layer" (the default), "omit" or "visible" hiddenObjects {v}: "layer" (varsayılan), "omit" veya "visible" +@msg highlight a layer to merge into içine birleştirilecek bir katmanı vurgulayın +@msg highlight two or more rows in one layer or group tek bir katman veya gruptaki iki veya daha fazla satırı vurgulayın +@msg highlight two or more rows to merge birleştirmek için iki veya daha fazla satırı vurgulayın +@msg icon docks a panel in the icon column: use window.panel.dock icon bir paneli simge sütununa yerleştirir: window.panel.dock kullanın +@msg id must be a dimension id id bir boyut kimliği olmalıdır +@msg image has no bounds görüntünün sınırları yok +@msg image {_1} is linked already {_1} görüntüsü zaten bağlantılı +@msg imageMap `{m}`: none, client or server imageMap `{m}`: none, client veya server +@msg index out of range dizin aralık dışında +@msg instances must be 1..1000 instances 1..1000 olmalıdır +@msg invalid `color` geçersiz `color` +@msg invalid anchor index {v}: expected a non-negative integer geçersiz bağlantı noktası dizini {v}: negatif olmayan bir tam sayı bekleniyordu +@msg invalid anchor reference {v}: expected [subpath, anchor] geçersiz bağlantı noktası başvurusu {v}: [subpath, anchor] bekleniyordu +@msg invalid angle geçersiz açı +@msg invalid brush: {e} geçersiz fırça: {e} +@msg invalid color geçersiz renk +@msg invalid colour {c} geçersiz renk {c} +@msg invalid delta geçersiz delta +@msg invalid point geçersiz nokta +@msg invalid size geçersiz boyut +@msg invalid t geçersiz t +@msg invalid tolerance geçersiz tolerans +@msg its artboards all lie beyond the canvas (more than {_1} pt from the origin) çalışma yüzeylerinin tümü tuvalin dışında kalıyor (başlangıç noktasından {_1} pt'den uzak) +@msg its clipping masks are nested too deeply kırpma maskeleri çok derin iç içe geçmiş +@msg its metadata has no description meta verilerinde açıklama yok +@msg its metadata has no direct length meta verilerinde doğrudan bir uzunluk yok +@msg join two different paths iki farklı yolu birleştirin +@msg justify must be auto|left|center|right|justifyAll justify auto|left|center|right|justifyAll olmalıdır +@msg kbps must be a positive number, not {kbps} kbps pozitif bir sayı olmalıdır, {kbps} değil +@msg keywords must be a list of words or a comma-separated string keywords bir sözcük listesi veya virgülle ayrılmış bir dize olmalıdır +@msg keywords must be at most {MAX_KEYWORD} characters, without control characters anahtar sözcükler en fazla {MAX_KEYWORD} karakter olmalı ve denetim karakteri içermemelidir +@msg kind must be 1, 2 or 3, or give a preset `name` (see perspective.presets.list) kind 1, 2 veya 3 olmalıdır ya da bir ön ayar için `name` verin (bkz. perspective.presets.list) +@msg kind must be graphic, fillColor, strokeColor, fillGradient, strokeGradient, fillPattern, strokePattern, charStyle or paraStyle kind graphic, fillColor, strokeColor, fillGradient, strokeGradient, fillPattern, strokePattern, charStyle veya paraStyle olmalıdır +@msg knockout must be "on", "off", "neutral" or a bool, not {v} knockout "on", "off", "neutral" veya bir mantıksal değer olmalıdır, {v} değil +@msg layer `{name}` has no art to export `{name}` katmanında dışa aktarılacak resim yok +@msg layer must name a layer or sublayer layer bir katmanı veya alt katmanı belirtmelidir +@msg layers can't be intertwined: select the objects in them katmanlar iç içe geçirilemez: içlerindeki nesneleri seçin +@msg layers go only at the top level or in layers, objects in layers and groups katmanlar yalnızca en üst düzeye veya katmanların içine, nesneler ise katmanların ve grupların içine yerleşir +@msg layers must be true or false layers true veya false olmalıdır +@msg layout must be gridByRow, gridByColumn, row or column layout gridByRow, gridByColumn, row veya column olmalıdır +@msg leading must be a number or "auto" leading bir sayı veya "auto" olmalıdır +@msg left/right must be non-negative widths left/right negatif olmayan genişlikler olmalıdır +@msg level `{t}`: 2 or 3 level `{t}`: 2 veya 3 +@msg line {line}: more than {MAX_CSV_COLS} columns satır {line}: {MAX_CSV_COLS} taneden fazla sütun +@msg line {line}: unclosed quote satır {line}: kapatılmamış tırnak +@msg line {line}: value for `{var}` must match its variable kind satır {line}: `{var}` değeri değişkeninin türüyle eşleşmelidir +@msg lineEndings `{other}`: lf or crlf lineEndings `{other}`: lf veya crlf +@msg loading profiles from disk isn't available in the browser diskten profil yükleme tarayıcıda kullanılamaz +@msg margin: a {m} pt margin leaves no imageable area on the paper margin: {m} pt'lik bir kenar boşluğu kâğıtta yazdırılabilir alan bırakmıyor +@msg matrix must be finite and invertible, depth finite matrix sonlu ve tersinir, depth ise sonlu olmalıdır +@msg matte: {e} matte: {e} +@msg member is for order front, forward, backward or back member; order değeri front, forward, backward veya back olduğunda kullanılır +@msg missing `artboards` `artboards` eksik +@msg missing `at` [x, y] `at` [x, y] eksik +@msg missing `attrs` `attrs` eksik +@msg missing `color` or `opacity` `color` veya `opacity` eksik +@msg missing `colors` `colors` eksik +@msg missing `commands` `commands` eksik +@msg missing `destinationFolder` `destinationFolder` eksik +@msg missing `effect` id `effect` kimliği eksik +@msg missing `family` `family` eksik +@msg missing `find` `find` eksik +@msg missing `gid` (a glyph id, or null for the default glyph) `gid` eksik (bir glif kimliği veya varsayılan glif için null) +@msg missing `group` `group` eksik +@msg missing `id` `id` eksik +@msg missing `id`: give one, or select one type object `id` eksik: bir tane verin veya tek bir metin nesnesi seçin +@msg missing `index` (a point index, or null to clear) `index` eksik (bir nokta dizini veya temizlemek için null) +@msg missing `index` (a stop index, or null to clear) `index` eksik (bir durak dizini veya temizlemek için null) +@msg missing `index` (an item index or null) `index` eksik (bir öğe dizini veya null) +@msg missing `item` `item` eksik +@msg missing `library` `library` eksik +@msg missing `library` (see graphicStyle.libraries) `library` eksik (bkz. graphicStyle.libraries) +@msg missing `library` (see swatch.library.list) `library` eksik (bkz. swatch.library.list) +@msg missing `map` (rows [{from, to}] or {current}) `map` eksik (satırlar [{from, to}] veya {current}) +@msg missing `matrix` [a,b,c,d,e,f] `matrix` [a,b,c,d,e,f] eksik +@msg missing `name` (see gradient.presets.list) `name` eksik (bkz. gradient.presets.list) +@msg missing `offset` (a distance in points) `offset` eksik (punto cinsinden bir uzaklık) +@msg missing `path` `path` eksik +@msg missing `path` (a path object id) `path` eksik (bir yol nesnesi kimliği) +@msg missing `rule` `rule` eksik +@msg missing `source` id `source` kimliği eksik +@msg missing `start` (the byte offset of a character) `start` eksik (bir karakterin bayt konumu) +@msg missing `status`: linked, embedded, missing or modified `status` eksik: linked, embedded, missing veya modified +@msg missing `target` id `target` kimliği eksik +@msg missing `text` `text` eksik +@msg missing `to` `to` eksik +@msg missing `to` (an index) `to` eksik (bir dizin) +@msg missing `to`: a non-negative integer `to` eksik: negatif olmayan bir tam sayı +@msg missing `type` `type` eksik +@msg missing `value` `value` eksik +@msg missing `{key}` `{key}` eksik +@msg missing `{k}` `{k}` eksik +@msg missing anchor bağlantı noktası eksik +@msg missing anchors bağlantı noktaları eksik +@msg missing anchors [[subpath, anchor]…] anchors [[subpath, anchor]…] eksik +@msg missing array `{key}` `{key}` dizisi eksik +@msg missing case case eksik +@msg missing color renk eksik +@msg missing commands komutlar eksik +@msg missing destination folder hedef klasör eksik +@msg missing from from eksik +@msg missing group grup eksik +@msg missing id or ids id veya ids eksik +@msg missing ids ids eksik +@msg missing indexes indexes eksik +@msg missing matrix [a,b,c,d,e,f] matrix [a,b,c,d,e,f] eksik +@msg missing name ad eksik +@msg missing op op eksik +@msg missing or invalid `color` `color` eksik veya geçersiz +@msg missing or unknown `tool` `tool` eksik veya bilinmiyor +@msg missing point nokta eksik +@msg missing point [x,y] [x,y] noktası eksik +@msg missing point `{key}` ([x, y]) `{key}` noktası eksik ([x, y]) +@msg missing points noktalar eksik +@msg missing points [[x,y]…] points [[x,y]…] eksik +@msg missing segment parça eksik +@msg missing stops duraklar eksik +@msg missing subpaths alt yollar eksik +@msg missing target hedef eksik +@msg missing to to eksik +@msg missing x, y x, y eksik +@msg mode is set, add or toggle, not `{other}` mode set, add veya toggle olur, `{other}` değil +@msg mode must be "cmyk" or "rgb" mode "cmyk" veya "rgb" olmalıdır +@msg mode must be area|onPath, got {o} mode area|onPath olmalıdır, verilen: {o} +@msg more than 10000 linked files: package dependencies in smaller parts 10000 taneden fazla bağlantılı dosya: bağımlılıkları daha küçük parçalar hâlinde paketleyin +@msg more than 256 commands 256 taneden fazla komut +@msg more than {MAX_BATCH_FILES} data sets {MAX_BATCH_FILES} taneden fazla veri kümesi +@msg more than {MAX_BATCH_FILES} files {MAX_BATCH_FILES} taneden fazla dosya +@msg more than {MAX_CSV_ROWS} data rows {MAX_CSV_ROWS} taneden fazla veri satırı +@msg more than {MAX_FILES} images {MAX_FILES} taneden fazla görüntü +@msg more than {MAX_IMPORT} presets {MAX_IMPORT} taneden fazla ön ayar +@msg moved must be [[x,y]…] moved [[x,y]…] olmalıdır +@msg name (a toolbar's name) is required name (bir araç çubuğunun adı) gereklidir +@msg name (a toolbar's name) must be a string name (bir araç çubuğunun adı) bir dize olmalıdır +@msg name must be a toolbar's name name bir araç çubuğunun adı olmalıdır +@msg names is empty names boş +@msg names must be an array of symbol names names bir sembol adları dizisi olmalıdır +@msg need `anchor` or `segment` + `t` `anchor` veya `segment` + `t` gerekir +@msg need at least one anchor en az bir bağlantı noktası gerekir +@msg need at least one point en az bir nokta gerekir +@msg need at least two points en az iki nokta gerekir +@msg needs points noktalar gerekir +@msg nineSlice must be true or false nineSlice true veya false olmalıdır +@msg nineSliceGuides must be [left, top, right, bottom], each -16..16, with left + right < 1 and top + bottom < 1 nineSliceGuides, her biri -16..16 aralığında, left + right < 1 ve top + bottom < 1 olacak şekilde [left, top, right, bottom] olmalıdır +@msg no PDF preset named `{n}` `{n}` adlı bir PDF ön ayarı yok +@msg no action set is current geçerli bir eylem seti yok +@msg no active data set etkin veri kümesi yok +@msg no appearance item {index} {index} numaralı görünüm öğesi yok +@msg no artboard {_1} {_1} numaralı çalışma yüzeyi yok +@msg no artboard {artboard} (0-based; the document has {_1}) {artboard} numaralı çalışma yüzeyi yok (0 tabanlı; belgede {_1} tane var) +@msg no asset {id} {id} kimlikli varlık yok +@msg no asset {id} (see assets.list) {id} kimlikli varlık yok (bkz. assets.list) +@msg no assets to export dışa aktarılacak varlık yok +@msg no assets yet: collect art for export first (assets.add) henüz varlık yok: önce dışa aktarılacak resmi toplayın (assets.add) +@msg no brush named `{n}` `{n}` adlı bir fırça yok +@msg no character at byte {start} {start} numaralı baytta karakter yok +@msg no colour renk yok +@msg no colour group `{group}` `{group}` renk grubu yok +@msg no colour group `{name}` `{name}` renk grubu yok +@msg no data sets veri kümesi yok +@msg no dataset named `{from}` `{from}` adlı bir veri kümesi yok +@msg no dataset named `{name}` `{name}` adlı bir veri kümesi yok +@msg no datasets veri kümesi yok +@msg no design named `{name}` `{name}` adlı bir tasarım yok +@msg no design named `{n}` `{n}` adlı bir tasarım yok +@msg no design named `{old}` `{old}` adlı bir tasarım yok +@msg no encoder for {_1} yet {_1} için henüz bir kodlayıcı yok +@msg no export preset `{name}` (see document.exportPresets.list) `{name}` adında dışa aktarma ön ayarı yok (bkz. document.exportPresets.list) +@msg no folder: pass `path` or set Preferences › Plug-ins & Scratch Disks › Additional Plug-ins Folder klasör yok: `path` verin veya Tercihler › Eklentiler ve Çalışma Diskleri › Ek Eklentiler Klasörü ayarını yapın +@msg no fonts to look for: they are all available aranacak yazı tipi yok: tümü kullanılabilir +@msg no formats to export dışa aktarılacak biçim yok +@msg no gradient preset `{name}` (see gradient.presets.list) `{name}` degrade ön ayarı yok (bkz. gradient.presets.list) +@msg no graphic style `{n}` in `{_1}` `{_1}` içinde `{n}` grafik stili yok +@msg no graphic style library `{key}` (see graphicStyle.libraries) `{key}` grafik stili kütüphanesi yok (bkz. graphicStyle.libraries) +@msg no guide selected seçili kılavuz yok +@msg no guide selected (or give an index) seçili kılavuz yok (veya bir dizin verin) +@msg no guide {i} {i} numaralı kılavuz yok +@msg no images in the folder klasörde görüntü yok +@msg no item at index {_1} {_1} dizininde öğe yok +@msg no item at index {from} {from} dizininde öğe yok +@msg no item at one of the indices {idx} {idx} dizinlerinden birinde öğe yok +@msg no layer katman yok +@msg no layer {id} (see layer.list) {id} kimlikli katman yok (bkz. layer.list) +@msg no layers to export dışa aktarılacak katman yok +@msg no library `{key}` `{key}` kütüphanesi yok +@msg no metafile format meta dosya biçimi yok +@msg no object {_1} {_1} nesnesi yok +@msg no objects nesne yok +@msg no parent layer üst katman yok +@msg no perspective grid preset named `{b}` (see perspective.presets.list) `{b}` adlı bir perspektif ızgarası ön ayarı yok (bkz. perspective.presets.list) +@msg no perspective grid preset named `{n}` `{n}` adlı bir perspektif ızgarası ön ayarı yok +@msg no point selected (give `index`) seçili nokta yok (`index` verin) +@msg no preset called `{from}` (see file.newPresets) `{from}` adlı bir ön ayar yok (bkz. file.newPresets) +@msg no preset called `{name}` (see file.newPresets) `{name}` adlı bir ön ayar yok (bkz. file.newPresets) +@msg no preset named `{n}` `{n}` adlı bir ön ayar yok +@msg no print preset named `{b}` (see print.presets.list) `{b}` adlı bir yazdırma ön ayarı yok (bkz. print.presets.list) +@msg no print preset named `{name}` (presets: {_1}) `{name}` adlı bir yazdırma ön ayarı yok (ön ayarlar: {_1}) +@msg no print preset named `{n}` `{n}` adlı bir yazdırma ön ayarı yok +@msg no profile named `{name}` `{name}` adlı bir profil yok +@msg no readable files in the folder klasörde okunabilir dosya yok +@msg no recovery copy `{f}` (see file.recovery.list) `{f}` kurtarma kopyası yok (bkz. file.recovery.list) +@msg no rows satır yok +@msg no saved PDF preset named `{name}` `{name}` adlı kayıtlı bir PDF ön ayarı yok +@msg no saved export preset `{name}` `{name}` adlı kayıtlı bir dışa aktarma ön ayarı yok +@msg no saved gradient preset called {name} {name} adlı kayıtlı bir degrade ön ayarı yok +@msg no saved gradient presets kayıtlı degrade ön ayarı yok +@msg no saved preset called `{name}` `{name}` adlı kayıtlı bir ön ayar yok +@msg no saved presets to export (name [Default] in `names` to export it) dışa aktarılacak kayıtlı ön ayar yok ([Default] ön ayarını dışa aktarmak için `names` içinde belirtin) +@msg no saved presets to export (name built-in ones in `names`) dışa aktarılacak kayıtlı ön ayar yok (yerleşik olanları `names` içinde belirtin) +@msg no saved print preset named `{name}` `{name}` adlı kayıtlı bir yazdırma ön ayarı yok +@msg no saved profile called {name} {name} adlı kayıtlı bir profil yok +@msg no saved selection `{name}` `{name}` adlı kayıtlı bir seçim yok +@msg no saved theme called {name} (see colorTheme.list) {name} adlı kayıtlı bir tema yok (bkz. colorTheme.list) +@msg no saved views kayıtlı görünüm yok +@msg no series {i} {i} numaralı seri yok +@msg no slice {n} in the image (see slice.list) görüntüde {n} numaralı dilim yok (bkz. slice.list) +@msg no source art kaynak resim yok +@msg no stop {i} (the gradient has {n}) {i} numaralı durak yok (degradede {n} tane var) +@msg no style `{name}` `{name}` stili yok +@msg no such assets (see assets.list) böyle varlıklar yok (bkz. assets.list) +@msg no such frame anchor, or the frame would reach past the canvas böyle bir çerçeve bağlantı noktası yok veya çerçeve tuvalin dışına taşardı +@msg no such objects böyle nesneler yok +@msg no such path anchor, or the path would reach past the canvas böyle bir yol bağlantı noktası yok veya yol tuvalin dışına taşardı +@msg no such rows böyle satırlar yok +@msg no swatch `{keep}` `{keep}` renk örneği yok +@msg no swatch `{n}` `{n}` renk örneği yok +@msg no swatch `{n}` (swatches and colour groups move separately) `{n}` renk örneği yok (renk örnekleri ve renk grupları ayrı ayrı taşınır) +@msg no swatch library `{key}` (see swatch.library.list) `{key}` renk örneği kütüphanesi yok (bkz. swatch.library.list) +@msg no swatch library `{key}` (see swatch.library.list; "document": the document's swatches) `{key}` renk örneği kütüphanesi yok (bkz. swatch.library.list; "document": belgenin renk örnekleri) +@msg no swatch library `{key}` (see swatch.library.list; "{DOCUMENT_SWATCHES}": the document's swatches) `{key}` renk örneği kütüphanesi yok (bkz. swatch.library.list; "{DOCUMENT_SWATCHES}": belgenin renk örnekleri) +@msg no swatch named `{n}` `{n}` adlı bir renk örneği yok +@msg no swatch or colour group `{n}` `{n}` adlı bir renk örneği veya renk grubu yok +@msg no swatch or colour group `{n}` in `{_1}` `{_1}` içinde `{n}` adlı bir renk örneği veya renk grubu yok +@msg no symbol named `{name}` `{name}` adlı bir sembol yok +@msg no text objects selected seçili metin nesnesi yok +@msg no toolbar named `{_1}` `{_1}` adlı bir araç çubuğu yok +@msg no toolbar named `{name}` `{name}` adlı bir araç çubuğu yok +@msg no tracing preset `{preset}` (see imageTrace.presets) `{preset}` izleme ön ayarı yok (bkz. imageTrace.presets) +@msg no user library folder here (save with a path, or without one to get the data) burada kullanıcı kütüphanesi klasörü yok (bir yolla kaydedin veya verileri almak için yol vermeden kaydedin) +@msg no variable named `{from}` `{from}` adlı bir değişken yok +@msg no variable named `{name}` `{name}` adlı bir değişken yok +@msg no variable named `{var}` `{var}` adlı bir değişken yok +@msg no variable named `{v}` `{v}` adlı bir değişken yok +@msg no view named `{name}` `{name}` adlı bir görünüm yok +@msg node {_1} is not a graph {_1} düğümü bir grafik değil +@msg node {_1} is not an image {_1} düğümü bir görüntü değil +@msg node {_1} is not type {_1} düğümü metin değil +@msg not a PDF presets file (format `{_1}`) bir PDF ön ayarları dosyası değil (biçim `{_1}`) +@msg not a PDF presets file: {e} bir PDF ön ayarları dosyası değil: {e} +@msg not a Word document: its WordDocument stream doesn't start with a file information block bir Word belgesi değil: WordDocument akışı bir dosya bilgi bloğuyla başlamıyor +@msg not a Word document: its compound file has no WordDocument stream bir Word belgesi değil: bileşik dosyasında WordDocument akışı yok +@msg not a Word document: its main part is not a WordprocessingML document bir Word belgesi değil: ana bölümü bir WordprocessingML belgesi değil +@msg not a Word document: its package has no main document part bir Word belgesi değil: paketinde ana belge bölümü yok +@msg not a closed path kapalı bir yol değil +@msg not a flattener presets file (format `{_1}`) bir düzleştirici ön ayarları dosyası değil (biçim `{_1}`) +@msg not a flattener presets file: {e} bir düzleştirici ön ayarları dosyası değil: {e} +@msg not a layer or group bir katman veya grup değil +@msg not a library file: {e} bir kütüphane dosyası değil: {e} +@msg not a mesh envelope point bir ağ zarfı noktası değil +@msg not a perspective grid presets file (format `{_1}`) bir perspektif ızgarası ön ayarları dosyası değil (biçim `{_1}`) +@msg not a perspective grid presets file: {e} bir perspektif ızgarası ön ayarları dosyası değil: {e} +@msg not a print presets file (format `{_1}`) bir yazdırma ön ayarları dosyası değil (biçim `{_1}`) +@msg not a print presets file: {e} bir yazdırma ön ayarları dosyası değil: {e} +@msg not a stored or deflated central record saklanmış veya deflate ile sıkıştırılmış bir merkezi kayıt değil +@msg not a valid SVGZ file: {e} geçerli bir SVGZ dosyası değil: {e} +@msg not an image VectorCraft reads (see document.formats) VectorCraft'ın okuduğu bir görüntü değil (bkz. document.formats) +@msg not area type (text in a frame) outside perspective perspektif dışında alan metni (çerçeve içindeki metin) değil +@msg not editing an opacity mask bir opaklık maskesi düzenlenmiyor +@msg not type on a path outside perspective perspektif dışında yol üzerindeki yazı değil +@msg nothing prints hiçbir şey yazdırılmıyor +@msg nothing to bind bağlanacak bir şey yok +@msg nothing to change değiştirilecek bir şey yok +@msg nothing to change: give dx, dy, hScale, vScale or rotation değiştirilecek bir şey yok: dx, dy, hScale, vScale veya rotation verin +@msg nothing to crop kırpılacak bir şey yok +@msg nothing to export dışa aktarılacak bir şey yok +@msg nothing to export: the document has no visible art dışa aktarılacak bir şey yok: belgede görünür resim yok +@msg nothing to mark işaretlenecek bir şey yok +@msg nothing to print: every artboard picked is blank yazdırılacak bir şey yok: seçilen her çalışma yüzeyi boş +@msg nothing to print: the document has no art that prints yazdırılacak bir şey yok: belgede yazdırılan resim yok +@msg object is not a path nesne bir yol değil +@msg object transparency cannot be sampled onto highlighted characters; disable Transparency in Eyedropper Options or select the whole object nesne saydamlığı vurgulanan karakterlere örneklenemez; Damlalık Seçenekleri'nde Saydamlık seçeneğini kapatın veya nesnenin tamamını seçin +@msg object {_1} can't be set as point type {_1} nesnesi nokta metni olarak ayarlanamaz +@msg object {_1} has lost its file's contents: relink it {_1} nesnesi dosyasının içeriğini kaybetti: yeniden bağlayın +@msg object {_1} has no path {_1} nesnesinin yolu yok +@msg object {_1} has no size {_1} nesnesinin boyutu yok +@msg object {_1} is hidden or locked, or on a locked artboard {_1} nesnesi gizli veya kilitli ya da kilitli bir çalışma yüzeyinde +@msg object {_1} is not a placed document {_1} nesnesi yerleştirilmiş bir belge değil +@msg object {_1} is not an Intertwine group {_1} nesnesi bir İç İçe Geçme grubu değil +@msg object {_1} is not an image {_1} nesnesi bir görüntü değil +@msg object {_1} is not an image or a linked file {_1} nesnesi bir görüntü veya bağlantılı bir dosya değil +@msg object {_1} is not an image or a placed document {_1} nesnesi bir görüntü veya yerleştirilmiş bir belge değil +@msg object {_1} is not in this Intertwine group {_1} nesnesi bu İç İçe Geçme grubunda değil +@msg object {_1} needs a 3D effect at index {index} {_1} nesnesinin {index} dizininde bir 3D efekti olmalıdır +@msg object {id} has anchors 0–{_1} for `corners`, not {past} {id} nesnesinde `corners` için 0–{_1} bağlantı noktaları var, {past} yok +@msg object {id} has {n} anchors, so no anchor {past} {id} nesnesinde {n} bağlantı noktası var, bu yüzden {past} numaralı bağlantı noktası yok +@msg objects must be none, move or copy objects none, move veya copy olmalıdır +@msg objects were left out nesneler dışarıda bırakıldı +@msg offset out of range konum aralık dışında +@msg on must be true or false on true veya false olmalıdır +@msg only groups, layers, type and images have a Contents (Characters) row yalnızca grupların, katmanların, metnin ve görüntülerin bir İçerik (Karakterler) satırı vardır +@msg only interior mesh lines can be deleted yalnızca iç ağ çizgileri silinebilir +@msg only solid colours can be added (not gradients or patterns) yalnızca düz renkler eklenebilir (degradeler veya desenler eklenemez) +@msg only solid-colour swatches can be spot colours yalnızca düz renkli renk örnekleri spot renk olabilir +@msg only this Affinity file's embedded preview could be read: use File › Open to see it with its warning, or export SVG or PDF from Affinity first bu Affinity dosyasının yalnızca gömülü önizlemesi okunabildi: uyarısıyla birlikte görmek için Dosya › Aç komutunu kullanın veya önce Affinity'den SVG ya da PDF olarak dışa aktarın +@msg only this Affinity file's embedded preview could be read; use File › Open to see it with its warning bu Affinity dosyasının yalnızca gömülü önizlemesi okunabildi; uyarısıyla birlikte görmek için Dosya › Aç komutunu kullanın +@msg onto, above, below, icon and a column place belong to window.panel.float and window.panel.dock onto, above, below, icon ve bir sütun yeri window.panel.float ve window.panel.dock komutlarına aittir +@msg onto, above, below, icon and a column place take no anchor, side, zone or before onto, above, below, icon ve bir sütun yeri anchor, side, zone veya before almaz +@msg onto, above, below, icon and a column place take no x, y, width or height onto, above, below, icon ve bir sütun yeri x, y, width veya height almaz +@msg open a document to look for its linked files bağlantılı dosyalarını aramak için bir belge açın +@msg options must be an object (see file.formatOptions) options bir nesne olmalıdır (bkz. file.formatOptions) +@msg order must be leftToRight or rightToLeft order leftToRight veya rightToLeft olmalıdır +@msg orientation must be portrait or landscape, not `{o}` orientation portrait veya landscape olmalıdır, `{o}` değil +@msg outlineText {v}: true or false outlineText {v}: true veya false +@msg output intent profile: {e} çıktı amacı profili: {e} +@msg output.destination: no RGB or CMYK profile is called “{name}” output.destination: “{name}” adlı bir RGB veya CMYK profili yok +@msg output.destination: {_1} files are CMYK, and “{name}” is an RGB profile output.destination: {_1} dosyaları CMYK'dir ve “{name}” bir RGB profilidir +@msg output.destination: {e} output.destination: {e} +@msg output.inks: no ink is set to print output.inks: yazdırılmak üzere ayarlanmış mürekkep yok +@msg output.outputIntent: no profile is called “{name}”, and a {std} output intent embeds its profile output.outputIntent: “{name}” adlı bir profil yok ve bir {std} çıktı amacı profilini gömer +@msg output.outputIntent: no profile is called “{name}”: a {std} output intent embeds a profile, or names a registered printing condition (outputConditionId and registry) output.outputIntent: “{name}” adlı bir profil yok: bir {std} çıktı amacı bir profil gömer veya kayıtlı bir baskı koşulunu belirtir (outputConditionId ve registry) +@msg output.outputIntent: {std} files print in CMYK, and “{name}” is an RGB profile output.outputIntent: {std} dosyaları CMYK olarak yazdırılır ve “{name}” bir RGB profilidir +@msg output.outputIntent: “{name}” is a grey profile, which can't be a {std} output intent output.outputIntent: “{name}” bir gri profildir ve bir {std} çıktı amacı olamaz +@msg overlap: {o} pt is half a tile or more overlap: {o} pt bir döşemenin yarısı veya daha fazlası +@msg overlapping Shaper paths must be in the same layer or group çakışan Şekillendirici yolları aynı katmanda veya grupta olmalıdır +@msg overlapping edits çakışan düzenlemeler +@msg page art conflicts with image data for {key} sayfa resmi {key} için görüntü verileriyle çakışıyor +@msg page art conflicts with pattern {name} sayfa resmi {name} deseniyle çakışıyor +@msg page art conflicts with swatch {name} sayfa resmi {name} renk örneğiyle çakışıyor +@msg page art is missing image data for {key} sayfa resminde {key} için görüntü verileri eksik +@msg page art is missing pattern {name} sayfa resminde {name} deseni eksik +@msg page art is missing swatch {name} sayfa resminde {name} renk örneği eksik +@msg page must be a whole number from 1 page 1'den başlayan bir tam sayı olmalıdır +@msg page thumbnail: {e} sayfa küçük resmi: {e} +@msg page {page} of the PDF has no objects PDF'nin {page} numaralı sayfasında nesne yok +@msg page {page}: `{file}` has {n} {artboards} sayfa {page}: `{file}` içinde {n} {artboards} var +@msg page {page}: `{name}` has {n} {pages} sayfa {page}: `{name}` içinde {n} {pages} var +@msg pages must be a range such as "2-3" or a page number, not {v} pages "2-3" gibi bir aralık veya bir sayfa numarası olmalıdır, {v} değil +@msg pages: {e} pages: {e} +@msg panel position must be finite panel konumu sonlu olmalıdır +@msg parameters must be an object parametreler bir nesne olmalıdır +@msg params must be an object params bir nesne olmalıdır +@msg passwords can have up to {MAX_PASSWORD} bytes parolalar en fazla {MAX_PASSWORD} bayt olabilir +@msg path has no open end yolun açık ucu yok +@msg paths must be strings paths dizelerden oluşmalıdır +@msg pdfCompatible: false needs every artboard to keep the editable artwork pdfCompatible: false, düzenlenebilir resmi korumak için her çalışma yüzeyine ihtiyaç duyar +@msg pdfs `{m}`: single or multiple pdfs `{m}`: single veya multiple +@msg pickColorFrom is "artwork" or "swatches", not {v} pickColorFrom "artwork" veya "swatches" olur, {v} değil +@msg pins and moved must be non-empty lists of the same length pins ve moved aynı uzunlukta, boş olmayan listeler olmalıdır +@msg pins must be [[x,y]…] pins [[x,y]…] olmalıdır +@msg pins must be finite pins sonlu olmalıdır +@msg place is above, below or inside, not `{other}` place above, below veya inside olur, `{other}` değil +@msg plane must be left|right|ground plane left|right|ground olmalıdır +@msg plane must be left|right|ground|none plane left|right|ground|none olmalıdır +@msg point is outside the mesh nokta ağın dışında +@msg points must be [t, left, right] with non-negative widths points, negatif olmayan genişliklerle [t, left, right] olmalıdır +@msg points must be a non-empty [[x,y,pressure?]…] list points boş olmayan bir [[x,y,pressure?]…] listesi olmalıdır +@msg points must be a non-empty list of finite [x,y] points, sonlu [x,y] değerlerinden oluşan boş olmayan bir liste olmalıdır +@msg points must be an array or null points bir dizi veya null olmalıdır +@msg points must be finite points sonlu olmalıdır +@msg points must be finite [x,y] pairs points sonlu [x,y] çiftleri olmalıdır +@msg points must contain 1–4096 coordinates points 1–4096 koordinat içermelidir +@msg position must be normal, superscript or subscript position normal, superscript veya subscript olmalıdır +@msg position must be topLeft, topRight, bottomLeft or bottomRight position topLeft, topRight, bottomLeft veya bottomRight olmalıdır +@msg positions must be between 0 and 100000 pt konumlar 0 ile 100000 pt arasında olmalıdır +@msg ppi must be a positive number, not {ppi} ppi pozitif bir sayı olmalıdır, {ppi} değil +@msg ppi must be between 1 and 2400 ppi 1 ile 2400 arasında olmalıdır +@msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}`, transforms|bounds|fileDimensions|fit|fill değerlerinden biri değil +@msg preserveShape must be clippingMask|transparency preserveShape clippingMask|transparency olmalıdır +@msg preset `{id}`: mobile or density preset `{id}`: mobile veya density +@msg preset must be standard, diffuse, topLeft or right preset standard, diffuse, topLeft veya right olmalıdır +@msg preset must be the name of a print preset preset bir yazdırma ön ayarının adı olmalıdır +@msg previewMode must be default, pixel or overprint previewMode default, pixel veya overprint olmalıdır +@msg print settings: {e} yazdırma ayarları: {e} +@msg procedures nest too deeply yordamlar çok derin iç içe geçiyor +@msg procedures nested too deeply yordamlar çok derin iç içe geçmiş +@msg quotes must be {double?, single?} quotes {double?, single?} olmalıdır +@msg quotes.{k} must be an opening and a closing quote, e.g. "“”" quotes.{k} bir açılış ve bir kapanış tırnağı olmalıdır, örneğin "“”" +@msg rasterEffectsPpi must be 1–2400 (72 screen, 150 medium, 300 high) rasterEffectsPpi 1–2400 olmalıdır (72 ekran, 150 orta, 300 yüksek) +@msg rating must be a whole number from 0 to {MAX_RATING} rating 0 ile {MAX_RATING} arasında bir tam sayı olmalıdır +@msg rect and {k} contradict each other: give the area or the artboards rect ve {k} birbiriyle çelişiyor: alanı veya çalışma yüzeylerini verin +@msg rect applies to raster formats, not {_1} rect raster biçimler için geçerlidir, {_1} için değil +@msg rect is [x, y, width, height] in points rect punto cinsinden [x, y, width, height] olur +@msg rect must be [x, y, width, height] rect [x, y, width, height] olmalıdır +@msg rect must be [x, y, width, height] with a positive width and height rect, pozitif genişlik ve yükseklikle [x, y, width, height] olmalıdır +@msg rect needs finite numbers and a positive width and height rect için sonlu sayılar ile pozitif bir genişlik ve yükseklik gerekir +@msg redraw needs id redraw için id gerekir +@msg redraw within must be a finite distance of 0 or more redraw within 0 veya daha büyük sonlu bir uzaklık olmalıdır +@msg registration must be 0..8 registration 0..8 olmalıdır +@msg release a layer or a group bir katmanı veya grubu serbest bırakın +@msg replace keeps the replaced object's place and transform: drop template, at and rect replace, değiştirilen nesnenin yerini ve dönüşümünü korur: template, at ve rect değerlerini çıkarın +@msg replace: select the one object to replace replace: değiştirilecek tek nesneyi seçin +@msg resolution must be a number or screen|medium|high resolution bir sayı veya screen|medium|high olmalıdır +@msg resolution must be between 1 and 2400 ppi resolution 1 ile 2400 ppi arasında olmalıdır +@msg rotation must be a number of degrees rotation derece cinsinden bir sayı olmalıdır +@msg rotation must be finite rotation sonlu olmalıdır +@msg rows and cols must be 1..50 rows ve cols 1..50 olmalıdır +@msg rows and columns must be 1..500 rows ve columns 1..500 olmalıdır +@msg rows of objects whose appearances differ can't be reordered together görünümleri farklı olan nesnelerin satırları birlikte yeniden sıralanamaz +@msg save the document first: Package collects a saved document önce belgeyi kaydedin: Paket kayıtlı bir belgeyi toplar +@msg save the document first: copy puts the file in its folder önce belgeyi kaydedin: copy dosyayı belgenin klasörüne koyar +@msg savedPreset: {e} savedPreset: {e} +@msg scale `{s}`: a factor such as 2x, a width (100w), a height (100h) or a resolution (72ppi) scale `{s}`: 2x gibi bir çarpan, bir genişlik (100w), bir yükseklik (100h) veya bir çözünürlük (72ppi) +@msg scale must be a number above 0, at most 64 scale 0'dan büyük, en fazla 64 olan bir sayı olmalıdır +@msg scale must be non-zero scale sıfırdan farklı olmalıdır +@msg scope must be selection or all (got {other}) scope selection veya all olmalıdır (verilen: {other}) +@msg scribble is too long karalama çok uzun +@msg segment does not exist parça yok +@msg select a Shaper group bir Şekillendirici grubu seçin +@msg select a blend to set easing or color shift yumuşatmayı veya renk kaymasını ayarlamak için bir karışım seçin +@msg select a compound shape bir bileşik şekil seçin +@msg select a graph bir grafik seçin +@msg select a group or layer with visible, unlocked members görünür ve kilitli olmayan üyeleri olan bir grup veya katman seçin +@msg select a layer bir katman seçin +@msg select a text object bir metin nesnesi seçin +@msg select an image (or an Image Trace group) bir görüntü (veya bir Görüntü İzleme grubu) seçin +@msg select an image, or pass id bir görüntü seçin veya id verin +@msg select an object (or pass `id`) bir nesne seçin (veya `id` verin) +@msg select an object with a freeform gradient serbest biçimli degradesi olan bir nesne seçin +@msg select an object with an opacity mask opaklık maskesi olan bir nesne seçin +@msg select area type alan metni seçin +@msg select area type (text in a frame) alan metni (çerçeve içindeki metin) seçin +@msg select area type and closed paths (at least one area type object) alan metni ve kapalı yollar seçin (en az bir alan metni nesnesi) +@msg select area type whose first line can fit its frame ilk satırı çerçevesine sığabilen alan metni seçin +@msg select artwork to add its colours renklerini eklemek için resim seçin +@msg select artwork to make a group of its colours renklerinden bir grup oluşturmak için resim seçin +@msg select artwork to recolour, or give a colour `group` yeniden renklendirilecek resmi seçin veya bir renk için `group` verin +@msg select exactly two path ends to join birleştirmek için tam olarak iki yol ucu seçin +@msg select members of a compound shape bir bileşik şeklin üyelerini seçin +@msg select objects or give ids nesneleri seçin veya ids verin +@msg select objects to align to the guide kılavuza hizalanacak nesneleri seçin +@msg select one Intertwine group tek bir İç İçe Geçme grubu seçin +@msg select one image or pass id tek bir görüntü seçin veya id verin +@msg select paths yolları seçin +@msg select paths or compound paths yolları veya bileşik yolları seçin +@msg select rows or objects to collect toplanacak satırları veya nesneleri seçin +@msg select something to export dışa aktarılacak bir şey seçin +@msg select something to export (or turn off selectedOnly) dışa aktarılacak bir şey seçin (veya selectedOnly seçeneğini kapatın) +@msg select text to redefine the style from stilin yeniden tanımlanacağı metni seçin +@msg select the art and, on top of it, the mask object resmi ve onun üstündeki maske nesnesini seçin +@msg select the art for the design tasarım için resmi seçin +@msg select the art for the pattern tile desen döşemesi için resmi seçin +@msg select the art to add first önce eklenecek resmi seçin +@msg select the art to collect (or give its ids) toplanacak resmi seçin (veya kimliklerini verin) +@msg select the content and a path on top içeriği ve üstteki bir yolu seçin +@msg select the images to relink, or pass ids yeniden bağlanacak görüntüleri seçin veya ids verin +@msg select the images, or pass ids görüntüleri seçin veya ids verin +@msg select the linked images or placed documents, or pass ids bağlantılı görüntüleri veya yerleştirilmiş belgeleri seçin ya da ids verin +@msg select the object to copy from kopyalanacak kaynak nesneyi seçin +@msg select the objects (or give their ids) nesneleri seçin (veya kimliklerini verin) +@msg select the objects to attach to the path yola iliştirilecek nesneleri seçin +@msg select the objects to bind bağlanacak nesneleri seçin +@msg select two or more objects to intertwine iç içe geçirmek için iki veya daha fazla nesne seçin +@msg select two or more slices to combine birleştirmek için iki veya daha fazla dilim seçin +@msg select type on a path yol üzerindeki yazıyı seçin +@msg selection `{m}`: one or each selection `{m}`: one veya each +@msg settings is an object of document.exportForScreens params settings, document.exportForScreens parametrelerinden oluşan bir nesnedir +@msg settings must be an object settings bir nesne olmalıdır +@msg show `{show}`: all, missing, modified or embedded show `{show}`: all, missing, modified veya embedded +@msg show must be true or false show true veya false olmalıdır +@msg size must be "small", "medium", "large" or a number of points over 0 up to {_1} size "small", "medium", "large" veya 0'dan büyük, en fazla {_1} olan punto cinsinden bir sayı olmalıdır +@msg size must be positive size pozitif olmalıdır +@msg sizeMode is "fixed" or "pressure", not `{other}` sizeMode "fixed" veya "pressure" olur, `{other}` değil +@msg sizeMode is "fixed" or "pressure", not {other} sizeMode "fixed" veya "pressure" olur, {other} değil +@msg sizeVariation must be 0 or more sizeVariation 0 veya daha büyük olmalıdır +@msg smallCaps must be true or false smallCaps true veya false olmalıdır +@msg sort `{x}`: name, kind or status sort `{x}`: name, kind veya status +@msg source paths are too large for Shaper kaynak yollar Şekillendirici için çok büyük +@msg spot, mode and group apply to solid colours only spot, mode ve group yalnızca düz renkler için geçerlidir +@msg status `{s}`: linked, embedded, missing or modified status `{s}`: linked, embedded, missing veya modified +@msg steps must be 1..1000 steps 1..1000 olmalıdır +@msg steps must be 1..{MAX_STEPS} steps 1..{MAX_STEPS} olmalıdır +@msg stop {i}: `plates` must be four numbers from 0 to 1 (C, M, Y, K) durak {i}: `plates` 0 ile 1 arasında dört sayı olmalıdır (C, M, Y, K) +@msg stopped before the archive was finished arşiv tamamlanmadan önce durduruldu +@msg strokeMode must be within|along|across, got {m} strokeMode within|along|across olmalıdır, verilen: {m} +@msg strokeOptions must be an object of stroke.set options strokeOptions, stroke.set seçeneklerinden oluşan bir nesne olmalıdır +@msg strokeWidth must be a positive number of pixels strokeWidth piksel cinsinden pozitif bir sayı olmalıdır +@msg subpath {si} is not an open subpath {si} numaralı alt yol açık bir alt yol değil +@msg subpaths required when joining the same path aynı yol birleştirilirken subpaths gereklidir +@msg swatchConflict must be "merge" or "add", not {v} swatchConflict "merge" veya "add" olmalıdır, {v} değil +@msg text must be {characterSet?, platform?, removeLineReturns?, removeParagraphReturns?, replaceSpaces?} text {characterSet?, platform?, removeLineReturns?, removeParagraphReturns?, replaceSpaces?} olmalıdır +@msg text transform is collapsed or unrepresentable metin dönüşümü çökmüş veya ifade edilemiyor +@msg text.replaceSpaces must be a whole number from 2 to 100 text.replaceSpaces 2 ile 100 arasında bir tam sayı olmalıdır +@msg text.{key} `{v}`: use "{_1}" or "{_2}" text.{key} `{v}`: "{_1}" veya "{_2}" kullanın +@msg textureImage: give {path} or {name, dataBase64} of an image file, or a texture as effect.list gives it textureImage: bir görüntü dosyasının {path} veya {name, dataBase64} değerini ya da effect.list'in verdiği biçimde bir doku verin +@msg textureImage: {e} textureImage: {e} +@msg that makes more than {MAX_PIECES} slices bu {MAX_PIECES} taneden fazla dilim oluşturuyor +@msg that object is not in the overlap o nesne çakışmanın içinde değil +@msg the Affinity document has no page with a size Affinity belgesinde boyutu olan bir sayfa yok +@msg the CMYK image couldn't be written CMYK görüntü yazılamadı +@msg the PDF security settings were saved without their passwords: give openPassword or permissionsPassword again, or security without passwordRequired to export unprotected PDF güvenlik ayarları parolaları olmadan kaydedildi: openPassword veya permissionsPassword değerini yeniden verin ya da korumasız dışa aktarmak için passwordRequired olmadan security verin +@msg the RTF file has too many paragraphs or formatting changes to place as type (at most {MAX_PARAGRAPHS} paragraphs and {MAX_RUNS} runs) RTF dosyasında metin olarak yerleştirilemeyecek kadar çok paragraf veya biçimlendirme değişikliği var (en fazla {MAX_PARAGRAPHS} paragraf ve {MAX_RUNS} dizi) +@msg the RTF file is too large to place as type (at most {_1} MB) RTF dosyası metin olarak yerleştirilemeyecek kadar büyük (en fazla {_1} MB) +@msg the SVG expands to more than {0} nested SVG images SVG, {0} taneden fazla iç içe SVG görüntüsüne genişliyor +@msg the SVG expands to more than {0} objects SVG, {0} taneden fazla nesneye genişliyor +@msg the SVG has no drawable objects SVG'de çizilebilir nesne yok +@msg the SVGZ file unpacks to more than {_1} MB SVGZ dosyası açılınca {_1} MB'ı aşıyor +@msg the Word document has more than {MAX_PAGES} pages of properties, too many to place Word belgesinde {MAX_PAGES} sayfadan fazla özellik var; yerleştirilemeyecek kadar çok +@msg the Word document has more than {MAX_RUNS} runs of character or paragraph properties, too many to place Word belgesinde {MAX_RUNS} taneden fazla karakter veya paragraf özelliği dizisi var; yerleştirilemeyecek kadar çok +@msg the Word document has more than {_1} MB of formatting properties, too many to place Word belgesinde {_1} MB'tan fazla biçimlendirme özelliği var; yerleştirilemeyecek kadar çok +@msg the Word document has too much text or formatting to place as type (at most {MAX_PARAGRAPHS} paragraphs, {MAX_RUNS} runs and {_1} MB of text) Word belgesinde metin olarak yerleştirilemeyecek kadar çok metin veya biçimlendirme var (en fazla {MAX_PARAGRAPHS} paragraf, {MAX_RUNS} dizi ve {_1} MB metin) +@msg the Word document has too much text to place as type (at most {_1} MB) Word belgesinde metin olarak yerleştirilemeyecek kadar çok metin var (en fazla {_1} MB) +@msg the Word document is encrypted or protected with a password; save it without one to place it Word belgesi şifrelenmiş veya parolayla korunmuş; yerleştirmek için parolasız kaydedin +@msg the Word document is too large to place (its {name} stream holds more than {_1} MB) Word belgesi yerleştirilemeyecek kadar büyük ({name} akışı {_1} MB'tan fazla veri içeriyor) +@msg the Word document was last saved with fast save, which VectorCraft doesn't read; save it again with fast save turned off Word belgesi son olarak hızlı kaydetme ile kaydedilmiş ve VectorCraft bunu okumaz; hızlı kaydetme kapalıyken yeniden kaydedin +@msg the Word document was saved by Word 6.0 or Word 95, which VectorCraft doesn't read; save it as a Word 97-2003 document Word belgesi Word 6.0 veya Word 95 ile kaydedilmiş ve VectorCraft bunu okumaz; Word 97-2003 belgesi olarak kaydedin +@msg the Word document's text is made of more than {MAX_PIECES} pieces, too many to place Word belgesinin metni {MAX_PIECES} taneden fazla parçadan oluşuyor; yerleştirilemeyecek kadar çok +@msg the action set ids are not a list eylem seti kimlikleri bir liste değil +@msg the active paint is not a gradient etkin boya bir degrade değil +@msg the artboards don't fit on the canvas: fewer artboards, less spacing or a smaller size çalışma yüzeyleri tuvale sığmıyor: daha az çalışma yüzeyi, daha az aralık veya daha küçük bir boyut kullanın +@msg the character's size can't be measured karakterin boyutu ölçülemiyor +@msg the compound shape is too complex to expand bileşik şekil genişletilemeyecek kadar karmaşık +@msg the container of the listed objects is gone listelenen nesnelerin kapsayıcısı artık yok +@msg the copy `{user_id}` can't be read as a library `{user_id}` kopyası bir kütüphane olarak okunamıyor +@msg the copy would leave the canvas kopya tuvalin dışına çıkardı +@msg the cut cannot be made on this art: {e} bu resimde kesim yapılamıyor: {e} +@msg the data isn't an EMF or WMF picture veri bir EMF veya WMF resmi değil +@msg the data isn't an EPS or PostScript picture veri bir EPS veya PostScript resmi değil +@msg the deferred paste is no longer available ertelenmiş yapıştırma artık kullanılamıyor +@msg the design is too big to draw at every data point of this graph tasarım bu grafiğin her veri noktasında çizilemeyecek kadar büyük +@msg the design is too big to draw in every column of this graph tasarım bu grafiğin her sütununda çizilemeyecek kadar büyük +@msg the dialog it was opened over is no longer open üzerinde açıldığı iletişim kutusu artık açık değil +@msg the dictionary stack overflowed sözlük yığını taştı +@msg the editing data's hash has no place düzenleme verilerinin karması için yer yok +@msg the entities the document declares expand to too much text belgenin bildirdiği varlıklar çok fazla metne genişliyor +@msg the envelope's content has no bounds zarfın içeriğinin sınırları yok +@msg the envelope's mesh is malformed zarfın ağı hatalı biçimlendirilmiş +@msg the file holds no `variableSets` element dosyada `variableSets` öğesi yok +@msg the file is larger than {_1} MB dosya {_1} MB'tan büyük +@msg the file is too large dosya çok büyük +@msg the file was updated or encrypted already dosya zaten güncellenmiş veya şifrelenmiş +@msg the first character of a line has no character before it to kern: it moves only up and down (dy) bir satırın ilk karakterinden önce aralığı ayarlanacak bir karakter yoktur: yalnızca yukarı ve aşağı hareket eder (dy) +@msg the font {_1} is not available {_1} yazı tipi kullanılamıyor +@msg the format has no file extension biçimin dosya uzantısı yok +@msg the graphic can't be read: {e} grafik okunamıyor: {e} +@msg the graphic is empty grafik boş +@msg the graphic's data is damaged grafiğin verileri hasarlı +@msg the graphic's document has no artboard grafiğin belgesinde çalışma yüzeyi yok +@msg the header `{cell}` for `{name}` would read back as the variable `{other}`: rename one of them `{name}` için `{cell}` başlığı `{other}` değişkeni olarak geri okunurdu: birini yeniden adlandırın +@msg the image `{path}` isn't followed: {r} `{path}` görüntüsü izlenmiyor: {r} +@msg the image has no embedded pixels görüntüde gömülü piksel yok +@msg the image is empty görüntü boş +@msg the image is fully transparent görüntü tamamen saydam +@msg the image is not on an artboard; pass rect görüntü bir çalışma yüzeyinde değil; rect verin +@msg the image's pixels are missing görüntünün pikselleri eksik +@msg the image's pixels aren't in the document görüntünün pikselleri belgede değil +@msg the image's pixels can't be read: {e} görüntünün pikselleri okunamıyor: {e} +@msg the image's transparency doesn't fit it görüntünün saydamlığı görüntüye uymuyor +@msg the job would print more than {MAX_PAGES} pages iş {MAX_PAGES} sayfadan fazla yazdırırdı +@msg the job would print more than {_1} pages iş {_1} sayfadan fazla yazdırırdı +@msg the layers hold no art to mask katmanlarda maskelenecek resim yok +@msg the layout moved düzen taşındı +@msg the library has a group `{name}` already kütüphanede `{name}` grubu zaten var +@msg the library has no group `{name}` kütüphanede `{name}` grubu yok +@msg the library has no item `{item}` kütüphanede `{item}` öğesi yok +@msg the library has no item `{other}` kütüphanede `{other}` öğesi yok +@msg the library holds {MAX_GROUPS} groups already kütüphanede zaten {MAX_GROUPS} grup var +@msg the library holds {MAX_ITEMS} items of this kind already kütüphanede bu türden zaten {MAX_ITEMS} öğe var +@msg the name is empty ad boş +@msg the object has no fill, stroke or effect nesnenin dolgusu, konturu veya efekti yok +@msg the object has no graphic style (pass `name`) nesnenin grafik stili yok (`name` verin) +@msg the objects don't match the plan nesneler planla eşleşmiyor +@msg the open and permissions passwords must differ açma ve izin parolaları farklı olmalıdır +@msg the operand stack overflowed işlenen yığını taştı +@msg the page has no area sayfanın alanı yok +@msg the page's type in an unread object's box isn't in its page art okunmamış bir nesnenin kutusundaki sayfa metni, sayfa resminde yok +@msg the paint behind the proxy is not a gradient vekilin arkasındaki boya bir degrade değil +@msg the parent must be a layer or sublayer üst öğe bir katman veya alt katman olmalıdır +@msg the path can't be extended yol uzatılamıyor +@msg the path can't be inside one of the objects to attach yol, iliştirilecek nesnelerden birinin içinde olamaz +@msg the path has no segments to measure yolda ölçülecek parça yok +@msg the path is empty yol boş +@msg the path is too short to shorten that much yol o kadar kısaltılamayacak kadar kısa +@msg the picture has no objects resimde nesne yok +@msg the program runs too long program çok uzun süre çalışıyor +@msg the program uses too much memory program çok fazla bellek kullanıyor +@msg the rectangle must have a width and a height dikdörtgenin bir genişliği ve bir yüksekliği olmalıdır +@msg the rectangle needs a size and must lie on the canvas dikdörtgenin bir boyutu olmalı ve tuvalin üzerinde bulunmalıdır +@msg the selected art has no width seçili resmin genişliği yok +@msg the selection draws nothing seçim hiçbir şey çizmiyor +@msg the selection has no area seçimin alanı yok +@msg the selection has no art to export seçimde dışa aktarılacak resim yok +@msg the selection has no bounds seçimin sınırları yok +@msg the selection has no graphic style seçimin grafik stili yok +@msg the slice would leave the canvas dilim tuvalin dışına çıkardı +@msg the spot colour couldn't be added spot renk eklenemedi +@msg the subpath has no ends to extend (it is closed or a single point) alt yolun uzatılacak ucu yok (kapalı veya tek bir nokta) +@msg the symbols are nested too deeply to expand their instances semboller, örnekleri genişletilemeyecek kadar derin iç içe geçmiş +@msg the text file is too large to place as type (at most {_1} MB) metin dosyası metin olarak yerleştirilemeyecek kadar büyük (en fazla {_1} MB) +@msg the text is empty metin boş +@msg the text is over {_1} MB metin {_1} MB'tan büyük +@msg the top object must be a path üstteki nesne bir yol olmalıdır +@msg the trace was cancelled izleme iptal edildi +@msg the trailer has no size trailer'ın boyutu yok +@msg the type object is flattened to nothing metin nesnesi düzleştirilince hiçbir şey kalmıyor +@msg the value of axis `{tag}` must be a number or null `{tag}` ekseninin değeri bir sayı veya null olmalıdır +@msg the variable library declares more than {MAX_LIBRARY_DATASETS} data sets değişken kütüphanesi {MAX_LIBRARY_DATASETS} taneden fazla veri kümesi bildiriyor +@msg the variable library declares more than {MAX_LIBRARY_ENTITIES} entities değişken kütüphanesi {MAX_LIBRARY_ENTITIES} taneden fazla varlık bildiriyor +@msg the variable library declares more than {MAX_LIBRARY_VARIABLES} variables değişken kütüphanesi {MAX_LIBRARY_VARIABLES} taneden fazla değişken bildiriyor +@msg the variable library declares no variables değişken kütüphanesi hiçbir değişken bildirmiyor +@msg the variable library is larger than {MAX_LIBRARY_BYTES} bytes değişken kütüphanesi {MAX_LIBRARY_BYTES} bayttan büyük +@msg the variable library is not UTF-8 değişken kütüphanesi UTF-8 değil +@msg the variable library is not well-formed XML: {e} değişken kütüphanesi iyi biçimlendirilmiş bir XML değil: {e} +@msg the variable library nests elements more than {MAX_LIBRARY_NESTING} deep değişken kütüphanesi öğeleri {MAX_LIBRARY_NESTING} düzeyden daha derin iç içe yerleştiriyor +@msg the variable library's document type declaration holds something other than entities of plain text değişken kütüphanesinin belge türü bildirimi, düz metin varlıklarından başka bir şey içeriyor +@msg the variable library's entities expand to more than {MAX_LIBRARY_BYTES} bytes değişken kütüphanesinin varlıkları {MAX_LIBRARY_BYTES} bayttan fazlasına genişliyor +@msg the window has no dock pencerede yerleştirme alanı yok +@msg the written PDF has no catalog yazılan PDF'de katalog yok +@msg the written PDF has no cross-reference table yazılan PDF'de çapraz başvuru tablosu yok +@msg the written PDF's metadata can't be edited yazılan PDF'nin meta verileri düzenlenemiyor +@msg there are no colour swatches to draw çizilecek renk örneği yok +@msg there is already a design named `{name}` `{name}` adlı bir tasarım zaten var +@msg there is already a design named `{to}` `{to}` adlı bir tasarım zaten var +@msg there is already a toolbar named `{name}` `{name}` adlı bir araç çubuğu zaten var +@msg there is already a toolbar named `{to}` `{to}` adlı bir araç çubuğu zaten var +@msg there is no library: create one first kütüphane yok: önce bir tane oluşturun +@msg these paths are too degenerate for Shaper bu yollar Şekillendirici için fazla yozlaşmış +@msg thumbnail: no page {v} (the {what} has {count}) thumbnail: {v} numaralı sayfa yok ({what} içinde {count} tane var) +@msg tileRange of {what}: {e} {what} için tileRange: {e} +@msg title can't be empty title boş olamaz +@msg to (the new name) is required to (yeni ad) gereklidir +@msg to must be fill or stroke to fill veya stroke olmalıdır +@msg to must be smooth or corner to smooth veya corner olmalıdır +@msg too large for a zip archive: package to a folder bir zip arşivi için çok büyük: bir klasöre paketleyin +@msg too many Shaper edits çok fazla Şekillendirici düzenlemesi +@msg too many `points` (at most 100000) çok fazla `points` (en fazla 100000) +@msg too many characters: at most {MAX_CHARS} çok fazla karakter: en fazla {MAX_CHARS} +@msg too many dots for this size: lower the frequency bu boyut için çok fazla nokta: frekansı düşürün +@msg too many filters over one file tek bir dosya üzerinde çok fazla filtre +@msg too many overlapping paths for Shaper Şekillendirici için çok fazla çakışan yol +@msg too many saved clips çok fazla kayıtlı kırpma +@msg too many saved graphics states çok fazla kayıtlı grafik durumu +@msg toolbar (a toolbar's name) must be a string toolbar (bir araç çubuğunun adı) bir dize olmalıdır +@msg toolbar name can't be empty araç çubuğu adı boş olamaz +@msg transparentImages {v}: "flatten" (the default) or "omit" transparentImages {v}: "flatten" (varsayılan) veya "omit" +@msg two saved selections would be named `{_1}` iki kayıtlı seçimin adı `{_1}` olurdu +@msg type dimension cannot be represented with this text transform metin boyutu bu metin dönüşümüyle ifade edilemiyor +@msg type dimension must be finite metin boyutu sonlu olmalıdır +@msg unexpected resources beklenmeyen kaynaklar +@msg unknown CMYK profile `{name}` bilinmeyen CMYK profili `{name}` +@msg unknown File Info field `{k}` bilinmeyen Dosya Bilgisi alanı `{k}` +@msg unknown OpenType feature `{t}` in featureChanges (the tags `features` takes) featureChanges içinde bilinmeyen OpenType özelliği `{t}` (`features` parametresinin aldığı etiketler) +@msg unknown PDF preset `{name}` (presets: {_1}) bilinmeyen PDF ön ayarı `{name}` (ön ayarlar: {_1}) +@msg unknown Warp style bilinmeyen Çarpıtma stili +@msg unknown alignToPath `{a}` bilinmeyen alignToPath `{a}` +@msg unknown arrowhead {v} bilinmeyen ok ucu {v} +@msg unknown artboardLayout key `{k}` (layout, columns, spacing, rightToLeft) bilinmeyen artboardLayout anahtarı `{k}` (layout, columns, spacing, rightToLeft) +@msg unknown attribute `{attribute}` bilinmeyen öznitelik `{attribute}` +@msg unknown attribute `{k}` bilinmeyen öznitelik `{k}` +@msg unknown axis `{other}` (vertical|horizontal|free) bilinmeyen eksen `{other}` (vertical|horizontal|free) +@msg unknown blend mode `{b}` bilinmeyen karıştırma modu `{b}` +@msg unknown blend mode {b} bilinmeyen karıştırma modu {b} +@msg unknown brush type `{o}` bilinmeyen fırça türü `{o}` +@msg unknown category `{c}` bilinmeyen kategori `{c}` +@msg unknown category `{c}` ({_1}) bilinmeyen kategori `{c}` ({_1}) +@msg unknown character `{c}` bilinmeyen karakter `{c}` +@msg unknown character style number field bilinmeyen karakter stili sayı alanı +@msg unknown effect `{e}` bilinmeyen efekt `{e}` +@msg unknown end {e} bilinmeyen uç {e} +@msg unknown flattenerPreset `{name}` (High Resolution, Medium Resolution, Low Resolution or a saved one: see flattener.presets.list) bilinmeyen flattenerPreset `{name}` (High Resolution, Medium Resolution, Low Resolution veya kayıtlı bir ön ayar: bkz. flattener.presets.list) +@msg unknown format `{f}` (vcswatches, gpl, ase or css) bilinmeyen biçim `{f}` (vcswatches, gpl, ase veya css) +@msg unknown from {f} bilinmeyen from {f} +@msg unknown graph type `{t}` bilinmeyen grafik türü `{t}` +@msg unknown grid colours `{name}` (one of {_1}) bilinmeyen ızgara renkleri `{name}` (şunlardan biri: {_1}) +@msg unknown gridType `{t}` bilinmeyen gridType `{t}` +@msg unknown highlight `{v}` bilinmeyen vurgu `{v}` +@msg unknown intent `{i}` bilinmeyen amaç `{i}` +@msg unknown issue kind {id} bilinmeyen sorun türü {id} +@msg unknown issue kind {v} bilinmeyen sorun türü {v} +@msg unknown knockout state {k} bilinmeyen nakavt durumu {k} +@msg unknown language `{language}` (one of {_1}) bilinmeyen dil `{language}` (şunlardan biri: {_1}) +@msg unknown language `{l}` (one of {_1}) bilinmeyen dil `{l}` (şunlardan biri: {_1}) +@msg unknown method `{m}` ({_1}) bilinmeyen yöntem `{m}` ({_1}) +@msg unknown mode `{other}` (gray, rgb, hsb, lab, cmyk or web) bilinmeyen mod `{other}` (gray, rgb, hsb, lab, cmyk veya web) +@msg unknown mode `{other}` (mono|cmyk) bilinmeyen mod `{other}` (mono|cmyk) +@msg unknown mode `{other}` (rgb|cmyk|gray|global) bilinmeyen mod `{other}` (rgb|cmyk|gray|global) +@msg unknown mode `{other}` (set, add, subtract) bilinmeyen mod `{other}` (set, add, subtract) +@msg unknown mode `{o}` bilinmeyen mod `{o}` +@msg unknown mode {m} bilinmeyen mod {m} +@msg unknown model `{other}` bilinmeyen model `{other}` +@msg unknown model `{other}` (keep, new or document) bilinmeyen model `{other}` (keep, new veya document) +@msg unknown op {o} bilinmeyen op {o} +@msg unknown order `{o}`: toggle, front, forward, backward or back bilinmeyen order `{o}`: toggle, front, forward, backward veya back +@msg unknown overprints `{v}` (preserve, simulate or discard) bilinmeyen overprints `{v}` (preserve, simulate veya discard) +@msg unknown panel bilinmeyen panel +@msg unknown pieLegend `{v}` (none, standard or wedges) bilinmeyen pieLegend `{v}` (none, standard veya wedges) +@msg unknown piePosition `{v}` (even, ratio or stacked) bilinmeyen piePosition `{v}` (even, ratio veya stacked) +@msg unknown pieSort `{v}` (none, all or first) bilinmeyen pieSort `{v}` (none, all veya first) +@msg unknown plate `{n}` bilinmeyen kalıp `{n}` +@msg unknown preference `{k}` bilinmeyen tercih `{k}` +@msg unknown profile {id} (see stroke.widthProfile.list) bilinmeyen profil {id} (bkz. stroke.widthProfile.list) +@msg unknown proof target `{t}` bilinmeyen prova hedefi `{t}` +@msg unknown quotes key `{k}` (double, single) bilinmeyen quotes anahtarı `{k}` (double, single) +@msg unknown resolution `{v}` bilinmeyen çözünürlük `{v}` +@msg unknown rule `{rule}` ({_1}) bilinmeyen kural `{rule}` ({_1}) +@msg unknown rule `{r}` (see color.harmony) bilinmeyen kural `{r}` (bkz. color.harmony) +@msg unknown setting `{k}` bilinmeyen ayar `{k}` +@msg unknown shape `{v}` (circle|ellipse|square|diamond|line) bilinmeyen şekil `{v}` (circle|ellipse|square|diamond|line) +@msg unknown spacing `{o}` (smooth|steps|distance) bilinmeyen spacing `{o}` (smooth|steps|distance) +@msg unknown tileType `{t}` ({_1}) bilinmeyen tileType `{t}` ({_1}) +@msg unknown units bilinmeyen birimler +@msg unknown units `{u}` bilinmeyen birimler `{u}` +@msg unknown value axis `{v}` (left, right or both) bilinmeyen değer ekseni `{v}` (left, right veya both) +@msg unknown variation `{v}` (tintsShades|warmCool|vividMuted) bilinmeyen çeşitleme `{v}` (tintsShades|warmCool|vividMuted) +@msg unknown warp style `{s}` bilinmeyen çarpıtma stili `{s}` +@msg unknown {key} `{v}` (none, short or full) bilinmeyen {key} `{v}` (none, short veya full) +@msg unknown {key} profile `{n}` bilinmeyen {key} profili `{n}` +@msg unknown {k} key `{key}` (size, position) bilinmeyen {k} anahtarı `{key}` (size, position) +@msg unreadable object okunamayan nesne +@msg unsafe destination file name güvenli olmayan hedef dosya adı +@msg use paths or compound paths yolları veya bileşik yolları kullanın +@msg useArtboards must be true or false, not {v} useArtboards true veya false olmalıdır, {v} değil +@msg value for `{var}` must match its variable kind `{var}` değeri değişkeninin türüyle eşleşmelidir +@msg variable `{_1}` is already defined `{_1}` değişkeni zaten tanımlı +@msg variable `{name}` has no `trait` `{name}` değişkeninde `trait` yok +@msg variable `{name}` is already defined `{name}` değişkeni zaten tanımlı +@msg variable `{name}` is declared twice `{name}` değişkeni iki kez bildirilmiş +@msg variable `{to}` already exists `{to}` değişkeni zaten var +@msg view is required view gereklidir +@msg view must be one of {_1} view şunlardan biri olmalıdır: {_1} +@msg warpStyle can only edit an applied Warp effect warpStyle yalnızca uygulanmış bir Çarpıtma efektini düzenleyebilir +@msg width and height must be more than 0 and at most {limit} width ve height 0'dan büyük ve en fazla {limit} olmalıdır +@msg width factors must be finite genişlik çarpanları sonlu olmalıdır +@msg width must be positive width pozitif olmalıdır +@msg width out of range genişlik aralık dışında +@msg width/height must be > 0 width/height > 0 olmalıdır +@msg x and y must be finite numbers x ve y sonlu sayılar olmalıdır +@msg x and y must be given together x ve y birlikte verilmelidir +@msg zone needs an anchor: dock beside a panel with anchor, or in a new dock column with side (Start or End) zone için bir anchor gerekir: anchor ile bir panelin yanına veya side (Start ya da End) ile yeni bir yerleştirme sütununa yerleştirin +@msg zoom must be positive zoom pozitif olmalıdır +@msg {C}: no effect at index {list} {C}: {list} dizininde efekt yok +@msg {DEFAULT_PRESET} is protected and stays {DEFAULT_PRESET} korumalıdır ve kalır +@msg {DEFAULT_PRESET} is protected: save the settings under another name {DEFAULT_PRESET} korumalıdır: ayarları başka bir adla kaydedin +@msg {LABEL} produced an empty result {LABEL} boş bir sonuç üretti +@msg {_1} MB of document, at most {_2} MB {_1} MB belge, en fazla {_2} MB +@msg {_1} MB of images, at most {_2} MB {_1} MB görüntü, en fazla {_2} MB +@msg {_1} bytes of RGBA data for a {width} × {height} image {width} × {height} boyutlu bir görüntü için {_1} bayt RGBA verisi +@msg {_1} can't be read, or changed since it was read: relink or update it first {_1} okunamıyor veya okunduktan sonra değişmiş: önce yeniden bağlayın veya güncelleyin +@msg {_1} can't go into {into} {_1}, {into} içine konulamaz +@msg {_1} can't limit printing to low resolution: choose PDF 1.4 or later, or allow high-resolution printing {_1} yazdırmayı düşük çözünürlükle sınırlayamaz: PDF 1.4 veya sonrasını seçin ya da yüksek çözünürlüklü yazdırmaya izin verin +@msg {_1} files can't be opened yet {_1} dosyaları henüz açılamıyor +@msg {_1} files can't be password-protected: remove the passwords or choose no standard {_1} dosyaları parolayla korunamaz: parolaları kaldırın veya standart seçmeyin +@msg {_1} files can't be {_2} {_1} dosyaları için şu yapılamaz: {_2} +@msg {_1} files can't carry editing data: turn off preserveEditing {_1} dosyaları düzenleme verileri taşıyamaz: preserveEditing seçeneğini kapatın +@msg {_1} files can't have PDF layers: turn off createLayers {_1} dosyalarında PDF katmanları olamaz: createLayers seçeneğini kapatın +@msg {_1} files need a creation date, and this platform has no clock to give one {_1} dosyaları için bir oluşturma tarihi gerekir ve bu platformda bunu verecek bir saat yok +@msg {_1} isn't a path {_1} bir yol değil +@msg {_1} options: {e} {_1} seçenekleri: {e} +@msg {_1} paints nothing to rasterize {_1} rasterleştirilecek hiçbir şey boyamıyor +@msg {_1} passwords can have up to {MAX_LEGACY_PASSWORD} ASCII characters (PDF 1.7 and later take any) {_1} parolaları en fazla {MAX_LEGACY_PASSWORD} ASCII karakter içerebilir (PDF 1.7 ve sonrası her karakteri alır) +@msg {_1} with linked images or an image map writes several files: use document.export bağlantılı görüntüler veya bir görüntü eşlemi içeren {_1} birkaç dosya yazar: document.export kullanın +@msg {_1} writes one file per artboard here: use document.export, or name one artboard {_1} burada çalışma yüzeyi başına bir dosya yazar: document.export kullanın veya tek bir çalışma yüzeyi belirtin +@msg {_1} × {_2} pixels is too large for {_3} (at most {max} pixels a side): lower the scale {_1} × {_2} piksel {_3} için çok büyük (kenar başına en fazla {max} piksel): ölçeği düşürün +@msg {_1}: belongs to another account {_1}: başka bir hesaba ait +@msg {_1}: not a folder of its own {_1}: kendine ait bir klasör değil +@msg {_1}: not a plain file {_1}: düz bir dosya değil +@msg {dest}: {e} {dest}: {e} +@msg {doc} has no folder {doc} belgesinin klasörü yok +@msg {file} isn't linked {file} bağlantılı değil +@msg {folder} is not a package folder {folder} bir paket klasörü değil +@msg {folder}: more than {max} files and folders {folder}: {max} taneden fazla dosya ve klasör +@msg {folder}: {e} {folder}: {e} +@msg {g} is not a Live Paint group {g} bir Canlı Boyama grubu değil +@msg {id} is not a slice {id} bir dilim değil +@msg {key} must be 0–{MAX_ADD_AROUND} pt {key} 0–{MAX_ADD_AROUND} pt olmalıdır +@msg {key} must be [x,y] {key} [x,y] olmalıdır +@msg {key} must be a percentage {min}..100 {key} {min}..100 aralığında bir yüzde olmalıdır +@msg {key} must be a positive number, not {n} {key} pozitif bir sayı olmalıdır, {n} değil +@msg {key} must be a positive number, not {v} {key} pozitif bir sayı olmalıdır, {v} değil +@msg {key} must be one of {_1} {key} şunlardan biri olmalıdır: {_1} +@msg {key} must be {_1}, got {s} {key} {_1} olmalıdır, verilen: {s} +@msg {key} must name a floating panel {key} yüzen bir paneli belirtmelidir +@msg {key} must name a panel in another group {key} başka bir gruptaki bir paneli belirtmelidir +@msg {key} must name a panel that shows {key} gösterilen bir paneli belirtmelidir +@msg {key} must name a registered panel {key} kayıtlı bir paneli belirtmelidir +@msg {kind} files have no transparency, and the file would have {what}: flatten it first (object.flattenTransparency) {kind} dosyalarında saydamlık yoktur ve dosyada {what} olurdu: önce düzleştirin (object.flattenTransparency) +@msg {kind} images can't be opened (see document.formats) {kind} görüntüleri açılamıyor (bkz. document.formats) +@msg {k} `{v}` is not one of the choices {k} `{v}` seçeneklerden biri değil +@msg {k} has control characters{_1} {k} denetim karakterleri içeriyor{_1} +@msg {k} is too long (at most {MAX_TEXT} characters) {k} çok uzun (en fazla {MAX_TEXT} karakter) +@msg {k} must be > 0 {k} > 0 olmalıdır +@msg {k} must be a number (pt) or a length such as "210 mm" {k} bir sayı (pt) veya "210 mm" gibi bir uzunluk olmalıdır +@msg {k} must be a number from {min} to {max} {k} {min} ile {max} arasında bir sayı olmalıdır +@msg {k} must be a number or "auto" {k} bir sayı veya "auto" olmalıdır +@msg {k} must be a string {k} bir dize olmalıdır +@msg {k} must be text {k} metin olmalıdır +@msg {k} must be true or false {k} true veya false olmalıdır +@msg {k} must be {{size?, position?}} {k} {{size?, position?}} olmalıdır +@msg {k}: can't read `{s}` as a length {k}: `{s}` bir uzunluk olarak okunamıyor +@msg {label} must be a number at most {max} {label} en fazla {max} olan bir sayı olmalıdır +@msg {label} must be a number from -1296 to 1296 {label} -1296 ile 1296 arasında bir sayı olmalıdır +@msg {label} must be a number from 1 to 10000 {label} 1 ile 10000 arasında bir sayı olmalıdır +@msg {name} `{s}`: {ids} {name} `{s}`: {ids} +@msg {name} is built in and can't be deleted {name} yerleşiktir ve silinemez +@msg {name}: CRC or size mismatch {name}: CRC veya boyut uyuşmazlığı +@msg {name}: only this Affinity file's embedded preview could be read; use File › Open to see it with its warning, or export SVG or PDF from Affinity before placing {name}: bu Affinity dosyasının yalnızca gömülü önizlemesi okunabildi; uyarısıyla birlikte görmek için Dosya › Aç komutunu kullanın veya yerleştirmeden önce Affinity'den SVG ya da PDF olarak dışa aktarın +@msg {name}: {e} {name}: {e} +@msg {native}; its embedded preview can't be read either ({e}) {native}; gömülü önizlemesi de okunamıyor ({e}) +@msg {std} files are CMYK, and the file would have colours in {_1} {std} dosyaları CMYK'dir ve dosyada {_1} renkleri olurdu +@msg {std} files embed their fonts, and the file would have one that isn't {std} dosyaları yazı tiplerini gömer ve dosyada gömülmemiş bir yazı tipi olurdu +@msg {target} is the file this document was read from, and reading it left things out ({what}): writing over it would lose them for good. Write another file instead, or pass acknowledgeLoss: true to replace it anyway {target}, bu belgenin okunduğu dosyadır ve okunurken bazı şeyler dışarıda kaldı ({what}): üzerine yazmak bunları kalıcı olarak kaybettirir. Bunun yerine başka bir dosya yazın veya yine de değiştirmek için acknowledgeLoss: true verin +@msg {ty} brushes need selected art (or params.{k}) {ty} fırçaları için seçili resim (veya params.{k}) gerekir +@msg {v} is not an asset id {v} bir varlık kimliği değil +@msg {what} can't be intertwined {what} iç içe geçirilemez +@msg {what} doesn't fit the paper with its bleed and marks {what}, taşma payı ve işaretleriyle birlikte kâğıda sığmıyor +@msg {what} would print on more than {MAX_TILES} tiles: scale it down {what} {MAX_TILES} taneden fazla döşemeye yazdırılırdı: ölçeğini küçültün Playback Options Oynatma Seçenekleri Accelerated Hızlandırılmış Step by Step Adım Adım @@ -6630,7 +8573,7 @@ axis Y Axis Y ekseni @plural Result: {n}|Results: {n} Sonuç: {n} @msg select one object bir nesne seçin @msg Global Edit works on paths, compound paths, symbol instances and groups of them Genel düzenleme yollar, bileşik yollar, sembol örnekleri ve bunların grupları üzerinde çalışır -@msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again benzer nesne bulunamadı (döndürülmüş veya yansıtılmış kopyalar eşleşmez); Genel Düzenleme Seçeneklerini değiştirip yeniden deneyin +@msg no similar objects found (reflected copies are not matched); change the Global Edit Options and try again benzer nesne bulunamadı (yansıtılmış kopyalar eşleşmez); Genel Düzenleme Seçeneklerini değiştirip yeniden deneyin @msg Global Edit is off Genel düzenleme kapalı @msg only an object of the Global Edit other than the one it started from can be left out yalnızca genel düzenlemenin başladığı nesne dışındaki bir nesne düzenlemenin dışında bırakılabilir @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all ya da 1, 3-5 gibi bir aralık olmalı, {v} değil @@ -7423,11 +9366,20 @@ breakText Glyphs Glifler Open Tutorial Sample Öğretici Örneğini Aç Finish Tutorial Öğreticiyi Bitir Next Tutorial Sonraki Öğretici + Show Learn Tab Öğren Sekmesini Göster + Show Skill Beceriyi Göster + Back One Level Bir Düzey Geri Back to Skills Becerilere Dön @msg tutorial `{id}` has no practice sample `{id}` öğreticisinin alıştırma örneği yok @msg open the practice sample of `{id}` first (see learn.openSample) önce `{id}` öğreticisinin alıştırma örneğini açın (bkz. learn.openSample) @msg finish `{id}` first (see learn.finish) önce `{id}` öğreticisini bitirin (bkz. learn.finish) @msg `{id}` is the last tutorial in its skill `{id}`, becerisinin son öğreticisidir + Reset progress İlerlemeyi sıfırla + Mark Tutorial Step Öğretici Adımını İşaretle + Reset Learn Progress Öğrenme İlerlemesini Sıfırla +@msg missing `step` (see learn.show) `step` eksik (bkz. learn.show) +@msg `step` must be a step number from 0 to {last} `step`, 0 ile {last} arasında bir adım numarası olmalıdır +@msg `{id}` is finished (see learn.resetProgress) `{id}` bitirildi (bkz. learn.resetProgress) # Deferred plug-in effects Refresh Deferred Effects Ertelenen Efektleri Yenile @@ -7457,3 +9409,15 @@ breakText Glyphs Glifler Grommets Kuşgözleri Grommet Inset Kuşgözlerinin kenara uzaklığı Diameter Çap +@msg `{key}` must be from 0.01 to 1000 pt `{key}` 0.01 ile 1000 pt arasında olmalıdır +@msg turn on at least one side en az bir kenarı açın +@msg with no hem and no grommets there is nothing to mark kenar kıvırma ve kuşgözü olmadan işaretlenecek bir şey yok +@msg select the banner, or mark every artboard afişi seçin veya her çalışma yüzeyini işaretleyin +@msg there is no banner to mark işaretlenecek afiş yok +@msg the banner has no width or height afişin genişliği veya yüksekliği yok +@msg the hem is too deep for the banner kenar kıvırma afiş için çok derin +@msg the grommet inset is too large for the banner kuşgözlerinin kenara uzaklığı afiş için çok büyük +@msg the spacing makes more than {MAX_GROMMETS} grommets bu aralık {MAX_GROMMETS} taneden fazla kuşgözü oluşturur + Nest Shapes… Şekilleri yerleştir… + Nest Shapes Şekilleri yerleştir + Roll Rulo diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index aa8d0c56f9..cef2ac7f83 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -17,6 +17,7 @@ Smoothness Згладжування Radial Blur… Радіальне розмиття… + Blur Center Центр розмиття Smart Blur… Розумне розмиття… Sharpen Різкість Unsharp Mask… Нерізка маска… @@ -639,6 +640,7 @@ font-technology Variable Варіативні Copy All Styles Копіювати всі стилі Copy Color Value (Hex) Копіювати значення кольору (hex) Copy Fonts Used in the Document Копіювати шрифти, використані у документі + Copy Info Копіювати відомості Copy Links Копіювати зв’язки Copy Selected Style Копіювати вибраний стиль Copy to User Defined Копіювати в «Користувацькі» @@ -906,6 +908,9 @@ font-technology Variable Варіативні The selected character's font is not available. Шрифт виділеного символу недоступний. No alternates for the selected character. Виділений символ не має альтернатив. Double-click to replace Двічі клацніть для заміни + Click to replace Клацніть для заміни + Show all alternates in the Glyphs panel Показати всі альтернативи на панелі «Гліфи» + Show Character Alternates Показувати альтернативи символу Select one character with the Type tool first. Спершу виділіть один символ інструментом «Текст». {glyph} is a glyph of {font}, not of the font the selected text is set in ({text_font}). {glyph} — гліф шрифту {font}, а не шрифту виділеного тексту ({text_font}). {glyph} belongs to {base} (U+{base_code}) {place}; your selection is {sel} (U+{code}). {glyph} належить символу {base} (U+{base_code}) {place}; виділено символ {sel} (U+{code}). @@ -1353,6 +1358,7 @@ file-filter Templates Шаблони Format Формат Format Options Параметри формату Format Settings Параметри формату + Format Settings… Параметри формату… Format: Формат: Formats: Формати: Fractional Widths Дробові ширини @@ -1714,6 +1720,7 @@ file-filter Templates Шаблони Images: Зображення: Import Keyboard Shortcuts… Імпортувати сполучення клавіш… Import PDF Імпортувати PDF + Import PDF pages as links Імпортувати сторінки PDF як зв’язки Import PDF Presets Імпортувати набори PDF Import Perspective Grid Presets Імпортувати набори сітки перспективи Import Print Presets Імпортувати набори друку @@ -3479,6 +3486,18 @@ effect Points Точки Smart Guides (View → Smart Guides) Розумні напрямні (Перегляд → Розумні напрямні) Smart Guides (⌘U) Розумні напрямні (⌘U) Smart Punctuation… Розумна пунктуація… + Smart Punctuation Розумна пунктуація + ff, fi, ffi Ligatures Лігатури ff, fi, ffi + ff, fl, ffl Ligatures Лігатури ff, fl, ffl + Smart Quotes Розумні лапки + Smart Spaces Розумні пробіли + En, Em Dashes Середні й довгі тире + Ellipses Трикрапки + Expert Fractions Експертні дроби + Replace In Замінити в + Selected Text Only Тільки виділений текст + Entire Document Увесь документ + Report Results Звіт про результати Smooth Згладити Corner Кут Relative Відносно @@ -3509,7 +3528,8 @@ effect Points Точки Solid Суцільний Sort by Kind Сортувати за типом Sort by Name Сортувати за назвою - Sort by Status Сортувати за: + Sort by Size Сортувати за розміром + Sort by Status Сортувати за станом Source code on GitHub Вихідний код GitHub Source Sans 3 Source Sans 3 Space After Paragraph Інтервал після абзацу @@ -4410,6 +4430,7 @@ axis Both Обидві @msg there is no script engine named {name} рушія скриптів з назвою {name} немає @msg Running a script Виконується скрипт @msg Copied the script report Звіт про сценарій скопійовано +@msg Copied the link info Відомості про зв’язок скопійовано @msg Corners edits the corners of a path «Кути» редагує кути контуру @msg Couldn't copy to the system clipboard: {e} Не вдалося скопіювати до системного буфера обміну: {e} @msg Couldn't open {name}: {e} Не вдалося відкрити {name}: {e} @@ -6280,7 +6301,7 @@ axis Y Axis Вісь Y @plural Result: {n}|Results: {n} Результат: {n}|Результати: {n}|Результати: {n} @msg select one object виберіть один об’єкт @msg Global Edit works on paths, compound paths, symbol instances and groups of them Глобальне редагування працює з контурами, складеними контурами, екземплярами символів та їхніми групами -@msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again схожих об’єктів не знайдено (повернуті чи віддзеркалені копії не враховуються); змініть параметри глобального редагування та спробуйте ще раз +@msg no similar objects found (reflected copies are not matched); change the Global Edit Options and try again схожих об’єктів не знайдено (віддзеркалені копії не враховуються); змініть параметри глобального редагування та спробуйте ще раз @msg Global Edit is off Глобальне редагування вимкнено @msg only an object of the Global Edit other than the one it started from can be left out виключити з глобального редагування можна лише об’єкт, відмінний від того, з якого воно почалося @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all або діапазон, наприклад 1, 3-5, а не {v} @@ -6998,6 +7019,122 @@ breakText Glyphs Гліфи @msg only an exporter or an importer declares `extensions` `extensions` оголошує лише модуль експорту або імпорту @msg an importer always gets an import's budget: leave `budget` out модуль імпорту завжди отримує бюджет імпорту: не вказуйте `budget` +# Messages of the image encoders, color profiles, swatch exchange files and color books, 3D and Revolve, path operations, DXF import, the script engine and parameter checks. +@msg 3D effects require finite coordinates within 100 million points 3D-ефектам потрібні скінченні координати в межах 100 мільйонів пунктів +@msg 3D effects require one to ten lights 3D-ефектам потрібно від одного до десяти джерел світла +@msg BMP depth {_1}: 1, 4, 8, 16, 24 or 32 bits per pixel Глибина BMP {_1}: 1, 4, 8, 16, 24 або 32 біти на піксель +@msg BMP encoding failed: {width} × {height} pixels doesn't fit the format or the pixel buffer Не вдалося закодувати BMP: {width} × {height} пікселів не вміщується у формат або не відповідає буферу пікселів +@msg GIF encoding failed: the palette image is malformed Не вдалося закодувати GIF: зображення з палітрою має неправильну структуру +@msg GIF encoding failed: {e} Не вдалося закодувати GIF: {e} +@msg JPEG colour profile: {e} Профіль кольору JPEG: {e} +@msg JPEG encoding failed: pixel buffer doesn't match the image size Не вдалося закодувати JPEG: буфер пікселів не відповідає розміру зображення +@msg JPEG encoding failed: {e} Не вдалося закодувати JPEG: {e} +@msg PNG encoding failed: pixel buffer doesn't match the image size Не вдалося закодувати PNG: буфер пікселів не відповідає розміру зображення +@msg PNG encoding failed: the palette image is malformed Не вдалося закодувати PNG: зображення з палітрою має неправильну структуру +@msg PNG encoding failed: {e} Не вдалося закодувати PNG: {e} +@msg PNG encoding failed: {width} × {height} pixels is not a valid image size Не вдалося закодувати PNG: {width} × {height} пікселів не є допустимим розміром зображення +@msg PSD colour profile: {e} Профіль кольору PSD: {e} +@msg PSD encoding failed: the pixel buffer doesn't match the image size Не вдалося закодувати PSD: буфер пікселів не відповідає розміру зображення +@msg Revolve profile contains invalid coordinates Обертання: профіль містить неприпустимі координати +@msg Revolve profile is too complex Обертання: профіль надто складний +@msg Revolve projection is not finite Обертання: проєкція не скінченна +@msg Revolve requires finite profile coordinates within 100 million points Обертання: потрібні скінченні координати профілю в межах 100 мільйонів пунктів +@msg Revolve surface is too complex; reduce Segments or simplify the profile Обертання: поверхня надто складна; зменште «Сегменти» або спростіть профіль +@msg Revolve surface is too complex; simplify the profile Обертання: поверхня надто складна; спростіть профіль +@msg Revolve visibility cannot split the projected boundary Обертання: обчислення видимості не може розділити спроєктовану межу +@msg Revolve visibility creates too many fragments Обертання: обчислення видимості створює забагато фрагментів +@msg Revolve visibility creates too many vector anchors Обертання: обчислення видимості створює забагато векторних опорних точок +@msg Revolve visibility exceeds its geometry work limit Обертання: обчислення видимості перевищує межу геометричних обчислень +@msg Revolve visibility exceeds its spatial index limit Обертання: обчислення видимості перевищує межу просторового індексу +@msg Revolve visibility has too many boundary crossings Обертання: обчислення видимості має забагато перетинів меж +@msg Revolve visibility has too many input anchors Обертання: обчислення видимості має забагато вхідних опорних точок +@msg Revolve visibility requires convex cap sectors Обертання: обчисленню видимості потрібні опуклі сектори кришки +@msg Revolve visibility requires finite projected faces Обертання: обчисленню видимості потрібні скінченні спроєктовані грані +@msg SVG options: {e} Параметри SVG: {e} +@msg Save for Web settings: {e} Параметри «Зберегти для Інтернету»: {e} +@msg TIFF colour profile: {e} Профіль кольору TIFF: {e} +@msg TIFF encoding failed: the pixel buffer doesn't match the image size Не вдалося закодувати TIFF: буфер пікселів не відповідає розміру зображення +@msg TIFF encoding failed: {e} Не вдалося закодувати TIFF: {e} +@msg Targa depth {_1}: 16, 24 or 32 bits per pixel Глибина Targa {_1}: 16, 24 або 32 біти на піксель +@msg Targa encoding failed: the pixel buffer doesn't match the image size Не вдалося закодувати Targa: буфер пікселів не відповідає розміру зображення +@msg The 3D projection is not finite 3D-проєкція не скінченна +@msg The 3D shadow is too complex; turn Shadows off or simplify the art 3D-тінь надто складна; вимкніть «Тіні» або спростіть ілюстрацію +@msg The shape contains invalid coordinates Фігура містить неприпустимі координати +@msg Too many Revolve faces for visibility evaluation Забагато граней обертання для обчислення видимості +@msg VectorCraft reads at most {ASE_MAX_ENTRIES} colors and groups from a swatch exchange file, and this library has {entries} VectorCraft читає з файлу обміну зразками не більше {ASE_MAX_ENTRIES} кольорів і груп, а в цій бібліотеці їх {entries} +@msg WebP encoding failed: {e} Не вдалося закодувати WebP: {e} +@msg [{j}] `{_1}`: {why} [{j}] `{_1}`: {why} +@msg `answers[{i}]` {e} `answers[{i}]` {e} +@msg `view` is smallThumb, mediumThumb, largeThumb, smallList or largeList `view` має бути smallThumb, mediumThumb, largeThumb, smallList або largeList +@msg a line can't run from a point to itself лінія не може йти з точки в ту саму точку +@msg a line needs at least two points лінії потрібні щонайменше дві точки +@msg a number cannot be read не вдалося прочитати число +@msg a swatch exchange block is too long блок файлу обміну зразками задовгий +@msg a swatch exchange name is too long назва у файлі обміну зразками задовга +@msg a {sw} × {sh} image can't be resized to {width} × {height} pixels розмір зображення {sw} × {sh} не можна змінити на {width} × {height} пікселів +@msg a {width} × {height} image is too large зображення {width} × {height} завелике +@msg a {width} × {height} image: {e} зображення {width} × {height}: {e} +@msg an image could not be written: {e} не вдалося записати зображення: {e} +@msg an image that couldn't be read was left out зображення, яке не вдалося прочитати, пропущено +@msg can't open “{name}”: {e} не вдалося відкрити «{name}»: {e} +@msg cannot align zip entries to {align} bytes не вдається вирівняти записи архіву zip до {align} байтів +@msg cannot open the automation {kind} root `{_1}`: {e} не вдається відкрити кореневу папку автоматизації ({kind}) `{_1}`: {e} +@msg cannot read profile: {0} не вдалося прочитати профіль: {0} +@msg color book version {version} isn't supported (only 1) версія книги кольорів {version} не підтримується (лише 1) +@msg color books in color space {other} aren't supported (only RGB, CMYK and Lab) книги кольорів у колірному просторі {other} не підтримуються (лише RGB, CMYK і Lab) +@msg file name too long to zip: {_1} назва файлу задовга для архіву zip: {_1} +@msg file name too long to zip: {name} назва файлу задовга для архіву zip: {name} +@msg freeform line {i}: {e} довільна лінія {i}: {e} +@msg freeform point {i}: {e} довільна точка {i}: {e} +@msg give `{key}` or `{other}`, not both укажіть `{key}` або `{other}`, але не обидва +@msg grayscale profiles can't be working spaces yet профілі відтінків сірого поки що не можуть бути робочими просторами +@msg input contains NaN or infinite coordinates вхідні дані містять координати NaN або нескінченні координати +@msg input path could not be closed не вдалося замкнути вхідний контур +@msg invalid ICC profile: {0} неприпустимий профіль ICC: {0} +@msg invalid scale {scale} неприпустимий масштаб {scale} +@msg its localized names take more than {_1} KB його локалізовані назви займають понад {_1} КБ +@msg its objects are nested too deep ({e}) його об’єкти мають завелику вкладеність ({e}) +@msg its tag table lists the `{_1}` tag more than once його таблиця тегів містить тег `{_1}` більше одного разу +@msg not a graphic style library: {e} це не бібліотека графічних стилів: {e} +@msg not a swatch library (.vcswatches or .gpl) це не бібліотека зразків (.vcswatches або .gpl) +@msg not a swatch library (format `{_1}`) це не бібліотека зразків (формат `{_1}`) +@msg not a swatch library: {e} це не бібліотека зразків: {e} +@msg not an action set file ({e}) це не файл набору дій ({e}) +@msg profile colour space {other} is not RGB, CMYK or Gray колірний простір профілю {other} не є RGB, CMYK чи Gray +@msg regular expression too large регулярний вираз завеликий +@msg script file is not UTF-8 text: {value} файл скрипта не є текстом UTF-8: {value} +@msg stop {i}: {e} точка переходу {i}: {e} +@msg swatch exchange version {major}.{minor} isn't supported (only 1.x) версія файлу обміну зразками {major}.{minor} не підтримується (лише 1.x) +@msg the color book holds more than {ASE_MAX_ENTRIES} colors книга кольорів містить понад {ASE_MAX_ENTRIES} кольорів +@msg the color book is cut short книгу кольорів обрізано +@msg the color book's names take more than {_1} MB назви книги кольорів займають понад {_1} МБ +@msg the image would be {w} × {h} pixels; raster exports are limited to {MAX_RASTER_SIDE} pixels per side and {_1} megapixels: lower the scale or resolution зображення мало б розмір {w} × {h} пікселів; растровий експорт обмежено {MAX_RASTER_SIDE} пікселями на сторону та {_1} мегапікселями: зменште масштаб або роздільну здатність +@msg the optimised image can't be read back: {e} оптимізоване зображення не вдається прочитати знову: {e} +@msg the pixel buffer doesn't match the image size буфер пікселів не відповідає розміру зображення +@msg the preview: {e} попередній перегляд: {e} +@msg the request may not read the New Document profiles folder запит не має права читати папку профілів нового документа +@msg the shapes are too degenerate to combine фігури занадто вироджені для об’єднання +@msg the shapes cross themselves and each other too often to combine фігури надто часто перетинають самі себе й одна одну, щоб їх можна було об’єднати +@msg the swatch exchange file holds more than {ASE_MAX_ENTRIES} colors and groups файл обміну зразками містить понад {ASE_MAX_ENTRIES} кольорів і груп +@msg the swatch exchange file is cut short файл обміну зразками обрізано +@msg the {_1} plate can't be read: {e} не вдалося прочитати форму {_1}: {e} +@msg this binary DXF file is damaged or cut short цей двійковий файл DXF пошкоджено або обрізано +@msg this is a DWG drawing, which can't be read: save it from the CAD app as a DXF and open that це креслення DWG, яке неможливо прочитати: збережіть його з CAD як DXF і відкрийте його +@msg too many classes забагато класів +@msg too many groups забагато груп +@msg too many layers for PSD (at most 32767) забагато шарів для PSD (не більше 32767) +@msg too many swatch exchange blocks забагато блоків обміну зразками +@msg unknown colour profile: {0} невідомий профіль кольору: {0} +@msg {_1} clashes with a built-in profile name {_1} збігається з назвою вбудованого профілю +@msg {_1} × {_2} pixels is too large for GIF (at most 65535 pixels a side): lower the resolution розмір {_1} × {_2} пікселів завеликий для GIF (не більше 65535 пікселів на сторону): зменште роздільну здатність +@msg {_1}: no usable transform to/from sRGB {_1}: немає придатного перетворення в sRGB або з sRGB +@msg {name} is not a CMYK profile {name} не є профілем CMYK +@msg {name} is not an RGB profile {name} не є профілем RGB +@msg {path}: could not be read {path}: не вдалося прочитати +@msg {width} × {height} pixels is too large for JPEG (at most 65535 pixels a side): lower the resolution розмір {width} × {height} пікселів завеликий для JPEG (не більше 65535 пікселів на сторону): зменште роздільну здатність +@msg {width} × {height} pixels is too large for Targa (at most 65535 pixels a side): lower the resolution розмір {width} × {height} пікселів завеликий для Targa (не більше 65535 пікселів на сторону): зменште роздільну здатність +@msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution розмір {w} × {h} пікселів завеликий для PSD (не більше {MAX_SIDE} пікселів на сторону): зменште роздільну здатність + # Copy Troubleshooting Info Copy Troubleshooting Info Копіювати відомості для усунення несправностей @msg Copied the troubleshooting info Відомості для усунення несправностей скопійовано @@ -7077,11 +7214,20 @@ breakText Glyphs Гліфи Open Tutorial Sample Відкрити приклад уроку Finish Tutorial Завершити урок Next Tutorial Наступний урок + Show Learn Tab Показати вкладку панелі «Навчання» + Show Skill Показати навичку + Back One Level На рівень назад Back to Skills Назад до навичок @msg tutorial `{id}` has no practice sample урок `{id}` не має навчального прикладу @msg open the practice sample of `{id}` first (see learn.openSample) спочатку відкрийте навчальний приклад уроку `{id}` (див. learn.openSample) @msg finish `{id}` first (see learn.finish) спочатку завершіть `{id}` (див. learn.finish) @msg `{id}` is the last tutorial in its skill `{id}` є останнім уроком своєї навички + Reset progress Скинути прогрес + Mark Tutorial Step Позначити крок уроку + Reset Learn Progress Скинути прогрес навчання +@msg missing `step` (see learn.show) відсутній `step` (див. learn.show) +@msg `step` must be a step number from 0 to {last} `step` має бути номером кроку від 0 до {last} +@msg `{id}` is finished (see learn.resetProgress) урок `{id}` завершено (див. learn.resetProgress) # Deferred plug-in effects Refresh Deferred Effects Оновити відкладені ефекти @@ -8484,6 +8630,8 @@ breakText Glyphs Гліфи @msg the RTF file is too large to place as type (at most {_1} MB) файл RTF завеликий, щоб помістити його як текст (не більше {_1} МБ) @msg the SVG expands to more than {0} nested SVG images SVG розгортається у понад {0} вкладених зображень SVG @msg the SVG expands to more than {0} objects SVG розгортається у понад {0} об’єктів +@msg the SVG's style sheets take too long to match зіставлення таблиць стилів SVG триває надто довго +@msg the SVG's styles expand to more than {0} MB стилі SVG розгортаються у понад {0} МБ @msg the SVG file is larger than {MAX_IMPORT_BYTES} bytes файл SVG більший за {MAX_IMPORT_BYTES} байтів @msg the SVG has no drawable objects SVG не містить об’єктів, які можна намалювати @msg the SVGZ file unpacks to more than {_1} MB файл SVGZ розпаковується у понад {_1} МБ @@ -8922,3 +9070,6 @@ breakText Glyphs Гліфи @msg turn on at least one side увімкніть принаймні одну сторону @msg with no hem and no grommets there is nothing to mark без підгину й люверсів немає чого розмічати @msg {saving} failed: {e} {saving}: не вдалося: {e} + Nest Shapes… Розкладка фігур… + Nest Shapes Розкладка фігур + Roll Рулон diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 7b7480cbfd..70540a0974 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -739,6 +739,7 @@ font-technology Variable Biến thiên Copy Color Value (Hex) Sao chép giá trị màu (Hex) Copy Fonts Used in the Document Sao chép phông đã dùng trong tài liệu Copy into the document's folder Sao chép vào thư mục tài liệu + Copy Info Sao chép thông tin Copy Links Sao chép liên kết Copy only fonts you own or are licensed to install. Chỉ sao chép phông chữ bạn sở hữu hoặc có giấy phép cài đặt. Copy Selected Style Sao chép kiểu đã chọn @@ -1065,6 +1066,9 @@ font-technology Variable Biến thiên The selected character's font is not available. Phông chữ của ký tự đã chọn không khả dụng. No alternates for the selected character. Ký tự đã chọn không có glyph thay thế. Double-click to replace Bấm đúp để thay thế + Click to replace Bấm để thay thế + Show all alternates in the Glyphs panel Hiện tất cả glyph thay thế trong bảng Glyph + Show Character Alternates Hiện glyph thay thế của ký tự Select one character with the Type tool first. Trước hết hãy chọn một ký tự bằng công cụ Chữ. {glyph} is a glyph of {font}, not of the font the selected text is set in ({text_font}). {glyph} là glyph của {font}, không phải của phông chữ mà văn bản đã chọn đang dùng ({text_font}). {glyph} belongs to {base} (U+{base_code}) {place}; your selection is {sel} (U+{code}). {glyph} thuộc về {base} (U+{base_code}) {place}; ký tự bạn chọn là {sel} (U+{code}). @@ -1573,6 +1577,7 @@ file-filter Templates Mẫu Format Định dạng Format Options Tùy chọn định dạng Format Settings Cài đặt định dạng + Format Settings… Cài đặt định dạng… Format: Định dạng: Formats: Các định dạng: Fractional Widths Chiều rộng phân số @@ -1955,6 +1960,7 @@ digits Hindi Hindi Import Library Nhập thư viện Import Library… Nhập thư viện… Import PDF Nhập PDF + Import PDF pages as links Nhập các trang PDF dưới dạng liên kết Import PDF Presets Nhập thiết lập sẵn PDF Import Perspective Grid Presets Nhập thiết lập sẵn lưới phối cảnh Import Print Presets Nhập thiết lập sẵn in @@ -3042,6 +3048,7 @@ mark-style Japanese Kiểu Nhật Radial Hướng tâm Radial Blur Mờ hướng tâm Radial Blur… Mờ hướng tâm… + Blur Center Tâm làm mờ Radial Dividers: Đường chia hướng tâm: Radial Glows Ánh sáng hướng tâm Organic Fades Mờ dần tự nhiên @@ -3835,6 +3842,18 @@ mark-style Japanese Kiểu Nhật Smart Guides (View → Smart Guides) Đường căn thông minh (Hiển thị → Đường căn thông minh) Smart Guides (⌘U) Đường căn thông minh (⌘U) Smart Punctuation… Dấu câu thông minh… + Smart Punctuation Dấu câu thông minh + ff, fi, ffi Ligatures Chữ ghép ff, fi, ffi + ff, fl, ffl Ligatures Chữ ghép ff, fl, ffl + Smart Quotes Dấu ngoặc kép thông minh + Smart Spaces Khoảng trắng thông minh + En, Em Dashes Gạch ngang ngắn và dài + Ellipses Dấu chấm lửng + Expert Fractions Phân số chuyên dụng + Replace In Thay thế trong + Selected Text Only Chỉ văn bản đã chọn + Entire Document Toàn bộ tài liệu + Report Results Báo cáo kết quả Smooth Mượt Smooth Color Màu mượt Smooth Tool Công cụ Làm mượt @@ -3857,6 +3876,7 @@ mark-style Japanese Kiểu Nhật Sort Sắp xếp Sort by Kind Sắp xếp theo loại Sort by Name Sắp xếp theo tên + Sort by Size Sắp xếp theo kích thước Sort by Status Sắp xếp theo trạng thái Source code on GitHub Mã nguồn trên GitHub Source Image Ảnh nguồn @@ -4840,6 +4860,7 @@ theme Appearance Giao diện @msg there is no script engine named {name} không có bộ máy tập lệnh nào tên {name} @msg Running a script Đang chạy tập lệnh @msg Copied the script report Đã sao chép báo cáo script +@msg Copied the link info Đã sao chép thông tin liên kết @msg Corners edits the corners of a path Corners chỉnh sửa các góc của đường dẫn @msg could not decode image: {0} không thể giải mã ảnh: {0} @msg Couldn't copy to the system clipboard: {e} Không thể sao chép vào khay nhớ tạm hệ thống: {e} @@ -5257,6 +5278,8 @@ theme Appearance Giao diện @msg result would exceed the canvas (coordinates out of range) kết quả sẽ vượt quá vùng vẽ (tọa độ ngoài phạm vi) @msg objects can't be nested more than 32 deep không thể lồng các đối tượng sâu quá 32 cấp @msg the SVG's elements are nested more than {0} deep các phần tử SVG lồng nhau sâu quá {0} cấp +@msg the SVG's style sheets take too long to match việc so khớp các biểu định kiểu của SVG mất quá nhiều thời gian +@msg the SVG's styles expand to more than {0} MB các kiểu của SVG khi mở rộng chiếm hơn {0} MB @msg Save for Web: the image is empty Lưu cho Web: ảnh trống @msg Save writes {_1}, not {_2}: use document.export for other formats Lưu ghi {_1}, không phải {_2}: dùng document.export cho các định dạng khác @msg Save writes {_1}, not {_2}: use file.saveAsTemplate to write it Lưu ghi {_1}, không phải {_2}: dùng file.saveAsTemplate để ghi định dạng này @@ -6281,7 +6304,7 @@ axis Y Axis Trục Y @plural Result: {n}|Results: {n} Kết quả: {n} @msg select one object hãy chọn một đối tượng @msg Global Edit works on paths, compound paths, symbol instances and groups of them Chỉnh sửa toàn cục hoạt động trên đường dẫn, đường dẫn phức hợp, phiên bản biểu tượng và nhóm của chúng -@msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again không tìm thấy đối tượng tương tự (các bản sao đã xoay hoặc lật không được tính); hãy thay đổi tùy chọn chỉnh sửa toàn cục rồi thử lại +@msg no similar objects found (reflected copies are not matched); change the Global Edit Options and try again không tìm thấy đối tượng tương tự (các bản sao đã lật không được tính); hãy thay đổi tùy chọn chỉnh sửa toàn cục rồi thử lại @msg Global Edit is off Chỉnh sửa toàn cục đang tắt @msg only an object of the Global Edit other than the one it started from can be left out chỉ có thể loại khỏi chỉnh sửa toàn cục một đối tượng khác với đối tượng mà nó bắt đầu @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all hoặc một phạm vi như 1, 3-5, không phải {v} @@ -7078,11 +7101,20 @@ breakText Glyphs Glyph Open Tutorial Sample Mở tệp mẫu của hướng dẫn Finish Tutorial Hoàn tất hướng dẫn Next Tutorial Hướng dẫn tiếp theo + Show Learn Tab Hiện thẻ của Học + Show Skill Hiện kỹ năng + Back One Level Quay lại một cấp Back to Skills Quay lại kỹ năng @msg tutorial `{id}` has no practice sample hướng dẫn `{id}` không có tệp mẫu thực hành @msg open the practice sample of `{id}` first (see learn.openSample) hãy mở tệp mẫu thực hành của `{id}` trước (xem learn.openSample) @msg finish `{id}` first (see learn.finish) hãy hoàn tất `{id}` trước (xem learn.finish) @msg `{id}` is the last tutorial in its skill `{id}` là hướng dẫn cuối cùng trong kỹ năng của nó + Reset progress Đặt lại tiến độ + Mark Tutorial Step Đánh dấu bước hướng dẫn + Reset Learn Progress Đặt lại tiến độ học +@msg missing `step` (see learn.show) thiếu `step` (xem learn.show) +@msg `step` must be a step number from 0 to {last} `step` phải là số bước từ 0 đến {last} +@msg `{id}` is finished (see learn.resetProgress) `{id}` đã hoàn tất (xem learn.resetProgress) # Deferred plug-in effects Refresh Deferred Effects Làm mới hiệu ứng bị hoãn @@ -7112,3 +7144,123 @@ breakText Glyphs Glyph Grommets Khoen Grommet Inset Khoảng cách từ mép đến khoen Diameter Đường kính + Nest Shapes… Xếp hình tiết kiệm vật liệu… + Nest Shapes Xếp hình tiết kiệm vật liệu + Roll Cuộn + +# Messages of the effects, 3D, image export, color profiles, swatch exchange files, color books and DXF import. +@msg 3D effects require finite coordinates within 100 million points Hiệu ứng 3D yêu cầu tọa độ hữu hạn trong phạm vi 100 triệu điểm +@msg 3D effects require one to ten lights Hiệu ứng 3D yêu cầu từ một đến mười nguồn sáng +@msg BMP depth {_1}: 1, 4, 8, 16, 24 or 32 bits per pixel Độ sâu BMP {_1}: chỉ hỗ trợ 1, 4, 8, 16, 24 hoặc 32 bit mỗi điểm ảnh +@msg BMP encoding failed: {width} × {height} pixels doesn't fit the format or the pixel buffer Mã hóa BMP thất bại: {width} × {height} điểm ảnh không vừa với định dạng hoặc bộ đệm điểm ảnh +@msg GIF encoding failed: the palette image is malformed Mã hóa GIF thất bại: ảnh bảng màu bị sai định dạng +@msg GIF encoding failed: {e} Mã hóa GIF thất bại: {e} +@msg JPEG colour profile: {e} Hồ sơ màu JPEG: {e} +@msg JPEG encoding failed: pixel buffer doesn't match the image size Mã hóa JPEG thất bại: bộ đệm điểm ảnh không khớp với kích thước ảnh +@msg JPEG encoding failed: {e} Mã hóa JPEG thất bại: {e} +@msg PNG encoding failed: pixel buffer doesn't match the image size Mã hóa PNG thất bại: bộ đệm điểm ảnh không khớp với kích thước ảnh +@msg PNG encoding failed: the palette image is malformed Mã hóa PNG thất bại: ảnh bảng màu bị sai định dạng +@msg PNG encoding failed: {e} Mã hóa PNG thất bại: {e} +@msg PNG encoding failed: {width} × {height} pixels is not a valid image size Mã hóa PNG thất bại: {width} × {height} điểm ảnh không phải là kích thước ảnh hợp lệ +@msg PSD colour profile: {e} Hồ sơ màu PSD: {e} +@msg PSD encoding failed: the pixel buffer doesn't match the image size Mã hóa PSD thất bại: bộ đệm điểm ảnh không khớp với kích thước ảnh +@msg Revolve profile contains invalid coordinates Biên dạng Xoay tròn chứa tọa độ không hợp lệ +@msg Revolve profile is too complex Biên dạng Xoay tròn quá phức tạp +@msg Revolve projection is not finite Phép chiếu của Xoay tròn không hữu hạn +@msg Revolve requires finite profile coordinates within 100 million points Xoay tròn yêu cầu tọa độ biên dạng hữu hạn trong phạm vi 100 triệu điểm +@msg Revolve surface is too complex; reduce Segments or simplify the profile Bề mặt Xoay tròn quá phức tạp; hãy giảm Đoạn hoặc đơn giản hóa biên dạng +@msg Revolve surface is too complex; simplify the profile Bề mặt Xoay tròn quá phức tạp; hãy đơn giản hóa biên dạng +@msg Revolve visibility cannot split the projected boundary Tính toán phần nhìn thấy của Xoay tròn không thể tách đường biên đã chiếu +@msg Revolve visibility creates too many fragments Tính toán phần nhìn thấy của Xoay tròn tạo ra quá nhiều mảnh +@msg Revolve visibility creates too many vector anchors Tính toán phần nhìn thấy của Xoay tròn tạo ra quá nhiều điểm neo vectơ +@msg Revolve visibility exceeds its geometry work limit Tính toán phần nhìn thấy của Xoay tròn vượt quá giới hạn khối lượng tính toán hình học +@msg Revolve visibility exceeds its spatial index limit Tính toán phần nhìn thấy của Xoay tròn vượt quá giới hạn chỉ mục không gian +@msg Revolve visibility has too many boundary crossings Tính toán phần nhìn thấy của Xoay tròn có quá nhiều điểm cắt đường biên +@msg Revolve visibility has too many input anchors Tính toán phần nhìn thấy của Xoay tròn có quá nhiều điểm neo đầu vào +@msg Revolve visibility requires convex cap sectors Tính toán phần nhìn thấy của Xoay tròn yêu cầu các hình quạt nắp lồi +@msg Revolve visibility requires finite projected faces Tính toán phần nhìn thấy của Xoay tròn yêu cầu các mặt chiếu hữu hạn +@msg SVG options: {e} Tùy chọn SVG: {e} +@msg Save for Web settings: {e} Cài đặt Lưu cho Web: {e} +@msg TIFF colour profile: {e} Hồ sơ màu TIFF: {e} +@msg TIFF encoding failed: the pixel buffer doesn't match the image size Mã hóa TIFF thất bại: bộ đệm điểm ảnh không khớp với kích thước ảnh +@msg TIFF encoding failed: {e} Mã hóa TIFF thất bại: {e} +@msg Targa depth {_1}: 16, 24 or 32 bits per pixel Độ sâu Targa {_1}: chỉ hỗ trợ 16, 24 hoặc 32 bit mỗi điểm ảnh +@msg Targa encoding failed: the pixel buffer doesn't match the image size Mã hóa Targa thất bại: bộ đệm điểm ảnh không khớp với kích thước ảnh +@msg The 3D projection is not finite Phép chiếu 3D không hữu hạn +@msg The 3D shadow is too complex; turn Shadows off or simplify the art Bóng đổ 3D quá phức tạp; hãy tắt Bóng đổ hoặc đơn giản hóa hình vẽ +@msg The shape contains invalid coordinates Hình dạng chứa tọa độ không hợp lệ +@msg Too many Revolve faces for visibility evaluation Quá nhiều mặt Xoay tròn để tính toán phần nhìn thấy +@msg VectorCraft reads at most {ASE_MAX_ENTRIES} colors and groups from a swatch exchange file, and this library has {entries} VectorCraft đọc tối đa {ASE_MAX_ENTRIES} màu và nhóm từ một tệp trao đổi mẫu màu, còn thư viện này có {entries} +@msg WebP encoding failed: {e} Mã hóa WebP thất bại: {e} +@msg [{j}] `{_1}`: {why} [{j}] `{_1}`: {why} +@msg `answers[{i}]` {e} `answers[{i}]` {e} +@msg `index` must be a whole number `index` phải là số nguyên +@msg `view` is smallThumb, mediumThumb, largeThumb, smallList or largeList `view` phải là smallThumb, mediumThumb, largeThumb, smallList hoặc largeList +@msg a line can't run from a point to itself một đường không thể đi từ một điểm đến chính nó +@msg a line needs at least two points một đường cần ít nhất hai điểm +@msg a number cannot be read không thể đọc một số +@msg a swatch exchange block is too long một khối trong tệp trao đổi mẫu màu quá dài +@msg a swatch exchange name is too long một tên trong tệp trao đổi mẫu màu quá dài +@msg a {sw} × {sh} image can't be resized to {width} × {height} pixels không thể đổi kích thước ảnh {sw} × {sh} thành {width} × {height} điểm ảnh +@msg a {width} × {height} image is too large ảnh {width} × {height} quá lớn +@msg a {width} × {height} image: {e} ảnh {width} × {height}: {e} +@msg an image could not be written: {e} không thể ghi một ảnh: {e} +@msg an image that couldn't be read was left out một ảnh không đọc được đã bị bỏ qua +@msg can't open “{name}”: {e} không thể mở “{name}”: {e} +@msg cannot align zip entries to {align} bytes không thể căn các mục zip theo {align} byte +@msg cannot open the automation {kind} root `{_1}`: {e} không thể mở thư mục gốc {kind} tự động `{_1}`: {e} +@msg cannot read profile: {0} không thể đọc hồ sơ màu: {0} +@msg color book version {version} isn't supported (only 1) không hỗ trợ sổ màu phiên bản {version} (chỉ 1) +@msg color books in color space {other} aren't supported (only RGB, CMYK and Lab) không hỗ trợ sổ màu trong không gian màu {other} (chỉ RGB, CMYK và Lab) +@msg file name too long to zip: {_1} tên tệp quá dài để nén zip: {_1} +@msg file name too long to zip: {name} tên tệp quá dài để nén zip: {name} +@msg freeform line {i}: {e} đường tự do {i}: {e} +@msg freeform point {i}: {e} điểm tự do {i}: {e} +@msg give `{key}` or `{other}`, not both hãy cung cấp `{key}` hoặc `{other}`, không phải cả hai +@msg grayscale profiles can't be working spaces yet hồ sơ màu thang xám chưa thể dùng làm không gian làm việc +@msg input contains NaN or infinite coordinates đầu vào chứa tọa độ NaN hoặc vô hạn +@msg input path could not be closed không thể đóng đường dẫn đầu vào +@msg invalid ICC profile: {0} hồ sơ ICC không hợp lệ: {0} +@msg invalid scale {scale} tỷ lệ không hợp lệ {scale} +@msg its localized names take more than {_1} KB các tên bản địa hóa của nó chiếm hơn {_1} KB +@msg its objects are nested too deep ({e}) các đối tượng của nó lồng nhau quá sâu ({e}) +@msg its tag table lists the `{_1}` tag more than once bảng thẻ của nó liệt kê thẻ `{_1}` nhiều hơn một lần +@msg not a graphic style library: {e} không phải thư viện kiểu đồ họa: {e} +@msg not a swatch library (.vcswatches or .gpl) không phải thư viện mẫu màu (.vcswatches hoặc .gpl) +@msg not a swatch library (format `{_1}`) không phải thư viện mẫu màu (định dạng `{_1}`) +@msg not a swatch library: {e} không phải thư viện mẫu màu: {e} +@msg not an action set file ({e}) không phải tệp bộ hành động ({e}) +@msg profile colour space {other} is not RGB, CMYK or Gray không gian màu {other} của hồ sơ không phải RGB, CMYK hoặc Gray +@msg regular expression too large biểu thức chính quy quá lớn +@msg script file is not UTF-8 text: {value} tệp tập lệnh không phải văn bản UTF-8: {value} +@msg stop {i}: {e} điểm dừng {i}: {e} +@msg swatch exchange version {major}.{minor} isn't supported (only 1.x) không hỗ trợ tệp trao đổi mẫu màu phiên bản {major}.{minor} (chỉ 1.x) +@msg the color book holds more than {ASE_MAX_ENTRIES} colors sổ màu chứa hơn {ASE_MAX_ENTRIES} màu +@msg the color book is cut short sổ màu bị cắt ngắn +@msg the color book's names take more than {_1} MB các tên trong sổ màu chiếm hơn {_1} MB +@msg the image would be {w} × {h} pixels; raster exports are limited to {MAX_RASTER_SIDE} pixels per side and {_1} megapixels: lower the scale or resolution ảnh sẽ có kích thước {w} × {h} điểm ảnh; xuất raster bị giới hạn ở {MAX_RASTER_SIDE} điểm ảnh mỗi cạnh và {_1} megapixel: hãy giảm tỷ lệ hoặc độ phân giải +@msg the optimised image can't be read back: {e} không thể đọc lại ảnh đã tối ưu hóa: {e} +@msg the pixel buffer doesn't match the image size bộ đệm điểm ảnh không khớp với kích thước ảnh +@msg the preview: {e} bản xem trước: {e} +@msg the request may not read the New Document profiles folder yêu cầu không được phép đọc thư mục hồ sơ Tài liệu mới +@msg the shapes are too degenerate to combine các hình dạng quá suy biến để kết hợp +@msg the shapes cross themselves and each other too often to combine các hình dạng tự cắt và cắt nhau quá nhiều lần để kết hợp +@msg the swatch exchange file holds more than {ASE_MAX_ENTRIES} colors and groups tệp trao đổi mẫu màu chứa hơn {ASE_MAX_ENTRIES} màu và nhóm +@msg the swatch exchange file is cut short tệp trao đổi mẫu màu bị cắt ngắn +@msg the {_1} plate can't be read: {e} không thể đọc bản in {_1}: {e} +@msg this binary DXF file is damaged or cut short tệp DXF nhị phân này bị hỏng hoặc bị cắt ngắn +@msg this is a DWG drawing, which can't be read: save it from the CAD app as a DXF and open that đây là bản vẽ DWG, không thể đọc được: hãy lưu nó dưới dạng DXF từ ứng dụng CAD rồi mở tệp đó +@msg too many classes quá nhiều lớp ký tự +@msg too many groups quá nhiều nhóm +@msg too many layers for PSD (at most 32767) quá nhiều lớp cho PSD (tối đa 32767) +@msg too many swatch exchange blocks quá nhiều khối trong tệp trao đổi mẫu màu +@msg unknown colour profile: {0} hồ sơ màu không xác định: {0} +@msg {_1} clashes with a built-in profile name {_1} trùng với tên hồ sơ màu có sẵn +@msg {_1} × {_2} pixels is too large for GIF (at most 65535 pixels a side): lower the resolution {_1} × {_2} điểm ảnh quá lớn cho GIF (tối đa 65535 điểm ảnh mỗi cạnh): hãy giảm độ phân giải +@msg {_1}: no usable transform to/from sRGB {_1}: không có phép chuyển đổi dùng được sang/từ sRGB +@msg {name} is not a CMYK profile {name} không phải hồ sơ màu CMYK +@msg {name} is not an RGB profile {name} không phải hồ sơ màu RGB +@msg {path}: could not be read {path}: không thể đọc +@msg {width} × {height} pixels is too large for JPEG (at most 65535 pixels a side): lower the resolution {width} × {height} điểm ảnh quá lớn cho JPEG (tối đa 65535 điểm ảnh mỗi cạnh): hãy giảm độ phân giải +@msg {width} × {height} pixels is too large for Targa (at most 65535 pixels a side): lower the resolution {width} × {height} điểm ảnh quá lớn cho Targa (tối đa 65535 điểm ảnh mỗi cạnh): hãy giảm độ phân giải +@msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} điểm ảnh quá lớn cho PSD (tối đa {MAX_SIDE} điểm ảnh mỗi cạnh): hãy giảm độ phân giải diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index e1ec9f659c..0f15c8f948 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -591,6 +591,7 @@ antiAlias Sharp 锐利 Copy All Styles 复制所有样式 Copy Color Value (Hex) 复制颜色值 (十六进制) Copy Fonts Used in the Document 复制文档中使用的字体 + Copy Info 复制信息 Copy Links 复制链接 Copy Selected Style 复制所选样式 Copy to User Defined 复制到用户定义 @@ -846,6 +847,9 @@ antiAlias Sharp 锐利 The selected character's font is not available. 所选字符的字体不可用。 No alternates for the selected character. 所选字符没有替代字。 Double-click to replace 双击以替换 + Click to replace 单击以替换 + Show all alternates in the Glyphs panel 在“字形”面板中显示所有替代字 + Show Character Alternates 显示字符的替代字 Select one character with the Type tool first. 请先用文字工具选择一个字符。 {glyph} is a glyph of {font}, not of the font the selected text is set in ({text_font}). {glyph} 是 {font} 的字形,不是所选文本所用字体({text_font})的字形。 {glyph} belongs to {base} (U+{base_code}) {place}; your selection is {sel} (U+{code}). {glyph} 属于 {base}(U+{base_code}){place};您选择的是 {sel}(U+{code})。 @@ -1289,6 +1293,7 @@ file-filter Templates 模板 Format 格式 Format Options 格式选项 Format Settings 格式设置 + Format Settings… 格式设置… Format: 格式: Formats: 格式: Fractional Widths 比例宽度 @@ -1639,6 +1644,7 @@ file-filter Templates 模板 Images: 图像: Import Keyboard Shortcuts… 导入键盘快捷键… Import PDF 导入 PDF + Import PDF pages as links 将 PDF 页面导入为链接 Import PDF Presets 导入 PDF 预设 Import Perspective Grid Presets 导入透视网格预设 Import Print Presets 导入打印预设 @@ -3302,6 +3308,18 @@ digits Malayalam 马拉雅拉姆数字 Smart Guides (View → Smart Guides) 智能参考线 (视图 → 智能参考线) Smart Guides (⌘U) 智能参考线 (⌘U) Smart Punctuation… 智能标点… + Smart Punctuation 智能标点 + ff, fi, ffi Ligatures ff、fi、ffi 连字 + ff, fl, ffl Ligatures ff、fl、ffl 连字 + Smart Quotes 智能引号 + Smart Spaces 智能空格 + En, Em Dashes 短破折号和长破折号 + Ellipses 删节号 + Expert Fractions 专家分数字 + Replace In 替换范围 + Selected Text Only 仅所选文本 + Entire Document 整个文档 + Report Results 报告结果 Smooth 平滑 Corner 尖角 Relative 相对 @@ -3332,6 +3350,7 @@ digits Malayalam 马拉雅拉姆数字 Solid 实心 Sort by Kind 按类型排序 Sort by Name 按名称排序 + Sort by Size 依大小排序 Sort by Status 依状态排序 Source code on GitHub GitHub 源代码 Source Sans 3 Source Sans 3 @@ -4871,6 +4890,7 @@ imageTrace Outline 轮廓 @msg there is no script engine named {name} 没有名为 {name} 的脚本引擎 @msg Running a script 正在运行脚本 @msg Copied the script report 已复制脚本报告 +@msg Copied the link info 已复制链接信息 @msg Exported {path} 已导出 {path} @msg no CSS to copy: select objects with CSS of their own 没有可复制的 CSS:请选择带有自身 CSS 的对象 @msg unknown highlight `{h}` 未知的高亮显示 `{h}` @@ -5557,6 +5577,7 @@ axis Both 两者 # Photoshop-style raster effects (Effect menu, their dialogs). Radial Blur… 径向模糊… + Blur Center 模糊中心 Smart Blur… 智能模糊… Sharpen 锐化 Unsharp Mask… 反锐化遮罩… @@ -6513,7 +6534,7 @@ axis Y Axis Y 轴 @plural Result: {n}|Results: {n} 结果:{n} @msg select one object 请选择一个对象 @msg Global Edit works on paths, compound paths, symbol instances and groups of them 全局编辑适用于路径、复合路径、符号实例及其编组 -@msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again 未找到相似对象(旋转或镜像的副本不会匹配);请更改全局编辑选项后重试 +@msg no similar objects found (reflected copies are not matched); change the Global Edit Options and try again 未找到相似对象(镜像的副本不会匹配);请更改全局编辑选项后重试 @msg Global Edit is off 全局编辑未开启 @msg only an object of the Global Edit other than the one it started from can be left out 只能从全局编辑中排除起始对象以外的对象 @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`:应为 all 或 1, 3-5 这样的范围,而不是 {v} @@ -7306,11 +7327,20 @@ breakText Glyphs 字形 Open Tutorial Sample 打开教程示例 Finish Tutorial 完成教程 Next Tutorial 下一个教程 + Show Learn Tab 显示学习选项卡 + Show Skill 显示技能 + Back One Level 返回上一级 Back to Skills 返回技能 @msg tutorial `{id}` has no practice sample 教程 `{id}` 没有练习示例 @msg open the practice sample of `{id}` first (see learn.openSample) 请先打开 `{id}` 的练习示例 (请参阅 learn.openSample) @msg finish `{id}` first (see learn.finish) 请先完成 `{id}` (请参阅 learn.finish) @msg `{id}` is the last tutorial in its skill `{id}` 是其技能的最后一个教程 + Reset progress 重置进度 + Mark Tutorial Step 标记教程步骤 + Reset Learn Progress 重置学习进度 +@msg missing `step` (see learn.show) 缺少 `step` (请参阅 learn.show) +@msg `step` must be a step number from 0 to {last} `step` 必须是 0 到 {last} 之间的步骤编号 +@msg `{id}` is finished (see learn.resetProgress) `{id}` 已完成 (请参阅 learn.resetProgress) # Deferred plug-in effects Refresh Deferred Effects 刷新延迟的效果 @@ -8842,6 +8872,8 @@ breakText Glyphs 字形 @msg the RTF file is too large to place as type (at most {_1} MB) RTF 文件过大,无法作为文字置入 (最多 {_1} MB) @msg the SVG expands to more than {0} nested SVG images SVG 展开后的嵌套 SVG 图像超过 {0} 个 @msg the SVG expands to more than {0} objects SVG 展开后的对象超过 {0} 个 +@msg the SVG's style sheets take too long to match 匹配 SVG 的样式表耗时过长 +@msg the SVG's styles expand to more than {0} MB SVG 的样式展开后超过 {0} MB @msg the SVG has no drawable objects SVG 中没有可绘制的对象 @msg the SVGZ file unpacks to more than {_1} MB SVGZ 文件解压后超过 {_1} MB @msg the Word document has more than {MAX_PAGES} pages of properties, too many to place Word 文档的属性页超过 {MAX_PAGES} 页,过多而无法置入 @@ -9154,6 +9186,9 @@ breakText Glyphs 字形 @msg {what} can't be intertwined {what} 不能交织 @msg {what} doesn't fit the paper with its bleed and marks {what} 连同出血和标记在纸张上放不下 @msg {what} would print on more than {MAX_TILES} tiles: scale it down {what} 会打印成超过 {MAX_TILES} 个拼贴:请将其缩小 + Nest Shapes… 形状排料… + Nest Shapes 形状排料 + Roll 卷材 # Messages of the effects, 3D, image export, color profiles, swatch exchange files, color books and DXF import. @msg 3D effects require finite coordinates within 100 million points 3D 效果需要 1 亿点以内的有限坐标 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 264a252f18..1af78f38b4 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -608,6 +608,7 @@ font-technology Variable 可變 Copy All Styles 複製所有樣式 Copy Color Value (Hex) 複製顏色值 (Hex) Copy Fonts Used in the Document 複製文件中使用的字體 + Copy Info 複製資訊 Copy Links 複製連結 Copy Selected Style 複製所選樣式 Copy to User Defined 複製到使用者定義 @@ -875,6 +876,9 @@ font-technology Variable 可變 The selected character's font is not available. 選取字元的字體無法使用。 No alternates for the selected character. 選取的字元沒有替代字。 Double-click to replace 按兩下以取代 + Click to replace 按一下以取代 + Show all alternates in the Glyphs panel 在「字符」面板中顯示所有替代字 + Show Character Alternates 顯示字元的替代字 Select one character with the Type tool first. 請先用文字工具選取一個字元。 {glyph} is a glyph of {font}, not of the font the selected text is set in ({text_font}). {glyph} 是 {font} 的字形,不是所選文字所用字體({text_font})的字形。 {glyph} belongs to {base} (U+{base_code}) {place}; your selection is {sel} (U+{code}). {glyph} 屬於 {base}(U+{base_code}){place};您選取的是 {sel}(U+{code})。 @@ -1324,6 +1328,7 @@ file-filter Templates 範本 Format 格式 Format Options 格式選項 Format Settings 格式設定 + Format Settings… 格式設定… Format: 格式: Formats: 格式: Fractional Widths 小數字寬 @@ -1686,6 +1691,7 @@ file-filter Templates 範本 Images: 影像: Import Keyboard Shortcuts… 匯入鍵盤快速鍵… Import PDF 匯入 PDF + Import PDF pages as links 將 PDF 頁面匯入為連結 Import PDF Presets 匯入 PDF 預設集 Import Perspective Grid Presets 匯入透視格點預設集 Import Print Presets 匯入列印預設集 @@ -2585,6 +2591,7 @@ file-filter Templates 範本 @msg there is no script engine named {name} 沒有名為 {name} 的指令碼引擎 @msg Running a script 正在執行指令碼 @msg Copied the script report 已複製指令碼報告 +@msg Copied the link info 已複製連結資訊 @msg Exported {path} 已匯出 {path} @msg no CSS to copy: select objects with CSS of their own 沒有可複製的 CSS:請選取有自己 CSS 的物件 @msg unknown highlight `{h}` 未知的反白顯示 `{h}` @@ -4559,6 +4566,18 @@ digits Malayalam 馬來亞拉姆數字 Smart Guides (View → Smart Guides) 智慧型參考線 (檢視 → 智慧型參考線) Smart Guides (⌘U) 智慧型參考線 (⌘U) Smart Punctuation… 智慧型標點… + Smart Punctuation 智慧型標點 + ff, fi, ffi Ligatures ff、fi、ffi 連字 + ff, fl, ffl Ligatures ff、fl、ffl 連字 + Smart Quotes 智慧型引號 + Smart Spaces 智慧型空格 + En, Em Dashes 短破折號和長破折號 + Ellipses 刪節號 + Expert Fractions 專家分數 + Replace In 取代範圍 + Selected Text Only 僅限選取的文字 + Entire Document 整份文件 + Report Results 報告結果 Smooth 平滑 Corner 角點 Relative 相對 @@ -4589,6 +4608,7 @@ digits Malayalam 馬來亞拉姆數字 Solid 實心 Sort by Kind 依類型排序 Sort by Name 依名稱排序 + Sort by Size 依大小排序 Sort by Status 依狀態排序 Source code on GitHub GitHub 上的原始碼 Source Sans 3 Source Sans 3 @@ -5392,6 +5412,7 @@ axis Both 兩者 # Photoshop-style raster effects (Effect menu, their dialogs). Radial Blur… 放射狀模糊… + Blur Center 模糊中心 Smart Blur… 智慧型模糊… Sharpen 銳利化 Unsharp Mask… 反銳利化遮罩… @@ -6320,7 +6341,7 @@ axis Y Axis Y 軸 @plural Result: {n}|Results: {n} 結果:{n} @msg select one object 請選取一個物件 @msg Global Edit works on paths, compound paths, symbol instances and groups of them 整體編輯適用於路徑、複合路徑、符號實體及其群組 -@msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again 找不到相似的物件(旋轉或鏡像的副本不會相符);請變更整體編輯選項後再試一次 +@msg no similar objects found (reflected copies are not matched); change the Global Edit Options and try again 找不到相似的物件(鏡像的副本不會相符);請變更整體編輯選項後再試一次 @msg Global Edit is off 整體編輯未開啟 @msg only an object of the Global Edit other than the one it started from can be left out 只能從整體編輯中排除起始物件以外的物件 @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`:應為 all 或 1, 3-5 這類範圍,而不是 {v} @@ -7114,11 +7135,20 @@ breakText Glyphs 字符 Open Tutorial Sample 開啟教學課程範例 Finish Tutorial 完成教學課程 Next Tutorial 下一個教學課程 + Show Learn Tab 顯示學習索引標籤 + Show Skill 顯示技能 + Back One Level 返回上一層 Back to Skills 返回技能 @msg tutorial `{id}` has no practice sample 教學課程 `{id}` 沒有練習範例 @msg open the practice sample of `{id}` first (see learn.openSample) 請先開啟 `{id}` 的練習範例 (請參閱 learn.openSample) @msg finish `{id}` first (see learn.finish) 請先完成 `{id}` (請參閱 learn.finish) @msg `{id}` is the last tutorial in its skill `{id}` 是其技能的最後一個教學課程 + Reset progress 重設進度 + Mark Tutorial Step 標記教學課程步驟 + Reset Learn Progress 重設學習進度 +@msg missing `step` (see learn.show) 未提供 `step` (請參閱 learn.show) +@msg `step` must be a step number from 0 to {last} `step` 必須是 0 到 {last} 之間的步驟編號 +@msg `{id}` is finished (see learn.resetProgress) `{id}` 已完成 (請參閱 learn.resetProgress) # Deferred plug-in effects Refresh Deferred Effects 重新整理延後的效果 @@ -7148,6 +7178,125 @@ breakText Glyphs 字符 Grommets 扣眼 Grommet Inset 扣眼邊距 Diameter 直徑 + Nest Shapes… 形狀排料… + Nest Shapes 形狀排料 + Roll 捲材 + +# Messages of the effects, 3D, image export, color profiles, swatch exchange files, color books and DXF import. +@msg 3D effects require finite coordinates within 100 million points 3D 效果需要位於 1 億點以內的有限座標 +@msg 3D effects require one to ten lights 3D 效果需要 1 到 10 個光源 +@msg BMP depth {_1}: 1, 4, 8, 16, 24 or 32 bits per pixel BMP 色彩深度 {_1}:須為每像素 1、4、8、16、24 或 32 位元 +@msg BMP encoding failed: {width} × {height} pixels doesn't fit the format or the pixel buffer BMP 編碼失敗:{width} × {height} 像素不符合格式或像素緩衝區 +@msg GIF encoding failed: the palette image is malformed GIF 編碼失敗:調色盤影像格式錯誤 +@msg GIF encoding failed: {e} GIF 編碼失敗:{e} +@msg JPEG colour profile: {e} JPEG 色彩描述檔:{e} +@msg JPEG encoding failed: pixel buffer doesn't match the image size JPEG 編碼失敗:像素緩衝區與影像尺寸不符 +@msg JPEG encoding failed: {e} JPEG 編碼失敗:{e} +@msg PNG encoding failed: pixel buffer doesn't match the image size PNG 編碼失敗:像素緩衝區與影像尺寸不符 +@msg PNG encoding failed: the palette image is malformed PNG 編碼失敗:調色盤影像格式錯誤 +@msg PNG encoding failed: {e} PNG 編碼失敗:{e} +@msg PNG encoding failed: {width} × {height} pixels is not a valid image size PNG 編碼失敗:{width} × {height} 像素不是有效的影像尺寸 +@msg PSD colour profile: {e} PSD 色彩描述檔:{e} +@msg PSD encoding failed: the pixel buffer doesn't match the image size PSD 編碼失敗:像素緩衝區與影像尺寸不符 +@msg Revolve profile contains invalid coordinates 迴轉的輪廓包含無效的座標 +@msg Revolve profile is too complex 迴轉的輪廓過於複雜 +@msg Revolve projection is not finite 迴轉的投影不是有限值 +@msg Revolve requires finite profile coordinates within 100 million points 迴轉需要位於 1 億點以內的有限輪廓座標 +@msg Revolve surface is too complex; reduce Segments or simplify the profile 迴轉曲面過於複雜;請減少「分段數」或簡化輪廓 +@msg Revolve surface is too complex; simplify the profile 迴轉曲面過於複雜;請簡化輪廓 +@msg Revolve visibility cannot split the projected boundary 迴轉的可見性計算無法分割投影邊界 +@msg Revolve visibility creates too many fragments 迴轉的可見性計算產生過多片段 +@msg Revolve visibility creates too many vector anchors 迴轉的可見性計算產生過多向量錨點 +@msg Revolve visibility exceeds its geometry work limit 迴轉的可見性計算超出幾何運算量上限 +@msg Revolve visibility exceeds its spatial index limit 迴轉的可見性計算超出空間索引上限 +@msg Revolve visibility has too many boundary crossings 迴轉的可見性計算有過多邊界交叉 +@msg Revolve visibility has too many input anchors 迴轉的可見性計算有過多輸入錨點 +@msg Revolve visibility requires convex cap sectors 迴轉的可見性計算需要凸形的端蓋扇區 +@msg Revolve visibility requires finite projected faces 迴轉的可見性計算需要有限的投影面 +@msg SVG options: {e} SVG 選項:{e} +@msg Save for Web settings: {e} 儲存為網頁用設定:{e} +@msg TIFF colour profile: {e} TIFF 色彩描述檔:{e} +@msg TIFF encoding failed: the pixel buffer doesn't match the image size TIFF 編碼失敗:像素緩衝區與影像尺寸不符 +@msg TIFF encoding failed: {e} TIFF 編碼失敗:{e} +@msg Targa depth {_1}: 16, 24 or 32 bits per pixel Targa 色彩深度 {_1}:須為每像素 16、24 或 32 位元 +@msg Targa encoding failed: the pixel buffer doesn't match the image size Targa 編碼失敗:像素緩衝區與影像尺寸不符 +@msg The 3D projection is not finite 3D 投影不是有限值 +@msg The 3D shadow is too complex; turn Shadows off or simplify the art 3D 陰影過於複雜;請關閉「陰影」或簡化圖稿 +@msg The shape contains invalid coordinates 形狀包含無效的座標 +@msg Too many Revolve faces for visibility evaluation 迴轉的面過多,無法計算可見性 +@msg VectorCraft reads at most {ASE_MAX_ENTRIES} colors and groups from a swatch exchange file, and this library has {entries} VectorCraft 從色票交換檔案最多讀取 {ASE_MAX_ENTRIES} 個顏色和群組,而此資料庫有 {entries} 個 +@msg WebP encoding failed: {e} WebP 編碼失敗:{e} +@msg [{j}] `{_1}`: {why} [{j}] `{_1}`:{why} +@msg `answers[{i}]` {e} `answers[{i}]` {e} +@msg `view` is smallThumb, mediumThumb, largeThumb, smallList or largeList `view` 必須是 smallThumb、mediumThumb、largeThumb、smallList 或 largeList +@msg a line can't run from a point to itself 線條不能從一個點連到同一個點 +@msg a line needs at least two points 線條至少需要兩個點 +@msg a number cannot be read 無法讀取數字 +@msg a swatch exchange block is too long 色票交換區塊過長 +@msg a swatch exchange name is too long 色票交換名稱過長 +@msg a {sw} × {sh} image can't be resized to {width} × {height} pixels {sw} × {sh} 的影像無法調整為 {width} × {height} 像素 +@msg a {width} × {height} image is too large {width} × {height} 的影像過大 +@msg a {width} × {height} image: {e} {width} × {height} 的影像:{e} +@msg an image could not be written: {e} 無法寫入影像:{e} +@msg an image that couldn't be read was left out 已略過無法讀取的影像 +@msg can't open “{name}”: {e} 無法開啟「{name}」:{e} +@msg cannot align zip entries to {align} bytes 無法將 ZIP 項目對齊至 {align} 位元組 +@msg cannot open the automation {kind} root `{_1}`: {e} 無法開啟自動化 {kind} 根目錄 `{_1}`:{e} +@msg cannot read profile: {0} 無法讀取描述檔:{0} +@msg color book version {version} isn't supported (only 1) 不支援色票簿版本 {version} (僅支援 1) +@msg color books in color space {other} aren't supported (only RGB, CMYK and Lab) 不支援色彩空間為 {other} 的色票簿 (僅支援 RGB、CMYK 和 Lab) +@msg file name too long to zip: {_1} 檔案名稱過長,無法壓縮為 ZIP:{_1} +@msg file name too long to zip: {name} 檔案名稱過長,無法壓縮為 ZIP:{name} +@msg freeform line {i}: {e} 任意形狀線條 {i}:{e} +@msg freeform point {i}: {e} 任意形狀點 {i}:{e} +@msg give `{key}` or `{other}`, not both 請提供 `{key}` 或 `{other}`,不能同時提供兩者 +@msg grayscale profiles can't be working spaces yet 灰階描述檔目前還不能作為工作空間 +@msg input contains NaN or infinite coordinates 輸入包含 NaN 或無限大的座標 +@msg input path could not be closed 無法封閉輸入路徑 +@msg invalid ICC profile: {0} 無效的 ICC 描述檔:{0} +@msg invalid scale {scale} 無效的縮放比例 {scale} +@msg its localized names take more than {_1} KB 其本地化名稱超過 {_1} KB +@msg its objects are nested too deep ({e}) 其物件巢狀層級過深 ({e}) +@msg its tag table lists the `{_1}` tag more than once 其標記表多次列出 `{_1}` 標記 +@msg not a graphic style library: {e} 不是繪圖樣式資料庫:{e} +@msg not a swatch library (.vcswatches or .gpl) 不是色票資料庫 (.vcswatches 或 .gpl) +@msg not a swatch library (format `{_1}`) 不是色票資料庫 (格式為 `{_1}`) +@msg not a swatch library: {e} 不是色票資料庫:{e} +@msg not an action set file ({e}) 不是動作組檔案 ({e}) +@msg profile colour space {other} is not RGB, CMYK or Gray 描述檔的色彩空間 {other} 不是 RGB、CMYK 或灰階 +@msg regular expression too large 規則運算式過大 +@msg script file is not UTF-8 text: {value} 指令碼檔案不是 UTF-8 文字:{value} +@msg stop {i}: {e} 色標 {i}:{e} +@msg swatch exchange version {major}.{minor} isn't supported (only 1.x) 不支援色票交換版本 {major}.{minor} (僅支援 1.x) +@msg the color book holds more than {ASE_MAX_ENTRIES} colors 色票簿包含超過 {ASE_MAX_ENTRIES} 個顏色 +@msg the color book is cut short 色票簿不完整 +@msg the color book's names take more than {_1} MB 色票簿的名稱超過 {_1} MB +@msg the image would be {w} × {h} pixels; raster exports are limited to {MAX_RASTER_SIDE} pixels per side and {_1} megapixels: lower the scale or resolution 影像會是 {w} × {h} 像素;點陣圖匯出的上限為每邊 {MAX_RASTER_SIDE} 像素及 {_1} 百萬像素:請降低縮放比例或解析度 +@msg the optimised image can't be read back: {e} 無法讀回最佳化後的影像:{e} +@msg the pixel buffer doesn't match the image size 像素緩衝區與影像尺寸不符 +@msg the preview: {e} 預覽:{e} +@msg the request may not read the New Document profiles folder 此要求不得讀取新增文件描述檔資料夾 +@msg the shapes are too degenerate to combine 形狀過度退化,無法合併 +@msg the shapes cross themselves and each other too often to combine 形狀自身及彼此之間交叉過多,無法合併 +@msg the swatch exchange file holds more than {ASE_MAX_ENTRIES} colors and groups 色票交換檔案包含超過 {ASE_MAX_ENTRIES} 個顏色和群組 +@msg the swatch exchange file is cut short 色票交換檔案不完整 +@msg the {_1} plate can't be read: {e} 無法讀取 {_1} 色版:{e} +@msg this binary DXF file is damaged or cut short 此二進位 DXF 檔案已損毀或不完整 +@msg this is a DWG drawing, which can't be read: save it from the CAD app as a DXF and open that 這是 DWG 圖面,無法讀取:請在 CAD 應用程式中將其儲存為 DXF,再開啟該檔案 +@msg too many classes 字元類別過多 +@msg too many groups 群組過多 +@msg too many layers for PSD (at most 32767) PSD 的圖層過多 (最多 32767 個) +@msg too many swatch exchange blocks 色票交換區塊過多 +@msg unknown colour profile: {0} 未知的色彩描述檔:{0} +@msg {_1} clashes with a built-in profile name {_1} 與內建描述檔名稱衝突 +@msg {_1} × {_2} pixels is too large for GIF (at most 65535 pixels a side): lower the resolution {_1} × {_2} 像素對 GIF 來說過大 (每邊最多 65535 像素):請降低解析度 +@msg {_1}: no usable transform to/from sRGB {_1}:沒有可與 sRGB 互相轉換的可用轉換 +@msg {name} is not a CMYK profile {name} 不是 CMYK 描述檔 +@msg {name} is not an RGB profile {name} 不是 RGB 描述檔 +@msg {path}: could not be read {path}:無法讀取 +@msg {width} × {height} pixels is too large for JPEG (at most 65535 pixels a side): lower the resolution {width} × {height} 像素對 JPEG 來說過大 (每邊最多 65535 像素):請降低解析度 +@msg {width} × {height} pixels is too large for Targa (at most 65535 pixels a side): lower the resolution {width} × {height} 像素對 Targa 來說過大 (每邊最多 65535 像素):請降低解析度 +@msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} 像素對 PSD 來說過大 (每邊最多 {MAX_SIDE} 像素):請降低解析度 # Status and error messages of commands, scripts, file import and export, and plug-ins. @msg 'caller', 'callee' and 'arguments' cannot be used on strict mode functions 嚴格模式的函式不能使用 'caller'、'callee' 和 'arguments' @@ -8651,6 +8800,8 @@ breakText Glyphs 字符 @msg the RTF file is too large to place as type (at most {_1} MB) RTF 檔案過大,無法置入為文字 (最多 {_1} MB) @msg the SVG expands to more than {0} nested SVG images SVG 展開後超過 {0} 個巢狀 SVG 影像 @msg the SVG expands to more than {0} objects SVG 展開後超過 {0} 個物件 +@msg the SVG's style sheets take too long to match 比對 SVG 的樣式表耗時過長 +@msg the SVG's styles expand to more than {0} MB SVG 的樣式展開後超過 {0} MB @msg the SVG has no drawable objects SVG 中沒有可繪製的物件 @msg the SVGZ file unpacks to more than {_1} MB SVGZ 檔案解壓縮後超過 {_1} MB @msg the Word document has more than {MAX_PAGES} pages of properties, too many to place Word 文件的屬性超過 {MAX_PAGES} 頁,數量過多而無法置入 diff --git a/crates/ui-egui/src/io.rs b/crates/ui-egui/src/io.rs index ee083d7d44..ea27320b52 100644 --- a/crates/ui-egui/src/io.rs +++ b/crates/ui-egui/src/io.rs @@ -446,6 +446,31 @@ mod tests { assert_eq!(&w[1].1[1..4], b"PNG", "PNG from the given path"); } + /// An option skips the options dialog, but without `path` the save panel still picks the file. + #[test] + fn export_selection_with_an_option_and_no_path_asks_for_the_file_only() { + let (mut app, written) = app(); + app.session.execute("file.new", &json!({"width": 60, "height": 40})).unwrap(); + app.session.execute("shape.rectangle", &json!({"x": 5, "y": 5, "width": 20, "height": 10})).unwrap(); + let asked = Rc::new(RefCell::new(0)); + let count = asked.clone(); + app.services.pick_save = Some(Box::new(move |_: &FilePick| { + *count.borrow_mut() += 1; + Some("/tmp/sel.png".into()) + })); + let r = app.run("document.exportSelection", json!({"scale": 2})).unwrap(); + assert_eq!(*asked.borrow(), 1, "the save panel picks the file"); + assert!(app.ui.dialog.is_none(), "no options dialog follows"); + assert_eq!(r["path"], "/tmp/sel.png"); + assert_eq!(&written.borrow()[0].1[1..4], b"PNG"); + app.run("document.exportSelection", json!({"path": "/tmp/sel2.png", "scale": 2})).unwrap(); + assert_eq!(*asked.borrow(), 1, "a path writes without the save panel"); + let w = written.borrow(); + assert_eq!(w.len(), 2); + assert_eq!(w[0].0, "/tmp/sel.png", "the picked file"); + assert_eq!(w[1].0, "/tmp/sel2.png", "the given path"); + } + #[test] fn written_files_open_as_file_urls() { let url = super::file_url("/tmp/My Art #1.pdf"); diff --git a/crates/ui-egui/src/io/save.rs b/crates/ui-egui/src/io/save.rs index 6e38e8cc63..10fae638c4 100644 --- a/crates/ui-egui/src/io/save.rs +++ b/crates/ui-egui/src/io/save.rs @@ -263,7 +263,9 @@ pub(super) fn save_current_in(app: &mut VectorcraftApp, p: &Value, folder: Optio return Ok(r); } let retry = super::read_only_save::Retry::new(&first, folder); - write_plan(app, first, ("file.save", p.clone()), Some(retry)) + // Only `path` was asked about: the files written beside it are checked against the file the + // document was read from when the save writes them. + write_plan(app, plan(app, SaveMode::Save, p)?, ("file.save", p.clone()), Some(retry)) } /// File → Save, Save As…, Save a Copy…, Save as Template… and the options dialogs' OK. `p` is the diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 3aab5e1e44..752d42b9ae 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -83,6 +83,8 @@ pub(super) fn menu_dialog(app: &VectorcraftApp, id: &str) -> Option<(&'static st crate::addons::select::COMMAND => (crate::addons::select::KIND, crate::addons::select::fields(app)), "artboard.rearrange" => (crate::dialogs::rearrange_artboards::KIND, crate::dialogs::rearrange_artboards::open_fields(app)), "artboard.rename" => (crate::dialogs::rename_artboards::KIND, crate::dialogs::rename_artboards::open_fields(app)), + // Smart Punctuation opens on the fields it was last confirmed with. + "type.smartPunctuation" => (crate::dialogs::smart_punctuation::KIND, crate::dialogs::smart_punctuation::fields(app)), _ => return None, }) } diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 7b7f7a6b21..ff578d81e5 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -976,6 +976,7 @@ fn run_ui_part11(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::panels::links::open_file(app, p, false), "links.reveal" => crate::panels::links::open_file(app, p, true), + "links.copyInfo" => crate::panels::links::copy_info(app, p), "ui.placementOptionsDialog" => crate::dialogs::placement_options::open(app, p), "ui.relinkDialog" => crate::dialogs::relink::open(app, p), "ui.findLinksInFolder" => { diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index 0d5775ffe9..98c13ec06e 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -310,6 +310,7 @@ pub fn enabled(app: &VectorcraftApp, id: &str) -> bool { "ui.dxfOptionsDialog" => app.session.active().is_some(), "links.editOriginal" | "links.reveal" => selected_image(app, |im| im.link.is_some()) || selected_placed(app), "ui.placementOptionsDialog" => selected_image(app, |_| true) || selected_placed(app), + "links.copyInfo" => !crate::panels::links::selected_rows_of_app(app).is_empty(), "ui.relinkDialog" => app.services.pick_open.is_some() && (selected_image(app, |_| true) || selected_placed(app)), "ui.findLinksInFolder" => crate::picks::can(app, &crate::picks::PickRequest::Folder) && app.session.active().is_some(), "ui.packageDialog" | "docInfo.save" => app.session.active().is_some(), diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index 4b86b4152d..cc63a489cf 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -436,7 +436,7 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { cp("Sentence case", "type.changeCase", json!({"case": "sentence"})), ], ), - cp("Smart Punctuation…", "type.smartPunctuation", json!({"quotes": true, "dashes": true, "ellipsis": true, "scope": "selection"})), + c("Smart Punctuation…", "type.smartPunctuation"), sub( "Bullets and Numbering", vec![ diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index af9252c333..4c14966462 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -261,7 +261,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "type.convertListToText", "Convert to Text", "", - "{} Type › Bullets and Numbering › Convert to Text: the bullets and numbers of the selected type's list paragraphs (or of those the Type tool's selection touches) become characters of the text, followed by a tab, and the lists are turned off (text.convertListToText); the Type tool's anchor and caret move past the characters inserted at or before them, into the frame the caret's character moved to in threaded type", + "{} Type › Bullets and Numbering › Convert to Text: the bullets and numbers of the selected type's list paragraphs, in every frame of a threaded story (or of those the Type tool's selection touches), become characters of the text, followed by a tab, and the lists are turned off (text.convertListToText); the Type tool's anchor and caret move past the characters inserted at or before them, into the frame the caret's character moved to in threaded type", ), ( "align.horizontalLeft", @@ -667,7 +667,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "learn.list", "List Tutorials", "", - "{} the Learn panel's skills in the order its Skills tab lists them: {skills: [{id, title, tutorials: [{id, title, steps: number of steps}]}]}", + "{} the Learn panel's skills in the order its Skills tab lists them, with the progress its rings, counts and check marks show: {skills: [{id, title, done: number of its tutorials finished, total: number of its tutorials, tutorials: [{id, title, steps: number of steps, finished: bool, completedSteps: [zero-based indexes of the steps marked done, every step once finished]}]}]}", + ), + ( + "learn.tab", + "Show Learn Tab", + "", + "{tab: forYou|skills} show the Learn panel on its For you or Skills tab, as the tab buttons do; the Skills tab keeps the skill and tutorial it had open; a missing, non-string or unknown tab is an error and changes nothing; returns {tab, skill, tutorial}, with null for no skill or no tutorial open", ), ( "learn.skills", @@ -675,12 +681,24 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} show the Learn panel on its Skills tab with the list of skills, with no skill and no tutorial open, as Back to skills after a skill's last tutorial and the Quick skill guide card do; returns what learn.list returns", ), + ( + "learn.skill", + "Show Skill", + "", + "{skill: id (see learn.list)} show the Learn panel on its Skills tab with that skill's tutorials, as choosing the skill's row does; a missing, non-string or unknown id is an error and changes nothing; returns the skill as learn.list lists it: {id, title, done, total, tutorials: [{id, title, steps, finished, completedSteps}]}", + ), ( "learn.show", "Show Tutorial", "", "{tutorial: id (see learn.list)} show the Learn panel on its Skills tab with that tutorial's numbered steps, as choosing its skill and then the tutorial does; a missing, non-string or unknown id is an error and changes nothing; returns {skill, tutorial, title, steps: [text]}", ), + ( + "learn.back", + "Back One Level", + "", + "{} show the Learn panel and go up one level on its Skills tab, as its Back button does: from a tutorial's steps to its skill's tutorials, and from a skill's tutorials to the list of skills; on the list of skills or the For you tab the view stays as it is; returns {tab, skill, tutorial}, as learn.tab does", + ), ( "learn.locateTool", "Show Tool Location", @@ -693,11 +711,17 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{tutorial: id (see learn.list)} open that tutorial's practice sample as a new untitled document, which becomes the active one, and move the Learn view to the tutorial, as its View more button does; each call opens another copy and open documents stay as they are; a missing, non-string or unknown id is an error and changes nothing; returns {tutorial, index, title} of the new document", ), + ( + "learn.markStep", + "Mark Tutorial Step", + "", + "{tutorial: id (see learn.list), step: zero-based step number, complete?: bool} mark a step of a tutorial whose sample learn.openSample opened as done (true, omitted or null) or not done (false), as the check box before the step does; marking does not finish the tutorial; a missing, non-string or unknown id, a missing step or one the tutorial does not have, a complete that is not true or false, a tutorial whose sample was not opened, or a finished tutorial is an error and changes nothing; the preferences keep the marks; returns {tutorial, step, complete}", + ), ( "learn.finish", "Finish Tutorial", "", - "{tutorial: id (see learn.list)} mark a tutorial whose sample learn.openSample opened as finished, as its Finish tutorial button does; finishing it again keeps one entry; a missing, non-string or unknown id, or a tutorial whose sample was not opened, is an error and changes nothing; returns {tutorial, finished: true, next: id of the next tutorial in its skill, or null after the skill's last one}", + "{tutorial: id (see learn.list)} mark a tutorial whose sample learn.openSample opened as finished, with all its steps done, as its Finish tutorial button does; finishing it again keeps one entry, and needs no sample after a restart; a missing, non-string or unknown id, or a tutorial not finished whose sample was not opened, is an error and changes nothing; the preferences keep the tutorials finished; returns {tutorial, finished: true, next: id of the next tutorial in its skill, or null after the skill's last one}", ), ( "learn.next", @@ -705,6 +729,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{tutorial: id (see learn.list)} show the Learn panel on the tutorial after a finished one in the same skill, as its Next Up button does, without opening a sample; a missing, non-string or unknown id, a tutorial not finished, or a skill's last tutorial is an error and changes nothing; returns {skill, tutorial, title} of the next tutorial", ), + ( + "learn.resetProgress", + "Reset Learn Progress", + "", + "{} clear the Learn panel's progress, every tutorial finished and every step marked done, as Reset progress under the list of skills does; open documents, opened practice samples and the Learn view stay as they are; returns what learn.list returns", + ), ("window.brightness", "UI Brightness", "", "{brightness: dark|mediumDark|mediumLight|light}"), ( "window.workspace", @@ -1223,7 +1253,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.svgFilterDialog", "Apply SVG Filter…", "", - "{index?, item?} open Apply SVG Filter for the active document (dialog `svgFilter`, fields `selected`: a filter's name, `code`: the code being edited, `editing`: \"\", \"new\" or the name of the filter being edited; with index, for the applied svg.filter effect at index of item, as effect.dialog opens it): its list shows svgFilter.list's filters; OK runs svgFilter.apply with selected, or effect.setParams on the applied effect; New and Edit open the code, Save runs svgFilter.define, Delete runs svgFilter.delete and Import… svgFilter.import with a picked SVG file", + "{index?, item?} open Apply SVG Filter for the active document (dialog `svgFilter`, fields `selected`: a filter's name, `code`: the code being edited, `editing`: \"\", \"new\" or the name of the filter being edited; with index, for the applied svg.filter effect at index of item, as effect.dialog opens it): its list shows svgFilter.list's defaults (the document's filter of a default's name in its place) and then the document's other filters; OK runs svgFilter.apply with selected, and with index and item for the applied effect; New and Edit open the code, Save runs svgFilter.define (replace: the filter edited, a default included), Delete runs svgFilter.delete (off for a default the document holds no copy of) and Import… svgFilter.import with a picked SVG file", ), ( "ui.importSvgFilter", @@ -1426,6 +1456,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{id?} show the file of linked image `id` (default: the selected linked image) in the system's file manager → {path}", ), + ( + "links.copyInfo", + "Copy Info", + "", + "{ids?} copy the file names of images and placed documents `ids` (default: the selected ones and the rows picked in the Links panel, in links.list order) to the clipboard, one per line in that order; an embedded image gives the name its Links panel row shows (Links panel menu) → {text, names}", + ), ( "ui.placementOptionsDialog", "Placement Options…", diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index ded320a5aa..3e7fb53316 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -379,14 +379,15 @@ mod tests { ) } - /// A pick of a "…" command whose menu bar item gives params opens that item's dialog, and Smooth - /// opens its slider; nothing changes until the dialog is confirmed. + /// A pick of a "…" command whose menu bar item gives params opens that item's dialog, Smart + /// Punctuation opens its dialog and Smooth opens its slider; nothing changes until the dialog + /// is confirmed. #[test] fn a_pick_opens_the_dialog_its_menu_item_opens() { let expected = [ ("object.path.cleanUp", "command"), ("object.mesh.create", "command"), - ("type.smartPunctuation", "command"), + ("type.smartPunctuation", crate::dialogs::smart_punctuation::KIND), ("edit.findReplace", "command"), ("object.path.smooth", crate::dialogs::smooth_slider::KIND), ]; diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 71019385b6..bbe91da5a6 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -54,7 +54,7 @@ pub mod variables; use egui::{Rect, Sense, Ui, vec2}; use serde_json::{Value, json}; use vectorcraft_color::{BlendMode, Color, Paint}; -use vectorcraft_doc::{LiveCorners, Node, StrokeLayer}; +use vectorcraft_doc::{LiveCorners, Node, NodeId, NodeKind, StrokeLayer}; use vectorcraft_engine::inspect::StrokeMixed; use vectorcraft_geom::shapes::CornerKind; @@ -322,11 +322,13 @@ pub(crate) fn current_paints(app: &VectorcraftApp) -> (Paint, Paint) { } /// Whether the selected objects' fills and strokes differ (the proxies show "?"), cached per -/// document revision and Appearance panel item. +/// document revision, Appearance panel item and picked gradient mesh points (picking points +/// changes no revision). pub(crate) fn mixed_paints(app: &VectorcraftApp, ctx: &egui::Context) -> (bool, bool) { + type Key = (u64, u64, Option, Vec<(NodeId, Vec)>); let Some(st) = app.session.active() else { return (false, false) }; - let key = (st.uid, st.revision, app.session.appearance_item()); - match pstate::), (bool, bool))>>(ctx, "proxy-mixed") { + let key: Key = (st.uid, st.revision, app.session.appearance_item(), app.session.fill_mesh_points()); + match pstate::>(ctx, "proxy-mixed") { Some((k, mixed)) if k == key => mixed, _ => { let mixed = app.session.proxy_mixed(); @@ -365,13 +367,23 @@ pub(crate) fn stroke_mixed(app: &VectorcraftApp, ctx: &egui::Context) -> StrokeM } /// Opacity and blend mode as the Transparency panel and Control bar show them: the Appearance -/// panel's active item's, else the first selected object's. +/// panel's active item's, else the first picked gradient mesh point's opacity (which +/// `transparency.set` changes then) with its object's blend mode, else the first selected object's. pub(crate) fn current_transparency(app: &VectorcraftApp) -> Option<(f32, BlendMode)> { let n = first_node(app)?; - Some(match app.session.appearance_item().and_then(|i| n.appearance.items.get(i)) { - Some(it) => (it.opacity(), it.blend()), - None => (n.opacity, n.blend), - }) + if let Some(it) = app.session.appearance_item().and_then(|i| n.appearance.items.get(i)) { + return Some((it.opacity(), it.blend())); + } + let picked = app.session.mesh_points_picked().and_then(|points| { + let (id, v) = points.first()?; + let d = &app.session.active()?.doc; + let m = match &d.node(*id)?.kind { + NodeKind::Mesh(m) => m, + _ => return None, + }; + Some((m.points.get(*v.first()?)?.opacity, d.node(*id)?.blend)) + }); + Some(picked.unwrap_or((n.opacity, n.blend))) } /// Is the active proxy "?" (the selected objects' paints differ)? @@ -529,6 +541,21 @@ const DRAG_SCROLL_EDGE: f32 = 28.0; /// the list's edge. const DRAG_SCROLL_SPEED: (f32, f32) = (60.0, 280.0); +/// The scrolling [`scroll_at_edges`] asks for, in points per second (positive shows earlier rows), +/// with the pointer `depth` points below the top of a list view `view_height` points tall. Each +/// band is [`DRAG_SCROLL_EDGE`] deep, or half the view in a view shorter than two bands, so the +/// pointer is in one band at most and the middle of a short view scrolls neither way. A view with +/// no height, or a value that isn't a number, gives 0. +fn drag_scroll_speed(view_height: f32, depth: f32) -> f32 { + if !(view_height.is_finite() && view_height > 0.0) { + return 0.0; + } + let band = DRAG_SCROLL_EDGE.min(view_height / 2.0); + let (slow, more) = DRAG_SCROLL_SPEED; + let speed = |depth: f32| if (0.0..band).contains(&depth) { slow + more * (1.0 - depth / band) } else { 0.0 }; + speed(depth) - speed(view_height - depth) +} + /// While something is dragged near the top or bottom edge of a scrolled list (`ui`: its contents), /// scroll that way, faster nearer the edge, and draw the next frame so a pointer held still keeps /// it scrolling. The pointer must be over the list's width. Each frame scrolls by the time it @@ -540,9 +567,7 @@ pub(crate) fn scroll_at_edges(ui: &mut Ui) { if !view.x_range().contains(pos.x) { return; } - let (slow, more) = DRAG_SCROLL_SPEED; - let speed = |depth: f32| if (0.0..DRAG_SCROLL_EDGE).contains(&depth) { slow + more * (1.0 - depth / DRAG_SCROLL_EDGE) } else { 0.0 }; - let per_second = speed(pos.y - view.top()) - speed(view.bottom() - pos.y); + let per_second = drag_scroll_speed(view.height(), pos.y - view.top()); if per_second != 0.0 { let dt = ui.input(|i| i.stable_dt).min(0.1); ui.scroll_with_delta_animation(vec2(0.0, per_second * dt), egui::style::ScrollAnimation::none()); @@ -683,6 +708,29 @@ mod tests { let tint = Paint::Solid { color: Color::gray(0.5), swatch: Some("Ink".into()), tint: 0.5 }; assert_eq!(paint_params(&tint), json!({"swatch": "Ink", "tint": 50.0}), "a tint keeps its percentage"); } + + #[test] + fn drag_scrolling_in_a_short_list_goes_toward_the_nearer_edge() { + let near = |a: f32, b: f32| (a - b).abs() < 1e-3; + // A 40 pt view: each band is 20 pt deep, so the pointer is in one band at most. + for (depth, want) in [(5.0, 270.0), (15.0, 130.0), (20.0, 0.0), (25.0, -130.0), (35.0, -270.0)] { + let got = drag_scroll_speed(40.0, depth); + assert!(near(got, want), "40 pt view, pointer {depth} pt down: {got} pt/s, want {want}"); + } + // Just outside a 20 pt view, the pointer does not scroll the list toward the far edge. + for depth in [-1.0, 21.0] { + assert_eq!(drag_scroll_speed(20.0, depth), 0.0, "20 pt view, pointer {depth} pt down"); + } + // From 56 pt up, the bands stay 28 pt deep and the speeds are unchanged. + for (h, depth, want) in [(100.0, 5.0, 290.0), (100.0, 95.0, -290.0), (100.0, 50.0, 0.0), (56.0, 0.0, 340.0), (56.0, 27.0, 70.0)] { + let got = drag_scroll_speed(h, depth); + assert!(near(got, want), "{h} pt view, pointer {depth} pt down: {got} pt/s, want {want}"); + } + for h in [0.0, -10.0, f32::NAN, f32::INFINITY] { + assert_eq!(drag_scroll_speed(h, 5.0), 0.0, "view height {h}"); + } + assert_eq!(drag_scroll_speed(40.0, f32::NAN), 0.0); + } } #[cfg(test)] mod tests_appearance; diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index eff4796601..4bab22d52e 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -6216,10 +6216,10 @@ mod tests { } } - /// A drag with the Selection tool (a committed preview) or the Rectangle tool (a command the - /// tool runs) that takes a recording past 10,000 steps keeps its edit and the journal, the - /// status bar names the limit as the tool ends, and Stop Playing/Recording keeps the 10,000 - /// steps that fit. One that fills the action exactly names no limit. + /// A drag with the Selection tool or the Rectangle tool (each commits its preview) that takes a + /// recording past 10,000 steps keeps its edit and the journal, the status bar names the limit + /// as the tool ends, and Stop Playing/Recording keeps the 10,000 steps that fit. One that fills + /// the action exactly names no limit. #[test] fn tool_commit_checks_recording_step_limit() { let steps = "the action already has 10,000 steps"; @@ -6272,6 +6272,115 @@ mod tests { } } + /// Drags the Enclosing Lasso away from the selected rectangle, which runs `select.set` with no + /// objects, and checks that the tool journaled that one step and cleared the selection. + fn lasso_nothing(app: &mut VectorcraftApp) { + app.select_tool(vectorcraft_tools::addons::enclosing_lasso::ID); + assert_eq!(app.session.tool_id(), vectorcraft_tools::addons::enclosing_lasso::ID); + assert!(!app.session.active().unwrap().selection.objects.is_empty()); + let journal = app.session.journal.len(); + tool_drag(app, (100.0, 80.0), (120.0, 80.0)); + assert_eq!(app.session.journal.len(), journal + 1, "the tool journals one step"); + assert_eq!(app.session.journal.last(), Some(&("select.set".to_string(), json!({"ids": []})))); + assert!(app.session.active().unwrap().selection.objects.is_empty(), "the edit stays"); + } + + /// A command a tool runs (the Enclosing Lasso's `select.set`) that takes a recording past + /// 10,000 steps keeps its edit and the journal, the status bar names the limit as the tool + /// ends, the next recorded command does not run, and Stop Playing/Recording keeps the 10,000 + /// steps that fit. One that fills the action exactly names no limit. + #[test] + fn tool_exec_checks_recording_step_limit() { + let steps = "the action already has 10,000 steps"; + for filler in [files::MAX_ACTION_STEPS, files::MAX_ACTION_STEPS - 1] { + let (mut app, _) = app_with_three_moves(); + recording_with(&mut app, filler); + app.ui.status.clear(); + lasso_nothing(&mut app); + if filler < files::MAX_ACTION_STEPS { + assert_eq!(app.ui.status, "", "10,000 steps fit"); + continue; + } + assert_eq!(app.ui.status, steps, "the status bar names the limit now"); + assert!(app.ui.recording.is_some(), "the recording goes on"); + let (journal, art) = (app.session.journal.len(), app.session.active().unwrap().doc.art_bounds()); + let r = app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 20, "height": 20})); + assert_eq!(r.unwrap_err(), steps, "no later command runs"); + assert_eq!(app.session.journal.len(), journal); + assert_eq!(app.session.active().unwrap().doc.art_bounds(), art, "no rectangle is drawn"); + assert_eq!(app.session.journal.since(recording_start(&app).unwrap()).len(), files::MAX_ACTION_STEPS + 1, "the journal keeps the step"); + app.run(STOP_RECORDING, json!({})).unwrap(); + assert_eq!(app.ui.action_sets[0].actions.last().unwrap().steps.len(), files::MAX_ACTION_STEPS); + } + } + + /// A command a tool runs (the Enclosing Lasso's `select.set`) whose step gives the recording's + /// set a file larger than 8 MiB keeps its edit, the status bar names the limit as the tool + /// ends, and Stop Playing/Recording leaves the step out of a set that Load Actions… reads. + #[test] + fn tool_exec_checks_recording_byte_limit() { + let size = "the action set would be larger than 8 MiB"; + let (mut app, _) = app_with_three_moves(); + app.run(START_RECORDING, json!({})).unwrap(); + let pad = |n: usize| ("object.move".to_string(), json!({"dx": 1, "dy": 0, "pad": "x".repeat(n)})); + app.ui.action_sets[0].actions[0].steps = vec![pad(0)]; + let room = files::MAX_SET_FILE - files::write_set(&app.ui.action_sets[0]).len(); + app.ui.action_sets[0].actions[0].steps = vec![pad(room)]; + app.ui.recording_into = Some(app.ui.action_sets[0].actions[0].id); + app.ui.status.clear(); + lasso_nothing(&mut app); + assert_eq!(app.ui.status, size, "the status bar names the limit now"); + assert_eq!(app.session.journal.since(recording_start(&app).unwrap()).len(), 1, "the journal keeps the step"); + app.run(STOP_RECORDING, json!({})).unwrap(); + assert_eq!(app.ui.action_sets[0].actions[0].steps.len(), 1, "the step is left out"); + let saved = files::write_set(&app.ui.action_sets[0]); + assert!(saved.len() <= files::MAX_SET_FILE); + assert!(files::read_set(&saved, "Test").is_ok()); + } + + /// The place cursor's `file.place` that takes a recording past 10,000 steps keeps the placed + /// file and the journal, and the status bar names the limit once the file is placed: on the + /// release when the file is read at once, and on the frame that places it when it is read off + /// the UI thread. Stop Playing/Recording keeps the 10,000 steps that fit. + #[test] + fn place_cursor_exec_checks_recording_step_limit_on_completion() { + let steps = "the action already has 10,000 steps"; + let mut png = vec![]; + image::RgbImage::new(8, 8).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let placed = |app: &VectorcraftApp| { + let st = app.session.active().unwrap(); + st.doc.layers.iter().flat_map(|l| l.children().into_iter().flatten()).filter(|n| n.name.as_deref() == Some("a.png")).count() + }; + for background in [false, true] { + let (mut app, _) = app_with_three_moves(); + app.placing.off_the_ui_thread = background; + app.run("file.place.queue", json!({"files": [{"name": "a.png", "dataBase64": vectorcraft_format::base64_encode(&png)}]})).unwrap(); + assert_eq!(app.session.tool_id(), "place"); + recording_with(&mut app, files::MAX_ACTION_STEPS); + app.ui.status.clear(); + let journal = app.session.journal.len(); + tool_drag(&mut app, (40.0, 40.0), (80.0, 80.0)); + if background { + assert_eq!(app.session.journal.len(), journal, "the release places nothing yet"); + assert_eq!(placed(&app), 0); + assert_ne!(app.ui.status, steps, "nothing is checked before the file is placed"); + app.placing.wait_for_reads(); + let ctx = egui::Context::default(); + app.begin_host_iteration(); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| app.tick(ui.ctx())); + out.textures_delta.clear(); + assert!(app.placing.pending.is_empty(), "the frame after the read places the file"); + } + assert_eq!(app.session.journal.len(), journal + 1, "background {background}: the place journals one step"); + assert_eq!(app.session.journal.last().map(|(c, _)| c.as_str()), Some("file.place")); + assert_eq!(placed(&app), 1, "background {background}: the placed file stays"); + assert_eq!(app.ui.status, steps, "background {background}: the status bar names the limit once the file is placed"); + assert!(app.ui.recording.is_some(), "the recording goes on"); + app.run(STOP_RECORDING, json!({})).unwrap(); + assert_eq!(app.ui.action_sets[0].actions.last().unwrap().steps.len(), files::MAX_ACTION_STEPS, "background {background}"); + } + } + /// A step that reaches the journal outside a command, as a panel's or a dialog's commit does, is /// checked on the app's next frame. A journal rewrite that makes a checked step larger is /// checked again, and a frame with no new step does not name the limit again. diff --git a/crates/ui-egui/src/panels/asset_export.rs b/crates/ui-egui/src/panels/asset_export.rs index 021bc848c9..39b3a0ea85 100644 --- a/crates/ui-egui/src/panels/asset_export.rs +++ b/crates/ui-egui/src/panels/asset_export.rs @@ -11,6 +11,12 @@ //! marked 3D on their tiles. While the panel's assets include 3D assets, a Format row picks their //! mesh format (USDA, USDZ, glTF or OBJ), and Export writes them as mesh files beside the pictures. //! +//! The panel menu also holds Format Settings… (Export for Screens showing the first row's format +//! settings), and Create Sub-folders and Open Location after Export, the dialog's two checkboxes, +//! which Export follows. Create Sub-folders sorts the pictures into a folder per format row, or per +//! format or item when Export for Screens remembers that choice; 3D assets' mesh files go in the +//! folder itself. +//! //! Everything runs through the `assets.*` commands. use std::cell::RefCell; @@ -26,7 +32,7 @@ use vectorcraft_engine::cmd::fileio::{FORMATS_3D, SCREEN_SETTINGS_KEYS, format_3 use super::{pstate, set_pstate}; use crate::dialogs::{ EXPORT_FOR_SCREENS, ScreenPresetPick, drop_unread_screen_settings, open_export_for_screens_assets, screen_export_preset, screen_formats, - screen_import_presets, screen_preset_list, screen_saved_options, screen_saved_rows, + screen_import_presets, screen_preset_list, screen_saved_options, screen_saved_rows, screen_settings_format, }; use crate::state::Dialog; use crate::theme::Tokens; @@ -229,7 +235,14 @@ fn export_now(app: &mut VectorcraftApp, ids: Vec, files_each: usize) { let (three_d, ids): (Vec, Vec) = ids.into_iter().partition(|id| format(id).is_some()); // An OBJ is two files. let mesh_files: usize = three_d.iter().map(|id| if format(id).as_deref() == Some("obj") { 2 } else { 1 }).sum(); - let mut p = json!({ "assets": ids }); + // Create Sub-folders as the panel menu checks it: on by default, and remembered folders (per + // row, format or item) are used as Export for Screens uses them (a remembered `subfolders` + // false beside them would alone put every file in the folder itself). + let saved = &st.doc.export_settings; + let mut p = keep_subfolders(saved, json!({ "assets": ids })); + if let Some(f) = saved.get("folders").and_then(Value::as_str).filter(|f| !matches!(*f, "none" | "")) { + p["folders"] = json!(f); + } // Match the shared dialog's TIFF defaults, retaining saved choices and other formats. if let Some(st) = app.session.active() && screen_saved_rows(&st.doc.export_settings) @@ -267,7 +280,7 @@ fn export_now(app: &mut VectorcraftApp, ids: Vec, files_each: usize) { } }; p["folder"] = json!(folder); - p["openLocation"] = json!(saved.get("openLocation").and_then(Value::as_bool).unwrap_or(true)); + p["openLocation"] = json!(open_location(&saved)); } let mut meshes = json!({ "assets": three_d }); if io::is_web(app) { @@ -290,6 +303,43 @@ fn export_now(app: &mut VectorcraftApp, ids: Vec, files_each: usize) { } } +/// Create Sub-folders for the remembered settings `saved`, as Export for Screens opens on it: off +/// for remembered folders `none`, on for any other remembered folders (a folder per row, format or +/// item); without them the remembered `subfolders`, else on for a document without settings or +/// with a preset's rows. +fn subfolders_on(saved: &serde_json::Map) -> bool { + match saved.get("folders").and_then(Value::as_str) { + // An export reads empty folders as none. + Some("none" | "") => false, + Some(_) => true, + None => saved.get("subfolders").and_then(Value::as_bool).unwrap_or_else(|| saved.is_empty() || screen_saved_rows(saved).1.is_some()), + } +} + +/// `p` (params of `assets.settings.set` or `assets.export`) with `subfolders: true` when `saved` +/// makes no Create Sub-folders choice and it is on by default: the export would otherwise write +/// into the folder itself, and settings `p` adds would turn the default off. +fn keep_subfolders(saved: &serde_json::Map, mut p: Value) -> Value { + if !saved.contains_key("folders") && !saved.contains_key("subfolders") && subfolders_on(saved) { + p["subfolders"] = json!(true); + } + p +} + +/// Open Location after Export for the remembered settings `saved` (on until it is turned off). +fn open_location(saved: &serde_json::Map) -> bool { + saved.get("openLocation").and_then(Value::as_bool).unwrap_or(true) +} + +/// Open Export for Screens on the Assets tab with assets `ids` checked, showing the Format Settings +/// of format `format`. +fn format_settings(app: &mut VectorcraftApp, ids: &[u64], format: &str) { + open_export_for_screens_assets(app, Some(ids)); + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("__settings".into(), json!(format)); + } +} + /// What the export settings rows asked for. enum Settings { /// Change the shared settings (`assets.settings.set`). @@ -328,7 +378,7 @@ fn settings(ui: &mut Ui, st: &DocState) -> (Option, usize) { Some(Settings::Set(json!({ "preset": picked, "subfolders": true }))) } else if picked != preset || formats.as_array() != Some(&rows) { // Rows edited, or Custom picked: the rows as they are, without the preset. - Some(Settings::Set(json!({ "formats": formats, "preset": "" }))) + Some(Settings::Set(keep_subfolders(&st.doc.export_settings, json!({ "formats": formats, "preset": "" })))) } else { None }; @@ -432,12 +482,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { Some(Settings::Set(p)) => { run(app, "assets.settings.set", p); } - Some(Settings::Format(f)) => { - open_export_for_screens_assets(app, Some(&sel_or_all(&sel, &all))); - if let Some(d) = app.ui.dialog.as_mut() { - d.fields.insert("__settings".into(), json!(f)); - } - } + Some(Settings::Format(f)) => format_settings(app, &sel_or_all(&sel, &all), &f), None => {} } if let Some(pick) = save_pick { @@ -575,6 +620,9 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let doc = st.uid; let (has_art, sel) = (!st.selection.is_empty(), selected(&ctx, st)); let all: Vec = st.doc.assets.iter().map(|a| a.id).collect(); + let saved = &st.doc.export_settings; + let (subfolders, open_after) = (subfolders_on(saved), open_location(saved)); + let settings_format = screen_settings_format(&screen_saved_rows(saved).0); if menu_item(ui, tl!("Add Selected Artwork as One Asset"), has_art, false) { collect(app, &ctx, None, true); } @@ -599,6 +647,17 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { if menu_item(ui, tl!("Export for Screens…"), true, false) { open_export_for_screens_assets(app, Some(&sel_or_all(&sel, &all))); } + if menu_item(ui, tl!("Format Settings…"), true, false) { + format_settings(app, &sel_or_all(&sel, &all), settings_format); + } + ui.separator(); + if menu_item(ui, tl!("Create Sub-folders"), true, subfolders) { + run(app, "assets.settings.set", json!({ "subfolders": !subfolders })); + } + // The web downloads the files: there is no location to open. + if !io::is_web(app) && menu_item(ui, tl!("Open Location after Export"), true, open_after) { + run(app, "assets.settings.set", json!({ "openLocation": !open_after })); + } ui.separator(); let (preset_doc, current): (u64, String) = pstate(&ctx, PRESET); let current = if preset_doc == doc { current } else { String::new() }; diff --git a/crates/ui-egui/src/panels/character.rs b/crates/ui-egui/src/panels/character.rs index d003fbcbce..32de20ec95 100644 --- a/crates/ui-egui/src/panels/character.rs +++ b/crates/ui-egui/src/panels/character.rs @@ -108,6 +108,20 @@ pub(crate) fn shared(app: &VectorcraftApp, f: impl Fn(&CharStyle) shared_styles(app, |_, _, style, _| Some(f(style))) } +/// The fonts (family and style) of the character styles the panels act on ([`shared`]), each +/// once, in the order the runs come. +pub(crate) fn selected_fonts(app: &VectorcraftApp) -> Vec<(String, String)> { + let fonts = std::cell::RefCell::new(Vec::<(String, String)>::new()); + shared_styles(app, |_, _, style, _| { + let mut fonts = fonts.borrow_mut(); + if !fonts.iter().any(|(family, face)| *family == style.font_family && *face == style.font_style) { + fonts.push((style.font_family.clone(), style.font_style.clone())); + } + Some(()) + }); + fonts.into_inner() +} + /// Dimensional controls use document units and tolerate arithmetic roundoff when comparing /// compensated runs. Keep raw styles available to font/paragraph controls and style definitions, /// even if a collapsed affine prevents editing dimensions. @@ -143,33 +157,52 @@ fn shared_styles( app: &VectorcraftApp, f: impl Fn(&vectorcraft_doc::TextObject, &vectorcraft_doc::ParaStyle, &CharStyle, bool) -> Option, ) -> Option { - let st = app.session.active()?; + let mut acc = Shared::None; + each_style(app, |t, para, style, inline| acc.add(f(t, para, style, inline))); + acc.value().flatten() +} + +/// Whether `f` holds for any of the character styles [`shared`] reads. +pub(crate) fn any_style(app: &VectorcraftApp, f: impl Fn(&CharStyle) -> bool) -> bool { + let mut any = false; + each_style(app, |_, _, style, _| any = any || f(style)); + any +} + +/// Call `f` with each character style the panels act on, as [`shared_styles`] describes: the +/// caret's style at a Type tool caret, else each piece of the runs the Type tool's selection +/// covers, else of every run of every frame of the selected stories. +fn each_style(app: &VectorcraftApp, mut f: impl FnMut(&vectorcraft_doc::TextObject, &vectorcraft_doc::ParaStyle, &CharStyle, bool)) { + let Some(st) = app.session.active() else { + return; + }; let text = |id: NodeId| match st.doc.node(id).map(|n| &n.kind) { Some(NodeKind::Text(t)) => Some(t), _ => None, }; - let mut acc = Shared::None; if let Some((id, a, b)) = text_editing(app) { - let t = text(id)?; + let Some(t) = text(id) else { + return; + }; if b <= a { let para = t.plain_text().get(..a).map_or(0, |s| s.bytes().filter(|&c| c == b'\n').count()); - return f(t, t.para_at(para), &vectorcraft_text::edit::insertion_style(&t.runs, a, b), false); + f(t, t.para_at(para), &vectorcraft_text::edit::insertion_style(&t.runs, a, b), false); + return; } match text_story(app) { // After Select All in threaded text: all the text of every frame of the story. Some(story) => { for t in story.into_iter().filter_map(text) { - each_paragraph_run(t, None, |para, style, inline| acc.add(f(t, para, style, inline))); + each_paragraph_run(t, None, |para, style, inline| f(t, para, style, inline)); } } - None => each_paragraph_run(t, Some((a, b)), |para, style, inline| acc.add(f(t, para, style, inline))), + None => each_paragraph_run(t, Some((a, b)), |para, style, inline| f(t, para, style, inline)), } } else { for t in selected_story_texts(app) { - each_paragraph_run(t, None, |para, style, inline| acc.add(f(t, para, style, inline))); + each_paragraph_run(t, None, |para, style, inline| f(t, para, style, inline)); } } - acc.value().flatten() } /// `f` of the paragraph and style of each piece of `t`'s runs that lies in one paragraph (a diff --git a/crates/ui-egui/src/panels/character/tests.rs b/crates/ui-egui/src/panels/character/tests.rs index cdeafd2b00..adaf523e53 100644 --- a/crates/ui-egui/src/panels/character/tests.rs +++ b/crates/ui-egui/src/panels/character/tests.rs @@ -651,6 +651,8 @@ fn reset_panel_closes_only_its_own_undo_group() { app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); assert_eq!(app.session.active_index(), Some(1)); let b = app.run("text.create", json!({"x": 20, "y": 50, "text": "B"})).unwrap()["id"].clone(); + // A reset that changes nothing records no step, so B starts away from the panel's defaults. + app.run("text.setFormat", json!({"id": b, "antiAlias": "crisp"})).unwrap(); app.session.set_active(0); app.run("edit.undoGroup.begin", json!({"label": "Batch"})).unwrap(); app.run("text.setFormat", json!({"id": a, "antiAlias": "none"})).unwrap(); diff --git a/crates/ui-egui/src/panels/color/tests.rs b/crates/ui-egui/src/panels/color/tests.rs index cd7b88cdd0..bd605eef01 100644 --- a/crates/ui-egui/src/panels/color/tests.rs +++ b/crates/ui-egui/src/panels/color/tests.rs @@ -949,6 +949,60 @@ fn a_mixed_selection_has_no_colour_to_edit() { assert_eq!(crate::panels::mixed_paints(&app, &ctx), (false, false), "a new revision recomputes it"); } +/// With gradient mesh points picked, the panel edits and shows their color (a solid fill +/// recolors just them), not the mesh object's fill, so the sliders keep the value they set, +/// through a drag too; "?" when the picked points differ, which picking alone (no new revision) +/// updates. The Control bar's opacity is the picked point's. +#[test] +fn picked_mesh_points_are_the_color_the_panel_shows_and_edits() { + use vectorcraft_doc::NodeKind; + use vectorcraft_engine::ViewInfo; + use vectorcraft_tools::{PointerEvent, PointerKind}; + let mut app = app(); + let ctx = egui::Context::default(); + let id = app.session.active().unwrap().selection.objects[0]; + app.run("paint.setFill", json!({"color": "#ff8500"})).unwrap(); + app.run("object.mesh.create", json!({"rows": 2, "cols": 2})).unwrap(); + app.run("object.mesh.setPointColor", json!({"id": id.0, "index": 0, "color": "#0000ff", "opacity": 0.5})).unwrap(); + let v = ViewInfo::default(); + app.session.select_tool("mesh", v).unwrap(); + let click = |app: &mut VectorcraftApp, x: f64, y: f64, shift: bool| { + for k in [PointerKind::Down, PointerKind::Up] { + let mut ev = PointerEvent::new(k, x, y); + ev.mods.shift = shift; + app.session.pointer(&ev, v).unwrap(); + } + }; + let picked = |app: &VectorcraftApp| app.session.fill_mesh_points().into_iter().flat_map(|(_, v)| v).collect::>(); + // The top-left corner point (index 0). + click(&mut app, 10.0, 10.0, false); + assert_eq!(picked(&app), vec![0], "the click picks the top-left point"); + frame(&mut app, &ctx, vec![], egui::Modifiers::NONE); + assert_eq!(crate::panels::mixed_paints(&app, &ctx), (false, false)); + let tgt = target_with(&app, false); + assert_eq!(tgt.color().map(|c| c.to_hex()), Some("#0000ff".into()), "the picked point's color, not the object's fill"); + assert_eq!(crate::panels::current_transparency(&app).map(|t| t.0), Some(0.5), "the picked point's opacity"); + // A slider drag: each step shows the color it set, and the release keeps it. + for c in [Color::rgb8(250, 0, 120), Color::rgb8(240, 10, 140)] { + let tgt = target_with(&app, false); + apply(&mut app, &tgt, c, Live::Dragging, false); + assert_eq!(target_with(&app, false).color(), Some(c), "the drag shows the color it set"); + } + let orange = Color::rgb8(255, 128, 0); + let tgt = target_with(&app, false); + apply(&mut app, &tgt, orange, Live::Released, false); + assert_eq!(target_with(&app, false).color(), Some(orange), "the panel keeps the color it set"); + let NodeKind::Mesh(m) = &app.session.active().unwrap().doc.node(id).unwrap().kind else { panic!("still a gradient mesh") }; + assert_eq!(m.points[0].color, orange); + let middle = m.idx(0, 1); + assert_ne!(m.points[middle].color, orange, "only the picked point"); + assert_eq!(crate::panels::mixed_paints(&app, &ctx), (false, false)); + // Shift-click the top middle point (still the object's color): the two differ. + click(&mut app, 35.0, 10.0, true); + assert_eq!(picked(&app), vec![0, middle], "the Shift-click adds the top middle point"); + assert_eq!(crate::panels::mixed_paints(&app, &ctx), (true, false), "picking recomputes it"); +} + #[test] fn rgb_roundtrip() { let c = Color::rgb8(230, 120, 40); diff --git a/crates/ui-egui/src/panels/glyphs.rs b/crates/ui-egui/src/panels/glyphs.rs index 7c0a18d14f..998b737c09 100644 --- a/crates/ui-egui/src/panels/glyphs.rs +++ b/crates/ui-egui/src/panels/glyphs.rs @@ -9,12 +9,14 @@ //! that glyph as one of its alternates in its word. A glyph no feature reaches whose name does //! not belong to another letter is applied as a glyph choice, which may not join. Other glyphs //! are drawn dimmed, and their tooltips say why they cannot be applied to the selection. +//! With Show East Asian Options, the panel menu sets the selected characters' East Asian glyph +//! form ([`glyph_form_items`]). use std::collections::HashMap; use egui::{Color32, Sense, Stroke, StrokeKind, Ui, vec2}; use serde_json::json; -use vectorcraft_doc::{CharStyle, NodeId, NodeKind}; +use vectorcraft_doc::{CharStyle, GlyphForm, NodeId, NodeKind}; use vectorcraft_geom::{Affine, BezPath, PathEl}; use vectorcraft_text::FontDb; @@ -564,6 +566,129 @@ fn apply_alternate(app: &mut VectorcraftApp, id: NodeId, bytes: (usize, usize), } } +/// The most alternate glyphs the canvas shows beside a selected character. Public behavior: at +/// most five alternates show on the canvas, and an icon to their right opens the Glyphs panel when +/// the font has more ("Replace a character with on-canvas alternate glyphs", +/// ). +pub(crate) const ON_CANVAS_ALTERNATES: usize = 5; + +/// The alternate glyphs the canvas offers beside the Type tool's one selected character +/// ([`on_canvas`]). +pub(crate) struct OnCanvas { + /// The text the character is in. + pub id: NodeId, + /// The character's bytes in the text, start and end. + pub bytes: (usize, usize), + /// The face that draws the character's glyph. + face: std::sync::Arc, + /// Up to [`ON_CANVAS_ALTERNATES`] glyphs, none of them the glyph the character is drawn with. + cells: Vec, + /// Whether the character has alternates that [`Self::cells`] leaves out. + pub more: bool, + features: Vec, + has_choice: bool, +} + +impl OnCanvas { + /// How many glyphs are offered: 1 to [`ON_CANVAS_ALTERNATES`]. + pub fn count(&self) -> usize { + self.cells.len() + } + + /// The id of glyph `i`. + #[cfg(test)] + pub fn gid(&self, i: usize) -> Option { + self.cells.get(i).map(|c| c.gid) + } + + /// The preview of glyph `i` in a square of `px` pixels. + pub fn texture(&self, ctx: &egui::Context, i: usize, px: u32) -> Option { + self.cells.get(i).map(|c| glyph_texture(ctx, &self.face, c.gid, px)) + } + + /// The tooltip of glyph `i`: its id, the feature that draws it, and what a click does. + pub fn tip(&self, i: usize) -> String { + let Some(c) = self.cells.get(i) else { return String::new() }; + let glyph = crate::i18n::fmt(tl!("glyph {id}"), &[("id", &c.gid.to_string())]); + let glyph = match (&c.apply, c.default) { + (_, true) => glyph, + (Some(tag), _) => format!("{glyph} ({tag})"), + (None, _) => format!("{glyph} ({})", String::from_utf8_lossy(&c.feature)), + }; + let mut tip = format!("{glyph}\n{}", tl!("Click to replace")); + if !c.default && c.apply.is_none() { + tip.push('\n'); + tip.push_str(tl!("No OpenType feature draws this glyph here, so it replaces the character's glyph and may not join its neighbors.")); + } + tip + } + + /// Draw the character with glyph `i`, as a double-click on that glyph in Show › Alternates for + /// Current Selection does: one command, so one undo step. + pub fn pick(&self, app: &mut VectorcraftApp, i: usize) { + let Some(c) = self.cells.get(i) else { return }; + let pick = match (&c.apply, c.default) { + (_, true) => Pick::Default, + (Some(tag), _) => Pick::Feature(tag.clone()), + (None, _) => Pick::Glyph(c.gid), + }; + super::character::end_typing(app); + apply_alternate(app, self.id, self.bytes, &self.features, self.has_choice, pick); + } +} + +/// What the canvas offers beside the Type tool's selection: the alternates of the selected +/// character as it stands in its word ([`alternates_found`], found once for each document +/// revision), in the font's order and without the glyph the character is drawn with. A character +/// drawn with an alternate gets its default glyph first. `None` unless the Type tool's selection +/// is exactly one character of one type object whose font is available and gives it another glyph. +pub(crate) fn on_canvas(app: &VectorcraftApp, ui: &Ui) -> Option { + let (_, a, b) = super::character::text_editing(app)?; + if a == b || super::character::text_story(app).is_some() { + return None; + } + let target = selected_target(app)?; + let (start, end) = (a.min(b), a.max(b)); + if target.byte != start || start + target.ch.len_utf8() != end { + return None; + } + let db = FontDb::global(); + let face = db.style_face(target.style).filter(|_| db.has_family(&target.style.font_family))?; + let found = alternates_found(app, ui, target.id, start, face.id())?; + let face = db.face_by_id(found.font_id).unwrap_or(face); + let default = (found.default != found.current).then_some(Variant { gid: found.default, feature: [0; 4], apply: None, default: true }); + let others = found.alternates.iter().filter(|a| a.gid != found.default && a.gid != found.current).map(|a| Variant { + gid: a.gid, + feature: a.feature, + apply: a.apply.clone(), + default: false, + }); + let mut cells: Vec = default.into_iter().chain(others).collect(); + if cells.is_empty() { + return None; + } + let more = cells.len() > ON_CANVAS_ALTERNATES; + cells.truncate(ON_CANVAS_ALTERNATES); + Some(OnCanvas { + id: target.id, + bytes: (start, end), + face, + cells, + more, + features: target.style.features.clone(), + has_choice: target.style.glyph_alternate.is_some(), + }) +} + +/// Show the Glyphs panel on Show › Alternates for Current Selection, for the canvas's control that +/// stands for the alternates it leaves out. A panel that is already shown stays where it is. +pub(crate) fn show_alternates(app: &mut VectorcraftApp, ctx: &egui::Context) { + set_pstate(ctx, "gl-subset", SUBSETS.len()); + if let Err(e) = crate::panel_docking::reveal_panel(app, "glyphs") { + app.status(e); + } +} + /// The Type tool's selected character, and what its word offers, for a double-click on a glyph no /// character maps in Show › Entire Font ([`Fit::pick`]). struct Fit { @@ -781,11 +906,115 @@ fn zoom_button(ui: &mut Ui, id: &str, label: &str, tip: &str, enabled: bool) -> resp.on_hover_text(tl!(tip)).clicked() && enabled } -pub fn menu(_app: &mut VectorcraftApp, ui: &mut Ui) { +/// The menu label of East Asian glyph form `form` ([`GlyphForm::ALL`]). +fn glyph_form_label(form: GlyphForm) -> &'static str { + match form { + GlyphForm::Traditional => "Traditional Forms", + GlyphForm::Expert => "Expert Forms", + GlyphForm::Jis04 => "JIS 04 Forms", + GlyphForm::Jis90 => "JIS 90 Forms", + GlyphForm::Jis78 => "JIS 78 Forms", + GlyphForm::Jis83 => "JIS 83 Forms", + GlyphForm::FullWidth => "Monospaced Full-Width Forms", + GlyphForm::HalfWidth => "Monospaced Half-Width Forms", + GlyphForm::ThirdWidth => "Monospaced Third-Width Forms", + GlyphForm::QuarterWidth => "Monospaced Quarter-Width Forms", + GlyphForm::Default => "Revert To Default Forms", + } +} + +/// The ids of the faces that draw the characters [`glyph_form_items`] acts on: the faces the +/// fonts of their styles name, and the faces layout draws them with, fallback faces included: +/// the Type tool's selected range (every frame of its story after Select All in threaded text, +/// the whole text object at a caret), else every frame of the selected stories. Laid out once for +/// each document revision, selection and set of fonts while the menu is open, overflow text +/// included. +fn selection_faces(app: &VectorcraftApp, ui: &Ui) -> Vec { + type Key = (u64, u64, u64, Option<(NodeId, usize, usize)>, Vec); + let editing = super::character::text_editing(app).map(|(id, a, b)| (id, a.min(b), a.max(b))); + let Some(state) = app.session.active() else { return vec![] }; + let story = super::character::text_story(app); + let stories = match editing { + Some(_) => story.clone().unwrap_or_default(), + None => super::character::selected_stories(app), + }; + let db = FontDb::global(); + let key: Key = (state.uid, state.revision, db.generation(), editing, stories); + let slot = ui.scope_id().with("gl-form-faces"); + if let Some((cached, ids)) = ui.ctx().data(|d| d.get_temp::<(Key, Vec)>(slot)) + && cached == key + { + return ids; + } + let mut ids: Vec = + super::character::selected_fonts(app).iter().filter_map(|(family, style)| db.face(family, style)).map(|f| f.id()).collect(); + let mut add = |t: &vectorcraft_doc::TextObject, range: Option<(usize, usize)>| { + // Laid out as point type, so that text overflowing its area or path counts too. + let mut all = t.clone(); + all.kind = vectorcraft_doc::TextKind::Point; + for g in vectorcraft_text::layout(db, &all).glyphs { + // A glyph counts when its characters overlap the range (a ligature may start before it). + if range.is_none_or(|(a, b)| g.byte < b && g.byte + g.len.max(1) > a) && !ids.contains(&g.font_id) { + ids.push(g.font_id); + } + } + }; + let text = |id: NodeId| match state.doc.node(id).map(|n| &n.kind) { + Some(NodeKind::Text(t)) => Some(t), + _ => None, + }; + match (editing, story) { + // After Select All in threaded text: every frame of the story. + (Some(_), Some(frames)) => frames.into_iter().filter_map(text).for_each(|t| add(t, None)), + (Some((id, a, b)), None) => { + if let Some(t) = text(id) { + // A caret applies the form to all the text of the object. + add(t, (a < b).then_some((a, b))); + } + } + (None, _) => super::character::selected_story_texts(app).into_iter().for_each(|t| add(t, None)), + } + ui.ctx().data_mut(|d| d.insert_temp(slot, (key, ids.clone()))); + ids +} + +/// The East Asian glyph forms of the panel menu, with Show East Asian Options: each draws the +/// selected characters (all the text of the selected type objects without a Type tool range) in +/// one form of their font, and is checked when they all have it; a form none of the faces that +/// draw the selected text has a feature for ([`selection_faces`]) is disabled. Revert To Default +/// Forms draws the font's default glyphs. +/// Public behavior: [Format East Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html) +/// (Replace Asian characters with a different glyph form). +fn glyph_form_items(app: &mut VectorcraftApp, ui: &mut Ui) { + let has = super::character::text_style(app).is_some(); + let db = FontDb::global(); + let faces: Vec<_> = selection_faces(app, ui).into_iter().filter_map(|id| db.face_by_id(id)).collect(); + let current = super::character::shared(app, |s| s.glyph_form); + for form in GlyphForm::ALL { + let enabled = match form.feature() { + Some(tag) => faces.iter().any(|f| f.has_substitution_feature(*tag)), + None => has, + }; + let checked = form != GlyphForm::Default && current == Some(form); + if form == GlyphForm::Default { + ui.separator(); + } + // Choosing the form every selected character already has changes nothing. + if menu_item(ui, tl!(glyph_form_label(form)), enabled, checked) && current != Some(form) { + super::character::format(app, json!({"glyphForm": form.id()})); + } + } +} + +pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { if menu_item(ui, tl!("Use the Selected Text's Font"), true, false) { set_pstate::>(ui.ctx(), "gl-font", None); } ui.separator(); + if app.session.prefs.show_east_asian_options { + glyph_form_items(app, ui); + ui.separator(); + } for (i, (name, _, _)) in SUBSETS.iter().enumerate() { let cur: usize = pstate(ui.ctx(), "gl-subset"); if menu_item(ui, tl!(name), true, cur == i) { @@ -979,6 +1208,59 @@ mod tests { text_anchors(&shapes(ctx, app, vec![])).into_iter().map(|(t, _)| t).collect() } + /// With Show East Asian Options, the panel menu lists the East Asian glyph forms; choosing one + /// draws the Type tool's selected characters in it, checks it, and Revert To Default Forms + /// takes it away. A form the font has no feature for is disabled. The second half needs + /// craft-fonts' BIZ UDMincho, which has JIS 78 forms and no JIS 04 forms (skipped without it). + #[test] + fn east_asian_glyph_forms_in_the_panel_menu_set_the_selected_characters_form() { + let (mut app, id) = editing("亜唖"); + let ctx = egui::Context::default(); + let labels = |app: &mut VectorcraftApp| menu_texts(&ctx, app, vec![]).into_iter().map(|(t, _)| t).collect::>(); + let plain = |l: &String| l.trim_start_matches(['✓', ' ']).to_string(); + app.session.prefs.show_east_asian_options = false; + assert!(!labels(&mut app).iter().map(plain).any(|l| l == "JIS 78 Forms"), "hidden without Show East Asian Options"); + app.session.prefs.show_east_asian_options = true; + let shown: Vec = labels(&mut app).iter().map(plain).collect(); + for form in GlyphForm::ALL { + assert!(shown.iter().any(|l| l == glyph_form_label(form)), "{form:?} in {shown:?}"); + } + const FAMILY: &str = "BIZ UDMincho"; + if FontDb::global().face(FAMILY, "Regular").is_none_or(|f| f.family != FAMILY) { + eprintln!("skipped: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout to run it)"); + return; + } + app.run("text.setRangeStyle", json!({"id": id, "font": FAMILY})).unwrap(); + let forms = |app: &VectorcraftApp| match &app.session.active().unwrap().doc.node(NodeId(id.as_u64().unwrap_or(0))).unwrap().kind { + NodeKind::Text(t) => t.runs.iter().map(|r| (r.text.clone(), r.style.glyph_form)).collect::>(), + _ => panic!("text"), + }; + select(&mut app, 3, 6); + choose(&ctx, &mut app, "JIS 78 Forms"); + assert_eq!(forms(&app), [("亜".to_string(), GlyphForm::Default), ("唖".to_string(), GlyphForm::Jis78)]); + assert!(labels(&mut app).iter().any(|l| l.starts_with('✓') && l.ends_with("JIS 78 Forms")), "checked"); + // A selection whose first font has no JIS 83 forms, and whose second one does, takes them. + let fallback = vectorcraft_text::FALLBACK_FAMILY; + if FontDb::global().face(fallback, "Regular").is_some_and(|f| !f.has_substitution_feature(*b"jp83")) { + app.run("text.setRangeStyle", json!({"id": id, "start": 0, "end": 3, "font": fallback})).unwrap(); + select(&mut app, 0, 6); + choose(&ctx, &mut app, "JIS 83 Forms"); + assert!(forms(&app).iter().all(|(_, f)| *f == GlyphForm::Jis83), "{:?}", forms(&app)); + app.run("text.setRangeStyle", json!({"id": id, "start": 0, "end": 3, "font": FAMILY})).unwrap(); + app.run("text.setRangeStyle", json!({"id": id, "glyphForm": "default"})).unwrap(); + select(&mut app, 3, 6); + choose(&ctx, &mut app, "JIS 78 Forms"); + } + // Choosing it again changes nothing, and the font has no JIS 04 forms: that item is disabled. + let n = app.session.active().unwrap().history.undo.len(); + choose(&ctx, &mut app, "JIS 78 Forms"); + choose(&ctx, &mut app, "JIS 04 Forms"); + assert_eq!(app.session.active().unwrap().history.undo.len(), n); + assert_eq!(forms(&app)[1].1, GlyphForm::Jis78); + choose(&ctx, &mut app, "Revert To Default Forms"); + assert!(forms(&app).iter().all(|(_, f)| *f == GlyphForm::Default), "{:?}", forms(&app)); + } + /// Show › Alternates for Current Selection lists the selected character's alternates from the /// font of its text, whatever font the panel browses; a double-click draws the character with /// one. A character without alternates, no selected character and a missing font each show a diff --git a/crates/ui-egui/src/panels/layers/rows.rs b/crates/ui-egui/src/panels/layers/rows.rs index b898ce8bf8..685da495e4 100644 --- a/crates/ui-egui/src/panels/layers/rows.rs +++ b/crates/ui-egui/src/panels/layers/rows.rs @@ -81,7 +81,9 @@ pub(super) fn drag_ghost(ui: &Ui, view: &View, src: NodeId, pos: egui::Pos2) { } /// Resolve the row clicked this frame: plain (highlight it), Ctrl/Cmd (toggle it) or Shift -/// (highlight the rows from the last one clicked down to it). +/// (highlight the rows from the last one clicked down to it). A plain click also lets go of the +/// selected ruler guides, keeping the selected art (#7340): a guide's row picks it the way a +/// highlight picks a row, so picking another row alone drops it. pub(super) fn resolve_click(ui: &Ui, view: &View, list: &[Row], out: &mut Out) { let Some((id, m)) = out.click.take() else { return }; let anchor: Option = ui.data(|d| d.get_temp(key("anchor"))); @@ -95,6 +97,10 @@ pub(super) fn resolve_click(ui: &Ui, view: &View, list: &[Row], out: &mut Out) { widgets::apply_row_click(&mut rows, &click); out.rows_after_click = Some(rows); let ids = |rows: &[NodeId]| rows.iter().map(|r| r.0).collect::>(); + if matches!(click, widgets::RowClick::Only(_)) && !view.guides.is_empty() { + // Toggled out of the selection, so the selected art stays. + out.actions.push(("guide.select".into(), json!({"indexes": view.guides, "toggle": true}))); + } out.actions.push(match click { widgets::RowClick::Only(id) => ("layer.setCurrent".into(), json!({"id": id.0})), widgets::RowClick::Toggle(id) => ("layer.highlight".into(), json!({"ids": [id.0], "mode": "toggle"})), diff --git a/crates/ui-egui/src/panels/layers/tests.rs b/crates/ui-egui/src/panels/layers/tests.rs index c072a45828..ae058ff348 100644 --- a/crates/ui-egui/src/panels/layers/tests.rs +++ b/crates/ui-egui/src/panels/layers/tests.rs @@ -987,6 +987,48 @@ fn guide_rows_are_deleted_with_the_trash_and_delete() { assert!(kept(&app)); } +/// A plain click on another row lets go of the guide a guide row selected, keeping the selected +/// art, so a guide can be dropped without Ctrl/Cmd-clicking its own row (#7340); a Ctrl/Cmd click +/// on a row adds to the pick and keeps it. +#[test] +fn a_plain_row_click_lets_go_of_the_selected_guide() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let run = |app: &mut VectorcraftApp, id: &str, p: serde_json::Value| app.session.execute(id, &p).unwrap(); + run(&mut app, "file.new", json!({"width": 200, "height": 200})); + let rect = NodeId(run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20}))["id"].as_u64().unwrap()); + run(&mut app, "guide.add", json!({"vertical": true, "pos": 50})); + run(&mut app, "select.none", json!({})); + expand(&mut app, &json!({})).unwrap(); + let ctx = egui::Context::default(); + // Rows top down: Layer 1, its guide (no target circle), the rectangle. + let (circles, _) = frame(&mut app, &ctx, vec![], false); + assert_eq!(circles.len(), 2); + let guide_row = egui::pos2(150.0, (circles[0].y + circles[1].y) / 2.0); + let rect_row = egui::pos2(150.0, circles[1].y); + let guides = |app: &VectorcraftApp| { + let st = app.session.active().unwrap(); + vectorcraft_engine::cmd::guide_indexes(&st.doc, &st.selection.guides) + }; + let art = |app: &VectorcraftApp| app.session.active().unwrap().selection.objects.clone(); + // Guide, then the rectangle's row: the guide is let go and the rectangle's row highlighted. + click_with(&mut app, &ctx, guide_row, egui::Modifiers::NONE); + assert_eq!(guides(&app), [0]); + click_with(&mut app, &ctx, rect_row, egui::Modifiers::NONE); + assert!(guides(&app).is_empty(), "a plain row click drops the guide"); + assert_eq!(app.session.active().unwrap().highlighted_rows(), [rect]); + // Art and a guide selected together: a plain row click drops only the guide. + run(&mut app, "select.all", json!({})); + click_with(&mut app, &ctx, guide_row, egui::Modifiers::SHIFT); + assert_eq!((guides(&app), art(&app)), (vec![0], vec![rect])); + click_with(&mut app, &ctx, egui::pos2(150.0, circles[0].y), egui::Modifiers::NONE); + assert!(guides(&app).is_empty()); + assert_eq!(art(&app), [rect], "the selected art stays"); + // A Ctrl/Cmd click on a row adds that row to the highlight and keeps the guide. + click_with(&mut app, &ctx, guide_row, egui::Modifiers::NONE); + click_with(&mut app, &ctx, rect_row, egui::Modifiers::COMMAND); + assert_eq!(guides(&app), [0], "a Ctrl/Cmd row click keeps the guide"); +} + /// The selection squares drawn: (big ones on rows whose object is selected, small ones on rows /// holding selected art). fn squares(app: &mut VectorcraftApp, ctx: &egui::Context) -> (usize, usize) { diff --git a/crates/ui-egui/src/panels/learn.rs b/crates/ui-egui/src/panels/learn.rs index 5d24167c99..82e139e25c 100644 --- a/crates/ui-egui/src/panels/learn.rs +++ b/crates/ui-egui/src/panels/learn.rs @@ -1,18 +1,24 @@ //! Learn panel (Window › Learn, and Explore tutorials at the right end of the app bar): short //! hands-on tutorials grouped by skill ([`catalog::SKILLS`]). The For you tab holds the Get started //! section with the Quick skill guide card, which opens the Skills tab. The Skills tab lists each -//! skill with an empty progress ring and its count of tutorials; a skill lists its tutorials, and a +//! skill with a progress ring that fills as its tutorials are finished and the count of tutorials +//! finished of all; a skill lists its tutorials, each finished one with a check mark, and a //! tutorial previews its numbered steps. A tool's name in a step is a link that shows where the tool //! is ([`locate`]). Back goes up one level. Under the steps, View more opens the tutorial's practice -//! sample as a new untitled document; Finish tutorial then marks it finished, and Next Up shows the -//! next tutorial in the same skill. `learn.list` lists the tutorials, `learn.skills` shows the list -//! of skills, `learn.show` opens one tutorial, `learn.locateTool` shows where a tool is, -//! `learn.openSample`, `learn.finish` and `learn.next` run the three practice controls, and -//! `window.learn` shows or hides the panel. The Home screen's Learn section shows the same card -//! ([`guide_card`]) and the tutorials, which open the panel. +//! sample as a new untitled document; the check box before each step then marks it done, Finish +//! tutorial marks the tutorial finished with all its steps, and Next Up shows the next tutorial in +//! the same skill. The preferences keep the progress ([`progress`]); Reset progress under the +//! skills clears it. `learn.list` lists the tutorials with their progress, `learn.tab` chooses a +//! tab, `learn.skills` shows the list of skills, `learn.skill` opens one skill, `learn.show` opens +//! one tutorial, `learn.back` goes up one level, `learn.locateTool` shows where a tool is, +//! `learn.openSample`, `learn.markStep`, `learn.finish` and `learn.next` run the practice controls, +//! `learn.resetProgress` clears the progress, and `window.learn` shows or hides the panel. The Home +//! screen's Learn section shows the same card ([`guide_card`]) and the tutorials, which open the +//! panel. pub mod catalog; pub mod locate; +pub mod progress; pub mod samples; use egui::{Sense, Stroke, Ui, vec2}; @@ -41,22 +47,29 @@ pub struct View { pub tutorial: Option<&'static str>, } -/// The tutorials whose samples View more opened, and the tutorials finished, in the order they -/// were finished. Each id is listed once. +/// The tutorials whose samples View more opened while the app runs. Each id is listed once. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct Practice { pub opened: Vec<&'static str>, - pub finished: Vec<&'static str>, } +/// Each tab with the name `learn.tab` takes for it. +const TABS: [(Tab, &str); 2] = [(Tab::ForYou, "forYou"), (Tab::Skills, "skills")]; + pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { + let mut chosen = None; ui.horizontal(|ui| { - for (tab, label) in [(Tab::ForYou, tl!("For you")), (Tab::Skills, tl!("Skills"))] { - if ui.selectable_label(app.ui.learn.tab == tab, label).clicked() { - app.ui.learn.tab = tab; + for ((tab, name), label) in TABS.into_iter().zip([tl!("For you"), tl!("Skills")]) { + if ui.selectable_label(app.ui.learn.tab == tab, label).clicked() && app.ui.learn.tab != tab { + chosen = Some(name); } } }); + if let Some(name) = chosen + && let Err(e) = app.run("learn.tab", json!({ "tab": name })) + { + app.status(e); + } crate::widgets::divider(ui); match app.ui.learn.tab { Tab::ForYou => for_you(app, ui), @@ -110,49 +123,71 @@ pub(crate) fn guide_card(app: &mut VectorcraftApp, ui: &mut Ui, id: egui::Id, fi /// The Skills tab: the skills, a skill's tutorials, or a tutorial's steps. fn skills(app: &mut VectorcraftApp, ui: &mut Ui) { + let mut run = None; let open = app.ui.learn.tutorial.and_then(catalog::tutorial); - if let Some((skill, tutorial)) = open { + if let Some((_, tutorial)) = open { if back(ui) { - app.ui.learn.skill = Some(skill.id); - app.ui.learn.tutorial = None; + run = Some(("learn.back", json!({}))); } steps(app, ui, tutorial); practice(app, ui, tutorial); - return; - } - if let Some(skill) = app.ui.learn.skill.and_then(catalog::skill) { + } else if let Some(skill) = app.ui.learn.skill.and_then(catalog::skill) { if back(ui) { - app.ui.learn.skill = None; + run = Some(("learn.back", json!({}))); } crate::widgets::subheader(ui, skill.title); for tutorial in skill.tutorials { - if row(ui, tutorial.title, None).clicked() { - app.ui.learn.tutorial = Some(tutorial.id); + if row(ui, tutorial.title, Mark::Check(app.ui.learn_progress.is_finished(tutorial.id))).clicked() { + run = Some(("learn.show", json!({ "tutorial": tutorial.id }))); } } - return; - } - for skill in catalog::SKILLS { - if row(ui, skill.title, Some(skill.tutorials.len())).clicked() { - app.ui.learn.skill = Some(skill.id); + } else { + for skill in catalog::SKILLS { + let ring = Mark::Ring { done: app.ui.learn_progress.done(skill), total: skill.tutorials.len() }; + if row(ui, skill.title, ring).clicked() { + run = Some(("learn.skill", json!({ "skill": skill.id }))); + } } + if !app.ui.learn_progress.is_empty() { + ui.add_space(6.0); + if ui.button(tl!("Reset progress")).clicked() { + run = Some(("learn.resetProgress", json!({}))); + } + } + } + if let Some((cmd, params)) = run + && let Err(e) = app.run(cmd, params) + { + app.status(e); } } -/// The Back button above a skill's tutorials and a tutorial's steps; true when it was clicked. +/// The Back button above a skill's tutorials and a tutorial's steps (`learn.back`); true when it +/// was clicked. fn back(ui: &mut Ui) -> bool { crate::widgets::icon_button(ui, "chevron-left", tl!("Back"), false, 22.0).clicked() } -/// A tutorial's title and its numbered steps. The tool's name in a step is a blue link: a click, or -/// Enter or Space while it has the keyboard focus, shows where the tool is (`learn.locateTool`). -fn steps(app: &mut VectorcraftApp, ui: &mut Ui, tutorial: &catalog::Tutorial) { +/// A tutorial's title and its numbered steps, each with a check box that shows whether it is done. +/// The check boxes can be changed once the tutorial's sample is open and until it is finished +/// (`learn.markStep`). The tool's name in a step is a blue link: a click, or Enter or Space while it +/// has the keyboard focus, shows where the tool is (`learn.locateTool`). +fn steps(app: &mut VectorcraftApp, ui: &mut Ui, tutorial: &'static catalog::Tutorial) { let t = Tokens::get(ui.ctx()); ui.label(egui::RichText::new(tutorial.title).size(13.0).color(t.text_strong)); ui.add_space(4.0); + let markable = app.ui.learn_practice.opened.contains(&tutorial.id) && !app.ui.learn_progress.is_finished(tutorial.id); let mut locate = None; + let mut marked = None; for (i, step) in tutorial.steps.iter().enumerate() { + let mut done = app.ui.learn_progress.step_done(tutorial, i); ui.horizontal_top(|ui| { + let resp = ui.add_enabled(markable, egui::Checkbox::without_text(&mut done)); + let name = format!("{}. {}", i + 1, step.plain()); + resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, markable, done, &name)); + if resp.changed() { + marked = Some((i, done)); + } ui.label(egui::RichText::new(format!("{}.", i + 1)).color(t.text_dim)); let (Some(tool), Some((before, name, after))) = (step.tool, step.tool_name()) else { ui.add(egui::Label::new(egui::RichText::new(step.text).color(t.text)).wrap()); @@ -173,6 +208,11 @@ fn steps(app: &mut VectorcraftApp, ui: &mut Ui, tutorial: &catalog::Tutorial) { }); ui.add_space(2.0); } + if let Some((step, complete)) = marked + && let Err(e) = app.run("learn.markStep", json!({ "tutorial": tutorial.id, "step": step, "complete": complete })) + { + app.status(e); + } if let Some(tool) = locate { if let Err(e) = app.run("learn.locateTool", json!({ "tool": tool })) { app.status(e); @@ -205,12 +245,11 @@ fn practice(app: &mut VectorcraftApp, ui: &mut Ui, tutorial: &'static catalog::T if ui.button(tl!("View more")).clicked() { run = Some(("learn.openSample", params.clone())); } - let done = &app.ui.learn_practice; - if done.opened.contains(&id) && !done.finished.contains(&id) && ui.button(tl!("Finish tutorial")).clicked() { + if app.ui.learn_practice.opened.contains(&id) && !app.ui.learn_progress.is_finished(id) && ui.button(tl!("Finish tutorial")).clicked() { run = Some(("learn.finish", params.clone())); } }); - if app.ui.learn_practice.finished.contains(&id) { + if app.ui.learn_progress.is_finished(id) { ui.add_space(6.0); match catalog::next(id) { Some(next) => { @@ -236,46 +275,115 @@ fn practice(app: &mut VectorcraftApp, ui: &mut Ui, tutorial: &'static catalog::T } } -/// A clickable row: `title`, and for a skill (`tutorials`) a progress ring before it and the -/// count of tutorials done of all after it. No progress is kept yet, so the ring is empty. -fn row(ui: &mut Ui, title: &str, tutorials: Option) -> egui::Response { +/// What a row shows before its title. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Mark { + /// A skill: a progress ring that fills as its tutorials are finished, and after the title the + /// count of tutorials finished of all. + Ring { done: usize, total: usize }, + /// A tutorial: a check mark once it is finished (true). + Check(bool), +} + +/// The radius of a row's progress ring or check mark. +const MARK_RADIUS: f32 = 7.0; + +/// A clickable row: `title`, with `mark` before it. Screen readers get the count of a skill's +/// tutorials finished, or Finished for a finished tutorial, as the row's value. +fn row(ui: &mut Ui, title: &str, mark: Mark) -> egui::Response { let t = Tokens::get(ui.ctx()); let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::click()); if resp.hovered() { ui.painter().rect_filled(rect, egui::CornerRadius::same(4), t.hover); } + let painter = ui.painter().with_clip_rect(rect); let mut left = rect.left() + 6.0; let mut right = rect.right() - 6.0; let chevron = egui::Rect::from_center_size(egui::pos2(right - 6.0, rect.center().y), vec2(12.0, 12.0)); crate::icons::paint(ui, "chevron-right", chevron, t.text_dim); right = chevron.left() - 6.0; - if let Some(total) = tutorials { - ui.painter().circle_stroke(egui::pos2(left + 8.0, rect.center().y), 7.0, Stroke::new(2.0, t.border)); - left += 24.0; - let count = ui.painter().layout_no_wrap(format!("0/{total}"), egui::FontId::proportional(11.5), t.text_dim); - right -= count.size().x; - ui.painter().galley(egui::pos2(right, rect.center().y - count.size().y / 2.0), count, t.text_dim); - right -= 6.0; - } - let name = ui.painter().layout(title.to_string(), egui::FontId::proportional(12.5), t.text, f32::INFINITY); + let at = egui::pos2(left + 8.0, rect.center().y); + left += 24.0; + let value = match mark { + Mark::Ring { done, total } => { + ring(&painter, &t, at, done, total); + let count = painter.layout_no_wrap(format!("{done}/{total}"), egui::FontId::proportional(11.5), t.text_dim); + right -= count.size().x; + painter.galley(egui::pos2(right, rect.center().y - count.size().y / 2.0), count, t.text_dim); + right -= 6.0; + Some(format!("{done}/{total}")) + } + Mark::Check(finished) => { + check(&painter, &t, at, finished); + finished.then(|| tl!("Finished").to_string()) + } + }; + let name = painter.layout(title.to_string(), egui::FontId::proportional(12.5), t.text, f32::INFINITY); let clip = egui::Rect::from_min_max(egui::pos2(left, rect.top()), egui::pos2(right.max(left), rect.bottom())); - ui.painter().with_clip_rect(clip).galley(egui::pos2(left, rect.center().y - name.size().y / 2.0), name, t.text); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), title)); + painter.with_clip_rect(clip).galley(egui::pos2(left, rect.center().y - name.size().y / 2.0), name, t.text); + resp.widget_info(|| egui::WidgetInfo { + current_text_value: value.clone(), + ..egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), title) + }); resp.on_hover_cursor(egui::CursorIcon::PointingHand) } -/// The Learn panel's UI commands: `window.learn`, `learn.list`, `learn.skills`, `learn.show`, -/// `learn.locateTool`, `learn.openSample`, `learn.finish` and `learn.next`. +/// A skill's progress ring at `center`: an outline, with the share `done` of `total` drawn over it +/// clockwise from the top. With no tutorials it stays empty. +fn ring(painter: &egui::Painter, t: &Tokens, center: egui::Pos2, done: usize, total: usize) { + painter.circle_stroke(center, MARK_RADIUS, Stroke::new(2.0, t.border)); + if done == 0 || total == 0 { + return; + } + let stroke = Stroke::new(2.0, t.accent); + if done >= total { + painter.circle_stroke(center, MARK_RADIUS, stroke); + return; + } + let sweep = std::f32::consts::TAU * done as f32 / total as f32; + // About one segment per 1/32 of a turn, and never fewer than two. + let segments = ((32.0 * done as f32 / total as f32).ceil() as usize).max(2); + let points = (0..=segments) + .map(|k| { + let angle = -std::f32::consts::FRAC_PI_2 + sweep * k as f32 / segments as f32; + center + MARK_RADIUS * vec2(angle.cos(), angle.sin()) + }) + .collect(); + painter.add(egui::Shape::line(points, stroke)); +} + +/// A tutorial's mark at `center`: an outline, filled with a check mark once it is finished. +fn check(painter: &egui::Painter, t: &Tokens, center: egui::Pos2, finished: bool) { + if !finished { + painter.circle_stroke(center, MARK_RADIUS, Stroke::new(1.0, t.border)); + return; + } + painter.circle_filled(center, MARK_RADIUS, t.accent); + let tick = vec![center + vec2(-3.5, 0.0), center + vec2(-1.0, 2.5), center + vec2(3.5, -2.5)]; + painter.add(egui::Shape::line(tick, Stroke::new(1.5, t.panel))); +} + +/// The Learn panel's UI commands: `window.learn`, `learn.list`, `learn.tab`, `learn.skills`, +/// `learn.skill`, `learn.show`, `learn.back`, `learn.locateTool`, `learn.openSample`, +/// `learn.markStep`, `learn.finish`, `learn.next` and `learn.resetProgress`. pub(crate) fn command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option> { Some(match id { "window.learn" => toggle(app, p), - "learn.list" => Ok(list()), + "learn.list" => Ok(list(&app.ui.learn_progress)), + "learn.tab" => tab(app, p), "learn.skills" => skills_list(app), + "learn.skill" => open_skill(app, p), "learn.show" => open(app, p), + "learn.back" => back_up(app), "learn.locateTool" => locate::locate_tool(app, p), "learn.openSample" => open_sample(app, p), + "learn.markStep" => mark_step(app, p), "learn.finish" => finish(app, p), "learn.next" => next(app, p), + "learn.resetProgress" => { + app.ui.learn_progress = progress::Progress::default(); + Ok(list(&app.ui.learn_progress)) + } _ => return None, }) } @@ -300,13 +408,89 @@ fn toggle(app: &mut VectorcraftApp, p: &Value) -> Result { Ok(json!(visible(&app.ui))) } -/// `learn.list`: every skill with its tutorials and their step counts. -fn list() -> Value { - let skills = catalog::SKILLS.iter().map(|s| { - let tutorials: Vec = s.tutorials.iter().map(|t| json!({"id": t.id, "title": t.title, "steps": t.steps.len()})).collect(); - json!({"id": s.id, "title": s.title, "tutorials": tutorials}) - }); - json!({ "skills": skills.collect::>() }) +/// `learn.list`: every skill with its count of tutorials finished (`done`) of all (`total`), and its +/// tutorials with their step counts, whether each is finished, and the zero-based indexes of its +/// steps marked done (`completedSteps`). +fn list(progress: &progress::Progress) -> Value { + json!({ "skills": catalog::SKILLS.iter().map(|s| skill_json(progress, s)).collect::>() }) +} + +/// A skill as `learn.list` lists it: `{id, title, done, total, tutorials: [{id, title, steps, +/// finished, completedSteps}]}`. +fn skill_json(progress: &progress::Progress, s: &catalog::Skill) -> Value { + let tutorials: Vec = s + .tutorials + .iter() + .map(|t| { + json!({ + "id": t.id, + "title": t.title, + "steps": t.steps.len(), + "finished": progress.is_finished(t.id), + "completedSteps": progress.completed_steps(t), + }) + }) + .collect(); + json!({"id": s.id, "title": s.title, "done": progress.done(s), "total": s.tutorials.len(), "tutorials": tutorials}) +} + +/// What the panel shows: `{tab: forYou|skills, skill, tutorial}`, with null for no skill or no +/// tutorial open. +fn view_json(view: &View) -> Value { + let tab = TABS.iter().find(|(t, _)| *t == view.tab).map(|(_, name)| *name); + json!({"tab": tab, "skill": view.skill, "tutorial": view.tutorial}) +} + +/// `learn.tab {tab}`: the For you and Skills tabs. Show the panel on that tab (`forYou` or +/// `skills`); the Skills tab keeps the skill and tutorial it had open → the view ([`view_json`]). A +/// missing or unknown tab is an error and changes nothing. +fn tab(app: &mut VectorcraftApp, p: &Value) -> Result { + let key = "tab"; + let name = match p.get(key) { + None | Some(Value::Null) => return Err(format!("missing `{key}`")), + Some(Value::String(name)) => name.as_str(), + Some(_) => return Err(format!("`{key}` must be a string")), + }; + let names = || TABS.map(|(_, name)| name).join(", "); + let tab = TABS.iter().find(|(_, n)| *n == name).map(|(t, _)| *t).ok_or_else(|| format!("`{key}` must be one of {}", names()))?; + crate::panel_docking::reveal_panel(app, ID)?; + app.ui.learn.tab = tab; + Ok(view_json(&app.ui.learn)) +} + +/// `learn.skill {skill}`: a skill's row on the Skills tab. Show the panel on the Skills tab with +/// that skill's tutorials → the skill, as `learn.list` lists it. A missing or unknown id is an error +/// and changes nothing. +fn open_skill(app: &mut VectorcraftApp, p: &Value) -> Result { + let key = "skill"; + let id = match p.get(key) { + None | Some(Value::Null) => return Err(format!("missing `{key}`")), + Some(Value::String(id)) => id.as_str(), + Some(_) => return Err(format!("`{key}` must be a string")), + }; + let ids = || catalog::SKILLS.iter().map(|s| s.id).collect::>().join(", "); + let skill = catalog::skill(id).ok_or_else(|| format!("`{key}` must be one of {}", ids()))?; + crate::panel_docking::reveal_panel(app, ID)?; + app.ui.learn = View { tab: Tab::Skills, skill: Some(skill.id), tutorial: None }; + Ok(skill_json(&app.ui.learn_progress, skill)) +} + +/// `learn.back`: the Back button on the Skills tab. Show the panel and go up one level: from a +/// tutorial's steps to its skill's tutorials, and from a skill's tutorials to the list of skills → +/// the view ([`view_json`]). On the list of skills or the For you tab the view stays as it is. +fn back_up(app: &mut VectorcraftApp) -> Result { + crate::panel_docking::reveal_panel(app, ID)?; + let view = &mut app.ui.learn; + if view.tab == Tab::Skills { + if let Some((skill, _)) = view.tutorial.and_then(catalog::tutorial) { + view.skill = Some(skill.id); + view.tutorial = None; + } else if view.skill.is_some() { + view.skill = None; + view.tutorial = None; + } + } + Ok(view_json(view)) } /// `learn.skills`: Back to skills, and the Quick skill guide card. Show the panel on the Skills tab @@ -314,7 +498,7 @@ fn list() -> Value { fn skills_list(app: &mut VectorcraftApp) -> Result { crate::panel_docking::reveal_panel(app, ID)?; app.ui.learn = View { tab: Tab::Skills, skill: None, tutorial: None }; - Ok(list()) + Ok(list(&app.ui.learn_progress)) } /// `learn.show {tutorial}`: show the panel on the Skills tab with that tutorial's steps → the @@ -357,19 +541,42 @@ fn open_sample(app: &mut VectorcraftApp, p: &Value) -> Result { Ok(json!({"tutorial": id, "index": opened["index"], "title": opened["title"]})) } -/// `learn.finish {tutorial}`: Finish tutorial. Mark a tutorial whose sample was opened finished → -/// `{tutorial, finished: true, next}`, where `next` is the id of the next tutorial in its skill, or -/// null after the skill's last one. Finishing it again keeps one entry. The Learn view stays as it is. +/// `learn.markStep {tutorial, step, complete?}`: a step's check box. Mark step `step` (zero-based) +/// of a tutorial whose sample was opened done (`complete` true or omitted) or not done (false) → +/// `{tutorial, step, complete}`. A finished tutorial keeps every step done, so marking one of its +/// steps is an error; so are a step the tutorial does not have and a `complete` that is not true or +/// false. An error changes nothing. +fn mark_step(app: &mut VectorcraftApp, p: &Value) -> Result { + let (_, tutorial) = tutorial_param(p)?; + let id = tutorial.id; + let last = tutorial.steps.len().saturating_sub(1); + let step = match p.get("step") { + None | Some(Value::Null) => return Err("missing `step` (see learn.show)".into()), + Some(v) => v.as_u64().and_then(|s| usize::try_from(s).ok()).filter(|s| *s < tutorial.steps.len()), + }; + let step = step.ok_or_else(|| format!("`step` must be a step number from 0 to {last}"))?; + let complete = crate::menus::opt_bool(p, "complete")?.unwrap_or(true); + if !app.ui.learn_practice.opened.contains(&id) { + return Err(format!("open the practice sample of `{id}` first (see learn.openSample)")); + } + if app.ui.learn_progress.is_finished(id) { + return Err(format!("`{id}` is finished (see learn.resetProgress)")); + } + app.ui.learn_progress.mark(id, step, complete); + Ok(json!({"tutorial": id, "step": step, "complete": complete})) +} + +/// `learn.finish {tutorial}`: Finish tutorial. Mark a tutorial whose sample was opened finished, +/// with all its steps done → `{tutorial, finished: true, next}`, where `next` is the id of the next +/// tutorial in its skill, or null after the skill's last one. Finishing it again keeps one entry, +/// also after a restart, when its sample has not been opened again. The Learn view stays as it is. fn finish(app: &mut VectorcraftApp, p: &Value) -> Result { let (_, tutorial) = tutorial_param(p)?; let id = tutorial.id; - let practice = &mut app.ui.learn_practice; - if !practice.opened.contains(&id) { + if !app.ui.learn_practice.opened.contains(&id) && !app.ui.learn_progress.is_finished(id) { return Err(format!("open the practice sample of `{id}` first (see learn.openSample)")); } - if !practice.finished.contains(&id) { - practice.finished.push(id); - } + app.ui.learn_progress.finish(id); Ok(json!({"tutorial": id, "finished": true, "next": catalog::next(id).map(|t| t.id)})) } @@ -379,7 +586,7 @@ fn finish(app: &mut VectorcraftApp, p: &Value) -> Result { fn next(app: &mut VectorcraftApp, p: &Value) -> Result { let (skill, tutorial) = tutorial_param(p)?; let id = tutorial.id; - if !app.ui.learn_practice.finished.contains(&id) { + if !app.ui.learn_progress.is_finished(id) { return Err(format!("finish `{id}` first (see learn.finish)")); } let after = catalog::next(id).ok_or_else(|| format!("`{id}` is the last tutorial in its skill"))?; diff --git a/crates/ui-egui/src/panels/learn/progress.rs b/crates/ui-egui/src/panels/learn/progress.rs new file mode 100644 index 0000000000..a425b0e58f --- /dev/null +++ b/crates/ui-egui/src/panels/learn/progress.rs @@ -0,0 +1,122 @@ +//! What a learner has done in the Learn panel: the steps marked done in each tutorial and the +//! tutorials finished. The UI preferences keep it (`UiState::learn_progress`), so it lasts from +//! one start to the next where the preferences are saved. Saved progress is read leniently: an +//! unknown tutorial id, a step the tutorial does not have, a repeated entry or a value of the wrong +//! kind is skipped, and the rest of the preferences read as usual. + +use std::collections::BTreeMap; + +use serde::{Deserialize, Deserializer, Serialize, Serializer}; +use serde_json::Value; + +use super::catalog; + +/// The most entries read from one saved list or map; the rest are skipped. +const MAX_READ: usize = 1024; + +/// The tutorials finished and the steps marked done. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Progress { + /// The tutorials finished, in the order they were finished. Each id is listed once. + pub finished: Vec<&'static str>, + /// For each tutorial not finished, the zero-based indexes of the steps marked done, ascending. + /// A tutorial with no step marked has no entry. + pub steps: BTreeMap<&'static str, Vec>, +} + +impl Progress { + /// Nothing is finished and no step is marked. + pub fn is_empty(&self) -> bool { + self.finished.is_empty() && self.steps.is_empty() + } + + /// Whether the tutorial `id` is finished. + pub fn is_finished(&self, id: &str) -> bool { + self.finished.contains(&id) + } + + /// The zero-based indexes of `tutorial`'s steps marked done, ascending: every step of a + /// finished tutorial. + pub fn completed_steps(&self, tutorial: &catalog::Tutorial) -> Vec { + if self.is_finished(tutorial.id) { + return (0..tutorial.steps.len()).collect(); + } + self.steps.get(tutorial.id).cloned().unwrap_or_default() + } + + /// Whether step `step` of `tutorial` is marked done. + pub fn step_done(&self, tutorial: &catalog::Tutorial, step: usize) -> bool { + self.is_finished(tutorial.id) || self.steps.get(tutorial.id).is_some_and(|s| s.contains(&step)) + } + + /// Mark step `step` of the unfinished tutorial `id` done (`complete`) or not done. + pub fn mark(&mut self, id: &'static str, step: usize, complete: bool) { + let marks = self.steps.entry(id).or_default(); + match (marks.binary_search(&step), complete) { + (Err(at), true) => marks.insert(at, step), + (Ok(at), false) => { + marks.remove(at); + } + _ => {} + } + if marks.is_empty() { + self.steps.remove(id); + } + } + + /// Mark the tutorial `id` finished, with all its steps done. Finishing it again keeps one entry. + pub fn finish(&mut self, id: &'static str) { + if !self.is_finished(id) { + self.finished.push(id); + } + self.steps.remove(id); + } + + /// How many of `skill`'s tutorials are finished. + pub fn done(&self, skill: &catalog::Skill) -> usize { + skill.tutorials.iter().filter(|t| self.is_finished(t.id)).count() + } + + /// Progress read from a saved value, keeping only what the catalog knows (see the module). + fn from_value(saved: &Value) -> Self { + let mut progress = Progress::default(); + let known = |id: &Value| id.as_str().and_then(catalog::tutorial).map(|(_, t)| t); + if let Some(finished) = saved.get("finished").and_then(Value::as_array) { + for tutorial in finished.iter().take(MAX_READ).filter_map(known) { + progress.finish(tutorial.id); + } + } + if let Some(steps) = saved.get("steps").and_then(Value::as_object) { + for (id, marks) in steps.iter().take(MAX_READ) { + let Some((_, tutorial)) = catalog::tutorial(id) else { continue }; + if progress.is_finished(tutorial.id) { + continue; + } + let indexes = marks.as_array().into_iter().flatten().take(MAX_READ).filter_map(Value::as_u64); + for step in indexes.filter_map(|s| usize::try_from(s).ok()).filter(|s| *s < tutorial.steps.len()) { + progress.mark(tutorial.id, step, true); + } + } + } + progress + } +} + +/// The saved form: `{finished: [id], steps: {id: [index]}}`. +#[derive(Serialize)] +struct Saved<'a> { + finished: &'a [&'static str], + steps: &'a BTreeMap<&'static str, Vec>, +} + +impl Serialize for Progress { + fn serialize(&self, serializer: S) -> Result { + Saved { finished: &self.finished, steps: &self.steps }.serialize(serializer) + } +} + +impl<'de> Deserialize<'de> for Progress { + fn deserialize>(deserializer: D) -> Result { + Ok(Progress::from_value(&Value::deserialize(deserializer)?)) + } +} diff --git a/crates/ui-egui/src/panels/learn/tests.rs b/crates/ui-egui/src/panels/learn/tests.rs index 4bd00648d1..319ca1decf 100644 --- a/crates/ui-egui/src/panels/learn/tests.rs +++ b/crates/ui-egui/src/panels/learn/tests.rs @@ -1,7 +1,7 @@ use std::collections::HashSet; -use egui::accesskit::Node; -use serde_json::json; +use egui::accesskit::{Node, Role, Toggled}; +use serde_json::{Value, json}; use vectorcraft_engine::Session; use super::{ID, Practice, Tab, View, catalog, samples, show}; @@ -225,7 +225,8 @@ fn learn_show_opens_a_tutorial_and_learn_list_lists_them() { assert_eq!(skills.len(), catalog::SKILLS.len()); let count: usize = skills.iter().map(|s| s["tutorials"].as_array().map_or(0, Vec::len)).sum(); assert_eq!(count, catalog::SKILLS.iter().map(|s| s.tutorials.len()).sum::()); - assert_eq!(skills[2]["tutorials"][1], json!({"id": "gradient", "title": "Add a gradient", "steps": 3})); + assert_eq!(skills[2]["tutorials"][1], json!({"id": "gradient", "title": "Add a gradient", "steps": 3, "finished": false, "completedSteps": []})); + assert_eq!((skills[2]["done"].clone(), skills[2]["total"].clone()), (json!(0), json!(3))); } /// Every tutorial has one sample of its own, in the catalog's order, each one small and read @@ -279,7 +280,8 @@ fn view_more_opens_the_tutorial_s_sample_as_a_new_untitled_document() { assert_eq!(docs[0].doc.node_count(), work, "the open document stays as it was"); assert!(docs[1].path.is_none() && docs[1].title().starts_with("Untitled-"), "{}", docs[1].title()); let pen = docs[1].doc.node_count(); - assert_eq!(app.ui.learn_practice, Practice { opened: vec!["pen-paths"], finished: vec![] }); + assert_eq!(app.ui.learn_practice, Practice { opened: vec!["pen-paths"] }); + assert!(app.ui.learn_progress.is_empty(), "opening a sample marks nothing"); let r = app.run("learn.openSample", json!({"tutorial": "gradient"})).unwrap(); assert_eq!(r["tutorial"], "gradient"); @@ -306,7 +308,7 @@ fn finishing_a_tutorial_offers_next_up_in_its_skill() { let text = painted_text(&mut app, show); assert!(text.contains("Finish tutorial") && !text.contains("Next Up"), "{text}"); click(&mut app, &ctx, "Finish tutorial", show); - assert_eq!(app.ui.learn_practice.finished, ["pen-paths"]); + assert_eq!(app.ui.learn_progress.finished, ["pen-paths"]); let text = painted_text(&mut app, show); assert!(text.contains("Next Up") && text.contains("Draw smooth curves") && !text.contains("Finish tutorial"), "{text}"); let docs = app.session.documents().len(); @@ -350,7 +352,7 @@ fn the_practice_controls_work_from_the_keyboard() { assert_eq!(app.ui.learn_practice.opened, ["pen-paths"]); tab_to(&mut app, &ctx, "Finish tutorial", show); key(&mut app, &ctx, egui::Key::Enter, show); - assert_eq!(app.ui.learn_practice.finished, ["pen-paths"]); + assert_eq!(app.ui.learn_progress.finished, ["pen-paths"]); tab_to(&mut app, &ctx, "Next Up", show); key(&mut app, &ctx, egui::Key::Enter, show); assert_eq!(app.ui.learn, View { tab: Tab::Skills, skill: Some("draw"), tutorial: Some("smooth-curves") }); @@ -408,13 +410,14 @@ fn learn_finish_and_learn_next_follow_the_practice() { assert_eq!(app.run("learn.finish", json!({"tutorial": "gradient"})).unwrap_err(), open); assert_eq!(app.run("learn.next", json!({"tutorial": "gradient"})).unwrap_err(), "finish `gradient` first (see learn.finish)"); assert_eq!(app.ui.learn_practice, Practice::default()); + assert!(app.ui.learn_progress.is_empty()); app.run("learn.openSample", json!({"tutorial": "gradient"})).unwrap(); assert_eq!(app.run("learn.next", json!({"tutorial": "gradient"})).unwrap_err(), "finish `gradient` first (see learn.finish)"); for _ in 0..2 { let r = app.run("learn.finish", json!({"tutorial": "gradient"})).unwrap(); assert_eq!(r, json!({"tutorial": "gradient", "finished": true, "next": "copy-colors"})); } - assert_eq!(app.ui.learn_practice.finished, ["gradient"], "finishing again keeps one entry"); + assert_eq!(app.ui.learn_progress.finished, ["gradient"], "finishing again keeps one entry"); let r = app.run("learn.next", json!({"tutorial": "gradient"})).unwrap(); assert_eq!(r, json!({"skill": "color", "tutorial": "copy-colors", "title": "Copy colors from other art"})); assert!(shown(&app)); @@ -471,6 +474,7 @@ fn the_practice_commands_reject_a_missing_or_unknown_tutorial() { assert_eq!(app.run(cmd, params).unwrap_err(), error, "{cmd}"); assert_eq!(app.ui.learn, View::default()); assert_eq!(app.ui.learn_practice, Practice::default()); + assert!(app.ui.learn_progress.is_empty()); assert_eq!(app.session.documents().len(), 1); assert!(!shown(&app)); } @@ -493,6 +497,90 @@ fn learn_show_rejects_a_missing_or_unknown_tutorial() { } } +/// The tab buttons, a skill's row, a tutorial's row and Back run `learn.tab`, `learn.skill`, +/// `learn.show` and `learn.back`: each one also shows a panel that was hidden, as the command does. +#[test] +fn the_tabs_rows_and_back_run_their_commands() { + for cmd in ["learn.tab", "learn.skill", "learn.back"] { + assert!(crate::menus::UI_COMMANDS.iter().any(|c| c.0 == cmd), "{cmd} is in the UI command catalog"); + } + let mut app = app(); + let ctx = context(); + let (skill, tutorial) = catalog::tutorial("gradient").unwrap(); + let press = |app: &mut VectorcraftApp, name: &str, view: View| { + app.run("window.learn", json!({"show": false})).unwrap(); + assert!(!shown(app)); + click(app, &ctx, name, show); + assert_eq!(app.ui.learn, view, "{name}"); + assert!(shown(app), "{name} runs its command: {}", app.ui.status); + }; + press(&mut app, "Skills", View { tab: Tab::Skills, skill: None, tutorial: None }); + press(&mut app, skill.title, View { tab: Tab::Skills, skill: Some(skill.id), tutorial: None }); + press(&mut app, tutorial.title, View { tab: Tab::Skills, skill: Some(skill.id), tutorial: Some(tutorial.id) }); + press(&mut app, "For you", View { tab: Tab::ForYou, skill: Some(skill.id), tutorial: Some(tutorial.id) }); + press(&mut app, "Skills", View { tab: Tab::Skills, skill: Some(skill.id), tutorial: Some(tutorial.id) }); + press(&mut app, "Back", View { tab: Tab::Skills, skill: Some(skill.id), tutorial: None }); + press(&mut app, "Back", View { tab: Tab::Skills, skill: None, tutorial: None }); +} + +/// A click on the tab the panel already shows runs no command. +#[test] +fn a_click_on_the_shown_tab_runs_no_command() { + let mut app = app(); + let ctx = context(); + for name in ["Skills", "For you"] { + click(&mut app, &ctx, name, show); + let commands = app.run_count; + click(&mut app, &ctx, name, show); + assert_eq!(app.run_count, commands, "{name}"); + } +} + +/// `learn.tab` switches tabs and keeps what the Skills tab had open; `learn.skill` opens a skill's +/// tutorials and answers the skill as `learn.list` lists it; `learn.back` goes up one level and +/// keeps the view on the list of skills and on the For you tab. +#[test] +fn learn_tab_skill_and_back_move_the_view() { + let mut app = app(); + let list = app.run("learn.list", json!({})).unwrap(); + assert_eq!(app.run("learn.skill", json!({"skill": "color"})).unwrap(), list["skills"][2]); + assert!(shown(&app)); + assert_eq!(app.ui.learn, View { tab: Tab::Skills, skill: Some("color"), tutorial: None }); + app.run("learn.show", json!({"tutorial": "gradient"})).unwrap(); + let view = json!({"tab": "forYou", "skill": "color", "tutorial": "gradient"}); + assert_eq!(app.run("learn.tab", json!({"tab": "forYou"})).unwrap(), view); + assert_eq!(app.run("learn.back", json!({})).unwrap(), view, "Back on the For you tab keeps the view"); + assert_eq!(app.run("learn.tab", json!({"tab": "skills"})).unwrap(), json!({"tab": "skills", "skill": "color", "tutorial": "gradient"})); + assert_eq!(app.run("learn.back", json!({})).unwrap(), json!({"tab": "skills", "skill": "color", "tutorial": null})); + let skills = json!({"tab": "skills", "skill": null, "tutorial": null}); + assert_eq!(app.run("learn.back", json!({})).unwrap(), skills); + assert_eq!(app.run("learn.back", json!({})).unwrap(), skills, "Back on the list of skills keeps the view"); + app.run("window.learn", json!({"show": false})).unwrap(); + assert_eq!(app.run("learn.back", json!({})).unwrap(), skills); + assert!(shown(&app), "learn.back shows the panel"); +} + +/// `learn.tab` and `learn.skill` reject a missing, mistyped or unknown value and change nothing. +#[test] +fn learn_tab_and_learn_skill_reject_a_missing_or_unknown_value() { + let mut app = app(); + let before = app.ui.learn.clone(); + let skills = catalog::SKILLS.iter().map(|s| s.id).collect::>().join(", "); + for (cmd, params, error) in [ + ("learn.tab", json!({}), "missing `tab`".to_string()), + ("learn.tab", json!({"tab": null}), "missing `tab`".to_string()), + ("learn.tab", json!({"tab": 1}), "`tab` must be a string".to_string()), + ("learn.tab", json!({"tab": "Skills"}), "`tab` must be one of forYou, skills".to_string()), + ("learn.skill", json!({}), "missing `skill`".to_string()), + ("learn.skill", json!({"skill": ["draw"]}), "`skill` must be a string".to_string()), + ("learn.skill", json!({"skill": "nope"}), format!("`skill` must be one of {skills}")), + ] { + assert_eq!(app.run(cmd, params.clone()).unwrap_err(), error, "{cmd} {params}"); + assert_eq!(app.ui.learn, before); + assert!(!shown(&app)); + } +} + /// The Pen tutorial's steps, as the panel shows them. fn pen_paths(app: &mut VectorcraftApp, ui: &mut egui::Ui) { app.ui.learn = View { tab: Tab::Skills, skill: Some("draw"), tutorial: Some("pen-paths") }; @@ -581,3 +669,274 @@ fn learn_locate_tool_is_unavailable_while_the_toolbars_are_hidden() { assert_eq!(reply["location"], "unavailable", "{reply}"); assert!(app.ui.learn_locate.is_none() && !app.ui.toolbar && app.ui.tab_hid.is_some(), "Tab's state stays"); } + +/// The screen-reader name of step `i` of the Pen tutorial's check box. +fn pen_step(i: usize) -> String { + let (_, tutorial) = catalog::tutorial("pen-paths").unwrap(); + format!("{}. {}", i + 1, tutorial.steps[i].plain()) +} + +/// The check boxes of what `draw` draws, from the top, as (enabled, checked). +fn check_boxes(app: &mut VectorcraftApp, ctx: &egui::Context, draw: fn(&mut VectorcraftApp, &mut egui::Ui)) -> Vec<(bool, bool)> { + let nodes = frame(app, ctx, vec![], draw); + let mut boxes: Vec<&Node> = nodes.iter().filter(|n| n.role() == Role::CheckBox).collect(); + boxes.sort_by(|a, b| a.bounds().map_or(0.0, |r| r.y0).total_cmp(&b.bounds().map_or(0.0, |r| r.y0))); + boxes.iter().map(|n| (!n.is_disabled(), n.toggled() == Some(Toggled::True))).collect() +} + +/// Each step has a check box, off until the tutorial's sample is open. A click marks only its own +/// step and a second click clears it; marking every step does not finish the tutorial. A finished +/// tutorial shows every step done, and its check boxes and `learn.markStep` no longer change them. +#[test] +fn a_step_s_check_box_marks_only_that_step() { + let mut app = app(); + let ctx = context(); + assert_eq!(check_boxes(&mut app, &ctx, pen_paths), [(false, false); 3], "off before View more"); + click(&mut app, &ctx, &pen_step(1), pen_paths); + assert!(app.ui.learn_progress.is_empty(), "a check box that is off changes nothing"); + app.run("learn.openSample", json!({"tutorial": "pen-paths"})).unwrap(); + click(&mut app, &ctx, &pen_step(1), pen_paths); + assert_eq!(check_boxes(&mut app, &ctx, pen_paths), [(true, false), (true, true), (true, false)], "{}", app.ui.status); + let list = app.run("learn.list", json!({})).unwrap(); + assert_eq!(list["skills"][1]["tutorials"][0]["completedSteps"], json!([1])); + assert_eq!(list["skills"][1]["tutorials"][1]["completedSteps"], json!([]), "other tutorials stay as they are"); + click(&mut app, &ctx, &pen_step(1), pen_paths); + assert!(app.ui.learn_progress.is_empty(), "a second click clears the mark"); + for i in 0..3 { + click(&mut app, &ctx, &pen_step(i), pen_paths); + } + assert_eq!(check_boxes(&mut app, &ctx, pen_paths), [(true, true); 3]); + assert!(!app.ui.learn_progress.is_finished("pen-paths"), "marking every step does not finish the tutorial"); + assert!(painted_text(&mut app, pen_paths).contains("Finish tutorial")); + click(&mut app, &ctx, &pen_step(0), pen_paths); + click(&mut app, &ctx, "Finish tutorial", pen_paths); + assert_eq!(app.ui.learn_progress.finished, ["pen-paths"]); + assert!(app.ui.learn_progress.steps.is_empty(), "a finished tutorial keeps no marks of its own"); + assert_eq!(check_boxes(&mut app, &ctx, pen_paths), [(false, true); 3], "Finish marks every step"); + let before = app.ui.learn_progress.clone(); + click(&mut app, &ctx, &pen_step(2), pen_paths); + let error = app.run("learn.markStep", json!({"tutorial": "pen-paths", "step": 2, "complete": false})).unwrap_err(); + assert_eq!(error, "`pen-paths` is finished (see learn.resetProgress)"); + assert_eq!(app.ui.learn_progress, before); +} + +/// The check boxes are reached with Tab and changed with Space. +#[test] +fn a_step_s_check_box_works_from_the_keyboard() { + let mut app = app(); + let ctx = context(); + app.run("learn.openSample", json!({"tutorial": "pen-paths"})).unwrap(); + frame(&mut app, &ctx, vec![], pen_paths); + tab_to(&mut app, &ctx, &pen_step(2), pen_paths); + key(&mut app, &ctx, egui::Key::Space, pen_paths); + assert_eq!(app.ui.learn_progress.steps.get("pen-paths"), Some(&vec![2]), "{}", app.ui.status); +} + +/// Finishing tutorials fills only their own skill's ring and count, once each however often they +/// are finished; the skill's tutorial rows show which are finished; `learn.list` answers the same. +#[test] +fn finishing_tutorials_fills_their_skill_s_ring_and_count() { + let mut app = app(); + let ctx = context(); + for id in ["pen-paths", "smooth-curves"] { + app.run("learn.openSample", json!({"tutorial": id})).unwrap(); + for _ in 0..2 { + app.run("learn.finish", json!({"tutorial": id})).unwrap(); + } + } + let values = |app: &mut VectorcraftApp, view: View| { + app.ui.learn = view; + let nodes = frame(app, &ctx, vec![], show); + nodes + .iter() + .filter(|n| n.role() == Role::Button) + .map(|n| (n.label().unwrap_or_default().to_string(), n.value().map(str::to_string))) + .collect::>() + }; + let skills = View { tab: Tab::Skills, skill: None, tutorial: None }; + let rows = values(&mut app, skills.clone()); + for skill in catalog::SKILLS { + let count = if skill.id == "draw" { "2/3".to_string() } else { format!("0/{}", skill.tutorials.len()) }; + assert!(rows.contains(&(skill.title.to_string(), Some(count.clone()))), "{} {count} in {rows:?}", skill.id); + } + assert!(painted_text(&mut app, show).contains("2/3")); + let list = app.run("learn.list", json!({})).unwrap(); + let draw = &list["skills"][1]; + assert_eq!((draw["done"].clone(), draw["total"].clone()), (json!(2), json!(3))); + assert_eq!(draw["tutorials"][1]["finished"], json!(true)); + assert_eq!(draw["tutorials"][1]["completedSteps"], json!([0, 1, 2])); + assert_eq!(list["skills"][2]["done"], json!(0), "other skills stay at 0"); + + let rows = values(&mut app, View { tab: Tab::Skills, skill: Some("draw"), tutorial: None }); + assert!(rows.contains(&("Draw paths with the Pen".to_string(), Some("Finished".to_string()))), "{rows:?}"); + assert!(rows.contains(&("Draw smooth curves".to_string(), Some("Finished".to_string()))), "{rows:?}"); + assert!(rows.contains(&("Sketch with the Pencil".to_string(), None)), "{rows:?}"); + + app.run("learn.openSample", json!({"tutorial": "pencil-sketch"})).unwrap(); + app.run("learn.finish", json!({"tutorial": "pencil-sketch"})).unwrap(); + let rows = values(&mut app, skills); + assert!(rows.contains(&("Draw and build".to_string(), Some("3/3".to_string()))), "every tutorial finished: {rows:?}"); +} + +/// A skill row with no tutorials, which the catalog does not have today, shows an empty ring and +/// 0/0. +fn empty_skill(_: &mut VectorcraftApp, ui: &mut egui::Ui) { + super::row(ui, "Empty skill", super::Mark::Ring { done: 0, total: 0 }); +} + +#[test] +fn a_skill_with_no_tutorials_shows_0_of_0() { + let mut app = app(); + let text = painted_text(&mut app, empty_skill); + assert!(text.contains("Empty skill") && text.contains("0/0"), "{text}"); +} + +/// `learn.markStep` marks a step done by default and with `complete: true`, clears it with `false`, +/// and answers what it did; a bad param is an error and changes nothing. +#[test] +fn learn_mark_step_checks_its_params() { + let mut app = app(); + let open = "open the practice sample of `gradient` first (see learn.openSample)"; + assert_eq!(app.run("learn.markStep", json!({"tutorial": "gradient", "step": 0})).unwrap_err(), open); + assert!(app.ui.learn_progress.is_empty()); + app.run("learn.openSample", json!({"tutorial": "gradient"})).unwrap(); + assert_eq!( + app.run("learn.markStep", json!({"tutorial": "gradient", "step": 0})).unwrap(), + json!({"tutorial": "gradient", "step": 0, "complete": true}) + ); + let before = app.ui.learn_progress.clone(); + let missing = "missing `step` (see learn.show)"; + let range = "`step` must be a step number from 0 to 2"; + for (params, error) in [ + (json!({"tutorial": "gradient"}), missing), + (json!({"tutorial": "gradient", "step": null}), missing), + (json!({"tutorial": "gradient", "step": 3}), range), + (json!({"tutorial": "gradient", "step": -1}), range), + (json!({"tutorial": "gradient", "step": 1.5}), range), + (json!({"tutorial": "gradient", "step": "1"}), range), + (json!({"tutorial": "gradient", "step": u64::MAX}), range), + (json!({"tutorial": "gradient", "step": 1, "complete": "yes"}), "`complete` must be true or false"), + (json!({"tutorial": "nope", "step": 1}), "unknown tutorial `nope` (see learn.list)"), + (json!({"step": 1}), "missing `tutorial` (see learn.list)"), + ] { + assert_eq!(app.run("learn.markStep", params.clone()).unwrap_err(), error, "{params}"); + assert_eq!(app.ui.learn_progress, before, "{params}"); + } + let r = app.run("learn.markStep", json!({"tutorial": "gradient", "step": 2, "complete": null})).unwrap(); + assert_eq!(r, json!({"tutorial": "gradient", "step": 2, "complete": true})); + let r = app.run("learn.markStep", json!({"tutorial": "gradient", "step": 0, "complete": false})).unwrap(); + assert_eq!(r, json!({"tutorial": "gradient", "step": 0, "complete": false})); + let r = app.run("learn.markStep", json!({"tutorial": "gradient", "step": 0, "complete": false})).unwrap(); + assert_eq!(r["complete"], json!(false), "clearing a step that is not marked is no error"); + assert_eq!(app.ui.learn_progress.steps.get("gradient"), Some(&vec![2])); + assert!(app.ui.learn_progress.finished.is_empty()); +} + +/// `learn.resetProgress` and Reset progress clear every tutorial finished and every step marked; +/// documents, opened samples and the Learn view stay. Reset progress shows only when there is +/// progress. +#[test] +fn reset_progress_clears_only_the_progress() { + let mut app = app(); + let ctx = context(); + let skills = View { tab: Tab::Skills, skill: None, tutorial: None }; + app.ui.learn = skills.clone(); + assert!(!painted_text(&mut app, show).contains("Reset progress")); + app.run("learn.openSample", json!({"tutorial": "pen-paths"})).unwrap(); + app.run("learn.finish", json!({"tutorial": "pen-paths"})).unwrap(); + app.run("learn.openSample", json!({"tutorial": "gradient"})).unwrap(); + app.run("learn.markStep", json!({"tutorial": "gradient", "step": 1})).unwrap(); + let view = app.ui.learn.clone(); + let docs = app.session.documents().len(); + let reply = app.run("learn.resetProgress", json!({})).unwrap(); + assert!(app.ui.learn_progress.is_empty()); + assert_eq!(reply, app.run("learn.list", json!({})).unwrap()); + assert_eq!(reply["skills"][1]["done"], json!(0)); + assert_eq!((app.ui.learn.clone(), app.session.documents().len()), (view, docs)); + assert_eq!(app.ui.learn_practice.opened, ["pen-paths", "gradient"], "opened samples stay open for practice"); + + app.run("learn.finish", json!({"tutorial": "gradient"})).unwrap(); + app.ui.learn = skills.clone(); + assert!(painted_text(&mut app, show).contains("Reset progress")); + click(&mut app, &ctx, "Reset progress", show); + assert!(app.ui.learn_progress.is_empty(), "{}", app.ui.status); + assert_eq!(app.ui.learn, skills); + assert!(!painted_text(&mut app, show).contains("Reset progress")); +} + +/// The UI state after its preferences are saved and read again, as at the next start. +fn restarted(app: &VectorcraftApp) -> crate::state::UiState { + let bytes = serde_json::to_vec(&app.ui).unwrap(); + crate::state::UiState::read_preferences(&bytes).expect("the preferences read").ui.sanitized() +} + +/// The preferences keep the tutorials finished and the steps marked; the opened samples, the +/// Learn view and a tool's mark last only while the app runs, so a step can be marked again only +/// after View more. +#[test] +fn the_preferences_keep_the_progress() { + let mut app = app(); + app.run("learn.openSample", json!({"tutorial": "pen-paths"})).unwrap(); + app.run("learn.finish", json!({"tutorial": "pen-paths"})).unwrap(); + app.run("learn.openSample", json!({"tutorial": "gradient"})).unwrap(); + for step in [2, 0] { + app.run("learn.markStep", json!({"tutorial": "gradient", "step": step})).unwrap(); + } + let list = app.run("learn.list", json!({})).unwrap(); + let ui = restarted(&app); + assert_eq!(ui.learn_progress, app.ui.learn_progress); + assert_eq!(ui.learn_progress.steps.get("gradient"), Some(&vec![0, 2])); + assert_eq!((ui.learn_practice.clone(), ui.learn.clone(), ui.learn_locate.is_none()), (Practice::default(), View::default(), true)); + + let mut next = self::app(); + next.ui = ui; + assert_eq!(next.run("learn.list", json!({})).unwrap(), list); + assert_eq!(next.run("learn.next", json!({"tutorial": "pen-paths"})).unwrap()["tutorial"], "smooth-curves"); + let again = next.run("learn.finish", json!({"tutorial": "pen-paths"})).unwrap(); + assert_eq!(again, json!({"tutorial": "pen-paths", "finished": true, "next": "smooth-curves"}), "finishing again needs no sample"); + assert_eq!(next.ui.learn_progress.finished, ["pen-paths"]); + let open = "open the practice sample of `gradient` first (see learn.openSample)"; + assert_eq!(next.run("learn.markStep", json!({"tutorial": "gradient", "step": 1})).unwrap_err(), open); +} + +/// Saved preferences with `learn_progress` set to `progress` (left out for None), and +/// `control_bar` on, read as at a start. +fn read_progress(progress: Option) -> crate::state::UiState { + let mut saved = serde_json::to_value(crate::state::UiState::default()).unwrap(); + let fields = saved.as_object_mut().unwrap(); + fields.insert("control_bar".into(), json!(true)); + match progress { + Some(p) => fields.insert("learn_progress".into(), p), + None => fields.remove("learn_progress"), + }; + let ui = crate::state::UiState::read_preferences(&serde_json::to_vec(&saved).unwrap()).expect("the preferences read").ui; + assert!(ui.control_bar, "the other preferences read as usual"); + ui +} + +/// Preferences saved before the progress was kept read with none. Saved progress keeps only the +/// catalog's tutorials and steps, each once, and a value of the wrong kind, or a huge list, does not +/// stop the rest of the preferences from reading. +#[test] +fn saved_progress_is_read_leniently() { + assert!(read_progress(None).learn_progress.is_empty()); + for bad in [json!("garbage"), json!(3), json!(null), json!([1, 2]), json!({"finished": "pen-paths", "steps": [0]})] { + assert!(read_progress(Some(bad.clone())).learn_progress.is_empty(), "{bad}"); + } + let ui = read_progress(Some(json!({ + "finished": ["pen-paths", "nope", 3, "pen-paths", "gradient"], + "steps": { + "gradient": [0], + "smooth-curves": [2, 0, 2, 99, -1, "1", 1.5], + "nope": [0], + "copy-colors": "x", + "add-headline": [], + }, + }))); + assert_eq!(ui.learn_progress.finished, ["pen-paths", "gradient"]); + let steps: Vec<(&str, Vec)> = ui.learn_progress.steps.iter().map(|(id, s)| (*id, s.clone())).collect(); + assert_eq!(steps, [("smooth-curves", vec![0, 2])], "a finished tutorial keeps no marks"); + let ui = read_progress(Some(json!({"finished": vec!["pen-paths"; 100_000], "steps": {"smooth-curves": vec![1; 100_000]}}))); + assert_eq!(ui.learn_progress.finished, ["pen-paths"]); + assert_eq!(ui.learn_progress.steps.get("smooth-curves"), Some(&vec![1])); +} diff --git a/crates/ui-egui/src/panels/libraries.rs b/crates/ui-egui/src/panels/libraries.rs index 3b55d34e11..9c10281783 100644 --- a/crates/ui-egui/src/panels/libraries.rs +++ b/crates/ui-egui/src/panels/libraries.rs @@ -30,6 +30,7 @@ use std::collections::HashMap; use egui::{Rect, Sense, Stroke, StrokeKind, Ui, vec2}; use serde_json::{Value, json}; use vectorcraft_color::Paint; +use vectorcraft_doc::resample::{Resample, fitted}; use vectorcraft_engine::cmd::library::{ItemKind, LIBRARY_EXT, LIBRARY_EXTS, Library, LibraryGraphic}; use crate::theme::Tokens; @@ -831,8 +832,7 @@ fn thumbnail(ctx: &egui::Context, library: &str, item: &str, png: &str, px: u32) } let tex = vectorcraft_format::base64_decode(png).and_then(|png| image::load_from_memory_with_format(&png, image::ImageFormat::Png).ok()).map(|img| { - let img = if img.width().max(img.height()) > px { img.resize(px, px, image::imageops::FilterType::Triangle) } else { img }; - let rgba = img.to_rgba8(); + let rgba = shrunk_thumbnail(img, px); let image = egui::ColorImage::from_rgba_unmultiplied([rgba.width() as usize, rgba.height() as usize], rgba.as_raw()); ctx.load_texture(format!("library-{library}-{item}-{px}"), image, egui::TextureOptions::LINEAR) }); @@ -846,6 +846,13 @@ fn thumbnail(ctx: &egui::Context, library: &str, item: &str, png: &str, px: u32) tex } +/// Thumbnail `img` shrunk smoothly to at most `px` pixels a side, its colors weighted by its alpha +/// so that clear pixels don't darken the edges of the art, as RGBA. +fn shrunk_thumbnail(img: image::DynamicImage, px: u32) -> image::RgbaImage { + let img = if img.width().max(img.height()) > px { fitted(img, px, px, Resample::Filter(image::imageops::FilterType::Triangle)) } else { img }; + img.into_rgba8() +} + /// Graphic `item` of `library`'s thumbnail in `r` (the chip a dragged graphic shows at the pointer). pub(crate) fn chip(app: &VectorcraftApp, ui: &Ui, r: Rect, library: &str, item: &str) { if let Some(g) = app.session.libraries.get(library).and_then(|l| l.graphics.iter().find(|g| g.id == item)) { diff --git a/crates/ui-egui/src/panels/libraries/tests.rs b/crates/ui-egui/src/panels/libraries/tests.rs index 931a91a444..00ff1bf2cd 100644 --- a/crates/ui-egui/src/panels/libraries/tests.rs +++ b/crates/ui-egui/src/panels/libraries/tests.rs @@ -525,3 +525,16 @@ fn libraries_are_exported_and_imported_from_the_panel_menu() { assert_eq!(names, ["Brand", "Brand (2)"]); assert_eq!(app.ui.status, "Imported library Brand (2)"); } + +/// A graphic's thumbnail shrunk for its tile keeps the color of the art beside clear pixels: the +/// clear black beside it does not darken it. +#[test] +fn a_shrunk_thumbnail_keeps_its_color_beside_clear_pixels() { + let img = image::RgbaImage::from_fn(64, 4, |x, _| if x % 2 == 0 { image::Rgba([200, 30, 30, 255]) } else { image::Rgba([0, 0, 0, 0]) }); + let small = shrunk_thumbnail(image::DynamicImage::ImageRgba8(img), 16); + assert_eq!(small.dimensions(), (16, 1)); + let m = |c: u8, a: u8| (u16::from(c) * u16::from(a) / 255) as u8; + for p in small.pixels() { + assert!(p[3] > 0 && [200, 30, 30].iter().zip(p.0).all(|(&want, c)| m(c, p[3]).abs_diff(m(want, p[3])) <= 1), "{p:?}"); + } +} diff --git a/crates/ui-egui/src/panels/links.rs b/crates/ui-egui/src/panels/links.rs index 2fb130ae3e..611c9e472a 100644 --- a/crates/ui-egui/src/panels/links.rs +++ b/crates/ui-egui/src/panels/links.rs @@ -5,8 +5,8 @@ //! Go To, Update and Edit Original act on the selected rows (Relink through its dialog, with the //! Replace choice: `ui.relinkDialog`); Link Info shows the details of the first. The flyout adds Relink to Folder, Find in Folder (Find Linked Files: //! `ui.findLinksInFolder`), Embed / Unembed, Placement Options, Select Linked / Embedded / Missing / -//! Modified (`addon.select.byLinkStatus`, Shift adds), Show filters, Sort, thumbnail size, -//! Show in Folder and Show DCS Transparency Interactions (a warning on the rows of images placed +//! Modified (`addon.select.byLinkStatus`, Shift adds), Show filters, Sort, Copy Info (the selected +//! rows' file names to the clipboard: `links.copyInfo`), thumbnail size, Show in Folder and Show DCS Transparency Interactions (a warning on the rows of images placed //! from DCS files that are transparent or overlap transparent objects). //! //! Images and placed documents in opacity-mask art and in the art of symbols, graph designs and @@ -29,7 +29,7 @@ pub const ID: &str = "links"; /// Seconds between two looks at the linked files (they change outside the app). const RECHECK: f64 = 2.0; const SHOW: [(&str, &str); 4] = [("all", "Show All"), ("missing", "Show Missing"), ("modified", "Show Modified"), ("embedded", "Show Embedded")]; -const SORT: [(&str, &str); 3] = [("name", "Sort by Name"), ("kind", "Sort by Kind"), ("status", "Sort by Status")]; +const SORT: [(&str, &str); 4] = [("name", "Sort by Name"), ("kind", "Sort by Kind"), ("status", "Sort by Status"), ("size", "Sort by Size")]; const THUMBS: [(f32, &str); 4] = [(0.0, "No Thumbnails"), (18.0, "Small Thumbnails"), (28.0, "Medium Thumbnails"), (44.0, "Large Thumbnails")]; /// The panel's options (flyout). @@ -92,28 +92,29 @@ fn cached(app: &mut VectorcraftApp, ctx: &egui::Context, o: &Options) -> Option< let mut c: Cache = pstate(ctx, "links-cache"); let stale = c.key != key || now - c.at > RECHECK; if stale { + let same_doc = c.key == key; c.list = app.session.execute("links.list", &json!({ "show": o.show, "sort": o.sort, "dcsTransparency": o.dcs })).ok()?; (c.key, c.at) = (key, now); // One pass over the stored art for the rows outside the layer tree and the objects whose - // opacity masks hold them, not one per frame. - let mut want: std::collections::HashSet = c.list["links"] + // opacity masks hold them, not one per frame. An object in the layer tree is looked up by + // its index when drawn. + let doc = app.session.active().map(|st| &st.doc); + let want: std::collections::HashSet = c.list["links"] .as_array() .into_iter() .flatten() .filter(|r| nested_row(r)) .flat_map(|r| [r["id"].as_u64(), r["owner"]["maskOf"].as_u64()]) .flatten() + .filter(|id| doc.is_some_and(|d| d.node(NodeId(*id)).is_none())) .collect(); - c.nested.clear(); - if !want.is_empty() - && let Some(st) = app.session.active() - { - st.doc.visit_stored_arcs(|n, place| { - if !place.in_layers() && want.remove(&n.id.0) { - c.nested.push((n.id.0, std::sync::Arc::clone(n))); - } - }); - c.nested.sort_by_key(|(id, _)| *id); + // The same revision keeps the objects collected for it, so their thumbnails are not drawn + // again each time the files are looked at. + if !(same_doc && want.iter().all(|id| c.nested_node(*id).is_some())) { + c.nested = match doc { + Some(d) if !want.is_empty() => stored_objects(d, want), + _ => vec![], + }; } } let want = first.filter(|_| o.info); @@ -126,6 +127,44 @@ fn cached(app: &mut VectorcraftApp, ctx: &egui::Context, o: &Options) -> Option< Some(c) } +/// The objects of `doc` outside the layer tree whose ids are in `want`, sorted by id. The art of +/// the stored brushes is set on `doc` only while a command uses it ([`Document::mounted_art`]), so +/// when an id is not found otherwise that art is set on a copy of `doc`, which gives its objects +/// the ids `links.list` reports for them. +/// +/// [`Document::mounted_art`]: vectorcraft_doc::Document::mounted_art +pub(super) fn stored_objects( + doc: &vectorcraft_doc::Document, + mut want: std::collections::HashSet, +) -> Vec<(u64, std::sync::Arc)> { + let mut out = vec![]; + collect_stored(doc, &mut want, &mut out); + if !want.is_empty() && doc.mounted_art.is_empty() { + let art = vectorcraft_brush::stored_art::StoredArt::read(doc); + if !art.is_empty() { + let mut d = doc.clone(); + art.mount(&mut d); + collect_stored(&d, &mut want, &mut out); + } + } + out.sort_by_key(|(id, _)| *id); + out +} + +/// Adds the objects of `d` outside the layer tree whose ids are in `want` to `out`, taking their +/// ids out of `want`. +fn collect_stored( + d: &vectorcraft_doc::Document, + want: &mut std::collections::HashSet, + out: &mut Vec<(u64, std::sync::Arc)>, +) { + d.visit_stored_arcs(|n, place| { + if !place.in_layers() && want.remove(&n.id.0) { + out.push((n.id.0, std::sync::Arc::clone(n))); + } + }); +} + /// The ids of the selected image objects and placed documents. fn selected_images(app: &VectorcraftApp) -> Vec { let Some(st) = app.session.active() else { return vec![] }; @@ -179,6 +218,15 @@ fn selected_links(app: &VectorcraftApp, ctx: &egui::Context) -> Vec { ids } +/// [`selected_links`] with the app's window context, for a command run outside the panel (the +/// selected images and placed documents alone when there is no window). +pub(crate) fn selected_rows_of_app(app: &VectorcraftApp) -> Vec { + match app.ui_ctx.clone() { + Some(ctx) => selected_links(app, &ctx), + None => selected_images(app), + } +} + /// The rows of `list` whose image is selected. fn selected_rows<'a>(list: &'a Value, selected: &[u64]) -> Vec<&'a Value> { list["links"].as_array().into_iter().flatten().filter(|r| r["id"].as_u64().is_some_and(|id| selected.contains(&id))).collect() @@ -318,6 +366,48 @@ pub(crate) fn open_file(app: &mut VectorcraftApp, p: &Value, reveal: bool) -> Re Ok(json!({ "path": path })) } +/// The UI command `links.copyInfo {ids?}` (the panel menu's Copy Info): copy the file names of +/// images and placed documents `ids` (default: the selected rows, [`selected_rows_of_app`], in the +/// order `links.list` gives them; `null` counts as left out) to the clipboard, one per line in that +/// order → `{text, names}`. An embedded image gives the name its row shows. +pub(crate) fn copy_info(app: &mut VectorcraftApp, p: &Value) -> Result { + let key = "ids"; + let given = match p.get(key) { + None | Some(Value::Null) => None, + Some(Value::Array(a)) => { + let mut out = Vec::with_capacity(a.len()); + for (index, value) in a.iter().enumerate() { + out.push(value.as_u64().ok_or_else(|| format!("`{key}` entry {index} is {value}, not a non-negative integer object id"))?); + } + Some(out) + } + Some(_) => return Err(format!("{key} must be an array of non-negative integer object ids")), + }; + let list = app.session.execute("links.list", &json!({})).map_err(|e| e.to_string())?; + let rows: Vec<&Value> = list["links"].as_array().into_iter().flatten().collect(); + let wanted = match given { + Some(wanted) => wanted, + None => { + let sel = selected_rows_of_app(app); + ids(&rows, |r| r["id"].as_u64().is_some_and(|id| sel.contains(&id))) + } + }; + let by_id: std::collections::HashMap = + rows.iter().filter_map(|r| Some((r["id"].as_u64()?, r["name"].as_str().unwrap_or_default()))).collect(); + let mut names = Vec::with_capacity(wanted.len()); + for id in &wanted { + let name = by_id.get(id).ok_or_else(|| format!("object {} is not an image or a linked file", *id))?; + names.push((*name).to_string()); + } + if names.is_empty() { + return Err("select the images, or pass ids".into()); + } + let text = names.join("\n"); + app.clipboard_out = Some(text.clone()); + app.status("Copied the link info"); + Ok(json!({ "text": text, "names": names })) +} + /// Whether Edit Original may hand `path` to the system's default app: a regular file (after /// following links) whose name, and the name it links to, have the extension of a format /// VectorCraft reads. Anything else (a folder or app bundle, a script, a shortcut) is refused. @@ -360,8 +450,8 @@ fn badge(ui: &Ui, r: egui::Rect, status: &str) { } /// The tooltip of row `r`. A row outside the layer tree also names where it is stored -/// (`links.list`'s `owner`): the symbol, graph design or pattern whose art holds it, and the object -/// whose opacity mask holds it, by `mask` (that object's name) or else by its id. +/// (`links.list`'s `owner`): the symbol, graph design, pattern or brush whose art holds it, and the +/// object whose opacity mask holds it, by `mask` (that object's name) or else by its id. pub(super) fn status_tip(r: &Value, mask: Option) -> String { let tip = file_tip(r); let owner = &r["owner"]; @@ -370,6 +460,7 @@ pub(super) fn status_tip(r: &Value, mask: Option) -> String { Some("symbol") => Some(tl!("Symbols")), Some("graphDesign") => Some(tl!("Graph Design")), Some("pattern") => Some(tl!("Pattern")), + Some("brush") => Some(tl!("Brushes")), _ => None, }; let tip = match art { @@ -692,7 +783,8 @@ fn link_info(ui: &mut Ui, info: Option<&Value>, units: vectorcraft_doc::Unit) { } /// The panel's flyout menu: the link commands for the selected rows, Select Linked / Embedded / -/// Missing / Modified for the whole document, and the Show, Sort and thumbnail options. +/// Missing / Modified for the whole document, the Show and Sort options, Copy Info and the +/// thumbnail options. pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let o = options(ui.ctx()); // The rows the panel shows (the menu opens from it). @@ -779,6 +871,10 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { } } ui.separator(); + if menu_item(ui, tl!("Copy Info"), any, false) { + crate::menus::invoke(app, "links.copyInfo", json!({ "ids": ids(&sel, |_| true) })); + } + ui.separator(); for (px, label) in THUMBS { if menu_item(ui, tl!(label), true, o.thumb == px) { set_options(ui.ctx(), |o| o.thumb = px); diff --git a/crates/ui-egui/src/panels/opentype.rs b/crates/ui-egui/src/panels/opentype.rs index 64daf1ac76..2d872872ff 100644 --- a/crates/ui-egui/src/panels/opentype.rs +++ b/crates/ui-egui/src/panels/opentype.rs @@ -1,13 +1,13 @@ //! OpenType panel: per-character OpenType features (ligatures, alternates, swashes, small caps, -//! ordinals, fractions, figure style, position) for the selected text or the Type tool's selected -//! characters. +//! ordinals, fractions, figure style, position) for the selected text (every frame of each +//! selected threaded story) or the Type tool's selected characters. use egui::Ui; use serde_json::json; use vectorcraft_doc::{CharStyle, NodeKind}; use vectorcraft_text::{EXTRA_FEATURES, FontDb, OtFeatures, StylisticSet}; -use super::character::{shared, text_editing, text_style}; +use super::character::{any_style, shared, text_editing, text_style}; use crate::VectorcraftApp; use crate::widgets::{self, menu_item}; @@ -112,6 +112,22 @@ fn position_label(shown: Option) -> &'static str { shown.and_then(|i| POSITIONS.get(i).copied()).unwrap_or("Mixed") } +/// The Figure menu entry for the characters the panel acts on, or `None` when they differ. +fn shown_figure(app: &VectorcraftApp) -> Option { + shared(app, |s| figure(&OtFeatures::from_tags(s.features.iter().map(String::as_str)))) +} + +/// Whether `flag` is on for every character the panel acts on (`Some(true)`), for none of them +/// (`Some(false)`), or only for some (`None`). +fn shown_flag(app: &VectorcraftApp, flag: Flag) -> Option { + shared(app, |s| flag.get(&OtFeatures::from_tags(s.features.iter().map(String::as_str)))) +} + +/// The Figure menu's text for entry `shown`: Mixed when the characters differ. +fn figure_label(shown: Option) -> &'static str { + shown.and_then(|i| FIGURES.get(i).copied()).unwrap_or("Mixed") +} + /// A change one of the panel's controls makes to the features of each character it acts on. #[derive(Clone, Copy)] enum Change { @@ -161,7 +177,8 @@ fn set(app: &mut VectorcraftApp, f: OtFeatures) { } /// Send `tags` as the `key` param (`features` or `featureChanges`) for the Type tool's range or -/// caret, or else for the selected type. +/// caret, or else for every frame of the selected stories +/// ([`super::character::selected_stories`]). fn run_features(app: &mut VectorcraftApp, key: &str, tags: Vec) { // After Select All in threaded text: every frame of the story. let story = super::character::text_story(app).and_then(|story| story.first().copied()); @@ -169,7 +186,11 @@ fn run_features(app: &mut VectorcraftApp, key: &str, tags: Vec) { (Some(_), Some(first)) => ("text.setRangeStyle", json!({ "id": first.0, "story": true })), (Some((id, a, b)), None) if b > a => ("text.setRangeStyle", json!({ "id": id.0, "start": a, "end": b })), (Some((id, _, _)), None) => ("text.setRangeStyle", json!({ "id": id.0 })), - (None, _) => ("text.setStyle", json!({})), + (None, _) => { + let mut p = json!({}); + super::character::target_selected_stories(app, &mut p); + ("text.setStyle", p) + } }; p[key] = json!(tags); if let Err(e) = app.run(cmd, p) { @@ -182,12 +203,11 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { widgets::dim_label(ui, tl!("Select text to set its OpenType features.")); return; }; - let cur = OtFeatures::from_tags(st.features.iter().map(String::as_str)); let mut change = None; + let fig = shown_figure(app); ui.horizontal(|ui| { widgets::dim_label(ui, tl!("Figure:")); - let fig = figure(&cur); - if let Some(i) = widgets::dropdown(ui, "ot-figure", FIGURES[fig], &FIGURES, 170.0) { + if let Some(i) = widgets::dropdown(ui, "ot-figure", figure_label(fig), &FIGURES, 170.0) { change = Some(Change::Figure(i)); } }); @@ -199,26 +219,30 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } }); widgets::divider(ui); - let mut next = cur; - if let Some(c) = change { - c.apply(&mut next); - } + // A row whose characters differ shows a dash, and a click turns the feature on for all of them. for (label, flag) in rows() { - let on = flag.get(&next); - if widgets::check(ui, label, on, true) { - change = Some(Change::Toggle(flag, !on)); + let shown = shown_flag(app, flag); + if widgets::check3(ui, label, shown, true) { + change = Some(Change::Toggle(flag, shown != Some(true))); } } // The font, not the text, decides which numbered sets can be offered. Each set is an // independent feature, so the menu permits several at once. A font's own label wins over - // the numbered fallback. See the public Stylistic Sets help page. - let sets = offered_sets(&st); + // the numbered fallback. See the public Stylistic Sets help page. A set is checked when every + // character has it. + let sets: Vec<(StylisticSet, Flag, bool)> = offered_sets(&st) + .into_iter() + .map(|set| { + let flag = Flag::Extra(EXTRA_FEATURES[usize::from(set.number - 1)]); + let on = shown_flag(app, flag) == Some(true); + (set, flag, on) + }) + .collect(); ui.add_enabled_ui(!sets.is_empty(), |ui| { ui.menu_button(tl!("Stylistic Sets"), |ui| { widgets::menu_scroll(ui, |ui| { - for set in &sets { - let flag = Flag::Extra(EXTRA_FEATURES[usize::from(set.number - 1)]); - let on = flag.get(&next); + for (set, flag, on) in &sets { + let (flag, on) = (*flag, *on); if widgets::check_name(ui, &set_label(set), on) { change = Some(Change::Toggle(flag, !on)); } @@ -226,7 +250,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { }); }); }); - if cur.ligatures && vectorcraft_text::ligatures_suppressed_by(st.tracking) && !vectorcraft_text::explicit_ligatures(&st.features) { + if tracking_drops_ligatures(app) { widgets::dim_label(ui, tl!("Ligatures are off while the text is tracked.")); } if let Some(c) = change { @@ -234,6 +258,17 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } } +/// Whether tracking turns off the standard ligatures of any character the panel acts on: one with +/// Standard Ligatures on, tracked past [`vectorcraft_text::ligatures_suppressed_by`]'s limit and +/// without an explicit `liga` or `clig` tag ([`vectorcraft_text::explicit_ligatures`]). +fn tracking_drops_ligatures(app: &VectorcraftApp) -> bool { + any_style(app, |s| { + OtFeatures::from_tags(s.features.iter().map(String::as_str)).ligatures + && vectorcraft_text::ligatures_suppressed_by(s.tracking) + && !vectorcraft_text::explicit_ligatures(&s.features) + }) +} + /// The stylistic sets of the font `st` names. A font that is not available offers none, rather than /// the sets of the face drawn in its place. fn offered_sets(st: &vectorcraft_doc::CharStyle) -> Vec { @@ -278,6 +313,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { #[cfg(test)] mod tests { use serde_json::Value; + use vectorcraft_doc::NodeId; use super::*; @@ -481,6 +517,90 @@ mod tests { } } + /// The features of every run of `id`, each as its tags. + fn frame_features(app: &VectorcraftApp, id: u64) -> Vec> { + match &app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind { + NodeKind::Text(t) => t.runs.iter().map(|r| r.style.features.clone()).collect(), + _ => panic!("not text"), + } + } + + /// With the Selection tool a selected frame of threaded text stands for its whole story: the + /// Figure and Position menus show Mixed when a locked or hidden frame differs, and a choice + /// reaches every frame in one undo step, each keeping its other features, while other type keeps + /// its own. A story selected through two frames and a group is changed once. + #[test] + fn selection_tool_features_reach_every_frame_of_the_story() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 900, "height": 300})).unwrap(); + let story = "The quick brown fox jumps over the lazy dog 1234.\n".repeat(12); + let area = json!({"x": 10, "y": 10, "text": story, "size": 12, "area": {"width": 150, "height": 60}}); + let a = app.run("text.create", area).unwrap()["id"].as_u64().unwrap(); + let b = app.run("text.thread.add", json!({"from": a, "rect": [200, 10, 150, 60]})).unwrap()["id"].as_u64().unwrap(); + let c = app.run("text.thread.add", json!({"from": b, "rect": [400, 10, 150, 200]})).unwrap()["id"].as_u64().unwrap(); + let other = app.run("text.create", json!({"x": 10, "y": 250, "text": "Other 12", "size": 12})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [b]})).unwrap(); + app.run("object.lock", json!({})).unwrap(); + app.run("select.set", json!({"ids": [c]})).unwrap(); + app.run("object.hide", json!({})).unwrap(); + app.run("text.setStyle", json!({"ids": [c], "features": ["onum", "smcp", "sups", "-liga"]})).unwrap(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + for id in [a, b, c] { + assert!(!frame_features(&app, id).is_empty(), "frame {id} holds text"); + } + assert_eq!(shown_figure(&app), None, "the hidden frame's figures differ"); + assert_eq!(figure_label(shown_figure(&app)), "Mixed"); + assert_eq!(shown_position(&app), None, "the hidden frame's position differs"); + let hidden = frame_features(&app, c); + let has = |app: &VectorcraftApp, id: u64, tag: &str| frame_features(app, id).iter().all(|f| f.iter().any(|t| t == tag)); + + let undo = undo_steps(&app); + edit(&mut app, Change::Figure(1)); + assert_eq!(undo_steps(&app), undo + 1, "one undo step"); + assert_eq!(shown_figure(&app), Some(1)); + for id in [a, b] { + assert!(frame_features(&app, id).iter().all(|f| *f == ["tnum"]), "frame {id}: {:?}", frame_features(&app, id)); + } + assert!( + ["smcp", "sups", "-liga", "tnum"].iter().all(|t| has(&app, c, t)) + && frame_features(&app, c).iter().all(|f| !f.iter().any(|t| t == "onum")), + "{:?}", + frame_features(&app, c) + ); + assert!(frame_features(&app, other).iter().all(Vec::is_empty), "other type keeps its features"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(frame_features(&app, c), hidden, "undo restores the hidden frame"); + + // Standard Ligatures is off in the hidden frame only: its row shows a dash, and a click on + // it turns ligatures on in every frame. + let liga = rows().into_iter().find(|(l, _)| *l == "Standard Ligatures").map(|(_, f)| f); + let Some(liga) = liga else { panic!("no Standard Ligatures row") }; + assert_eq!(shown_flag(&app, liga), None); + let ctx = egui::Context::default(); + let draw = |app: &mut VectorcraftApp, ui: &mut Ui| show(app, ui); + super::super::tests_appearance::frame_events(&ctx, &mut app, vec![], draw); + let texts = super::super::tests_appearance::frame_events(&ctx, &mut app, vec![], draw); + let at = super::super::tests_appearance::text_rect(&texts, "Standard Ligatures").center(); + let undo = undo_steps(&app); + super::super::tests_appearance::click(&ctx, &mut app, at, draw); + assert_eq!(undo_steps(&app), undo + 1, "one undo step"); + assert_eq!(shown_flag(&app, liga), Some(true)); + for id in [a, b, c] { + assert!(frame_features(&app, id).iter().all(|f| !f.iter().any(|t| t == "-liga")), "frame {id} has ligatures"); + } + assert!(has(&app, c, "smcp"), "the hidden frame keeps its other features"); + + // Two frames of the story and the other type in a group: each story once. + app.run("object.unlockAll", json!({})).unwrap(); + app.run("select.set", json!({"ids": [a, other]})).unwrap(); + let group = app.run("object.group", json!({})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [group, b]})).unwrap(); + edit(&mut app, Change::Position(1)); + for id in [a, b, c, other] { + assert!(frame_features(&app, id).iter().all(|f| f.iter().filter(|t| *t == "sups").count() == 1), "frame {id} has sups once"); + } + } + /// Type with two positions turned on shows the Position menu as mixed, and the entry of one /// of them turns the other off. #[test] @@ -535,6 +655,45 @@ mod tests { ); } + /// With the Selection tool on the first frame of a threaded story, the tracked-ligatures note + /// reads every frame: it shows when a later, locked frame is tracked with Standard Ligatures + /// on, and not once that frame's ligatures are explicit, off, or its tracking is back within + /// the limit. + #[test] + fn ligature_note_reads_every_frame_of_the_story() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 900, "height": 300})).unwrap(); + let story = "The quick brown fox jumps over the lazy dog and keeps running far beyond the first frame. ".repeat(6); + let area = json!({"x": 10, "y": 10, "text": story, "size": 12, "area": {"width": 150, "height": 60}}); + let a = app.session.execute("text.create", &area).unwrap()["id"].clone(); + let b = app.session.execute("text.thread.add", &json!({"from": a, "rect": [200, 10, 150, 60]})).unwrap()["id"].clone(); + assert!(!run_features(&mut app, &b, 4).is_empty(), "the second frame holds text"); + app.session.execute("text.setStyle", &json!({"ids": [b], "tracking": 100})).unwrap(); + app.session.execute("select.set", &json!({"ids": [b]})).unwrap(); + app.session.execute("object.lock", &json!({})).unwrap(); + app.session.execute("select.set", &json!({"ids": [a]})).unwrap(); + assert_eq!(text_editing(&app), None); + assert_eq!(text_style(&app).unwrap().0.tracking, 0.0, "the panel reads its first run from the first frame"); + assert!(tracking_drops_ligatures(&app), "the tracked second frame shows the note"); + let ctx = egui::Context::default(); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(&mut app, ui)); + out.textures_delta.clear(); + // Commands write `liga` as the default and leave it out; an opened file can keep it. + let b_id = NodeId(b.as_u64().unwrap()); + for tags in [&["liga"][..], &["clig"][..], &["-liga"][..]] { + let doc = std::sync::Arc::make_mut(&mut app.session.doc_mut().unwrap().doc); + let Some(NodeKind::Text(t)) = doc.node_mut(b_id).map(|n| &mut n.kind) else { panic!("no second frame") }; + for r in &mut t.runs { + r.style.features = tags.iter().map(|s| s.to_string()).collect(); + } + assert!(!tracking_drops_ligatures(&app), "{tags:?}"); + } + app.session.execute("text.setStyle", &json!({"ids": [b], "features": [], "tracking": 20})).unwrap(); + assert!(!tracking_drops_ligatures(&app), "tracking within the limit"); + app.session.execute("text.setStyle", &json!({"ids": [b], "tracking": -100})).unwrap(); + assert!(tracking_drops_ligatures(&app), "tight tracking shows the note too"); + } + /// At a caret whose insertion style is already a denominator, Denominator still reaches the /// characters the command styles at a caret (all of them) in one undo step; chosen again once /// every character has it, it adds no undo step. diff --git a/crates/ui-egui/src/panels/paragraph.rs b/crates/ui-egui/src/panels/paragraph.rs index e02d81e14c..e594052f60 100644 --- a/crates/ui-egui/src/panels/paragraph.rs +++ b/crates/ui-egui/src/panels/paragraph.rs @@ -79,13 +79,7 @@ fn para_cmd(app: &mut VectorcraftApp, cmd: &str, p: Value) { /// Run `cmd` on the paragraphs the Paragraph panel acts on ([`format`]) and return its result. With /// the Selection tool these are the paragraphs of every frame of the selected stories /// ([`super::character::selected_stories`]). -pub(crate) fn run_on_paragraphs(app: &mut VectorcraftApp, cmd: &str, p: Value) -> Result { - run_on(app, cmd, p, true) -} - -/// [`run_on_paragraphs`], with the Selection tool on the selected type objects alone unless -/// `stories`. -fn run_on(app: &mut VectorcraftApp, cmd: &str, mut p: Value, stories: bool) -> Result { +pub(crate) fn run_on_paragraphs(app: &mut VectorcraftApp, cmd: &str, mut p: Value) -> Result { if let Some((id, a, b)) = super::character::text_editing(app) { super::character::end_typing(app); match super::character::text_story(app) { @@ -97,7 +91,7 @@ fn run_on(app: &mut VectorcraftApp, cmd: &str, mut p: Value, stories: bool) -> R p["end"] = json!(b); } } - } else if stories { + } else { super::character::target_selected_stories(app, &mut p); } app.run(cmd, p) @@ -260,7 +254,7 @@ pub(crate) fn shared_single_word_justify(app: &VectorcraftApp) -> Option(app: &VectorcraftApp, field: impl Fn(&ParaStyle) -> T) -> Option { +pub(crate) fn shared_para(app: &VectorcraftApp, field: impl Fn(&ParaStyle) -> T) -> Option { let mut acc = Shared::None; let mut any = false; visit_paragraphs(app, |p| { @@ -474,12 +468,13 @@ pub(crate) fn number_sample(style: vectorcraft_doc::text::NumberStyle, n: u32) - } /// Type › Bullets and Numbering › Convert to Text (`type.convertListToText`): the markers of the -/// list paragraphs of the selected type, or of those the Type tool's selection touches, become -/// characters of the text and the lists are turned off (`text.convertListToText`, which also moves -/// the Type tool's anchor and caret past the characters inserted at or before them). +/// list paragraphs the Paragraph panel acts on ([`run_on_paragraphs`]: with the Selection tool, +/// every frame of the selected stories) become characters of the text and the lists are turned +/// off (`text.convertListToText`, which also moves the Type tool's anchor and caret past the +/// characters inserted at or before them). pub(crate) fn convert_list_to_text(app: &mut VectorcraftApp) -> Result { text_style(app).ok_or("select some type first")?; - run_on(app, "text.convertListToText", json!({}), false) + run_on_paragraphs(app, "text.convertListToText", json!({})) } /// The Bullets button and the arrow beside it (Paragraph panel). The button makes the paragraphs diff --git a/crates/ui-egui/src/panels/paragraph/tests.rs b/crates/ui-egui/src/panels/paragraph/tests.rs index 180f0b1fa1..f570beaeca 100644 --- a/crates/ui-egui/src/panels/paragraph/tests.rs +++ b/crates/ui-egui/src/panels/paragraph/tests.rs @@ -678,6 +678,50 @@ fn convert_to_text_keeps_the_caret_by_its_character_in_threaded_type() { assert_eq!(super::super::character::text_editing(&app).map(|(id, _, _)| id), Some(NodeId(a))); } +/// With the Selection tool, Convert to Text takes the same story as Apply Numbers: the numbers +/// of every frame of the selected story, its locked and hidden frames included, become characters +/// of the text in one undo step, and other type keeps its list. +#[test] +fn selection_tool_convert_to_text_takes_every_frame_of_the_story() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 900, "height": 300})).unwrap(); + let story = "The quick brown fox jumps over the lazy dog.\n".repeat(12); + let area = json!({"x": 10, "y": 10, "text": story, "size": 12, "area": {"width": 150, "height": 60}}); + let a = app.run("text.create", area).unwrap()["id"].as_u64().unwrap(); + let b = app.run("text.thread.add", json!({"from": a, "rect": [200, 10, 150, 60]})).unwrap()["id"].as_u64().unwrap(); + let c = app.run("text.thread.add", json!({"from": b, "rect": [400, 10, 150, 200]})).unwrap()["id"].as_u64().unwrap(); + let other = app.run("text.create", json!({"x": 10, "y": 250, "text": "Other", "size": 12})).unwrap()["id"].as_u64().unwrap(); + app.run("text.setFormat", json!({"ids": [other], "list": "bullet"})).unwrap(); + app.run("select.set", json!({"ids": [b]})).unwrap(); + app.run("object.lock", json!({})).unwrap(); + app.run("select.set", json!({"ids": [c]})).unwrap(); + app.run("object.hide", json!({})).unwrap(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + let frame = |app: &VectorcraftApp, id: u64| match &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => (t.plain_text(), (0..t.paragraph_count()).map(|i| t.para_at(i).list.is_some()).collect::>()), + _ => panic!("not text"), + }; + let undo_steps = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len(); + app.run("type.applyNumbers", json!({})).unwrap(); + for id in [a, b, c] { + let (_, lists) = frame(&app, id); + assert!(!lists.is_empty() && lists.iter().all(|l| *l), "Apply Numbers numbers frame {id}"); + } + let before = frame(&app, c); + + let steps = undo_steps(&app); + app.run("type.convertListToText", json!({})).unwrap(); + assert_eq!(undo_steps(&app), steps + 1, "one undo step"); + for id in [a, b, c] { + let (plain, lists) = frame(&app, id); + assert!(lists.iter().all(|l| !*l), "frame {id} leaves the list"); + assert!(plain.contains(".\tThe quick"), "frame {id} holds its numbers as text: {plain:?}"); + } + assert_eq!(frame(&app, other), ("Other".to_string(), vec![true]), "other type keeps its list"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(frame(&app, c), before, "undo restores the hidden frame"); +} + /// Reset Panel turns Hyphenate and Roman Hanging Punctuation off and sets the Hyphenation and /// Justification options back to their defaults in every paragraph it acts on, so the paragraphs /// save neither. @@ -1016,7 +1060,9 @@ fn reset_panel_leaves_an_undo_group_open_in_another_document() { // The second document is open before the group begins, so switching to it opens no group in it. app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); assert_eq!(app.session.active_index(), Some(1)); - app.run("text.create", json!({"x": 20, "y": 50, "text": "B"})).unwrap(); + let b = app.run("text.create", json!({"x": 20, "y": 50, "text": "B"})).unwrap()["id"].clone(); + // A reset that changes nothing records no step, so B starts away from the panel's defaults. + app.run("text.setFormat", json!({"id": b, "mojikumi": "none"})).unwrap(); app.session.set_active(0); app.run("edit.undoGroup.begin", json!({"label": "Batch"})).unwrap(); app.run("text.setFormat", json!({"id": a, "mojikumi": "none"})).unwrap(); diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index ad081ddfcd..c0abeb9dac 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -154,6 +154,69 @@ fn has_instances_selected(app: &VectorcraftApp) -> bool { instance_selected(app, |_| true) } +/// Collect the IDs of selected instances of symbol `name` (including inside groups). +fn selected_symbol_instances(app: &VectorcraftApp, name: &str) -> Vec { + let mut ids = vec![]; + if let Some(st) = app.session.active() { + for id in &st.selection.objects { + if let Some(n) = st.doc.node(*id) { + n.walk(&mut |c| { + if matches!(&c.kind, NodeKind::SymbolInstance { symbol, .. } if symbol == name) { + ids.push(c.id.0); + } + }); + } + } + } + ids +} + +/// A symbol item's context menu. +fn item_context_menu(app: &mut VectorcraftApp, ui: &mut Ui, name: &str) { + let center = app + .view() + .map(|v| v.center) + .or_else(|| app.session.active().and_then(|st| st.doc.artboards.first().map(|a| a.rect.center()))) + .unwrap_or(vectorcraft_geom::Point::ZERO); + + if menu_item(ui, tl!("Place Symbol Instance"), true, false) { + if let Err(e) = app.run("symbol.place", json!({ "name": name, "x": center.x, "y": center.y })) { + app.status(e); + } + ui.close(); + } + if menu_item(ui, tl!("Edit Symbol"), true, false) { + if let Err(e) = app.run("symbol.edit", json!({ "name": name })) { + app.status(e); + } + ui.close(); + } + if menu_item(ui, tl!("Duplicate Symbol"), true, false) { + if let Err(e) = app.run("symbol.duplicate", json!({ "name": name })) { + app.status(e); + } + ui.close(); + } + if menu_item(ui, tl!("Delete Symbol"), true, false) { + delete(app, &[], Some(name), false); + ui.close(); + } + let break_ids = selected_symbol_instances(app, name); + let break_enabled = !break_ids.is_empty(); + if menu_item(ui, tl!("Break Link to Symbol"), break_enabled, false) { + if let Err(e) = app.run("symbol.breakLink", json!({ "ids": break_ids })) { + app.status(e); + } + ui.close(); + } + if menu_item(ui, tl!("Select All Instances"), true, false) { + if let Err(e) = app.run("symbol.selectInstances", json!({ "name": name })) { + app.status(e); + } + ui.close(); + } +} + /// Does the selection hold a symbol instance with appearance changes of its own (a dynamic /// symbol's), which Reset drops? pub(crate) fn changed_instances_selected(app: &VectorcraftApp) -> bool { @@ -249,11 +312,19 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } chip(ui, &doc, &keys, egui::Rect::from_center_size(r.left_center() + vec2(3.0 + side / 2.0, 0.0), vec2(side, side)), n); ui.painter().text(r.left_center() + vec2(side + 10.0, 0.0), egui::Align2::LEFT_CENTER, n, egui::FontId::proportional(text), t.text); + let resp = resp.on_hover_text(n); if resp.double_clicked() { clicked = Some((n.clone(), true)); } else if resp.clicked() { clicked = Some((n.clone(), false)); } + if resp.secondary_clicked() && (sel.as_deref() != Some(n) || !marked.is_empty()) { + set_pstate(ui.ctx(), MARKED, (uid, Vec::::new())); + if let Err(e) = app.run("symbol.setCurrent", json!({ "name": n })) { + app.status(e); + } + } + resp.context_menu(|ui| item_context_menu(app, ui, n)); } } else { ui.horizontal_wrapped(|ui| { @@ -274,6 +345,13 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } else if resp.clicked() { clicked = Some((n.clone(), false)); } + if resp.secondary_clicked() && (sel.as_deref() != Some(n) || !marked.is_empty()) { + set_pstate(ui.ctx(), MARKED, (uid, Vec::::new())); + if let Err(e) = app.run("symbol.setCurrent", json!({ "name": n })) { + app.status(e); + } + } + resp.context_menu(|ui| item_context_menu(app, ui, n)); } }); } @@ -1498,4 +1576,165 @@ mod tests { bar(&mut app, vec![egui::Event::PointerMoved(at), button(at, true), button(at, false)]); assert!(close(xf(&app), master), "the Control bar's Reset resets the instance: {:?} vs {master:?}", xf(&app)); } + + /// Right-clicking a symbol in the Symbols panel selects it (if not already selected), + /// displays the context menu, and clicking an item dispatches the corresponding command. + #[test] + fn right_click_context_menu_in_symbols_panel_runs_actions() { + use egui_kittest::kittest::{NodeT, Queryable}; + + let has_instance = |doc: &Document, name: &str| { + let mut found = false; + for l in &doc.layers { + l.walk(&mut |c| found |= matches!(&c.kind, NodeKind::SymbolInstance { symbol, .. } if symbol == name)); + } + found + }; + + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + // Create two symbols "A" and "B" (clearing the instances symbol.new leaves) + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap(); + let id_a = app.run("symbol.new", json!({"name": "A"})).unwrap()["id"].as_u64().unwrap(); + app.run("edit.clear", json!({"ids": [id_a]})).unwrap(); + app.run("shape.rectangle", json!({"x": 50, "y": 10, "width": 30, "height": 20})).unwrap(); + let id_b = app.run("symbol.new", json!({"name": "B"})).unwrap()["id"].as_u64().unwrap(); + app.run("edit.clear", json!({"ids": [id_b]})).unwrap(); + + // Currently "B" is the current symbol + assert_eq!(current(&mut app), Some("B".to_string())); + + let mut h = egui_kittest::Harness::builder().with_size(vec2(260.0, 400.0)).with_accessibility_check(false).build_ui_state( + |ui, app: &mut VectorcraftApp| { + show(app, ui); + }, + app, + ); + h.run_steps(2); + + // In thumbnail view, get symbol A + let node_a = h.get_by_label("A"); + let pos_a = node_a.rect().center(); + + // Right-click symbol A + h.event(egui::Event::PointerMoved(pos_a)); + h.event(egui::Event::PointerButton { pos: pos_a, button: egui::PointerButton::Secondary, pressed: true, modifiers: Default::default() }); + h.event(egui::Event::PointerButton { pos: pos_a, button: egui::PointerButton::Secondary, pressed: false, modifiers: Default::default() }); + h.run_steps(2); + + // Right-clicking unselected "A" selected it + assert_eq!(current(h.state_mut()), Some("A".to_string())); + + // Context menu items are displayed + let place = h.get_by_label(" Place Symbol Instance"); + let _ = h.get_by_label(" Edit Symbol"); + let _ = h.get_by_label(" Duplicate Symbol"); + let _ = h.get_by_label(" Delete Symbol"); + let break_link = h.get_by_label(" Break Link to Symbol"); + let _ = h.get_by_label(" Select All Instances"); + + // Break Link to Symbol is disabled because no instances of A are selected + assert!(break_link.accesskit_node().is_disabled()); + + // 1. Click "Place Symbol Instance" + place.click(); + h.run_steps(2); + + // An instance of A is placed on the canvas and selected + let doc = &h.state().session.active().unwrap().doc; + assert!(has_instance(doc, "A")); + + // 2. Right-click symbol A again now that its instance is selected + // Place an instance of B as well and select both to verify Break Link is scoped to A + let inst_b = h.state_mut().run("symbol.place", json!({ "name": "B" })).unwrap()["id"].as_u64().unwrap(); + let inst_a = h.state().session.active().unwrap().doc.layers[0].children().unwrap()[0].id.0; + h.state_mut().run("select.set", json!({ "ids": [inst_a, inst_b] })).unwrap(); + h.run_steps(2); + + h.event(egui::Event::PointerMoved(pos_a)); + h.event(egui::Event::PointerButton { pos: pos_a, button: egui::PointerButton::Secondary, pressed: true, modifiers: Default::default() }); + h.event(egui::Event::PointerButton { pos: pos_a, button: egui::PointerButton::Secondary, pressed: false, modifiers: Default::default() }); + h.run_steps(2); + + // Now "Break Link to Symbol" is enabled + let break_link = h.get_by_label(" Break Link to Symbol"); + assert!(!break_link.accesskit_node().is_disabled()); + break_link.click(); + h.run_steps(2); + + // Link broken for A (no longer a SymbolInstance of A), while B remains an instance + let doc = &h.state().session.active().unwrap().doc; + assert!(!has_instance(doc, "A")); + assert!(has_instance(doc, "B")); + + // 3. Right-click A and click "Duplicate Symbol" + let before_syms = symbols(h.state_mut()); + h.event(egui::Event::PointerMoved(pos_a)); + h.event(egui::Event::PointerButton { pos: pos_a, button: egui::PointerButton::Secondary, pressed: true, modifiers: Default::default() }); + h.event(egui::Event::PointerButton { pos: pos_a, button: egui::PointerButton::Secondary, pressed: false, modifiers: Default::default() }); + h.run_steps(2); + + h.get_by_label(" Duplicate Symbol").click(); + h.run_steps(2); + + let after_syms = symbols(h.state_mut()); + assert_eq!(after_syms.len(), before_syms.len() + 1); + assert!(before_syms.iter().all(|s| after_syms.contains(s))); + assert!(after_syms.contains(&"A copy".to_string())); + + // 4. Right-click B and click "Edit Symbol" + let node_b = h.get_by_label("B"); + let pos_b = node_b.rect().center(); + h.event(egui::Event::PointerMoved(pos_b)); + h.event(egui::Event::PointerButton { pos: pos_b, button: egui::PointerButton::Secondary, pressed: true, modifiers: Default::default() }); + h.event(egui::Event::PointerButton { pos: pos_b, button: egui::PointerButton::Secondary, pressed: false, modifiers: Default::default() }); + h.run_steps(2); + + assert_eq!(current(h.state_mut()), Some("B".to_string())); + h.get_by_label(" Edit Symbol").click(); + h.run_steps(2); + assert!(h.state().session.active().unwrap().doc.symbol_edit.is_some()); + + // Exit symbol editing mode + h.state_mut().run("symbol.exitEditing", json!({})).unwrap(); + h.run_steps(2); + + // 5. Right-click B and click "Delete Symbol" + h.event(egui::Event::PointerMoved(pos_b)); + h.event(egui::Event::PointerButton { pos: pos_b, button: egui::PointerButton::Secondary, pressed: true, modifiers: Default::default() }); + h.event(egui::Event::PointerButton { pos: pos_b, button: egui::PointerButton::Secondary, pressed: false, modifiers: Default::default() }); + h.run_steps(2); + + h.get_by_label(" Delete Symbol").click(); + h.run_steps(2); + + // Dialog opened; cancelling preserves B + assert!(h.state().ui.dialog.is_some()); + h.state_mut().ui.dialog = None; + assert!(symbols(h.state_mut()).contains(&"B".to_string())); + + // Right-click B again and confirm deletion + h.event(egui::Event::PointerMoved(pos_b)); + h.event(egui::Event::PointerButton { pos: pos_b, button: egui::PointerButton::Secondary, pressed: true, modifiers: Default::default() }); + h.event(egui::Event::PointerButton { pos: pos_b, button: egui::PointerButton::Secondary, pressed: false, modifiers: Default::default() }); + h.run_steps(2); + h.get_by_label(" Delete Symbol").click(); + h.run_steps(2); + crate::dialogs::confirm(h.state_mut()).unwrap(); + assert!(!symbols(h.state_mut()).contains(&"B".to_string())); + + // Also test list view + set_pstate(&h.ctx, VIEW, View::SmallList); + h.run_steps(2); + let node_a = h.get_by_label("A"); + let pos_a = node_a.rect().center(); + h.event(egui::Event::PointerMoved(pos_a)); + h.event(egui::Event::PointerButton { pos: pos_a, button: egui::PointerButton::Secondary, pressed: true, modifiers: Default::default() }); + h.event(egui::Event::PointerButton { pos: pos_a, button: egui::PointerButton::Secondary, pressed: false, modifiers: Default::default() }); + h.run_steps(2); + + assert!(h.query_by_label(" Place Symbol Instance").is_some()); + h.get_by_label(" Select All Instances").click(); + h.run_steps(2); + } } diff --git a/crates/ui-egui/src/panels/tests_asset_export.rs b/crates/ui-egui/src/panels/tests_asset_export.rs index 82a6f21245..8b9a9ed884 100644 --- a/crates/ui-egui/src/panels/tests_asset_export.rs +++ b/crates/ui-egui/src/panels/tests_asset_export.rs @@ -514,8 +514,7 @@ fn the_preset_menu_saves_changes_and_opens_import_and_export() { #[cfg(not(target_arch = "wasm32"))] #[test] fn export_writes_into_the_picked_folder() { - let dir = std::env::temp_dir().join(format!("vc-asset-panel-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); + let dir = vectorcraft_testkit::TempDir::new("asset-panel"); let folder = dir.to_string_lossy().replace('\\', "/"); let (mut app, _, [a, _]) = app(false); let picked = folder.clone(); @@ -526,8 +525,179 @@ fn export_writes_into_the_picked_folder() { frame(&ctx, &mut app, vec![], false); let texts = frame(&ctx, &mut app, vec![], false); frame(&ctx, &mut app, click(at(&texts, "Export")), false); - assert!(dir.join("Badge.png").is_file(), "{:?}", std::fs::read_dir(&dir).map(|d| d.count())); + // Create Sub-folders is on by default: the 1x row's folder. + assert!(dir.join("1x").join("Badge.png").is_file(), "{:?}", std::fs::read_dir(&dir).map(|d| d.count())); +} + +/// The panel menu's Create Sub-folders and Open Location after Export are check items, on by +/// default, that change the settings the panel shares with Export for Screens, and the panel's +/// Export follows them. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn the_menu_sets_create_subfolders_and_open_location_and_export_follows_them() { + let dir = vectorcraft_testkit::TempDir::new("asset-panel-menu"); + let folder = dir.to_string_lossy().replace('\\', "/"); + let (mut app, _, [a, _]) = app(false); + let picked = folder.clone(); + app.services.pick_folder = Some(Box::new(move || Some(picked.clone()))); + let shown = Rc::new(RefCell::new(Vec::::new())); + let s = shown.clone(); + app.services.reveal = Some(Box::new(move |path: &str| { + s.borrow_mut().push(path.to_string()); + Ok(()) + })); + app.run("assets.add", json!({"ids": [a], "name": "Badge"})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + menu_frame(&ctx, &mut app, vec![]); + let texts = menu_frame(&ctx, &mut app, vec![]); + for item in ["✓ Create Sub-folders", "✓ Open Location after Export", " Format Settings…"] { + assert!(has(&texts, item), "{item}"); + } + // Both on: the 1x row's folder, and the file manager shows the file. + let export = |app: &mut VectorcraftApp| { + frame(&ctx, app, vec![], false); + let texts = frame(&ctx, app, vec![], false); + frame(&ctx, app, click(at(&texts, "Export")), false); + }; + export(&mut app); + assert!(dir.join("1x").join("Badge.png").is_file()); + assert_eq!(shown.borrow().len(), 1); + // Both turned off (a click lands on the items of the frame before). + menu_frame(&ctx, &mut app, vec![]); + menu_frame(&ctx, &mut app, click(at(&texts, "✓ Create Sub-folders"))); + let texts = menu_frame(&ctx, &mut app, vec![]); + menu_frame(&ctx, &mut app, click(at(&texts, "✓ Open Location after Export"))); + let settings = app.run("document.exportSettings", json!({})).unwrap()["settings"].clone(); + assert_eq!((&settings["subfolders"], &settings["openLocation"]), (&json!(false), &json!(false)), "{settings}"); + let texts = menu_frame(&ctx, &mut app, vec![]); + assert!(has(&texts, " Create Sub-folders") && has(&texts, " Open Location after Export")); + // Export for Screens opens on the same choices. + app.run("file.exportForScreens", json!({})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((&d.fields["subfolders"], &d.fields["openLocation"]), (&json!(false), &json!(false))); + crate::dialogs::cancel(&mut app); let _ = std::fs::remove_dir_all(&dir); + export(&mut app); + assert!(dir.join("Badge.png").is_file() && !dir.join("1x").exists()); + assert_eq!(shown.borrow().len(), 1, "no file manager after export"); + // Create Sub-folders on again: a folder per row. + menu_frame(&ctx, &mut app, vec![]); + menu_frame(&ctx, &mut app, click(at(&texts, " Create Sub-folders"))); + let settings = app.run("document.exportSettings", json!({})).unwrap()["settings"].clone(); + assert_eq!((&settings["subfolders"], &settings["folders"]), (&json!(true), &json!("rows")), "{settings}"); + // Only true and false are taken. + for bad in [json!({"openLocation": "yes"}), json!({"subfolders": 1})] { + assert!(app.run("assets.settings.set", bad.clone()).is_err(), "{bad}"); + } +} + +/// A folder per format, remembered by Export for Screens or a preset, is used by the panel's Export +/// too. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn export_uses_a_remembered_folder_per_format() { + let dir = vectorcraft_testkit::TempDir::new("asset-panel-format"); + let folder = dir.to_string_lossy().replace('\\', "/"); + let (mut app, _, [a, _]) = app(false); + app.services.pick_folder = Some(Box::new(move || Some(folder.clone()))); + let asset = app.run("assets.add", json!({"ids": [a], "name": "Badge"})).unwrap()["assets"][0].clone(); + // An export as Export for Screens sends it with Create Sub-folders by Format, which the + // document remembers. + let formats = json!([{"format": "png"}, {"format": "svg"}]); + app.run("document.exportForScreens", json!({"assets": [asset], "formats": formats, "folders": "format", "subfolders": false})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + menu_frame(&ctx, &mut app, vec![]); + assert!(has(&menu_frame(&ctx, &mut app, vec![]), "✓ Create Sub-folders")); + frame(&ctx, &mut app, vec![], false); + let texts = frame(&ctx, &mut app, vec![], false); + frame(&ctx, &mut app, click(at(&texts, "Export")), false); + assert!(dir.join("png").join("Badge.png").is_file() && dir.join("svg").join("Badge.svg").is_file()); +} + +/// Remembered empty folders are none, as an export reads them: Create Sub-folders is off in the +/// panel menu and in Export for Screens. +#[test] +fn empty_remembered_folders_are_create_subfolders_off() { + let (mut app, _, [a, _]) = app(true); + let asset = app.run("assets.add", json!({"ids": [a]})).unwrap()["assets"][0].clone(); + app.run("document.exportForScreens", json!({"assets": [asset], "formats": [{"format": "svg"}], "folders": "", "subfolders": true})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + menu_frame(&ctx, &mut app, vec![]); + assert!(has(&menu_frame(&ctx, &mut app, vec![]), " Create Sub-folders")); + app.run("file.exportForScreens", json!({})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["subfolders"], false); +} + +/// Open Location after Export turned off in a document without settings leaves Create Sub-folders +/// on, in the panel menu and in Export for Screens. +#[test] +fn open_location_off_leaves_create_subfolders_on() { + let (mut app, _, _) = app(false); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + menu_frame(&ctx, &mut app, vec![]); + let texts = menu_frame(&ctx, &mut app, vec![]); + menu_frame(&ctx, &mut app, click(at(&texts, "✓ Open Location after Export"))); + let texts = menu_frame(&ctx, &mut app, vec![]); + assert!(has(&texts, "✓ Create Sub-folders") && has(&texts, " Open Location after Export")); + app.run("file.exportForScreens", json!({})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((&d.fields["subfolders"], &d.fields["openLocation"]), (&json!(true), &json!(false))); +} + +/// Editing the rows of a document without a Create Sub-folders choice keeps it on, in Export for +/// Screens too; a preset that turns it off shows it off, and the menu turns it on again. +#[test] +fn row_edits_keep_create_subfolders_on_and_a_preset_can_turn_it_off() { + let (mut app, _, [a, _]) = app(true); + app.run("assets.add", json!({"ids": [a]})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + frame(&ctx, &mut app, vec![], false); + let texts = frame(&ctx, &mut app, vec![], false); + frame(&ctx, &mut app, click(at(&texts, "+ Add Scale")), false); + assert!(has(&menu_frame(&ctx, &mut app, vec![]), "✓ Create Sub-folders")); + app.run("file.exportForScreens", json!({})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["subfolders"], true); + crate::dialogs::cancel(&mut app); + // Logo Package sorts by format: checked, as in Export for Screens. Turned off, the sorting + // ends; turned on again, a folder per row. + app.run("assets.settings.set", json!({"exportPreset": "Logo Package"})).unwrap(); + let texts = menu_frame(&ctx, &mut app, vec![]); + menu_frame(&ctx, &mut app, click(at(&texts, "✓ Create Sub-folders"))); + let settings = app.run("document.exportSettings", json!({})).unwrap()["settings"].clone(); + assert_eq!((&settings["subfolders"], &settings["folders"]), (&json!(false), &json!("none")), "{settings}"); + app.run("file.exportForScreens", json!({})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["subfolders"], false); + crate::dialogs::cancel(&mut app); + let texts = menu_frame(&ctx, &mut app, vec![]); + menu_frame(&ctx, &mut app, click(at(&texts, " Create Sub-folders"))); + let settings = app.run("document.exportSettings", json!({})).unwrap()["settings"].clone(); + assert_eq!((&settings["subfolders"], &settings["folders"]), (&json!(true), &json!("rows")), "{settings}"); + let texts = menu_frame(&ctx, &mut app, vec![]); + assert!(has(&texts, "✓ Create Sub-folders")); + // The web downloads the files: the menu has no Open Location after Export. + assert!(!texts.iter().any(|(t, _)| t.ends_with("Open Location after Export"))); +} + +/// Format Settings… in the panel menu opens Export for Screens on its Assets tab, showing the +/// first row's format settings. +#[test] +fn format_settings_opens_the_first_rows_format_settings() { + let (mut app, _, [a, b]) = app(true); + app.run("assets.add", json!({"ids": [a, b], "multiple": true})).unwrap(); + app.run("assets.settings.set", json!({"formats": [{"format": "jpeg"}, {"format": "svg"}]})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + menu_frame(&ctx, &mut app, vec![]); + let texts = menu_frame(&ctx, &mut app, vec![]); + menu_frame(&ctx, &mut app, click(at(&texts, " Format Settings…"))); + let d = app.ui.dialog.as_ref().expect("Export for Screens"); + assert_eq!((d.kind.as_str(), &d.fields["tab"], &d.fields["__settings"]), (crate::dialogs::EXPORT_FOR_SCREENS, &json!("assets"), &json!("jpg"))); + assert_eq!(d.fields["assets"].as_array().map(Vec::len), Some(2)); } #[test] @@ -716,8 +886,7 @@ fn tiff_panel_preserves_shared_antialias_and_explicit_overrides() { #[cfg(not(target_arch = "wasm32"))] #[test] fn tiff_saved_aliases_use_document_defaults_and_explicit_rgb() { - let dir = std::env::temp_dir().join(format!("vc-asset-tiff-aliases-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); + let dir = vectorcraft_testkit::TempDir::new("asset-tiff-aliases"); // The first case is the historical control: saved tif without an explicit model must be CMYK. // Native picked folders let the mixed-row case inspect each file without introducing a ZIP decoder. for (case, (alias, rgb_override, mixed)) in @@ -764,7 +933,6 @@ fn tiff_saved_aliases_use_document_defaults_and_explicit_rgb() { "direct export preserves saved aliases and explicit options" ); } - let _ = std::fs::remove_dir_all(&dir); } /// Export 3D Object in the panel menu collects the selected 3D object; its tile is marked 3D, the diff --git a/crates/ui-egui/src/panels/tests_links.rs b/crates/ui-egui/src/panels/tests_links.rs index 8055c1288c..2771fe568e 100644 --- a/crates/ui-egui/src/panels/tests_links.rs +++ b/crates/ui-egui/src/panels/tests_links.rs @@ -90,12 +90,56 @@ fn the_panel_lists_the_images_with_link_info_for_the_selected_one() { assert!(text.contains("Linked") && text.contains("300 × 200 px") && text.contains("Location"), "{text}"); // The flyout draws with every item. let menu = painted_text(&mut app, super::links::menu); - for item in ["Relink to Folder…", "Embed Image(s)", "Placement Options…", "Show Missing", "Sort by Status", "Large Thumbnails", "Show in Folder"] - { + for item in [ + "Relink to Folder…", + "Embed Image(s)", + "Placement Options…", + "Show Missing", + "Sort by Status", + "Sort by Size", + "Large Thumbnails", + "Show in Folder", + ] { assert!(menu.contains(item), "{item}: {menu}"); } } +/// Copy Info copies the file names of the selected links, or of `ids` in the order given, one per +/// line; it is off with nothing selected, and a bad `ids` leaves the clipboard as it was. +#[test] +fn copy_info_copies_the_file_names_of_the_links() { + let dir = Folder::new("copy-info"); + let (mut app, linked, embedded) = app(&dir); + let menu = painted_text(&mut app, super::links::menu); + assert!(menu.contains("Copy Info"), "{menu}"); + // The selection is the embedded image: its row's name. + assert!(crate::menus::enabled(&app, "links.copyInfo")); + let r = app.run("links.copyInfo", json!({})).unwrap(); + assert_eq!(r["names"], json!(["embedded.png"])); + assert_eq!(app.clipboard_out.take().as_deref(), Some("embedded.png")); + // Both selected: in the order the list gives them (the top image first). + app.run("select.set", json!({"ids": [linked, embedded]})).unwrap(); + assert_eq!(app.run("links.copyInfo", json!({})).unwrap()["text"], "embedded.png\nlinked.png"); + assert_eq!(app.clipboard_out.take().as_deref(), Some("embedded.png\nlinked.png")); + // `ids` in the order given, whatever is selected. + app.run("select.none", json!({})).unwrap(); + let r = app.run("links.copyInfo", json!({"ids": [linked, embedded]})).unwrap(); + assert_eq!(r["names"], json!(["linked.png", "embedded.png"])); + assert_eq!(app.clipboard_out.take().as_deref(), Some("linked.png\nembedded.png")); + // Errors copy nothing. + let rect = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 60, "height": 60})).unwrap()["id"].as_u64().unwrap(); + app.run("select.none", json!({})).unwrap(); + for bad in + [json!({"ids": [linked, rect]}), json!({"ids": [linked, 999_999]}), json!({"ids": "all"}), json!({"ids": [linked, -1]}), json!({"ids": []})] + { + assert!(app.run("links.copyInfo", bad.clone()).is_err(), "{bad}"); + assert!(app.clipboard_out.is_none(), "{bad}"); + } + assert!(!crate::menus::enabled(&app, "links.copyInfo")); + assert!(app.run("links.copyInfo", json!({})).is_err()); + assert!(app.clipboard_out.is_none()); +} + /// Shift-click selects the images of the rows from the last row clicked without Shift; Ctrl/Cmd-click /// adds or removes one image, and Ctrl/Cmd-Shift-click adds the rows' images to the selection. #[test] @@ -160,6 +204,11 @@ fn a_link_inside_a_symbol_is_listed_and_picked_in_the_panel() { click_row(&mut app, &ctx, "inside.png", egui::Modifiers::NONE, 1.0); assert!(selected(&app).is_empty(), "the canvas can't select it"); assert!(shown(&mut app, 1.5).iter().any(|t| t == "30 × 20 px"), "Link Info of the symbol's image"); + // Copy Info without ids copies the row picked in the panel. + app.ui_ctx = Some(ctx.clone()); + assert!(crate::menus::enabled(&app, "links.copyInfo")); + assert_eq!(app.run("links.copyInfo", json!({})).unwrap()["text"], "inside.png"); + assert_eq!(app.clipboard_out.take().as_deref(), Some("inside.png")); click_row(&mut app, &ctx, "layer.png", egui::Modifiers::COMMAND, 2.0); assert_eq!(selected(&app), [layer]); // Both rows are selected until the canvas selection changes: then the panel's pick goes too. @@ -189,6 +238,7 @@ fn a_nested_rows_tooltip_names_what_holds_it() { assert_eq!(tip(json!({"kind": "symbol", "name": "Mark"}), None), "/x/a.png\nSymbols: Mark"); assert_eq!(tip(json!({"kind": "pattern", "name": "Dots"}), None), "/x/a.png\nPattern: Dots"); assert_eq!(tip(json!({"kind": "graphDesign", "name": "Bar"}), None), "/x/a.png\nGraph Design: Bar"); + assert_eq!(tip(json!({"kind": "brush", "name": "Leaf", "index": 2}), None), "/x/a.png\nBrushes: Leaf"); assert_eq!(tip(json!({"kind": "layers", "maskOf": 7}), Some("")), "/x/a.png\nOpacity Mask: "); assert_eq!(tip(json!({"kind": "symbol", "name": "Mark", "maskOf": 7}), None), "/x/a.png\nSymbols: Mark\nOpacity Mask: 7"); // A row in the layers says only its file. @@ -229,6 +279,28 @@ fn a_mask_rows_tooltip_names_its_object_inside_a_symbol() { assert!(text.iter().any(|t| t.contains(&want)), "{want} in {text:?}"); } +/// The row of an image in a stored brush's art finds its object for the thumbnail, though that art +/// is set on the document only while a command uses it. +#[test] +fn a_row_in_a_stored_brushs_art_finds_its_object() { + let dir = Folder::new("brush-art"); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let leaf = dir.file("leaf.png", &png(30, 20)); + let id = app.run("file.place", json!({"path": leaf, "at": [100, 100]})).unwrap()["ids"][0].as_u64().unwrap(); + app.run("brush.new", json!({"type": "scatter", "name": "Leaf", "ids": [id]})).unwrap(); + app.run("edit.clear", json!({"ids": [id]})).unwrap(); + let list = app.run("links.list", json!({})).unwrap(); + let row = list["links"].as_array().unwrap().iter().find(|r| r["name"] == "leaf.png").unwrap_or_else(|| panic!("{list}")).clone(); + assert_eq!(row["owner"]["kind"], "brush", "{list}"); + let row = row["id"].as_u64().unwrap(); + let doc = &app.session.active().unwrap().doc; + assert!(doc.mounted_art.is_empty(), "the brush's art is not set on the document"); + let found = super::links::stored_objects(doc, [row].into()); + assert_eq!(found.iter().map(|(id, _)| *id).collect::>(), [row]); + assert!(matches!(found[0].1.kind, vectorcraft_doc::NodeKind::Image(_)), "{:?}", found[0].1.kind); +} + #[test] fn an_empty_document_shows_how_to_add_images() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); diff --git a/crates/ui-egui/src/panels/text_styles.rs b/crates/ui-egui/src/panels/text_styles.rs index 880de94c16..4f8ba904de 100644 --- a/crates/ui-egui/src/panels/text_styles.rs +++ b/crates/ui-egui/src/panels/text_styles.rs @@ -1,10 +1,11 @@ //! Character Styles and Paragraph Styles panels (one implementation, two kinds). //! -//! Click a style to apply it to the selected text (or the Type tool's selected characters); -//! Alt-click applies it and clears overrides. Double-clicking a character style's row opens its -//! Character Style Options (`ui.charStyleOptions`), as the panel menu does; a paragraph style's row -//! opens its Paragraph Style Options (`ui.paraStyleOptions`). The style of the -//! selection is highlighted, with a "+" when the text overrides some of its attributes. New makes +//! Click a style to apply it to the selected text (every frame of each selected threaded story) or +//! the Type tool's selected characters; Alt-click applies it and clears overrides. Double-clicking a +//! character style's row opens its Character Style Options (`ui.charStyleOptions`), as the panel +//! menu does; a paragraph style's row opens its Paragraph Style Options (`ui.paraStyleOptions`). +//! The style all of that text has is highlighted, with a "+" when some of the text overrides some +//! of its attributes; text in several styles highlights none. New makes //! a style from the selected text; Alt-click on New first asks for its name (`ui.newCharStyle`, //! `ui.newParaStyle`). @@ -15,8 +16,9 @@ use serde_json::{Map, Value, json}; use vectorcraft_doc::Document; use vectorcraft_engine::cmd::{fileio, textstyles}; -use super::character::{end_typing, text_editing, text_style}; +use super::character::{end_typing, shared, text_editing, text_style}; use super::memo::Memo; +use super::paragraph::shared_para; use super::{alt_held, pstate, selection_len, set_pstate}; use crate::VectorcraftApp; use crate::theme::Tokens; @@ -172,14 +174,25 @@ thread_local! { static LISTED: std::cell::Cell = const { std::cell::Cell::new(0) }; } -/// The selection's style name (Normal when none) and every one of its attributes, written as a -/// style holds them, if text is selected. -fn current(app: &VectorcraftApp, kind: Kind) -> Option<(Option, Map)> { - let (c, p) = text_style(app)?; - Some(match kind { - Kind::Char => (c.style_name.clone(), textstyles::char_attrs(&c)), - Kind::Para => (p.style_name.clone(), textstyles::para_attrs(&p)), - }) +/// The style name (`None`: the Normal style) that every character the panel acts on has (paragraph +/// styles: every paragraph), with the Selection tool in every frame of the selected stories; +/// `None` when they differ or no type is selected. +fn current(app: &VectorcraftApp, kind: Kind) -> Option> { + match kind { + Kind::Char => shared(app, |s| s.style_name.clone()), + Kind::Para => shared_para(app, |p| p.style_name.clone()), + } +} + +/// Whether any character (paragraph styles: paragraph) the panel acts on differs from the style +/// attributes `attrs` in one of them. +fn has_overrides(app: &VectorcraftApp, kind: Kind, attrs: &Map) -> bool { + let differs = |m: Map| attrs.iter().any(|(k, v)| m.get(k) != Some(v)); + let same = match kind { + Kind::Char => shared(app, |s| differs(textstyles::char_attrs(s))), + Kind::Para => shared_para(app, |p| differs(textstyles::para_attrs(p))), + }; + same != Some(false) } /// Parameters targeting the selection: the Type tool's selected characters (paragraph styles: the @@ -196,14 +209,19 @@ fn target(app: &VectorcraftApp, kind: Kind, mut p: Value) -> Value { } /// [`target`] for applying a style: after Select All in threaded text, all the text of every -/// frame of the story. +/// frame of the story; with the Selection tool, every frame of the selected stories +/// ([`super::character::selected_stories`]). fn apply_target(app: &VectorcraftApp, kind: Kind, mut p: Value) -> Value { + if text_editing(app).is_none() { + super::character::target_selected_stories(app, &mut p); + return p; + } match super::character::text_story(app) { - Some(story) if text_editing(app).is_some() => { + Some(story) => { p["ids"] = json!(story.iter().map(|f| f.0).collect::>()); p } - _ => target(app, kind, p), + None => target(app, kind, p), } } @@ -242,9 +260,8 @@ fn open_style_options(app: &mut VectorcraftApp, kind: Kind, name: &str) { pub fn show(app: &mut VectorcraftApp, ui: &mut Ui, kind: Kind) { let t = Tokens::get(ui.ctx()); let all = styles(app, kind); - let cur = current(app, kind); let normal = all.first().map(|s| s.0.clone()).unwrap_or_default(); - let cur_name = cur.as_ref().map(|(n, _)| n.clone().unwrap_or_else(|| normal.clone())); + let cur_name = current(app, kind).map(|n| n.unwrap_or_else(|| normal.clone())); let mut clicked: Option<(String, egui::Modifiers)> = None; // A double-clicked style's row, whose options open after the list is laid out. let mut options: Option = None; @@ -270,8 +287,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui, kind: Kind) { widgets::list_box(ui, |ui| { for (name, attrs, _) in &all { let is_cur = cur_name.as_deref() == Some(name.as_str()); - // Overrides: an attribute the style sets that the selection doesn't match. - let overridden = is_cur && cur.as_ref().is_some_and(|(_, m)| attrs.iter().any(|(k, v)| m.get(k) != Some(v))); + // Overrides: an attribute the style sets that some of the text doesn't match. + let overridden = is_cur && has_overrides(app, kind, attrs); let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click_and_drag()); if resp.drag_started_by(egui::PointerButton::Primary) { egui::DragAndDrop::set_payload(ui.ctx(), RowDrag { kind, name: name.clone() }); @@ -310,7 +327,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui, kind: Kind) { if scroll_to.is_some() { set_pstate::>(ui.ctx(), kind.scroll_key(), None); } - let has_text = cur.is_some(); + let has_text = text_style(app).is_some(); if let Some((name, m)) = clicked { sel = super::swatches::click_selection(ui, kind.anchor_key(), sel, &listed, &name, m); // Shift and Cmd/Ctrl clicks only highlight, as in the Graphic Styles panel. The second @@ -381,7 +398,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui, kind: Kind) { let normal = if kind == Kind::Char { "[Normal Character Style]" } else { "[Normal Paragraph Style]" }; let user = sel.as_ref().is_some_and(|s| s != normal); let doomed: Vec<&String> = many.iter().filter(|s| *s != normal).collect(); - let has_text = current(app, kind).is_some() || selection_len(app) > 0; + let has_text = text_style(app).is_some() || selection_len(app) > 0; let p = kind.prefix(); if menu_item(ui, &crate::i18n::fmt(tl!("New {kind} Style…"), &[("kind", kind.what_label())]), true, false) { // A later typing preview must not restore the document from before this capture. diff --git a/crates/ui-egui/src/panels/text_styles/tests.rs b/crates/ui-egui/src/panels/text_styles/tests.rs index a83103aec8..e550f82ab4 100644 --- a/crates/ui-egui/src/panels/text_styles/tests.rs +++ b/crates/ui-egui/src/panels/text_styles/tests.rs @@ -29,8 +29,8 @@ fn panels_draw_and_apply_headless() { out.textures_delta.clear(); } app.run("charStyle.apply", target(&app, Kind::Char, json!({"name": "Big"}))).unwrap(); - let (name, attrs) = current(&app, Kind::Char).unwrap(); - assert_eq!((name.as_deref(), attrs["size"].as_f64()), (Some("Big"), Some(30.0))); + let (style, _) = text_style(&app).unwrap(); + assert_eq!((current(&app, Kind::Char), style.size), (Some(Some("Big".to_string())), 30.0)); } #[test] @@ -818,6 +818,74 @@ fn the_styles_are_listed_once_per_document_version() { } } +/// The style names of `id`'s runs (`Kind::Para`: of its paragraphs). +fn frame_style_names(app: &VectorcraftApp, kind: Kind, id: u64) -> Vec> { + match &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) if kind == Kind::Char => t.runs.iter().map(|r| r.style.style_name.clone()).collect(), + NodeKind::Text(t) => (0..t.paragraph_count()).map(|i| t.para_at(i).style_name.clone()).collect(), + _ => panic!("not text"), + } +} + +/// With the Selection tool a selected frame of threaded text stands for its whole story, in both +/// panels: no row shows as the current style while a locked or hidden frame has another style, a +/// row click applies the style to every frame in one undo step and leaves other type alone, the +/// row shows "+" while a hidden frame overrides the style, and an Alt-click clears that override. +#[test] +fn selection_tool_styles_reach_every_frame_of_the_story() { + use egui::Modifiers; + for kind in [Kind::Char, Kind::Para] { + let what = kind.what(); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 900, "height": 300})).unwrap(); + let story = "The quick brown fox jumps over the lazy dog.\n".repeat(12); + let area = json!({"x": 10, "y": 10, "text": story, "size": 12, "area": {"width": 150, "height": 60}}); + let a = app.run("text.create", area).unwrap()["id"].as_u64().unwrap(); + let b = app.run("text.thread.add", json!({"from": a, "rect": [200, 10, 150, 60]})).unwrap()["id"].as_u64().unwrap(); + let c = app.run("text.thread.add", json!({"from": b, "rect": [400, 10, 150, 200]})).unwrap()["id"].as_u64().unwrap(); + let other = app.run("text.create", json!({"x": 10, "y": 250, "text": "Other", "size": 12})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [b]})).unwrap(); + app.run("object.lock", json!({})).unwrap(); + app.run("select.set", json!({"ids": [c]})).unwrap(); + app.run("object.hide", json!({})).unwrap(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + app.run(&format!("{}.new", kind.prefix()), json!({"name": "Plain"})).unwrap(); + app.run(&format!("{}.new", kind.prefix()), json!({"name": "Second", "attrs": {}})).unwrap(); + app.run(&format!("{}.apply", kind.prefix()), json!({"name": "Second", "ids": [c]})).unwrap(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + for id in [a, b, c] { + assert!(!frame_style_names(&app, kind, id).is_empty(), "frame {id} holds text"); + } + assert_eq!(current(&app, kind), None, "{what} Styles: the hidden frame has another style"); + + let ctx = egui::Context::default(); + let rows = |app: &mut VectorcraftApp, ui: &mut egui::Ui| { + ui.set_width(280.0); + show(app, ui, kind); + }; + let undo = app.session.doc().unwrap().history.undo.len(); + click_text_held(&ctx, &mut app, "Plain", Modifiers::NONE, rows); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1, "{what} Styles: one undo step"); + for id in [a, b, c] { + assert!(frame_style_names(&app, kind, id).iter().all(|n| n.as_deref() == Some("Plain")), "{what} Styles: frame {id}"); + } + assert!(frame_style_names(&app, kind, other).iter().all(Option::is_none), "{what} Styles: other type keeps its style"); + assert_eq!(current(&app, kind), Some(Some("Plain".to_string()))); + + app.run("text.setFormat", json!({"ids": [c], "kerning": 40, "composer": "singleLine"})).unwrap(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui, kind)); + assert!(shown.lines().any(|line| line == "Plain+"), "{what} Styles: the hidden frame's override shows: {shown}"); + // A new context, so that this click does not count as the second click of a double-click. + click_text_held(&egui::Context::default(), &mut app, "Plain+", Modifiers::ALT, rows); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui, kind)); + assert!(shown.lines().any(|line| line == "Plain"), "{what} Styles: Alt-click clears the override: {shown}"); + app.run("edit.undo", json!({})).unwrap(); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui, kind)); + assert!(shown.lines().any(|line| line == "Plain+"), "{what} Styles: undo brings the override back: {shown}"); + } +} + /// A row dragged from the highlighted styles carries all of them: dropped on Create New Style it /// duplicates each in one undo step and highlights the copies, and dropped on Delete it deletes each /// but the Normal style in one undo step and clears the highlight. A row from outside the highlight @@ -1201,7 +1269,7 @@ fn alt_clicking_new_paragraph_style_asks_for_its_name() { assert!(app.session.doc().unwrap().doc.para_styles.is_empty(), "no style is added before OK"); set_name(&mut app, "Body Copy"); crate::dialogs::confirm(&mut app).unwrap(); - let (_, attrs) = current(&app, Kind::Para).unwrap(); + let attrs = textstyles::para_attrs(&text_style(&app).unwrap().1); let doc = &app.session.doc().unwrap().doc; assert_eq!(doc.para_styles.iter().map(|s| (s.name.as_str(), &s.attrs)).collect::>(), [("Body Copy", &attrs)]); diff --git a/crates/ui-egui/src/panels/transparency.rs b/crates/ui-egui/src/panels/transparency.rs index 229a23c411..4279ac11e4 100644 --- a/crates/ui-egui/src/panels/transparency.rs +++ b/crates/ui-egui/src/panels/transparency.rs @@ -20,12 +20,12 @@ pub(super) const MASK_THUMB: &str = "tr-mask-thumb"; /// The panel's values ([`vectorcraft_engine::Session::transparency_info`]) and its first target /// (the selection, or the object whose mask is being edited), recomputed only when the document -/// or the selection changes. +/// or the selection changes, or other gradient mesh points are picked. fn state(app: &VectorcraftApp, ctx: &egui::Context) -> (TransparencyInfo, Option) { - type Key = (u64, u64, usize, Option, Option); + type Key = (u64, u64, usize, Option, Option, Option)>>); let Some(st) = app.session.active() else { return Default::default() }; let sel = &st.selection.objects; - let key: Key = (st.uid, st.revision, sel.len(), sel.first().copied(), sel.last().copied()); + let key: Key = (st.uid, st.revision, sel.len(), sel.first().copied(), sel.last().copied(), app.session.mesh_points_picked()); let id = egui::Id::unique("tr-state"); if let Some((k, v)) = ctx.data(|d| d.get_temp::<(Key, (TransparencyInfo, Option))>(id)) && k == key @@ -351,6 +351,50 @@ mod tests { assert!(app.session.active().unwrap().doc.mask_edit.is_none()); } + /// Picking other gradient mesh points (which gives the document no new revision) shows their + /// opacity, the one `transparency.set` changes then. + #[test] + fn picking_mesh_points_shows_their_opacity() { + use vectorcraft_engine::ViewInfo; + use vectorcraft_tools::{PointerEvent, PointerKind}; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + run(&mut app, "file.new", json!({"width": 100, "height": 100})); + let a = run(&mut app, "shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50}))["id"].clone(); + run(&mut app, "object.mesh.create", json!({"rows": 2, "cols": 2})); + run(&mut app, "object.mesh.setPointColor", json!({"id": a, "index": 0, "opacity": 0.3})); + run(&mut app, "paint.setStroke", json!({"color": "#000000"})); + let v = ViewInfo::default(); + app.session.select_tool("mesh", v).unwrap(); + let click = |app: &mut VectorcraftApp, x: f64, y: f64| { + for k in [PointerKind::Down, PointerKind::Up] { + app.session.pointer(&PointerEvent::new(k, x, y), v).unwrap(); + } + }; + let picked = |app: &VectorcraftApp| app.session.mesh_points_picked().map(|p| p.into_iter().flat_map(|(_, v)| v).collect::>()); + let ctx = egui::Context::default(); + click(&mut app, 35.0, 10.0); + assert_ne!(picked(&app), Some(vec![0]), "the click picks the top middle point"); + assert_eq!(picked(&app).map(|v| v.len()), Some(1)); + assert_eq!(state(&app, &ctx).0.opacity, Some(100.0)); + click(&mut app, 10.0, 10.0); + assert_eq!(picked(&app), Some(vec![0]), "the click picks the top-left point"); + assert_eq!(state(&app, &ctx).0.opacity, Some(30.0), "the newly picked point's opacity"); + // An active Appearance row takes the opacity, so the values are the object's again. + let rows = app + .session + .active() + .unwrap() + .selection + .objects + .first() + .map(|id| app.session.active().unwrap().doc.node(*id).unwrap().appearance.items.len()); + assert!(rows.is_some_and(|n| n > 0), "the mesh has its stroke row"); + run(&mut app, "appearance.setActiveItem", json!({"index": 0})); + assert_eq!(picked(&app), None); + assert_eq!(app.session.transparency_info().opacity, Some(100.0), "the object's opacity, not the point's"); + assert_eq!(run(&mut app, "transparency.info", json!({}))["opacity"], json!(100.0)); + } + #[test] fn mixed_values_show_blank() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); diff --git a/crates/ui-egui/src/panels/variables.rs b/crates/ui-egui/src/panels/variables.rs index a8987855eb..3ab5fc2484 100644 --- a/crates/ui-egui/src/panels/variables.rs +++ b/crates/ui-egui/src/panels/variables.rs @@ -268,8 +268,6 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let highlighted_bound: Vec = highlighted.as_ref().map(|h| bound_objects(st, h)).unwrap_or_default(); let Picked { selected, has_selection, selection_bound, single_type, single_image, selection_graph } = picked(st); let locked = st.doc.variables.locked; - // Save Variable Library writes text variables only. - let has_text = st.doc.variables.variables.iter().any(|v| v.kind == VariableKind::Text); if widgets::menu_item(ui, tl!("New Variable…"), !locked, false) { crate::menus::invoke(app, "variable.define", json!({})); @@ -333,7 +331,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { if widgets::menu_item(ui, tl!("Load Variable Library…"), true, false) { crate::picks::button(app, load_library); } - if widgets::menu_item(ui, tl!("Save Variable Library…"), has_text, false) { + if widgets::menu_item(ui, tl!("Save Variable Library…"), !vars.is_empty(), false) { crate::picks::button(app, save_library); } ui.separator(); @@ -494,19 +492,22 @@ mod tests { assert!(text.contains("Name") && text.contains("Data Set 1"), "{text}"); } - /// Load Variable Library's warning about variables that aren't text shows in the status bar, - /// translated in every language but English. + /// Load Variable Library defines a library's variables of every kind and gives no warning. The + /// warning an SVG's variable data gives about variables that aren't text is translated in every + /// language but English. #[test] - fn the_variable_library_warning_shows_in_the_status_bar() { + fn the_svg_variable_data_warning_is_translated() { use crate::i18n::{Lang, message}; let mut app = app_with_data(); + let status = app.ui.status.clone(); let xml = r#""#; app.run("variable.loadLibrary", json!({"xml": xml})).unwrap(); - assert_eq!(app.ui.status, "variables that aren't text were left out: other (1)"); + assert_eq!(app.ui.status, status, "the load gives no warning"); + let warning = "variables that aren't text were left out: other (1)"; let langs: Vec = Lang::all().filter(|l| l.code() != "en").collect(); assert!(langs.len() >= 23, "{} languages", langs.len()); for l in langs { - let shown = message(l, &app.ui.status); + let shown = message(l, warning); assert!(!shown.contains("left out") && shown.contains("other") && shown.contains('1'), "{}: {shown}", l.code()); } } diff --git a/crates/ui-egui/src/placing.rs b/crates/ui-egui/src/placing.rs index 11ae770d5d..a627321d76 100644 --- a/crates/ui-egui/src/placing.rs +++ b/crates/ui-egui/src/placing.rs @@ -178,6 +178,23 @@ pub struct Placing { pub(crate) reading: std::sync::Arc<[std::sync::atomic::AtomicUsize; 2]>, } +impl Placing { + /// Unit tests: wait until the reader thread has finished every read started so far. The thread + /// runs its jobs in order, so a job sent after them runs once they have handed back their files. + #[cfg(test)] + pub(crate) fn wait_for_reads(&self) { + if let Some(reader) = &self.reader { + let (tx, rx) = channel(); + let marker: Job = Box::new(move || { + let _ = tx.send(()); + }); + if reader.send(marker).is_ok() { + let _ = rx.recv(); + } + } + } +} + struct PendingSwatch { clipboard: Clipboard, insertion: Insertion, diff --git a/crates/ui-egui/src/prefs_dialog.rs b/crates/ui-egui/src/prefs_dialog.rs index 9029459195..f9939177de 100644 --- a/crates/ui-egui/src/prefs_dialog.rs +++ b/crates/ui-egui/src/prefs_dialog.rs @@ -404,7 +404,8 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { }); }); ui.add_space(14.0); - ui.horizontal(|ui| { + // Export, Import and Reset share one row, which wraps when it is wider than the dialog. + ui.horizontal_wrapped(|ui| { if widgets::secondary_button(ui, tl!("Export Preferences…")).on_hover_text(tl!("Save the applied preferences to a JSON file")).clicked() { export_preferences(app, &mut d); @@ -417,15 +418,15 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { { import_preferences(app, &mut d); } - }); - ui.add_space(8.0); - ui.horizontal(|ui| { if widgets::secondary_button(ui, tl!("Reset Preferences")) .on_hover_text(tl!("Restore every preference to its default (applied on OK)")) .clicked() { reset = true; } + }); + ui.add_space(8.0); + ui.horizontal(|ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { if widgets::primary_button(ui, tl!("OK")).clicked() { ok = true; diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index 6c7382200f..5c9356edd9 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -55,6 +55,29 @@ fn start_lists_from_typed_markers_is_a_saved_type_preference() { } } +/// Type › Show Character Alternates is a checkbox in the Type panel, on by default; turning it +/// off is saved, and every bundled language translates its label and the row's two tooltips. +#[test] +fn show_character_alternates_is_a_saved_type_preference() { + const LABEL: &str = "Show Character Alternates"; + let mut a = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + assert!(a.session.prefs.show_character_alternates); + open(&mut a, Some("Type")); + let text = crate::tests_labels::painted_text(&mut a, |a, ui| show(a, ui.ctx())); + assert!(text.contains(LABEL), "{text}"); + assert_eq!(a.ui.dialog.as_ref().unwrap().fields.get("showCharacterAlternates"), Some(&json!(true))); + a.ui.dialog.as_mut().unwrap().fields.insert("showCharacterAlternates".into(), json!(false)); + confirm(&mut a).unwrap(); + assert!(!a.session.prefs.show_character_alternates); + let saved: Prefs = serde_json::from_value(a.ui.engine_prefs.clone()).unwrap(); + assert!(!saved.show_character_alternates); + for lang in crate::i18n::Lang::all().filter(|l| l.code() != crate::i18n::Lang::EN.code()) { + for source in [LABEL, "Click to replace", "Show all alternates in the Glyphs panel"] { + assert!(crate::i18n::has(lang, source), "{}: {source}", lang.code()); + } + } +} + /// A resting checkbox must have a visible outline in both states and every brightness. #[test] fn preference_checkboxes_draw_outlines_without_hover() { @@ -312,6 +335,74 @@ fn reset_preferences(app: &mut VectorcraftApp) { crate::dialogs::confirm(app).unwrap(); } +/// The Preferences dialog drawn in `lang` with the open dialog available: the label and screen +/// rectangle of each control, from the accessibility tree, and the dialog's content rectangle +/// (inside its 20 pt margin and frame stroke). +fn dialog_controls(lang: crate::i18n::Lang) -> (Vec<(String, egui::Rect)>, egui::Rect) { + crate::i18n::set_current(lang); + let mut a = app(); + a.services.pick_open = Some(Box::new(|_: &crate::FilePick| None)); + open(&mut a, Some("General")); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + let mut v = vec![]; + for time in [0.0, 0.25, 0.5] { + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 900.0))); + let raw = egui::RawInput { screen_rect, time: Some(time), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| show(&mut a, ui.ctx())); + out.textures_delta.clear(); + let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + v = nodes + .iter() + .filter_map(|(_, n)| { + let b = n.bounds()?; + Some((n.label()?.to_string(), egui::Rect::from_min_max(egui::pos2(b.x0 as f32, b.y0 as f32), egui::pos2(b.x1 as f32, b.y1 as f32)))) + }) + .collect(); + } + crate::i18n::set_current(crate::i18n::Lang::EN); + let window = ctx.memory(|m| m.area_rect(egui::Id::unique("dialog-preferences"))).expect("the dialog window is shown"); + let content = window.shrink(20.0 + ctx.global_style().visuals.window_stroke.width); + (v, content) +} + +/// Export Preferences…, Import Preferences… and Reset Preferences share one row above OK and +/// Cancel. +#[test] +fn export_import_and_reset_share_one_row() { + let (controls, _) = dialog_controls(crate::i18n::Lang::EN); + let top = |label: &str| controls.iter().find(|(t, _)| t == label).map(|(_, r)| r.top()).unwrap_or_else(|| panic!("no `{label}` in {controls:?}")); + let row = top("Export Preferences…"); + assert!((top("Import Preferences…") - row).abs() < 0.5, "Import is on Export's row"); + assert!((top("Reset Preferences") - row).abs() < 0.5, "Reset is on Export's row"); + assert!(top("OK") > row + 20.0, "OK is on the row below"); +} + +/// In every language the dialog keeps its 760 pt content width, and the three buttons above OK +/// lie inside it and above the row of OK and Cancel. +#[test] +fn export_import_and_reset_fit_in_every_language() { + for lang in crate::i18n::Lang::all() { + let (controls, content) = dialog_controls(lang); + assert!(content.width() <= 760.5, "{}: the dialog's content grew to {content:?}", lang.code()); + let find = |label: &str| { + let label = crate::i18n::tr(lang, label); + controls.iter().find(|(t, _)| t == label).map(|(_, r)| *r).unwrap_or_else(|| panic!("{}: no `{label}` in {controls:?}", lang.code())) + }; + let ok = find("OK"); + for label in ["Export Preferences…", "Import Preferences…", "Reset Preferences"] { + let r = find(label); + assert!( + r.right() <= content.right() + 0.5 && r.left() >= content.left() - 0.5, + "{}: `{label}` at {r:?} is outside the dialog's content {content:?}", + lang.code() + ); + assert!(r.bottom() <= ok.top(), "{}: `{label}` at {r:?} reaches the OK row at {ok:?}", lang.code()); + } + } +} + /// Reset Preferences then OK resets the preferences, General included, and leaves the open /// document's units, with no undo step in the document. #[test] diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index 4e02180017..88a97206c7 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -765,12 +765,10 @@ fn chosen_path(items: &[(String, Value)]) -> Option<&str> { items.iter().find(|(_, p)| is_bare(p)).or(items.first()).map(|(path, _)| path.as_str()) } -/// Does a command's params doc (`{a?, b?} …`) say it runs with no params, as a shortcut runs it? +/// Does a command's params doc (`{a?, b?: bool} …`) say it runs with no params, as a shortcut runs +/// it? It does when it starts with `{` and [`names_a_required_field`] finds no field a call must give. fn runs_without_params(params: &str) -> bool { - params - .strip_prefix('{') - .and_then(|r| r.split_once('}')) - .is_some_and(|(fields, _)| fields.split(',').all(|f| f.trim().is_empty() || f.trim_end().ends_with('?'))) + params.starts_with('{') && !names_a_required_field(params) } /// Does the editor list `e` under `overrides`? An entry that [`needs_a_value`] is listed only while @@ -783,8 +781,13 @@ fn listed(overrides: &Overrides, e: &Entry) -> bool { /// with none, and that no item of the menu bar runs: Transparency and Opacity Mask Options need /// a value to set, Align and Distribute a direction, Delete Swatch and Move Swatch a swatch name, /// and the library, data set, text style and SVG filter loaders a file, which their menu items ask -/// for. -const NEEDS_A_PARAM: [&str; 20] = [ +/// for. The commands after them have no menu path: the setters of panels and dialogs (Fill, Stroke +/// Options, Character, Set Bounds), the exports and saves that give the file back without a `path` +/// (Save Document gives the file back when the document has no file yet; File › Save takes a key +/// instead), the undo group's begin and end, and the commands that need a point, a value or a name +/// (Create Dimension, Edit Freeform Point, Select by Color, Move Brush, Paintbrush). New Symbol is left out +/// because the Symbols panel runs it through the Symbol Options dialog. +const NEEDS_A_PARAM: [&str; 75] = [ "transparency.set", "transparency.setOpacityMask", "stroke.set", @@ -805,6 +808,61 @@ const NEEDS_A_PARAM: [&str; 20] = [ "paraStyle.load", "textStyle.loadAll", "svgFilter.import", + "addon.pathtools.setAnchor", + "addon.shapes.configure", + "appearance.addEffect", + "artboard.align", + "artboard.distribute", + "assets.export", + "assets.export3D", + "assets.settings.set", + "attributes.set", + "brush.freehand", + "brush.move", + "css.export", + "dimension.create", + "document.export", + "document.exportDxf", + "document.exportEps", + "document.exportForWeb", + "document.exportPdf", + "document.save", + "document.setup", + "edit.undoGroup.begin", + "edit.undoGroup.end", + "eyedropper.setOptions", + "file.package", + "library.createGroup", + "links.placementOptions", + "links.unembed", + "livePaint.gapOptions", + "object.blend.createSpine", + "object.blend.setEasing", + "object.intertwine.arrange", + "object.objectsOnPath.options", + "object.puppetWarp.pins", + "object.setBounds", + "object.setLiveShape", + "object.setOverprint", + "object.setProps", + "object.slice.select", + "paint.freeform.setPoint", + "paint.setFill", + "paint.setGradientGeom", + "paint.setStroke", + "perspective.grid.define", + "perspective.grid.set", + "perspective.plane.move", + "print.setup", + "select.color", + "select.globalEditOptions", + "stroke.setAdvanced", + "symbol.new", + "symbol.options", + "text.setFormat", + "text.setRangeStyle", + "text.setStyle", + "type.ruby", ]; /// The (label, params) of each menu bar item, by command id. @@ -907,7 +965,7 @@ fn a_menu_bar_item_runs(id: &str, params: &str) -> bool { /// Is engine command `c` listed in Edit › Keyboard Shortcuts whether or not an item of the menu bar /// runs it? A command with a menu path of its own is. One without (a panel menu item) is when a key /// alone can run it: it has a default key, or it is an undoable command, not an alias, whose params -/// doc ends each field with `?`. +/// doc names no field a call must give ([`runs_without_params`]). fn listed_on_its_own(c: &vectorcraft_engine::CommandSpec) -> bool { !c.menu.is_empty() || c.shortcut.is_some() || (c.journal && !vectorcraft_engine::cmd::is_alias(c.id) && runs_without_params(c.params)) } @@ -2309,11 +2367,39 @@ mod tests { for id in ["brush.duplicate", "path.convertAnchors", "document.json", "prefs.list"] { assert!(entry(id).is_none(), "{id}"); } - for (doc, bare) in - [("{}", true), ("{dx?, dy?} x", true), ("{id?|ids?, clip?}", true), ("{name, newName?}", false), ("{a?: {b}}", false), ("same as", false)] - { + // The Symbols panel runs New Symbol through Symbol Options, so it waits for a key the user gives it. + assert!(entry("symbol.new").is_some_and(|e| !listed(&Overrides::new(), &e))); + for (doc, bare) in [ + ("{}", true), + ("{dx?, dy?} x", true), + ("{id?|ids?, clip?}", true), + ("{name, newName?}", false), + ("{a?: {b}}", true), + ("{ids?|id?, on?: bool} turn it on or off", true), + ("{ids?: [id…] (the selection), anchors?: [index…]}", true), + ("{format?: a|b, size?: 1|3|5}", true), + ("{artboard?: index=0}", true), + ("{mode: a|b, on?: bool}", false), + ("same as", false), + ] { assert_eq!(runs_without_params(doc), bare, "{doc}"); } + // Panel menu commands whose params doc gives each optional field a type are listed too. + let none = Overrides::new(); + for id in [ + "type.fractionalWidths", + "type.systemLayout", + "object.setPixelAligned", + "links.embed", + "links.update", + "object.slice.delete", + "artboard.switchOrientation", + "appearance.targetContents", + "paint.invert", + "artboard.distributeSpacing", + ] { + assert!(entry(id).is_some_and(|e| listed(&none, &e)), "{id}"); + } let mut ov = Overrides::new(); assert!(assign(&mut ov, "symbol.breakLink", Some("Cmd+Alt+Shift+F9"), true).is_ok()); assert_eq!(effective_in(&ov, "symbol.breakLink").as_deref(), Some("Cmd+Alt+Shift+F9")); diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index ea32f6c078..d102c40d7e 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -226,7 +226,10 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context) { // Escape closes a dropdown list or popover open in the dialog (each closes itself on it) and // leaves the dialog open. let popup = app.ui.dialog.as_ref().is_some_and(|d| { - egui::Popup::is_any_open(ctx) || crate::dialogs::brush_options::tips_open(d) || crate::dialogs::new_document_popup_open(d) + egui::Popup::is_any_open(ctx) + || crate::dialogs::brush_options::tips_open(d) + || crate::dialogs::new_document_popup_open(d) + || crate::dialogs::export_artboard_name_editing(app, d) }); // Escape in Preferences' search field with text clears the field first. if !popup && pressed_anew(ctx, Key::Escape) && !crate::prefs_dialog::clear_search_on_escape(app, ctx) { diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs index 92a1ab9768..10ed4efa13 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -297,8 +297,8 @@ fn a_shortcut_runs_what_its_menu_item_runs() { /// Vector Halftone, Rearrange All Artboards, Pathfinder Options, the Object › Plug-ins dialogs /// (Arrange in Grid, Replace with Top Object, the size, opacity and sort dialogs of the Arrange /// add-on, Set Corners…, Divide into Dashes, Find Nearest Swatch, the swatch legend, the type -/// tools, the select add-on and Select by Link Status…), four "…" items whose menu entry gives -/// params, Edit Custom Dictionary…, Composite Fonts…, Recolor Artwork…, the Edit menu's preset +/// tools, the select add-on and Select by Link Status…), three "…" items whose menu entry gives +/// params, Smart Punctuation…, Edit Custom Dictionary…, Composite Fonts…, Recolor Artwork…, the Edit menu's preset /// dialogs and Apply SVG Filter…. const MENU_DIALOG_COMMANDS: [&str; 39] = [ "object.path.smooth", diff --git a/crates/ui-egui/src/shortcuts/typing.rs b/crates/ui-egui/src/shortcuts/typing.rs index cee164c7f8..2befac02c3 100644 --- a/crates/ui-egui/src/shortcuts/typing.rs +++ b/crates/ui-egui/src/shortcuts/typing.rs @@ -42,6 +42,8 @@ enum Seq { Text(String), Preedit(String, Option>), Commit(String), + /// A space the IME commits during a Zoom tool drag on the canvas, where Space moves the marquee. + MarqueeSpace, Erase(ToolKey, Mods), /// An input method replaces text around the composition (upstream's character counts or /// the fork's exact UTF-8 byte counts), then commits. @@ -82,6 +84,11 @@ pub(super) fn type_text(app: &mut VectorcraftApp, ctx: &egui::Context) -> bool { // Set once the IME commits text in this frame. let mut committed = false; for e in seq { + // With text marked, the IME's space commits that text as usual. + let e = match e { + Seq::MarqueeSpace if app.session.tool_composing() || app.ime_marked.is_some() => Seq::Commit(" ".into()), + e => e, + }; // Before the UI, a changed composition or guard is settled `pending`: a token bound here // could outlive a route this pass invalidates later (a palette/dialog/Home) and attach to // the stock descriptor. The post-UI finalizer binds the confirmed replacement. @@ -94,10 +101,16 @@ pub(super) fn type_text(app: &mut VectorcraftApp, ctx: &egui::Context) -> bool { match &e { // Accepted old payloads precede the fence even when their terminal arrives. // None of these events proves the local reset has reached its boundary. - Seq::Commit(_) | Seq::DeleteSurrounding(..) | Seq::Preedit(..) => continue, + Seq::Commit(_) | Seq::MarqueeSpace | Seq::DeleteSurrounding(..) | Seq::Preedit(..) => continue, _ => {} } } + // Otherwise the IME's input ends there, and the space is not typed. + if matches!(e, Seq::MarqueeSpace) { + committed = true; + app.ime_compositions.remove(&viewport); + continue; + } // A pointer/navigation/command notice has not reached its real handler yet. Text and // erases after it belong to the old caret, not to the destination it will establish. if crate::ime::deferred(app, ctx) { @@ -135,10 +148,11 @@ pub(super) fn type_text(app: &mut VectorcraftApp, ctx: &egui::Context) -> bool { } /// Take this frame's typed text, IME events, editing keys, Enter and clipboard events, in the order -/// they arrived. +/// they arrived. A space typed during the canvas's Zoom tool drag is not typed. fn type_sequence(ctx: &egui::Context) -> Vec { let mut seq = vec![]; let mut edits = vec![]; + let zooming = crate::canvas::dragging_zoom(ctx); ctx.input_mut(|i| { // Move the events out instead of cloning their strings: a keyboard hook that reinjects a // batch keeps the batch in `seq` only, not in both the input list and a second copy. @@ -155,10 +169,13 @@ fn type_sequence(ctx: &egui::Context) -> Vec { .unwrap_or_else(|| i.pointer.primary_down()); for e in std::mem::take(&mut i.events) { match e { + // The zoom drag lasts until the primary button goes up. + egui::Event::Text(t) if zooming && primary_down && t == " " => {} egui::Event::Text(t) => seq.push(Seq::Text(t)), egui::Event::Ime(egui::ImeEvent::Preedit { text, active_range_chars }) => { seq.push(Seq::Preedit(text, active_range_chars)); } + egui::Event::Ime(egui::ImeEvent::Commit(t)) if zooming && primary_down && t == " " => seq.push(Seq::MarqueeSpace), egui::Event::Ime(egui::ImeEvent::Commit(t)) => seq.push(Seq::Commit(t)), egui::Event::Ime(egui::ImeEvent::DeleteSurrounding { before_chars, after_chars }) => { seq.push(Seq::DeleteSurrounding(before_chars, after_chars, SurroundingUnit::Chars)); @@ -254,7 +271,7 @@ fn apply_type_event( } Ok(vec![]) } - Seq::ResetCompleted(_) => Ok(vec![]), + Seq::ResetCompleted(_) | Seq::MarqueeSpace => Ok(vec![]), // Keys the IME passed through come as text only when nothing is marked. This is an // application edit (also a hook IME's reinjected characters): `Other` dominates. Seq::Text(t) if !app.session.tool_composing() && !shortcut_mods => { diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index d06c0dbcb2..b28e4034a7 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -424,10 +424,11 @@ pub struct UiState { /// is on screen. Not saved. #[serde(skip)] pub learn_locate: Option, - /// The tutorials whose practice samples were opened and the tutorials finished, kept while the - /// app runs. + /// The tutorials whose practice samples were opened, kept while the app runs. #[serde(skip)] pub learn_practice: crate::panels::learn::Practice, + /// The Learn panel's tutorials finished and steps marked done, saved with the preferences. + pub learn_progress: crate::panels::learn::progress::Progress, pub control_bar: bool, /// The Control bar is docked to the bottom of the window instead of the top /// (`window.control.dock`). @@ -787,6 +788,9 @@ pub struct UiState { /// dialog opens on them (#1152). #[serde(default)] pub offset_path: Value, + /// The Smart Punctuation fields confirmed last (null: never used): its dialog opens on them. + #[serde(default)] + pub smart_punctuation: Value, /// The Average & Join fields confirmed last (`to`; null: never used): its dialog opens on them. #[serde(default)] pub average_join: Value, @@ -1121,6 +1125,7 @@ impl Default for UiState { learn: Default::default(), learn_locate: None, learn_practice: Default::default(), + learn_progress: Default::default(), control_bar: false, control_bar_bottom: false, control_bar_floating: false, @@ -1224,6 +1229,7 @@ impl Default for UiState { dxf_options: Value::Null, eps_options: Value::Null, offset_path: Value::Null, + smart_punctuation: Value::Null, average_join: Value::Null, recolor_preserve: Value::Null, simplify: Value::Null, diff --git a/crates/ui-egui/src/tests/picks.rs b/crates/ui-egui/src/tests/picks.rs index ff290952fb..d6a06960bb 100644 --- a/crates/ui-egui/src/tests/picks.rs +++ b/crates/ui-egui/src/tests/picks.rs @@ -366,18 +366,17 @@ fn load_variable_library_asks_off_the_ui_thread() { let _ = std::fs::remove_dir_all(dir); } -/// The Variables panel menu's Save Variable Library… is enabled once the document has a text -/// variable, and then asks off the UI thread: the library is written -/// to the path the dialog answers, Load Variable Library reads it back, and the warning about the -/// visibility variable it left out shows in the status bar. +/// The Variables panel menu's Save Variable Library… is enabled once the document has a variable, +/// of any kind, and then asks off the UI thread: the library is written to the path the dialog +/// answers, and Load Variable Library reads back its visibility and text variables. #[test] fn save_variable_library_asks_off_the_ui_thread() { let (mut app, shown, _) = app(); app.run("file.new", json!({"width": 100, "height": 80})).unwrap(); - app.run("variable.define", json!({"name": "Shown", "kind": "visibility"})).unwrap(); - // Without a text variable the item is disabled and asks for no file. + // Without a variable the item is disabled and asks for no file. click(&mut app, "Save Variable Library…", crate::panels::variables::menu); assert!(shown.requests().is_empty(), "{:?}", shown.requests()); + app.run("variable.define", json!({"name": "Shown", "kind": "visibility"})).unwrap(); app.run("variable.define", json!({"name": "Name", "kind": "text"})).unwrap(); app.run("dataset.new", json!({"name": "A", "values": {"Name": "x", "Shown": true}})).unwrap(); let dir = vectorcraft_testkit::temp_dir("picks-save-variable-library"); @@ -392,10 +391,11 @@ fn save_variable_library_asks_off_the_ui_thread() { assert!(!library.exists(), "nothing is written before the dialog answers"); shown.answer(&[&library.to_string_lossy()]); poll(&mut app); - assert_eq!(app.ui.status, "variables that aren't text were left out: visibility (1)"); let xml = std::fs::read_to_string(&library).unwrap_or_else(|e| panic!("{e}: {}", app.ui.status)); let loaded = app.run("variable.loadLibrary", json!({"xml": xml})).unwrap(); - assert_eq!((loaded["variables"].clone(), loaded["names"].clone()), (json!(["Name"]), json!(["A"]))); + assert_eq!((loaded["variables"].clone(), loaded["names"].clone()), (json!(["Shown", "Name"]), json!(["A"]))); + let values = &app.session.doc().unwrap().doc.variables.datasets[0].values; + assert_eq!(values.get("Shown"), Some(&vectorcraft_doc::DataValue::Visible(true))); let _ = std::fs::remove_dir_all(dir); } diff --git a/crates/ui-egui/src/tests/save.rs b/crates/ui-egui/src/tests/save.rs index 33e6709913..b9b4111516 100644 --- a/crates/ui-egui/src/tests/save.rs +++ b/crates/ui-egui/src/tests/save.rs @@ -355,6 +355,37 @@ fn a_save_does_not_replace_the_file_read_from_through_a_file_written_beside_the_ let _ = std::fs::remove_dir_all(d); } +#[test] +fn file_save_does_not_replace_the_file_read_from_through_a_file_written_beside_the_path() { + let d = dir("lossy-beside-save"); + let path = d.join("Art.eps").to_string_lossy().to_string(); + let mut app = app(); + checks_files_there(&mut app); + app.run("file.new", json!({"width": 200, "height": 100, "artboards": 2})).unwrap(); + rect(&mut app); + let options = json!({"useArtboards": true, "previewFormat": "none", "thumbnails": false}); + let _ = app.run("file.saveAs", json!({"path": path, "options": options})); + crate::background::wait_all(&mut app); + let siblings = artboard_files(&d); + assert_eq!(siblings.len(), 2, "{siblings:?}"); + let sibling = siblings[0].clone(); + let saved = std::fs::read(&sibling).unwrap(); + std::fs::remove_file(&path).unwrap(); + let st = app.session.doc_mut().unwrap(); + st.imported_from = Some(sibling.clone()); + st.import_losses = vec!["hidden type".into()]; + rect(&mut app); + // File > Save to the document's own file reuses its options, so it writes the artboard files + // again; the one the document was read from is refused, as on Save As. + let _ = app.run("file.save", json!({})); + crate::background::wait_all(&mut app); + assert!(app.ui.dialog.as_ref().is_none_or(|d| d.kind != dialogs::confirm::REPLACE_FILES)); + assert_eq!(std::fs::read(&sibling).unwrap(), saved); + assert!(!std::path::Path::new(&path).exists(), "no file of the set is written when one is refused"); + assert!(app.session.active().unwrap().is_dirty()); + let _ = std::fs::remove_dir_all(d); +} + /// The app checks for files that are there, as the desktop app does. fn checks_files_there(app: &mut VectorcraftApp) { app.services.exists = Some(std::sync::Arc::new(|p: &str| std::path::Path::new(p).exists())); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index cc52d58ed7..115412d241 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -96,7 +96,7 @@ the two can still win that race. | `ui.menu.list` / `ui.menu.invoke` | `{command, params}` | the full menu tree / invoke an item | | `ui.contextMenu.list` | | the canvas context menu for the current selection, flattened like `ui.menu.list` (`path` holds its submenus). `ui.click {x, y, button: "right"}` on the canvas opens it, after selecting the object there unless it is already selected. With the Artboard tool it lists the artboard entries (see `docs/mcp.md`), after selecting the artboard there unless it is already selected. While a menu opened over locked objects is open, it has an `Unlock` submenu with one item for each locked object under the pointer, topmost first and at most 20, labeled with the object's name, which runs `layer.setProps {ids: [id], locked: false}`. A locked group gets one item, and the locked objects inside it get none. Hidden objects, objects on hidden, locked or template layers, and in isolation mode objects outside the isolated group get no item | | `ui.tool.select` / `ui.tool.list` | `{tool}` | | -| `ui.pointer` | `{events:[{kind: down|drag|up|move|doubleclick, x, y, space?: "doc"|"screen", mods?}]}` | drive the active tool exactly like the mouse: `mods.cmd` held at a press with any tool but a selection tool drags with the selection tool chosen last (Direct Selection with the Pen until one is), and the release gives the tool back as it was; the reply lists `selection`, `key` (the key object, null without one) and `tool`. With the Shape Builder or the Live Paint Bucket and a selection of more than 128 segments, the app finds the regions off the UI thread, so a `move` replies before the region under the pointer is highlighted, and the highlight shows in the first frame after the regions are found. With the Shape Builder and such a selection, the app also merges off the UI thread: the reply to the events that end a click or drag comes once the merge is applied. A click or drag made before the regions are found does not wait for them; the app records it and makes it once they are found. Until then the canvas keeps drawing, with the touched regions highlighted and the busy pointer. A click or drag sent meanwhile, with `mods.cmd` too, and the Shape Builder's arrow keys are made after the merge in the order sent, and the reply to such a request comes once its events are made and any merge they start is applied; a request of `move` events alone is answered at once. A command that can edit, select, save or redraw the documents (an edit, an undo, a selection, a save or an export, a tool option, another tool, another document, closing, a dialog's preview, a menu item, a command of the app's own such as `ui.recolorDialog`, the proof and separations views, a preference, added fonts) waits for the merge and the input sent before it, and runs after them; queries that only read, such as `document.inspect`, run at once on the document before the merge | +| `ui.pointer` | `{events:[{kind: down\|drag\|up\|move\|doubleclick\|tripleclick, x, y, space?: "doc"\|"screen", mods?}]}` | drive the active tool exactly like the mouse (`doubleclick` follows the second click's `up`, and `tripleclick` the third's): `mods.cmd` held at a press with any tool but a selection tool drags with the selection tool chosen last (Direct Selection with the Pen until one is), and the release gives the tool back as it was; the reply lists `selection`, `key` (the key object, null without one) and `tool`. With the Shape Builder or the Live Paint Bucket and a selection of more than 128 segments, the app finds the regions off the UI thread, so a `move` replies before the region under the pointer is highlighted, and the highlight shows in the first frame after the regions are found. With the Shape Builder and such a selection, the app also merges off the UI thread: the reply to the events that end a click or drag comes once the merge is applied. A click or drag made before the regions are found does not wait for them; the app records it and makes it once they are found. Until then the canvas keeps drawing, with the touched regions highlighted and the busy pointer. A click or drag sent meanwhile, with `mods.cmd` too, and the Shape Builder's arrow keys are made after the merge in the order sent, and the reply to such a request comes once its events are made and any merge they start is applied; a request of `move` events alone is answered at once. A command that can edit, select, save or redraw the documents (an edit, an undo, a selection, a save or an export, a tool option, another tool, another document, closing, a dialog's preview, a menu item, a command of the app's own such as `ui.recolorDialog`, the proof and separations views, a preference, added fonts) waits for the merge and the input sent before it, and runs after them; queries that only read, such as `document.inspect`, run at once on the document before the merge | | `ui.key` / `ui.text` | `{key, shift?, alt?, cmd?}` / `{text}` | synthetic keyboard input | | `ui.move` | `{x, y}` | screen-point pointer move | | `ui.click` / `ui.drag` | `{x, y, button?, count?, shift?, alt?, ctrl?, cmd?}` / `{x, y, toX, toY, steps?, count?, button?, shift?, alt?, ctrl?, cmd?}` | egui pointer input; see synthetic input budgets above | @@ -122,8 +122,8 @@ the two can still win that race. | 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; 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` with params still exports the selection in one go, without the dialog; with no params or `{}` the save panel picks the file and its format's options dialog follows, as after Export As, and the call returns `null` while the dialog is open (OK returns what `file.exportAs` returns, without `format` or `bounds`). `file.exportAs {path, exportSelection: true, …options}` writes the selection without a dialog | +| 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. Its Create Sub-folders and Open Location after Export run `assets.settings.set {subfolders}` and `{openLocation}`; its Format Settings… opens the dialog on the Assets tab with `__settings` set to the first row's format. | +| `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` with params still exports the selection in one go, without the options dialog (without `path`, the save panel picks the file first); with no params or `{}` the save panel picks the file and its format's options dialog follows, as after Export As, and the call returns `null` while the dialog is open (OK returns what `file.exportAs` returns, without `format` or `bounds`). `file.exportAs {path, exportSelection: true, …options}` writes the selection without a dialog | | CSS Properties panel | `window.panel {panel: "cssProperties"}`; `engine.execute` `css.copy` / `css.exportFile` | the panel shows `css.selection` of the selection (after Generate CSS, while nothing is selected, `css.generate`); its menu holds the options the commands take (`units`, `position`, `dimensions`, `unnamed`, `rasterize`). `css.copy {scope?, …options}` copies the CSS to the clipboard → `{css, rules}`; `css.exportFile {path?, scope?, …options}` writes `css.export` to `path` (else a picked file; the web downloads it) with the pictures of rasterized art next to it → `{path, rules, images, warnings}`, and the status bar shows `warnings` as Export As shows an export's notes | | `ui.dialog.*` on `importPdf` | `{field: "page" \| "allPages" \| "range" \| "cropTo" \| "password", value}` | opening (`app.open`, `file.open`) a PDF, `.ai` or `.ait` with a password, or one with several pages unless it is a `.ai` or `.ait` with its editing data or carries its VectorCraft document (those open whole), or placing (`file.place` without `page`) any of them with several pages or a password, opens the Import PDF dialog (`mode`: `open` or `place`; `pageCount`). While `__locked` is true, set `password` and `ui.dialog.confirm` to unlock it (a one-page file then opens or is placed). Then set `allPages: false` and `range` ("2-3, 5") to open some pages, or `page` to place one, and `cropTo` (`bounding`, `art`, `crop`, `trim`, `bleed`, `media`); `ui.dialog.confirm` opens or places them (placing keeps the other `file.place` params, such as `link`, `template` and `at`, in `__place`). `document.open {pages, cropTo, password}` and `file.place {page, crop, password}` do the same without the dialog | diff --git a/docs/development.md b/docs/development.md index 5dfd67a7c1..7c22d6ae98 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 (`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:** 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 the files a file manager copied (`text/uri-list`, else `x-special/gnome-copied-files`; local `file:` URIs only, 1,024 at most), then `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, file lists, 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 takes its windows off screen before these waits (`apps/vectorcraft/src/quit_windows.rs`). An X11 main window, an XWayland one included, is hidden. winit cannot hide a native Wayland window, so on Linux the app attaches no buffer to the main window's surface, which unmaps it while the window and its connection stay open for the Wayland clipboard. On Linux the X11 windows of floating panels and documents are unmapped through a second X11 connection. On native Wayland, floating panels and documents are normally drawn inside the main window; on the BSDs a native Wayland main window stays on screen until the waits end. Windows and macOS keep the check on the UI thread: Windows only asks which formats the clipboard holds, macOS asks the pasteboard server. - **Copied files:** files copied in a file manager (`text/uri-list`; `CF_HDROP` on Windows, file URLs on macOS) paste as the first one that is art (SVG, PDF, EPS, EMF/WMF or a bitmap; a `.ai` or `.ait` file from the editing data it holds, else as the PDF or PostScript it holds), before the clipboard's other formats (which include the files' paths as text). - **Dropping files on the window does not work under Wayland:** winit 0.30, which eframe 0.37 runs on, has no Wayland drag and drop ([winit#1881](https://github.com/rust-windowing/winit/issues/1881), added in winit 0.31; [egui#1563](https://github.com/emilk/egui/issues/1563)), so no `dropped_files` arrive. Until eframe moves to winit 0.31: copy the files in the file manager and paste them, use File › Place or Open, or open the window through XWayland, where drops work: set **Preferences › Performance › Linux Display Server** to **X11 (XWayland)** and restart (#1151), or start the app with `WAYLAND_DISPLAY= vectorcraft`. The preference (`linuxDisplayServer`, read at startup in `apps/vectorcraft/src/main.rs`, shown on Linux only) has winit open the window on X11 (`EventLoopBuilderExtX11::with_x11`) when the session is Wayland, `DISPLAY` is set and the X11 libraries winit loads are installed (`apps/vectorcraft/src/xwayland.rs` reads `ldconfig -p` and the usual library directories); otherwise the window opens on Wayland and the log says why. Unlike clearing `WAYLAND_DISPLAY`, it leaves the clipboard on the compositor's own. @@ -297,7 +297,7 @@ other `sv-*` locale resolve to it), Georgian (`ka`, complete; `ka-GE` and `ka_GE placeholders are translated in turn (the reason after `: {e}` is often a message too). A literal brace in a row is written `{{` or `}}`, in the English and in the translation: a message made with `format!` keeps the doubled braces of its format string, and a plain string literal has each of its braces doubled, so the row for - `"expected {\"objects\": [...]}"` is `expected {{"objects": [...]}}`. Czech, German, Greek, Spanish, French, Georgian, Hungarian, Italian, Japanese, Korean, Polish, Brazilian Portuguese, Russian, Simplified Chinese, Traditional Chinese, Swedish, Ukrainian, Vietnamese, Finnish, Turkish, Catalan and Dutch + `"expected {\"objects\": [...]}"` is `expected {{"objects": [...]}}`. Czech, German, Greek, Spanish, French, Georgian, Hindi, Hungarian, Italian, Japanese, Korean, Polish, Brazilian Portuguese, Russian, Simplified Chinese, Traditional Chinese, Swedish, Ukrainian, Vietnamese, Finnish, Turkish, Catalan, Dutch and Danish translate status and error messages (`COMPLETE_MESSAGES` in `i18n::tests`); the untranslated report lists the message literals the scan finds, and the phrases a parameter schema's error builds at run time (`SCHEMA_PHRASES`), that one of them has no row for. The scan covers the crates in `MESSAGE_CRATES`, the diff --git a/docs/dimensions.md b/docs/dimensions.md index 9cba8a66dc..de48bdb776 100644 --- a/docs/dimensions.md +++ b/docs/dimensions.md @@ -15,13 +15,17 @@ The **Dimension Tool** is in the Modify section of the toolbar. Its strip offers path's length. A press on an anchor picks it when the pointer moves less than 8 pixels before the release; a longer drag drags out the dimension of the segment under the pointer. A curved segment is measured from end to end. With Smart Guides on, both points also snap into line with other objects' - anchors and centres, and the second onto the construction guides through the first; the guides + anchors and centres. With Snap to Perpendicular or Snap to Tangent on, the second point also + snaps onto a segment where the line from the first meets it square or grazes a curve. When the + first point was picked on an anchor, the second also snaps onto the construction guides through + it; any other first point has no construction guides through it. The guides show while hovering, before each click. VectorCraft's own rules decide where a point lands: an anchor within 8 pixels takes it first; a point on a guide stays on the guide where the pointer - is, except that it moves onto a segment within the Smart Guides snapping tolerance, or onto the - place where a construction guide crosses another object's alignment line within twice that - tolerance; a point that no anchor, guide, grid or pixel snapping places lands on the closest - point of a segment within 8 pixels. + is, except that it moves onto a segment within the Smart Guides snapping tolerance, or, on a + construction guide or a Snap to Glyph guide that runs at an angle, onto the place where that + guide crosses another object's alignment line within twice that tolerance; a point that no + anchor, guide, grid or pixel snapping places lands on the closest point of a segment within 8 + pixels. A linear dimension is aligned, horizontal or vertical, as the [linear dimensions help](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/plot-linear-dimensions-of-objects.html) describes: after the second click, clicking again places an aligned dimension, and moving the @@ -66,7 +70,8 @@ Measurements follow the art they measure through moves, scaling and anchor and h undo and redo included. When the art is reflected, the line of a linked linear dimension goes to the reflected side, as far past the outermost point as before. This does not happen for art whose anchors and handles all lie on one line, such as a straight line, which a half turn puts in the -same place as a reflection. Deleting the art, changing its number of anchors or whether it is +same place as a reflection. An unlinked aligned dimension that is reflected, or scaled by a +negative factor, has its line on the reflected side of its points. Deleting the art, changing its number of anchors or whether it is closed, turning an angle's arm into a curve, or making a measured circle or arc no longer circular leaves its dimensions where they were, no longer linked, in the same undo step, rather than attaching them to a different edge. Undo links them again. A linked dimension moved on its own diff --git a/docs/effects-parity.md b/docs/effects-parity.md index 1457e35bc6..342a5171b6 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -27,7 +27,7 @@ Part of [target-app-parity.md](target-app-parity.md); open work is in [gaps.md]( | Pathfinder | Add, Intersect, Exclude, Subtract, Minus Back, Divide, Trim, Merge, Crop, Outline, Hard Mix, Soft Mix, Trap | 13/13 | Trap traps only solid fills (gradients and patterns hide what is below them but don't trap) and spreads each colour's visible area as a whole; the public page gives no default values, so Trap's 0.25 pt, 100% and 40% are VectorCraft's own | | Rasterize | Rasterize… (as a live effect) | 1/1 | — | | Stylize | Drop Shadow, Feather, Inner Glow, Outer Glow, Round Corners, Scribble | 6/6 | Scribble Options' Settings presets | -| SVG Filters | Apply SVG Filter… and the filter list | 1/1 | The submenu lists the document's own filters: VectorCraft ships no default filters. A filter that is the object's last effect is written to SVG as a `` element; otherwise SVG export draws the object as an image. A filter on a turned or skewed object in an imported SVG is left out with a warning | +| SVG Filters | Apply SVG Filter… and the filter list | 1/1 | The submenu lists 14 default filters and then the document's own; the public page names no default set, so the set, names and values are VectorCraft's own, and a default is copied into the document when it is applied or edited. A filter that is the object's last effect is written to SVG as a `` element; otherwise SVG export draws the object as an image. A filter on a turned or skewed object in an imported SVG is left out with a warning | | Warp | Arc, Arc Lower, Arc Upper, Arch, Bulge, Shell Lower, Shell Upper, Flag, Wave, Fish, Rise, Fisheye, Inflate, Squeeze, Twist | 15/15 | warp point editing in envelopes; each style bends the bounds as one Bézier patch (`version` 1), so Arc's edges are cubic curves close to concentric arcs; warps saved without a version keep the earlier map, where Arc is a circular arc in the object's own proportions (#1578) | Document Raster Effects Settings exists. When the 64 million pixel cap on an effect image lowers diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index a211c0ca53..bf52925f5c 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -281,11 +281,11 @@ Names in the editing data that aren't UTF-8 (layers, objects, artboards, colors, | VectorCraft `.vectorcraft` / `.vctemplate` | — | yes | yes | lossless JSON, versioned, save down to v1; property-tested round trips (`format/tests/prop_format.rs`); documents with a lot of path data are written as compact JSON, about a fifth of the size (#1492); a save falls back to a plain fsync and to writing elsewhere and copying in when the folder refuses the usual steps (#1625, #1649, part of #1620; not confirmed on a real network share); the size limits on embedded data also apply to files read from memory (#1783), and saving over a private file on Unix leaves no readable temporary copy beside it (#1778); a dynamic symbol's type (`dynamic` on the symbol) and an instance's appearance changes to its art (`symbol_overrides`, each path at most 64 deep, counted against the object budget) are written only when set, so documents without them save as before (#4938) | | Illustrator template `.ait` | open, save | yes | PDF-compatible only, from Save as Template (`.vctemplate` stays its default) | New from Template opens a saved `.ait` untitled with its layers and art (`tests_pdfedit.rs`) | | Illustrator `.ai` | open, save | yes (PDF-compatible + editing-data structure with template layers and ruler guides, File Info) | PDF-compatible, or legacy version 7 (layers and groups) | see above; no real-file corpus | -| PDF | open, place, save | yes (authored ActualText in editable import, #6165; layers, masks, editable text, security, overprint, File Info from the XMP packet and the document information dictionary; Crop To › Trim takes the bleed box as the document's bleed) | yes (presets, PDF/X-1a/3/4, layers, marks and bleed, ICC, fast web view, 1.3+; objects' URLs as link annotations, not in PDF/X) | fuzzed import; shared guarded writer and windowed reader ([pdf-backend.md](pdf-backend.md)), metadata, incomplete-content and dependency-source regressions; PDF text opens where the file draws it, glyph by glyph (#722: kerning or none, spacing per character, text rise as baseline shift, vertical writing, justified text boxes); alpha soft masks drawn as images import with the mask (#1551); a clip only counts as covering the page when its shape does (#1542); a PDF another app copied pastes as editable vector art (#1499); letter-spaced type on a path keeps its length and its glyph-by-glyph stroke comes in as one text object (#1586, #1585); a crafted name tree with shared nodes no longer takes exponential time on open (#1781); fonts named with hyphens (`Noto-Sans-Bold`) or with a composite font's CMap (`Name-Identity-H`) find the installed family; invisible text (rendering mode 3: a scanned page's recognized text) opens as type with no fill or stroke and saves back as invisible, searchable text (#2675); PDF/X-1a and X-3 flattening in a CMYK document keeps CMYK inks where it rasterizes (#2160); an image mask (`/ImageMask true`) painted in a solid color opens as a grayscale image colorized by that color, a spot color keeping its swatch and tint, so Fill and Recolor Artwork reach it, and the same mask painted again in another color keeps that color (#6313); an image in a Separation space opens as a grayscale image of its tints colorized by its ink at 100 % (a spot swatch, a process plate or Registration), its soft mask as its opacity mask (#6314); a DeviceN image of one colorant opens the same way, and one of process plates only (the ink `None` may be among them) opens in CMYK with each colorant's tint in its plate (#6348) PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. | -| EPS | open, place, save | yes (own PostScript L3 interpreter, Illustrator EPS editing data structure) | yes (L2/L3, TIFF previews) | CIDFonts the file doesn't carry not drawn, but for those over a predefined CMap (`UniJIS-UCS2-H`, `90ms-RKSJ-H`, `GBK-EUC-H`, `KSCms-UHC-H`, `ETen-B5-H`), set as type in the font of the CIDFont's name, vertical over a `-V` CMap; a name that ends in the row-and-cell CMap `H` or `V` splits off the CMap only when the file defines the CIDFont of that name, or the name has a hyphen and an installed face that covers Japanese has it; name-keyed fonts in a FontSet set as type by name; #505; images encoded with `CCITTFaxDecode` (ITU-T T.4 Group 3 and T.6 Group 4, with `K`, `Columns`, `Rows`, `EndOfBlock`, `EndOfLine`, `EncodedByteAlign` and `BlackIs1`) draw, and damaged data keeps the rows decoded before its first damaged row; Type 42 (TrueType) fonts set type at its size (#1553); an embedded Type 1 font's encrypted part is read for its glyphs, which space its type, outline it and draw glyphs without a character, in plain and composite fonts; a Type 42 font that carries its TrueType font gives each code its character by its glyph name or, for names that say nothing (`/g12`), by the glyph's entry in the font's own character map, spaces its type by its own widths and draws glyphs that stand for no character from its outlines; the show operators' spacing along the baseline (`ashow`, `widthshow`, `xshow`, `yshow`, `xyshow`, and the moves of `kshow`'s procedure, run between each two characters) is kept on live type as tracking, so type in a font that isn't installed keeps the file's line lengths (spacing that moves characters off the baseline, as `yshow`, `xyshow` or a `kshow` procedure can, places each character as its own text object); composite (Type 0) fonts with the 8/8 mapping, as PDF-to-PostScript converters write two-byte fonts, draw a Type 42 descendant's glyphs from the TrueType outlines it carries and an embedded Type 1 descendant's from its charstrings, and set other descendants' characters as type at the composite font's size (other mappings are still set as type in the font of their name); CID-keyed fonts (`composefont`, `FMapType` 9 over a CMap built with the CIDInit operators or `Identity-H`/`Identity-V`; `bfchar` and `bfrange` mappings give a base-font descendant its codes or glyph names) draw the glyphs of the Type 0 CIDFonts (Type 1 charstrings in their `StartData` binary data or `GlyphDirectory`) and Type 2 CIDFonts (TrueType glyphs through `CIDMap`) they carry, and the CID-keyed fonts of a FontSet's Compact Font Format data (Type 2 charstrings); a clip only counts as covering the page when its shape does (#1542); an EPS another app copied pastes as editable vector art (`clipboard.importEps`, #1499); a stitched shading keeps its hard colour changes on import (#1654); sampled functions (type 0) interpolate between their samples, multilinearly or by cubics with `Order 3`, and a sampled axial or radial gradient has a stop at each sample; a gradient the page paints as a row of abutting one-colour strips (as Level 2 writers draw smooth shades) imports as one linear gradient, without the seams the strips leave when each is drawn alone; CMYK images, CMYK JPEGs included, keep their ink amounts on import, as from PDF, and the pixels a `MaskColor` or `ImageType 3` mask hides become a grayscale opacity mask; ruzstd 0.9.1 for compressed editing data (#1807, RUSTSEC-2026-0344) | +| PDF | open, place, save | yes (authored ActualText in editable import, #6165; layers, masks, editable text, security, overprint, File Info from the XMP packet and the document information dictionary; Crop To › Trim takes the bleed box as the document's bleed; Import PDF pages as links opens each page as a placed document linked to it, on its own artboard, `tests/placed_document.rs`) | yes (presets, PDF/X-1a/3/4, layers, marks and bleed, ICC, fast web view, 1.3+; objects' URLs as link annotations, not in PDF/X) | fuzzed import; shared guarded writer and windowed reader ([pdf-backend.md](pdf-backend.md)), metadata, incomplete-content and dependency-source regressions; PDF text opens where the file draws it, glyph by glyph (#722: kerning or none, spacing per character, text rise as baseline shift, vertical writing, justified text boxes); alpha soft masks drawn as images import with the mask (#1551); a clip only counts as covering the page when its shape does (#1542); a PDF another app copied pastes as editable vector art (#1499); letter-spaced type on a path keeps its length and its glyph-by-glyph stroke comes in as one text object (#1586, #1585); a crafted name tree with shared nodes no longer takes exponential time on open (#1781); fonts named with hyphens (`Noto-Sans-Bold`) or with a composite font's CMap (`Name-Identity-H`) find the installed family; invisible text (rendering mode 3: a scanned page's recognized text) opens as type with no fill or stroke and saves back as invisible, searchable text (#2675); PDF/X-1a and X-3 flattening in a CMYK document keeps CMYK inks where it rasterizes (#2160); an image mask (`/ImageMask true`) painted in a solid color opens as a grayscale image colorized by that color, a spot color keeping its swatch and tint, so Fill and Recolor Artwork reach it, and the same mask painted again in another color keeps that color (#6313); an image in a Separation space opens as a grayscale image of its tints colorized by its ink at 100 % (a spot swatch, a process plate or Registration), its soft mask as its opacity mask (#6314); a DeviceN image of one colorant opens the same way, and one of process plates only (the ink `None` may be among them) opens in CMYK with each colorant's tint in its plate (#6348) PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. | +| EPS | open, place, save | yes (own PostScript L3 interpreter, Illustrator EPS editing data structure) | yes (L2/L3, TIFF previews) | CIDFonts the file doesn't carry not drawn, but for those over a predefined CMap (`UniJIS-UCS2-H`, `90ms-RKSJ-H`, `GBK-EUC-H`, `KSCms-UHC-H`, `ETen-B5-H`), set as type in the font of the CIDFont's name, vertical over a `-V` CMap; a name that ends in the row-and-cell CMap `H` or `V` splits off the CMap only when the file defines the CIDFont of that name, the CIDFont is `Ryumin-Light` or `GothicBBB-Medium` (the Japanese CIDFonts a printer carries), or the name has a hyphen and an installed face that covers Japanese has it; name-keyed fonts in a FontSet set as type by name; #505; images encoded with `CCITTFaxDecode` (ITU-T T.4 Group 3 and T.6 Group 4, with `K`, `Columns`, `Rows`, `EndOfBlock`, `EndOfLine`, `EncodedByteAlign` and `BlackIs1`) draw, and damaged data keeps the rows decoded before its first damaged row; Type 42 (TrueType) fonts set type at its size (#1553); an embedded Type 1 font's encrypted part is read for its glyphs, which space its type, outline it and draw glyphs without a character, in plain and composite fonts; a Type 42 font that carries its TrueType font gives each code its character by its glyph name or, for names that say nothing (`/g12`), by the glyph's entry in the font's own character map, spaces its type by its own widths and draws glyphs that stand for no character from its outlines; the show operators' spacing along the baseline (`ashow`, `widthshow`, `xshow`, `yshow`, `xyshow`, and the moves of `kshow`'s procedure, run between each two characters) is kept on live type as tracking, so type in a font that isn't installed keeps the file's line lengths (spacing that moves characters off the baseline, as `yshow`, `xyshow` or a `kshow` procedure can, places each character as its own text object); composite (Type 0) fonts with the 8/8 mapping, as PDF-to-PostScript converters write two-byte fonts, draw a Type 42 descendant's glyphs from the TrueType outlines it carries and an embedded Type 1 descendant's from its charstrings, and set other descendants' characters as type at the composite font's size (other mappings are still set as type in the font of their name); CID-keyed fonts (`composefont`, `FMapType` 9 over a CMap built with the CIDInit operators or `Identity-H`/`Identity-V`; `bfchar` and `bfrange` mappings give a base-font descendant its codes or glyph names) draw the glyphs of the Type 0 CIDFonts (Type 1 charstrings in their `StartData` binary data or `GlyphDirectory`) and Type 2 CIDFonts (TrueType glyphs through `CIDMap`) they carry, and the CID-keyed fonts of a FontSet's Compact Font Format data (Type 2 charstrings); a clip only counts as covering the page when its shape does (#1542); an EPS another app copied pastes as editable vector art (`clipboard.importEps`, #1499); a stitched shading keeps its hard colour changes on import (#1654); sampled functions (type 0) interpolate between their samples, multilinearly or by cubics with `Order 3`, and a sampled axial or radial gradient has a stop at each sample; a gradient the page paints as a row of abutting one-colour strips (as Level 2 writers draw smooth shades) imports as one linear gradient, without the seams the strips leave when each is drawn alone; CMYK images, CMYK JPEGs included, keep their ink amounts on import, as from PDF, and the pixels a `MaskColor` or `ImageType 3` mask hides become a grayscale opacity mask; ruzstd 0.9.1 for compressed editing data (#1807, RUSTSEC-2026-0344) | | PostScript `.ps` | open, place | yes (the EPS reader reads its first page; `.epsf` files open and place as EPS) | via Print to PostScript | `tests_epsimport.rs` | | DCS 1.0 / 2.0 | place linked | place linked only (one image of the plates; spot plates as spot swatches; the composite's clipping path; each plate on its own ink in Separations Preview and print separations) | no | `crates/eps/src/dcs/tests.rs`, `crates/engine/src/tests/dcs.rs` | -| SVG / SVGZ | open, place, save | yes | yes (SVG Options, Preserve Editing, symbols, filters, rich text) | strongest format; tests in `crates/svg/tests`; text on a path follows basic shapes as their SVG 2 equivalent paths (#1527); CSS transforms and the `font` shorthand (#1565), percentage lengths in symbols (#1596), Inkscape flowed text as area type (#1568) and Inkscape pages as artboards (#1601) import; an unsupported filter is named in its warning (#1598); an artboard exported on its own (Export As with Use Artboards, Export for Screens, Asset Export) has the artboard's name as ``, Save the document's (#3544); attributes in other applications' XML namespaces (`plotter:pen="2"`) kept on their objects from import to export, as `data-*` attributes are (`crates/svg/tests/it/foreign_attributes.rs`); simple shapes export as `<rect>`, `<circle>`, `<ellipse>`, `<line>`, `<polygon>` and `<polyline>` where they draw the same as the path (#4652, `crates/svg/tests/it/basic_shapes.rs`); the regions of exported masks and filters (opacity masks, inverted masks, knockout groups) cover the art they apply to, and over type keep a region that covers any artwork (#6401, `crates/svg/tests/it/blend_export.rs`); SVG Options › Include Variable Data writes the text variables, data sets and bound type objects, and opening the SVG reads them back (`tests::variables::an_svg_with_variable_data_opens_with_its_variables_data_sets_and_bindings`) | +| SVG / SVGZ | open, place, save | yes | yes (SVG Options, Preserve Editing, symbols, filters, rich text) | strongest format; tests in `crates/svg/tests`; text on a path follows basic shapes as their SVG 2 equivalent paths (#1527); CSS transforms and the `font` shorthand (#1565), percentage lengths in symbols (#1596), Inkscape flowed text as area type (#1568) and Inkscape pages as artboards (#1601) import; an unsupported filter is named in its warning (#1598); an artboard exported on its own (Export As with Use Artboards, Export for Screens, Asset Export) has the artboard's name as `<title>`, Save the document's (#3544); attributes in other applications' XML namespaces (`plotter:pen="2"`) kept on their objects from import to export, as `data-*` attributes are (`crates/svg/tests/it/foreign_attributes.rs`); simple shapes export as `<rect>`, `<circle>`, `<ellipse>`, `<line>`, `<polygon>` and `<polyline>` where they draw the same as the path (#4652, `crates/svg/tests/it/basic_shapes.rs`); the regions of exported masks and filters (opacity masks, inverted masks, knockout groups) cover the art they apply to, and over type keep a region that covers any artwork (#6401, `crates/svg/tests/it/blend_export.rs`); a masked group, or a knockout group's masked group, whose content has a shadow, glow, blur or feather starts with a hidden, unpainted rectangle over the mask's region, so readers that draw a masked group only inside the box of its shapes draw those effects too (`crates/svg/tests/it/blend_export.rs`); SVG Options › Include Variable Data writes the text variables, data sets and bound type objects, and opening the SVG reads them back (`tests::variables::an_svg_with_variable_data_opens_with_its_variables_data_sets_and_bindings`) | | DXF | open, export | yes | yes (R12–2018) | R13–2018 closed SPLINE flags and control-point closure on import verified (#1299); circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; R12 weighted strokes remain POLYLINE while non-circular curves keep the existing fallback (`crates/cad/src/tests.rs`); [Autodesk group 70](https://help.autodesk.com/cloudhelp/2024/ENU/AutoCAD-DXF/files/GUID-E1F884F8-AA90-4864-A215-3182D47A9C74.htm). DXF 2000–2018 LAYOUT objects write the paper image origin as 148/149 (was a stray 158), the shade plot codes (2004+) and the model type flag, and the plot style placeholder carries no subclass marker (#3085; structure test `r2000_and_later_files_have_the_structure_cad_apps_require`, checked with ezdxf's audit; not yet confirmed in Autodesk Fusion). DXF Options' Preset menu and `document.exportDxf`'s `dxfPreset: "cnc"` set the CNC / CAM options (#5500); VCarve QA remains open | | HP-GL/2 `.plt`, `.hpgl`, `.hgl`, `.hpg` | — | yes (pen moves, pens and widths, line types and attributes, circles, arcs, wedges and Bézier curves, filled and edged rectangles, wedges and polygons, encoded polylines, scaling and rotation; labels, symbol mode, raster images and hatching aren't drawn) | yes (`.plt`: each visible path once along its line, a pen per color or a pen table, type as outlines, clipping applied, HP-GL or HP-GL/2 with pen colors and encoded polylines) | recognized by its first instructions after any printer escapes, under its own extensions or one no other format reads; `crates/cad/src/hpgl/tests.rs`, `crates/cad/src/hpgl/write/tests.rs` (plots read back by the reader), `tests_hpgl.rs`, `import_fuzz.rs` | | DWG | open, export | no | no | no open spec; DXF instead | diff --git a/docs/gaps.md b/docs/gaps.md index 2b002dc1c7..0c4d904d3e 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-15 · **Change:** minor (G12: Swatches item menus tested and rendered; Linux full CI passed; Windows engine baseline failures noted; scores and estimates unchanged; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups <g>, 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) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-15 · **Change:** minor (G12: Swatches item menus tested and rendered; original feature Linux CI passed; integration blocked by upstream #7727; Windows engine baseline failures noted; scores and estimates unchanged; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups <g>, 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,8 +34,9 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| -| 2026-11-15 | minor | G12: Swatches item menus validated in all five views: 39 focused tests passed, regression fails without the menu hooks, rendered list/thumbnail layouts inspected, and fresh local deep CodeRabbit review found zero issues. Full workspace CI passed on Linux/WSL (all 13 gates); native Windows full CI has two unchanged engine-test failures. Scores and estimates unchanged. | +| 2026-11-15 | minor | G12: Swatches item menus validated in all five views: 39 focused tests passed, regression fails without the menu hooks, rendered list/thumbnail layouts inspected, and fresh local deep CodeRabbit review found zero issues. Full workspace CI passed on Linux/WSL for feature commit `6f4a651c0` (all 13 gates); validation after merging main stops at the upstream test-helper compile error tracked in #7727; native Windows full CI has two unchanged engine-test failures. Scores and estimates unchanged. | | 2026-11-14 | minor | G12: Swatches item context menus in list and thumbnail views: Swatch Options…, Duplicate Swatch and Delete Swatch target the clicked item without applying paint. Reserved or missing swatches disable actions. Headless interaction tests added; execution and visual verification pending. Scores and estimates unchanged. | +| 2026-11-14 | minor | G12: Symbols panel context menu: right-click on a symbol in thumbnail or list view displays a context menu (Place Symbol Instance, Edit Symbol, Duplicate Symbol, Delete Symbol, Break Link to Symbol, Select All Instances), selecting the symbol first if unselected; scores and estimates unchanged. | | 2026-11-14 | minor | G5: Weather Icons joins Basic Shapes, UI Frames, Map Markers, Inventory Icons and Skill Icons as a sixth built-in symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow; original procedural vector symbols generated in code, no default 9-slice); estimate decremented (5–15 → 4–14 h). | | 2026-11-14 | minor | G12: Layers panel row context menu (Options…, Duplicate, Delete, Lock Others/Show All/Hide Others/Unlock All, Locate Object, Collect for Export) with selection handling and undo tracking. Scores and estimates unchanged. | | 2026-11-13 | minor | PDF import: preserve Type 3 font text runs as named groups `<g>`, 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. | @@ -467,8 +468,9 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G12 Preferences and panels that don't act yet -- **Implemented and tested (2026-11-15):** Swatches list rows and thumbnail cells have item context menus with Swatch Options…, Duplicate Swatch and Delete Swatch. Right-click selects the target without painting art; actions use that item's name and are disabled for reserved or missing swatches. All 39 Swatches tests pass, covering all five views, command dispatch, selection and Undo; the regression fails with the menu hooks removed. Rendered list and thumbnail menus were inspected. Full workspace CI passed on Linux/WSL (all 13 gates); native Windows full CI has two unchanged engine-test failures. Other panels without context menus remain in G12; estimate unchanged. +- **Implemented and tested (2026-11-15):** Swatches list rows and thumbnail cells have item context menus with Swatch Options…, Duplicate Swatch and Delete Swatch. Right-click selects the target without painting art; actions use that item's name and are disabled for reserved or missing swatches. All 39 Swatches tests pass, covering all five views, command dispatch, selection and Undo; the regression fails with the menu hooks removed. Rendered list and thumbnail menus were inspected. Full workspace CI passed on Linux/WSL for feature commit `6f4a651c0` (all 13 gates); validation after merging main stops at the upstream test-helper compile error tracked in #7727; native Windows full CI has two unchanged engine-test failures. Other panels without context menus remain in G12; estimate unchanged. +- **Done (2026-11-14):** Symbols panel context menu: right-click on a symbol in thumbnail or list view displays a context menu with Place Symbol Instance, Edit Symbol, Duplicate Symbol, Delete Symbol, Break Link to Symbol (enabled when canvas selection includes instances of the symbol), and Select All Instances, selecting the symbol if unselected. Estimate unchanged. - **Done (2026-10-29, #4522):** the Pathfinder panel menu's Make, Release and Expand Compound Shape, which were dimmed placeholders, and the panel's Expand button act on live compound shapes ([Create compound shapes with Pathfinder](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/create-compound-shapes-with-pathfinder.html)): Alt-clicking a Shape Mode makes one in that mode, a Shape Mode sets the mode of the members selected, and the compound shape draws, exports and saves as the area its members' modes make (`object.compoundShape.*`, `crates/engine/src/tests/compound_shape.rs`). Left: blends, envelopes and warps as members, question marks on the buttons for mixed member modes, clicks that hit the area rather than the members. Estimate unchanged. - **Done (2026-10-25, #3426):** Pathfinder panel › Pathfinder Options… ([Pathfinder panel overview](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/pathfinder-panel-overview.html)): Precision (0.001–10 pt; results are refit to within it and pieces thinner than it are dropped), Remove Redundant Points and Divide and Outline Will Remove Unpainted Artwork (pieces of objects with no fill), kept in the preferences (`object.pathfinder.options`, group `pathfinder`) and used by every Shape Mode and Pathfinder button and Repeat; the page gives no defaults, so ours (0.01 pt, both off) keep the earlier results byte for byte. Trap is left as it was. Estimate unchanged. - **Done (2026-10-25):** Artboards panel › Delete Empty Artboards ([Delete artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/delete-artboards.html), [artboard context menu](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/use-artboard-context-menu.html)): `artboard.deleteEmpty` deletes every unlocked artboard with no artwork, with its guides, in one undo step, and keeps artboard 1 when every artboard is empty and none is locked; an artboard is empty when no object (hidden, locked and template art included; guides not) has visual bounds that meet or touch it, a group counting by its members and a clip group or clipping layer by its members inside the clip (our reading of "no artwork"; the pages give no finer rule). The Artboard tool's canvas context menu lists it too. Estimate unchanged. @@ -636,6 +638,9 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi 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)); + rotated copies of the object or group are taken too, and an edit reaches each turned by its angle + ([public source](https://helpx.adobe.com/vn_vi/illustrator/how-to/modern-logo-design.html); reflected copies are not + taken, VectorCraft's own rule); 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 @@ -681,8 +686,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi painted with the texture effects; User Defined; Other Library…; `graphicStyle.libraries`, `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, Skill Icons and Weather Icons; original, generated in code, never Adobe's); dynamic symbols' `.ai` read and write; - Global Edit of rotated copies as matches. + Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons and Weather Icons; original, generated in code, never Adobe's); dynamic symbols' `.ai` read and write. - **Estimate:** 4–14 h. ## G3 3D and Materials @@ -886,7 +890,7 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | Date | Change | Summary | |---|---|---| -| 2026-11-15 | minor | G12: Swatches item menus validated in all five views: 39 focused tests passed, regression fails without the menu hooks, rendered list/thumbnail layouts inspected, and fresh local deep CodeRabbit review found zero issues. Full workspace CI passed on Linux/WSL (all 13 gates); native Windows full CI has two unchanged engine-test failures. Scores and estimates unchanged. | +| 2026-11-15 | minor | G12: Swatches item menus validated in all five views: 39 focused tests passed, regression fails without the menu hooks, rendered list/thumbnail layouts inspected, and fresh local deep CodeRabbit review found zero issues. Full workspace CI passed on Linux/WSL for feature commit `6f4a651c0` (all 13 gates); validation after merging main stops at the upstream test-helper compile error tracked in #7727; native Windows full CI has two unchanged engine-test failures. Scores and estimates unchanged. | | 2026-11-14 | minor | G12: Swatches item context menus implemented in list and thumbnail views, with clicked-item actions and reserved/missing-swatch guards. Harness tests added; execution and visual verification pending. Scores and estimates unchanged. | | 2026-11-12 | minor | 3D: The seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins (the seams of Revolve and of colored lights, and 3D (Classic) Wireframe edges, were already round): no thorns on edge-on facets, and facets with no neighbour now have rounded convex corners ([three-d.md](three-d.md#seams)). Scores and estimates unchanged. | | 2026-11-12 | minor | Explicit editing-data import keeps a single artboard beyond a capped 14,400 pt PDF page (#6865), with a warning; automatic mode stays unchanged. Scores and estimates unchanged. | diff --git a/docs/image-trace-adjustments.md b/docs/image-trace-adjustments.md index f1c0b7d3dd..22557771e2 100644 --- a/docs/image-trace-adjustments.md +++ b/docs/image-trace-adjustments.md @@ -18,6 +18,13 @@ its current location. Opening the controls does not add a document undo step. | Create | Fills / Strokes | Creates filled areas, stroked lines, or both. | | Ignore Color | Color picker | Leaves out the selected color (white by default). | +The built-in presets other than Auto Color and Flat Logo all use Paths 50, and so do their enhanced +versions. Among those presets, Corners is 100 in Technical Drawing, 75 in Default, Black and White +Logo, Line Art and Outline, and 50 in the other eight. Noise is 1 px in Technical Drawing, 5 in High Fidelity Photo, 10 in Low Fidelity Photo, 15 in 3 Colors, +6 Colors, 16 Colors and Shades of Gray, 20 in Sketched Art, Line Art and Outline, 25 in Default and +Black and White Logo, and 90 in Silhouettes (see +[image-trace-quality.md](image-trace-quality.md#preset-paths-corners-and-noise)). + Sliders apply on release, and their numeric fields can be edited directly. Each committed adjustment re-traces the selected object as one undo step and changes the preset to Custom. While dragging, the preset and Enhanced row stay in place until release so the @@ -109,6 +116,24 @@ The trace then uses only the named colors, and white while white is a color of i color that was not named is traced too: each of its pixels goes to the named color, white or transparent that has the largest share in the blend of them that comes closest to the pixel. +**Flat Logo with a color between two others.** When a traced color lies between two others, as a gray +lies between black and white, an anti-aliased edge pixel between the outer two is also a blend of the +middle color and one of them. Flat Logo then reads the pixel as the blend of the colors that lie nearest +it in the flat areas within 6 pixels, when the pixel has a neighbor darker and a neighbor lighter than the +middle color, along the line between the other two. A black disc beside a gray square on white traces +with one gray shape, the square, and no gray slivers around the disc, when its edges are sharp or blurred +by up to about half a pixel. An edge blurred by a pixel or more can still leave gray slivers along the +disc, and so can an image with noise of a level or more in its pixels. A gray stroke two or three pixels +wide beside black has no darker pixel next to it and stays gray. A soft-edged gray stroke about two +pixels wide that touches black traces as black and white, and one about three pixels wide that touches +black can lose most or all of its gray when it is short (12 pixels long or less). A line of gray one +pixel wide between black and white stays gray when at least 13 of its pixels touch: such a line and a +straight black-to-white edge whose pixels are as light as the gray give the same pixels, and both +trace as gray. A one-pixel gray line between black and white that is shorter than 13 pixels, falls +between pixels or is blurred traces as black and white. A flat area whose color lies between two named colors, as when the colors are named +some levels off, counts as holding the named colors it is a blend of, and so do the pixels of exactly +its color that touch it. + **Large images.** An image of more than 1500 pixels on a side is traced as any other, only more slowly, and the trace says so: `imageTrace.make` returns the note in `warnings` and the status bar shows it (the [results optimization](https://helpx.adobe.com/illustrator/using/image-trace-results-optimization.html) @@ -118,12 +143,14 @@ most 1024 pixels on a side: a larger decoded raster is averaged down in whole-nu image is traced at 513, and a 16,000 × 12,000 image, decoded at 9,459 × 7,094, is traced at 946 × 710), and the trace names both sizes in `warnings`. Flat Logo gives that note in place of the slower-trace note for an image over 1500 pixels and in place of the 64-megapixel note. An image at most 1024 pixels on a side is traced at its own size, also when the named `logoColors` differ slightly from the -image's colors. Only an image with more than 150,000 different pixel values that are not exactly one traced -color is averaged down further: the factor doubles until at most 150,000 remain or the working copy has at +image's colors. Only an image with more than 150,000 different pixel values to unmix (values that are +not exactly one traced color, and values that are, at pixels outside a flat area) is averaged down +further: the factor doubles until at most 150,000 remain or the working copy has at most 16,384 pixels (at most six times). A trace that would make more than 8,000,000 anchor points (2,000,000 on the web) is refused to protect memory, with advice: raise Noise, lower Paths or Colors, or pick a lower-fidelity preset. A trace keeps -about 90 bytes an anchor; a 4000 × 3000 photo at High Fidelity Photo makes about 1.9 million. +about 90 bytes an anchor; a 4000 × 3000 photo at Limited 64 colors, Paths 90, Corners 25 and Noise 4 +makes about 1.9 million. **Tracing in the background.** On the desktop a trace runs on a thread of its own, so the window keeps answering while a photo or a large image is traced (#3098). Make, Make and Expand, the task bar's Image Trace and the panel's Trace and presets start it. The status bar says "Tracing the diff --git a/docs/image-trace-quality.md b/docs/image-trace-quality.md index 4765a2d779..dacf436036 100644 --- a/docs/image-trace-quality.md +++ b/docs/image-trace-quality.md @@ -82,6 +82,9 @@ gradient, texture, sensor noise): (The last two rows were measured without a limit; they are refused now.) The 4000 × 3000 High Fidelity Photo trace was 86,000 anchors under the old limit; a noisier scan of the same size would have been refused. At 8,000,000 anchors a trace keeps about 0.7 GB, with a peak of about 0.9 GB while tracing. +The preset rows were measured with the earlier preset values: High Fidelity Photo at Paths 90, Corners 25 +and Noise 4, Low Fidelity Photo at Paths 60, Noise 12 and 16 Colors at Paths 70, Corners 55 and Noise 10 +(see [Preset Paths, Corners and Noise](#preset-paths-corners-and-noise)). ## Collapsed loops keep few segments A small closed loop (or a piece that returns to its own junction) whose fit collapsed to a single cubic cannot stay as one, so it kept every positioned point as a straight segment. A looser Paths @@ -225,6 +228,47 @@ in a smooth area), `a_staircase_that_runs_on_from_a_smooth_area_into_an_edge_kee `a_staircase_of_mixed_one_pixel_and_longer_steps_is_one_slope_without_a_notch`, `a_run_of_two_steps_keeps_its_corners`, `a_junction_on_a_step_ends_the_staircase_there` and `a_step_whose_cracks_read_as_an_edge_ends_the_staircase_there`. +## Preset Paths, Corners and Noise +Every built-in preset other than Auto Color and Flat Logo traces at Paths 50. Corners and Noise are: + +| preset | Paths | Corners | Noise | before | +|:--|--:|--:|--:|:--| +| Default | 50 | 75 | 25 | unchanged | +| High Fidelity Photo | 50 | 50 | 5 | 90, 25, 4 | +| Low Fidelity Photo | 50 | 50 | 10 | 60, 50, 12 | +| 3 Colors | 50 | 50 | 15 | 60, 60, 20 | +| 6 Colors | 50 | 50 | 15 | 65, 60, 16 | +| 16 Colors | 50 | 50 | 15 | 70, 55, 10 | +| Shades of Gray | 50 | 50 | 15 | 60, 50, 10 | +| Black and White Logo | 50 | 75 | 25 | 95, 80, 8 | +| Sketched Art | 50 | 50 | 20 | 50, 50, 100 | +| Silhouettes | 50 | 50 | 90 | 40, 60, 30 | +| Line Art | 50 | 75 | 20 | 80, 70, 10 | +| Technical Drawing | 50 | 100 | 1 | 95, 90, 4 | +| Outline | 50 | 75 | 20 | 80, 70, 10 | + +The palettes, color counts, thresholds and other options of the presets did not change. The enhanced +versions of these presets use the same Paths, Corners and Noise. + +Measured with the harness below (section 1, each preset on the inputs it is meant for), before and after: +anchors fall in 10 of the 12 changed presets, for example 5,494 to 3,136 (High Fidelity Photo), 33 to 27 +(16 Colors), 27 to 14 (Black and White Logo) and 43 to 28 (Line Art); Silhouettes rises from 13 to 15 and +Sketched Art does not change. Outlines on flat art lie further from the true edge: off mean 0.100 to 0.123 +px (16 Colors), 0.101 to 0.119 (6 Colors), 0.104 to 0.129 (3 Colors), 0.064 to 0.092 (Black and White Logo) +and 0.056 to 0.074 (Line Art), and off max 1.00 to 1.16 px in 6 Colors and 16 Colors. Technical Drawing +leaves 1.4 specks (was 0.5), and Outline's stroked center lines lie 0.095 px off (was 0.086) with 2.7 +anchors a stroke (was 3.0). ΔE changes by 0.01 or less except Line Art and Outline (2.62 and 2.61 to 2.66 +and 2.67); edge ΔE rises in 8 of the 12, for example 4.79 to 5.25 (16 Colors), 3.98 to 4.46 (3 Colors) and 9.46 to 10.03 +(Black and White Logo). On synthetic shapes and photos of 300 to 4,000 px traced outside this harness, +High Fidelity Photo makes 41% fewer anchors and 16 Colors 20% fewer; the mean pixel difference of each +trace changes by −0.23 to +0.26 of a level; 16 Colors leaves 41 staircases of steps of 2 px or more where it left 40, High +Fidelity Photo 440 where it left 391, Low Fidelity Photo 96 where it left 77, Line Art 17 where it left 13, Outline 13 +where it left 10 and 3 Colors 14 where it left 12. On the same images Sketched Art makes 4,084 anchors where it made +3,936 and Silhouettes 1,608 where it made 1,578. The figures for these twelve presets and their enhanced versions in +the other sections of this file, and in the Image Trace entries of +[target-app-parity.md](target-app-parity.md), were measured at the earlier values. +Test: `presets_have_their_paths_corners_and_noise` in `crates/trace/src/tests.rs`. + ## A simpler contour walk `contour::trace_mask` follows each region's outline along the pixel cracks with the inside on the right. It used to build a table of outgoing directions for every pixel corner in a raster pass and diff --git a/docs/localization-hi.md b/docs/localization-hi.md index 3d304a5d50..743a1697ec 100644 --- a/docs/localization-hi.md +++ b/docs/localization-hi.md @@ -32,6 +32,13 @@ every clause such as "all" or "what follows it". Type as a text object is टा in `crates/ui-egui/src/i18n/tests.rs` checks the save, swatch, crop, resolution and path terms and the point unit in every row. +Translate a label by its sense in the interface, not by its first dictionary sense. A ruler is +रूलर, never शासक (a sovereign); a text character is कैरेक्टर, never चरित्र (a personality); a +vector point is पॉइंट and a printer's mark is मार्क, never अंक (a digit); fills are फ़िल्स, never +भरता (the verb). In a minimum, desired and maximum range, Desired is वांछित, never देसी (local), +and a range message keeps both comparisons: minimum ≤ desired ≤ maximum. The same test rejects +these senses, and others found in the catalog, in every row whose English names the word. + A variable is वेरिएबल (plural वेरिएबल्स) in every sense: a data-merge variable and the variable library, a variable font, a variable stroke width and an environment variable. It is never चर, परिवर्तनीय or वैरिएबल. Joining paths, anchor points, point type or the lines of a @@ -61,7 +68,10 @@ checks every `@msg` row's lists. | Artwork | आर्टवर्क | | Path / Anchor point / Handle | पाथ / एंकर पॉइंट / हैंडल | | File path on disk | फ़ाइल पाथ | -| Fill / Stroke | फ़िल / स्ट्रोक | +| Fill / Fills / Stroke | फ़िल / फ़िल्स / स्ट्रोक | +| Point (vector) / Printer's marks | पॉइंट / मार्क्स | +| Ruler / Ruler origin | रूलर / रूलर ओरिजिन | +| Minimum / Desired / Maximum | न्यूनतम / वांछित / अधिकतम | | Gradient / Mesh / Blend | ग्रेडिएंट / मेश / ब्लेंड | | Pattern / Swatch | पैटर्न / स्वॉच | | Type (text object) / Crop / Resolution | टाइप / क्रॉप / रिज़ॉल्यूशन | @@ -89,7 +99,10 @@ percentage of the application's entire interface. On 2026-11-13 the catalog has 8,782 rows, including 3,014 `@msg`, 47 `@msgplural` and 41 `@plural` rows. A wording pass on that date corrected 193 rows outside the plug-in messages for meaning, dropped clauses, English left in place and the save, swatch, crop, -resolution, path and type terms. It is not a native proofread. +resolution, path and type terms. A second pass on that date corrected 85 short labels and +messages that used a word's unrelated sense, such as देसी (local) for Desired, शासक (a +sovereign) for a ruler and उच्च न्यायालय (a high court) for High Contrast. It is not a native +proofread. The comparison covers release `v0.21.1` (`f6aa4309`) and current `main` (`3c7d9e1f`). Their non-English catalogs have no missing Hindi keys except the names deliberately kept in English. @@ -98,8 +111,12 @@ main added paragraph labels, spine-index validation and two error messages: six Main's workspace version is still 0.21.0; this PR does not change release versioning. `cargo test -p vectorcraft-ui-egui --lib i18n::tests` passes all 55 tests in Ubuntu 24.04 (WSL). -The untranslated report has no Hindi section, meaning it found no missing Hindi rows among the -categories it checks. This does not check dynamically assembled strings that the scanners miss. +On 2026-11-14 the untranslated report on main (`f793044f83`) has a Hindi section with 608 +missing rows: 28 menu strings, 30 `tl!` strings, 11 undo labels and 539 messages. Its +`every language` section lists 68 more that every checked language lacks, Hindi included: 10 menu +strings, 2 undo labels and 56 messages. These include labels for newer features and command +parameter, script and file import or export errors, which show in English until a catalog row +is added. The report does not check dynamically assembled strings that the scanners miss. Additional checks compare placeholders, backtick-delimited identifiers and numeric values. The native Hindi UI fallback test also passes with the installed Nirmala UI font. A running desktop preview was checked in Hindi, including the New Document dialog and File menu. diff --git a/docs/localization-parity.md b/docs/localization-parity.md index d62b475105..2fa44a769e 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -15,7 +15,7 @@ translation never fails a test or a build: the interface shows the English text `cargo xtask ci` prints the untranslated report (`cargo xtask i18n-report` alone), which lists per language the strings missing from each catalog with the `complete_menus` flag and the messages missing from each language in the `COMPLETE_MESSAGES` list. Every non-English language marked "full" has the flag, and all of them except -Bulgarian, Danish and Indonesian are in the list. No language has help content: there is no translated (or +Bosnian, Bulgarian and Indonesian are in the list. No language has help content: there is no translated (or English) in-app help, and the docs are English. **Native review:** every catalog was written clean-room from the English meaning, most of it by agents @@ -31,21 +31,21 @@ Chinese by `imachus`). Georgian and the original Gujarati catalog are recorded a | English | `en` | source, 100% | all | Latin | — | full | — | | Simplified Chinese (Mandarin) | `zh-hans` | 5,102 rows, 791 of them `@msg` (counted 2026-10-21): menus, `tl!` literals and messages complete when counted | all (3,554 `@msg` and 48 `@msgplural` rows, counted 2026-11-13: the untranslated report lists 55 missing messages for it, which open #7116, #7211, #7330, #7378 and #7405 translate) | CJK UI font from craft-fonts (BIZ UDPGothic) when embedded, else a system font; IME with marked text at the caret; vertical type partial ([type-parity.md](type-parity.md)) | no | full | — (review) | | Spanish | `es` | 4,009 / 4,020 (99.7%) | all (604 messages) | Latin | no | full | — (review) | -| Hindi | `hi` | 8,782 rows (2026-11-13): 3,014 `@msg`, 47 `@msgplural`, 41 `@plural`; no gaps in the untranslated report | menus, dialogs, tooltips and scanned messages; contributor-approved loanword terminology; agent wording pass | UI and document text shape with HarfRust; installed desktop Devanagari fallback, or a `Deva` craft-fonts face; web font still needed | contributor terminology review; 2026-11-13 wording pass on messages and longer labels, with a glossary-term test; wider proofread welcome | complete catalog, machine-assisted draft | native review, layout and web font | +| Hindi | `hi` | 8,782 rows (2026-11-13): 3,014 `@msg`, 47 `@msgplural`, 41 `@plural`; the untranslated report on main `f793044f83` (2026-11-14) lists 676 missing rows for it: 608 in its own section and 68 that every checked language lacks | menus, dialogs, tooltips and scanned messages; contributor-approved loanword terminology; agent wording pass | UI and document text shape with HarfRust; installed desktop Devanagari fallback, or a `Deva` craft-fonts face; web font still needed | contributor terminology review; 2026-11-13 wording pass on messages and longer labels, and a word-sense pass on short labels, with a glossary-term test; wider proofread welcome | complete catalog, machine-assisted draft | reported missing rows, native review, layout and web font | | Gujarati | `gu` | 4,673 rows (2026-11-14): original 4,286 unchanged; all 387 additions contributor-reviewed and approved | menus and dialogs; status/error messages partial | installed Gujarati fonts on desktop; optional `Gujr` craft-fonts fallback; no Gujarati face in the pinned CI/release fonts or web startup list | original catalog reviewed by a native speaker; all 387 later additions approved by the contributor, with 11 wording corrections | contributor-reviewed catalog | remaining messages and a bundled Gujarati web font | | Arabic | `ar` | 0 | none | document text: bidi layout and Paragraph Direction; interface: no right-to-left layout, no Arabic shaping in egui | no | none | 25–40 | | French | `fr` | 9,166 rows, 3,436 of them `@msg` and 48 `@msgplural` (counted 2026-11-13): the untranslated report lists 178 missing messages for it | all | Latin | no | full | — (review) | -| Portuguese | `pt-br` | 9,260 rows, 3,445 of them `@msg` and 48 `@msgplural` (counted 2026-11-13): the untranslated report lists 39 missing messages for it; one/other plurals | all | Latin | contributor is a Brazilian Portuguese speaker; further native review welcome | full | — (review) | -| Indonesian | `id` | 5,279 rows, 750 of them `@msg` (counted 2026-10-21): menus and `tl!` literals complete when counted; its messages are partial; one plural form | dialogs and tooltips all; 750 message rows (French has 796) | Latin | no | full | — (review) | -| Japanese | `ja` | 4,004 / 4,020 (99.6%) | all | CJK UI font as above; Japanese IME; vertical type partial; Japanese crop marks and composition settings | no | full | — (review) | +| Portuguese | `pt-br` | 9,378 rows, 3,563 of them `@msg` and 48 `@msgplural` (counted 2026-11-13): the untranslated report lists 55 missing messages for it, which open #7116, #7211, #7330, #7378 and #7405 translate; one/other plurals | all | Latin | contributor is a Brazilian Portuguese speaker; further native review welcome | full | — (review) | +| Indonesian | `id` | 6,825 rows, 1,036 of them `@msg` and 47 `@msgplural` (counted 2026-11-14 on `main` at `676f0524cc`): the untranslated report lists 60 missing menu strings, 35 `tl!` literals and 13 undo labels for it; not in `COMPLETE_MESSAGES`, and checked against the same scanned messages it lacks 2,508; one plural form | most dialogs and tooltips; status and error messages partial | Latin | no | full | — (review) | +| Japanese | `ja` | 4,004 / 4,020 (99.6%) | partial (3,562 `@msg` and 49 `@msgplural` rows, counted 2026-11-14: the untranslated report lists 98 messages without a Japanese row, 77 of which every complete-message language lacks; open #7116 and #7211 translate 35 of them) | CJK UI font as above; Japanese IME; vertical type partial; Japanese crop marks and composition settings | no | full | — (review) | | German | `de` | 3,952 / 4,020 (98%; menus, literals and messages complete when counted) | all (3,563 `@msg` and 48 `@msgplural` rows, counted 2026-11-13: the untranslated report lists 52 missing messages for it, which open #7116, #7211 and #7378 translate) | Latin | contributor-written, not reviewed | full | — (review) | | Korean | `ko` | 4,870 rows (counted 2026-10-21): menus, `tl!` literals and messages complete when counted; one plural form | all (3,438 `@msg` and 48 `@msgplural` rows, counted 2026-11-13: the untranslated report lists 39 missing messages for it) | Hangul from an installed system font on the desktop (Apple SD Gothic Neo, Malgun Gothic, Noto Sans CJK KR…); the web build has no Korean UI font yet (craft-fonts); IME path exists | no (AI-drafted) | full | — (review; web font) | -| Vietnamese | `vi` | 4,886 rows (counted 2026-10-21): menus, `tl!` literals and messages complete when counted; one plural form; 4,046 plain + 18 `@plural` + 28 contextual + 794 `@msg` | all | Latin with Vietnamese diacritics (stacked marks attach in precomposed, decomposed and keyboard forms, #4491; glyph tests pass) | contributor is a Vietnamese speaker; AI-assisted draft, further native review welcome | full | — (review) | +| Vietnamese | `vi` | 4,886 rows (counted 2026-10-21): menus, `tl!` literals and messages complete when counted; one plural form; 4,046 plain + 18 `@plural` + 28 contextual + 794 `@msg` | dialogs and tooltips all; messages partial (1,750 `@msg` and 49 `@msgplural` rows, counted 2026-11-14: the untranslated report lists 1,875 messages without a Vietnamese row, 53 of which open #7211, #7378, #7405 and #7434 translate) | Latin with Vietnamese diacritics (stacked marks attach in precomposed, decomposed and keyboard forms, #4491; glyph tests pass) | contributor is a Vietnamese speaker; AI-assisted draft, further native review welcome | full | — (review) | **Historical 12-language score: ~82%** (equal weights: 100 + 85 + 100 + 0 + 0 + 100 + 100 + 100 + 100 + 98 + 100 + 100, over 12). **To `full` for all twelve: ~50–85 h** (historical estimate, not re-scored here). Hindi now has -a complete catalog and UI shaping; its remaining work is native review, layout checking and the -web font. Arabic still needs its catalog and right-to-left interface. Each new Latin-script catalog is ~4,000 rows; the existing ones were written in a few agent hours each +a catalog that the tests count as complete, and UI shaping; its remaining work is the rows the +untranslated report lists for it, native review, layout checking and the web font. Arabic still needs its catalog and right-to-left interface. Each new Latin-script catalog is ~4,000 rows; the existing ones were written in a few agent hours each plus review. Native-speaker review is human work and isn't in the hours. ## Other shipped languages @@ -53,22 +53,21 @@ plus review. Native-speaker review is human work and isn't in the hours. | Language | Code | Translated | Status | |---|---|---|---| | Traditional Chinese (Taiwan) | `zh-hant` | 8,820 rows, 3,438 of them `@msg` and 48 `@msgplural` (counted 2026-11-13): the untranslated report lists 40 missing messages for it; menus, `tl!` literals and messages were complete when counted on 2026-10-21 (80% overall) | partial | -| Italian | `it` | 8,757 rows, 3,422 of them `@msg` and 48 `@msgplural` (counted 2026-11-13): the untranslated report lists 40 missing messages for it | full | +| Italian | `it` | 8,924 rows, 3,560 of them `@msg` and 48 `@msgplural` (counted 2026-11-13): the untranslated report lists 54 missing messages for it, which open #7116, #7211, #7378 and #7405 translate | full | | Dutch | `nl` | 3,447 `@msg` and 48 `@msgplural` rows (counted 2026-11-13): in `COMPLETE_MESSAGES`, and the untranslated report lists 41 missing messages for it; one/other plurals | full | -| Danish | `da` | 5,279 rows, 750 of them `@msg` (counted 2026-10-21): menus and `tl!` literals complete when counted; its messages are partial; one/other plurals | full | +| Danish | `da` | 7,422 rows, 1,636 of them `@msg` and 48 `@msgplural` (counted 2026-11-14 on `main` at `edb228ac3`): in `COMPLETE_MESSAGES`, and the untranslated report lists the same missing messages for it as for Greek, Spanish and Finnish; one/other plurals | full | | Russian | `ru` | 4,009 / 4,020 | full | | Ukrainian | `uk` | 8,802 rows, 3,439 of them `@msg` and 48 `@msgplural` (counted 2026-11-13); one/few/many plurals | full | -| Hungarian | `hu` | 5,253 rows (counted 2026-10-21): menus, `tl!` literals and messages complete when counted; one plural form | full | +| Hungarian | `hu` | 9,166 rows, 3,444 of them `@msg` and 48 `@msgplural` (counted 2026-11-13): the untranslated report lists 40 missing messages for it, and lists 47 menu strings, 25 `tl!` strings, 11 undo labels and 45 swatch names without a row; one plural form | full | | Polish | `pl` | 9,044 rows, 3,439 of them `@msg` and 48 `@msgplural` (counted 2026-11-13): the untranslated report lists 46 missing messages for it, and 47 menu strings, 26 `tl!` literals, 11 undo labels and 45 swatch names; one/few/many plurals | full; native review pending | | Finnish | `fi` | 5,318 rows (counted 2026-10-21): menus, `tl!` literals and messages complete when counted; one/other plurals, 797 `@msg` rows | full; AI-assisted, native proofreading pending | -| Czech | `cs` | 9,155 rows, 3,445 of them `@msg` and 48 `@msgplural` (counted 2026-11-13): the untranslated report lists 40 missing messages for it | catalog complete; render-site gaps reduced; native review pending | -| Bosnian | `bs` | 5,841 rows (counted 2026-10-30): menus, `tl!` literals and messages complete when counted; one/few/other plurals | full; AI-assisted, native review pending | -| Swedish | `sv` | 5,251 rows, 795 of them `@msg` (counted 2026-10-21): menus, `tl!` literals and messages complete when counted; one/other plurals | full; native review welcome | +| Czech | `cs` | 9,273 rows, 3,560 of them `@msg` and 48 `@msgplural` (counted 2026-11-13): the untranslated report lists 2 missing Czech messages, and 54 messages that no language has a row for | catalog complete; render-site gaps reduced; native review pending | +| Bosnian | `bs` | 6,887 rows, 1,144 of them `@msg` and 47 `@msgplural` (counted 2026-11-14 on `main` at `676f0524cc`): the untranslated report lists 97 missing menu strings, 53 `tl!` literals and 27 undo labels for it; not in `COMPLETE_MESSAGES`, and checked against the same scanned messages it lacks 2,416; one/few/other plurals | full; AI-assisted, native review pending | +| Swedish | `sv` | 8,991 rows, 3,106 of them `@msg` and 48 `@msgplural` (counted 2026-11-14): the untranslated report lists 518 missing messages for it, and 12 menu strings, 1 `tl!` literal and 3 undo labels; one/other plurals | full; native review welcome | | Bulgarian | `bg` | 5,245 rows, 763 of them `@msg` (counted 2026-10-21): menus and `tl!` literals complete when counted; its messages are partial | full; AI-drafted, native review pending | | Greek | `el` | 5,251 rows, 795 of them `@msg` (counted 2026-10-21): menus, `tl!` literals and messages complete when counted | full; native review welcome | | Georgian | `ka` | 5,200 rows (counted 2026-10-21): menus, panels, dialogs, plurals (one count-neutral form) and messages, tested complete; reviewed by a native speaker | full | -| Turkish | `tr` | 5,558 rows, 880 of them `@msg` (counted 2026-10-28); 6 menu strings and the default swatch names still fall back to English | full | -| Indonesian | `id` | 5,531 rows, 788 of them `@msg` (counted 2026-10-28): menus and `tl!` literals complete when counted; its messages are partial; one plural form | full | +| Turkish | `tr` | 9,175 rows, 3,446 of them `@msg` and 48 `@msgplural` (counted 2026-11-13); 41 messages, 62 menu strings, 26 `tl!` literals, 13 undo labels and the default swatch names still fall back to English | full | | Catalan | `ca` | 5,626 rows, 881 of them `@msg` (counted 2026-10-28): menus, `tl!` literals and messages complete when counted; one/other plurals; every `ca-*` locale resolves here | full; AI-drafted, native review welcome | Twenty-seven non-English catalogs in all (registry count, 2026-11-06). Illustrator, as its public documentation lists, ships around two dozen diff --git a/docs/mcp.md b/docs/mcp.md index 0cbb30e0b6..d4e03892e9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1,6 +1,6 @@ # VectorCraft MCP server -> **Last updated:** 2026-11-13 · **Change:** Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; no response-shape change. Previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter (#7097); existing response shapes retained. +> **Last updated:** 2026-11-14 · **Change:** Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; no response-shape change. Previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; no response-shape change. Previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; no response-shape change. Previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter (#7097); existing response shapes retained. `vectorcraft-cli mcp` runs a [Model Context Protocol](https://modelcontextprotocol.io) server on stdio (newline-delimited JSON-RPC 2.0; see [Protocol](#protocol) for version negotiation). Agents use it to @@ -289,7 +289,13 @@ the suite) keep the agent to the folders you give it: - The preferences that move folders the app reads or writes on its own (`fontsFolder`, `pluginsFolder`, `recoveryFolder`, `templatesFolder`) can only be set inside the roots. The app's own folders (preferences, Data Recovery, the User Defined library folders, VectorCraft's Fonts folder) are not - confined: no agent names a path there. + confined. These commands that act on a file there are confined: `stroke.arrowheads.edit` and + `stroke.arrowheads.reload` refuse an arrowheads file outside the read roots, and `stroke.arrowheads.list` gives its + `file` as `null` there (see [Arrowheads](#arrowheads)); `file.newProfiles.edit` needs read and write access to the + New Document profile's file, `file.newProfiles.reset` needs write access, and `file.new` starts with the defaults + when the read roots leave out the profiles folder (see [New Document profiles](#new-document-profiles)); + `script.listInstalled` lists the Scripts folder and `ui.runInstalledScript` runs a script only inside a read root + (see [Script engines](#script-engines)). - The roots must be existing folders; a missing one stops the server with an error. Each flag takes one folder per use (`--flag <dir>` or `--flag=<dir>`) and may be used again for more. @@ -641,8 +647,8 @@ sampler. | `inspect_document` | `{depth?, childLimit?, ids?, kind?, limit?, offset?}` | Artboards (with `color`, `#rrggbb`, for one with a background color), layer tree (ids, kinds, bounds, paint), selection, history, tool. A type node's `fill`, `stroke` and `strokeWidth` are the paint its characters show (its first run's); fills and strokes of the type object itself come as `objectFill`, `objectStroke` and `objectStrokeWidth`. Paint comes as a label (`"#ff0000"`, `"None"`, `"G1 40% (#ff9999)"` for a swatch at a tint); `paint.proxies` gives it as an object. | | `inspect_ui` | `{}` | UI state. Remote mode only. | | `select_tool` | `{tool}` | `selection`, `directSelection`, `pen`, `rectangle`, `ellipse`, `polygon`, `star`, `lineSegment`, … | -| `pointer_gesture` | `{events:[{kind,x,y,mods?,backquote?,pressure?,tiltX?,tiltY?,rotation?,holdMs?}], tool?, mods?, backquote?}` | `kind` is one of `down`, `drag`, `up`, `move`, `doubleclick`. `backquote` is the held state for each event; the top-level value supplies its default, and a `backquote` that is not a boolean is an error. Events go through the same path as the mouse. Headless, a `move` replies after the tool's highlight under the pointer is ready, including the Shape Builder's and the Live Paint Bucket's regions of a large selection, which the desktop app finds off the UI thread and highlights after the reply. The release of a Shape Builder click or drag over such a selection replies once the merge is applied, headless and in the desktop app, which computes the merge off the UI thread. In the desktop app, a gesture sent before then is made after the merge, and its reply comes once it is made; a command that can edit, select, save or redraw the documents (a preference, the proof and separations views), sent before then, waits for the merge and runs after it. | -| `pointer_gesture` | `{events:[{kind,x,y,mods?,backquote?,pressure?,tiltX?,tiltY?,rotation?,holdMs?}], tool?, mods?, backquote?}` | `kind` is one of `down`, `drag`, `up`, `move`, `doubleclick`. `backquote` is the held state for each event; the top-level value supplies its default. Events go through the same path as the mouse. Headless, a `move` replies after the tool's highlight under the pointer is ready, including the Shape Builder's and the Live Paint Bucket's regions of a large selection, which the desktop app finds off the UI thread and highlights after the reply. Remote, the events wait until the keys and other input sent before them (`press_key`, `type_text`) have reached the app, so a key pressed between two calls of one drag applies before the release. When that input is dropped because the document, a dialog or the focus changed first, the call fails and its events are not sent. The release of a Shape Builder click or drag over such a selection replies once the merge is applied, headless and in the desktop app, which computes the merge off the UI thread. In the desktop app, a gesture sent before then is made after the merge, and its reply comes once it is made; a command that can edit, select, save or redraw the documents (a preference, the proof and separations views), sent before then, waits for the merge and runs after it. | +| `pointer_gesture` | `{events:[{kind,x,y,mods?,backquote?,pressure?,tiltX?,tiltY?,rotation?,holdMs?}], tool?, mods?, backquote?}` | `kind` is one of `down`, `drag`, `up`, `move`, `doubleclick`, `tripleclick` (`doubleclick` follows the second click's `up`, and `tripleclick` the third's). `backquote` is the held state for each event; the top-level value supplies its default, and a `backquote` that is not a boolean is an error. Events go through the same path as the mouse. Headless, a `move` replies after the tool's highlight under the pointer is ready, including the Shape Builder's and the Live Paint Bucket's regions of a large selection, which the desktop app finds off the UI thread and highlights after the reply. The release of a Shape Builder click or drag over such a selection replies once the merge is applied, headless and in the desktop app, which computes the merge off the UI thread. In the desktop app, a gesture sent before then is made after the merge, and its reply comes once it is made; a command that can edit, select, save or redraw the documents (a preference, the proof and separations views), sent before then, waits for the merge and runs after it. | +| `pointer_gesture` | `{events:[{kind,x,y,mods?,backquote?,pressure?,tiltX?,tiltY?,rotation?,holdMs?}], tool?, mods?, backquote?}` | `kind` is one of `down`, `drag`, `up`, `move`, `doubleclick`, `tripleclick` (`doubleclick` follows the second click's `up`, and `tripleclick` the third's). `backquote` is the held state for each event; the top-level value supplies its default. Events go through the same path as the mouse. Headless, a `move` replies after the tool's highlight under the pointer is ready, including the Shape Builder's and the Live Paint Bucket's regions of a large selection, which the desktop app finds off the UI thread and highlights after the reply. Remote, the events wait until the keys and other input sent before them (`press_key`, `type_text`) have reached the app, so a key pressed between two calls of one drag applies before the release. When that input is dropped because the document, a dialog or the focus changed first, the call fails and its events are not sent. The release of a Shape Builder click or drag over such a selection replies once the merge is applied, headless and in the desktop app, which computes the merge off the UI thread. In the desktop app, a gesture sent before then is made after the merge, and its reply comes once it is made; a command that can edit, select, save or redraw the documents (a preference, the proof and separations views), sent before then, waits for the merge and runs after it. | | `draw_path` | `{points \| d, closed?, fill?, stroke?, strokeWidth?, dash?, cap?, join?, opacity?, name?, effects?}` | `points` is `[[x,y],…]` or `[{x,y,in?,out?,smooth?},…]`. `d` is SVG path data. The options are below. | | `draw_shape` | `{shape, …geometry, fill?, stroke?, strokeWidth?, dash?, cap?, join?, opacity?, name?, effects?}` | `rectangle`/`ellipse`: `x,y,width,height` (plus `radius` for corners). `polygon`: `cx,cy,radius,sides`. `star`: `cx,cy,radius1,radius2,points`. Polygons and stars take `rotation` in degrees clockwise (0: a corner or point straight up). `line`: `x1,y1,x2,y2`. | | `set_paint` | `{fill?, stroke?, strokeWidth?, ids?}` | Applies to the selection (or `ids`) and becomes the default for new art. Returns `{applied, objects}`: `objects` is the number of objects painted, as the `objects` of the `paint.setFill`, `paint.setStroke` and `stroke.set` replies (the largest of them): a selected group counts the objects inside it. When it is 0, a `note` says that only the paint for new art changed. | @@ -660,8 +666,8 @@ sampler. | `pathfinder` | `{operation, ids?}` | `unite`, `minusFront`, `intersect`, `exclude`, `divide`, `trim`, `merge`, `crop`, `outline`, `minusBack`. For a live version, apply the `pathfinder.*` effect to a group (`effect.apply` groups several loose selected objects first). In remote desktop mode, `run_command` and `invoke_menu` can both call `pathfinder.repeat` with `{}`. Successful panel operations, direct `object.pathfinder.*` commands, and `command.batch` steps (including Actions panel playback) set its history. Repeat applies it to the current selection using current Pathfinder Options. Trap, compound-shape edits, live effects and `action.batch` do not set history. With no history it returns "no Pathfinder operation applied yet". | | `transform` | `{ids?, dx?, dy?, rotate?, scale?, scaleX?, scaleY?, reflect?, shear?, origin?, copy?}` | Runs move, rotate, scale, reflect, shear in that order. `rotate` is in degrees counter-clockwise; a positive `shear` moves the top to the right. With `copy`, the first step duplicates. | | `create_graph` | `{type?, x, y, width, height, csv? \| series?, categories?, rows?}` | The nine Illustrator graph types: column, stacked column, bar, stacked bar, line, area, scatter, pie and radar. An empty CSV cell or a `null` in `rows` is a blank value; a number in straight quotes is a label. Edit later with `graph.setData` / `graph.setType` via `run_command`. `graph.column {design, columnType: vertical\|uniform\|repeating\|sliding, each, fractions: chop\|scale}` draws the columns or bars of the series picked with Group Selection (or `seriesIndexes`, or all of them) with a graph design saved by `graph.design`; with no `design` it returns the series' current design and options. Type in the design that holds a `%` followed by two digits shows each column's value, with at least the first digit's places before the decimal point and the second digit's places after it. | -| `text_wrap` | `{ids?, offset?, invert?, release?}` | Area type below the objects (same layer) flows around them. | -| `undo` / `redo` | `{}` | Many calls that change nothing record no undo step, for example `object.align` with nothing to move, `object.move` by 0 without `copy` and `object.showAll` with nothing hidden. `undo` (`edit.undo`) after such a call undoes the step before it. `inspect_document` lists the undo steps as `history`. `run_command` with `edit.clearHistory` removes every undo and redo step of the active document and returns `{cleared}`, the number of steps removed; the document stays as it is, and the command records no undo step. `run_command` with `edit.newDocumentFromState` and `{index?, created?}` makes a new document holding the art as it was at that state and makes it the active document, and returns `{index, title}`. `index` is a row of the History panel, with 0 the oldest state kept, and an omitted `index` uses the current state. An `index` that names no state is an error and changes nothing. `created` is File Info's created date in Unix seconds or null, and defaults to now. The new document takes the next `Untitled-N` name, is marked unsaved, has nothing selected and has no steps to undo or redo. It is out of symbol, opacity-mask and pattern editing, and the art drawn in a pattern's tile is stored in the pattern, as `object.pattern.done` stores it. The source document and its steps stay as they are, except that typing or a drag in progress is first kept as a step. When a command keeps a drag whose preview Real-time Drawing off had not applied yet (`edit.undo`, `edit.redo`, `edit.clearHistory`, `edit.newDocumentFromState` and the other commands that end a drag first), and applying that preview gives a warning, the command's result carries it as `previewWarning`, and as `warning` too when the command gives no warning of its own; the app's status bar shows `warning`. While the Type tool edits type, `undo` and `redo` put its caret, with no characters selected, at the end of the text the step changed: after the text it puts back or retypes, or where the text it takes out was. A step that changes no characters, such as a formatting change, leaves the caret and the selection where they are. | +| `text_wrap` | `{ids?, offset?, invert?, release?}` | Area type below the objects (same layer) flows around them. `offset` is in points, from -1000 to 1000 (default 6). An offset outside that range or not a number, or an `invert` or `release` that is not true or false, is an error and changes nothing; `object.textWrap.make` and `object.textWrap.options` refuse the same values. | +| `undo` / `redo` | `{}` | Many calls that change nothing record no undo step, for example `object.align` with nothing to move, `object.move` by 0 without `copy` and `object.showAll` with nothing hidden. `undo` (`edit.undo`) after such a call undoes the step before it. `inspect_document` lists the undo steps as `history`. `run_command` with `edit.clearHistory` removes every undo and redo step of the active document and returns `{cleared}`, the number of steps removed; the document stays as it is, and the command records no undo step. `run_command` with `edit.newDocumentFromState` and `{index?, created?}` makes a new document holding the art as it was at that state and makes it the active document, and returns `{index, title}`. `index` is a row of the History panel, with 0 the oldest state kept, and an omitted or null `index` uses the current state. An `index` that names no state fails with `no history state N`, one that is not a whole number with `` `index` must be a whole number ``, and either changes nothing. `created` is File Info's created date in Unix seconds or null, and defaults to now. The new document takes the next `Untitled-N` name, is marked unsaved, has nothing selected and has no steps to undo or redo. It is out of symbol, opacity-mask and pattern editing, and the art drawn in a pattern's tile is stored in the pattern, as `object.pattern.done` stores it. The source document and its steps stay as they are, except that typing or a drag in progress is first kept as a step. When a command keeps a drag whose preview Real-time Drawing off had not applied yet (`edit.undo`, `edit.redo`, `edit.clearHistory`, `edit.newDocumentFromState` and the other commands that end a drag first), and applying that preview gives a warning, the command's result carries it as `previewWarning`, and as `warning` too when the command gives no warning of its own; the app's status bar shows `warning`. While the Type tool edits type, `undo` and `redo` put its caret, with no characters selected, at the end of the text the step changed: after the text it puts back or retypes, or where the text it takes out was. A step that changes no characters, such as a formatting change, leaves the caret and the selection where they are. | For example, create editable Japanese area type with the engine's vertical writing mode: @@ -678,7 +684,8 @@ CJK composition. (the selection, or `ids`) and reply `{vertical, ids}`. The writing direction is a setting of the whole thread: the commands set every frame of a selected frame's thread, and `ids` lists them all. Threading frames gives the thread its first frame's direction, frames taken out of a thread keep theirs, and a file whose frames of one thread differ opens -with the first frame's direction in all of them. +with the first frame's direction in all of them. When every frame already has the direction, the command records no +undo step. For SVG/SVGZ, `export`'s top-level `outlineText: true` writes text as paths; DXF takes it too (its type is outlined anyway unless `preserve: editability`). PDF instead uses `options: {"advanced": {"outlineText": true}}`; its default is false (live text). @@ -806,10 +813,18 @@ look was edited keep their look. Read as a source, by `graphicStyle.new`, `graph style link of its own gives the look and the style link of the topmost path directly in it, and a move with `appearance.transfer` clears each of those paths; a series group that has one of them is read itself. +`transparency.set` and `object.setProps` with an opacity, blend mode, isolation, knockout or knockout shape for the +object, given a series group's id or the selected series group, set them on the group itself, and the graph stores them +for that series. The series group has them again when the graph is drawn again, and they apply to the group as a whole +in addition to each path's own opacity and blend mode. `addon.arrange.randomizeOpacity` and `addon.arrange.sort` with +`apply: "opacity"` given a series group, and Global Edit when a series group takes an edit from another match, store +what they change on the group the same way. Each of the commands above that clears the group's own opacity, blend mode, isolation +and knockout also removes what the graph stores for it. + The other commands given a series group's id edit the group itself, and the graph does not store what they set on it: -`transparency.set` and `object.setProps` with an opacity or blend mode for the object, the `effect.*` commands and -`appearance.addEffect`, and the paint, stroke and gradient commands with a fill or stroke `item`, which is a row of the -group's own stack. The Appearance panel and `appearance.setActiveItem` read the selected group's own rows. +the `effect.*` commands and `appearance.addEffect`, and the paint, stroke and gradient commands with a fill or stroke +`item`, which is a row of the group's own stack. The Appearance panel and `appearance.setActiveItem` read the selected +group's own rows. The graph draws the art of a column or marker design in a series again from the design, so the commands that add, change, move or remove fill and stroke rows, effects or graphic styles leave that art out: the `appearance.*` commands @@ -849,7 +864,8 @@ stored without its placement (its vector, aspect ratio, focal point and freeform own box when the graph is drawn again, so `paint.setGradientGeom` and the `paint.freeform.*` edits do not store the placement they set there. A stroke weight and dashes are stored as the label shows them, also on a label that was scaled. When the characters of labels of one kind change differently, the frontmost label sets what the kind keeps. On -a pie with Legends in Wedges whose legend labels have no fill of their own, the legend labels' fill is stored only when +a pie with Legends in Wedges, a fill a command sets on the legend labels is drawn on every wedge, black included, until +that command is undone; a size, font or stroke change does not set one. Before that, their fill is stored only when every legend label the command reaches ends up with the same fill. Otherwise they are drawn again in black, or white on a dark wedge. These commands do not store the colors they give a graph's axis lines, ticks and radar rings, which are drawn again with their default paint. @@ -860,6 +876,17 @@ kind takes them when the graph is drawn again. The graph saves the paragraph att `categoriesPara` and `legendPara` in its label styles, and still sets each label's alignment for its place. The legend leaves room for a legend label's stored indents, spacing and leading. +When a graph is drawn again, its plot moves and scales with any move or scale of the graph made since it was last +drawn. The graph saves the bounds of its art other than type as `placedArt` (and the bounds of all of its art as +`placed`), and measures the move or scale on those. Changing the size or indents of the labels, moving a label on its +own, `type.createOutlines` on labels and `object.path.outlineStroke` on the graph's strokes do not move or scale the +plot. Outlined labels are no longer type: moving one of them on its own, like moving a swatch, an axis or a tick mark on +its own, can move or scale the plot at the next redraw. When all of a graph's art other than type has been deleted, or +the art measured has no width or no height, a redraw leaves the plot where it is and does not follow a move or scale of +the graph. A graph opened from a `.ai` file +saves `placedArt` too. A graph saved without `placedArt`, or with a `placedArt` that has no width or height, is +measured on `placed`. + The `appearance.*` commands, `graphicStyle.apply` and `graphicStyle.redefine`, and the paint, stroke, gradient and transparency commands given an `item` (or the Appearance panel's active row) store a graph label's object rows for its kind of label: the paint, weight, opacity and blend mode of its topmost visible fill and stroke row, their order and @@ -886,13 +913,15 @@ Errors (unknown tool, bad arguments, a disabled or failing command) come back as `isError: true` and a message. The model can read the message and retry. Swatches go through `run_command`: `swatch.list` lists every swatch with its colour group, kind and colour; -`swatch.edit {name, newName?, color?, mode?, global?, spot?}` edits one (fills, strokes and text linked to a +`swatch.edit {name, newName?, color?, mode?, global?, spot?, paint?}` edits one (fills, strokes and text linked to a global or spot swatch follow its colour and name, as one undo step, in the art, opacity masks, symbols, graph -designs, pattern tiles, graphic styles and the art of brushes); `swatch.delete {names, unlink?}` deletes +designs, pattern tiles, graphic styles and the art of brushes). A replacement colour, gradient or pattern given as +`paint` (`{color}`, `{gradient}`, `{swatch}` or `{pattern: name}`) is stored as `swatch.new` stores it; +`swatch.delete {names, unlink?}` deletes swatches and colour groups in one undo step (art using a deleted global swatch keeps its colour, unlinked). `swatch.new {color?, mode?, spot?, global?, group?}` saves a colour (into a colour group with `group`), gradient -or pattern (a gradient swatch holds no link to the swatch its gradient came from, and a pattern swatch holds the -pattern untransformed); `swatch.newGroup {fromArtwork: true, toGlobal?, includeTints?}` makes a colour group of the selected +or pattern (a gradient swatch keeps the gradient's aspect, with or without `start` and `end`, and holds no link to +the swatch its gradient came from, and a pattern swatch holds the pattern untransformed); `swatch.newGroup {fromArtwork: true, toGlobal?, includeTints?}` makes a colour group of the selected art's colours (by default as global swatches the art links to). `swatch.move {names, to?, group?}` reorders swatches or moves them into or out of a colour group (as dragging them in the Swatches panel does); give colour group names instead to reorder the groups. Dropping a swatch on art @@ -1076,7 +1105,16 @@ or `range`), named `<file>-<artboard>.<ext>`, and returns `{path, files}` (a PDF SVG writes one file per artboard of a `range`); `useArtboards: false` exports the bounds of the visible art with what its effects paint, the effects of groups, type and images included. `artboard.fitToArt` measures the art the same way. `document.exportPdf {useArtboards: false}` writes that one page as well, and ignores `artboard`, `artboards` and -`range`. A PDF of that page, from either command, carries no Preserve Editing data; when Preserve Editing is on (as it +`range`. A PDF or `.ai` page of the art's bounds is measured without the non-printing layers that the file leaves out +(unless `includeNonPrinting` or `createLayers` keeps them; a `.ai` file keeps layers by default). An HP-GL plot of the +art's bounds is measured without what the plot leaves out: non-printing layers, objects at 0% opacity, placed images, +gradient meshes whose every point is at 0% opacity, and paths without effects whose fills and strokes paint nothing. +An image or a mesh with a Crop Marks effect, or with a Vector Halftone effect that makes dots, is measured. +Such objects in the art of a symbol are left out of its instances too, and an instance whose symbol holds nothing +else is left out. In the art of a dynamic symbol, an object that an instance's fill, stroke or opacity makes +the plot draw is measured. +A document whose only visible art is left out is refused, and Export As refuses an HP-GL plot of it before the save +dialog. A PDF of that page, from either command, carries no Preserve Editing data; when Preserve Editing is on (as it is in VectorCraft Default), the export comes back with a warning that says so. A `.ai` export with `useArtboards: false` writes that one page too, without the native document and without the editing copy for other apps (`editingData`), and always comes back with the warning `Preserve editing was left out: an .ai file of the art's @@ -1089,8 +1127,9 @@ follows as after Export As: Save PDF without its Artboards section, SVG Options options, EPS Options, DXF Options without Export Selected Art Only, Text Export Options with Selection Only on, or an exporter plug-in's parameters. Other formats are written at once. OK writes the selection alone, cropped to it, as `document.exportSelection` writes it, with the chosen options. While a dialog is open the call returns `null`, and -OK returns what `file.exportAs` returns, which has no `format` or `bounds` (Text Export Options: `{path}`). To -write without a dialog, pass `path` or any option. `file.exportAs {path, exportSelection: true, …options}` writes the selection the same way. +OK returns what `file.exportAs` returns, which has no `format` or `bounds` (Text Export Options: `{path}`). Any +option skips the options dialog, but without `path` the save panel still picks the file. To write without a +dialog, pass `path`. `file.exportAs {path, exportSelection: true, …options}` writes the selection the same way. Raster exports default to the document's raster effects resolution. An explicit `scale` sets pixels per point (72 times that value in ppi); `options.ppi` wins over either scale option. CLI `run --export` and @@ -1239,6 +1278,15 @@ empty `boxes`, and `thumbnail: 1` shows what that page prints. A page whose `Use opens at its size in points, the file's numbers times the `UserUnit` (one above 75,000 counts as 75,000), and `document.pdfInfo` gives its size and boxes in points too. A `.ai` whose editing data has its artboards in the units of such a page opens from that data at the page's size. +`linkPages: true` (File › Open's Import PDF dialog: Import PDF pages as links) opens each page `pages` picks as a +placed document linked to that page of the file, as `file.place` with `link` places one, instead of as editable art. +Each page gets an artboard of its `cropTo` box (`bounding`: its art's bounds), in a row from the left 36 pt apart, and +a layer named after the page (`Page 2`). The document opens in CMYK when most of those pages are painted mostly in +CMYK, unless `colorMode` names a mode. All the pages' objects share one copy of the file. The Links panel lists each +page, and `links.embed` makes a page editable art. +`document.open` refuses `linkPages` for a file that is not a PDF or a PDF-compatible `.ai`, for a file given as +`dataBase64` without a path, with a `password`, and with `textAs: "outlines"`, and rejects a `linkPages` that is not +true or false. Save then asks for a name. `document.open`, `file.place` and `document.pdfInfo` reject a `cropTo`, `crop`, `password`, `colorMode` or `textAs` that is not a string, and `document.pdfInfo` rejects a `thumbnailSize` that is not a number. The error names the param, and nothing opens or is placed. Leaving a param out or giving null keeps its default. @@ -1254,6 +1302,7 @@ CMYK too. ```json {"name":"run_command","arguments":{"command":"document.pdfInfo","params":{"path":"/tmp/brochure.pdf","thumbnail":2,"cropTo":"trim"}}} {"name":"run_command","arguments":{"command":"document.open","params":{"path":"/tmp/brochure.pdf","pages":"2-3","cropTo":"trim"}}} +{"name":"run_command","arguments":{"command":"document.open","params":{"path":"/tmp/brochure.pdf","linkPages":true}}} ``` PostScript files (`.eps`, `.epsf`, `.ps`, and `.ai` files saved in older formats or without PDF compatibility) open through the EPS @@ -1687,6 +1736,16 @@ one opens as before and draws it as `rgb`: → invalid parameters for `effect.setParams`: `channel` must be one of rgb, red, green, blue ``` +Radial Blur's Blur Center, `centerX` and `centerY`, must each be a number from 0 to 1: the share of the object's bounds +across from its left edge and down from its top edge (0.5 each, the object's center, by default). The effect turns or +zooms about that point, which moves and scales with the object. `effect.apply` and `effect.setParams` refuse any other +value themselves in the same way, and a document saved with one draws it at the nearest edge: + +```json +{"id": "effect.setParams", "params": {"index": 0, "params": {"centerX": 1.5}}} +→ invalid parameters for `effect.setParams`: `centerX` must be a number from 0 to 1 +``` + A number outside the range the effect documents is still stored as given and clamped when the effect draws. A plug-in effect's parameters are resolved against its manifest instead. `effect.setParams` as a step of `command.batch` is checked when the step runs, against the effects the steps before it added, and the batch then @@ -2762,11 +2821,11 @@ nearest to the pointer. ## Global Edit Select › Start Global Edit is `select.globalEdit {appearance?, size?, artboards?, includeCanvas?}`. With one path, -compound path or symbol instance selected, it finds the objects of the same shape (moved or scaled copies; not rotated -ones), among those `select.all` would take and the objects in their groups, and returns `{active: true, count, ids}`, +compound path or symbol instance selected, it finds the objects of the same shape (moved, scaled or rotated copies; +not reflected ones), among those `select.all` would take and the objects in their groups, and returns `{active: true, count, ids}`, the selected object first (at most 10,000). With a group of such objects selected (nested groups and clipping paths included; not type or images), it finds the groups like it: as many objects, in the same order, each of the same -shape, lying the same way relative to each other (the group moved or scaled as a whole). While Global Edit is off, +shape, lying the same way relative to each other (the group moved, scaled or rotated as a whole). While Global Edit is off, the command is disabled for any other selection, including a group that holds type, an image or nothing (it is off in the Select menu, the Properties panel's Quick Actions do not show it, and the Control bar does not show its Global Edit Options). `appearance` also asks for @@ -2775,7 +2834,9 @@ the same fill and stroke (for groups, of each object in them), `size` for the sa params come from `select.globalEditOptions` (the Global Edit Options, kept for the session; it returns them with `count`, the objects a start would take now). The selection stays the one object. Until the next `select.globalEdit` (Stop Global Edit, `{active: false}`), what an edit of a selected match changed is given to the other matches, in the -same undo step, and nothing else. A changed outline or anchors go to each match in proportion to its size. A changed +same undo step, and nothing else. A changed outline or anchors go to each match in proportion to its size, and to a +rotated copy turned by its angle: an anchor moved to the right on the selected object moves upward on a copy rotated +a quarter turn counter-clockwise. A changed opacity or blending, and each changed setting of a fill or stroke (paint, weight, opacity, blending, effects…), are copied as they are to the match's fill or stroke of the same kind and rank; its other fills and strokes, and their unchanged settings, stay its own (a stroke weight change leaves the fills). A stroke weight set on the selected match @@ -2791,6 +2852,16 @@ nothing. Nothing of it is saved. Before Global Edit starts, while one object tha selected with the Selection tool, the canvas highlights the other objects a start would take with the current Global Edit Options (none while a drag is in progress, or when there are none). +Rotated copies are edited together as in [Design a modern geometric +logo](https://helpx.adobe.com/vn_vi/illustrator/how-to/modern-logo-design.html), where copies of a group rotated +around a point are edited at once from one of their objects. These rules for them are VectorCraft's own. A copy's +angle is the one that lays each anchor and handle of the selected object on the copy's anchor and handle of the same +order, so a square whose anchors were turned a quarter turn is a copy rotated a quarter turn. The copy is the same +shape when, laid so, every anchor and handle lies within a millionth of the larger side of the copy's box of its own. A +reflected copy is another shape, and so is a copy stretched along one direction. With `size`, a rotated copy has the +same size when it is the selected object rotated without scaling: a 30 × 70 pt object and its copy rotated a quarter +turn (70 × 30 pt by its box) have the same size. + `select.globalEditExclude {id}` leaves the match `id` out of the Global Edit, as a Shift-click on a highlighted match (or on an object inside it) with the Selection tool does: it is no longer highlighted, and later edits leave it as it is. It returns `{active, count, ids}`, the objects left in the Global Edit; with fewer than two left, the Global Edit @@ -2901,35 +2972,62 @@ own layout rules. Window › Learn and the Explore tutorials button beside the search icon at the right end of the app bar show and hide the Learn panel. Its For you tab holds a Get started section with a Quick skill guide card; choosing the card opens -the Skills tab. The Skills tab lists VectorCraft's own skills, each with its number of tutorials and an empty progress -ring. Choosing a skill lists its tutorials, choosing a tutorial shows its numbered steps, and Back goes up one level. +the Skills tab. The Skills tab lists VectorCraft's own skills, each with a progress ring and the count of its tutorials +finished of all its tutorials. Choosing a skill lists its tutorials, choosing a tutorial shows its numbered steps, and +Back goes up one level. The tutorial text is English. `window.learn {show?}` shows the panel (`show: true`), hides it (`show: false`) or toggles it (`show` omitted or null), and answers whether it shows; Window › Learn and Explore tutorials run it. The panel counts as hidden while the dock is hidden or a full screen mode hides the panels. Showing it shows a hidden dock; in a full screen mode it makes Learn the front panel, which shows when the mode ends, and answers false. Any -other value of `show` is an error and changes nothing. `learn.list {}` → `{skills: [{id, title, tutorials: [{id, title, steps}]}]}`, in the order the Skills tab -lists them, where `steps` is the number of steps. `learn.skills {}` shows the panel on its Skills tab with the list of +other value of `show` is an error and changes nothing. `learn.list {}` → +`{skills: [{id, title, done, total, tutorials: [{id, title, steps, finished, completedSteps}]}]}`, in the order the +Skills tab lists them, where `done` is the number of the skill's tutorials finished, `total` the number of its +tutorials, `steps` the number of a tutorial's steps, `finished` whether it is finished, and `completedSteps` the +zero-based indexes of its steps marked done (every step of a finished tutorial). `learn.skills {}` shows the panel on its Skills tab with the list of skills, with no skill and no tutorial open, as the Quick skill guide card and Back to skills do, and answers what `learn.list` answers. `learn.show {tutorial}` shows the panel on its Skills tab with that -tutorial's steps → `{skill, tutorial, title, steps: [text]}`. A missing, non-string or unknown `tutorial` is an error -and changes nothing. +tutorial's steps → `{skill, tutorial, title, steps: [text]}`; choosing a tutorial's row runs it. A missing, non-string +or unknown `tutorial` is an error and changes nothing. A click on the For you or Skills tab button runs +`learn.tab {tab}` when the panel shows the other tab, and runs no command when the panel already shows that tab. +`learn.tab {tab}`, with `tab` set to `forYou` or `skills`, shows the panel on that tab → `{tab, skill, tutorial}`, +with null for no skill or no tutorial open; the Skills tab keeps the skill and tutorial it had open. Choosing a skill's row runs +`learn.skill {skill}`, which shows the panel on the Skills tab with that skill's tutorials → the skill as `learn.list` +lists it. A missing, non-string or unknown `tab` or `skill` is an error and changes nothing. Back runs `learn.back {}`, +which shows the panel and goes up one level on the Skills tab, from a tutorial's steps to its skill's tutorials and +from a skill's tutorials to the list of skills, and answers what `learn.tab` answers; on the list of skills or the For +you tab the view stays as it is. Under a tutorial's steps, View more opens the tutorial's practice sample, a small drawing of VectorCraft's own with the art its steps work on, as a new untitled document that becomes the active one; Save asks where to save it. Once the sample is open, Finish tutorial marks the tutorial finished. A finished tutorial shows Next Up with the title of the next tutorial in the same skill, which Next Up shows without opening its sample. A skill's last tutorial, finished, -says so and shows Back to skills instead; Next Up never moves to another skill. Which tutorials are finished is kept -while the app runs, and the skill rings and counts do not show it yet. These are VectorCraft's own rules; the help -page also plays a short video, which VectorCraft does not have. `learn.openSample {tutorial}` runs View more → +says so and shows Back to skills instead; Next Up never moves to another skill. These are VectorCraft's own rules; the +help page also plays a short video, which VectorCraft does not have. `learn.openSample {tutorial}` runs View more → `{tutorial, index, title}` of the new document, and moves the Learn view to that tutorial; each call opens another copy and leaves the open documents as they are. `learn.finish {tutorial}` runs Finish tutorial → `{tutorial, finished: true, next}`, where `next` is the next tutorial's id in the skill, or null after the skill's -last one; the tutorial's sample must have been opened, and finishing it again keeps one entry. `learn.next {tutorial}` +last one; the tutorial's sample must have been opened, and finishing it again keeps one entry, also after a restart +without opening the sample again. `learn.next {tutorial}` runs Next Up on a finished tutorial and shows the panel on the next one → `{skill, tutorial, title}`; on a tutorial not finished, or a skill's last tutorial, it is an error. For all three, a missing, non-string or unknown `tutorial` is an error, and an error changes nothing. Behavior reference: [Quick skill guide](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/learn-skills-quick-skill-guide.html). +Each step has a check box before its number that shows whether it is done, and a skill's ring fills as its tutorials +are finished, as the help page describes; a finished tutorial has a check mark in its skill's list. A step is marked +done by its check box, which can be changed once the tutorial's sample is open and until the tutorial is finished; +marking every step does not finish the tutorial. Finish tutorial marks all its steps done, and a finished tutorial's +steps stay marked. Reset progress under the list of skills, shown while there is progress, clears every tutorial +finished and every step marked. The desktop app keeps the progress in its preferences, so it lasts to the next start; +when two windows change it, the one that saves last keeps its progress. The web build keeps it while the page is open. +Marking steps by hand, keeping the progress and Reset progress are VectorCraft's own rules. +`learn.markStep {tutorial, step, complete?}` runs a step's check box → `{tutorial, step, complete}`: `step` is the +zero-based step number, and `complete` marks the step done (`true`, omitted or null) or not done (`false`). A missing, +non-string or unknown `tutorial`, a missing `step` or one the tutorial does not have, a `complete` that is not true or +false, a tutorial whose sample was not opened, and a finished tutorial are errors, and an error changes nothing. +`learn.resetProgress {}` runs Reset progress and answers what `learn.list` answers; open documents, opened samples and +the Learn view stay as they are. + The Home screen has a Learn section between Recent Files and the new-file presets, as [the help page](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/homescreen-overview.html) lists Learn, with in-app tutorials, among the Home screen's options. The section holds the Quick skill guide card, @@ -2941,9 +3039,14 @@ rules. ```json {"name":"invoke_menu","arguments":{"command":"learn.show","params":{"tutorial":"pen-paths"}}} {"name":"invoke_menu","arguments":{"command":"learn.openSample","params":{"tutorial":"pen-paths"}}} +{"name":"invoke_menu","arguments":{"command":"learn.markStep","params":{"tutorial":"pen-paths","step":0}}} {"name":"invoke_menu","arguments":{"command":"learn.finish","params":{"tutorial":"pen-paths"}}} {"name":"invoke_menu","arguments":{"command":"learn.next","params":{"tutorial":"pen-paths"}}} {"name":"invoke_menu","arguments":{"command":"learn.skills","params":{}}} +{"name":"invoke_menu","arguments":{"command":"learn.skill","params":{"skill":"draw"}}} +{"name":"invoke_menu","arguments":{"command":"learn.back","params":{}}} +{"name":"invoke_menu","arguments":{"command":"learn.tab","params":{"tab":"forYou"}}} +{"name":"invoke_menu","arguments":{"command":"learn.resetProgress","params":{}}} ``` A step that names a tool shows the tool's name as a blue link. A click on it, or Enter or Space while it has the @@ -3143,7 +3246,12 @@ already walks Image Trace. Short agent entry points: is unused, and offers Remove Strokes or Cancel when one of them is in use. - Brushes: `brush.list`, `brush.get {name}`, `brush.apply {name, ids?}`, `brush.new {type, name?, params?, ids?}`, `brush.setCurrent {name}`, `brush.options {name, params?, newName?}`, `brush.delete {name} | {names}`, - `brush.duplicate {name, newName?} | {names}`, `brush.freehand`, `object.expandBrush {ids?}`. A document or brush + `brush.duplicate {name, newName?} | {names}`, `brush.freehand {…path.freehand params, brush?}`, + `object.expandBrush {ids?}`. `brush.freehand` draws the plain path when `brush` is left out or null. It refuses a + `brush` that is not a string with "`brush` must be a string", a name that no brush in the document has (an empty + name included) with "no brush named `<name>`", and a `style` other than "pencil" or "brush"; the document does not + change and no undo step is recorded. The Paintbrush skips a tool brush or current brush that has been deleted and + paints with the other, or draws the plain path when neither is in the document. A document or brush library file whose brushes repeat a name is read with the first brush of that name as stored and each later one numbered with the first "`<name>` 2", "`<name>` 3"… the file does not have; strokes of the name keep the first brush. `brush.new`, @@ -3189,8 +3297,12 @@ already walks Image Trace. Short agent entry points: is rejected with an error. The Pencil and the Paintbrush give Fidelity in screen pixels, 0.01 to 100 px, and send it divided by the zoom (0.0313 to 640) and kept within that range, so a stroke is fitted at the same tolerance on screen at every zoom. A stroke - that continues a path (`extend`) closes it when it ends within four times the Fidelity of the path's other end, at - least 6 pt and at most 400 pt. The Blob Brush's `path.blob` Fidelity stays in points, 0.01 to 100 pt. + that continues a path (`extend`) closes it when `closed` is true: the Pencil and the Paintbrush send it when the + stroke ends within Close Paths When Ends Are Within of the path's other end (the cursor shows the closing ring there), + a straight Pencil line too, or with Alt held at the release. The stroke's end then joins the other end when it is + within four times the Fidelity of it (at least 6 pt and at most 400 pt), and a straight segment closes the path from + farther away. Without `closed`, the stroke closes the path when it ends within that four-times-Fidelity distance. The + Blob Brush's `path.blob` Fidelity stays in points, 0.01 to 100 pt. - Variables: `variable.list`, `variable.define {name, kind: text|visibility|image|graph}`, `variable.bind {variable, ids?}`, `variable.makeTextDynamic`, `variable.makeVisibilityDynamic`, `variable.makeImageDynamic`, `variable.makeGraphDynamic` (`variable.bind` and `variable.makeTextDynamic` refuse type that already has another text variable and name it), @@ -3234,39 +3346,56 @@ already walks Image Trace. Short agent entry points: byte order that reads a line break (`\n` or `\r`). It is refused when fewer of its units hold a NUL byte (UTF-8 or Windows-1252 text with stray NUL bytes, or UTF-16 text made mostly of other characters, which needs a byte-order mark), when both byte orders read a line break (the text holds U+0A00 or U+0D00), when it has an odd length, and - when it isn't valid UTF-16 in that order or holds a NUL character. A file with no line break has no data rows and is - refused for that. `csv` and `data` are read as the text they hold. + when it isn't valid UTF-16 in that order or holds a NUL character. A file with no line break is read big-endian when + more of its two-byte units start with a NUL byte than end with one, and little-endian otherwise; it has no data rows, + so the import is refused. `csv` and `data` are read as the text they hold. - Variable libraries: `variable.loadLibrary {path|xml|dataBase64}` (the Variables panel menu's Load Variable Library…) replaces the document's variables and data sets with a variable library's in one undo step. A load, like a `dataset.import`, adds no undo step when it leaves the variables and data sets as they were. The library is XML whose `variableSets` element holds `variableSet` elements, each with a `variables` element of `variable` elements (`varName`, `trait`) and a `sampleDataSets` element of `sampleDataSet` elements (`dataSetName`). Every - data set is deleted, and every variable of the document is deleted with its bindings and values, except a text - variable the library also declares: it keeps its bindings, so selecting one of the library's data sets changes the - objects bound to it. Then the library's other variables whose `trait` is `textcontent` are defined as text - variables, unbound. In each data set, the element named - after a text variable gives its value: the text of its `p` elements, one paragraph each. An element without a `p` - element gives no value. Variables of other kinds are left out with their values: the reply lists them in `skipped` - (`name`, `trait`), and its `warning` names each `trait` with its count. The reply's `deleted` and `deletedDataSets` + data set is deleted, and every variable of the document is deleted with its bindings and values, except a variable + the library also declares with the same kind: it keeps its bindings, so selecting one of the library's data sets + changes the objects bound to it. Then the library's other variables are defined, unbound, with the kind their + `trait` gives: `textcontent` is text, `visibility` is visibility, `fileref` (a linked file) is image and + `graphdata` is graph. A variable without a `trait`, or with one VectorCraft doesn't know, is defined of unknown + kind and takes no values. In each data set, the element named after a variable gives its value: + - text: the text of its `p` elements, one paragraph each; an element without a `p` element gives no value; + - visibility: `true` or `false`, in any case; + - image: a file's absolute path (from `/`, `\\` or a drive's root) or a `file:` URL of one, whose `%XX` escapes + are decoded; the file isn't read, so a library can name files that aren't there; + - graph: a `data` element. Its optional `propertyRow` holds a corner cell and then the series names, and each `row` + of its `values` holds the row's category in a first `value` whose `key` is `name`, then a `value` per series. A + value that is empty, marked `type="string"` or not a number is a blank. The data is read as the CSV + `graph.setData` takes, at most 256 KiB of it. Graph data with more than 10,000 rows or 256 series, which a + graph doesn't hold, is refused, by `variable.saveLibrary` too. `variable.saveLibrary` also refuses graph data + with neither rows nor series, which loads back as no value. + + Visibility, image and graph values are read without the white space round them, and an element holding only white + space gives no value. The reply's `variables` lists the library's variables, and `deleted` and `deletedDataSets` list the variables and data sets the load deleted. While the variables are locked, a library that would delete or - define a variable fails with "variables are locked". The reply is `{variables, deleted, deletedDataSets, names, - skipped, warning?}`. A library larger than 8 MiB, one whose elements nest more than 256 deep, and one with more + define a variable fails with "variables are locked". The reply is `{variables, deleted, deletedDataSets, names}`. A + library larger than 8 MiB, one whose elements nest more than 256 deep, and one with more than 256 variables or 1,000 data sets are refused. Its document type declaration may hold an external identifier, comments, processing instructions and up to 64 entity declarations whose values are plain text (no `<`, `&` or `%`). A declaration that holds anything else, and entity references that expand the library past 8 MiB, are - refused. So are a variable or data set declared twice and a value for a variable the library doesn't declare. - `variable.saveLibrary {path?}` (the panel menu's Save Variable Library…) writes the document's text variables and - every data set as a variable library in the layout `variable.loadLibrary` reads: a `variable` element with - `varName` and `trait="textcontent"` for each text variable, and a `sampleDataSet` element with `dataSetName` for - each data set, holding an element named after each text variable it has a value for, with one `p` element per line - of the value. Loading the file gives back the same text variables, data set names and text values. Variables of - other kinds are left out with their values: the reply lists them in `skipped` (`name`, `kind`), and its `warning` - names each kind with its count. Saving is refused for a document without a text variable, for a text variable whose - name isn't an XML name (it starts with a letter or `_` and holds only letters, digits, `-`, `_` and `.`), for a - data set whose name or text value holds a control character, for a data set name with white space at either end, - for a name longer than 255 characters or used twice, and past `variable.loadLibrary`'s caps (256 variables, 1,000 - data sets, 8 MiB). Without `path` the reply is `{xml, variables, datasets, skipped, warning?}`; - with it, the file is written and the reply is `{path, variables, datasets, skipped, warning?}`. + refused. So are a variable or data set declared twice, a value for a variable the library doesn't declare, and a + value that doesn't fit its variable's kind. + `variable.saveLibrary {path?}` (the panel menu's Save Variable Library…) writes the document's variables and every + data set as a variable library in the layout `variable.loadLibrary` reads: a `variable` element with `varName` for + each variable, with the `trait` and `category` of its kind (`textcontent` and `&ns_flows;`, `visibility` and + `&ns_vars;`, `fileref` and `&ns_vars;`, `graphdata` and `&ns_graphs;`; neither for a variable of unknown kind), and + a `sampleDataSet` element with `dataSetName` for each data set, holding an element named after each variable it has + a value for. A text value is written with one `p` element per line, a visibility value as `true` or `false`, an + image value as its path (a path from the root of a Unix file system as a `file:///` URL), and a graph value as a + `data` element, with a blank category marked `type="string"`. Loading the file gives back the same variables with their kinds, data set names and values; graph + data comes back in the CSV form Graph Data writes. Saving is refused for a document without a variable, for a + variable whose name isn't an XML name (it starts with a letter or `_` and holds only letters, digits, `-`, `_` and + `.`; a variable of unknown kind has no values, so its name isn't checked), for a name or value that holds a control + character, for a name with white space at either end, for a name longer than 255 characters or used twice, for an + image value that isn't a file's absolute path, and past `variable.loadLibrary`'s caps (256 variables, 1,000 data + sets, 8 MiB). Without `path` the reply is `{xml, variables, datasets}`; with it, the file is written and the reply + is `{path, variables, datasets}`. - Batch: `action.batch {commands, source?: folder|datasets, folder?, destination?: none|saveAndClose|folder, destinationFolder?, overrideOpen?, overrideSave?, overrideExport?, includeSubdirs?, stopOnError?}` plays an action on every file in a folder or every data set (the Actions panel menu's Batch…). Override Save and Override @@ -3568,7 +3697,7 @@ already walks Image Trace. Short agent entry points: is changed, renamed or deleted. In the app, `ui.imageTracePresetDialog {params?, rename?}` opens the Image Trace panel's Save as New Preset… or Rename… dialog. - Live Paint: `livePaint.make`, `livePaint.merge`, `livePaint.fill {group?, point}`, `livePaint.strokeEdge`, - `livePaint.info {group}`, `livePaint.release`, `livePaint.expand`, and `livePaint.gapOptions {ids?, detect?, size?, + `livePaint.info {group?|id?}`, `livePaint.release`, `livePaint.expand`, and `livePaint.gapOptions {ids?, detect?, size?, color?, closeGaps?}` (Object › Live Paint › Gap Options). Make gives each covered face the fill of its front-most covering source, including compound paths with shared curved boundaries. Expand keeps those face fills. `livePaint.expand` keeps each face and edge that draws, with all its fill and stroke rows: it is shown, its opacity @@ -3577,6 +3706,13 @@ already walks Image Trace. Short agent entry points: row is hidden is removed. `livePaint.merge` copies the fill and stroke rows, visibility, opacity and blending mode of each face that draws by this rule, and of each edge, to the rebuilt parts, with their gradients kept at their fit on the old outline and without the strokes' pen pressure, tilt, bearing and rotation. + `livePaint.info` lists each face's top fill as `fill` and each edge's top stroke and its weight as `stroke` and + `width`, and lists every fill and stroke row of each face and edge in `appearance`, bottom first, as + `{index, kind, paint, opacity, visible, width?, drawn}`: `index` counts fills and strokes together, `opacity` runs + from 0 to 1, and `width` (strokes only) is the weight in points. `drawn` is true when the row draws by the rule + above: the part is shown with an opacity above 0, and the row is shown, has paint and has an opacity above 0 (a + stroke also a weight above 0). An unpainted top row can sit over a lower row that draws, so `fill`, `stroke` and + `width` alone may not describe what the part draws. With `detect: true`, paint stops at the gaps that run from a loose end of a path to the nearest path, up to `size` wide (`small` 3 pt, `medium` 6 pt, `large` 12 pt, or a number of points up to 72); `closeGaps: true` adds an unpainted path across each of them. `color` (the Gap Preview @@ -3611,6 +3747,16 @@ already walks Image Trace. Short agent entry points: 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. + A double-click (`pointer_gesture` kind `doubleclick`, after the two clicks' `down` and `up`) on the face a click there + picks runs `select.set {ids}` with that face and the faces of its group that a flood from it reaches across edges + that are hidden or draw no stroke (an edge that is fully transparent, or whose strokes are each hidden, without + paint, 0 pt wide or fully transparent); a stroked edge and a Gap Detection gap stop the flood, and hidden faces are + left out. On the edge a click + there picks, it runs `select.set {ids}` with that edge and the edges of its group, not hidden, joined to it end to + end through edges that draw with the stroke paint it draws with (the paint of an edge's topmost stroke that is + shown, with paint, above 0 pt and not fully transparent; none for an edge that draws no stroke). With Shift held it runs `select.toggle {ids}` with the same faces or edges, + and where a click selects no face or edge it runs nothing. The same options, locks and isolation rules apply as for + a click. The Live Paint Bucket's options (`tool.setOption {tool: "livePaintBucket", values}`; double-clicking the tool opens them, dialog `livePaintBucketOptions`) are `paintFills` (on), `paintStrokes` (off), `cursorSwatchPreview` (on), `highlight` (on), `color` (the @@ -3626,6 +3772,31 @@ already walks Image Trace. Short agent entry points: `livePaint.strokeEdge` when an edge is within 4 screen pixels of the pointer and `livePaint.fill` otherwise, and Shift-click runs `livePaint.fill`. With both off, a click runs nothing. With `highlight` off, the face or edge under the pointer is not outlined. + A double-click runs the command a click there runs with `scope: "connected"`, and a triple-click with + `scope: "samePaint"`; Alt held runs nothing, and so does Cmd/Ctrl (`mods.cmd`), whose presses go to the selection + tool Cmd lends. With Space held (`mods.space`, the view tools), a press, a + double-click or a triple-click runs nothing, and a move outlines no face or edge. On a face, `connected` fills the face and every face reached from it + across edges that draw no stroke (an edge that is hidden or fully transparent, or whose strokes are each hidden, + without paint, 0 pt wide or fully transparent); a stroked edge, a hidden face, a gap + that Gap Detection closes and the group's outside stop it. `samePaint` fills every face + of the group, joined to it or not, whose fill is the `match` paint. On an edge, `connected` paints the edge and the + edges joined to it end to end that draw with the stroke paint `match`, and `samePaint` paints every edge of the + group that draws with that stroke paint; the stroke's weight is not compared. An edge draws with the paint of its + topmost stroke that is shown, with paint, above 0 pt and not fully transparent, and with none when the edge is fully + transparent or has no such stroke. Each click of a double-click or triple-click runs as it + arrives and is its own undo step. `match` is the paint the face or edge had before the first of the double-click's + two clicks or the triple-click's three that painted it, or before the double-click when the triple-click's double-click + reached it, so the clicks before the last do not change what it matches; + a first click that made the Live Paint group counts when the face it filled is the clicked face. Hidden faces and edges are not painted. An edge takes the + paint and weight in its topmost stroke that is shown, or in a new stroke above the others when it has none. These rules + for what faces and edges join and what paints match are VectorCraft's own. The help page describes the gestures: + https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html. + `livePaint.fill {scope}` and `livePaint.strokeEdge {scope}` take `scope` as `"one"` (the default), `"connected"` or + `"samePaint"`; any other value is an error and changes nothing. `match` is a paint in the model JSON that + `document.node {id}` writes for an appearance's paints (`{"type": "none"}` for none), taken only with a scope that compares paints, and + defaults to the face's fill or the stroke paint the edge draws with. `livePaint.fill` refuses a `scope` other than `"one"` with + `points`. Both replies add `count`, the number of faces or edges the click reaches, including those that already had the + paint. With the Live Paint Bucket selected and no drag in progress, Left and Right without Shift, Alt or Cmd/Ctrl (which keep their shortcuts) run `paint.setFill {swatch, ids: []}` (or `paint.setStroke` when the Stroke proxy is in front) with the color swatch before or after the active paint in the @@ -3642,7 +3813,8 @@ already walks Image Trace. Short agent entry points: objects; otherwise it returns an error and does not merge the objects. A Live Paint command that changes nothing records no undo step, keeps the redo steps, leaves a saved document saved and replies as usual: `livePaint.fill` (a click, or a Bucket drag) when every face it reaches already has the paint, - `livePaint.strokeEdge` when the edge already has the paint and the width, `livePaint.gapOptions` (and the Gap Options + `livePaint.strokeEdge` when the topmost shown stroke of each edge it reaches already has the paint and the width, + `livePaint.gapOptions` (and the Gap Options dialog's OK) when every group already has the options and `closeGaps` finds no gap, and `livePaint.make` or `livePaint.merge` given one Live Paint group alone, which they select. Such a fill or stroke also leaves the recent colors and the last color as they are. `livePaint.gapOptions` makes a group's faces again, with new ids, only when it adds a path or when Gap Detection is turned on or off or given a new size while it is on. @@ -4362,7 +4534,11 @@ with); without `path` it returns `{data}`, and `user: true` saves into the user (category `user`, User Defined). `graphicStyle.loadLibrary {path? | data? | dataBase64?, name?}` loads a `.vcstyles` file, or another document's graphic styles, as a library to add from (a `.ai` or EPS whose editing data holds graphic styles and no layers gives the styles of its style list, in that order); a file in the user library folder, or a file -with the same extension and bytes as one there, loads as that User Defined library. +with the same extension and bytes as one there, loads as that User Defined library. A `.ai` or EPS style that paints a +fill or stroke with one of the file's gradients by name loads with that gradient at the style's angle. The style stores +only the gradient's name and angle, so the gradient is fitted to the bounds of each object the style is applied to; this +placement is VectorCraft's own rule. A style that names a gradient the file doesn't define, or paints with a pattern, is +left out. ## Symbol libraries @@ -5015,8 +5191,12 @@ when its symbol or a symbol nested in its art holds an instance of itself, and w nest 32 deep in its art. PDF and EPS export and the SVG of an artboard leave out art outside the page or artboard, and Skip Blank Artboards skips an artboard with no art on it. For both, the box of an instance whose art holds brushed strokes grows by 16 times the widest stroke (at least 1 pt) of the objects in its art that have a brushed stroke, -plus 8 pt. The SVG of an artboard also keeps an object whose effects paint onto the artboard, and an object that holds -an instance when the effects in the symbol's art, or the instance's own, paint onto it. +plus 8 pt. PDF and EPS export and Skip Blank Artboards grow the box of an object with a visible, painted brushed stroke the +same way, by its own widest stroke, and the box of an object that holds one by the largest such room among them (of a +clip group, only its clipping path counts). Print with Ignore Artboards frames the page around the art with the same +room for brushed objects and for instances whose art holds brushed strokes. The SVG of an artboard also keeps an +object whose effects paint onto the artboard, and an object that holds an instance when the effects in the symbol's +art, or the instance's own, paint onto it. ## Expand @@ -5096,7 +5276,8 @@ The Attributes panel (`window.panel {panel: "attributes"}`, Cmd+F11) reads `attr objects differ) and `recentUrls`. `attributes.set {overprintFill?, overprintStroke?, showCenter?, imageMap?, url?, note?, ids?}` sets them in one undo step; `path.setFillRule {rule: "nonZero"|"evenOdd"}` sets the fill rule of the paths and compound paths, and `path.reverse {reversed?}` makes subpaths run counter-clockwise (true) or clockwise -(false). SVG export wraps an object with a URL in `<a xlink:href>`, and SVG import reads `<a href>` links back. +(false). When every subpath of a path or compound path turns alike, its strokes' width profiles (left and right swapped) and pen +pressure, tilt, bearing and rotation turn with it, so the strokes draw as before. SVG export wraps an object with a URL in `<a xlink:href>`, and SVG import reads `<a href>` links back. ```json {"name":"run_command","arguments":{"command":"attributes.set","params":{"ids":[12],"url":"https://example.com","imageMap":"rectangle"}}} @@ -5133,8 +5314,19 @@ it. The native format keeps the events and the files. ## SVG filters -Effect › SVG Filters lists the document's SVG filters below Apply SVG Filter… and Import SVG Filter…; choosing one -applies it to the selection. `svgFilter.list {}` returns them as `filters: [{name, xml}]`. Each is one `<filter>` +Effect › SVG Filters lists the default SVG filters and then the document's other filters below Apply SVG Filter… and +Import SVG Filter…; choosing one applies it to the selection +([apply SVG filter effects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/apply-svg-filter-effects.html)). +The 14 defaults are VectorCraft's own set, written with [SVG 1.1 filter primitives](https://www.w3.org/TR/SVG11/filters.html): +Soft Blur, Heavy Blur, Soft Shadow, Hard Shadow, Glow, Bevel, Emboss, Thicken, Thin, Rough Edges, Grain, Grayscale, +Invert and Hue Shift. Every document lists them, and a document holds none of them until one is applied or edited +there. `svgFilter.apply` with a default's name copies the default into the document in the same undo step (refused +when the document already holds 64 filters), and `svgFilter.define` with `replace` naming a default adds the edited +copy under that name (code equal to the default's adds nothing). The document's filter of a default's name is then +listed in the default's place. `svgFilter.delete` refuses a default the document holds no copy of; deleting the copy +lists the default again, and applying the default again makes the effects that still name it draw with it. +`svgFilter.list {}` returns the document's filters as `filters: [{name, xml}]` and the defaults as +`defaults: [{name, xml, inDocument}]`. Each filter is one `<filter>` element whose `id` is its name, with 1 to 64 primitives and at most 64 KB of XML (`feTurbulence` octaves up to 10, `feConvolveMatrix` kernels up to 9 cells a side, `feMorphology` radii and `kernelUnitLength` up to 100 and `stdDeviation` up to 500 user units, elements nested at most 16 deep). It holds only filter primitives, @@ -5145,8 +5337,9 @@ a filter after the others, or with `replace` replaces the filter of that name, w filter has is refused, and the same filter again records no undo step. `svgFilter.delete {name}` removes one, and `svgFilter.import {path?|svg?}` adds the `<filter>` elements of an SVG file (at most 16 MB, not SVGZ, the first 256 filters) or of SVG text, leaving out the names the document already has and the filters `svgFilter.define` would refuse (`{added, skipped}`). Each change is one undo -step. `svgFilter.apply {name, ids?|id?, item?}` applies one as the live effect `svg.filter`, as `effect.apply` does, -in one undo step. The effect (`{name, xml, scale, origin}`) names the document's filter: editing the filter changes +step. `svgFilter.apply {name, ids?|id?, item?, index?}` applies one as the live effect `svg.filter`, as `effect.apply` does, +in one undo step; with `index` it puts the filter in the place of the applied `svg.filter` effect at that index of +`item`, as `effect.setParams` does, and an index that is not an applied SVG filter is an error. The effect (`{name, xml, scale, origin}`) names the document's filter: editing the filter changes what every object that uses it draws, in the edit's one undo step, and an application after an edit takes the edited filter. Deleting a filter that objects use leaves their effects in place, still named, drawing nothing (their `xml` empty) until a filter of that name is defined or imported again. A pasted effect that names one of the document's @@ -5391,6 +5584,13 @@ keeps the segment's direction when the smoothed path there turns back by 90° or path, the curve keeps the direction of the part outside the drag. `object.path.smooth` and Simplify keep each end's direction. +`path.smoothRegion` keeps an anchor as a corner where the path turns by more than 57.5° (an angle inside the corner +under 122.5°) at the anchor and also over `radius` and over twice `radius` on either side of it (on a closed path that the drag reaches all the +way round, no more than an eighth of its length), so a jag or a bump smaller than `radius` is still smoothed. The stretches on either side of a kept corner are smoothed and refitted on their +own, and the corner keeps its place and the directions the path arrives and leaves along, on every call and at any +`fidelity`. A call that changes no anchor returns `{ids: [], before: 0, after: 0}` and adds no undo step. The 57.5° +threshold is VectorCraft's own value. + In the desktop app, Object › Path › Smooth, the canvas context menu's Smooth… (listed while the selection holds a path) and the Contextual Task Bar's Smooth (with a path selected whole with the Direct Selection tool) open the slider (`ui.menuDialog {command: "object.path.smooth"}`, dialog `smoothSlider` with field `level`) at the @@ -5454,7 +5654,9 @@ too and printer's marks are not. The destination is any profile `edit.colorSetti for its colour mode). `profiles` (`all`, `destination`, or `taggedSource` for a document assigned profiles with `edit.assignProfile`) writes colours in ICC-based spaces with their profiles embedded: CMYK with the destination's or the document's CMYK profile, RGB as sRGB, grey with the sRGB tone curve (PDF/A, PDF/X-3 and PDF/X-4 files are -always tagged, whatever `profiles` says). `outputIntent` embeds a profile as the file's +always tagged, whatever `profiles` says). A CMYK image that keeps its numbers carries the CMYK profile it embeds +with `all` and `taggedSource`, and in PDF/A, PDF/X-3 and PDF/X-4 unless `profiles` is `destination`; PDF/X-1a +images are always untagged CMYK. `outputIntent` embeds a profile as the file's `/GTS_PDFX` output intent with `outputCondition`, `outputConditionId` and `registry`, and `trapped` sets `/Trapped` (PDF/A files keep their own output intent). Type is written as selectable, searchable text in embedded subset fonts with a ToUnicode map (fonts whose licence forbids embedding stay outlines, with a warning); `advanced: {outlineText: @@ -5715,6 +5917,15 @@ tool's active artboard in place, and the Distribute buttons then send the Distri can then be negative. Align to Selection sends `to: "selection"`. The Distribute buttons need two or more selected artboards with Align to Artboard, and three or more with Align to Selection. +Edit › Keyboard Shortcuts and `shortcuts.list` list an undoable command that is not an alias and has no menu path or +default shortcut, such as a panel menu's Break Link to Symbol (`symbol.breakLink`), when its params doc names no +required field and it is not one of the commands left out below. A field is optional when each of its names ends with +`?`, whatever type follows it (`on?: bool`, `ids?: [id…]`), when its name is followed directly by an `=` default +(`rows=10`), or when it starts with `…`. Such a command is listed in the group named by the first part of its id. +Commands listed this way include `type.fractionalWidths`, `type.systemLayout`, `object.setPixelAligned`, +`links.embed`, `links.update`, `object.slice.delete`, `artboard.switchOrientation`, `artboard.distributeSpacing`, +`appearance.targetContents` and `paint.invert`. + Edit › Keyboard Shortcuts and `shortcuts.list` leave out a command with no default shortcut when a key press cannot run it: no item of the menu bar runs it, it opens no dialog when run without params, and it is one of these: @@ -5724,7 +5935,22 @@ run it: no item of the menu bar runs it, it opens no dialog when run without par - a command that sets nothing or fails without a param: `transparency.set`, `transparency.setOpacityMask`, `stroke.set`, `layer.setProps`, `object.align`, `object.distribute`, `swatch.delete`, `swatch.move`, `swatch.spotOptions`, `edit.colors.adjustBalance`, `swatch.library.load`, `graphicStyle.loadLibrary`, - `symbol.loadLibrary`, `brush.loadLibrary`, `dataset.import` and `variable.loadLibrary`. + `symbol.loadLibrary`, `brush.loadLibrary`, `dataset.import`, `variable.loadLibrary`, `charStyle.load`, + `paraStyle.load`, `textStyle.loadAll` and `svgFilter.import`; +- a command without a menu path that sets nothing, fails or only gives data back without a param: + `addon.pathtools.setAnchor`, `addon.shapes.configure`, `appearance.addEffect`, `artboard.align`, + `artboard.distribute`, `assets.export`, `assets.export3D`, `assets.settings.set`, + `attributes.set`, `brush.move`, `css.export`, `dimension.create`, `document.export`, `document.exportDxf`, + `document.exportEps`, `document.exportForWeb`, `document.exportPdf`, `document.save`, `document.setup`, + `edit.undoGroup.begin`, `edit.undoGroup.end`, `eyedropper.setOptions`, `file.package`, `library.createGroup`, + `links.placementOptions`, `links.unembed`, `livePaint.gapOptions`, `object.blend.createSpine`, + `object.blend.setEasing`, `object.intertwine.arrange`, `object.objectsOnPath.options`, `object.puppetWarp.pins`, + `object.setBounds`, `object.setLiveShape`, `object.setOverprint`, `object.setProps`, `object.slice.select`, + `paint.freeform.setPoint`, `paint.setFill`, `paint.setGradientGeom`, `paint.setStroke`, `perspective.grid.define`, + `perspective.grid.set`, `perspective.plane.move`, `print.setup`, `select.color`, `select.globalEditOptions`, + `stroke.setAdvanced`, `symbol.options`, `text.setFormat`, `text.setRangeStyle`, `text.setStyle` and `type.ruby`; +- `symbol.new`, which the Symbols panel's New Symbol button and its New Symbol… menu item run through the Symbol + Options dialog. They list such a command while the user has changed its shortcut (`overridden: true` in `shortcuts.list`), and `shortcuts.set` can change or clear it. When every menu bar item that runs a command gives it the same params, a @@ -5841,7 +6067,12 @@ files or data sets, 8 folder levels, 256 steps. `action.batch` refuses `includeS `` `stopOnError` must be true or false ``, and `source`, `folder`, `destination`, `destinationFolder`, `datasetFileNaming` or `label` given as anything but a string with `` `label` must be a string ``, naming the key. It checks them, and that `source` is `folder` or `datasets`, before it makes the destination folder or opens a file. -A null is read as a key left out. An action recorded in the Actions panel leaves the artboard out, +A null is read as a key left out. When a step fails on a file or data set, that row's `error` names the step by its +place in the `commands` sent, from 1, counting the Open steps the batch skips: with `commands` of an Open, an Unlock +All and an Align, a failed Align gives `` action step 3 (`object.align`) failed: `` and the reason. The batch's own +opening of a source file, choosing of a data set and destination save, export or close give their errors without a +step number. This numbering is VectorCraft's own rule. A `prefs.import` step is refused before any file is opened, +with `` commands[1]: `prefs.import` runs on its own, not as a batch step `` (counted from 0, as for an unknown command). An action recorded in the Actions panel leaves the artboard out, and its steps of these commands get the artboard that is active when the action plays. A press with the Selection, Direct Selection or Group Selection tool inside an artboard makes that artboard the active one; with the Selection tool, a Shift-click on an empty spot inside an artboard makes it active and keeps the selection. Choosing the Artboard @@ -6048,8 +6279,9 @@ Color on (HDR or Automatic Color Management) and macOS windows are converted by again. In a Wayland session, and where no profile is set or the profile is not an RGB display profile of at most 1 MiB, the canvas stays sRGB. The app reads the display again every 10 seconds and when the window moves to another display. Exports, `ui.render`, the document, panels and thumbnails are not converted; with Proof Colors on, the proof is drawn -first and then converted. The art is converted before it is drawn over the converted paper, so the blend of a -translucent object or an antialiased edge with the paper can differ slightly from a conversion of the blended color. +first and then converted. Translucent art and the antialiased edges of art over an artboard's paper or the +transparency grid are blended with it in sRGB, and the blend is converted; over the pasteboard and in Outline the art +is converted on its own. `ui.inspect` returns `displayProfile`: `{enabled, display, source, profile, from, applied, reason, osManaged}`, where `source` is `profile`, `srgbProfile` (a profile that shows sRGB unchanged), `system`, `none`, `pending` or `unsupported`, `applied` says whether the canvas is converted, and `reason` says why not. @@ -6178,9 +6410,11 @@ snap the pointer as drawing tools do, so dragging a corner onto another object's ``` Every point a drawing tool places snaps the same way, through one snapper (#506): the Pen's and Curvature tool's -anchors, the Pencil's first and last point, the shape tools' start and dragged corner or radius (`rectangle`, +anchors, the shape tools' start and dragged corner or radius (`rectangle`, `roundedRectangle`, `ellipse`, `polygon`, `star`, `lineSegment`, `arc`, `spiral`, `rectangularGrid`, `polarGrid`), the -Type tool's click and frame, and a new artboard's corners. The point lands on another object's anchor, centre or +Type tool's click and frame, and a new artboard's corners. The Pencil ignores Smart Guides and Snap to Point and +shows no Smart Guides: its strokes and straight lines follow the hand (Snap to Grid and Snap to Pixel still move +their ends). The point lands on another object's anchor, centre or path ("anchor", "center", "path"), else lines up with the anchors, edges and centres of the art and the artboards (a line from the target and "align"); the Pen's lands on the path being drawn too, so a click on its first anchor closes it exactly. With `mods.shift` the point keeps to its 45° step from the anchor before it (from `constrainAngle`; a box @@ -6251,6 +6485,10 @@ Pen's second anchor at (150, 431), in line with the square's centre. - `highlightAlternateGlyphs` (off by default): Preferences › Type › Highlight Alternate Glyphs. On, the canvas paints pink behind OpenType substitutions (ligatures, contextual forms). Document Setup's Highlight Substituted Glyphs stays separate. Agents set it with `prefs.set`; the desktop canvas reads it on the next paint. +- `showCharacterAlternates` (on by default): Preferences › Type › Show Character Alternates. On, the desktop canvas + shows the alternate glyphs of the one character selected with a Type tool beside it (see + [Alternate glyphs](#alternate-glyphs)). Off, it shows none. It is VectorCraft's own option. `prefs.set` refuses a + value that is not a boolean. - `highlightSubstitutedFonts` (on by default): Preferences › Type › Highlight Substituted Fonts. On, the canvas paints pink behind text drawn in a substitute for a missing font, in every open document. Off, no document shows that highlight. `document.setup` ignores this key and adds a `warnings` entry that names `prefs.set` to its reply. A file @@ -6675,7 +6913,10 @@ copies in artboard order); `artboard` wins when both are given. Without either, several artboards selected, they paste a copy on each of those, and the journal records them as `artboards`; a recorded action leaves both out. Art copied from no artboard keeps its place on the first artboard named and its offset to that one on the others. An index the document does not have, a repeated index, a value that is not an index -or an empty list fails, and nothing is pasted. Copied artboards come back once, where they were, whichever artboards +or an empty list fails, and nothing is pasted. An `artboard` that is not a whole number, null included, fails with +`` `artboard` must be a whole number ``, and an `artboards` entry that is not one with +`` `artboards` must contain whole numbers ``; both keys are checked when both are given. Copied artboards come back +once, where they were, whichever artboards are named. `layer.pasteRemembersLayers {on?}` (a document option, `document.inspect` → `pasteRemembersLayers`) pastes objects back into the layers and sublayers they came from: in the same document while those are still there, else by the names of the layer and the layers around it (the topmost chain that matches the most names, a shown and @@ -6718,9 +6959,15 @@ also move the pattern tiles of the copies when `patterns` is true (default: pref `artboard.duplicate`, `artboard.copy`, `artboard.cut`, `artboard.move` and `artboard.rearrange` take `lockedAndHidden?` (default: prefs `moveLockedWithArtboard`), and with the Artboard tool chosen `edit.copy` and `edit.cut` pass it on. When art goes along, the journal records the value, so a replay under another preference takes the same art. -Every artboard command that takes an `index` fails with `no such artboard` when the `index` is not the -0-based index of an artboard (past the last one, negative, fractional, a string or null), and the document and the -clipboard stay as they were. +Every artboard command that takes an `index` fails with `no such artboard` when the `index` is a whole number past +the last artboard, with `` `index` must be a whole number `` when it is negative, fractional, a string or another value +that is not a whole number, and with `missing index` when it is null, also in a command that picks an artboard when +`index` is left out. An `indices` (or a replayed `selectedArtboards`) that is not a list fails with +`` `indices` must be a list of artboard indices ``, an empty one with +`` `indices` must be a non-empty list of artboard indices ``, one with an entry that is not a whole number with +`` `indices` must contain whole numbers ``, each naming its key, and one with a whole number past the last artboard +with `no such artboard`. `artboard.align`, `artboard.distribute` and `artboard.distributeSpacing` name `artboard` or +`activeArtboard` the same way. The document and the clipboard stay as they were. These artboard commands refuse a string, a number or another value that is not true or false with `` `art` must be true or false ``, naming the key, and leave the document, its undo history and the clipboard as they were: `moveArt`, `scaleArt`, `strokes`, `corners`, `patterns`, `lockedAndHidden` and an artboard's `locked`, @@ -7091,7 +7338,7 @@ comes back to the front, following the same preference. `links.check` reports ev `missing`), `links.update {ids?}` reads modified files again and `links.relink {ids?, path | folder}` points images at another file (or each at the file of its name in a folder); images keep their bounds, one undo step each. `links.relink`'s `scope` picks which links take the new file (Relink's Replace choice): `selected` (the default) relinks `ids`; `all` also relinks every other stored object linked to the same file as -one of them, in the layers, opacity-mask art, symbols, graph designs and patterns; `missingInFolder` relinks `ids` to `path`, then every other missing link to the file of its name in +one of them, in the layers, opacity-mask art, symbols, graph designs, patterns and the art of the stored brushes; `missingInFolder` relinks `ids` to `path`, then every other missing link to the file of its name in `path`'s folder, and lists the names not there in `notFound` (with `copy`, only missing images are looked for); `each` takes `paths: [{ids, path}]` in place of `ids`, `path` and `folder` and relinks each link to its own file. An unknown scope, `paths` without `each`, `each` with `ids`, `path` or `folder`, an entry without `path` or `ids`, an id in two entries and `missingInFolder` with `folder` are @@ -7099,9 +7346,11 @@ errors, and nothing is relinked. Each call is one undo step. The Links panel's R (`ui.relinkDialog`) with a Replace menu of these four choices. A PNG, JPEG, another file (or each at the file of its name in a folder); images keep their bounds, one undo step each. `links.update`, and `document.open` when it reads a modified file, also read the file again for the images and placed -documents inside symbols, graph designs, patterns and opacity masks that show the same content. Those objects have ids +documents inside symbols, graph designs, patterns, opacity masks and the art of the stored brushes (a scatter or art +brush's art, a pattern brush's tiles) that show the same content. Those objects have ids of their own: `links.list`, `links.check`, `links.findFiles`, the `missingLinks`, `modifiedLinks` and `updatedLinks` -rows and the link watch list them, and every `links.*` command takes their ids. Opening a document gives an object +rows and the link watch list them, and every `links.*` command takes their ids. A `links.*` command that changes a +brush's art writes it back into the brush library with those ids. Opening a document gives an object there whose id is 0 or already used by another object a new id, and the next save writes it. Saving a document also reads it again for the placed documents of it inside that art in the other open documents. A PNG, JPEG, GIF or WebP file whose pixels can't be read is not shown: `links.relink` fails with "the image's pixels can't be @@ -7156,9 +7405,14 @@ the document; so does `object.expand`. Placing a text file (`.txt`) sets it as area type: `file.place {path | name+dataBase64, text?: {characterSet?: "unicode" | "ansi", platform?: "windows" | "mac", removeLineReturns?, removeParagraphReturns?, replaceSpaces?: n}}` (Text Import Options). Unicode reads UTF-8, or UTF-16 with a byte-order mark; ANSI reads Windows-1252 (Mac Roman on -`mac`). `removeLineReturns` joins the lines of each block into one paragraph, `removeParagraphReturns` drops blank -lines, `replaceSpaces: 3` turns runs of 3 or more spaces into tabs. The frame fills `rect`, the replaced object's -bounds, or the artboard less a 36 pt margin. +`mac`). Unicode reads a file without a byte-order mark as UTF-16 by the rule `dataset.import` uses: at least half of +its two-byte units hold a NUL byte, in the byte order that reads a line break, or for a file with one line, big-endian +when more of its units start with a NUL byte than end with one, and little-endian otherwise. Any other file is read as +UTF-8, else as the platform's 8-bit set: one with fewer NUL bytes, one with an odd length, one where both byte orders +read a line break, and one that isn't valid UTF-16 in that order or holds a NUL character. `removeLineReturns` joins +the lines of each block into one paragraph, `removeParagraphReturns` drops blank lines, `replaceSpaces: 3` turns runs +of 3 or more spaces into tabs. The frame fills `rect`, the replaced object's bounds, or the artboard less a 36 pt +margin. ```json {"name":"run_command","arguments":{"command":"file.place","params":{"path":"/tmp/notes.txt","text":{"removeLineReturns":true,"removeParagraphReturns":true}}}} @@ -7341,12 +7595,16 @@ listed in `warnings`. ASCII and binary DXF files are read; DWG files answer an e ## Links panel -`links.list {show?: all|missing|modified|embedded, sort?: name|kind|status}` lists every image in the layers, top -first, as the Links panel does, then every image and placed document in opacity-mask art and in the art of symbols, -graph designs and patterns, one row per stored object (never one per symbol instance or pattern tile): `{id, name, -linked, status: ok|modified|missing|embedded, format, pixelWidth, pixelHeight, path?, found?, page?, preview?, note?, -owner?}` (`owner`, for an object outside the layer tree: `{kind: layers|symbol|graphDesign|pattern, name?, maskOf?}`, -`maskOf` naming the object whose opacity mask holds it; `note`: the image takes more than the decode allowance, 2 GiB +`links.list {show?: all|missing|modified|embedded, sort?: name|kind|status|size}` lists every image in the layers, top +first, as the Links panel does (`sort: "size"`, the panel menu's Sort by Size, puts the smallest file first by the +size Link Info shows; rows without one, embedded images and missing files whose size is not kept, come last, and equal +sizes go by name), then every image and placed document in opacity-mask art and in the art of symbols, +graph designs, patterns and stored brushes, one row per stored object (never one per symbol instance, pattern tile or +brushed stroke): `{id, name, linked, status: ok|modified|missing|embedded, format, pixelWidth, pixelHeight, path?, +found?, page?, preview?, note?, owner?}` (`owner`, for an object outside the layer tree: +`{kind: layers|symbol|graphDesign|pattern|brush, name?, maskOf?, index?, tile?}`, `maskOf` naming the object whose +opacity mask holds it, `index` a brush's place in the library as `brush.list` lists it and `tile` the pattern brush tile +that holds it: `side`, `outerCorner`, `innerCorner`, `start` or `end`; `note`: the image takes more than the decode allowance, 2 GiB or 512 MiB in the web app, as RGBA or as decoded, and it is drawn at the largest size within the allowance ("shown at reduced size"; the document keeps the whole file) or, when it can't be read that way or has more pixels than the allowance has bytes, drawn as a crossed gray box on the canvas and left out of exports ("too large to draw"); `document.open` and `file.place` say the same in their `warnings`). `links.info {id?}` is the Link Info: `image.info`'s fields plus @@ -7374,6 +7632,12 @@ bounds; `clip` puts it in a clip group of the old bounds when it is larger). The except for a placed document, which opens in a tab. With the preference `editOriginalSystemDefaults` (Preferences › File Handling › Use System Defaults for Edit Original, on by default) off, Edit Original opens a raster image in the app that made it, PhotoCraft, where it is installed, and anything else in the system's default app (#5236). +The UI command `links.copyInfo {ids?}` (the panel menu's Copy Info) copies the file names of images and placed +documents `ids` to the clipboard, one per line in the order given, and returns `{text, names}`. Without `ids` (or with +`ids: null`, as for the other `ids` commands) it copies the selected ones, and the rows outside the layer tree picked in +the panel, in the order `links.list` gives them; the panel menu passes the selected rows in the order the panel shows +them. An embedded image gives the name its row shows. An id that is not an image or a placed document, a +malformed `ids`, or nothing to copy is an error, and the clipboard is left as it was. ```json {"name":"run_command","arguments":{"command":"links.list","params":{"show":"missing"}}} @@ -7729,10 +7993,11 @@ and is missing from the picture" once for all such images. `document.open` and `file.place` read `.emf` and `.wmf` (placeable or not) into one artboard, the picture's frame, and one layer: paths with their fills and strokes (pens become strokes with caps, joins and dashes), clipping groups, -images and point type in the font the file names. Records VectorCraft doesn't read (EMF+ drawing among them) are -skipped with one warning. `clipboard.importEmf {dataBase64, center?}` loads an EMF or WMF picture into the clipboard -for `edit.paste`; the app pastes `image/emf` from the system clipboard ahead of text and bitmaps when the platform's -clipboard service offers it (the Windows desktop service doesn't read metafiles yet). +images and point type in the font the file names. An EMF that draws with EMF+ records is read from them. Hatched and +pattern brushes fill with their average color. Records VectorCraft doesn't read are skipped with one warning. +`clipboard.importEmf {dataBase64, center?}` loads an EMF or WMF picture into the clipboard for `edit.paste`; the app +pastes `image/emf` from the system clipboard ahead of text and bitmaps when the platform's clipboard service offers it +(the Windows desktop service doesn't read metafiles yet). ```json {"name":"export","arguments":{"path":"/tmp/logo.emf"}} @@ -7801,7 +8066,7 @@ instructions is refused with "not an HP-GL file". `document.export` (and `export`, and Export As) with format `hpgl` writes a plot file (`.plt`) of the first artboard (or `artboard`) for pen plotters and cutters; `useArtboards: true` writes one file per chosen artboard -(`{stem}-{artboard}.plt`), `false` the bounds of the visible art. Each visible path is drawn once along its own line: +(`{stem}-{artboard}.plt`), `false` the bounds of the art it plots. Each visible path is drawn once along its own line: a filled shape is its closed outline, also when a stroke gives its color, and a stroked path is its center line, so fills, stroke widths, dashes, brushes and arrowheads are not painted. Type is drawn as its glyph outlines, and a gradient mesh as its outline, also inside a blend (a mesh whose every point is at 0% opacity draws nothing). A @@ -7921,7 +8186,12 @@ moving the art moves the crop, and deleting it removes it from its asset (an ass format row of the document's export settings, the ones Export for Screens remembers (`document.exportSettings`); any `formats`, `preset`, `settings`, `prefix` or `subfolders` given win for that export. `assets.settings.set` changes those shared settings (not an undo step); its `subfolders: true` sets Export for Screens' Folders to a folder per row, -and `subfolders: false` sets a folder per row back to All in One Folder. `document.exportForScreens {assets: [id…]}` does the same with its own params +and `subfolders: false` sets a folder per row (without `exportPreset`, also a folder per format or item) back to All +in One Folder. Its `openLocation: true|false` +is Open Location after Export, kept in `document.exportSettings` (not in presets). The panel menu's Create Sub-folders and +Open Location after Export run these two (sub-folders sort the pictures; `assets.export3D` writes mesh files in the +folder itself), and its Format Settings… opens Export for Screens on the first row's format +settings. `document.exportForScreens {assets: [id…]}` does the same with its own params (the dialog's Assets tab). An asset's crop, and the crop of `export` with `selection: true`, is the bounds the renderer measures for what the art draws, its effects included. @@ -8291,7 +8561,8 @@ undo step. Object › Transform › Scale, the Scale tool and the Transform pane text reflows along it. `text.setPathHandle {id, subpath?, anchor, which: "in"|"out", x, y, independent?}` moves a direction handle of one of its anchors, as `path.setHandle` moves a path's (Direct Selection dragging a handle of the path, #3565), in one -undo step. +undo step. A call of `text.reshapeArea`, `text.reshapePath` or `text.setPathHandle` that changes nothing (`dx` and +`dy` both 0, or a handle moved to where it already is) adds no undo step and keeps redo. ```json {"name":"run_command","arguments":{"command":"text.reshapeArea","params":{"id":42,"anchors":[[0,2]],"dx":40,"dy":60}}} @@ -8356,7 +8627,10 @@ the end of the path), and `fit`, `fitScale` and `dynamicText` (Block is on) for Given for several area types (`ids`, or a selection of several), `text.areaOptions` changes only the options given on each one: each frame keeps its other options (it used to take the first frame's), and `fitMinPercent` alone changes only the frames that already shrink text to fit. Options that change nothing (the vertical alignment already set, say) add -no undo step and keep redo. +no undo step and keep redo. The same holds for `text.setText` when no object changes (the text it already has, in one +style, every paragraph with the first one's attributes and no ruby), `text.setStyle` when no character, paragraph or +graph label style changes, `type.ruby` with the same reading and options again or `remove` where there is no ruby, and +`text.fitHeadline` on a first line that already has the tracking it would set. Text that doesn't fit is drawn up to the last line that does, so a one-line headline in a frame lower than its line draws nothing. The commands that make type or change what it holds say so in their own reply: `text.create`, @@ -8517,6 +8791,34 @@ on again. {"name":"run_command","arguments":{"command":"type.convertToAreaType","params":{"ids":[42]}}} ``` +## Smart Punctuation + +`type.smartPunctuation` replaces keyboard characters in the selected type, or in every text object with `scope: +"document"` or nothing selected, in one undo step. Each option is a switch: + +- `fiLigatures` (default `false`): ff, fi and ffi become the ligature characters U+FB00, U+FB01 and U+FB03. +- `flLigatures` (default `false`): ff, fl and ffl become U+FB00, U+FB02 and U+FB04. The longest match is taken first. +- `quotes` (default `true`): straight quotes become the Document Setup quotes. +- `spaces` (default `false`): two or more spaces after a period become one. +- `dashes` (default `true`): `--` becomes an en dash and `---` an em dash. +- `ellipsis` (default `true`): `...` becomes an ellipsis. +- `fractions` (default `false`): 1/2, 1/4, 3/4 and the other fractions Unicode encodes as one character (thirds, + fifths, sixths, sevenths, eighths, ninths and 1/10) become that character. A fraction with a digit of any script, a + slash or a decimal point next to it, as in 1/25, 1/2/26 or 1/2.5, is left as it is, also when a change of style falls + inside it. An inline graphic separates the text before it from the text after it, for this option and for `spaces`. + +A ligature or a fraction is written only where the run's font has a glyph for it; elsewhere the letters stay. Ruby +stays on the characters it was set on, and no replacement joins characters on both sides of a ruby span's end. A value +other than true, false or null is refused. The reply gives the number of text objects changed and how many of each +replacement were made; with nothing to replace, no undo step is recorded. Type › Smart Punctuation… opens a dialog with +these options, Replace In (Selected Text Only or Entire Document) and Report Results, which lists the count of each +chosen replacement after OK. The dialog opens on the options confirmed last. + +```json +{"name":"run_command","arguments":{"command":"type.smartPunctuation","params":{"fiLigatures":true,"spaces":true,"fractions":true}}} +→ {"changed": 1, "replaced": {"fiLigatures": 2, "flLigatures": 0, "quotes": 1, "spaces": 1, "dashes": 0, "ellipses": 0, "fractions": 2}} +``` + ## Hyphenation options `text.setFormat` sets the Paragraph panel menu's Hyphenation… options of the selected type (or `ids`, or the @@ -8795,7 +9097,8 @@ Options). Warichu characters are set at `warichuScale` percent of their size (10 `warichuLines` lines (a whole number from 1 to 6, default 2) inside their line: one above the other in horizontal type and side by side across the column in vertical type, the first line above or to the right. `warichuGap` is the space between the lines in points (0 to 100, default 0, document points as `baselineShift`). The stack is centered across the -line on the center of the line's ideographic em box, and the line keeps the height of the characters' own size. +line on the center of the line's ideographic em box, and the line keeps the height of the characters' own size, or +more when the stack needs it: the line's ascent and descent take in the characters of the outer lines. A stretch of warichu characters is one block that takes the settings of its first character; a character with other settings, another size or the other kind of leading (Auto or a number) starts a new one, and a tab, a forced line break or a tate-chu-yoko character ends it. In vertical type a character marked `tateChuYoko` as well is set as tate-chu-yoko at its own size, and two or three digits @@ -8842,7 +9145,11 @@ menus, and a value typed past 1000 sets 1000; Reset Panel sets both to 0. Charac in Advanced Character Formats. With Fractional Widths off or System Layout on, each side is set in whole points, and justification keeps that width. Live SVG text places each character the space moves, and type on a path with Insert Aki is written as outlines. An SVG saved without Preserve Editing (`preserveEditing`) reopens without the -Insert Aki values; save it with Preserve Editing to keep them editable. +Insert Aki values; save it with Preserve Editing to keep them editable. An `.ai` file's text document keeps both +values, and opening the file reads them back. The stored values are read in thousandths of an em and a negative +value opens as 0; these are VectorCraft's own rules. When a legacy `.ai` save writes type as text, it writes type with +Insert Aki without the values and warns that they are left out. With `outlineText: true` it writes the type as outlines, +which keep the space Insert Aki adds, and does not warn that the values are left out. ```json {"name":"run_command","arguments":{"command":"text.setRangeStyle","params":{"id":12,"start":0,"end":3,"akiRight":500}}} @@ -8870,6 +9177,27 @@ as outlines. {"name":"run_command","arguments":{"command":"text.setRangeStyle","params":{"id":12,"start":0,"end":3,"tsume":50}}} ``` +## East Asian glyph forms + +`text.setFormat` and `text.setRangeStyle {glyphForm}` set the East Asian glyph form the characters are drawn in +([the help page](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)): `"traditional"`, +`"expert"`, `"jis04"`, `"jis90"`, `"jis78"`, `"jis83"`, `"fullWidth"`, `"halfWidth"`, `"thirdWidth"` or +`"quarterWidth"`, which draw them with the font's OpenType feature `trad`, `expt`, `jp04`, `jp90`, `jp78`, `jp83`, +`fwid`, `hwid`, `twid` or `qwid` ([feature list](https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist)), +or `"default"`, the font's default glyphs. A character holds one form at a time, so setting one replaces another. The +text keeps its characters, and a character the font has no glyph of that form for keeps its own. Runs that differ only +in their form are shaped as one piece of text. The form is saved only when it is not `"default"`, character styles +carry it, PDF draws the glyphs the canvas draws, and live SVG text writes it in `font-feature-settings`. Another value +is refused with `` `glyphForm` must be one of "traditional", … ``. One undo step, and a `text.setFormat` call that +gives the form the characters already have records none. With Show East Asian Options on, the Glyphs panel menu lists +the ten forms and Revert To Default Forms: a form is checked when every selected character has it, choosing it again +does nothing, and it is disabled when none of the faces that draw the selected text, fallback faces included, has a +feature for it. + +```json +{"name":"run_command","arguments":{"command":"text.setRangeStyle","params":{"id":12,"start":0,"end":3,"glyphForm":"jis78"}}} +``` + ## Composite Fonts A composite font sets each class of character in a font of its own @@ -8925,6 +9253,7 @@ for the selected type objects (or `ids`); without `on` it sets the opposite of t on. Optical Margin Alignment is a setting of the whole thread: the command sets every frame of a selected frame's thread, and `ids` lists them all. Threading frames gives the thread its first frame's setting, frames taken out of a thread keep it, and a file whose frames of one thread differ opens with the first frame's setting in all of them. +When every frame already has the setting, the command records no undo step. In every paragraph of point and area type, these characters hang outside the margin when they start or end a line: quotation marks, hyphens (a hyphenated line's hyphen too), full stops and commas hang wholly; asterisks, tildes, ellipses, en and em dashes, colons and semicolons hang by half their width; and A, V, W, Y, v, w @@ -9069,7 +9398,9 @@ send an Alignment or Level change for paragraphs that stay in no list. With no t with an unknown `tab`, `ui.bulletsAndNumbering` is an error. Type › Bullets and Numbering › Convert to Text runs `type.convertListToText` on the selected type's paragraphs, or on -those the Type tool's selection touches, and that runs `text.convertListToText {ids?, start?, end?}`. The marker of +those the Type tool's selection touches, and that runs `text.convertListToText {ids?, start?, end?}`. With the +Selection tool, a selected frame of threaded text names every frame of its story in `ids`, locked and hidden frames +included, as Apply Bullets and Apply Numbers do. The marker of each list paragraph becomes characters at the start of the paragraph: the bullet, or the number and its period as the paragraph showed it, then a tab. They are set in the marker's font, size and color: the style of the paragraph's first character without the attributes the marker leaves out. The paragraph leaves its list. A paragraph at a list level @@ -9096,9 +9427,8 @@ the type it changed, how many paragraphs were `converted`, and the characters `i Type tool edits, `text.convertListToText` ends its typing first and moves its anchor and caret past the characters inserted at or before them, whether the call comes from the menu, MCP or the control channel. After Select All in a frame of threaded text, a call without `ids`, `id`, `start` or `end` converts every paragraph of -the story's frames that are neither locked nor hidden. While the story is selected, its locked and hidden frames are -not converted, even when `ids` names them, and neither is a paragraph whose text starts in one. When the call converts -all of its other frames, the whole story stays selected. +every frame of the story, locked and hidden frames included. `ids` naming a locked or hidden frame converts its +paragraphs too. When the call converts every frame of the story, the whole story stays selected. In threaded type, when the caret's character moved to another frame, the Type tool edits that frame with the caret next to the same character, and that frame becomes the selection when it was not selected. @@ -9356,6 +9686,15 @@ and a glyph that the character's style does not draw (All Caps, Small Caps or an system). Choosing the glyph a character already draws is not an edit. Character styles do not take `glyphAlternate`: `charStyle.new`, `charStyle.edit` and `charStyle.setAttrs` refuse it. +On the desktop canvas, a Type tool with exactly one character selected shows up to five of that character's alternates +in a row beside it, in the same order and without the glyph the character is drawn with; a character drawn with an +alternate gets its default glyph first. A click on a glyph runs the same command as the panel's double-click +(`text.setRangeStyle {featureChanges}`, or `text.setGlyphAlternate` for a glyph no feature draws there), as one undo +step. When the character has more alternates than the row shows, an arrow at the end of the row opens the Glyphs panel +on Alternates for Current Selection. The row has no command of its own: an agent reads the alternates with +`text.glyphAlternates` and applies one with the commands above. The `showCharacterAlternates` preference turns the row +off. + ```json {"name":"run_command","arguments":{"command":"text.glyphAlternates","params":{"id":7,"start":2}}} {"name":"run_command","arguments":{"command":"text.setGlyphAlternate","params":{"id":7,"start":2,"gid":1043}}} @@ -9711,7 +10050,9 @@ and turn, shear and flip about it (`origin`). WebAssembly plug-ins ([plugins.md](plugins.md)) are reached through commands; the desktop app and an unconfined `vectorcraft-cli` keep the ones `plugin.install` installs in a `Plug-ins` folder next to the preferences and install -them again at startup (`plugin.remove` deletes them there): +them again at startup (`plugin.remove` deletes them there). A window or process locks `disabled.lock` in that folder +while it changes it, so installs, removals, grants and plug-in settings from two of them do not mix; when the file can't +be locked, `plugin.install` and `plugin.remove` fail and change nothing: `plugin.install {path | dataBase64}` installs one, `plugin.list` / `plugin.info {id}` describe them (parameters, schema, defaults). An object filter runs on the selected paths and compound paths with `plugin.run {id, params}` (one undo step; it may change, delete or add objects, and the result is selected). A filter whose manifest lists `inputs` @@ -10032,7 +10373,8 @@ A canvas-click dialog also has `preview` (initially on): tentative settings draw ``` The Shape Builder tool's options are its Shape Builder Tool Options (dialog `shapeBuilderOptions`): -`openFilledAsClosed` (on: a filled open path bounds a region as if an invisible edge closed it; off: it cuts regions +`openFilledAsClosed` (on: a filled open path bounds a region as if an invisible edge closed it; a path counts as +filled when any of its fill rows is shown, painted and above 0% opacity, whichever row is on top; off: it cuts regions as an unfilled path does), `pickColorFrom` (`artwork`, the default: a merged shape takes the appearance, opacity and blending mode of the front-most selected object under the drag's first point, else of the one under its last point, else of the front-most selected object; `swatches`: the current fill, and the Left and Right arrow keys without @@ -10109,8 +10451,10 @@ Perspective grid presets: `perspective.presets.list` lists the built-in views (` `[1P-High View]`, `[2P-Normal View]`, `[2P-Low View]`, `[2P-High View]`, `[3P-Normal View]`, `[3P-Low View]`; `builtIn: true`, fitted to the first artboard, protected), then the saved ones, each with its Define Grid fields. `perspective.grid.preset {name}` (or `{kind}`, that type's normal view) resets the grid to one, fitted to the first -artboard. `perspective.presets.save {name?, newName?, preset?, …fields}` saves a preset: just `{name}` saves the -document's grid (View → Perspective Grid → Save Grid as Preset). `perspective.presets.delete {name}`, +artboard. It adds no undo step when the document already holds that grid. When only whether the grid shows or its +active plane differs, it sets them without an undo step, as `perspective.grid.show` and `perspective.plane.set` do. +`perspective.presets.save {name?, newName?, preset?, …fields}` saves a preset: just `{name}` saves the document's grid +(View → Perspective Grid → Save Grid as Preset). `perspective.presets.delete {name}`, `perspective.presets.export {names?, path?}` (a `.vcperspective` JSON file; without `path` it returns `data`) and `perspective.presets.import {path? | data? | dataBase64?, replace?}` manage them. Saved presets are kept with the preferences, and a grid whose fields are a preset's is named after it (`name`). @@ -10138,9 +10482,30 @@ or of a plane widget, cancels it and puts the grid back. The Plane Switching Wid of the document window (headless: the first artboard's top-left corner); a press on it picks the plane with any tool while the grid shows (choosing a perspective tool shows it, and `perspective.grid.show` hides it again with the tool still chosen), and the keys 1–4 (`key` with `"1"`…`"4"`) pick the left, horizontal, right and no plane. -`perspective.widget.options {show?, position?}` (Perspective Grid Options, double-click the tool) hides it or moves -it to `topLeft`, `topRight`, `bottomLeft` or `bottomRight`, kept with the preferences (`prefs.get`/`prefs.set` key -`perspectiveWidget`). +`perspective.widget.options {show?, position?, anchorPoint?, gridlineIntersection?}` (Perspective Grid Options, +double-click the tool) hides it or moves it to `topLeft`, `topRight`, `bottomLeft` or `bottomRight`, and turns the +two targets of Automatic Plane Positioning on or off (`anchorPoint`: Anchor Point of Perspective Artwork; +`gridlineIntersection`: Intersection of Gridlines; both on by default). The options are kept with the preferences +(`prefs.get`/`prefs.set` key `perspectiveWidget`), and a value that is not `true` or `false` is an error. + +Automatic Plane Positioning: `perspective.plane.infer {at?: [x, y], tolerance?, clear?}` moves the active plane +through the anchor point of shown art in perspective, or the gridline intersection of a plane that shows, within +`tolerance` points of `at` (6 by default), for now, and hides the other planes. An anchor point within reach wins +over an intersection. With the Perspective Selection tool, `pointer` `move` with Shift over one does the same, +within 6 screen pixels; with a button down, Shift constrains the move as before. `perspective.plane.set` then brings +the plane it makes active through the same point. The plane goes back to its place, and the other planes show +again, when an object is drawn on it or attached to it (`perspective.draw`, `perspective.attach`, or an object +brought into perspective by `perspective.move` or `perspective.transform`; a drag keeps the plane held until it is +committed), when `perspective.plane.matchObject` moves a plane, when the grid hides, when no plane is active, when +the file is opened again, and with `clear` (Escape with the Perspective Selection tool). `perspective.plane.move` +moves the held plane from where it is held and leaves it at its new place, and the other planes show again. +The held point is view state, not an undo step: `perspective.grid.get` reports it as `grid.inferred` (x, y and z +in the grid's frame). `perspective.grid.set`, `perspective.grid.define` and `perspective.grid.preset` keep it +unless the grid they make hides, has no active plane, or would put the plane through the point behind the viewer. +Without params the command reads the state: +`{active, plane, offset, point?, source?: anchor|gridline}`. With `at`, `source` is absent when nothing was within +reach, and the grid stays as it was. It is an error when the grid is hidden, when no plane is active, when both +targets are off, and when `at`, `tolerance` or `clear` is not what the params take. ## Envelopes @@ -10426,9 +10791,9 @@ How blends interpolate: closed shapes start where they twist least unless `start interpolate weight, dashes (a solid stroke counts as the dashed one with its gaps closed), miter limit, arrowhead scale, width profiles and the pen pressure, tilt, bearing and rotation recorded with the Paintbrush (a stroke without a recording counts as half pressure, half tilt and 0°, as brushes read it; angles turn the shorter way round; a key's -profiles, recordings and arrowheads turn with its path when the blend starts it at another anchor), while -caps, joins, alignment, arrowheads and brushes switch halfway; gradients of one kind with -different stop counts resample to a common set of stops. Groups pair their members in stacking order (members only +profiles, recordings, arrowheads, dashes and gradient along or across the stroke turn with its path when the blend +starts it at another anchor), while caps, joins, alignment, arrowheads and brushes switch halfway; gradients of one +kind with different stop counts resample to a common set of stops, keeping each step (two stops at one offset). Groups pair their members in stacking order (members only one group has grow out of the other's centre), compound paths stay compound paths, and type, symbol instances and images interpolate their transforms (type also its colours, stroke weight and size run by run; the words and the symbol switch halfway). New blends are knockout groups (`object.setProps {knockout}` changes it), drawn on the @@ -10576,6 +10941,10 @@ threaded frame, which composes them again at its own widths. Such a paragraph fa frame has no room for its first line, or when the search for its breaks passes VectorCraft's own limits (1,000,000 lines tried and 2,000,000 baseline steps for one paragraph, 2,000,000 lines and 4,000,000 steps for all the paragraphs of a frame). +Single-line measures each line's room the same way: a line that takes in a taller character is placed again across its +new height and broken again in the room there. When that leaves the taller character for the next line, the line is +set at its own height where the room there is no narrower, with the words before that character that fit there, and +otherwise stays where it was placed. The UI command `type.lineComposer` (Cmd+Alt+Shift+C, in remote mode `press_key {key: "C", mods: {cmd: true, alt: true, shift: true}}` or `invoke_menu`) sets `singleLine` when every paragraph of the selected type (or every paragraph the Type tool's selection touches) uses Every-line, else `everyLine`, and returns the composer it set. @@ -10634,7 +11003,12 @@ and the arrow keys nudge them by the keyboard increment. The active tool lists t (`tool.setOption {}` returns them as `meshPoints: [{id, index}…]`). On gradient meshes a solid fill colour (`paint.setFill`, from the Color panel, Swatches or the Eyedropper) recolours just the picked points, and when every target of `transparency.set` is a gradient mesh with points picked, its `opacity` fades those points instead of the objects -(`transparency.info` then shows their opacity, `null` when it differs). Both are one undo step. +(`transparency.info` then shows their opacity, `null` when it differs). Both are one undo step, and neither goes to the +points while the Appearance panel's active row takes the fill or the opacity. When the first selected object is a +gradient mesh with points picked, the Fill proxy, the Color panel, the Color Wheel and `paint.proxies` show its first +picked point's color, and `fillMixed` compares the picked points' colors with each other and with the fills of the other +selected objects. The Transparency panel shows the picked points' opacity (blank when it differs), and the Control +bar shows the first picked point's opacity. `object.mesh.movePoints {id, points: [index…], dx, dy}` (or `{items: [{id, points}…], dx, dy}` over several meshes) moves points by (dx, dy), their handles with them; `object.mesh.setPointColor` takes `points` or `items` the same @@ -10770,8 +11144,12 @@ topmost piece. ### Text tools The add-on's text tools act on the selected type (or `ids`), each as one undo step, and refuse with an error when there -is nothing for them to do. The pieces they make are point type that keeps its characters' styles, each placed so the -glyph of its first character lands where it was drawn. +is nothing for them to do. From the selection they take only type that can be edited; the type that `ids` names, or +that is inside a group or layer it names, is taken even when it, its group or its layer is locked or hidden (not type +on a locked artboard). The objects they make from locked or hidden type are not selected. Combine Point Text and Join +Point Text join a piece only with pieces that are as visible and as locked as it is, counting their groups and layers. +The pieces they make are point type that keeps its characters' styles, each placed so the glyph of its first character +lands where it was drawn. - `addon.cleanup.breakText {by?, ids?}` turns each horizontal point or area type object into point type objects, one per line (`by: "lines"`, the default), paragraph (`"paragraphs"`), word (`"words"`) or glyph (`"glyphs"`; a ligature @@ -10783,17 +11161,19 @@ glyph of its first character lands where it was drawn. staying where it was (within 0.01 pt). Pieces turned and sheared alike whose baselines lie within 0.4 em of each other join left to right (a baseline a little off becomes baseline shift); a space goes between pieces at least half a space apart, and tracking on the character before each piece keeps its place. A gap wider than 10 em, an overlap of - more than 1 em, another look (paint, opacity, effects) or a piece that can't keep its place once joined (a ligature - forming across the join) starts another object. Each object made takes the place and paint of its leftmost piece. The - main use is type from a PDF that arrives one glyph per object. + more than 1 em, another look (paint, opacity, effects), another visibility or lock state, or a piece that can't keep + its place once joined (a ligature forming across the join) starts another object. Each object made takes the place + and paint of its leftmost piece. The main use is type from a PDF that arrives one glyph per object. - `addon.cleanup.joinText {ids?}` (Join Point Text) joins one-line horizontal point type into one point type object, - for text that arrives one line or fragment per object. Pieces turned and sheared like the top-left one are read as - lines (baselines within 0.4 em), top to bottom; a line's pieces join left to right with a space between them. Each - line becomes a left-aligned paragraph whose leading is the distance from the baseline above, so the lines stay where - they were. Character styles stay; the object takes the top-left piece's place and paint. Returns `{id, joined, lines}`. + for text that arrives one line or fragment per object. Pieces turned and sheared like the top-left one, and as visible + and as locked as it is, are read as lines (baselines within 0.4 em), top to bottom; a line's pieces join left to + right with a space between them. Each line becomes a left-aligned paragraph whose leading is the distance from the + baseline above, so the lines stay where they were. Character styles stay; the object takes the top-left piece's + place and paint. Returns `{id, joined, lines}`. - `addon.cleanup.removeBreaks {kind, ids?}` removes the forced line breaks (`kind: "line"`) or paragraph returns (`"paragraph"`) in the characters selected with a Type tool, else in all the text of the selected type. After - Select All in a frame of threaded text, it removes them from the text of every frame of the story, as one undo step. + Select All in a frame of threaded text, it removes them from the text of every frame of the story, locked and hidden + frames included, as one undo step. A break between two words becomes a space; merged paragraphs take the first one's paragraph style. The frames of a threaded story, selected all together or through Select All, are read as one text, so a break at the end of one frame before a word in the next one also becomes a space. @@ -11166,8 +11546,8 @@ A `configure` call that changes no shape records no undo step and returns `{upda ## Cutting Tools add-on Cutting Tools is a built-in add-on that prepares art for cutting. Its commands are `addon.cutting.bridges`, -`addon.cutting.weed` and `addon.cutting.banner`; in the desktop app they are Object › Plug-ins › Cutting Tools › Stencil -Bridges…, Weed Box and Lines… and Banner Hems and Grommets…. +`addon.cutting.weed`, `addon.cutting.banner` and `addon.cutting.nest`; in the desktop app they are Object › Plug-ins › +Cutting Tools › Stencil Bridges…, Weed Box and Lines…, Banner Hems and Grommets… and Nest Shapes…. ### Stencil Bridges @@ -11288,6 +11668,39 @@ Banner Hems and Grommets… opens the command dialog with Preview. {"name":"run_command","arguments":{"command":"addon.cutting.banner","params":{"hem":"1 in","grommetInset":"0.5 in","spacing":"2 ft"}}} ``` +### Nest Shapes + +`addon.cutting.nest {roll?, width?, height?, margin?, spacing?, rotate?, usePreviewBounds?, artboard?, patterns?}` moves +the selected objects close together onto a sheet or a roll of material +([packing problems](https://en.wikipedia.org/wiki/Packing_problems)). The ranges, defaults and rules below are +VectorCraft's own. The sheet starts at the top-left corner of artboard `artboard` (0-based; by default the artboard +under the center of the selection, else the first). It is `width` × `height` points (0 to 1000000 each; 0, the default, +takes the artboard's width or height). With `roll` true it is a roll `width` wide with no end, and `height` is not used. +`margin` (0 to 100000, default 18) is kept clear inside each edge of the sheet; on a roll, inside the sides and the +start. `spacing` (0 to 100000, default 9) is kept between two objects. + +Each selected object is packed by its bounding box: with its strokes and effects, including the reach of shadows, glows +and blurs, when `usePreviewBounds` is true (the default), else by its geometry. A group is one object. The tallest +objects go first, each where its bottom edge is highest and then furthest left. With `rotate` true (false by default), +an object may turn 90° clockwise where that puts its bottom edge higher, or where only the turned object fits; the +longest side then decides the order, and a turned object is measured as it is after the turn. A path of a +pixel-aligned compound path is not turned. Objects are moved, and turned with `rotate`, never resized. An object on the +pixel grid moves by whole points and takes 1 pt more room across and down. Objects that do not fit go in a column to +the right of the sheet, from its top, `spacing` from its edge and from each other, in stacking order (back to front). +Objects without bounds, such as an empty group, are not moved. `patterns` moves pattern fills and strokes with the art +(default: General › Transform Pattern Tiles). + +All of it is one undo step, and nothing changes when no object moves. The command fails when nothing selected can be +measured, when the margin leaves no room on the sheet, when no selected object fits, with more than 10000 objects +selected, and with bad params. Result: `{placed, unplaced, rotated, skipped, length}`: the number of objects placed, +the ids of the objects put beside the sheet, the ids of the objects turned, the ids of the objects without bounds, and +the length of material used in points, from the sheet's top edge to the margin below the lowest object placed. Nest +Shapes… opens the command dialog with Preview. + +```json +{"name":"run_command","arguments":{"command":"addon.cutting.nest","params":{"roll":true,"width":"24 in","margin":"0.25 in","spacing":"0.125 in","rotate":true}}} +``` + ## Color Effects add-on Color Effects is a built-in add-on: its effects are colour adjustments in Effect › Color Effects, its command is @@ -11497,7 +11910,7 @@ as `object.setBounds` measures them (Use Preview Bounds), except Arrange in Grid | `addon.arrange.replace` | `fit`: `keep`, `bounds` (the replaced object's width and height), `proportional` (fits inside them) (`keep`); `scaleStrokes`; `keep` (false) | Puts a copy of the topmost selected object centred on each of the other selected objects, in that object's place in the stacking order; the replaced objects are deleted unless `keep` (the copy then goes right above each). Needs two objects or more; the copies are selected. → `{ids}` | | `addon.arrange.size` | `width`, `height` pt, 0.001…1000000 (at least one); `proportional` (false: a side not given stays; true: it follows the given one in proportion); `reference` 0…8 (4, the centre); `scaleStrokes` | Gives every selected object that width and height, keeping its reference point in place (the 9-point grid row by row from the top-left). | | `addon.arrange.groupOverlapping` | none | Groups the selected objects (at most 20000) wherever their visual bounds overlap or touch, chains included: when A overlaps B and B overlaps C, all three go in one group. Only objects in the same layer or group are grouped together; objects that overlap nothing stay as they are. Each new group goes where its frontmost member was in the stacking order, and the groups and the objects left alone stay selected; with nothing overlapping it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) | -| `addon.arrange.randomizeOpacity` | `min`, `max` % 0…100 (30, 100; `min` not more than `max`); `seed` whole number (0); `ids` (the selection) | Gives each selected object its own opacity (the object opacity the Transparency panel sets), picked at random and evenly from `min` to `max`; the same seed, objects and range give the same opacities. Groups take one opacity of their own; the objects inside keep theirs. → `{count}` | +| `addon.arrange.randomizeOpacity` | `min`, `max` % 0…100 (30, 100; `min` not more than `max`); `seed` whole number (0); `ids` (the selection) | Gives each selected object its own opacity (the object opacity the Transparency panel sets), picked at random and evenly from `min` to `max`; the same seed, objects and range give the same opacities. Groups take one opacity of their own; the objects inside keep theirs. A run that changes no opacity, such as `min` and `max` both at the opacity every object has, records no undo step. → `{count}` | | `addon.arrange.sort` | `by`, `apply`: `width`, `height`, `area` (width × height), `x` (left edge), `y` (top edge), `opacity` (%), `stacking` (stacking order from the back) (`area`, `stacking`); `order`: `ascending` (small to large), `descending` (large to small), `random` (`ascending`); `distribute` (false); `seed` whole number (0, for `random`); `scaleStrokes`; `ids` (the selection) | Sorts the selected objects (at most 20000) by `by` and gives them the values of `apply` in that order: the first gets the smallest value. Without `distribute` the objects trade the values they have; with it the values step evenly from the smallest to the largest. A width, height or area changes about each object's centre (an area in proportion), a place moves the top-left corner. Stacking order always trades places, and only among objects in the same layer or group. Needs two objects or more. → `{count}` | Zoom to Selection is the UI command `addon.arrange.zoomSelection {}` (remote mode only): it zooms and centres the @@ -11758,6 +12171,8 @@ the error text. The interactive fallback applies only to ordinary File > Save, n | Date | Change | |---|---| +| 2026-11-13 | The Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides; Snap to Grid and Snap to Pixel still move its ends (#7252). | +| 2026-11-13 | `path.freehand`: `closed`, when given, decides whether a stroke that continues a path (`extend`) closes it; the Pencil and the Paintbrush send it by Close Paths When Ends Are Within. | | 2026-11-13 | Snap to Point with Smart Guides off draws no Smart Guides labels or lines (#7250). | | 2026-11-13 | Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter (#7097). | | 2026-11-11 | Document READ_ONLY_LOCATION for saves (#6146); no response-shape change. | diff --git a/docs/plugins.md b/docs/plugins.md index fac6460249..dd3df7f7ac 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -269,7 +269,13 @@ capability model proposed for PhotoCraft plug-ins while `plugin.install` checks a module, the install is refused, before anything is written to the `Plug-ins` folder, if the other plug-in would need `replace: true` or the changed grant no longer approves the module. A `plugin.remove` in another session waits until the install has written the `Plug-ins` folder, and then removes the - module and its grant. Loading the `Plug-ins` folder or a plug-ins folder in another session waits for it too. When + module and its grant. Loading the `Plug-ins` folder or a plug-ins folder in another session waits for it too. + Another process using the same `Plug-ins` folder, for example `vectorcraft-cli` beside the app, waits as well: each + window or process locks `disabled.lock` in the folder while it reads and changes the stored modules, `grants.json`, + `disabled.json` and the plug-ins' settings and caches. An install therefore keeps a module with its own grant, and a + grant or setting written in one process does not undo one written in another. When `disabled.lock` can't be + locked, `plugin.install` and `plugin.remove` fail and change nothing, `plugin.setEnabled` keeps its change in the + process until a later change can be saved, and loading the folder writes nothing to it. When an install of a module that lists no permissions can't write the module to the `Plug-ins` folder, or can't remove the grant from `grants.json`, the folder keeps the module it held and `grants.json` keeps the grant. The new module runs until the session ends. When the grant can't be diff --git a/docs/roadmap.md b/docs/roadmap.md index 70e0dce666..2bb166ed1e 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # Roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-15 · **Change:** minor (G12: Swatches item menus tested and rendered; Linux full CI passed; Windows engine baseline failures noted; 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: 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; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; 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 are in; 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; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; 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; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #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; 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; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-15 · **Change:** minor (G12: Swatches item menus tested and rendered; original feature Linux CI passed; integration blocked by upstream #7727; Windows engine baseline failures noted; 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: 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; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; 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 are in; 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; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; 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; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #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; 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; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **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). > @@ -56,7 +56,7 @@ M7 type: Touch Type moves a right-to-left character along its line and up from i | Date | Change | Summary | |---|---|---| -| 2026-11-15 | minor | G12: Swatches item menus validated in all five views: 39 focused tests passed, regression fails without the menu hooks, rendered list/thumbnail layouts inspected, and fresh local deep CodeRabbit review found zero issues. Full workspace CI passed on Linux/WSL (all 13 gates); native Windows full CI has two unchanged engine-test failures. Scores and estimates unchanged. | +| 2026-11-15 | minor | G12: Swatches item menus validated in all five views: 39 focused tests passed, regression fails without the menu hooks, rendered list/thumbnail layouts inspected, and fresh local deep CodeRabbit review found zero issues. Full workspace CI passed on Linux/WSL for feature commit `6f4a651c0` (all 13 gates); validation after merging main stops at the upstream test-helper compile error tracked in #7727; native Windows full CI has two unchanged engine-test failures. Scores and estimates unchanged. | | 2026-11-13 | minor | Graphic Styles: in a panel made taller the list fills the space above the footer instead of stopping at 220 pt (#2992; `the_list_fills_a_tall_panel_above_its_footer` in `crates/ui-egui/src/panels/graphic_styles.rs`). Scores and estimates unchanged. | | 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 | Library panels (swatch, Color Book, brush, symbol and graphic style libraries): in a panel made taller the list fills the space above the footer instead of scrolling inside 220 or 280 pt (#2992; `the_list_fills_a_tall_panel_above_its_footer` in `crates/ui-egui/src/panels/library_panel/tests.rs`). Scores and estimates unchanged. | @@ -160,7 +160,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M1 | Selection, transform, layers, MCP (common command tools, strict keys, session resources and version-aware result hints) | ✅ mostly done (document-tab artwork drag with lossless resource transfer and one target Undo; malformed MCP app replies discard the connection without replay, #1761; bounded control socket waits and connection-slot recovery, #1726; bounded synthetic control input, #1709; no-op anchor Align keeps Undo, Redo and saved state (#1180 follow-up); transform reference point snaps to anchors/centres; rotated objects keep a rotated bounding box and their angle; Free Transform, Scale and Reflect along a rotated box pending; the Transform fields take one Tab each, the W/H link after them) | 4–6 | | M2 | Drawing tools + smart guides | ✅ mostly done (#3380 deletion creates independent selected path pieces and keeps bounds-fitted gradients in place; endpoint highlighting remains open; Polygon/Star exact-size count persistence, with repeated-drag, tool-switch and Cancel regression coverage; Curvature point markers without direction handles (#1236, in part); Direct Selection segment click/Delete preserves neighboring edges, #1278; Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper rough-shape recognition and orientation steps, the remaining Pen modifier nuances; Shaper Groups with editable sources and separate fill/stroke edits landed; custom ruler origin with drag preview, active-artboard reset, relative X/Y fields and native round-trip (#1212); construction widget/refinements pending); a shape just drawn moves by its centre point and turns from the zone outside a corner with its tool still active (#5477); Tangent and straight-segment perpendicular snapping use saved Smart Guides Geometric Guides preferences and Control bar quick access (#2537), including the existing Snap to Glyph and Alignment Guides toggles (#6164); no View submenu; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123) | 12–18 | | M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper copies transformed character dimensions (#6404) and styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel, Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit; finite-arithmetic follow-up regressions and full CI passed ([Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area))), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; PDF export writes dithered gradient fills with spot stops, and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, as images in process colors; confirm the Scale Strokes & Effects default; Recolor model selection is available through the engine and MCP only (#2520); the dialog retains its existing controls; Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill a taller panel above its footer (#2992; scores and estimates unchanged); Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); Swatches list fills a taller panel above its footer (#1638; `the_list_fills_a_tall_panel_above_its_footer`; scores and estimates unchanged); | 4–8 | -| M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | Explicit editing-data import keeps oversized capped-page artboards (#6865; estimates unchanged); Save refusal continuation (#6146): ordinary Save offers Save As; unchanged format keeps options, changed format opens its Save options; cancellation/automation isolation; focused UI regressions passed, native acceptance pending; PDF authored ActualText preserved once in editable import (#6165; first-glyph line/style, bounded input; estimates unchanged); PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. `.ai`/EPS type from the text document keeps its paragraphs' tab stops (#6147); `.ai`/EPS type from the text document keeps auto leading per line, its hyphenation options, and may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them (#6137); ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding no text (#6971; scores and estimates unchanged); | 3–6 (existing scope; Affinity export unestimated) | +| M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | Rename artboards in Export for Screens (#7275); Explicit editing-data import keeps oversized capped-page artboards (#6865; estimates unchanged); Save refusal continuation (#6146): ordinary Save offers Save As; unchanged format keeps options, changed format opens its Save options; cancellation/automation isolation; focused UI regressions passed, native acceptance pending; PDF authored ActualText preserved once in editable import (#6165; first-glyph line/style, bounded input; estimates unchanged); PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. `.ai`/EPS type from the text document keeps its paragraphs' tab stops (#6147); `.ai`/EPS type from the text document keeps auto leading per line, its hyphenation options, and may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them (#6137); ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding no text (#6971; scores and estimates unchanged); | 3–6 (existing scope; Affinity export unestimated) | | M5 | Performance | 🟡 background render + caches + MT done; `vectorcraft-cli bench` and `vectorcraft-cli perf` (budget suite); opaque solid-fill knockout paths draw once in hard-edge/supersampled raster export, with analytical-AA compositing unchanged; file format v2 opens 3× faster (50k paths: 722 → 244 ms); raster effects (glows, shadows, blur, feather) no longer force the whole frame single-threaded (filtered offscreen per effect, verified equal to the single-threaded reference); Craquelure/Mosaic Tiles/Stained Glass distance searches optimized with pixel-invariance checks and the `texture_drag_perf` probe (#1257); effect-heavy demos need a clean-machine benchmark; dirty-region rendering, GPU backend spike pending | 15–25 | | M6 | Path operations (Pathfinder, Shape Builder, offset…) | ✅ mostly done (live compound shapes: Make, Alt-click a Shape Mode, member modes, Release, Expand (#4522); single-result Pathfinder names and SVG IDs retained (#1293); Divide open-cutting-path geometry, appearance and history verified (#1307; existing segment cap remains); Simplify preview/counts and rewritten-path component selection verified (#1272; the slider opens at the Auto-Simplify level; a Direct Selection part of a path simplifies on its own); Compound appearance and member fill-rule edits verified (#1197); Boolean precision on almost-horizontal edges fixed and the property tests made deterministic; Shape Builder gap detection, large-offset bug open); Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog | 3–6 | | M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof and the custom dictionary and Ignore All commands and Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, and Spelling › Auto Spell Check in the context menu of type, and the Edit Custom Dictionary dialog (#4936; the Check Spelling dialog remains); Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs (feature-valued alternates and unencoded glyphs applied in one Undo step while keeping Arabic joining, #5514), OpenType panel (including font-defined Stylistic Sets), Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, spell check, vertical type pending | 45–60 | @@ -208,7 +208,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| -| 2026-11-15 | minor | G12: Swatches item menus validated in all five views: 39 focused tests passed, regression fails without the menu hooks, rendered list/thumbnail layouts inspected, and fresh local deep CodeRabbit review found zero issues. Full workspace CI passed on Linux/WSL (all 13 gates); native Windows full CI has two unchanged engine-test failures. Scores and estimates unchanged. | +| 2026-11-15 | minor | G12: Swatches item menus validated in all five views: 39 focused tests passed, regression fails without the menu hooks, rendered list/thumbnail layouts inspected, and fresh local deep CodeRabbit review found zero issues. Full workspace CI passed on Linux/WSL for feature commit `6f4a651c0` (all 13 gates); validation after merging main stops at the upstream test-helper compile error tracked in #7727; native Windows full CI has two unchanged engine-test failures. Scores and estimates unchanged. | | 2026-11-14 | minor | G12: Swatches item context menus implemented in list and thumbnail views, with clicked-item actions and reserved/missing-swatch guards. Harness tests added; execution and visual verification pending. Scores and estimates unchanged. | | 2026-11-14 | minor | Gujarati (#6613): contributor proofreading completed for all 387 additions, with 11 wording corrections; 4,673 reviewed catalog rows. Status/error messages remain partial; web selection requires a bundled Gujarati face. Scores and estimates unchanged. | | 2026-11-12 | minor | Gujarati (`gu`): 4,286-row machine-assisted catalog reviewed by a native speaker, zero/one singular plurals, desktop font fallback and optional Gujarati craft-fonts fallback; all 72 translation tests pass; a web font and about 2,600 untranslated messages remain; scores and estimates unchanged | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b2f89a7a54..cb9668c84b 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-15 · **Change:** minor (G12: Swatches item menus tested and rendered; Linux full CI passed; Windows engine baseline failures noted; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.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) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-15 · **Change:** minor (G12: Swatches item menus tested and rendered; original feature Linux CI passed; integration blocked by upstream #7727; Windows engine baseline failures noted; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.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). > @@ -46,6 +46,7 @@ The shared assessment status line and revision history are current upstream; thi - File formats and Type core (#6147): `.ai`/EPS type from the text document keeps its paragraphs' tab stops, and right-aligned area type sets the text before a line's last tab at its stops, from the left edge, and the text after it against the right edge. Evidence: `ate::tests::a_paragraph_keeps_its_tab_stops`, `ate::tests::a_story_s_tab_stops_are_bounded`, `tests::right_aligned_area_type_sets_the_text_after_its_last_tab_against_the_edge`, `import_fuzz::text_frames_with_hostile_paragraph_attributes_never_panic`; scores and estimates unchanged - Type core: a right-to-left line with tabs is measured in the order it is drawn, with tab stops still measured from the left edge. Each tab goes to its stop from where the glyphs drawn before it end, and right, center and decimal stops align the text drawn after the tab. Right, Auto and centered lines are aligned by that width, and area type wraps a line that is too wide when drawn. Evidence: `tests::justify::a_right_to_left_line_with_a_tab_is_aligned_as_it_is_drawn`, `tests::justify::a_right_to_left_line_with_a_tab_wraps_when_it_does_not_fit_as_drawn`, `tests::justify::right_to_left_tab_stops_align_the_text_drawn_after_them`, `tests::justify::a_right_to_left_line_with_two_tabs_and_a_latin_run_ends_on_the_right_edge`, `tests::justify::right_aligned_right_to_left_point_type_with_a_tab_ends_at_its_origin`; scores and estimates unchanged +- Type core: a right-to-left line with tabs and negative tracking that is wider than its frame in the order of its text reads at most 1,024 line breaks further and ends at the latest of them that fits as drawn, so a long paragraph is not read to its end to set each line. This is VectorCraft's own limit. Evidence: `layout::wrapping_tests::a_tabbed_line_stepping_back_stops_reading_past_its_overflow`, `layout::wrapping_tests::a_tabbed_line_stepping_back_ends_at_the_latest_break_read_that_fits`; scores and estimates unchanged - File formats and Type core (#6137): `.ai`/EPS type from the text document keeps auto leading at the paragraph's share of each line's largest type, the paragraph's hyphenation options, and may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them; a line a soft return ends is justified as a wrapped line is. Evidence: `ate::tests::auto_leading_follows_the_size_of_each_line`, `ate::tests::a_paragraph_keeps_its_hyphenation_options`, `ate::tests::the_last_lines_the_file_sets_in_its_frame_show`, `tests::fit_source_lines_keeps_the_last_lines_the_source_sets`, `tests::typo::soft_return_in_justified_text_spreads_like_a_wrapped_line`. Limits: frames grow only for area type of one frame, horizontal, by its lines' deepest descent plus 0.05 pt; type in a font that isn't installed, and hyphenation in a language that isn't imported, still lay out differently; scores and estimates unchanged - Current-main conflict reconciliation retains upstream and feature behavior; scores and estimates unchanged - Superseded 2026-10-20 behavior, retained as history: Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting uses the original target artboard and revision-scoped bounds caches (scores/hours unchanged) @@ -58,10 +59,12 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| -| 2026-11-15 | minor | G12: Swatches item menus validated in all five views: 39 focused tests passed, regression fails without the menu hooks, rendered list/thumbnail layouts inspected, and fresh local deep CodeRabbit review found zero issues. Full workspace CI passed on Linux/WSL (all 13 gates); native Windows full CI has two unchanged engine-test failures. Scores and estimates unchanged. | +| 2026-11-15 | minor | G12: Swatches item menus validated in all five views: 39 focused tests passed, regression fails without the menu hooks, rendered list/thumbnail layouts inspected, and fresh local deep CodeRabbit review found zero issues. Full workspace CI passed on Linux/WSL for feature commit `6f4a651c0` (all 13 gates); validation after merging main stops at the upstream test-helper compile error tracked in #7727; native Windows full CI has two unchanged engine-test failures. Scores and estimates unchanged. | | 2026-11-14 | minor | Swatches item context menus added in all list/thumbnail views, with clicked-item selection, Options/Duplicate/Delete and reserved/missing-swatch guards. Headless regressions added; execution and visual verification pending. Scores and estimates unchanged. | | 2026-11-14 | minor | G5: Weather Icons joins Basic Shapes, UI Frames, Map Markers, Inventory Icons and Skill Icons as a sixth built-in symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow; original procedural vector symbols generated in code, no default 9-slice); area score and estimate unchanged. | | 2026-11-14 | minor | Pencil and Paintbrush: a closed stroke (Alt at the release, or ending within Close Paths When Ends Are Within of its start) is fitted as the open stroke would be and closed by a straight segment back to its start, instead of curving on past both ends (`pencil_alt_closes_a_stroke_straight_back_to_its_start` in `crates/engine/src/tests/draw2.rs`). Scores and estimates unchanged. | +| 2026-11-13 | minor | Pencil cursors: the continuation cursor (a short rising line) shows over an open end of a selected path before any press, freehand too, and while a continuing stroke nears another selected path's open end it connects to; the straight-line cursor is a short level line; a continued path, a straight line too, shows the closing cursor and closes within Close Paths When Ends Are Within of its other end, and with Alt at the release (`a_continued_stroke_shows_where_it_connects_or_closes` in `crates/tools/src/draw2/gesture/tests.rs`, `pencil_extend_closes_as_closed_says` in `crates/engine/src/tests/draw2.rs`). Scores and estimates unchanged. | +| 2026-11-13 | minor | Pencil: ignores Smart Guides and Snap to Point and shows no Smart Guides, hovering or drawing; a stroke's ends and both ends of its straight lines follow the hand, while Snap to Grid and Snap to Pixel still move them (#7252; `pencil_follows_the_hand_and_shows_no_smart_guides`, `pencil_ends_still_snap_to_the_grid_and_pixels` in `crates/tools/src/draw2/gesture/tests.rs`). Public basis: community experts on the reference app's forum say Smart Guides and the other snapping options don't make the Pencil snap ([Drawing and snapping to path in Illustrator](https://community.adobe.com/questions-652/drawing-and-snapping-to-path-in-illustrator-766887)). Scores and estimates unchanged. | | 2026-11-13 | minor | Snap to Point: with Smart Guides off it still pulls drawn and dragged points onto anchors and ruler guides, but draws none of the Smart Guides labels ("anchor") or lines (#7250; `guides::tests::snap_to_point_without_smart_guides_shows_no_guides`). Scores and estimates unchanged. | | 2026-11-13 | minor | Graphic Styles: in a panel made taller the list fills the space above the footer instead of stopping at 220 pt (#2992; `the_list_fills_a_tall_panel_above_its_footer` in `crates/ui-egui/src/panels/graphic_styles.rs`). Scores and estimates unchanged. | | 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. | @@ -207,11 +210,8 @@ tests and the CI gate. See [Calibration](#calibration). - **From the code (measured, origin/main `01e165af`):** - Menu tree (`crates/ui-egui/src/menus.rs`, laid out in Illustrator's menu order): 348 items bound to commands, 26 stubs (`todo(…)`/`todos(…)`), so 93.0% of menu items do something (348 and 26 after Snap to Glyph shipped in #3124; 348 and 27 after the - Revolve merge; 350 and 25, 93.3%, after Graph › Design and Marker; 353 and 22, 94.1%, after Extrude & Bevel, Inflate and Rotate). The stubs: Effect › 3D and Materials › Materials, Effect › SVG Filters, Edit › Spelling (3), Graph › Column, Live Paint - Gap Options, Optical Margin Alignment, global and video rulers (2), - Window › Arrange (4), SVG Interactivity, Other Script…, Help. - Gap Options, Optical Margin Alignment, Start Global Edit, global and video rulers (2), - Window › Arrange (4), SVG Interactivity, Other Script…, Help (the Brush and Symbol Libraries placeholders are gone: Window › Symbol Libraries works since 2026-10-23, Window › Brush Libraries since 2026-10-24). + Revolve merge; 350 and 25, 93.3%, after Graph › Design and Marker; 353 and 22, 94.1%, after Extrude & Bevel, Inflate and Rotate). The menu stubs on `a47d7eec` are Effect › 3D and Materials › Materials, + Edit › Spelling › Check Spelling and Help › VectorCraft Help. - Engine commands: ~710 ids registered with `cmd!` across `crates/engine/src/cmd` (plus macro-generated families), and 85 UI-only commands (`UI_COMMANDS`). - Tools: 91 in `crates/tools/src/catalog.rs`; Touch Type is listed but not implemented, and the Dimension @@ -586,6 +586,7 @@ since 2026-10-01. - 3D lighting presets: `crates/effects/src/lighting_presets.rs`, `crates/engine/src/cmd/effectcmd/lighting_presets_tests.rs` and the pointer tests in `crates/ui-egui/src/dialogs/revolve/tests.rs` cover recognition, atomic targeting, native round trips, preview, Cancel, reset and Undo. - 3D shadows: Revolve, Extrude & Bevel, Inflate and Rotate take a Shadows switch with Position (Behind Object or Below Object), Distance from Object (0–100 %) and Shadow Bounds (10–400 %) on the Lighting tab ([three-d.md](three-d.md#shadows)); the first light casts one hard-edged vector shadow, drawn behind the solids, in exports and kept by Expand Appearance. Evidence: `crates/three-d/src/shadow/tests.rs`, `crates/effects/src/solids/tests_shadow.rs`, `effectcmd::tests::a_3d_shadow_is_one_undo_step_saved_exported_and_expanded`. Softness and the shadows of lights after the first are not built. Scores unchanged. +- 3D shadows: with Shadows on, Revolve, Extrude & Bevel, Inflate and Rotate cast the shadow from the faces kept by the build that draws each solid, so drawing an object builds each of its solids once. The art and the shadow are unchanged. Evidence: `crates/three-d/src/shadow/tests.rs` (`a_solid_and_its_shadow_are_built_once` and the tests that compare each solid and its shadow with the two built apart), `solids::tests_shadow::a_shadowed_3d_object_builds_each_solid_once`, `solids::tests_shadow::the_shadow_cast_from_the_solids_drawn_is_the_shadow_of_solids_built_for_it`, `revolve::tests::the_shadow_cast_from_the_surfaces_drawn_is_the_shadow_of_surfaces_swept_for_it`. Scores unchanged. - Window › 3D and Materials panel: `crates/ui-egui/src/panels/three_d.rs` applies a 3D effect by object type (Plane, Extrude, Revolve, Inflate), changes an applied one in place (`effect.setParams` `threeDType`) and edits it with the options dialog's Object, Rotation and Lighting controls, one undo step per change; `crates/engine/src/cmd/effectcmd/three_d_type_tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. No Materials tab. - 3D and Materials › Quick Actions › Expand as Wireframes (#6354): `effect.expandAsWireframes` replaces each selected 3D object with a group of 0.5 pt black stroked paths, the edges of the faces its effect draws, each edge once and joined end to end, curves kept, in one undo step ([three-d.md](three-d.md#3d-and-materials-panel)); `crates/effects/src/solids/wireframe/tests.rs`, `crates/engine/src/cmd/wireframe/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. Scores and hours unchanged. - 3D effects on clipping groups, blends and symbol instances (#6140, #5725): every 3D type builds from the art the object shows (the art inside the clipping path, the blend's keys and steps, the symbol's art where the instance places it), alone or in a group, on the canvas, in exports, Object › Rasterize and `assets.add3D`; an image is refused with a pointer to Object › Image Trace › Make. `crates/effects/src/solids/tests_sources.rs`, `crates/engine/src/cmd/effectcmd/three_d_source_tests.rs` and `fx::tests::a_symbol_instance_a_blend_and_a_clipping_group_draw_their_solids` cover it. Scores and estimates unchanged. @@ -597,7 +598,8 @@ since 2026-10-01. **Drawing tools, Star inner radius held with Ctrl/Cmd:** While a star is dragged out, Ctrl/Cmd keeps the inner radius the star showed when the key went down, also when the key is pressed with the pointer still. `a_star_drag_holds_its_inner_radius_with_ctrl_and_straightens_with_alt` and `a_star_drag_holds_the_inner_radius_it_shows_when_ctrl_goes_down` cover it, with Alt's straight shoulders and a drag canceled with Escape. **Drawing tools, Dimension tool horizontal and vertical linear dimensions:** A linear dimension between two clicked points or dragged out from a segment is aligned, horizontal or vertical, chosen by where the pointer moves while it is placed, and a click again by the second point gives aligned; `dimension.create` and `dimension.update` take `orientation`, and the dimension stays linked to the anchors it measures, keeps its orientation when it or the art turns, with a line that lay outside the points kept outside them; an unlinked horizontal or vertical dimension that is reflected has its line on the reflected side. `the_pointer_chooses_aligned_horizontal_or_vertical`, `two_points_measure_horizontally_vertically_or_aligned`, `clicking_again_by_the_second_point_places_an_aligned_dimension`, `a_segment_drag_measures_horizontally_vertically_or_aligned`, `points_on_a_vertical_line_measure_aligned`, `horizontal_and_vertical_dimensions_draw_lines_along_their_axis`, `turned_horizontal_dimensions_stay_horizontal`, `a_linked_horizontal_dimension_keeps_its_gap_from_turned_art`, `a_linked_horizontal_dimension_below_or_between_its_points_follows_turned_art`, `a_reflected_horizontal_dimension_keeps_its_line_on_the_reflected_side`, `a_dimension_without_an_orientation_reads_as_aligned`, `dimension_orientation_is_checked` and `a_turned_dimension_keeps_its_line_on_its_side` cover it. **Drawing tools, Dimension tool points that are not anchors follow the art:** A clicked point on a segment stays at its place along the segment, also when the segment curves, and a point off the art is linked to anchors (or, when the anchors lie on one line, anchors and handles) of the path, so both ends of the dimension follow when the art is moved, scaled, turned or reflected, also when the point was placed by a Smart Guide and when the dimension is saved and opened again; a linked linear dimension of reflected art (other than art on one line) has its line on the reflected side; deleting the art, changing its anchor count or whether it is closed, turning an angle's arm into a curve, or making a measured circle or arc no longer circular leaves the dimension where it was, no longer linked, instead of removing it. `a_dimension_to_a_point_on_a_segment_follows_the_art_at_both_ends`, `a_dimension_to_a_point_off_the_art_moves_with_the_art`, `a_dimension_whose_art_changes_its_anchors_stays_where_it_was`, `a_dimension_whose_art_is_opened_stays_where_it_was`, `angle_and_arc_dimensions_whose_art_no_longer_fits_stay_where_they_were`, `a_dimension_that_cannot_be_drawn_again_keeps_its_art`, `a_linked_dimension_of_reflected_art_has_its_line_on_the_reflected_side`, `a_dimension_to_a_point_off_a_line_follows_the_line`, `a_point_off_an_arch_is_reflected_with_the_arch`, `a_point_beside_an_almost_straight_curve_follows_it`, `a_point_off_a_loop_with_its_anchors_in_one_place_follows_it`, `a_point_beside_a_reflected_line_moves_as_a_half_turn_would`, `a_point_on_a_segment_stays_on_it_when_the_segment_curves`, `a_linked_dimension_of_a_reflected_curve_has_its_line_on_the_reflected_side`, `a_dimension_of_art_reflected_across_its_points_changes_sides`, `a_dimension_between_paths_reflected_each_in_its_own_way_keeps_its_offset`, `free_points_survive_a_native_file`, `dimension_free_points_are_checked`, `points_off_anchors_are_held_against_the_path` and `a_point_smart_guides_place_is_held_against_the_path` cover it. -**Drawing tools, Dimension tool points on a Smart Guide stay on the guide:** By VectorCraft's own rule, a clicked point that lies on a Smart Guide already, such as a point straight below the first one on the vertical construction guide through it, or one in line with an object's center, stays where the pointer is when no anchor is within 8 pixels and no segment is within the Smart Guides snapping tolerance, instead of moving onto a segment farther than that tolerance and within 8 pixels; with Snap to Grid or Snap to Pixel on, a point stays on the grid or the whole pixel those options give. `a_point_on_a_guide_stays_on_the_guide` covers it. +**Drawing tools, Dimension tool points on a Smart Guide stay on the guide:** By VectorCraft's own rule, a clicked point that lies on a Smart Guide already, such as one in line with an object's center, stays where the pointer is when no anchor is within 8 pixels and no segment is within the Smart Guides snapping tolerance, instead of moving onto a segment farther than that tolerance and within 8 pixels; with Snap to Grid or Snap to Pixel on, a point stays on the grid or the whole pixel those options give. `a_point_on_a_guide_stays_on_the_guide` covers it. +**Drawing tools, Dimension tool second point without construction guides through a first point off the anchors:** By VectorCraft's own rule, with Smart Guides on, the second Linear point does not snap to the construction guides through a first point that is not on an anchor, so a click beside a segment straight below such a first point lands on the segment; after a first point picked on an anchor, the construction guides through it still apply. The second point still snaps to anchors, centers and alignment lines, and with Snap to Perpendicular or Snap to Tangent on, it lands where the line from the first point meets a segment square or grazes a curve. `a_point_on_a_guide_stays_on_the_guide`, `the_second_point_after_an_anchor_lands_on_construction_guides`, `the_second_point_lands_square_to_a_segment_or_grazing_a_curve` and `linear_picks_show_and_snap_to_smart_guides` cover it. **Drawing tools, Dimension tool dimensions selected with their art keep their lines and label:** Object › Expand, Object › Expand Appearance and Object › Path › Outline Stroke leave a dimension selected with art it measures, directly or in selected groups without fills, strokes or effects of their own, as it is and change only the other art; when the new art no longer fits its link, the dimension stays where it was, no longer linked, and undo links it again. `expand_leaves_a_dimension_selected_with_its_art_as_it_is`, `expand_appearance_leaves_a_dimension_selected_with_its_art_as_it_is`, `outline_stroke_leaves_a_dimension_selected_with_its_art_as_it_is`, `a_dimension_selected_with_art_that_has_nothing_to_expand_changes_nothing`, `a_group_effect_expanded_reaches_the_dimension_it_holds`, `expand_keeps_a_dimension_in_its_asset_and_its_variable_binding`, `a_dimension_keeps_no_link_to_the_art_expand_replaced`, `a_dimension_outlasts_the_art_outline_stroke_or_expand_appearance_replaced`, `a_dimension_outlasts_the_stroke_expand_outlined` and `expand_appearance_in_safe_mode_leaves_a_dimension_selected_with_its_art` cover it. **Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views:** `live_trace_result_bounds_exclude_the_retained_bitmap_at_any_angle` checks every TraceView, geometric and visual bounds and rotated result bounds. `live_trace_selection_highlight_excludes_the_retained_source_rectangle` checks result highlights and the existing ordinary-group policy. Shared editing-child traversal also preserves Shaper handling. **Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards:** Shared existing preset definitions are reused; no external preset assets are added. Presets preserve each selected artboard's orientation, and orientation choices apply even when the active board already matches. Fit operations draft bounds until OK, affect only the active artboard and leave artwork in place. Regression coverage checks draft/Cancel, selected-set application, active-only fitting and Undo. @@ -614,11 +616,13 @@ since 2026-10-01. - **Cached canvas frames during viewport changes:** Cached screen textures use their own raster dimensions and pixels-per-point when reprojected. `canvas::tests::cached_frames_keep_their_scale_during_resize_rotation_and_dpi_changes` holds the worker and checks every UV corner against the cached render transform, including isolated viewport-only resize at zero/30-degree rotation, fractional raster dimensions, zoom/pan, changed rotation, monitor-DPI changes in both directions, Pixel Preview and replacement-frame delivery. The contributor rebuilt and confirmed the original resize issue is fixed with their own artwork on 2026-10-19; the subsequent upstream rebase is checked by regressions and full CI. The artwork stays local. Scores and estimates are unchanged. - **PDF editable import:** Place from bytes or a path with `link: false`, and `clipboard.importPdf` followed by Paste, preserve live type on the selected page. Place still honors `textAs: "outlines"`. Synthetic two-page regressions: `crates/engine/src/cmd/fileio/tests_pdffidelity.rs`. No change to the PDF reader's existing fallback rules. - **Tab stops in `.ai`/EPS type and right-aligned lines with tabs (#6147):** type from the text document keeps its paragraphs' tab stops (key 30: positions and left, center, right and decimal alignments; leaders aren't read), at most 1,024 a paragraph and 2^20 a story, past which the default stops apply with a warning. In right-aligned area type, the text before a line's last tab sits at its stops, measured from the left edge, and the text after it (none when the tab ends the line, with its hyphen when the line is hyphenated) against the right edge; centred and justified lines, point type and right-to-left paragraphs are aligned as a whole as before. Evidence: `ate::tests::a_paragraph_keeps_its_tab_stops`, `ate::tests::a_story_s_tab_stops_are_bounded`, `tests::right_aligned_area_type_sets_the_text_after_its_last_tab_against_the_edge`, `import_fuzz::text_frames_with_hostile_paragraph_attributes_never_panic`. Scores unchanged. +- **`.ai`/EPS graphic styles that paint with a named gradient:** a graphic style library's style (or a file's listed style) whose fill, or the fill or stroke of a style of one paint, paints with one of the file's gradients by name loads with that gradient at the style's angle, fitted to the bounds of each object it is applied to (VectorCraft's own placement; the style stores only the gradient's name and angle). A style naming a gradient the file doesn't define, or painting with a pattern, is still left out. Evidence: `fileio::tests_aiimport::graphic_styles_in_a_ai_library_that_paint_with_a_named_gradient_load_with_it`, `style::tests::a_style_of_one_paint_reads_as_the_fill_and_stroke_its_xd_turns_on`. Scores unchanged. - **`.ai`/EPS type laid out closer to the file's page (#6137):** type from the text document keeps auto leading as auto, each line taking the paragraph's Auto Leading share (key 7) of the largest type on it ([Line and character spacing](https://helpx.adobe.com/illustrator/using/line-character-spacing.html)); the paragraph's hyphenation options (keys 10 to 15) are read; area type of one frame whose last lines the file sets, but which don't fit here, may get a frame taller from its bottom, by its lines' deepest descent plus 0.05 pt and only when that shows more of those lines and no more than the file has (`vectorcraft_text::fit_source_lines`), with a warning when it does: the frame can stay as it is, or show only some of them; and a line a soft return ends is justified as a wrapped line is, a paragraph's last line keeping its alignment. Evidence: `ate::tests::auto_leading_follows_the_size_of_each_line`, `ate::tests::a_paragraph_keeps_its_auto_leading`, `ate::tests::a_paragraph_keeps_its_hyphenation_options`, `ate::tests::the_last_lines_the_file_sets_in_its_frame_show`, `tests::fit_source_lines_keeps_the_last_lines_the_source_sets`, `tests::typo::soft_return_in_justified_text_spreads_like_a_wrapped_line`. Limits: frames grow only for area type of one frame, horizontal, by its lines' deepest descent plus 0.05 pt; type in a font that isn't installed, and hyphenation in a language that isn't imported, still lay out differently. Scores unchanged. - **Selected Grid Repeat handles (#2691):** `tools/src/repeat_grid.rs` tests place the handles outside the grid at zoom 0.5, 1 and 4, preview rows, columns and spacing, leave no undo step for a drag that ends where it began, and give bounding-box handles priority; a headless canvas regression drags the row handle two tiles down in a zoomed view (3 → 5 rows, the source unchanged, one Undo back) and the column-spacing slider. Scores and hours unchanged. - **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 that makes copies:** the Transform effect can make copies with its transformation applied ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html)). Giving each copy the raster effects listed before that effect is VectorCraft's own rule. On a path or compound path, each copy now carries the Drop Shadow, glow, blur, Feather or pixel filter listed before the last Transform effect that makes copies, with its sizes scaled by that copy's mean scale and a Drop Shadow's offset turned, reflected and scaled with the copy; a raster effect listed after it paints once around all the copies. Before, one shadow was drawn under all the copies at the object's own distances. The canvas, the object's bounds, export and Expand Appearance draw the same copies, and copies that stop at the effect budget each keep their effects (effects `tests::rasterfollow::each_copy_of_a_transform_effect_carries_the_shadow_listed_before_it`, `tests::rasterfollow::a_shadow_after_a_copying_transform_paints_once_around_the_copies`, `tests::rasterfollow::copies_past_the_budget_each_keep_their_shadow`; render `objectfx::each_copy_of_a_transform_effect_draws_its_own_shadow`; engine `objexpand::each_copys_shadow_expands_as_the_canvas_draws_it`). A Transform effect without copies draws as before. Not yet: the copies of type, images, symbol instances and groups, and a fill's or stroke's own copying Transform effect, still share one set of raster effects, and so does a path with Rasterize, an SVG filter or another effect that is neither a geometry effect nor one of those raster effects before the copying effect. 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. @@ -627,6 +631,7 @@ since 2026-10-01. - **Warp as a Bézier patch per style:** each of the fifteen Warp styles bends the object's bounds as one Bézier patch whose control points the style sets from the bend and the size of the bounds; the horizontal distortion then scales each column of control points about its middle and the vertical distortion scales each row. The Warp effects and warp envelopes share the map, and content with no width or no height takes the middle of the patch along that side. New warps, the built-in graphic styles' Warps and warps opened from `.ai` files carry `version` 1 for it. Warps in `.vectorcraft` documents saved before it read as `version` 0 and keep their earlier look, and edits keep a warp's version; a `version` 0 warp saved to `.ai` opens again with `version` 1, since the file holds only its settings. The patches are VectorCraft's own rules; the styles and ranges are those of the Warp options in [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html) (doc `live::tests::warp_nets_bend_each_style_as_its_own_patch`, `warp_net_arc_edges_are_concentric_circles`, `warp_net_distortion_scales_the_columns_then_the_rows`, `warp_net_takes_any_numbers`, `warp_net_bends_a_huge_box_without_overflowing`, `warp_envelopes_bend_flat_content_as_the_middle_of_the_patch`, `warp_envelopes_write_their_map_version_only_when_it_has_one`, `style_libs::tests::builtin_warp_styles_take_the_nets_map`; effects `tests::a_warp_draws_with_the_map_its_version_names`, `tests::a_warp_bends_a_flat_box_as_the_middle_of_its_patch`, `tests::new_warps_take_the_nets_version`; engine `effectedit::warps_keep_the_map_their_version_names`, `envelope::new_warp_envelopes_take_the_net_and_saved_ones_keep_their_map`; eps `ai_editing::tests::every_effect_a_graphic_style_holds_is_read_back`, `import::ai::tests::a_warp_envelope_opens_live`, `import::ai::tests::warp_envelopes_read_every_style`, `import::ai::style::tests::a_stack_of_fills_with_effects_of_their_own_is_read_as_itself`; ui-egui `dialogs::tests_warp::warp_options_edit_keeps_each_targets_map_version`). Scores and hours unchanged. - **Warp effects bend images:** a Warp effect on an image, or on a group that holds one, bends the image's pixels with its frame, as the Warp effect is documented to distort bitmap images in [Reshaping with effects](https://helpx.adobe.com/illustrator/using/reshaping-objects-effects.html): after the last effect, the image is cut into 10 × 10 cells of two triangles, each a clipped piece under its own affine map. Effects after the Warp reshape only the frame, a second Warp bends the same pieces, and warps saved without a version bend the pixels with their earlier map, as they bend the frame. A placed gradient on a group that holds the image follows the group's bounds as the pieces draw them. SVG writes the image once for the pieces; PDF, EPS, `.ai` and PNG write the bent pieces. The images stay unbent when their pieces would make the art pass 2 million objects, and so does an image whose frame keeps its shape past the anchor budget. A grayscale image's fill color now colorizes the pieces of a warp or an envelope, and an image under any geometry effect keeps that color and its smoothing setting. Existing documents with a Warp effect on an image, or on a group that holds one, draw differently: before, the image showed unbent, cut by the bent frame. So do existing documents with a colorized image under an envelope or a geometry effect, or an image drawn without smoothing under a geometry effect: before, those lost the color or the setting. The cell count and the limits are VectorCraft's own (effects `tests::warped_images_stay_within_the_object_budget`, `tests::warped_images_keep_document_keys_and_hidden_images_apart`, `tests::an_image_whose_frame_passes_the_budget_stays_whole`, `tests::effects_after_a_warp_reshape_an_images_frame_and_not_its_pieces`, `tests::an_images_pixels_take_the_map_their_warps_version_names`, `tests::an_image_under_a_geometry_effect_keeps_its_color_and_smoothing`, `tests::a_nested_groups_gradient_follows_its_warped_image`; engine `warp_images::an_images_pixels_bend_with_effect_warp`, `a_warped_image_keeps_its_bend_in_svg`, `a_warped_image_keeps_its_bend_in_pdf`, `a_warped_image_keeps_its_bend_in_ai`, `a_warped_image_keeps_its_bend_in_eps`, `a_warped_image_keeps_its_bend_in_png`, `svg_writes_an_image_clipped_twice_in_a_users_group_twice`, `expand_appearance_of_a_warped_image_draws_as_the_canvas_did`, `a_colorized_image_keeps_its_color_when_warped`, `a_warp_on_a_group_bends_the_image_in_it`, `envelope_distort::a_colorized_image_keeps_its_color_in_an_envelope`). Scores and hours unchanged. - **`.ai` files keep an image's Warp live:** an embedded image whose appearance is one Warp effect, with no opacity mask, is saved to the `.ai` editing data with an art style of that Warp: its bent pieces are its drawn look, and the image itself follows on `%_` lines, as for other styled objects. Opening an `.ai` file reads such an image as the image with its Warp live, its pixels, placement, name and opacity kept, when the live warp draws as the file's drawn look and the import has a comparison left; otherwise the drawn look stays, with the drawn-look note. The Warp effect applies to bitmap images ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html)), and native files keep live effects ([the help page](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/supported-file-formats-in-illustrator.html)). Images with an opacity mask, and images with a Warp and another effect or with another geometry effect, are saved and opened as their drawn art. Existing `.ai` files with an embedded image on `%_` lines open differently: before, that image also came in beside its drawn look. Which images keep the Warp and the comparison are VectorCraft's own rules (eps `ai_editing::tests::an_image_with_a_warp_reads_back_with_its_warp_live`, `an_image_whose_warp_draws_otherwise_than_its_look_keeps_its_look`, `an_image_on_hidden_lines_does_not_come_in_beside_its_look`, `other_warped_images_are_written_as_their_drawn_art`, `import::ai::read::ops::tests::an_image_takes_a_style_of_one_warp_alone`). Scores and hours unchanged. +- **`.ai` saves count images with a Warp against the envelope limit:** opening an `.ai` file compares at most 256 envelopes and images with a Warp with their drawn art, and saving the `.ai` editing data now counts both against those 256, in the order they are written. An image with a Warp past them is saved as its drawn look, without its Warp, and an envelope past them as its distorted art, each with a warning on saving. An image with a Warp whose pixels can't be read is saved as its gray outline and is not counted. Before, saving counted only envelopes, so images with a Warp were saved live past the 256 without a warning, and the file opened with the ones past them as their drawn art. The limit of 256 is VectorCraft's own (eps `ai_editing::tests::warped_images_past_the_readers_checks_are_written_as_their_drawn_look`, `envelopes_get_the_checks_warped_images_left`, `a_warped_image_written_as_its_outline_takes_no_check`, `an_unreadable_warped_image_past_the_checks_is_warned_about_its_pixels`). Scores and hours unchanged. - **`.ai` files keep a linked image's Warp live and its link:** a linked image whose appearance is one Warp effect, with no opacity mask, is saved to the `.ai` editing data with an art style of that Warp, as an embedded one is: its bent pieces are its drawn look, and the image itself follows on `%_` lines as a placed file with its path, its folder relative to the document's and its preview. Before, it was saved as its drawn art and its live Warp was lost. Opening the file reads it as the linked image with its Warp live, its link, pixels, placement, name, opacity, hide and lock kept, under the same drawn-look comparison; a hidden image with a Warp, embedded or linked, is now compared with its look drawn shown, and keeps its Warp too. A linked image with a Warp in an opacity mask's art keeps its Warp and is embedded, with the existing warning for linked images in masks. Linked files stay connected to their source and track it by relative path ([the help page](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/manage-linked-and-embedded-files/links-panel-overview.html)); the placed-file form is the one the `.ai` reader reads (`crates/eps/src/import/ai/read/art.rs` `end_place`). eps `ai_editing::tests::a_linked_image_with_a_warp_reads_back_linked_with_its_warp_live`, `a_large_linked_image_with_a_warp_reads_back_from_its_preview`, `a_hidden_or_locked_image_with_a_warp_keeps_its_state`, `a_linked_image_with_a_warp_in_a_mask_is_embedded_with_its_warp_live`. Scores and hours unchanged. - **EPS writes a repeated image's samples once:** an image drawn more than once in an EPS file (the pieces of an envelope or a Warp effect, copies of one image, or one image in a symbol's instances) has its compressed samples written once in the setup, and each placement reads them from there: a reusable stream rewound for each placement at Language Level 3 ([PostScript Language Reference, 3rd ed., §3.13](https://www.adobe.com/jp/print/postscript/pdfs/PLRM.pdf)), and an array of strings of at most 49,152 bytes fed to the image by a procedure at Level 2. An image drawn once is written where it is drawn, as before. The 256 MB limit on the page counts the samples once, so an envelope of a large photo no longer loses pieces to it. A colorized image is reused per ink (eps `tests::an_image_placed_twice_writes_its_samples_once_at_both_levels`, `tests::an_envelopes_image_pieces_draw_one_copy_of_its_samples`, `tests::each_ink_of_a_colorized_image_placed_twice_is_written_once`, `tests::samples_longer_than_a_string_are_reused_at_both_levels`, `tests::the_page_limit_counts_a_repeated_images_samples_once`). Scores and hours unchanged. - **`.ai` files write a warped image's pieces as the parts they show:** in the `.ai` editing data and in legacy `.ai` files, an embedded image cut to a clipping path (in the editing data, also an image under an opacity mask that clips) is written with all of its pixels the first time, and every later copy of the same pixels is written as the rectangle of them that the path or mask shows, 2 pixels more on each side, placed where it lies in the image. The pieces of a Warp effect, an envelope or their expanded art, 200 copies of the image for 10 × 10 cells before, now hold about 7 times the image's pixels in all for a 64 × 64 image. A copy whose opacity mask is left out, nested too deep or past the object limit, keeps all of its pixels. Each image's pixels are read once for the pieces that follow one another. An image cut to a rectangle of half its pixels or more, and the first copy written, keep all of their pixels. The `XI` operator's arguments give an image's location and size ([AI file-format specification, §8.1](https://web.archive.org/web/20050126105313/https://partners.adobe.com/public/developer/en/illustrator/sdk/AI7FileFormat.pdf)); the 2-pixel margin and the half-the-pixels limit are VectorCraft's own rules (eps `ai_editing::tests::the_pieces_of_a_warped_image_are_written_as_the_parts_they_show`, `masked_pieces_of_a_warped_image_are_written_as_the_parts_they_show`, `an_image_with_a_live_warp_writes_its_pixels_whole_once`, `a_clipped_image_written_first_keeps_all_of_its_pixels`, `a_masked_copy_whose_mask_is_left_out_keeps_all_of_its_pixels`, `a_masked_copy_nested_too_deep_for_its_mask_keeps_all_of_its_pixels`, `legacy_ai::tests::the_pieces_of_a_warped_image_are_written_as_the_parts_they_show`). Scores and hours unchanged. @@ -647,6 +652,7 @@ since 2026-10-01. - **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`. - **Start Global Edit is offered only for a group it can start on:** with a group selected, Select › Start Global Edit is disabled, and the Properties panel's Quick Actions and the Control bar do not offer it or its options, when the group holds type, an image or nothing, at any depth; the check walks the group's objects the same way, stopping at the first one Global Edit does not take. This is VectorCraft's own rule. Regression test: `start_global_edit_is_offered_only_for_a_group_of_supported_objects` in `crates/engine/src/tests/globaledit.rs`. +- **Global Edit takes rotated copies:** Select › Start Global Edit on an object or group also takes its rotated copies, with the highlights before the start and the options' Results count, and an edit reaches each copy turned by its angle, as copies of a group rotated around a point are edited at once ([Design a modern geometric logo](https://helpx.adobe.com/vn_vi/illustrator/how-to/modern-logo-design.html)). Under VectorCraft's own rules, a copy's angle is the one that lays the selected object's anchors and handles on the copy's in order, each within a millionth of the larger side of the copy's box; a reflected copy is not taken; and with Size, a rotated copy has the same size when it is the object rotated without scaling. Regression tests: `start_global_edit_takes_rotated_copies_*`, `a_rotated_copy_leads_*`, `size_takes_a_rotated_copy_*`, `a_square_whose_anchors_were_turned_*`, `rotated_groups_are_like_the_group_*` and `a_rotated_symbol_instance_*` in `crates/engine/src/tests/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`. - **Control bar docks to the top or the bottom, or floats:** the Control bar's panel menu, at the bar's right end, has Dock to Top and Dock to Bottom, the edge in use checked and neither while the bar floats. Dragging the bar's gripper and releasing it within 24 points of the top (under the menu bar) or the bottom of the window docks it at that edge, with a band along that edge while it moves; releasing it farther from both edges floats the bar there, with its outline under the pointer while it moves, and a floating bar's gripper moves it or docks it again (`window.control.dock {edge: "top"|"bottom"|"float"}`), as the help page describes ([Control panel overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/control-panel-overview.html)). Escape cancels a gripper drag. The 24-point zones, the floating bar's 800-point width and first position, a release outside the window leaving the bar where it was, a window too short for a floating bar docking it at the nearer edge, the floating bar staying inside a window that shrinks, and keeping the edge and the floating position with the workspace, with older workspaces docking the bar at their edge, are VectorCraft's own rules. Regression tests: `the_control_bar_panel_menu_docks_it_to_the_top_or_the_bottom`, `dragging_the_control_bar_gripper_docks_it_at_the_nearer_edge`, `dragging_the_control_bar_gripper_away_from_both_edges_floats_it`, `floating_control_bar_moves_and_redocks_from_each_edge`, `floating_control_bar_menu_docks_to_either_edge`, `control_bar_drag_escape_restores_placement`, `control_bar_drag_release_outside_window_keeps_previous_placement`, `floating_control_bar_stays_reachable_in_tiny_and_resized_windows`, `the_control_bar_dock_command_takes_top_bottom_or_float` and `menus_stop_above_a_control_bar_docked_at_the_bottom` in `crates/ui-egui/src/chrome/tests.rs`, `saved_workspaces_restore_the_control_bar_edge` and `saved_workspaces_restore_floating_control_bar_position` in `crates/ui-egui/src/workspaces.rs`. - **Control bar panel menu turns groups of options on or off:** the Control bar's panel menu lists the bar's groups of options (Snapping, Anchor Points, Tool Options, Object Options, Image Options, Fill and Stroke, Opacity, Graphic Style, Character, Paragraph, Vertical Alignment, Align and Distribute, Transform, Artboard Options and Document Options) above Dock to Top and Dock to Bottom, each checked while it is on; a click turns that group off or on (`window.control.options {group, visible?}`), and a group that is off stays out of the bar even while its tool or object is selected, as the help page describes ([Control panel overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/control-panel-overview.html)). The list of groups and what each holds, every group on to start, a group that is off leaving its room to the groups after it, and keeping the groups with the preferences and the workspace are VectorCraft's own rules. Regression tests: `the_control_bar_panel_menu_turns_each_group_on_or_off`, `the_control_bar_keeps_its_label_and_menu_with_every_group_off`, `the_control_bar_panel_menu_scrolls_in_a_short_window`, `the_control_bar_options_command_turns_a_group_on_or_off`, `groups_that_are_off_leave_their_room_to_the_later_groups`, `the_artboard_tool_s_control_bar_follows_its_two_groups` and `the_anchor_points_group_holds_convert_and_anchors` in `crates/ui-egui/src/chrome/tests.rs`, `the_image_options_group_holds_the_image_and_trace_controls` in `crates/ui-egui/src/tests/place.rs`, `the_character_and_paragraph_groups_hold_the_type_controls` in `crates/ui-egui/src/panels/paragraph/tests.rs`, `saved_workspaces_restore_the_control_bar_groups` in `crates/ui-egui/src/workspaces.rs`. @@ -682,7 +688,9 @@ since 2026-10-01. - **COLR colour fonts:** v0 and v1 glyphs draw as vector layers (solid colours, linear and radial gradients, including ones that repeat or reflect, clips, blend modes, the foreground colour from the run's fill) on the canvas, as paths in SVG, EPS, legacy `.ai` and PDF with outlined text, as Type 3 text in PDF, and as editable groups with Create Outlines; sweep gradients, Porter-Duff compositing and radial gradients that repeat or reflect and start at a circle draw the glyph as an image. Measured by `tests_colr`, `render::tests_colrglyphs`, `pdf::tests::colr_glyphs_export_as_vector_art`, `svg/tests/it/colour_glyphs.rs`, `eps` `colr_glyphs_*`, `tests_pathops::create_outlines_turns_colr_glyphs_into_layer_groups`. Scores unchanged (estimated). - **OpenType SVG colour fonts:** each glyph's SVG document is read by the SVG importer (registered by the engine) into vector art in the run's colours, then drawn, exported and outlined as COLR glyphs are; PDF real text writes them as text that draws nothing and draws their art where they sit. Measured by `tests_svg_glyphs`, `svg/tests/it/svg_glyphs.rs`, `tests_colourfonts::create_outlines_turns_svg_glyphs_into_groups`, `tests_colourfonts::pdf_real_text_draws_svg_glyphs_as_art_and_keeps_their_characters`. Scores unchanged (estimated). - **Create Outlines keeps the type object's own appearance:** Type › Create Outlines and Object › Expand put the type object's own fills and strokes (the Appearance panel's items around its Characters row) on paths of the whole outline, below or above the glyph paths as that row places them, with one gradient across every glyph, so the outlines draw what the type drew; `object.expand.info` reports those strokes, pattern fills and gradient fills. Outlined characters keep their stroke and fill (the help page, <https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=337>); a type object's appearance is separate from its characters' (the help page, <https://helpx.adobe.com/illustrator/using/appearance-attributes.html>); where the object's items go is VectorCraft's own rule. Measured by `tests::pathops::create_outlines_keeps_the_objects_own_fills_and_strokes`, `tests::objexpand::create_outlines_draws_the_type_objects_own_paint`, `tests::objexpand::type_objects_own_stroke_pattern_and_gradient_are_reported`, `tests::objexpand::type_without_an_outline_reports_no_own_stroke_or_fill`, `tests::objexpand::a_stroke_under_an_unpainted_stroke_is_reported_and_outlined` and `tests::objexpand::expand_keeps_the_type_objects_own_paint`. Scores unchanged (estimated). +- **Create Outlines keeps the characters' gradients across the type:** Type › Create Outlines and Object › Expand give every glyph, ruby glyph and underline or strikethrough bar the gradient its characters drew with: a gradient with no vector of its own stays fitted to the whole layout rather than to each glyph, and one with a vector keeps its place, both moved, scaled and rotated with the type; the characters' stroke keeps the weight it was drawn at on scaled type. `object.expand.info` measures gradient fills on the same paths. Outlined characters keep their stroke and fill (the help page, <https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=337>); the gradient fitted across the whole layout is VectorCraft's own rule. Measured by `tests::objexpand::create_outlines_keeps_a_character_gradient_across_the_type` and `tests::objexpand::expand_keeps_a_character_gradient_across_the_type`. Scores unchanged (estimated). - **Composite fonts that two documents define differently:** when two open documents each define a composite font (Type › Composite Fonts…) by the same name with different parts, each document draws and exports its type in its own definition: in a tiled or floating window drawn while the front document draws, when it is placed in a document that defines the name differently, and in an export made while another document is in front. Evidence: `tests::composite::nested_loans_of_one_name_use_each_documents_definition` and `threads_lending_one_name_at_once_use_their_own_definitions` (`crates/text`), `tests::fontchange::a_placed_document_draws_its_own_definition_of_a_name_the_page_defines` (`crates/render`). Scores unchanged (estimated). +- **Composite fonts only another document defines:** a document draws, measures and exports its type only in the composite fonts it defines itself. Type naming a composite font that only another open document, or the document a placed document sits in, defines is set as in a missing font, also when the document defines no composite font: in a window, a thumbnail or an export of a document in the back, in a file being opened and in a placed document. A temporary document drawn while a document draws keeps that document's composite fonts. Evidence: `tests::composite::a_lent_document_does_not_use_another_documents_composite_font` and `a_document_without_composite_fonts_uses_none_and_a_preview_is_unchanged` (`crates/text`), `tests::fontchange::a_placed_document_draws_its_own_definition_of_a_name_the_page_defines` and `a_document_draws_type_in_another_documents_composite_font_as_missing` (`crates/render`), `a_document_replaced_in_the_back_measures_a_font_it_lacks_as_missing` (`crates/engine`). Scores unchanged (estimated). - **Character-style Auto leading:** capture and explicit style attributes retain Auto as a reset, distinct from omitted leading. Redefine and later numeric updates preserve local leading overrides; the Character Styles marker recognizes Auto correctly. Regression assertions cover partial definitions, Undo/Redo and native save/load serialization. Public references: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html) and [Leading](https://helpx.adobe.com/illustrator/using/line-character-spacing.html). - **Character-style numeric bounds:** `charStyle.new`, `charStyle.edit`, and `charStyle.setAttrs` accept size from 0.1 to 1296 pt, explicit leading from 0.1 to 5000 pt, horizontal and vertical scale from 1% to 10,000%, and baseline shift and Tate-chu-yoko offsets from -1296 to 1296 pt. Out-of-range input leaves the style and Undo history unchanged; Auto leading remains available. These limits match the Character panel controls. - **Character Style Options, General and Basic Character Formats:** the dialog edits a style's name and stored character formats together. Empty fields remain unset, checkboxes show an indeterminate unset state, Basic's Reset Panel clears its explicit settings, and Preview can be canceled without changing history. OK saves one undo step; New Character Style offers the same fields from captured text or the interface language's defaults without a selection. Public reference: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). @@ -737,8 +745,9 @@ 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`. - **Canvas through the display's profile on Windows and X11:** Preferences › Performance › Use Monitor Profile for Canvas (on by default) converts the canvas's art, artboard paper and transparency grid from sRGB into the ICC profile of the display that shows most of the main window, after any proof, as the help page describes the monitor's profile translating the document's colors for the monitor ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=151)). Windows gives the display's default profile, and a display with Advanced Color on is left to Windows ([Microsoft Learn](https://learn.microsoft.com/en-us/windows/win32/wcs/advanced-color-icc-profiles)); X11 gives colord's profile for the output or the `_ICC_PROFILE` property. macOS converts the window itself, and a Wayland session stays sRGB. `ui.inspect` reports `displayProfile`. Tests in `color/src/cms/display.rs`, `ui-egui/src/display_profile.rs` and `canvas::tests::the_canvas_is_drawn_through_the_display_profile_while_the_preference_is_on`. +- **Translucent art blended before the display profile:** with Use Monitor Profile for Canvas converting, translucent art and the anti-aliased edges of art over an artboard's paper, a colored artboard or the transparency grid are blended with it in sRGB and the blend is converted, so the monitor's profile translates the document's colors as they are composited ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=151)). The frame rendered whole, the part an edit renders again, the render worker's frame, the pan fill and the other windows' panes do the same; over the pasteboard and in Outline the art is converted on its own, and with no profile to convert into nothing changes. Tests `display_profile::tests::translucent_pixels_over_the_paper_are_blended_before_they_are_converted`, `the_transparency_grid_is_blended_cell_by_cell`, `the_backdrop_is_found_through_the_view` and `canvas::tests::translucent_art_over_the_paper_is_blended_before_the_display_profile`. - **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`. +- **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. With Window › Arrange › Tile or floating document windows, each document behind the front one draws its art, paper and transparency grid through its own assigned profiles, and loading or removing a profile redraws the documents assigned it; placed documents inside it still draw through the front document's profiles. How documents behind the front one draw is VectorCraft's own rule. 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`, `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). @@ -773,6 +782,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Variables: Lock Variables (`variable.lock`, in the Variables panel's bottom bar and menu) stops variables from being defined, deleted or renamed until they are unlocked, while objects can still be bound and unbound and data sets still change and apply; the lock is saved with the document. - Batch…: Override Save and Override Export name each file with the extension of the format the step writes, however the step spells the format (`.svg` and `SVG` give `.svg`, `png8` gives `.png`), in `action.batch`. - Batch…: Override Export writes the files of an Export for Screens or Export Assets step into a folder for each source file or data set inside the destination folder, under the names the export gives them (`action.batch`). The folder and file names drop trailing periods and spaces (`a..svg` gives `a`). When two source files would get the same name that way (compared without case), or a later file's folder or file would take the name of an output an earlier file wrote, of a source file in the destination folder or, for data sets, of a file already there, Batch adds `-2`, `-3`… to the later one's name. + - Batch…: when a step fails on a file or data set, the error names the step by its place in the action's steps, from 1, counting the Open steps the batch skips (`action.batch`). This numbering is VectorCraft's own rule. Tests `cmd::fileio::action_batch::tests::{a_folder_batch_error_names_the_step_in_the_commands_sent, a_recorded_open_that_fails_is_the_first_step, a_data_set_batch_error_names_the_step_in_the_commands_sent, a_redirected_export_that_fails_keeps_its_place, a_source_that_does_not_open_names_no_step}`. - Actions panel menu: Save Actions… writes the current action set with all its actions to a file, and Load Actions… adds the set from such a file to the panel ([Manage a set of actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/manage-a-set-of-actions.html); `ui.actionSet.save`, `ui.actionSet.load`). The file is VectorCraft's own action set file (`.vcactions`); a loaded set named like one in the panel gets the next free number. - Actions panel menu: Load Actions… keeps a step whose command this build or its installed plug-ins do not have, and reports each one when the set loads: the `ui.actionSet.load` answer lists the action, step and command id (`unknownCommands`, `unknownCount`), and the status bar names the first and the count. An action with such a step included does not play, and the error names the step and its id before any step runs; an excluded one does not stop it. These are VectorCraft's own rules. Tests `panels::actions::tests::{load_actions_reports_steps_with_unknown_commands, load_actions_bounds_what_it_reports_of_unknown_commands, an_action_with_an_unknown_command_does_not_play}`. - Actions panel menu: Save Actions… does not write a set with a step that sets a folder preference (the Fonts, Plug-ins, Templates and Recovery folders and the two scratch disks) to a folder, and names the action and the preference instead; an empty folder and the scratch disk choices Startup and None save. Export Preferences leaves out both scratch disks, and `ui.inspect` under automation read roots leaves such a folder outside them out of recorded steps. These are VectorCraft's own rules (`ui.actionSet.save`, `prefs.export`). @@ -799,6 +809,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Batch… over data sets offers None, Save and Close and Folder as the destination, as for a folder source. Save and Close saves the open document over its own file after each data set, so the file keeps only the last data set, unless a recorded Save step that Override Save points into the destination folder first makes each data set's file the document's own. A recorded Save, Save a Copy, Save as Template or export step that writes a file and that the batch does not point into the destination folder (destination None, Override Save or Override Export off, or a copy, template, PDF, EPS, DXF, Save for Web or Save for Office Documents step) also writes the same file for every data set. In either case the dialog shows a warning and `action.batch` returns a `warning`. Unless a recorded Save or Save As step writes a file and makes it the document's own first, `action.batch` refuses Save and Close over the data sets of a document that was never saved, was converted from an older version or was restored by Data Recovery. - Export for Screens: the dialog's Example line shows the path of the file the export writes first, sub-folder included, named as the export names it, for the first chosen artboard, asset, layer or object (`document.exportForScreens`). - Export presets: the Asset Export panel menu lists the export presets of Export for Screens, with Import Preset… and Export Preset…, which read and write `.vcexportpresets` files (`document.exportPresets.import`, `document.exportPresets.export`). An imported preset whose name is taken gets a number. In the panel, a preset applies to the shared export settings (`assets.settings.set {exportPreset}`), and Save Preset… saves them. With Create Sub-folders off, the panel's Export writes every file into the folder itself, mobile and density rows included. + - Export for Screens artboard names can be double-clicked to rename them in grid or list view (#7275). Enter, a click outside the field or switching to Assets commits the name; Escape cancels the edit. The dialog stays open, checked artboards stay selected and the rename is undoable. The typed name goes to the artboard that was double-clicked even when the artboards change order while it is typed; the field closes when its artboard is deleted or another document becomes active. Evidence: `dialogs::tests_screens::double_clicking_an_artboard_name_in_export_for_screens_renames_it`, `dialogs::tests_screens::switching_export_tabs_commits_an_artboard_name`, `dialogs::tests_screens::an_artboard_name_follows_its_artboard_while_it_is_typed` and `dialogs::tests_screens::an_artboard_name_stays_with_its_document`. + - Asset Export panel menu: Create Sub-folders (on by default) and Open Location after Export are check items that set the dialog's two checkboxes (`assets.settings.set {subfolders, openLocation}`), and the panel's Export follows them, including a folder per format or item that Export for Screens remembers (3D assets' mesh files go in the folder itself); Format Settings… opens Export for Screens on the first row's format settings ([Asset Export panel](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/collect-and-export-assets-from-asset-export-panel.html)). Tests: `panels::tests_asset_export`. - Export for Screens is laid out as the reference app's dialog: on the left the Artboards and Assets tabs (thumbnails with their checkboxes, number and name, in a grid or a list), Clear Selection and Prefix; on the right Select (All, Range, Include Bleed, Include Artboard Fill, Full Document), Export to, Open Location after Export, Create Sub-folders by Scale or by Format (on by default), Export PDFs As (Single File writes the chosen artboards as the pages of one PDF named after the document, `pdfs: "single"`), and the format rows with the iOS and Android buttons, the format presets (☰) and Format Settings; under them, how many items are selected and how many files the export writes. File name patterns, the Layers and Selection sources and per-item folders stay available through `document.exportForScreens` (scripts and MCP). Tests: `dialogs::tests_screens` (layout, iOS/Android, Clear Selection, sub-folders, Single File) and `fileio::tests_screens::single_file_pdfs_hold_every_chosen_artboard`. - Save for Web: Preview in Browser writes each preview's page and images to a folder of its own inside `VectorCraft Save for Web` in the system's temporary folder. A later preview, from the same app or another one running, does not overwrite an earlier one. Each preview first removes the preview folders there that are an hour old or older and, on Linux, macOS and FreeBSD, belong to the current user; it leaves other files and folders alone. The folders a preview makes there are open to their owner only on those systems. When `VectorCraft Save for Web` is a link or is not a folder, or on those systems belongs to another user or can be written by other users, the preview goes to a new folder of its own in the temporary folder, which a later preview removes once it is an hour old (`file.saveForWeb.browser`). - Export for Screens, Save for Web (slice images, and files named after the document's title) and the Libraries panel name files with the characters Windows does not allow written as `-` and with a `-` after a Windows device name such as `CON`, on every platform (`document.exportForScreens`, `document.exportForWeb`, `library.create`). @@ -806,9 +818,10 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Export for Screens numbers distinct row files whose names collide, compared without case, as `-2`, `-3`… instead of leaving them out; identical rows still write one file. It puts row folders that differ only in case into one folder (`document.exportForScreens`). - Variables: Import Data Sets… (`dataset.import`) reads tab-separated files as well as comma-separated ones. Every header cell is a variable, and the rows replace the document's data sets as Data Set 1, Data Set 2 and so on. An import error about a row's values gives the file line the row starts on. - Variables: Import Data Sets… (`dataset.import`) reads a UTF-16 file without a byte-order mark, instead of refusing it, when at least half of its two-byte units hold a NUL byte; it uses the byte order that reads its line breaks. + - Graphs: the Graph Data window's Import Data reads a UTF-16 text file without a byte-order mark by the same rule as Import Data Sets…, instead of filling the cells with NUL characters. It reads a file cut short by one byte, or with an unpaired surrogate, as it reads one after a byte-order mark. - Variables: Import Data Sets… (`dataset.import`) defines the variables a file's header names that the document lacks, unbound. `#Shown` defines a visibility variable, `@Photo` defines an image variable, and a header without a prefix defines a text variable. A header that is a variable's exact name keeps naming it, and any other `%` header (graph data files) is refused. - - Variables: Load Variable Library… in the Variables panel menu (`variable.loadLibrary`) replaces the document's variables and data sets with a variable library's, read from its XML file, in one undo step: every data set is deleted, and every variable is deleted with its bindings and values, except a text variable the library also declares, which stays bound so the library's data sets change its objects (#4136); then the library's other text variables are defined, unbound, and its data sets take the text of each value's `p` elements, one paragraph each. Variables of other kinds are left out with a warning that names their kinds. - - Variables: Save Variable Library… in the Variables panel menu (`variable.saveLibrary`) writes the document's text variables and data sets as a variable library's XML file, which Load Variable Library reads back with the same text variables, data set names and text values. Variables of other kinds are left out with a warning that names their kinds. + - Variables: Load Variable Library… in the Variables panel menu (`variable.loadLibrary`) replaces the document's variables and data sets with a variable library's, read from its XML file, in one undo step: every data set is deleted, and every variable is deleted with its bindings and values, except a variable the library also declares with the same kind, which stays bound so the library's data sets change its objects (#4136); then the library's other variables are defined, unbound: text, visibility, image (linked file) and graph variables, and variables without a known `trait` as unknown. Its data sets take text values from each value's `p` elements, one paragraph each, visibility values from `true` or `false`, image values from a file's absolute path or `file:` URL, and graph values from a `data` element of series names and rows. + - Variables: Save Variable Library… in the Variables panel menu (`variable.saveLibrary`) writes the document's variables of every kind and its data sets as a variable library's XML file, which Load Variable Library reads back with the same variables, kinds, data set names and values. - JSON-lines control channel with real egui pointer and keyboard injection. - Variables: a type object holds one text variable. `variable.bind` and Make Text Dynamic refuse a second one and name the text variable the object has; a visibility variable can still share the object, and a document saved with two text variables on one object opens with both. - Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709). @@ -885,7 +898,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Screen readers get the value of the color and channel sliders that panels and dialogs draw (the Color panel, the Color Picker, Swatch Options, the Navigator's Zoom, the Character panel's variable font axes, the Perspective Grid and flattener options, and the sliders of the effect, tool option and transform dialogs): the number and text of the field beside each one, such as 128 for G or 50% for an opacity, with the slider's range, which extends to include a number past the slider's end. The harmony wheel's Brightness slider, which has no field, reports its brightness in percent. - A layer whose Layer Options › Print is off shows its name italic in the Layers panel, and while its row is dragged, as the reference application shows non-printing layers (#5739); a printing layer stays upright and ticking Print again restores the upright name (`panels::layers` test `a_layer_that_does_not_print_has_its_name_italic`). - In the Layers panel only the primary mouse button drags. A drag with the right or middle button on a row, a guide row, the selection square, the eye or lock column or a target circle moves, copies, hides, locks and transfers nothing and records no undo step, and a right-click still opens the row's menu (`panels::layers` test `only_the_primary_button_drags_rows_guides_art_columns_and_appearances`). - - Rows dragged in the Layers panel and held within 28 points of the list's top or bottom edge scroll a long list that way, faster nearer the edge (60 points a second at the band's inner side, 340 at the edge, at every frame rate), and keep scrolling while the pointer stays still, so a row out of view can take the drop (a move, or a copy with Alt); the Libraries panel's list scrolls by the same rule. A pointer beside the list, a drag of the eye or lock column and a release stop the scrolling, and scrolling changes nothing in the document. The band and speeds are VectorCraft's own (`panels::layers` tests `rows_held_near_the_bottom_or_top_edge_scroll_the_list_to_a_row_out_of_view`, `a_held_row_scrolls_the_list_as_far_in_the_same_time_at_any_frame_rate` and `the_list_scrolls_only_for_rows_held_over_it`). + - Rows dragged in the Layers panel and held within 28 points of the list's top or bottom edge scroll a long list that way, faster nearer the edge (60 points a second at the band's inner side, 340 at the edge, at every frame rate), and keep scrolling while the pointer stays still, so a row out of view can take the drop (a move, or a copy with Alt); the Libraries panel's list scrolls by the same rule. In a list view shorter than 56 points each band is half the view, so a pointer in the top half scrolls up, one in the bottom half scrolls down, and a pointer just outside the view does not scroll it toward the far edge. A pointer beside the list, a drag of the eye or lock column and a release stop the scrolling, and scrolling changes nothing in the document. The band and speeds are VectorCraft's own (`panels::layers` tests `rows_held_near_the_bottom_or_top_edge_scroll_the_list_to_a_row_out_of_view`, `a_held_row_scrolls_the_list_as_far_in_the_same_time_at_any_frame_rate` and `the_list_scrolls_only_for_rows_held_over_it`; `panels` test `drag_scrolling_in_a_short_list_goes_toward_the_nearer_edge`). - The other panels' item drags start only with the primary mouse button too: swatches and color groups, brushes, symbols, graphic styles, library items and groups, character and paragraph styles, Appearance rows and its thumbnail, the Fill and Stroke squares, Recent Colors and the Gradient panel's thumbnail. A right or middle drag on one carries nothing, moves, copies, deletes and applies nothing and records no undo step; right-click menus and the Graphic Styles panel's held right-button preview stay as they were (`panels::swatches` test `only_a_primary_drag_moves_swatches_and_groups`, `panels::text_styles` test `only_a_primary_drag_carries_a_style_row`, `panels::tests_symbol_libraries` test `only_a_primary_drag_carries_a_library_symbol_out`, `panels::tests_effectedit` test `only_a_primary_drag_carries_the_thumbnail_or_a_row`). - Panels undock (#495): a dock tab, a panel icon or a popped-out panel's title dragged out of the dock floats that panel (in an OS window of its own on the desktop, #4135), and the strip right of the dock's tabs floats the whole tabbed group. A floating group moves by its title bar, a tab dragged out of it floats on its own, and dropped on another group's title bar or tabs it stacks with that group; dropped on a dock group's tabs, which light up under the pointer, its panels join that group, and on the group's upper or lower half they make a new group above or below it (`window.panel.dock {anchor, zone}`); dropped on the icon column they become icons there, the tabbed group's panels too (`window.panel.dock {icon: true}`); dropped anywhere else on the dock, which lights up, they go back where they live (the tabbed group or the icon column), as its × and the panel menus' Float Panel / Dock Panel do (`window.panel.float`, `window.panel.dock`). The Tools panel floats by its title bar and docks again on the window's left edge. Floating groups stack into sets: dropped on the upper or lower half of another group (a line shows where), a group joins it right above or below it, and the set's groups stack top to bottom, each showing one panel, moving together by the top group's title bar, whose × docks them all; a group dragged by its tab strip leaves the set (`window.panel.float {below, above}`). A double-click on a tab collapses a floating group to its tabs (`collapsed`), and a dock group too, a group below it moving up into the room; a second double-click, or a click on another of its tabs, expands it (`window.panel.collapse`, kept with the preferences and in saved workspaces). Sets dropped on the left edge of the icon column or of another dock column dock as dock columns (a multi-column dock, `window.panel.dock {column}`), whose groups stack, tab and tear out as a floating set's do, and whose top strip floats the column again. Floating panels, their sets and the Tools panel's position are kept with the preferences and in user workspaces, and clamped into a smaller window. Not done: panels in separate OS windows, reordering tabs by dragging, collapsing a set or dock column to icons, dock columns right of the default dock, resizing floating panels and the groups of a set. - A floating panel's OS window hides while a tool group's flyout or the All Tools drawer is open in the main window, as it does under a modal dialog or a menu, and shows again when the flyout or the drawer closes (#5813; `a_tool_flyout_hides_the_palette_windows_until_it_closes`). @@ -900,29 +913,39 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Hindi (2026-11-06): Hindi (`hi`): 7,877-row machine-assisted catalog, zero/one singular plurals, desktop font fallback and optional Devanagari craft-fonts fallback; all 55 translation tests pass; native review and a web font remain; scores and estimates unchanged. [Terminology and limitations](localization-hi.md). - Gujarati (2026-11-14, #6613): `gu` has 4,673 catalog rows, zero/one singular plurals, installed desktop font fallback and support for optional `Gujr` craft-font faces. The original 4,286 rows remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status/error messages remain partial; the pinned fonts and web startup list have no Gujarati face, so web selection remains unavailable until one is bundled. Current-head validation is recorded in the PR; scores and estimates unchanged. - Hindi wording (2026-11-13): rows outside the plug-in messages keep their English's meaning, quantities and clauses, and use the catalog's save, swatch, crop, resolution, path and type terms; a test checks those terms and the point unit in every row; native review remains; scores and estimates unchanged. + - Hindi word senses (2026-11-13): 85 labels and messages use the interface sense of their English: Desired is वांछित and the range message keeps both comparisons, rulers are रूलर, text characters कैरेक्टर, vector points पॉइंट, fills फ़िल्स and High Contrast उच्च कंट्रास्ट; the glossary test rejects the unrelated senses in every row; native review remains; scores and estimates unchanged. - Hindi terms (2026-11-13): every row that names a variable (data merge, variable fonts and widths, environment variables) says वेरिएबल, and joining paths, anchor points, point type and lines says जोड़ें instead of शामिल हों, which stays for joining the community; a test checks both terms in every row; scores and estimates unchanged. - Hindi English words (2026-11-13): 264 rows no longer keep English words in their sentences, repeat a parameter's name in Hindi or garble them, among them "unknown align", which now names the alignment; lists of accepted values such as `(left|right|top|bottom)` stay as their English writes them; two tests check every row; native review remains; scores and estimates unchanged. - Message field names and values (2026-11-13): 49 status and error messages in the Hindi, Bulgarian, Danish, Indonesian, Dutch, Brazilian Portuguese, Swedish and Turkish catalogs keep the field names in brackets, such as `[subpath, anchor]`, and the values an `unknown` message lists, such as `(points, lines)`, as their English writes them; a test checks every catalog; scores and estimates unchanged. - Italian messages (2026-11-13): the Italian catalog (`it`) has 1,802 more status and error message rows, and the untranslated report's missing Italian messages go from 1,842 to 40; the translations are VectorCraft's own and await native review; scores and estimates unchanged. See [localization-parity.md](localization-parity.md). + - Italian messages no catalog had (2026-11-13): the Italian catalog has 126 more `@msg` rows, 3,560 in all: the image export, color profile, color book, swatch exchange file, DXF and DWG import, 3D and Revolve, script and zip errors that no other catalog translates yet, and the Banner Hems and Grommets, parameter range and recovery save messages that other catalogs translate. The untranslated report lists 54 Italian messages, which open #7116, #7211, #7378 and #7405 translate; scores and estimates unchanged. - Window › Help Bar shows or hides the tool-help strip at the bottom of the window apart from the status bar (`window.helpBar`). Each setting is kept with the UI preferences and in saved workspaces, and Presentation Mode hides both bars. Layouts saved before the setting existed show the Help Bar where they show the status bar (`help_bar_toggle_is_independent_and_saved_in_workspaces`, `help_bar_and_status_bar_render_independently`, `legacy_help_bar_visibility_follows_each_layouts_status_bar`, `a_help_bar_setting_the_file_lacks_is_saved`). - Czech render-site labels: desktop/web file filters, diagnostics, suggested preset names and contributor tooltips/plurals now use catalog lookups; gradients have Czech adjective agreement and printer marks have a separate context (PDF/Print and Summary). Search, Home, toolbar/panel tooltips and Preferences already look up their labels. Every complete catalog has rows for these labels and for the Roman and Japanese printer mark styles. Evidence: `i18n::tests::czech_render_site_follow_up`, `i18n::tests::complete_catalogs_translate_render_site_labels`, `dialogs::tests_modal::printer_mark_labels_are_distinct_from_language_names`; see [localization-parity.md](localization-parity.md). + - The Czech catalog (`crates/ui-egui/src/i18n/cs.tsv`) translates 114 status and error messages that no catalog had a row for: the 3D and Revolve limits, image export and encoding errors, color profiles, color books and swatch exchange files, binary DXF and DWG import, path operations, swatch, graphic style and action set libraries, and zip, script and regular expression errors. The untranslated report (`untranslated_report`) still lists 54 messages for every language: the 53 composite font, SVG filter, read root and graph design errors that open #7211, #7378 and #7405 translate, and `` `index` must be a whole number ``. See [localization-parity.md](localization-parity.md). - The History panel, Edit › Undo and Edit › Redo translate the names of the steps that apply or redefine a character or paragraph style and of the step that redefines a graphic style: each such step keeps its template (`Apply {name}`, `Redefine {name}`, `Redefine Graphic Style “{name}”`) and the style's name, every complete catalog has a row for each template, and the panel and the menu show the style's name as the document holds it, except the Normal styles' names, which they show in the interface language (`steps_named_after_a_style_list_the_template_around_the_name`, `undo_and_redo_name_a_style_step_around_the_style_name`). - The Polish catalog (`crates/ui-egui/src/i18n/pl.tsv`) has an `@msg` row for the status and error messages the untranslated report (`untranslated_report`) finds in the sources, 3,439 `@msg` rows in all: the errors of commands, scripts, file import and export and plug-ins. The report lists 46 Polish messages: 44 that open #7211, #7214, #7116, #7330 and #1931 translate, and 2 that no language has a row for. A message with two placeholders in a row (`Template::parse` in `crates/ui-egui/src/i18n/catalog.rs`) is still shown in English. - The status bar translates the limits a plug-in run can exceed (its instruction, time and memory budgets and its output size) and the error of a plug-in removal that leaves the plug-in's grant in the plug-in store, in every language that translates every message. The untranslated-strings report also lists messages that an error or a status takes from a `&str` constant (`plugin_limit_errors_are_translated`, `message_scan_reads_messages_held_in_constants`). - The status bar translates the plug-in host's other errors (manifest, module and run checks, the output an importer, exporter or effect returns, and the approval a plug-in's permissions need) in every language that translates every message. A JSON object or array inside a message stays as written, and a message that wraps another one, such as `plug-in manifest: {0}`, is matched by its own row before a row that starts with a placeholder. The reasons inside these errors (what is wrong with a parameter's spec or dialog keys, the value a parameter needs, what is wrong with an object, stroke, paint or effect in a plug-in's output) are translated with them, and the untranslated-strings report lists the reasons the plug-in host's error helpers take (`plugin_messages_are_translated_in_every_complete_catalog`, `plugin_errors_translate_with_their_values`, `plugin_error_reasons_are_translated_with_the_error`, `message_scan_reads_plugin_helpers`, `templates_that_start_with_text_match_first`). + - The Japanese catalog (`crates/ui-egui/src/i18n/ja.tsv`) has 3,562 `@msg` rows and 49 `@msgplural` rows (counted 2026-11-14). The untranslated report (`untranslated_report`) lists 98 status and error messages in the sources that have no Japanese row: 77 that every complete-message language lacks, and 21 more. Open #7211 translates 34 of them, among them the composite font errors, and open #7116 translates the justification order error. The status bar does not use the rows for ``unknown parameter `{within}{key}`; {why}`` and `{name} must be {lo}–{hi}{unit} (got {v})`, because a message with two placeholders in a row cannot be matched (`Template::parse` in `crates/ui-egui/src/i18n/catalog.rs`). The row for `{k} has control characters{_1}` does not match the File Info error for a multi-line field, where the last placeholder is empty. A native speaker has not reviewed the wording. - A status or error message whose braces are literal, such as a plug-in's `expected {"objects": [...]}` or a command's `quotes must be {double?, single?}`, is translated only when the whole message matches its row: the row writes those braces doubled and has no placeholder, so it no longer replaces a different message that starts with the same words, such as a JSON reason `expected value at line 1 column 1`, which stays in English. A row without placeholders is found at any message length (`plain_message_keys_double_their_braces`, `literal_brace_rows_match_only_their_message`). - The status bar translates the errors a script's `File` and `Folder` objects, `vc.run`, `$.evalFile`, the `$` object's properties and functions, `alert`, `confirm` and `prompt`, `vc.document` and `vc.log` raise, the limits a run can pass, and the errors of Drop Script Engine, and the line for a run that fails (a syntax error, a thrown error, a limit, a stop or an internal error, with the script's name, the line and column, the included file it is in and the files left written), in every language that translates every message. The script's name, paths, numbers, command ids and the text a script throws itself are shown as they are. A failure with no line and column, such as an error in code `eval` compiled, is shown with one colon after the script's name (`an_error_without_a_place_names_the_script_and_kind`). A message template that names a value twice matches only when both places hold the same text, so the line for a failed run is not taken for the message inside it (`a_repeated_placeholder_matches_the_same_text`). The untranslated-strings report also lists the messages the script host's `fail`, `value` and `over` helpers take and the errors the script interpreter throws, and a constant's text comes from the file or crate that declares it, so the Scripts menu's headers are not listed as messages (`script_errors_are_translated`, `script_host_errors_are_translated`, `message_scan_reads_script_interpreter_errors`, `message_scan_reads_constants_of_the_file_and_its_crate`, `message_scan_skips_test_modules_with_any_test_cfg`). + - The Turkish catalog (`crates/ui-egui/src/i18n/tr.tsv`) has an `@msg` row for all but 41 of the status and error messages the untranslated report (`untranslated_report`) finds in the sources, 3,446 `@msg` rows in all. The row for `{k} has control characters{_1}` does not match the File Info error for a multi-line field, where the last placeholder is empty. A native speaker has not reviewed the wording. + - The Hungarian catalog (`crates/ui-egui/src/i18n/hu.tsv`) has an `@msg` row for the status and error messages the untranslated report (`untranslated_report`) finds in the sources, 3,444 `@msg` rows in all: the errors of commands, scripts, file import and export and plug-ins. The report lists 40 Hungarian messages: the composite font, justification order and connect end errors that open #7211, #7116 and #7330 translate, and two messages that no catalog has a row for. The status bar does not use the rows for ``unknown parameter `{within}{key}`; {why}`` and `{name} must be {lo}–{hi}{unit} (got {v})`, because a message with two placeholders in a row cannot be matched (`Template::parse` in `crates/ui-egui/src/i18n/catalog.rs`). The row for `{k} has control characters{_1}` does not match the File Info error for a multi-line field, where the last placeholder is empty. A native speaker has not reviewed the wording. - The Dutch catalog (`crates/ui-egui/src/i18n/nl.tsv`) has an `@msg` row for the status and error messages the untranslated report (`untranslated_report`) finds in the sources, 3,447 `@msg` rows in all. The report lists 41 Dutch messages: the composite font errors, the justification spacing error and the `connect` end error, which open #7211, #7116 and #7330 translate, and three unknown-parameter and range errors (``unknown parameter `{within}{key}`; {why}``, ``unknown parameter `{within}settings.{format}`; {why}`` and `{name} must be {lo}–{hi}{unit} (got {v})`), which open #7353 rewrites so that a catalog row can match them. The row for `{k} has control characters{_1}` does not match the File Info error for a multi-line field, where the last placeholder is empty. A native speaker has not reviewed the wording. - The Traditional Chinese catalog (`crates/ui-egui/src/i18n/zh-hant.tsv`) has an `@msg` row for the status and error messages the untranslated report (`untranslated_report`) finds in the sources, 3,438 `@msg` rows in all: the errors of commands, scripts, file import and export and plug-ins. The report lists 40 Traditional Chinese messages: open #7211, #7116 and #7330 add the rows for 38 of them, and the other 2 have no row in any catalog. A message with two placeholders in a row (`Template::parse` in `crates/ui-egui/src/i18n/catalog.rs`) is still shown in English. - Localised UI: menus (in-window and native), panels, dialogs, toolbar and Preferences read from per-language catalogs (`crates/ui-egui/src/i18n`, see `docs/development.md`); Traditional Chinese (Taiwan), Simplified Chinese (mainland), Japanese, Korean, Vietnamese, German, Spanish, French, Italian, Polish, Brazilian Portuguese, Russian, Ukrainian, Georgian and Catalan ship complete, and Czech covers every menu label (and more), with system-locale detection on macOS, Windows, Linux and the web (the browser's languages, or `?lang=`), a Language preference and, on macOS, a VectorCraft ▸ Language menu. Names are never translated (fonts and their styles, layers, artboards, saved presets, user libraries, custom workspaces, recent files, plug-ins). + - The Brazilian Portuguese catalog (`crates/ui-egui/src/i18n/pt-br.tsv`) has an `@msg` row for the status and error messages the untranslated report (`untranslated_report`) finds in the sources, 3,563 `@msg` rows in all, including the image export, color profile, color book, swatch exchange file, DXF import and Revolve errors. The report lists 55 Brazilian Portuguese messages: the composite font, SVG filter, read root, graph design, justification order and Blob Brush connect end errors that open #7211, #7378, #7405, #7116 and #7330 translate. The counts that Package's status and question, the folder search of Missing Fonts and Find Linked Files, the modified and missing linked file prompts and the CSS Properties panel's notes show use the interface language's plural forms instead of a fixed "(s)" form. Evidence: `the_missing_links_note_uses_each_count_form` in `crates/ui-egui/src/dialogs/tests_package.rs`, `the_modified_links_question_uses_each_count_form` in `crates/ui-egui/src/dialogs/missing_links.rs`, `search_counts_use_each_count_form` in `crates/ui-egui/src/dialogs/missing_fonts/tests.rs` and `the_unnamed_objects_note_uses_each_count_form` in `crates/ui-egui/src/panels/tests_css_properties.rs`. The status bar's messages for relinked, replaced, updated and embedded images, broken links, linked files that can't be read or changed on disk, images that can't be decoded, added and unavailable fonts, copied CSS, downloads and exports with their notes name one item in the singular and more in the plural, in English and in each language's plural forms (`counted_status_messages_take_the_plural_form` in `crates/ui-egui/src/i18n/tests.rs`). The status bar's messages for documents opened or saved with notes and for discarded or restored recovered documents, and the Global Edit options' Results line, do the same (`open_save_and_recovery_messages_take_the_plural_form` in `crates/ui-egui/src/i18n/tests.rs`); the warnings for linked images and placed documents output as their previews and the errors for a page past a placed file's last page or artboard name their counts in the singular or the plural in English. - The Simplified Chinese catalog (`crates/ui-egui/src/i18n/zh-hans.tsv`) has an `@msg` row for the status and error messages the untranslated report (`untranslated_report`) finds in the sources, 3,554 `@msg` rows in all: the errors of commands, scripts, file import and export and plug-ins, including the image export, color profile, color book, swatch exchange file, DXF import and Revolve errors. The report lists 55 Simplified Chinese messages: the composite font, SVG filter, read root, graph design, justification order and Blob Brush connect end errors that open #7211, #7378, #7405, #7116 and #7330 translate. A message with two placeholders in a row (`Template::parse` in `crates/ui-egui/src/i18n/catalog.rs`) is still shown in English. - Edit › Undo and Edit › Redo, in the in-window and native menus, name the step in the interface language as the History panel lists it (`panels::history::step_name`), so when the catalog has no plain row for a step named after an effect, such as Feather, the menu shows the translation of the effect's menu row without its ellipsis (`undo_and_redo_name_the_step_as_the_history_panel_does`). - The History panel translates the undo step names the engine, the tools and the shell write as literals: the untranslated report (`untranslated_report`) lists any a complete catalog lacks, and a step whose catalog row exists only with an ellipsis (such as an effect's menu name) shows that row without the ellipsis. + - Ukrainian messages (2026-11-13): the Ukrainian catalog (`crates/ui-egui/src/i18n/uk.tsv`) has an `@msg` row for 114 of the 167 status and error messages that the untranslated report (`untranslated_report`) lists as missing in all 23 complete-message languages: the errors of the image encoders, color profiles, swatch exchange files and color books, 3D and Revolve, path operations, DXF import, the script engine and the parameter checks. Open #7211, #7378 and #7405 translate the other 53 (the composite font, SVG filter and read-root errors). The rows keep the placeholders, backticked names, accepted values and limits of their English (`ukrainian_translates_encoder_profile_swatch_revolve_and_parameter_errors`); native review remains; scores and estimates unchanged. - The German catalog (`crates/ui-egui/src/i18n/de.tsv`) has an `@msg` row for the status and error messages the untranslated report (`untranslated_report`) finds in the sources, 3,563 `@msg` rows in all: the errors of commands, scripts, file import and export and plug-ins, including the image export, color profile, color book, swatch exchange file, DXF import and Revolve errors that no other catalog translates yet. The report lists 52 German messages: the composite font and SVG filter errors that open #7211 and #7378 translate, and the justification order error that open #7116 translates. A message with two placeholders in a row (`Template::parse` in `crates/ui-egui/src/i18n/catalog.rs`) is still shown in English. - The Korean catalog (`crates/ui-egui/src/i18n/ko.tsv`) has an `@msg` row for the status and error messages the untranslated report (`untranslated_report`) finds in the sources, 3,438 `@msg` rows in all: the errors of commands, scripts, file import and export and plug-ins. The report lists 39 Korean messages; they are the composite font, select-a-path, justification order and `path.freehand` connect errors that open #7211, #7214, #7116 and #7330 translate. A message with two placeholders in a row (`Template::parse` in `crates/ui-egui/src/i18n/catalog.rs`) is still shown in English. + - The Vietnamese catalog (`crates/ui-egui/src/i18n/vi.tsv`) has an `@msg` row for 115 of the status and error messages that the untranslated report listed for every complete-message catalog, among them the image export, color profile, color book, swatch exchange file, swatch library, DXF and DWG import, 3D and Revolve errors and the `index` whole-number error, 1,750 `@msg` rows in all. The untranslated report (`untranslated_report`) lists 1,875 Vietnamese messages without a row; open #7211, #7378, #7405 and #7434 translate 53 of them. + - The Swedish catalog (`crates/ui-egui/src/i18n/sv.tsv`) translates status and error messages, among them the image export, color profile, color book, swatch exchange file, DXF import, 3D and Revolve errors and the `index` check of `document.activate`, 3,106 `@msg` rows in all. The untranslated report (`untranslated_report`) lists 518 Swedish messages, 54 of them messages that no catalog translates yet. - The History panel menu has Step Backward and Step Forward, which run Edit › Undo and Edit › Redo and are disabled when there is no step to undo or redo, and Set History Limit…, which opens Preferences at Performance, where History States is set. - The History panel menu's Clear History (`edit.clearHistory`) removes every step to undo and to redo and leaves the document as it is; it is not an undo step itself, and it is disabled when there is no step to clear. - The New Document from State button at the bottom of the History panel (`edit.newDocumentFromState`) makes a new document, which becomes active, from the state the panel has selected ([public source](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/undo-edits-and-manage-design-history.html)). VectorCraft's own rules: the new document takes the next Untitled-N name, is marked unsaved, has nothing selected and has no steps to undo or redo, and the source document and its steps stay as they are. @@ -935,15 +958,17 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Perspective Distort and Free Distort (`object.distort`) turn each warped object's bounding box as the warp turns the object at its own center, the objects inside groups, compound paths and clip groups and the art of linked opacity masks included, so the next Selection or Free Transform drag uses the tilted box; Object › Transform › Reset Bounding Box squares it again, and corners left where they are add no undo step (VectorCraft's own rule; `bboxrotate::distort_turns_an_upright_box_with_the_warp_at_its_center`, `distort_turns_each_member_and_linked_mask_by_its_own_warp`, `mirrored_and_collapsing_distorts_keep_valid_angles`, `distort_angles_undo_redo_and_reopen_together`, `xform::unchanged_distort_records_no_history`). - The Free Transform widget's Constrain works in Free Distort as well as in Free Transform ([the help page](https://helpx.adobe.com/illustrator/using/tool-techniques/free-transform-tool.html)). With Constrain on, or Shift held, a corner dragged in Free Distort moves only along the line through the opposite corner, in the box's own proportions, and the other three corners stay in place; on a turned box the line runs through the box's own corners. The line is VectorCraft's own rule. Cmd/Ctrl+Alt+Shift on a corner still drags in Perspective Distort, where Constrain stays unavailable (tools `xform::free::tests::free_distort_corner_keeps_to_its_diagonal_with_shift_or_constrain`, `shift_pressed_during_a_free_distort_drag_constrains_it`, `a_turned_box_is_constrained_along_its_own_diagonal`, `along_diagonal_of_a_degenerate_box`; engine `xform::free_transform_constrained_distort_keeps_the_corner_on_its_diagonal`; ui-egui `free_transform::tests::the_widget_sets_the_mode_and_a_corner_drag_then_distorts`). - Native macOS menu bar, vector tool cursors, a ⌘K command palette, middle-button panning with any tool. Native menus explicitly end tracking on command selection, outside window presses and Escape; menu updates wait until tracking ends, and a dismissing press never starts a canvas gesture (M14.8). - - The Learn panel (Window › Learn, or Explore tutorials beside the search icon on the app bar) has a For you tab with a Get started section and a Quick skill guide card, and a Skills tab that lists VectorCraft's own skills with their tutorial counts and empty progress rings; a skill lists its tutorials, a tutorial shows its numbered steps, and Back goes up a level; `learn.list` and `learn.show {tutorial}` script it ([the help page](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/learn-skills-quick-skill-guide.html); `panels::learn::tests`). + - The Learn panel (Window › Learn, or Explore tutorials beside the search icon on the app bar) has a For you tab with a Get started section and a Quick skill guide card, and a Skills tab that lists VectorCraft's own skills with their progress rings and counts of tutorials finished; a skill lists its tutorials, a tutorial shows its numbered steps, and Back goes up a level; `learn.list`, `learn.tab {tab}`, `learn.skill {skill}`, `learn.show {tutorial}` and `learn.back` script it, and the tab buttons, the rows and Back run them ([the help page](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/learn-skills-quick-skill-guide.html); `panels::learn::tests`). - A tool's name in a Learn tutorial step is a blue link that shows where the tool is without choosing it (`learn.locateTool {tool}`): its toolbar button is marked, a collapsed group's flyout opens with the tool's row marked, a torn-off strip comes to the front, and a tool no shown toolbar holds is marked in the All Tools drawer. The mark, its 3 seconds and the hidden-toolbar cases are VectorCraft's own rules ([the help page](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/learn-skills-quick-skill-guide.html); `panels::learn::tests`, the `a_learn_link_*` tests in `toolbar::tests`). - - Under a tutorial's steps, View more opens the tutorial's own practice sample as a new untitled document, and once the tutorial is finished, Next Up moves to the next tutorial in the same skill, as the help page describes ([the help page](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/learn-skills-quick-skill-guide.html)). The samples are VectorCraft's own drawings. A Finish tutorial button that shows once the sample is open, the untitled copy, Back to skills in place of Next Up after a skill's last tutorial, and Next Up showing the next tutorial without opening its sample are VectorCraft's own rules. `learn.openSample`, `learn.finish`, `learn.next` and `learn.skills` (Back to skills) script them. Not done: the help page's short video, and progress kept between sessions and shown in the skill rings. Regression tests: `view_more_opens_the_tutorial_s_sample_as_a_new_untitled_document`, `finishing_a_tutorial_offers_next_up_in_its_skill`, `the_practice_controls_work_from_the_keyboard`, `the_last_tutorial_of_a_skill_offers_back_to_skills`, `learn_finish_and_learn_next_follow_the_practice`, `learn_skills_shows_the_list_of_skills`, `the_practice_commands_reject_a_missing_or_unknown_tutorial`, `every_tutorial_has_its_own_readable_sample` and `the_next_tutorial_is_the_next_one_in_the_same_skill` in `crates/ui-egui/src/panels/learn/tests.rs`. + - Under a tutorial's steps, View more opens the tutorial's own practice sample as a new untitled document, and once the tutorial is finished, Next Up moves to the next tutorial in the same skill, as the help page describes ([the help page](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/learn-skills-quick-skill-guide.html)). The samples are VectorCraft's own drawings. A Finish tutorial button that shows once the sample is open, the untitled copy, Back to skills in place of Next Up after a skill's last tutorial, and Next Up showing the next tutorial without opening its sample are VectorCraft's own rules. `learn.openSample`, `learn.finish`, `learn.next` and `learn.skills` (Back to skills) script them. Not done: the help page's short video. Regression tests: `view_more_opens_the_tutorial_s_sample_as_a_new_untitled_document`, `finishing_a_tutorial_offers_next_up_in_its_skill`, `the_practice_controls_work_from_the_keyboard`, `the_last_tutorial_of_a_skill_offers_back_to_skills`, `learn_finish_and_learn_next_follow_the_practice`, `learn_skills_shows_the_list_of_skills`, `the_practice_commands_reject_a_missing_or_unknown_tutorial`, `every_tutorial_has_its_own_readable_sample` and `the_next_tutorial_is_the_next_one_in_the_same_skill` in `crates/ui-egui/src/panels/learn/tests.rs`. + - A Learn tutorial's steps are marked complete as the learner works, and a skill's progress ring fills as its tutorials are finished, as the help page describes ([the help page](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/learn-skills-quick-skill-guide.html)). Each step has a check box that marks it done once the tutorial's sample is open (`learn.markStep`); Finish tutorial marks every step done; a skill's count shows its tutorials finished of all, and a finished tutorial has a check mark in its skill's list. Marking steps by hand, the count, keeping the progress in the preferences (the web build keeps it while the page is open) and Reset progress (`learn.resetProgress`) are VectorCraft's own rules; `learn.list` reports the progress. Regression tests: `a_step_s_check_box_marks_only_that_step`, `a_step_s_check_box_works_from_the_keyboard`, `finishing_tutorials_fills_their_skill_s_ring_and_count`, `a_skill_with_no_tutorials_shows_0_of_0`, `learn_mark_step_checks_its_params`, `reset_progress_clears_only_the_progress`, `the_preferences_keep_the_progress` and `saved_progress_is_read_leniently` in `crates/ui-egui/src/panels/learn/tests.rs`. - The Home screen has a Learn section with the in-app tutorials, as the help page lists among the Home screen's options ([the help page](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/homescreen-overview.html)): the Quick skill guide card shows the Learn panel's list of skills (`learn.skills`), and each tutorial, listed under its skill, shows the panel at its steps (`learn.show`). It shows with no document open and over open documents, and a choice leaves the documents as they are. Its place between Recent Files and the new-file presets, its layout and what a choice opens are VectorCraft's own rules (`tests::home::home_has_a_learn_section_that_opens_the_learn_panel`, `home_learn_section_over_open_documents_leaves_them_as_they_are`, `home_quick_skill_guide_card_works_from_the_keyboard`). - The errors of the blend spine commands (Move Spine Point, Reshape Spine Segment, Add Spine Point and Delete Spine Point) show in the status bar in the interface language: each has a row in every catalog that translates all status and error messages and in Bulgarian (`blend_spine_param_errors_are_translated`). - The errors of the 3D effects (Extrude & Bevel, Revolve, Inflate, Rotate and their Classic forms) show in the status bar in the interface language: the art a 3D effect cannot build a solid from, invalid light, graphics and surface settings, and the notes for an object that draws no 3D faces or more wireframe edges than the limit. Each has a row in every catalog that translates all status and error messages, and the effect's name and the values in the message are translated or kept as written (`three_d_refusals_are_translated_in_every_complete_catalog`, `three_d_refusals_translate_with_their_values`). - The errors of the parameter checks that many commands share show in the status bar in the interface language: a value that is not a number where a number goes (`object.move` with `"dx": "60 mm"`, and `object.rotate`, `object.setBounds` and the other commands that call `check_numbers`), a missing number or index, `ids` that are not a list of object ids, an object id that is not a non-negative integer or names no object, and a date that is not Unix seconds. Each has a row in every catalog that translates all status and error messages, and in Bulgarian, Danish, Indonesian and Dutch (`shared_param_check_errors_are_translated`). - A parameter schema's errors show in the status bar with what the value must be in the interface language, for every type a schema has (a number with each kind of range and with a unit, an integer and its range, true or false, a string, a list of names, an object id, a list of object ids, a color, a point, an object and a list), in every catalog that translates all status and error messages; the path, the refused value, the bounds, the unit and the names stay as the English gives them. The error for a value that is not one of its names is also translated in Bulgarian, Bosnian, Danish, Indonesian and Dutch (`parameter_schema_expected_phrases_are_translated`, `bracketed_message_parts_translate_only_as_exact_messages`). - The untranslated report lists the status and error messages of the effects, swatch libraries, raster sizes and encoders, 3D solids and path operations that a catalog lacks, the messages that a `.map_err` closure or a named error handler returns, and the phrases a parameter schema's error builds for what a value must be (`untranslated_report_checks_every_message_crate_and_schema_phrase`, `message_scan_reads_map_err_closures`, `message_scan_reads_named_map_err_handlers`). + - Spanish messages (2026-11-13): the Spanish catalog (`crates/ui-egui/src/i18n/es.tsv`) has an `@msg` row for 114 of the 167 status and error messages that the untranslated report (`untranslated_report`) lists as missing in all 23 complete-message languages: the errors of the image encoders, color profiles, swatch exchange files and color books, 3D and Revolve, path operations, DXF import, the script engine and the parameter checks. Open #7211 and #7378 translate 51 of the others (the composite font and SVG filter errors), and 2 stay in English. The rows keep the placeholders, backticked names, accepted values and limits of their English (`spanish_translates_encoder_profile_swatch_revolve_and_parameter_errors`); native review remains; scores and estimates unchanged. - Export commands run through MCP, the control channel or the CLI refuse a key that no format takes, and warn about a key that only another format takes (`{"format": "pdf", "quality": 80}` writes the PDF with the warning "`quality` was not used: PDF files don't read it"; `an_option_only_another_format_reads_gets_a_note`, `control_export_notes_an_option_the_format_does_not_read`, `convert_warns_about_an_unused_option_only_when_one_was_given`), and a command that writes one format (`document.exportPdf`, `document.exportEps`, `document.exportDxf`) or takes one format's options (`document.pdfSettings`, `pdf.preset.save`) refuses a key that format doesn't take. An unknown key inside `marks`, `bleed`, `compression`, `output`, `advanced`, `security` or `flattener` is refused by its path. - Save commands run through MCP, the control channel or the CLI (`document.save`, `file.saveAs`, `file.saveCopy`, `file.saveAsTemplate`, `app.save`) refuse a key that no save format takes, beside the path or in `options`, and warn about a key the file doesn't read, beside the path or in `options`, with an export's `.ai` rules; Save Options sends a `.ai` save only the options the chosen version reads (`a_save_notes_the_ai_options_its_file_does_not_read`, `ai_save_options_send_only_the_options_the_version_reads`). Export for Screens refuses a key it doesn't take, and a key that no format takes in a format row or in a format's settings, by its path (`formats[1].marks.useDocumentBleed`), and warns about a key there that only another format takes (`a_row_option_only_another_format_reads_gets_a_note`); Export Assets (`assets.export`, `assets.settings.set`) checks the rows and settings it is given the same way. - Commands that read their `ids` (or `slices`) list themselves refuse a list with an entry that is not a non-negative integer, and a value that is not a list, and change nothing; they no longer drop the entry and act on the rest (Copy Appearance From, the Edit Colors commands and Overprint Black, Find and Replace, `layer.highlight`, `layer.move`, `library.add`, the Links panel commands, `object.transform`, Make Pattern, the Repeat commands, the slice commands, Join, Average and Join, `plugin.run`, `symbol.edit`, Make Opacity Mask; `tests::ids_without_selection::an_ids_entry_that_is_not_an_id_is_refused_and_changes_nothing`). The error for an entry of an object id list names the key, the entry and its value ("`ids` entry 1 is true, not a non-negative integer object id"), with a row in every catalog that has the other object id errors. @@ -963,6 +988,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **9-slice guides on the canvas** ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/maintain-proportions-while-scaling-symbols.html)): while a symbol with Enable Guides for 9-Slice Scaling on is edited in symbol editing mode, the canvas draws its two horizontal and two vertical guides as dotted lines across its art, with any tool and with ruler guides hidden. With the Selection tool the pointer near a guide shows the Move cursor, and dragging the guide moves it (`symbol.options`'s `nineSliceGuides`) as one undo step; Escape during the drag puts it back. VectorCraft's own rules: a guide within 4 screen pixels takes the press before the art and the bounding box; it may pass the art's edges (see the next entry) and stops short of the opposite guide; the drag does not snap. Tests: `nineslice::tests`, `symbol_nine_slice::tests::the_edited_symbols_guides_cross_its_art_where_the_editing_layer_shows_it`, `a_moved_guide_passes_the_arts_edges_and_stops_short_of_the_opposite_guide`, `canvas::tests::the_edited_symbols_nine_slice_guides_are_drawn_and_dragged_on_the_canvas`. - **9-slice guides outside the art** ([the help page](https://help.adobe.com/archive/en/illustrator/cs6/illustrator_reference.pdf), Use 9-slice scaling section): a guide may lie outside the symbol's art, set by dragging it past the art's edge in symbol editing mode, by `symbol.options`'s `nineSliceGuides` or by a Symbol Options field below 0% or above 100%, and a scaled instance still scales, by the cells its art falls in. VectorCraft's own rules: each guide lies within 16 times the art's width or height of its edge (`-16..16` as a fraction, `-1600..1600` in percent) and the two guides of an axis keep their order; a guide past an edge of the art cuts the art at that edge, so the outer cell on its side holds no art; with both guides of an axis past opposite edges the art scales as a whole along it; with both past the same edge the art lies in the outer cell at the other edge and keeps its size, from that edge of the instance, or shrinks to the instance's width or height when the instance is smaller than the art; Symbol Options shows and keeps the guides unrounded. Native files keep the guides exactly; SVG and `.ai` write such an instance as its placed art and keep no guides. Tests: `symbol_nine_slice::tests::guides_outside_the_art_are_accepted_in_order_and_within_the_limit`, `art_scales_by_the_cells_it_falls_in_when_guides_lie_outside_it`, `the_map_with_guides_outside_the_art_is_continuous_and_monotone` in `crates/doc`, `guides_outside_the_art_are_set_by_command_and_scale_by_the_cells_that_hold_art`, `a_guide_dragged_past_the_arts_edge_lies_outside_it`, `guides_outside_the_art_survive_saving_and_reopening_a_native_file` in `crates/engine`, `nineslice::tests::a_guide_outside_the_art_is_taken_and_dragged_past_the_arts_edge`, `a_nine_slice_instance_with_a_guide_outside_its_art_is_written_as_drawn` (SVG and `.ai`). - **Delete Symbol asks first** ([Symbols panel](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), [symbol libraries](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html), [Alt-click Delete](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)): the Symbols panel's Delete Symbol button and menu item ask "Delete the selected symbol?" with Yes and No for a symbol no instance uses. For a symbol with placed instances they ask with Expand Instances (the instances become ordinary art), Delete Instances and Cancel; either Instances button deletes the symbol in one undo step. Alt-click on the button deletes an unused symbol without asking and still asks about one with instances. A question left open while another document became active deletes nothing. `symbol.delete` itself does not ask. Tests: `panels::symbols::tests::delete_symbol_asks_first_and_alt_click_deletes_an_unused_symbol_at_once`, `the_in_use_question_expands_or_deletes_the_instances`, `a_stale_delete_symbol_question_deletes_nothing`, `the_delete_symbol_questions_show_their_buttons`. + - **Symbols panel context menu** ([Symbols panel](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): right-clicking a symbol in thumbnail view or list view displays a context menu with Place Symbol Instance (passes view center or artboard center), Edit Symbol, Duplicate Symbol, Delete Symbol, Break Link to Symbol (enabled when canvas selection includes instances of this symbol), and Select All Instances. Right-clicking an unselected symbol selects it first (`symbol.setCurrent`). Tests: `panels::symbols::tests::right_click_context_menu_in_symbols_panel_runs_actions`. - **Symbols › Select All Unused** ([Symbols panel](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), #4918): the Symbols panel menu's Select All Unused shows the symbols nothing places selected (`symbol.unused`): instances in the art (opacity masks included), graph designs, pattern tiles and brush art count, and so do instances in a used symbol's art. Delete Symbol, the button or the menu item, then asks "Delete the selected symbols?" once and deletes those still unused in one undo step (`symbol.delete {names}`); Alt-click on the button deletes them without asking, and a click on a symbol picks just it again. Tests: `tests::brushsym::symbol_unused_lists_the_symbols_nothing_places_and_delete_takes_several`, `panels::symbols::tests::select_all_unused_picks_the_unused_symbols_and_delete_deletes_them`, `dialogs::symbol_delete::tests::several_symbols_get_the_plural_question`. - **Symbols › Sort by Name and the list views** ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): the Symbols panel menu's Sort by Name puts the symbols in alphabetical order (`symbol.sortByName`), and its Thumbnail View, Small List View and Large List View show them as thumbnails, in a compact list or in a list with larger thumbnails. VectorCraft's own rules: the sort ignores case and keeps names that differ only in case in their order; it changes the document's order, which `symbol.list` reports, as one undo step, keeps the current symbol and adds no undo step when the symbols are already in order; Thumbnail View is the default, Small List View has 18-point rows with 14-point thumbnails and Large List View 26-point rows with 22-point thumbnails, and a click or double-click on a symbol does the same in every view. Tests: `tests::brushsym::symbol_sort_by_name_orders_the_symbols_in_one_undo_step`, `panels::symbols::tests::sort_by_name_and_the_small_and_large_list_views`. - **Expand of symbol instances:** Object › Expand turns selected symbol instances (without effects, not in perspective, in groups or placed documents too) into their art as Break Link to Symbol places it, one level deep, as one undo step; the Expand dialog's Fill and Stroke reach that art (`object.expand`, `crates/engine/src/tests/expand_symbols.rs`; estimated, score unchanged). @@ -1016,10 +1042,12 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - On Windows and Linux, F2, F3 and F4 run Cut, Copy and Paste alongside Ctrl+X, Ctrl+C and Ctrl+V, and in the web build they do so everywhere except macOS. The Edit menu keeps the Ctrl shortcuts, and Keyboard Shortcuts lists both keys of each row. On macOS only Cmd+X, Cmd+C and Cmd+V are the defaults. F2, F3 and F4 do not run these commands in a focused text field or while the Type tool edits text. A saved shortcut set that assigns one of these keys to another command keeps that assignment. Public reference: [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html). - Cmd/Ctrl+A follows the keyboard: in a panel, dialog or search field it selects the field's text, while the Type tool edits it selects all of that text (also `select.all` over MCP), and only otherwise every object. On macOS the menu bar's Select All, Cut, Copy and Paste (keys or clicks) act on a focused field too, and elsewhere the in-window menus' do: the field that had the keyboard when the menu opened gets them, with its selection, and the keyboard back (#516). Not yet: Select All across threaded frames (one frame's text is selected). - Cmd/Ctrl+A follows the keyboard: in a panel, dialog or search field it selects the field's text, while the Type tool edits it selects all of that text (also `select.all` over MCP), and only otherwise every object. On macOS the menu bar's Select All, Cut, Copy and Paste (keys or clicks) act on a focused field too, and elsewhere the in-window menus' do: the field that had the keyboard when the menu opened gets them, with its selection, and the keyboard back (#516). In a frame of threaded text, Select All selects the whole story, highlighted in every frame: Copy and Cut take all of it, typing or Delete replaces it as one undo step, and a fill, a size step or a Character or Paragraph panel change applies to every frame's text (VectorCraft's own behavior; `textedit::select_all_in_a_threaded_frame_selects_the_whole_story`, `textedit::typing_over_the_whole_story_replaces_every_frames_text_in_one_step`). - - With the whole story of threaded text selected by Select All, Remove Line Breaks, Remove Paragraph Breaks and Type › Bullets and Numbering › Convert to Text act on the text of every frame as one undo step, and the story stays selected after Convert to Text; a selection inside one frame changes only that frame (VectorCraft's own behavior; `textedit::remove_breaks_takes_the_whole_story_that_select_all_selected`, `textedit::convert_to_text_takes_the_whole_story_that_select_all_selected`). + - With the whole story of threaded text selected by Select All, Remove Line Breaks, Remove Paragraph Breaks and Type › Bullets and Numbering › Convert to Text act on the text of every frame as one undo step, locked and hidden frames included, and the story stays selected after Convert to Text; a selection inside one frame changes only that frame (VectorCraft's own behavior; `textedit::remove_breaks_takes_the_whole_story_that_select_all_selected`, `textedit::convert_to_text_takes_the_whole_story_that_select_all_selected`, `textedit::convert_to_text_of_the_whole_story_converts_locked_and_hidden_frames`, `textedit::remove_breaks_of_the_whole_story_takes_locked_and_hidden_frames`). + - When only some frames of a threaded story are selected, Remove Line Breaks and Remove Paragraph Breaks go through that story's frames once for all of them, not once per selected frame; each selected frame still loses its own breaks, in the order selected, as one undo step (`addons::cleanup::text::tests::remove_breaks_goes_through_a_partly_named_story_once`). - With the whole story of threaded text selected by Select All, the Character, Paragraph, OpenType, Tabs and Text Styles panels, the Justification dialog and the font menu change the frames that are in the edited frame's thread at the time of the change, locked and hidden frames included. A frame that has left the thread is not changed, and a frame added to the thread is (VectorCraft's own behavior; `panels::character::tests::story_changes_follow_the_edited_frames_thread_after_the_first_saved_frame_leaves`, `story_changes_leave_out_a_frame_that_left_and_take_in_a_frame_that_joined`, `story_changes_stay_in_the_edited_frame_once_its_thread_is_removed`, `story_changes_take_in_locked_and_hidden_frames`, `panels::tabs::tests::indent_markers_after_select_all_keep_each_story_paragraphs_indents`, `dialogs::justification::tests::justification_dialog_follows_the_story_thread_at_ok`). - With the whole story of threaded text selected by Select All, the Character, Paragraph, OpenType, Tabs and Text Styles panels, the Justification dialog and the font menu change the frames that are in the edited frame's thread at the time of the change, locked and hidden frames included. A frame that has left the thread is not changed, and a frame added to the thread is (VectorCraft's own behavior; `panels::character::tests::story_changes_follow_the_edited_frames_thread_after_the_first_saved_frame_leaves`, `story_changes_leave_out_a_frame_that_left_and_take_in_a_frame_that_joined`, `story_changes_stay_in_the_edited_frame_once_its_thread_is_removed`, `story_changes_take_in_locked_and_hidden_frames`). - With the Selection tool, a Character or Paragraph panel change to a selected frame of threaded text changes every frame of its story, locked and hidden frames included, as one undo step. The anti-aliasing method, Variable Font axes, the Tabs panel's tab stops and both panels' Reset Panel change the whole story too, and the panels show a value only when every frame of the story has it. A story selected through several of its frames or through a group is changed once, and other type keeps its formatting (VectorCraft's own behavior; `panels::character::tests::selection_tool_changes_reach_every_frame_of_the_story`, `selection_tool_fields_read_every_frame_of_the_story`, `selected_stories_list_each_frame_once`, `panels::paragraph::tests::selection_tool_paragraph_changes_reach_every_frame_of_the_story`, `panels::tabs::tests::selection_tool_tab_stops_reach_every_frame_of_the_story`). + - With the Selection tool, the Justification dialog, the OpenType panel, a Character or Paragraph Styles row and Type › Bullets and Numbering › Convert to Text also change every frame of a selected story, locked and hidden frames included, as one undo step. The Justification dialog acts on the story's frames as they were when it opened. When the frames differ, the OpenType panel's Figure menu shows Mixed, its checkboxes show a dash (a click turns the feature on everywhere), and the style panels highlight no row; a row shows "+" when any frame overrides its style (VectorCraft's own behavior; `dialogs::justification::tests::selection_tool_justification_reaches_every_frame_of_the_story`, `panels::opentype::tests::selection_tool_features_reach_every_frame_of_the_story`, `panels::text_styles::tests::selection_tool_styles_reach_every_frame_of_the_story`, `panels::paragraph::tests::selection_tool_convert_to_text_takes_every_frame_of_the_story`). - Switching from a Type tool to the Eyedropper keeps a whole story selected by Select All: a pick applies to the text of every frame as one undo step, and switching back restores the story selection (VectorCraft's own behavior; `textedit::switching_to_the_eyedropper_keeps_the_whole_story_selected`). - While the Type tool edits text, a character typed with AltGr is typed and runs no command. Firefox on Windows reports AltGr as Ctrl and Alt held, so in the web build AltGr+L (ł on a Polish layout) does not also open Layer Options for a new layer, and AltGr+Q (@ on a German layout) does not also run Reset Tracking and Kerning. A Ctrl+Alt chord that types no character runs its command. - On a layout without Latin letters, a one-key shortcut goes by the position of the key that typed the character, in the web build too, where the character arrives before its key press: on a Russian layout the P key (`з`) chooses the Pen, and two keys pressed in one frame each run their own shortcut. @@ -1096,7 +1124,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Curvature point markers are circular, with no direction handles. While drawing, its own point feedback replaces generic selection markers; existing paths use the selection overlay, including partial selections and Hide Edges. Anchor Size applies, and Direct Selection and Pen retain their handles. The real egui-frame regressions in `crates/ui-egui/src/canvas.rs` verify marker positions, counts and unchanged documents (#1236, in part); the existing-path interpolation request remains open. The curve through the points (`curvature_spline` in `crates/tools/src/draw2.rs`) makes each stretch of three points follow the circle through them: a smooth point's handles lie along that circle's tangent, each `chord / (3 cos²(α/2))` long (α between handle and chord, capped at 90°), and the ends of an open path mirror their neighbour's tangent in their chord, so a J or a U curves evenly, a turn tighter than 30° comes to a point, and uneven spacing doesn't loop; the rubber band, a dragged or inserted point and `path.convertAnchor` to smooth use the same rule, while the Pencil's fitting keeps its own; `tests/draw2.rs` checks that the rubber band is the path the click makes (#1236, in part). The Smooth tool smooths only the stretch of path under the drag (#1547, fixes #1512). A path the Smooth tool changes stays selected whole, and the anchor points and segments selected on it with Direct Selection are deselected. Selected paths the drag does not change keep their selected anchors, and undo restores the earlier selection (`tests/draw2.rs`, `smoothing_a_path_drops_its_direct_selected_anchors`). While the Smooth tool drags with a path selected that it can smooth, a dashed outline shows the band it smooths: everything within its radius of the drag (12 screen pixels, VectorCraft's own value), round at both ends; Alt smoothing with the Pencil, Paintbrush and Blob Brush shows the same band. While Alt is held during a Paintbrush stroke or before a press with no path selected that the Smooth tool can act on, the Paintbrush shows a closing cursor (a crosshair with a ring), and so does the Pencil with Alt key toggles to Smooth Tool off when Alt is pressed after the drag starts; releasing the mouse button with Alt still held closes the path. Before a Paintbrush press with such a path selected, Alt shows the Smooth cursor, and holding Alt at the press smooths that path with the Smooth tool's radius and Smooth Tool Options' Fidelity. A Pencil drag started with Shift or Alt held draws a straight line instead, which stays open. Smooth Tool Options' Fidelity is in pixels, as [the help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=79) gives it: the Smooth tool, and an Alt smoothing drag with the Pencil, Paintbrush or Blob Brush, refits the path at Fidelity divided by the zoom, so a drag smooths a path as much on screen at 25 % as at 800 %. Reading the pixels as screen pixels is VectorCraft's own rule, as for the Pencil and the Paintbrush (#5729); the range (0.05 to 100 px) and the default (2.5 px) are VectorCraft's own values, and a saved Fidelity keeps its number (`crates/tools/src/draw2/gesture/tests.rs` test `smooth_fidelity_is_in_screen_pixels_at_any_zoom`, `crates/engine/src/tests/draw2.rs` test `smooth_region_refits_at_the_tolerance_sent_at_any_zoom`). - With Shift held at the press, the Pencil draws a straight line from the press point to the pointer at 45° steps from the Constrain Angle, as [Draw straight lines with the Pencil tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-straight-lines-with-the-pencil-tool.html) describes; pressed on an end of a selected open path, the line continues the path from that end (part of #3799). With Option/Alt held at the press and Alt key toggles to Smooth Tool off, the Pencil draws a straight line at any angle, whose ends snap to Smart Guides, and it stays open when Alt is still held at the release; Shift and Alt together keep the 45° steps (#3799). While Shift or Alt is held before the press, the Pencil shows a straight-line cursor (a crosshair with a short line), and over an end of a selected open path, where the line continues the path, a path-continuation cursor (the same line leaving a small square), as the page describes. + With Shift held at the press, the Pencil draws a straight line from the press point to the pointer at 45° steps from the Constrain Angle, as [Draw straight lines with the Pencil tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-straight-lines-with-the-pencil-tool.html) describes; pressed on an end of a selected open path, the line continues the path from that end (part of #3799). With Option/Alt held at the press and Alt key toggles to Smooth Tool off, the Pencil draws a straight line at any angle, and it stays open when Alt is still held at the release; Shift and Alt together keep the 45° steps (#3799). While Shift or Alt is held before the press, the Pencil shows a straight-line cursor (a crosshair with a short level line), as the page describes. Over an end of a selected open path, where the stroke continues the path, freehand or as a straight line, it shows a path-continuation cursor (a crosshair with a short line rising to the right), as [Extend paths with the Pencil tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/extend-paths-with-the-pencil-tool.html) describes, and again while a continuing stroke ends near an open end of another selected path, where the release connects the two ([Connect two paths with the Pencil tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/connect-two-paths-with-the-pencil-tool.html)). A continuing stroke, a straight line too, that ends within Close Paths When Ends Are Within of the path's other end shows the closing cursor, and the release closes the path; Alt held at the release closes a continuing freehand stroke too (a straight line stays open, as above). - **Shapes:** all shape tools (including Flare) and the line, arc, spiral and grid tools. Space held while dragging out a shape, line, arc, spiral or grid moves it at its current size. While a grid is dragged out, Up/Down change its rows (concentric dividers) and Left/Right its columns (radial dividers). A click with a grid tool asks for the size, the divider counts and the grid options (#1377, in part): a skew for each set of dividers, Use Outside Rectangle As Frame or Create Compound Path From Ellipses, and Fill Grid; they are parameters of `shape.rectangularGrid` and `shape.polarGrid`, stay as the tool's options and apply to drags too. A shape just drawn stays adjustable with its tool: its Live Shape widgets drag, a press on its centre point (Show Center) moves the selection with the Selection tool's move arrow, snapping and Alt copy, and a press in the rotate zone just outside a bounding-box corner turns it about the centre with the Selection tool's rotate cursor (#5477; tests `a_shape_tool_moves_the_selection_by_its_centre_point_and_turns_it_from_a_corner` and, through the engine, `shapetools.rs`). A drag on one of its eight bounding-box handles scales it as the Selection tool's handles do, with their cursors and snapping, instead of drawing a new shape from the handle. A shape tool takes a press as a handle's only on the drawn handle square (VectorCraft's own rule: 3 screen points from its centre along each axis at the default Anchor Size, a half point more or less per step; the Selection tool takes 5), so a press just beside a handle still draws (tests `a_shape_tool_scales_the_selection_by_its_bounding_box_handles`, `a_shape_tool_draws_from_a_press_just_beside_a_handle` and `a_shape_tool_scales_the_shape_just_drawn_by_its_bounding_box_handle`). The curve a skew percentage follows and the direction of the radial skew are our own (the public documentation gives neither), and the dialogs have no reference point locator. An ellipse's Pie Start and End Angle and Invert Pie (Transform and Properties panels' Ellipse Properties, `object.setLiveShape {pieStart, pieEnd, invertPie}`) cut it as a pie (#812). With the bounding box showing, the Selection tool shows a selected ellipse's two pie widgets just outside it; dragging one sets its angle in one undo step and double-clicking one makes the ellipse whole again. A live polygon's Polygon Properties there: side count, angle, corner type and radius, radius, side length and Make Sides Equal once an uneven scale has made its sides differ (`object.setLiveShape {sides, polygonAngle, polygonRadius, sideLength, makeSidesEqual}`, part of #812); a star is a plain path, as in Illustrator. The Flare Tool Options last as the tool's options: the next flare dragged out uses them, a click's dialog shows them and double-clicking the tool opens them (part of #812). - **Shapes:** all shape tools (including Flare) and the line, arc, spiral and grid tools. Space held while dragging out a shape, line, arc, spiral or grid moves it at its current size. The Flare tool's center drag turns the rays by 0.1 radian at each drag update in which the pointer's document y grows, and back by as much at each one in which it falls, Shift held keeps their turn, and Space held during either of its drags moves the flare. While a grid is dragged out, Up/Down change its rows (concentric dividers) and Left/Right its columns (radial dividers). A click with a grid tool asks for the size, the divider counts and the grid options (#1377, in part): a skew for each set of dividers, Use Outside Rectangle As Frame or Create Compound Path From Ellipses, and Fill Grid; they are parameters of `shape.rectangularGrid` and `shape.polarGrid`, stay as the tool's options and apply to drags too. The curve a skew percentage follows and the direction of the radial skew are our own (the public documentation gives neither), and the dialogs have no reference point locator. An ellipse's Pie Start and End Angle and Invert Pie (Transform and Properties panels' Ellipse Properties, `object.setLiveShape {pieStart, pieEnd, invertPie}`) cut it as a pie (#812). With the bounding box showing, the Selection tool shows a selected ellipse's two pie widgets just outside it; dragging one sets its angle in one undo step and double-clicking one makes the ellipse whole again. A live polygon's Polygon Properties there: side count, angle, corner type and radius, radius, side length and Make Sides Equal once an uneven scale has made its sides differ (`object.setLiveShape {sides, polygonAngle, polygonRadius, sideLength, makeSidesEqual}`, part of #812); a star is a plain path, as in Illustrator. The Flare Tool Options last as the tool's options: the next flare dragged out uses them, a click's dialog shows them and double-clicking the tool opens them (part of #812). - **Shapes:** all shape tools (including Flare) and the line, arc, spiral and grid tools. Space held while dragging out a shape, line, arc, spiral or grid moves it at its current size. The Flare tool's center drag turns the rays with the pointer, Shift keeps them in their original orientation (unturned, or turned by a nonzero General › Constrain Angle), and Space held during either of its drags moves the flare. While a grid is dragged out, Up/Down change its rows (concentric dividers) and Left/Right its columns (radial dividers). A click with a grid tool asks for the size, the divider counts and the grid options (#1377, in part): a skew for each set of dividers, Use Outside Rectangle As Frame or Create Compound Path From Ellipses, and Fill Grid; they are parameters of `shape.rectangularGrid` and `shape.polarGrid`, stay as the tool's options and apply to drags too. The curve a skew percentage follows and the direction of the radial skew are our own (the public documentation gives neither), and the dialogs have no reference point locator. An ellipse's Pie Start and End Angle and Invert Pie (Transform and Properties panels' Ellipse Properties, `object.setLiveShape {pieStart, pieEnd, invertPie}`) cut it as a pie (#812). With the bounding box showing, the Selection tool shows a selected ellipse's two pie widgets just outside it; dragging one sets its angle in one undo step and double-clicking one makes the ellipse whole again. A live polygon's Polygon Properties there: side count, angle, corner type and radius, radius, side length and Make Sides Equal once an uneven scale has made its sides differ (`object.setLiveShape {sides, polygonAngle, polygonRadius, sideLength, makeSidesEqual}`, part of #812); a star is a plain path, as in Illustrator. The Flare Tool Options last as the tool's options: the next flare dragged out uses them, a click's dialog shows them and double-clicking the tool opens them (part of #812). @@ -1128,6 +1156,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur `path.reshapeSegment` refuses a delta of 1e9 pt or longer, as `object.blend.spine.reshapeSegment` does, and `path.convertAnchor` and `path.freehand` refuse a point whose x or y is 1e9 pt or more in size. `path.reshapeSegment`, `object.blend.spine.reshapeSegment`, `path.convertAnchor`, `path.curvatureEdit`, `path.insertAnchor`, `path.moveAnchors`, `path.reshape`, `path.close` and the Pencil, Curvature, Knife, Eraser, Path Eraser, Smooth, Join and Blob Brush commands refuse a number, point or handle given as text, such as "10", and leave the document unchanged; `path.convertAnchor` refuses an `x` without a `y`, or a `y` without an `x`. `path.setHandle`, `path.moveAnchor`, `text.setPathHandle` (`anchor`), `path.insertAnchor` (`segment`), `artboard.reorder`, `library.moveGroup`, `graphicStyle.move` (`to`), `path.appendAnchor`, `path.close`, `path.reverse` (`subpath`) and the ruler origin commands (`artboard`) refuse a value that is not a whole number of 0 or more, such as `"3"` or `2.5`, with `` `anchor` must be a whole number ``, naming the key, instead of reporting it as missing or reading it as the default subpath or artboard; a null `artboard` is artboard 0 (`tests::params::a_malformed_index_is_not_missing_or_its_default`). + The artboard commands that take `index`, `indices` or a replayed `selectedArtboards`, the artboard Align and Distribute commands (`artboard`, `activeArtboard`), `edit.newDocumentFromState` (`index`) and Paste in Place, in Front and in Back (`artboard`, `artboards`) report a value that is not a whole number as such, naming the key, and keep `no such artboard`, `no history state N` and the paste range messages for a whole number that names nothing; a null artboard `index` is `missing index`, and an `indices` value that is not a list, an empty list and a malformed entry each have their own message (`tests::panelcmds::artboard_lists_name_the_fault_and_the_key`). `path.close` and `path.setHandle` (`independent`), `path.moveAnchors` (`patterns`), the Pencil (`closed`, `keepSelected`, `fill`), Curvature (`closed` and a point's `corner`), `path.curvatureEdit` (`corner`), `path.reshapeSegment` (`perpendicular`) and the Blob Brush (`keepSelected`, `mergeOnlySelection`, `merge`) refuse a value other than true, false or null, such as "true", and leave the document unchanged. Direct Selection's marquee selects the frame anchors of area type that lie inside it, and a click on a frame anchor selects that one; Shift toggles them. The selected frame anchors show filled. A drag of one of them moves all of them, the arrow keys nudge them, and the type reflows at its size (`text.reshapeArea`, which takes `items` to move the anchors of several frames in one step), as [Create text](http://web.archive.org/web/20220127090642/https://helpx.adobe.com/illustrator/using/creating-text.html) and [Selecting objects](http://web.archive.org/web/20211230015528/https://helpx.adobe.com/illustrator/using/selecting-objects.html) describe. When the selection also holds other objects, path anchors or ruler guides, or when another change to the document or the selection follows the pick, the type is selected whole. A press on a selected object's centre point (Attributes panel › Show Center) selects the object whole, and a drag from it moves the object as one Move, held by that point (#4891; test `the_centre_point_selects_and_moves_the_object_whole`). @@ -1138,9 +1167,10 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Live Corners:** drag a live rectangle's corner widgets (Selection or Direct Selection) to round all corners, with a radius readout; with Direct Selection, select corner anchors to show and round just those corners (#381). Each corner keeps its own radius and kind (Round, Inverted Round, Chamfer): Alt-click a widget to cycle the kind, double-click it for the Corners dialog, and the Properties and Transform radius fields set the selected corners (`object.setLiveShape {corners, radius, kind}`). A link toggle behind Corner Radius (the `singleCornerRadius` preference) switches the panels to a field for each corner of a live rectangle: Top Left, Top Right, Bottom Right and Bottom Left. Corners stay circular when the rectangle is scaled unevenly or along its own sides when rotated (the radius keeps its size, or scales by the mean scale with Scale Corners on); only a shear distorts them. On a rectangle that isn't square every corner is the same circle: a radius past half the shorter side stops there for all of them, the widgets sit on the corners as drawn and turn the edited corners red at that limit, CSS export writes the drawn radii, and rectangles saved stretched by older versions get circular corners when their corners are next set (#442). Live Corners work on any path's corners too, as on a rectangle's (#511): a star's, a live polygon's (which also shows them to the Selection tool, has a Corner Radius field in the Properties and Transform panels and keeps its radius as its sides change) and a pen path's, wherever two sides meet at an angle at an anchor that isn't smooth: curved sides too, trimmed to what the cut leaves of them (#1144). Direct Selection shows the widgets of every corner, or of the corners holding selected anchors; each corner is a circle tangent to both sides, drawn no larger than takes its cut halfway along its shorter side; a path keeps its uncut outline so its corners stay editable, and the same command, dialog, angle preference and View › Hide Corner Widget apply. With Direct Selection a click on a widget (no drag) selects its corner, as a click on the corner's anchor does, so the next drag on it rounds that corner alone; Shift-click toggles it (#1239). While a corner widget is dragged with the Selection tool the bounding box hides, so the rounding shows against the path alone (#1229). A round corner next to a curved side curves smoothly instead of sticking out of the shape (#1547, fixes #1512). View › Hide Edges hides the Live Corners widgets, the bounding box and the type widget, and the selection tools then do not answer a press on them or change the cursor over them. - **Blend spine Anchor Point tool (#2544):** on a selected blend, dragging a spine corner makes symmetric Smooth handles; the tool displays and picks existing spine handles when switched to, drags one independently or retracts it on click, and clicking a point with handles retracts both. The spine is edited live without moving its key objects. Windows native canvas checks and screenshots reviewed: symmetric and independent handles, corner/retraction, Shift constraints and perpendicular reshaping, tool switching, key preservation, Undo/Redo, save/reopen, hidden handles and overlapping Path/Blend priority (PR #2643). Behaviour reference: [public path-editing documentation](https://helpx.adobe.com/illustrator/using/adjust-path-segments.html). - - **Blend steps of brushed strokes:** the steps interpolate the pen pressure, tilt, bearing and rotation recorded with the Paintbrush, so a Calligraphic, Scatter or Art brush that varies with the pen changes gradually from one key to the next. A key without a recording counts as half pressure, half tilt and 0°, as brushes read it, and angles turn the shorter way round. When the blend starts a key's path at another anchor (an open path run from its end, a closed one turned to another start), the key's recordings, width profile and arrowheads turn with the path. Different brushes still switch halfway (VectorCraft's own rule; strokes blend their options, as [Blended objects overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blended-objects-overview.html) describes; `crates/doc/src/blend.rs`, `pen_pressure_tilt_and_angles_interpolate_for_brushes`, `stroke_profiles_turn_with_a_key_path_started_elsewhere`). + - **Blend steps of brushed strokes:** the steps interpolate the pen pressure, tilt, bearing and rotation recorded with the Paintbrush, so a Calligraphic, Scatter or Art brush that varies with the pen changes gradually from one key to the next. A key without a recording counts as half pressure, half tilt and 0°, as brushes read it, and angles turn the shorter way round. When the blend starts a key's path at another anchor (an open path run from its end, a closed one turned to another start), the key's recordings, width profile, arrowheads, dashes and a gradient along or across the stroke turn with the path. Different brushes still switch halfway (VectorCraft's own rule; strokes blend their options, as [Blended objects overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blended-objects-overview.html) describes; `crates/doc/src/blend.rs`, `pen_pressure_tilt_and_angles_interpolate_for_brushes`, `stroke_profiles_turn_with_a_key_path_started_elsewhere`, `stroke_gradients_and_dashes_turn_with_a_key_path_started_elsewhere`). + - **Blend steps of spot gradients with process plates:** when the matching stops of two gradients, or of a gradient and a solid, are tints of one spot swatch, each step's stop stays linked to it at a tint between the two and keeps the process inks printed with it, each of C, M, Y and K between the two stops' amounts; a stop or solid without process inks counts as none of each. Gradients with different stop counts keep the inks at every resampled stop. PDF export writes such a step as one DeviceN shading of the spot and process inks. Tints of one spot color blend into tints of it, as [the help page](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blended-objects-overview.html) describes; the process-ink interpolation is VectorCraft's own rule (`crates/doc/src/blend.rs`, `blend_gradient_spot_process_plates_interpolate`, `resampled_gradient_spot_process_plates_interpolate`, `blend_gradient_missing_plates_mean_zero`, `blend_solid_to_spot_gradient_does_not_copy_plates`; `crates/pdf/src/tests/output.rs`, `blend_steps_between_spot_gradients_with_process_plates_print_both_inks`). - **Path editing (#494):** the handles shown are the handles that drag: Direct Selection drags those of a path selected as a whole (as the Pen leaves it), the Anchor Point tool and Pen+Alt no longer grab handles that Show handles when multiple anchors are selected hides, a handle shorter than the tolerance leaves its anchor to be picked, and the anchor tools pick within Selection & Anchor Display › Tolerance. A dragged segment keeps a smooth anchor at either end smooth. With Direct Selection, the Pen, the Curvature and the anchor tools, a path selected as a whole shows all its anchors selected, and the Control bar and the Properties panel offer Convert (corner, smooth) for them too; Remove and Cut wait for anchors direct-selected (#504). A handle drag gathers its snap targets once per drag (it took 21 ms per pointer move on a 20,000-path document, now 1 ms; `vectorcraft-cli perf` measures handle and segment drags on a 5,000-anchor path). Join merges the selected anchor points that lie on one another, as after Average, into one anchor (#1582, fixes #1533), and removes the merged anchors in one pass over the path, so a long run of them no longer moves the anchors after it once per merge (`cmd::path::tests::a_long_run_before_many_other_anchors_merges_in_one_pass`); Object › Path › Average & Join… (`path.averageJoin`, Cmd+Alt+Shift+J, the "Create corner or smooth join" shortcut of [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)) moves two open path ends to their midpoint and joins them there, a corner or smooth point as its dialog's Points choice asks, in one undo step. - - **Graphs:** Column, Stacked Column, Bar, Stacked Bar, Line, Area, Scatter, Pie and Radar graph tools with Graph Data and Graph Type. A series starts in greyscale; Group Selection's fill and stroke, the paint, weight, opacity and blend mode of a mark's top visible fill or stroke row after an Appearance command or a graphic style (each given a mark or its series picked with Group Selection), the Eyedropper, Default Fill and Stroke or Swap Fill and Stroke, the paint or stroke weight a stroke weight, gradient or recolor command changes there, and a mark's object opacity and blend mode, are kept separately on the graph and reapplied when its data, type or size changes, and through save, open and undo; a kept gradient takes the same place on each mark's own box. A series that draws Filled Lines bands keeps no stroke paint or weight: its bands are drawn again with their 0.25 pt black outline. Graph Type's Override Calculated Values (both `axisMin` and `axisMax`) uses exactly that value-axis range, split into the tick count (5 when automatic). Line graphs take Edge-to-Edge Lines (off by default: the points sit at the centres of their categories; graphs saved before the option keep their edge-to-edge lines), and radar graphs follow Mark Data Points and Connect Data Points. Blank cells (an empty CSV cell or `null`) are values left out, not zeros: columns, bars and stacked segments skip them, lines and scatter lines break around them and the value axis ignores them, while area, pie and radar draw them as 0; a number in straight quotes is a label, and the data window writes it back quoted. Graph types combine: Graph Type on series picked with Group Selection (or `series` indexes) draws them as their own type, with column, stacked column, line and area mixing on the vertical value axis and bar and stacked bar on the horizontal one; stacked columns take one slot of the cluster, lines draw in front of columns and areas behind. The value axis goes on the left, the right or both sides (column, stacked column, line, area and scatter graphs; bar graphs keep theirs along the bottom), and Separate Scales gives the series assigned to the right axis a scale of their own with its own tick values. Each value axis takes tick marks of no, short or full (across the plot) length and a count per division, and a prefix and suffix for its numbers; the category axis takes tick marks too (none by default), at or between its labels. Graph designs: Object › Graph › Design lists the designs with a preview of the selected one, and New Design (the selected art), Rename, Delete Design, Paste Design (a copy back to edit) and Select Unused, and Marker draws the data points and legend swatches of line, scatter and radar series with a design, scaled so its backmost object fills the default marker's square. The Appearance, effect and graphic style commands do not edit a design's art inside a series, which the graph draws again from the design. Graph Data transposes rows and columns and switches a scatter graph's x and y, and a `|` in a category or series label starts a new line. Pie graphs take Legends in Wedges, Position (Even, Ratio sized by area, Stacked on one centre) and Sort (None, All, First). Graph Type takes column and cluster widths up to 1000% (overlapping past 100%) with First Row and First Column in Front (First Row orders each series' categories; across series the series order decides, so series stay one group each for Group Selection), draws filled lines, adds drop shadows behind columns, bars, lines and wedges, and puts the legend in rows across the top. Text formatted with the Character, Paragraph, Appearance, Transparency or Graphic Styles controls or the Eyedropper, or recolored, given Swap Fill and Stroke or Default Fill and Stroke, or given stroke options or a gradient, on the whole graph or on labels picked with Group Selection, is kept per kind of label (value axis numbers, category labels, legend labels) through the graph being drawn again, the paint, weight, opacity and blend mode of a label's topmost visible fill and stroke rows and its object opacity and blend mode included. Object › Graph › Data opens a worksheet: cells picked with a click and edited above the sheet (Tab moves right, Enter down, the arrows between cells), Import Data from a tab-separated text file, Transpose, Switch x/y, Cell Style (decimals shown, column width), Revert and Apply. `graph.setData` returns and takes the data as CSV with each value written exactly, not rounded to two decimals, so applying the returned CSV changes nothing (#1485). + - **Graphs:** Column, Stacked Column, Bar, Stacked Bar, Line, Area, Scatter, Pie and Radar graph tools with Graph Data and Graph Type. A series starts in greyscale; Group Selection's fill and stroke, the paint, weight, opacity and blend mode of a mark's top visible fill or stroke row after an Appearance command or a graphic style (each given a mark or its series picked with Group Selection), the Eyedropper, Default Fill and Stroke or Swap Fill and Stroke, the paint or stroke weight a stroke weight, gradient or recolor command changes there, a mark's object opacity and blend mode, and the opacity, blend mode, isolation and knockout of a series group picked with Group Selection, are kept separately on the graph and reapplied when its data, type or size changes, and through save, open and undo; a kept gradient takes the same place on each mark's own box. A series that draws Filled Lines bands keeps no stroke paint or weight: its bands are drawn again with their 0.25 pt black outline. Graph Type's Override Calculated Values (both `axisMin` and `axisMax`) uses exactly that value-axis range, split into the tick count (5 when automatic). Line graphs take Edge-to-Edge Lines (off by default: the points sit at the centres of their categories; graphs saved before the option keep their edge-to-edge lines), and radar graphs follow Mark Data Points and Connect Data Points. Blank cells (an empty CSV cell or `null`) are values left out, not zeros: columns, bars and stacked segments skip them, lines and scatter lines break around them and the value axis ignores them, while area, pie and radar draw them as 0; a number in straight quotes is a label, and the data window writes it back quoted. Graph types combine: Graph Type on series picked with Group Selection (or `series` indexes) draws them as their own type, with column, stacked column, line and area mixing on the vertical value axis and bar and stacked bar on the horizontal one; stacked columns take one slot of the cluster, lines draw in front of columns and areas behind. The value axis goes on the left, the right or both sides (column, stacked column, line, area and scatter graphs; bar graphs keep theirs along the bottom), and Separate Scales gives the series assigned to the right axis a scale of their own with its own tick values. Each value axis takes tick marks of no, short or full (across the plot) length and a count per division, and a prefix and suffix for its numbers; the category axis takes tick marks too (none by default), at or between its labels. Graph designs: Object › Graph › Design lists the designs with a preview of the selected one, and New Design (the selected art), Rename, Delete Design, Paste Design (a copy back to edit) and Select Unused, and Marker draws the data points and legend swatches of line, scatter and radar series with a design, scaled so its backmost object fills the default marker's square. The Appearance, effect and graphic style commands do not edit a design's art inside a series, which the graph draws again from the design. Graph Data transposes rows and columns and switches a scatter graph's x and y, and a `|` in a category or series label starts a new line. Pie graphs take Legends in Wedges, Position (Even, Ratio sized by area, Stacked on one centre) and Sort (None, All, First). Graph Type takes column and cluster widths up to 1000% (overlapping past 100%) with First Row and First Column in Front (First Row orders each series' categories; across series the series order decides, so series stay one group each for Group Selection), draws filled lines, adds drop shadows behind columns, bars, lines and wedges, and puts the legend in rows across the top. Text formatted with the Character, Paragraph, Appearance, Transparency or Graphic Styles controls or the Eyedropper, or recolored, given Swap Fill and Stroke or Default Fill and Stroke, or given stroke options or a gradient, on the whole graph or on labels picked with Group Selection, is kept per kind of label (value axis numbers, category labels, legend labels) through the graph being drawn again, the paint, weight, opacity and blend mode of a label's topmost visible fill and stroke rows and its object opacity and blend mode included. On a pie with Legends in Wedges, the legend labels are drawn black, or white on a dark wedge, until a command sets their fill, which is then drawn on every wedge, black included, and kept through save and open. Object › Graph › Data opens a worksheet: cells picked with a click and edited above the sheet (Tab moves right, Enter down, the arrows between cells), Import Data from a tab-separated text file, Transpose, Switch x/y, Cell Style (decimals shown, column width), Revert and Apply. `graph.setData` returns and takes the data as CSV with each value written exactly, not rounded to two decimals, so applying the returned CSV changes nothing (#1485). An Eyedropper pick that includes transparency and leaves a mark's top fill or stroke row without paint, or removes that row when the source has no row of that kind, where that row had paint before, also replaces the opacity and blend mode the graph keeps for that kind of row in the series; a row that had no paint before the pick leaves them as they are. What Global Edit gives a mark from another match (in an isolated graph) is kept on the graph the same way, and so is the object opacity, with its blend mode, that Randomize Opacity and Sort Objects change on marks. - **Graph column designs:** Object › Graph › Column (`graph.column`) draws the columns, bars or stacked segments and the legend swatch of the series picked with Group Selection with a graph design: Vertically Scaled stretches it to each column's length, Uniformly Scaled scales it both ways and centers it, Repeating stacks a copy for each Each Design Represents value and chops or scales the last one (For Fractions), and Sliding keeps the part above the design's guide line in proportion and stretches the part below. The dialog lists the designs with a preview; the choice is saved with the graph and follows the design's rename and delete. @@ -1160,6 +1190,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Space held while the Zoom tool drags a marquee moves the marquee and keeps its size ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). When Space is let go, the drag sizes the marquee again from where it moved to. A Space+Shift drag rotates the view whatever the tool, as a Rotate View tool drag does, and Shift does not round the angle to 15°. While the Type tool edits text, Space types a space: held, it does not show the hand, pan or rotate the view, and Cmd+Space still zooms ([the help page](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) lists the Spacebar as the Hand tool when not in text-edit mode). Test: `canvas::tests::space_types_a_space_while_editing_text_and_does_not_pan`. + As VectorCraft's own rule, a zoom marquee that Cmd+Space starts while the Type tool edits text keeps the marquee's Space rules after Cmd is let go: Space held since the press sizes it, Space pressed again moves it ([the help page](https://helpx.adobe.com/illustrator/using/viewing-artwork.html) describes holding the spacebar to move the marquee), and that Space types no space, nor does it during an animated zoom drag. With no zoom drag, Space types a space. Test: `canvas::tests::space_moves_a_text_edit_zoom_marquee_after_cmd_is_let_go`. - **Swatches panel clicks:** Ctrl/Cmd-clicking New Swatch makes a spot color, and Ctrl/Cmd+Shift-clicking it makes a global process color. - **Panel drag and drop:** art dragged off the canvas onto the Symbols panel becomes a symbol, art dragged onto the Swatches panel becomes a pattern swatch, and art dropped on the Brushes panel opens New Brush for that art; a symbol dragged onto the canvas places an instance where it is dropped, and a brush dragged onto a path is applied to it. New Brush asks for the type of brush first, as the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy) describes. The Brushes panel's New Brush button, its menu's New Brush… and art dropped on the panel open the New Brush dialog, where Scatter Brush, Art Brush and Pattern Brush need selected or dropped art. OK opens that type's Brush Options for the new brush, and their OK makes the brush with the name and options set; Cancel in either dialog adds no brush (`ui.newBrush`). The menu's New Calligraphic Brush, New Bristle Brush and New Art, Scatter and Pattern Brush from Selection items still make a brush at once. @@ -1173,14 +1204,18 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur In the Pencil and Paintbrush Tool Options, Edit selected paths within 0 px turns editing off, so a stroke that starts exactly on an end of a selected open path draws a new path; Close paths when ends are within 0 px turns closing off, so a stroke that ends exactly where it started stays open. The Pencil's and the Paintbrush's Fidelity is in screen pixels, the same at any zoom: their Tool Options give it in px, from 0.01 px on the logarithmic slider to 20 px and up to 100 px in the field, and the tool sends `path.freehand` the value in points at the current zoom (#5729). The Smooth tool's and the Blob Brush's Fidelity stays in points. `path.freehand` and `brush.freehand` take a Fidelity of up to 100 / 0.0313 pt (about 3194.89 pt), the 100 px field maximum at the lowest zoom (3.13 %), and reject a value outside their range with an error, so a Pencil or Paintbrush stroke drawn zoomed out keeps the Fidelity set in pixels (engine tests `pencil_fit_keeps_its_anchors_on_a_stroke_drawn_zoomed_out` and `pencil_takes_fidelity_within_its_range_and_rejects_the_rest`). + `brush.freehand` refuses a `brush` that names no brush in the document, or is not a string, and a `style` other than "pencil" or "brush", with an error and no change or undo step, instead of drawing the plain path; the Paintbrush skips a chosen brush that has since been deleted (engine tests `brush_freehand_refuses_a_brush_or_style_it_cannot_use` and `paintbrush_tool_skips_a_deleted_brush`). Each drag of the Smooth tool smooths the stretch of a selected path in its reach along its length before refitting it within Fidelity, so a wobble wider than Fidelity is smoothed out and another drag over the same place smooths it further, as [the help page](https://helpx.adobe.com/illustrator/using/tool-techniques/smooth-tool.html) describes (`path.smoothRegion`). The smoothing spread (a third of the reach) and the rule that each refit stays within twice the distance the smoothing moved the path, so repeated drags do not drift from it, are VectorCraft's own. A drag over the whole of a closed path smooths it across its first anchor too, so a bump there is smoothed like any other and no corner is left; Object › Path › Smooth smooths a closed path across its first anchor the same way. + When a Smooth tool drag reaches the first anchor of a closed path, the smoothed path starts at its point nearest where that anchor was: at an anchor there, or at a new anchor split into the curve without changing its outline. Dashes and type on the path start from that point. A drag that does not reach the first anchor leaves it first. This is VectorCraft's own rule (engine tests `smoothing_over_a_closed_paths_first_anchor_keeps_its_start` and `smoothing_a_whole_closed_path_with_a_spike_keeps_its_start`). The Smooth tool shows the Not Allowed cursor while no path is selected that it can act on (an editable path, not a guide, with three or more anchors on one of its subpaths or two anchors joined by a curve), and the release of a drag then sends no command and changes nothing; [the help page](https://helpx.adobe.com/illustrator/using/tool-techniques/smooth-tool.html) has the path selected first. A selected path anywhere on the canvas gives the Smooth cursor wherever the pointer is. The Pencil with Alt key toggles to Smooth Tool on and the Blob Brush show Not Allowed the same way when Alt gives them the Smooth tool; the Paintbrush keeps its closing cursor, since its release with Alt closes the stroke. Use Precise Cursors leaves Not Allowed as it is. This cursor rule is VectorCraft's own (tools `smooth_shows_not_allowed_without_a_selected_path_to_smooth`, `borrowed_smooth_shows_not_allowed_without_a_selected_path_to_smooth`, `smoothing_release_sends_nothing_without_a_selected_path_to_smooth`; engine `use_precise_cursors_keeps_the_smooth_tools_not_allowed_pointer`). When a Smooth tool drag reaches the first or last anchor of an open path, that anchor stays where it is and the curve there leaves or arrives along the smoothed path within the reach, so a jagged first or last segment no longer sets the end's direction; an end where the smoothed path turns back by 90° or more keeps its segment's direction, and where the refitted stretch ends inside the path the curve keeps the direction of the part outside the drag. This rule is VectorCraft's own (`tests/draw2.rs`, `smoothing_an_open_path_turns_its_jagged_ends_with_the_path` and `a_smooth_drag_turns_only_the_end_it_reaches`). + A Smooth tool drag keeps a corner where the path turns by more than 57.5° (an angle inside the corner under 122.5°) and rounds a wider one. An anchor is kept as a corner when the path turns by that much at the anchor and also over the drag's reach and over twice the reach on either side of it, so a jag or a bump smaller than the reach is still smoothed; [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/refine-paths.html) describes the tool as reducing irregularities in a path. The stretches on either side of a kept corner are smoothed and refitted on their own, and the corner keeps its place and the directions the path arrives and leaves along, on every drag, on open and closed paths, the anchor a closed path starts at included. A drag that changes no anchor adds no undo step. The threshold and the two distances are VectorCraft's own values, the same on every drag and at any Fidelity (`tests/draw2.rs`, `the_smooth_tool_keeps_corners_sharper_than_its_threshold`, `smoothing_a_closed_path_keeps_its_corners` and `a_smooth_drag_that_only_meets_corners_adds_no_undo_step`). A Smooth drag along a curved segment smooths the stretch of it in the drag's reach even when neither of the segment's anchors is in reach, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/refine-paths.html) describes dragging along the path segment; the segment is cut where the drag enters and leaves the reach, and the parts outside keep their shape (`path.smoothRegion`). Paths of two anchors are smoothed too, and Alt with the Paintbrush smooths a selected two-anchor curve; a two-anchor straight line still gets the closed stroke. How the reach is found on a segment (samples no more than half the reach apart) is VectorCraft's own, and a straight segment is left as it is. Before a press that draws a new path, the Pencil cursor shows a small star, as [Draw freeform paths with the Pencil tool](https://web.archive.org/web/20260926095638/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-freeform-paths-with-the-pencil-tool.html) describes; over a selected path within Edit selected paths' distance, which the press continues from an end or redraws, the star is not shown ([Reshape paths with the Pencil tool](https://web.archive.org/web/20260106004407/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/reshape-paths-with-the-pencil-tool.html)). Keep selected in the Pencil and Paintbrush Tool Options is on by default: while it is on, a stroke selects the path it draws or continues and replaces the earlier selection. While it is off, a new stroke leaves nothing selected, the earlier selection included, as the reference application starts the stroke by dropping it (#5752); a continued or redrawn path is deselected while the rest of the selection stays (`path.freehand` `keepSelected`). With two open paths selected, a Pencil stroke from an end of one that ends within Edit selected paths' distance of an end of the other connects them into one path with the first path's appearance, in one undo step, as [Connect two paths with the Pencil tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/connect-two-paths-with-the-pencil-tool.html) describes (`path.freehand` `connect`). Double-clicking the Shape Builder tool opens Shape Builder Tool Options ([Shape Builder tool options](https://web.archive.org/web/20260105172244/https://helpx.adobe.com/illustrator/using/building-new-shapes-using-shape.html)): with Consider Open Filled Paths as Closed off, a filled open path cuts regions as an unfilled one does; Pick Color From Color Swatches fills merged shapes with the current fill, the Left and Right arrow keys step it through the document's color swatches, and Cursor Swatch Preview shows the current fill and the swatches before and after it above the pointer; Selection Straight Line merges what the line from a drag's first point to its last crosses ([Setting Illustrator's Shape Builder Options](https://web.archive.org/web/20260615204453/https://creativepro.com/setting-illustrators-shape-builder-options/)); with Highlight Fill off, merge mode shades no regions (`shapeBuilder.merge` `openFilledAsClosed` and `pickColorFrom`). + As VectorCraft's own rule, Consider Open Filled Paths as Closed counts an open path as filled when any of its fill rows draws (shown, painted and above 0% opacity), whichever row is on top, as the canvas paints it: a painted fill under an unpainted top fill closes the path, and a painted fill that is hidden or at 0% opacity does not. The region map, merges, erasing and Clicking Stroke Splits the Path follow that rule, and the Shape Builder takes the faces and edges of a Live Paint group that one of their fill or stroke rows draws and whose own opacity is above 0. Regression tests: `tests::build::shape_builder_closes_open_paths_by_the_fill_rows_that_draw`, `tests::build::shape_builder_stroke_split_closes_open_paths_by_the_fill_rows_that_draw` and `tests::build::shape_builder_takes_the_live_paint_faces_and_edges_that_draw`. With In Merge Mode, Clicking Stroke Splits the Path on in the same dialog, a click on a stroke in merge mode splits its path into the run of stroke under the pointer and the rest of the path, as the [Shape Builder tool options](https://web.archive.org/web/20260105172244/https://helpx.adobe.com/illustrator/using/building-new-shapes-using-shape.html) page describes; the run goes from the anchor or crossing point before the pointer to the one after it, and the pointer shows scissors over it. Highlight Stroke When Editable draws that run in the color chosen in its Color list (Red by default), and with Pick Color From Color Swatches the run takes the current fill as its stroke (`shapeBuilder.merge` `splitStroke`). As VectorCraft's own rule, OK in Shape Builder Tool Options gives an error for a highlight Color with an alpha part (`#rrggbbaa` or `#rgba`) and changes nothing. Regression test: `dialogs::shape_builder_options::tests::a_highlight_color_with_an_alpha_part_is_refused`. With Pick Color From Artwork, a merged shape takes the appearance, opacity and blending mode of the object where the drag starts, else of the object where it ends, else of the front-most selected object, as the [Shape Builder combine page](https://web.archive.org/web/20251006211643/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/combine-shapes-with-shape-builder-tool.html) describes. A click in an area that no selected object covers, such as a hole other shapes enclose, takes the front-most selected object's look (`shapeBuilder.merge` `points`: the first point is where the drag starts, and the last point is where it ends). @@ -1192,7 +1227,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Blob Brush Tool Options' tip preview is the Angle slider for screen readers, with the Angle in degrees as its value: a click or a drag in it points the Angle at the pointer and gives it the keyboard focus, Tab reaches it after the Roundness field, and the arrow keys step the Angle by 1° (10° with Shift, Home and End to −180° and 180°). The Blob Brush Tool Options also have Fidelity, which the reference app's [Blob Brush options](https://web.archive.org/web/20261012042029/https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/blob-brush-options-and-best-practices.html) list as setting how far the pointer moves before the path gets a new anchor point. The range and default are VectorCraft's own values: the Pencil's logarithmic slider from Accurate (0.01 pt) to Smooth (20 pt) and its field (up to 100 pt), 1.5 pt by default and kept with the tool's options. The brush follows the stroke fitted at the Fidelity, as a Pencil stroke is fitted: a low value follows the drag closely, jitter included, and a higher one gives smoother curves (`path.blob` `fidelity`). A Blob Brush stroke merges with the topmost path of its fill color and no stroke that it touches, and with the other such paths it touches in the same group or layer that are next to that path in stacking order with no other kind of object between them; matching paths in other groups or layers are left alone, as the Blob Brush tool guidelines in [Paint with fills and strokes](https://web.archive.org/web/20241219085603/https://helpx.adobe.com/illustrator/using/painting-fills-strokes.html) describe (`path.blob`). -- **Ruler guides as layer objects:** a guide goes on the current layer, shows, hides, locks and is deleted with it, is listed in the Layers panel (its row selects it) and moves to another layer (`guide.setLayer`, or its row dragged onto that layer's rows); guides on a hidden or locked layer can't be selected, moved or deleted, Duplicate copies a layer's guides and Merge Selected and Flatten Artwork keep them on the merged layer; guides from files saved before guides had layers go on the top visible, unlocked layer when the document opens. A guide's row has its own eye and lock, which hide or lock that guide alone in one undo step and take part in a drag down either column ([help page](https://helpx.adobe.com/in_hi/tutorial-builder/user-guide/illustrator-tutorial-builder/-ai--examples-of-common-coach-marks.html) lists a Guide among the Layers panel's items); a hidden guide is not drawn and does not snap, a locked one is drawn and snaps but can't be selected, moved or deleted, and its own state is kept through save and reopen and while its layer is hidden or locked (`layer.setProps` on its `guide.list` id). Object › Lock › Selection and Object › Hide › Selection lock or hide a selected guide with the selected art, and Unlock All and Show All unlock or show such guides and select them ([help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf) for Lock and Hide Selection). A guide row dropped on the panel's trash deletes its guide, the trash deletes a guide its row selected, and after a click on a guide row Delete deletes the guide rather than the rows highlighted before ([help page](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/align-graphic-objects-with-guides.html) for deleting a selected guide). Not done: guides stacked among the art of their layer (they are listed above it). Lock Guides also locks the objects made into guides: they can't be selected, moved or deleted (#1543); they are drawn in the guide colour and style of Preferences, and a dragged selection snaps to ruler guides with Smart Guides on (#1583, fixes #1534). Preferences › Guides & Grid › Lock Guides by Default locks guides when the app starts; it is off by default, and new guides can still be dragged out of a ruler while guides are locked. The Transform panel shows a selected ruler guide's X or Y, and typing a value moves it (#1659, part of #1597). This is not established by the documentation we could find: the public help pages on guides, rulers and the Transform, Control and Properties panels (read again on 2026-10-14) describe selecting and dragging unlocked guides and the panels' X and Y for a selection, not a guide's position in a panel, and the one public statement of it is a user's [community answer](https://community.adobe.com/questions-652/adding-a-new-custom-guide-785586), which is not documentation. It is kept as a convenience pending the owner's decision, with no parity claim and nothing counted towards a score. +- **Ruler guides as layer objects:** a guide goes on the current layer, shows, hides, locks and is deleted with it, is listed in the Layers panel (its row selects it) and moves to another layer (`guide.setLayer`, or its row dragged onto that layer's rows); guides on a hidden or locked layer can't be selected, moved or deleted, Duplicate copies a layer's guides and Merge Selected and Flatten Artwork keep them on the merged layer; guides from files saved before guides had layers go on the top visible, unlocked layer when the document opens. A guide's row has its own eye and lock, which hide or lock that guide alone in one undo step and take part in a drag down either column ([help page](https://helpx.adobe.com/in_hi/tutorial-builder/user-guide/illustrator-tutorial-builder/-ai--examples-of-common-coach-marks.html) lists a Guide among the Layers panel's items); a hidden guide is not drawn and does not snap, a locked one is drawn and snaps but can't be selected, moved or deleted, and its own state is kept through save and reopen and while its layer is hidden or locked (`layer.setProps` on its `guide.list` id). Object › Lock › Selection and Object › Hide › Selection lock or hide a selected guide with the selected art, and Unlock All and Show All unlock or show such guides and select them ([help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf) for Lock and Hide Selection). A guide row dropped on the panel's trash deletes its guide, the trash deletes a guide its row selected, and after a click on a guide row Delete deletes the guide rather than the rows highlighted before ([help page](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/align-graphic-objects-with-guides.html) for deleting a selected guide). A plain click on another row lets go of a guide its row selected, keeping the selected art, as a plain click on a row picks that row alone; a Ctrl/Cmd or Shift click keeps it (#7340, `panels::layers` test `a_plain_row_click_lets_go_of_the_selected_guide`). Not done: guides stacked among the art of their layer (they are listed above it). Lock Guides also locks the objects made into guides: they can't be selected, moved or deleted (#1543); they are drawn in the guide colour and style of Preferences, and a dragged selection snaps to ruler guides with Smart Guides on (#1583, fixes #1534). Preferences › Guides & Grid › Lock Guides by Default locks guides when the app starts; it is off by default, and new guides can still be dragged out of a ruler while guides are locked. The Transform panel shows a selected ruler guide's X or Y, and typing a value moves it (#1659, part of #1597). This is not established by the documentation we could find: the public help pages on guides, rulers and the Transform, Control and Properties panels (read again on 2026-10-14) describe selecting and dragging unlocked guides and the panels' X and Y for a selection, not a guide's position in a panel, and the one public statement of it is a user's [community answer](https://community.adobe.com/questions-652/adding-a-new-custom-guide-785586), which is not documentation. It is kept as a convenience pending the owner's decision, with no parity claim and nothing counted towards a score. - **Releasing ruler guides:** View › Guides › Release Guides turns the selected ruler guides into paths with no fill or stroke. An artboard guide becomes a line across its artboard, and a canvas guide becomes a line across the artboards (`view.guides.release {index?, ids?}`). A Cmd/Ctrl+Shift double-click with the Selection, Direct Selection or Group Selection tool releases the ruler guide or guide path under the pointer. - **Layers panel:** every layer, sublayer, group and object is a clickable row at any depth: a click highlights it and makes its layer current (new art goes there), Shift-click a range, Ctrl/Cmd-click toggles. Sublayers are no longer treated as objects: clicks, marquees, Select All and the Select menu take the art inside them, and each sublayer selects in its own colour. Selection squares on rows with selected art (click selects a row's art, Shift adds or removes; dragging the square moves the selection to another row, Alt copies), the eye and lock on every row with drag-down-the-column (one undo step), Ctrl/Cmd-click an eye for per-layer Outline, Alt-click an eye or lock to hide or lock the other layers (again: show or unlock them all), triangles with Alt to open or close everything inside, drag and drop rows above, below or into layers and groups with a drop line (Alt copies) and a dimmed copy of the row under the pointer (layers dropped in the empty space under the last row go below the bottom layer, #2260; dropped on the trash rows are deleted, on New Layer duplicated, as in Illustrator), inline rename, Delete key on highlighted rows. Buttons and the full panel menu: New Layer/Sublayer (Alt: options, Ctrl: on top), Duplicate, Delete, Options for Selection, clipping mask, isolation, Locate Object, Merge Selected, Flatten Artwork, Collect in New Layer, Collect for Export (As Single Asset, As Multiple Assets), Release to Layers (Sequence and Build), Reverse Order, Template, Hide/Outline/Lock Others and Show/Preview/Unlock All, Paste Remembers Layers, Panel Options (row size, thumbnails per kind, Show Layers Only). Right-clicking a layer, sublayer, group or object row offers Collect for Export for that row, or for every highlighted row when it is one of them; guide and blend spine rows have no context menu. Layer Options: name, colour (presets, each with a chip of its colour, or custom), Template, Lock, Show, Print, Preview (outline drawing and clicking) and Dim Images to %. Every operation is a command (`layer.move`, `layer.highlight`, `layer.merge`…) with validation against cycles and invalid nesting. A document opens with only its top-level layers open; the rows left open are saved in the native file (nothing is written for the default) and reopen that way. Only the rows scrolled into view are laid out, from a row list made once per change: a layer of 5,000 groups of 10 paths, all open, draws the panel in 0.4 ms a frame instead of about 29 s (#638). With Paste Remembers Layers on, art copied from a sublayer pastes back into that sublayer, as [the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=223) describes art going back to the layer it was copied from: in the same document while the sublayer is still there, two sublayers of the same name in different layers kept apart; in another document by the names of the sublayer and the layers around it. These rules are VectorCraft's own: a missing sublayer is made inside its layer (a missing layer on top, with the sublayer inside it), in the paste's one undo step; of layers with the same names, the topmost chain that matches the most names wins, a shown and unlocked one first; a matched layer that is hidden or locked, or inside one that is, refuses the paste, and nothing is pasted. @@ -1272,13 +1307,16 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - A 3D effect on one fill or stroke ([the help page](https://helpx.adobe.com/illustrator/using/effects.html)) leaves the object's other fills and strokes drawn with the path's or compound path's fill rule, so an even-odd compound path keeps its holes in them; this holds for Extrude & Bevel, Inflate, Rotate and Revolve, and for the Classic Extrude & Bevel, Rotate and Revolve. Tests: `solids::tests::a_fill_or_stroke_without_the_effect_keeps_the_even_odd_hole`, `revolve::tests::a_fill_without_the_revolve_keeps_the_even_odd_hole`. - With caps and opaque paint, Extrude & Bevel (both kinds) and Inflate draw each side face of the fill's solid before the faces of the same object's strokes that overlap it (strokes on closed paths without dashes, a width profile or a brush, in a solid color or an opaque gradient), so the stroke's walls cover the fill's walls at concave corners instead of showing stripes of the fill. Tests: `solids::tests::a_fills_walls_are_drawn_before_the_stroke_faces_over_them`, `solids::tests::the_draw_order_moves_a_fill_wall_before_the_stroke_faces_it_overlaps`, `solid::tests::facets_tell_the_sides_from_the_ends_and_the_faces_turned_away`. - When the fill and strokes are at full opacity with Normal blending, under a stroke that leaves parts of the fill's edge uncovered (dashed, with a width profile or a brush, on an open subpath, or in a paint that may show through), Extrude & Bevel (both kinds) and Inflate cut each stroke face that passes through a face of the fill's solid, or of another of the shape's strokes, where their depths meet, and draw the faces of the shape's fill and strokes that overlap in the order of their depths where they overlap, instead of by the depths of their centers. Inflate orders a plain stroke the same way, since its fill can rise in front of the stroke. The fill no longer paints over a nearer dash, and a dash's end no longer covers the fill wall in front of it; a fill wall in a gap between dashes stays visible. The same order applies inside a group member's own opacity mask or blending mode, to a gradient with transparent stops under a colored light with graphics on its caps, and to Inflate in gradients under a colored light. Tests: `solids::tests::fill_walls_and_strokes_that_leave_gaps_draw_in_the_order_of_their_depths_where_they_overlap`, `solids::tests::local_order_puts_overlapping_fill_walls_and_stroke_faces_in_depth_order`, `solids::tests::a_stroke_face_through_a_fill_wall_is_cut_where_their_depths_meet`, `solids::tests::a_masked_members_fill_and_stroke_faces_go_in_one_order`, `solids::tests::a_colored_inflate_in_gradients_draws_its_faces_in_one_order`, `solids::tests::a_depth_cycle_keeps_the_cap_last`, `solids::graphics::tests::a_transparent_gradient_with_a_graphic_keeps_the_shared_face_order`. + - A graphic mapped onto Extrude & Bevel's cap or onto a Plane is drawn once when the fill is a gradient with transparent stops under a colored light and the object has a stroke (dashed or plain) with the same opacity and blending mode: the fill and stroke share it, as they do without the mask, and it is drawn after the stroke's cap with the mask of the stroke's surface (none for an opaque stroke), instead of once on the fill's cap and again on the stroke's. Members of a 3D group drawn with a mask keep graphics of their own. Unmasked fills and strokes alone draw as before. Tests: `solids::graphics::tests::a_transparent_gradient_with_a_graphic_keeps_the_shared_face_order`, `solids::graphics::tests::a_plane_in_a_transparent_gradient_with_a_stroke_draws_its_graphic_once`, `solids::graphics::tests::members_in_transparent_gradients_keep_graphics_of_their_own`. - Revolve and Revolve (Classic) draw two overlapping faces of a surface in the order of their depths where they overlap, instead of by the depths of their centers, on one object and across a group's members, so a tilted profile with long edges or a profile of several contours no longer draws a nearer face under a farther one. A surface whose faces were already in the right order keeps it. Tests: `solids::tests_revolve_order::a_revolved_surface_draws_the_nearer_of_two_overlapping_faces_last`, `solids::tests_revolve_order::a_revolved_groups_members_draw_the_nearer_of_two_overlapping_faces_last`, `solids::tests_revolve_order::a_classic_revolved_surface_draws_the_nearer_of_two_overlapping_facets_last`, `solids::tests_revolve_order::a_surface_already_in_order_keeps_it`, `solids::tests_revolve_order::surface_order_puts_the_nearer_face_where_they_overlap_last`, `tests::a_revolved_face_measures_its_depth_on_its_plane`. - Under a colored light, an Inflate fill and strokes in solid colors, opaque with Normal blending, also draw their faces in that one order, inside a group member's own opacity mask too, instead of each solid as one composite with the stroke's faces over every fill face. Each face keeps the composite's paint, light ramps and seam width; a lone solid, the solids of an object with a translucent or blended fill or stroke, and such solids holding more than 30,720 faces together (VectorCraft's own limit) are still drawn as one composite each. Tests: `solids::tests::colored_solid_fills_and_strokes_share_face_depth_order`, `solids::tests::a_colored_solid_face_on_its_own_keeps_the_composites_colors`, `solids::tests::colored_solid_inflate_batches_channels_and_clips_once_per_surface`, `solids::tests::colored_solids_past_the_face_limit_draw_as_composites`. - Without a twist, a tapered Extrude & Bevel wall (and each bevel band) is one flat face; only a twist cuts walls into slices, so no seam between slices paints a light tick or a light line on a tapered, untwisted wall (#7019). Test: `solid::tests::a_tapered_wall_is_one_flat_face_and_a_twisted_one_is_sliced`. + - Extrude & Bevel cuts a corner square where the bevel opens it and its miter would reach past four times the width (a sharp point with the bevel outside, a narrow notch with it inside), so the bevel (and, with the bevel outside, the walls) no longer runs out to a spike that does not line up with the art (#7525). Tests: `solid::tests::a_bevel_cuts_sharp_corners_square`, `solid::tests::a_cap_draws_no_empty_segment_at_a_corner_cut_square`. - Extrude & Bevel, Inflate and Rotate apply to type: it makes a solid of its glyph outlines, painted with its own fills and strokes or, when it has none, its characters' colour (the first run's), and stays type, so editing the text reshapes the solid (#4715). - Extrude & Bevel, Inflate and Rotate (Effect › 3D and Materials): live effects in the `three-d` crate with depth, twist, taper, solid or hollow caps, five original bevel shapes (width, height, repeat, spacing, inside, both sides), Inflate's volume, both sides, twist, taper and cap, Rotate's turned fills and strokes, Position presets, the rotation and light gizmos, SVG/PDF vector output and Expand Appearance; one 3D effect per object; covered by geometry, effect, canvas-versus-export, command and dialog tests ([three-d.md](three-d.md)). - Extrude & Bevel and Inflate build detailed shapes: each solid takes up to 65,536 outline points and 163,840 faces (VectorCraft's own limits, was 2,048 points and 32,768 faces), counted before any point is sampled; when the faces do not fit, every curve takes fewer pieces, down to 4. A closed path of 2,000 curves extrudes with a bevel and inflates, and paths of 5,000 and 10,000 curves build at the default settings (`crates/three-d/src/solid/tests_limits.rs`). - The solids of one Extrude & Bevel (both kinds) or Inflate effect on one object, its fill's, its strokes' and a group's members' together, keep up to 163,840 faces (VectorCraft's own limit). Each solid is built in turn; once their faces pass the limit, no later solid is built, the object draws its source art, and applying or editing the effect, Export 3D Object and Expand as Wireframes report that the 3D surface is too complex. Tests `solids::tests::an_objects_solids_count_their_faces_together`, `a_groups_solids_together_past_the_limit_draw_the_source`, `a_fill_and_strokes_together_past_the_limit_draw_the_source`. + - Inflate at a Volume of 0 % works out each shape's puff only when its solid is built, so no puff is worked out for the shapes after the face limit stops, and the solids are the same bit for bit; with any volume every puff is worked out first, as the highest one places the eye. The shadow builds no solid for a fully transparent fill or stroke. Tests `solid::tests::a_flat_inflate_solves_each_puff_as_its_solid_is_taken`, `a_flat_inflate_solved_as_taken_matches_one_solved_first`, `shadow::tests::an_inflate_shape_that_casts_nothing_builds_no_solid`. - Extrude & Bevel (both kinds) and Rotate keep the art's curves in the faces they draw, export and expand: caps and the edges of walls and bevels where they meet a cap are cubics with smooth anchors where the art's are, fitted within 0.001 pt in perspective and within the sampling tolerance on a bevel's inset. An edge of a twisted wall that is cut into pieces, a piece of curve that does not fit after 8 halvings, and the curves past 1,048,576 for one solid stay straight (VectorCraft's own values; [three-d.md](three-d.md#what-differs-from-the-public-documentation)). Tests `solid::tests::a_cap_keeps_the_curves_of_the_art`, `a_cap_in_perspective_fits_the_projected_curves`, `a_beveled_cap_and_its_walls_share_their_curves`, `twisted_beveled_tiny_and_degenerate_caps_keep_their_curves`. - Export 3D Object (Asset Export's menu): an object with Extrude & Bevel, Revolve, Inflate or Rotate becomes a 3D asset whose Format is USDA (the default), USDZ, glTF or OBJ, and Export writes each of its solids as a mesh with a material in its paint's color (`assets.add3D`, `assets.set3DFormat`, `assets.export3D`; [export 3D vector artwork](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/export-3d-vector-artwork.html)). - Export 3D Object builds each Extrude & Bevel (both kinds) and Inflate solid once: the same build gives the faces that count toward the object's limit and the faces of its mesh, and the meshes match those of a separate build bit for bit. Tests `mesh::tests::a_meshed_solid_is_built_once`, `an_extruded_solid_and_its_mesh_match_the_two_built_apart`, `inflated_solids_and_their_meshes_match_the_two_built_apart`, `solids::tests_mesh::one_build_exports_the_meshes_built_apart`, `a_stroke_past_the_limits_is_left_out_of_the_export`. @@ -1322,6 +1360,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Manual kerning in right-to-left text:** a manual kerning value on a Hebrew or Arabic character changes the space between it and the next character in reading order, the one drawn to its left, under Auto and Optical kerning. The character before it keeps its place, and the caret between the pair stays beside the next character. The side the space goes on is VectorCraft's own rule. Behavior reference: [Line and character spacing](https://web.archive.org/web/20260916050333/https://helpx.adobe.com/illustrator/using/line-character-spacing.html). Test: `rtl_manual_kerning_spaces_the_character_from_the_next_in_reading_order`. - **Manual kerning on inline graphics:** a manual kerning value on an inline graphic's character spaces it from the next character in reading order by the same distance as on a letter of its run's size, in left-to-right, right-to-left and vertical type; Auto and Optical kerning still apply no font pairs to it. This is VectorCraft's own rule. Test: `manual_kerning_on_an_inline_graphic_spaces_it_like_a_letter`. - **Inline graphics in symbol art follow their symbols:** when a symbol changes, type with an inline graphic of it is laid out again wherever the type is: in the layers, in the art of other symbols, graph designs and pattern tiles, and in opacity masks. A symbol's type is laid out before the type that shows that symbol inline, so a symbol whose art holds an inline graphic, its instances and the inline graphics that show it take its new size. Opening and reverting a document and Refresh Font List resolve them in the same order. An inline graphic of a symbol whose art shows that symbol inline, directly or through other symbols, is an empty slot. This is VectorCraft's own rule. Tests: `inline_graphics_in_symbol_art_follow_their_symbol`, `inline_graphics_in_masks_and_pattern_tiles_follow_their_symbol`, `symbols_are_resolved_after_the_symbols_they_show_inline`, `a_symbol_that_shows_itself_inline_is_an_empty_slot` in `crates/engine/src/tests/inline.rs`. +- **Inline graphics of symbols that hold other symbols:** an inline graphic of a symbol whose art holds an instance of another symbol is sized by that symbol's own art, placed by the instance, and follows it when that symbol changes. A symbol's type is laid out after the type in the art of the symbols its instances show. An inline graphic of a symbol whose art reaches that symbol through an instance and an inline graphic is an empty slot; an instance that does not size the art, such as one a clipping path hides, does not count. An instance of a missing symbol, of a symbol without art, of a symbol that holds an instance of itself, or of a symbol whose art nests symbols 32 deep is measured by the 20 × 20 square. This is VectorCraft's own rule. Tests: `an_inline_graphic_follows_the_art_of_a_symbol_nested_in_its_symbol`, `symbols_are_resolved_after_the_symbols_their_instances_show`, `a_symbol_that_shows_itself_through_an_instance_is_an_empty_slot` in `crates/engine/src/tests/inline.rs`; `a_symbol_nested_in_symbol_art_is_measured_by_its_own_art`, `nested_instances_without_art_of_their_own_are_measured_by_the_square`, `only_instances_that_size_a_symbols_art_make_it_depend_on_their_symbol` in `crates/doc/src/inline.rs`. - **Recent font pickers (#3515):** The shared Character, Properties, Glyphs and Find Font family picker lists recently applied families first, once each, in most-recent order and limited by Preferences › Type › Number of Recent Fonts. Search and filters apply to both sections; unavailable families are omitted. Section headings cannot be selected or previewed. Confirmed character-range font edits update the same saved history; previews and failed edits do not. Requirement: [issue #3515](https://github.com/storytold/vectorcraft/issues/3515). - **Show samples on white (a VectorCraft addition):** Preferences › Type › Show samples on white (`fontSamplesOnWhite`, off by default) draws each family's sample in every font menu, and in Type → Font in the in-window menu bar, in dark type on a white area in every interface brightness. A highlighted row's color shows above and below the white area, and the names and the rest of the menu keep the interface's colors. The checkbox is dimmed while Enable in-menu font previews is off. Tests: `crates/ui-egui/src/tests/font_menu.rs`, `crates/ui-egui/src/font_menu/tests.rs`, `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Find Font: Replace With Font From:** a dropdown under Replace With Font chooses the list the replacement font comes from: Document lists the families the document uses, once each; Recent lists the recently applied families that are installed (fonts applied with Find Font's Change and Change All included), newest first, as many as Preferences › Type › Number of Recent Fonts allows; System, the default, lists the installed families available in the font menu. The dialog opens on System with Source Sans 3 chosen, or the font menu's first family when Source Sans 3 is not installed. Choosing a list keeps the chosen font when the list has it and it is installed; otherwise Document and Recent choose the list's first installed font, and System chooses Source Sans 3 or the font menu's first family. Change and Change All are unavailable when the list has no installed font (Recent before any font was applied) and when the chosen family is not installed or is not in the shown list. Behavior reference: [Find and replace fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/find-and-replace-fonts.html) (public documentation). Tests: `crates/ui-egui/src/find_font.rs`. @@ -1330,24 +1369,27 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Mouse wheel over the font family field (#5253):** In the Character and Properties panels and the Control bar, turning the mouse wheel over the closed font family field applies the next family to the selected type (the previous one when turned up), keeping the style when the family has it, else its closest. Each notch is one undo step; leaving the field or Escape keeps the family, and Undo takes it back. The steps use the font menu's order at the first turn and keep it until the pointer leaves the field or the text selection changes, so recent-font updates do not reshuffle later turns. That order follows the font filters every font menu shares (one chosen in the Glyphs panel's menu or a dialog's applies too) but ignores its search text, puts recent families first, and stops at the first and last family. A turn with a modifier key is left to the panel and the canvas. Behavior reference: the [Illustrator CS6 reference](https://help.adobe.com/archive/en/illustrator/cs6/illustrator_reference.pdf#page=10) describes editing hovered dropdown controls with the mouse wheel; [Find and apply fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/find-and-apply-fonts.html) names the family field's places. Applying it to the font field, the order, the ends and the undo steps are VectorCraft's own rules. Tests: `crates/ui-egui/src/tests/font_menu.rs`, `crates/ui-egui/src/font_menu/tests.rs`, `crates/ui-egui/tests/font_wheel.rs`. - **Type:** Character size, leading, baseline shift and horizontal-scale controls account for object/group transforms (#1034): exact document-point sizes, mixed-value display and keyboard increments, range edits, resettable horizontal stretch, undo/redo and native save/reopen (`tests_typescale`, Character panel tests). Point size is the transformed em-height axis, independent of glyph ink bounds; affine rotation, reflection and shear are retained. Group scaling still scales text; preserving font sizes is a separate enhancement. Behaviour reference: [Transform text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/transform-text.html) (public documentation). Text Wrap, Type on a Path effects (Rainbow/Skew/3D Ribbon/Stair Step/Gravity) and Options (Flip, Align to Path, Spacing; OK keeps the type where it is), type on a path's start, centre and end brackets (Selection and Direct Selection drag them to set where the type runs, slide it along its path and, across the path, flip it: #429), Character and Paragraph Styles (override-preserving redefine), paragraph attributes per paragraph (alignment, indents, spacing, hyphenation, hanging punctuation, tab stops, paragraph style, direction, mojikumi and leading model; the Paragraph, Tabs and Paragraph Styles panels act on the paragraphs the Type tool's selection or caret touches, Return continues the paragraph's style, threads and SVG keep them), Area Type Options (rows/columns/inset/first baseline, Text Flow by rows or by columns (#4978), vertical Align Top/Center/Bottom/Justify per row/column, reflowing non-rectangular frames and text wrap), threaded text across any closed shapes, Fit Headline, the Every-line Composer for justified and ragged text (paragraph-wide breaks for an even rag, Single-line per object from the Paragraph panel menu or `text.setFormat {composer}`). Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`), and an anchor of the path of type on a path outside perspective, the type reflowing along it (`text.reshapePath`, #3980). Point type still scales. Auto Size: the frame height follows the text after every edit, in the same undo step (rectangular frames of horizontal type in one row; columns get the least height that holds them; a height set by hand or threading turns it off), and the "Auto Size New Area Type" preference gives it to new area type. Shrink Text to Fit (beyond Illustrator): overflowing area type scales its sizes, leading and baseline shifts down by the largest factor (in 0.1 pt steps of the first run, down to a minimum percentage) that fits, at layout time so every export sees it. `text.areaOptions` and `document.inspect` report overflow and the shrink factor. The Selection tool shows the type widget beside selected type's bounding box (hollow on point type, filled on area type); double-clicking it converts between them (Type › Convert To Area Type / Convert To Point Type), keeping the text and its styles in place. Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. The Character panel's Variable Font sliders set each axis (see Fonts). Beyond Illustrator: inline graphics (`text.insertInline`, Type ▸ Insert Inline Symbol) set a document symbol in a run of type as one character that flows, wraps and justifies like a glyph (InDesign-style inline objects, e.g. mana symbols in card rules text): sized to a multiple of the font size, centred on the cap height, opening up tall lines, following Redefine Symbol; a character of its run's size for Character Alignment and Top-to-Top leading, placed by the bidi reordering in right-to-left text (a neutral U+FFFC); drawn on the canvas, kept as live text plus a `<use>` in SVG and as vector art in PDF; Backspace removes it whole. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm (embedded Latin and numbers keep their direction, lines put in visual order after wrapping) in point, area and path type, with caret, selection and arrow keys in visual order; each paragraph's direction comes from its first strong character unless Paragraph Direction sets it (Paragraph panel with Show Indic Options, `text.setFormat {direction}`), and new type aligns to the start of its direction. SVG export outlines right-to-left text. Arabic typefaces: builds made with a craft-fonts checkout that holds its Arabic families (Noto Sans Arabic, the Arabic fallback, plus Cairo, Tajawal, Almarai, IBM Plex Sans Arabic, Noto Kufi Arabic, Amiri, Alexandria, Fustat, Reem Kufi, Aref Ruqaa and Gulzar once craft-fonts adds them, storytold/craft-fonts#11; releases get them when their craft-fonts pin moves) list them in the font menus on desktop; the web build fetches them from beside the wasm (Noto Sans Arabic before start, so Arabic never shows as boxes, the rest in the background). Font Size and Leading are combo boxes in the Character and Properties panels (Font Size in the Control bar too, beside the Character link, font family and style): type, step with ↑/↓ or the spinner, scrub the label, or pick a preset (6–72 pt, shown in the type unit; Leading also Auto), each pick one undo step; Kerning and Tracking list -100…200; a size, leading, kerning or tracking the selected text doesn't share shows blank (#458). Type › Bold and Italic (beyond Illustrator, as page layout apps have them; Cmd+Shift+B / Cmd+Shift+I while the Type tool edits text) switch the selected type to its family's own Bold or Italic face and back, keeping its width (a Narrow face stays Narrow); a family without that face says so (#724). The commands that make or restyle type (and the MCP `add_text` tool) say in their result when area type does not fit its frame, and `add_text` takes Auto Size and Shrink Text to Fit (#1500, fixes #1471). Cmd+Shift+C (Align center) works on Windows and Linux too (#1940). A double-click on area type's bottom middle handle turns on Auto Size (#1940). Print and Print Preview warn about the area type and type on a path that prints without the text that doesn't fit, and give their ids. A tab stop in the Tabs panel drags from where the press landed, a stop just added included (#1487, fixes #1458). Area type in a non-rectangular shape moves a word too wide for the top lines down to the first line that holds it instead of breaking it (#1617, fixes #1615). Stylistic sets (ss01–ss20), stylistic and titling alternates, proportional and lining figures, and superscript and subscript glyphs can be turned on as OpenType features of a character style (`text.setStyle {features}`), and the OpenType panel keeps them (#1611, fixes #1607). Escape while typing ends the edit, keeps the type selected and switches back to the tool that was active before type editing began (kept while clicks move editing to other text), or to the Selection tool when there was none (#1802, #1686, #1656). Select › Same matches type on its characters' fill and stroke (#1746, #1737). `text.create`, `text.createInPath` and the MCP `add_text` tool take `justify`, so point type can be centred on or end at its point (#1752, #1748). The Character panel menu's Show Font Height Options shows a Set Font Height Reference dropdown under Font Size (`text.setFormat` or `text.setRangeStyle` `{fontHeightReference}`). Each reference shows an icon of the height it measures before its name, in the open list and in the closed field (#6304): a frame around a letter for Em Box, a bar from the baseline to the top of a capital for Cap Height and of a lowercase x for x-Height, and a frame inset in the em square for ICF Box. With Em Box, the default, the font size is the size of the em square; with Cap Height, x-Height or ICF Box, the characters are set at the em size at which the font's OS/2 cap height, its x height or the height of its ideographic character face equals the font size. With a font that has no such value, or one outside 0.1 to 2 em, the size measures the em box. SVG, PDF and legacy `.ai` export and the CSS Properties rules write the em size the characters are drawn at, and DXF export writes 0.7 times that em size as each TEXT entity's height (group 40, the height of its capitals). Behavior reference: [Vary font height](https://web.archive.org/web/20251118174722/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/vary-font-height.html). - The Every-line Composer composes a paragraph whose characters differ in line metrics (type size, font, leading or vertical scale, or an inline graphic taller than the text) in area type of any shape, rows, columns and text wrap included. In a frame that is not a rectangle, or with text wrap, each line it tries is measured where the lines above it put it, across the line's own height, so a taller line gets the room of the narrower part of the frame, or of the span beside a wrap object, that it reaches. When the frame cannot hold all of such a paragraph, the lines it holds are still composed with the whole paragraph, the lines past the frame's end measured as wide as the last line the frame holds (VectorCraft's own rule); they overflow or go on in the next threaded frame, which composes them again. Such a paragraph is broken with the Single-line Composer when the frame has no room for its first line or when the search passes VectorCraft's own limits. Behavior reference: [the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/set-hyphenation-and-line-breaks.html), and for text that flows on between threaded objects, [the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/add-manage-text/create-text-threads-between-objects.html). + The Every-line Composer composes a paragraph whose characters differ in line metrics (type size, font, leading or vertical scale, or an inline graphic taller than the text) in area type of any shape, rows, columns and text wrap included. In a frame that is not a rectangle, or with text wrap, each line it tries is measured where the lines above it put it, across the line's own height, so a taller line gets the room of the narrower part of the frame, or of the span beside a wrap object, that it reaches. When the frame cannot hold all of such a paragraph, the lines it holds are still composed with the whole paragraph, the lines past the frame's end measured as wide as the last line the frame holds (VectorCraft's own rule); they overflow or go on in the next threaded frame, which composes them again. Such a paragraph is broken with the Single-line Composer when the frame has no room for its first line or when the search passes VectorCraft's own limits. The Single-line Composer measures a line's room across the height of its tallest character too: a line that takes in a taller character is placed again and broken again in the room there. Behavior reference: [the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/set-hyphenation-and-line-breaks.html), and for text that flows on between threaded objects, [the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/add-manage-text/create-text-threads-between-objects.html). A text wrap object's Offset may be negative as well as positive ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=307)). A negative Offset (to -1000 pt) shrinks the wrap object by that distance, measured from each edge itself and from the edges of its holes, so lines beside it, above it and below it run that far into it, and an object narrower than twice the distance no longer moves text aside. With Invert Wrap, a negative Offset keeps the text that far inside the object. These are VectorCraft's own rules for the shape of the shrunk object. Text Wrap Options, `object.textWrap.make` and `object.textWrap.options` and the MCP `text_wrap` tool take the negative value, and layout uses it (`crates/text/src/layout/region.rs` tests, `cmd::textwrap::tests::text_wrap_options_negative_offset_reflows_and_round_trips`). + `object.textWrap.make`, `object.textWrap.options` and the MCP `text_wrap` tool refuse an Offset outside -1000 to 1000 pt, VectorCraft's own range, or one that is not a number, and an Invert Wrap value that is not true or false, with an error and no change or undo step; an omitted or null value takes the default (`cmd::textwrap::tests::text_wrap_commands_refuse_bad_offsets_and_inverts_without_editing`). In area type of a shape other than a rectangle, each line's whole band, ascent to descent, stays inside the frame: where an edge pinches in within the band, the line ends at the narrowest point, and a line runs beside a hole that starts and ends within its band, not across it. In area type of any shape, a line also stays clear of a text wrap object that reaches into any part of its band, and inside an Invert Wrap object over its whole band (`crates/text/src/layout/region.rs` tests). In area type whose frame has several contours, a line runs across an edge two contours share only when their edges lie exactly on one line, so a gap between contours keeps lines from crossing it, even a gap one unit in the last place wide near the edge of the canvas; an edge divided by an anchor exactly on it still lets lines cross (`layout::region::separate_slanted_contours_keep_a_four_ulp_gap_near_canvas_limit`, `shared_slanted_edge_still_joins_near_canvas_limit`, `area_type_sets_no_line_across_a_four_ulp_gap_between_slanted_contours`). - With Invert Wrap, the spans a line keeps inside a wrap shape of many parts (a comb of 500 teeth) are found by stepping through the line's spans and the shape's spans once for each piece of the band, so the work grows with the number of spans, not with its square (`crates/text/src/layout/region.rs` tests). + With Invert Wrap and a positive Offset, a line uses all the room the wrap shape grown by the Offset (across and along) holds at every height of its band: beside a notch the Offset fills, the line reaches the grown edge, whatever the band's height, the slope of the notch's sides or the number of anchors on the shape (VectorCraft's own measure). Measuring a wrap shape of many parts (a comb of 500 teeth) takes a few dozen steps per part, not one per pair of parts. The measure stops after a fixed number of steps; a shape that needs more, for example one whose edges cross one another tens of thousands of times, has its band cut into at most 64 pieces instead, which keeps the line inside the grown shape but can leave it shorter than the grown shape allows (`crates/text/src/layout/region.rs` tests). Text Wrap Options › Offset is a distance field in the document's units: a bare number is in those units, a typed unit ("12 pt") is read as typed, and OK sends points. In a document in picas, a bare number follows Preferences › Units › Numbers Without Units Are Points as the other length fields do: it is in points while that preference is on (the default) and in picas while it is off (`dialogs::command::tests::text_wrap_offset_in_picas_follows_numbers_without_units_are_points`). An Offset typed outside -1000 to 1000 pt, VectorCraft's own range for the command, or text that doesn't read, is refused: the field flashes and the dialog stays open, whether Enter or a click on OK ends the entry; in every dialog drawn by the shared dialog window, a click on OK no longer confirms it when the distance field it takes the focus from refuses its text (`dialogs::command::tests::text_wrap_offset_field_takes_document_units_and_refuses_values_outside_its_range`). Behavior reference: [the help page](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/enter-values-in-panels-and-dialog-boxes.html). The Character panel's Small Caps, Superscript and Subscript buttons and the panel menu's items of the same names turn small caps and the superscript or subscript position on and off for the selected type, or for the text the Type tool has selected (`text.setFormat` or `text.setRangeStyle` `{smallCaps, position}`), in Document Setup's proportions. Turning Superscript on turns Subscript off, and turning Subscript on turns Superscript off. A button or item shows as on when the first selected character (at a caret, the character before it) has its attribute. The Character panel's Anti-aliasing Method dropdown, under Character Rotation, sets how the edges of the selected type objects are drawn as pixels (`text.setFormat {antiAlias}`), for the whole object, with each frame of a thread keeping its own method and graph labels keeping it when the graph is drawn again, on the canvas, in raster exports and when the type is rasterized. VectorCraft defines the methods: Sharp, the default, draws edges as before; None paints a pixel only where the type covers at least half of it; Crisp shows a pixel covered by a share c at `2c - 0.5`, and Strong shows it at `2c`, each kept between 0 and 1. SVG, PDF and EPS export are unchanged. Scores and hours unchanged. The OpenType panel's Stylistic Alternates and Titling Alternates checkboxes turn `salt` and `titl` on and off for the selected type, and its Figure menu lists Default Figure, Tabular Lining, Proportional Lining, Proportional Oldstyle and Tabular Oldstyle; Proportional Lining sets `pnum` and `lnum` and turns `tnum` and `onum` off, Tabular Lining turns `pnum` off and keeps `lnum`, Proportional Oldstyle turns `lnum` off and keeps `pnum`, and Default Figure and Tabular Oldstyle turn `pnum` and `lnum` off. Behavior reference: [Format text with OpenType features](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/format-text-with-opentype-features.html) and [Use swashes, titling alternates, or stylistic alternates](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/use-swashes-titling-alternates-or-stylistic-alternates.html) (public documentation). Tests: `panels::opentype::tests`. The OpenType panel's Position menu lists Default Position, Superscript, Subscript, Numerator and Denominator, as [Format text with OpenType features](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/format-text-with-opentype-features.html) describes; Superscript, Subscript, Numerator and Denominator set `sups`, `subs`, `numr` and `dnom` for the selected type and turn the other three off, and Default Position turns all four off. The menu shows Mixed when the characters it acts on differ, and an entry chosen then applies to all of them. These two rules are VectorCraft's own, as is setting the feature on type whose font lacks the glyphs, which then draws unchanged. The panel's menus and checkboxes change only their own features on each selected character, so characters keep their other OpenType features (`text.setStyle` and `text.setRangeStyle` `{featureChanges}`). Tests: `panels::opentype::tests`, `features::tests::numerators_and_denominators_are_kept_and_shaped`. + The OpenType panel's note that ligatures are off while the text is tracked shows when any character the panel reads has Standard Ligatures on, tracking outside -20 to 55 thousandths of an em, and no explicit `liga` or `clig` tag. With the Selection tool, those characters include every frame of a selected threaded story, locked and hidden frames included; the panel's commands still change only the selected frames. The tracking limits and this rule are VectorCraft's own. Tests: `panels::opentype::tests::ligature_note_reads_every_frame_of_the_story`. The Glyphs panel's Show menu and panel menu have Alternates for Current Selection, as [Replace characters with alternate glyphs](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/replace-characters-with-alternate-glyphs.html) describes. The grid lists the selected character's alternate glyphs from `GSUB` single and alternate substitutions of `aalt`, then `salt`, `ss01` to `ss20`, `swsh`, `cv01` to `cv99` and a few other alternate features, each glyph once. A double-click applies the feature that draws the variant, or a glyph choice if no supported feature draws it, as detailed below. The list uses the font of the character's text even when the panel browses another font, and the panel shows a note when the character has no alternates, its font is missing or no character is selected; these rules are VectorCraft's own. Native files keep a glyph choice with the face it was made in; another font or version draws the default glyph. Tests: `panels::glyphs::tests`, `tests::alternates`, `tests::textedit::a_glyph_alternate_replaces_one_character_through_undo_and_reopen`. The Glyphs panel's Alternates for Current Selection (#5514) applies the OpenType feature that draws the glyph to the selected character alone, as [Replace characters with alternate glyphs](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/replace-characters-with-alternate-glyphs.html) describes (Alternates For Current Selection in the Show menu; double-click the glyph to replace the selected character). One deliberate difference from a literal reading: the text keeps the Unicode character and gains a character-style feature with a value (`salt=2`, `ss03`; `text.setRangeStyle {featureChanges}`) instead of taking an unencoded glyph in its place. The grid lists the alternates of the glyph the shaper makes for the character in its word (a medial letter shows its medial variants; the default glyph comes first and the current glyph is highlighted); a variant no supported feature draws there stays enabled as a replacement glyph (`text.setGlyphAlternate`, including positional alternates), and its tooltip says it may not join its neighbors; the default glyph takes the character's alternate features off again. Runs that differ only in their OpenType features are shaped as one piece of text, each run's features over its own characters, so the letters of an Arabic word keep their joining forms. Show › Entire Font also lists the glyphs no character maps, with the font's name for them (or `gid N`) and the feature that gives them. It applies the selected letter's contextual alternates the same way, and applies a glyph no feature reaches whose name does not belong to another letter as a glyph choice; other glyphs are dimmed with the reason. An Arabic presentation form picked there inserts its base letter. These rules are VectorCraft's own. Tests: `tests::glyph_alternates` in the text crate (a fixture font; Kufi Murabba PIIIX when it is installed), `panels::glyphs::tests` (including positional glyph choices, unlisted glyph name ownership, apply and Undo), `tests::textedit::feature_values_are_set_replaced_and_saved`. + With a Type tool and exactly one character selected, the canvas shows that character's alternate glyphs in a row beside it, and a click on one replaces the character's glyph, as [Replace characters with alternate glyphs](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/replace-characters-with-alternate-glyphs.html) describes ("Replace a character with on-canvas alternate glyphs"). The row shows at most five alternates, and an arrow at its end opens the Glyphs panel on Alternates for Current Selection when the character has more, as the [reference manual](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=479) describes. A click runs the command the panel's double-click runs, as one undo step, so a letter of an Arabic word keeps the word joined. These rules are VectorCraft's own: the row leaves out the glyph the character is drawn with and puts the default glyph first for a character drawn with an alternate; it stands under a character of horizontal type and on the right of a character of vertical type, or on the other side when the canvas ends there or the Contextual Task Bar is there; Preferences › Type › Show Character Alternates (`showCharacterAlternates`, on by default) turns it off. Tests: `canvas::alternates_bar::tests`, `tests::prefs::show_character_alternates_preference_is_on_by_default_and_saved`. The OpenType panel's Stylistic Sets menu offers `ss01`–`ss20` sets present in the selected text's font, using the font's custom labels when available and numbered labels otherwise. Sets can be combined and deselected individually. With mixed fonts, the menu shows the first selected character's font's sets and applies the feature tag to all selected text; a font without that set draws unchanged. The mixed-font rule is a VectorCraft design choice. Behavior reference: [Add stylistic sets to selected text](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/add-stylistic-sets-to-selected-text.html) and the [OpenType specification](https://learn.microsoft.com/en-us/typography/opentype/spec/features_pt). `text.setStyle {stroke, strokeWidth}` sets the character stroke's color and weight of the selected type or of a range of its characters (the weight in document points, as `stroke.set` sets it), in the same undo step as the command's other changes. Tests: `tests::textedit::set_style_sets_the_character_stroke`. - **Paragraph alignment:** the shared Paragraph/Properties alignment row leaves every button unselected when the paragraphs it acts on differ. Auto resolves per paragraph; choosing an alignment uses the existing command. Headless paragraph_mixed_alignment_* regressions exercise mixed → Center → Undo, caret/uniform states, Unicode range boundaries, Auto/direction, split runs and grouped text. These regressions and full integration CI pass. Original captures confirm mixed → Center → Undo in the existing alignment-button layout. The [public Paragraph panel guide](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/paragraph-panel-overview.html) lists the seven controls, but does not specify mixed-state rendering. Other paragraph fields remain outside this change; scores and hours unchanged. For Auto Size area type in columns, the bisection for the frame's height runs on the lines of the one-column layout, and its result is checked with at most two layouts of the columns. When the text wraps around objects or does not fit the one-column layout, or when the check fails, the columns are laid out at every step of the bisection, as before. Typing at the start of a story of 50,000 characters in 2 columns took 1,670 ms a keystroke and now takes 292 ms (release build, `auto_height_in_columns_typing_timing`). Exports to PDF, EPS, SVG, EMF, WMF and the raster formats warn about the area type and type on a path that they draw without the text that doesn't fit, and give their ids, as Print and Print Preview do. - On a shaped area type frame, Inset Spacing keeps text that far from the frame's edge, holes included, measured from the edge itself rather than along the line; the archived help treats the inset as the space an area type object leaves between its text and the path that bounds it (<https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=317>, <https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=325>). A rectangular frame keeps its inset from each side as before, and a column's inner edges keep it once. Tests: `layout::region::inset_on_a_shaped_frame_is_measured_from_its_sloped_edge`, `inset_keeps_text_clear_of_a_hole_s_sloped_edges`, `inset_applies_once_at_a_column_s_edge_and_at_the_frame_s_edge`. + On a shaped area type frame, Inset Spacing keeps text that far from the frame's edge, holes included, measured from the edge itself rather than along the line; the archived help treats the inset as the space an area type object leaves between its text and the path that bounds it (<https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=317>, <https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=325>). A rectangular frame keeps its inset from each side as before, and a column's inner edges keep it once. An edge that two contours of the frame share lies inside the frame, so text runs across it with no inset on either side, and a negative text wrap offset does not shrink a wrap object beside such an edge. Tests: `layout::region::inset_on_a_shaped_frame_is_measured_from_its_sloped_edge`, `inset_keeps_text_clear_of_a_hole_s_sloped_edges`, `inset_applies_once_at_a_column_s_edge_and_at_the_frame_s_edge`, `inset_is_not_kept_beside_an_edge_two_contours_share`, `negative_wrap_offset_does_not_shrink_beside_an_edge_two_contours_share`. An edit copies a thread's story only when it changes one of the thread's frames: with a story of 50,000 characters threaded through 8 frames with a style change at every word, moving another object took 7.8 ms and now takes 0.013 ms, and a frame of a drag took 7.2 ms and now takes 0.012 ms (release build, `threaded_story_edit_timing`). When a story flows through threaded area type, each frame is measured with the whole paragraphs of the story that it needs and a few more, not with the whole rest of the story, and it keeps the same text as before. A story of 1,500 one-line paragraphs (55,892 bytes) through 40 frames was laid out over 2,126,762 bytes of text while the frames were measured, and is now laid out over 21,035 (`thread::tests::many_frames_measure_about_the_text_they_take`). Area type with its lines aligned to the center, the bottom or justified vertically, and type on a path whose first paragraph is aligned Left, Justify Left, Justify All or Auto, are measured the same way: the same story through 40 area frames aligned to the center was laid out over 2,126,762 bytes and is now laid out over 21,035, through 40 paths aligned Left over 2,135,202 bytes and now over 20,583, and through 40 paths aligned Justify All over 2,135,202 bytes and now over 20,583 (same test). Shrink Text to Fit, Dynamic Text, Optical Margin Alignment and Roman Hanging Punctuation on a path, a path aligned to the center or the right, horizontal type on a path whose first paragraph is set right to left or with right-to-left text in the rest of the story, and a frame whose share ends in the story's last paragraph are still measured with the whole rest. A paragraph that continues from one threaded frame into the next has its first-line indent and bullet or number in the frame where it starts; in the next frame its first line starts where its wrapped lines start. In frames that are no longer threaded, copies of a frame and point type converted from one, the first paragraph has its indent and bullet or number again. @@ -1363,7 +1405,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Object › Flatten Transparency takes a frame of threaded text out of the thread in the same way when Convert All Text to Outlines outlines it or when the frame becomes flat regions or an image, and the other frames keep the text they hold. Object › Flatten Transparency, the Flattener Preview, and EPS, PDF and print output that flatten transparency stop building a group's flat regions at the first region past the raster/vector balance's limit (10^(balance/20), rounded down) and rasterize the whole group without building the remaining regions. Building every region gives the same flattened art and the same files. With Clip Complex Regions on, a group builds every region and its image is clipped to them. Object › Flatten Transparency, the Flattener Preview, and EPS, PDF and print output that flatten transparency leave art without transparency as it is when it overlaps only other art without transparency, unless it overlaps a member of a see-through object's group and lies above that member and below the group's topmost object. Such art joins the group, and the group takes the place of its topmost object, so the stacking order stays the same. In files without transparency with Clip Complex Regions on, art under the group within one image pixel of a member joins it too. The 1 pt antialiasing margin goes around a group's art once, however deeply its groups nest. On a grid of 3,000 rectangles with a 0.5 pt stroke, 60 of them with a drop shadow, the Flattener Preview counts 180 affected objects where it counted 3,000, and Flatten Transparency with the Medium preset makes 240 flat regions and 2 images where it made one image of the whole grid. These rules are VectorCraft's own (`tests::flatten::opaque_art_that_touches_only_opaque_art_stays`, `tests::flatten::opaque_art_the_group_would_move_under_joins_it`). - When they group art for flattening, Object › Flatten Transparency, the Flattener Preview, and EPS, PDF and print output that flatten transparency compare the box of an object without transparency only with the boxes of see-through objects in the pass that splits art by transparency. In both passes, a box that lies inside an earlier box that ends no further right and joins everything it overlaps is not compared with later boxes. With one see-through object inside 512 nested objects without transparency, the grouping compares 1,024 pairs of boxes where it compared 262,145, and the groups stay the same (`cmd::flatten::analysis::tests::nested_opaque_boxes_meet_only_the_see_through_box`, `a_shrinking_nest_meets_only_its_outermost_box`). + When they group art for flattening, Object › Flatten Transparency, the Flattener Preview, and EPS, PDF and print output that flatten transparency compare the box of an object without transparency only with the boxes of see-through objects in the pass that splits art by transparency. In both passes, a box that lies inside an earlier box that ends no further right and joins everything it overlaps is not compared with later boxes. With one see-through object inside 512 nested objects without transparency, the grouping compares 1,024 pairs of boxes where it compared 262,145, and the groups stay the same (`cmd::flatten::analysis::tests::nested_opaque_boxes_meet_only_the_see_through_box`, `a_shrinking_nest_meets_only_its_outermost_box`). When a later box that joins everything it overlaps covers an earlier box to the right and below, the grouping compares the earlier box with still later boxes only above the later box's top: 512 boxes, each 1 pt right of and below the one before, compare 511 pairs where they compared 130,816, with and without transparency, and the groups stay the same (`cmd::flatten::analysis::tests::staggered_boxes_meet_only_the_box_before`, `staggered_boxes_group_as_comparing_every_pair`). New Symbol and Redefine Symbol on a frame of threaded text take it out of the thread with the text it shows, which the symbol's art holds, and the other frames keep the text they hold. When the last frame goes into the symbol, the text it has no room for goes after the text of the last frame that stays. When every frame of a thread goes into the symbol, the copy of the last frame keeps all its text. With Optical Margin Alignment on, or Roman Hanging Punctuation on in the first paragraph, the glyphs at the ends of left-to-right type on a path hang outside its brackets, measured along the path. The type hangs at the start bracket when its line is placed there, hangs at the end bracket when the line is placed there, and hangs at both when it is centered. Glyphs that hang past the end bracket do not make the type overflow, and a hang stops at an open path's end. SVG export writes such type as outlines. Type › Type on a Path › Center on Top and Center on Bottom (`type.pathCenter.top`, `type.pathCenter.bottom`, also on the Contextual Task Bar for type on a closed path) slide type on a closed path so the middle of its span lands on the path's topmost or bottommost point as drawn, keep the span's length, and set the first paragraph to Center unless it is Center or Justify Center. This is VectorCraft's own behavior (`crates/geom/src/arc.rs`, `crates/engine/src/tests/pathtype.rs`). @@ -1405,14 +1447,16 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur When a drag on the Tabs panel's ruler or a value typed in its X field moves a tab stop past another stop, the moved stop stays selected. With the Selection tool, the Tabs panel shows the ruler and stops of the first paragraph of the first selected text object, also when the text is inside a selected group or a shape is selected before it; a selection without text shows "No text selected". A stop set on that ruler is set on every selected text object and the text in selected groups, and other objects are left as they were. This is VectorCraft's own rule. Tests `panels::tabs::tests::the_ruler_shows_text_selected_after_an_object_that_is_not_text`, `the_ruler_shows_text_inside_a_selected_group`, `a_stop_added_on_a_mixed_selection_sets_every_selected_text` and `a_selection_without_text_shows_no_ruler`. The Tabs panel menu's Clear All Tabs (`text.tabs.clear`), Delete Tab and Repeat Tab (`text.tabs.set`) can be chosen while the panel's ruler shows tab stops. Delete Tab removes the stop selected on the ruler. Repeat Tab replaces the stops after the selected stop with up to 20 copies of it. The copies are spaced by the selected stop's distance from the stop before it, or from the paragraph's left indent (18 pt further in for each list level past the first) when it is the first stop, and no copy is placed at 2,000 pt or beyond. Clear All Tabs removes every stop, so the default stops every ½ inch apply again. -- **Interface languages, vertical type:** Preferences ▸ User Interface (or VectorCraft ▸ Language on macOS) picks Automatic (the system locale) or a registered language, persisted as `interfaceLanguage`. Translations come from per-language catalogs (`i18n/*.tsv`): Traditional and Simplified Chinese, Japanese, German (every `de-*` locale), Spanish (neutral international Spanish, for every `es-*` locale), French (every `fr-*` locale), Italian (every `it-*` locale), Russian (every `ru-*` locale) and Ukrainian (every `uk-*` locale), Catalan (every `ca-*` locale) and Polish (every `pl-*` locale; AI-drafted, native review pending) cover the whole interface, Czech every menu label; Czech, German, Greek, Spanish, French, Hungarian, Italian, Japanese, Korean, Vietnamese, Polish, Brazilian Portuguese, Russian, Simplified Chinese, Traditional Chinese, Swedish, Ukrainian, Finnish and Dutch also translate status-bar and error messages as they are shown (`@msg` templates, every message literal tested; the messages themselves stay English for agents); untranslated text stays English. Japanese and Chinese glyphs come from the craft-fonts build input (release builds) or the installed fonts, Czech, German, Spanish, French, Italian, Russian and Ukrainian ones from the bundled UI fonts. The web app follows the browser's languages (or `?lang=`). The Basic toolbar's Type button holds Vertical Type in its flyout. Vertical Type, Vertical Area Type and Vertical Type on a Path create vertical text (columns right to left, upright CJK glyphs and marks with `vert` alternates, Latin and longer numbers on their side, two- and three-digit numbers set as tate-chu-yoko in one em of the column (kept whole when justified), upright glyphs centred on the column (tracked or justified too), point type's anchor on the first column's centre line; on a vertical path, upright glyphs and tate-chu-yoko blocks face the path's start, and letters on their side are a quarter turn clockwise from them (with Skew, 3D Ribbon and Stair Step only on a path that runs to the right), in one column that Align to Path Baseline or Center centers on the path and that the caret and selection span); kinsoku applies to horizontal and vertical Japanese (Paragraph panel › Kinsoku Set, `text.setFormat {kinsoku}`: Hard, the default, keeps closing marks, iteration marks, the prolonged sound mark and small kana off the line start and opening brackets off its end; Soft lets 々, ー and small kana start a line as JLREQ's level 3 rules do; None turns it off), and justified Japanese lines spread their room between characters (not inside Latin words); Paragraph panel › Mojikumi Set (shown with Preferences › Type › Show East Asian Options, `text.setFormat {mojikumi}`): None or Line-end Punctuation Half Width (new type's default, as in Illustrator; older documents and imported text keep None) shares one half-em space between consecutive punctuation, sets a closing mark ending a line half width and an opening bracket starting a line flush with its start (a paragraph's first line at its first-line indent, JIS X 4051's principle in JLREQ 3.1.5), and puts a quarter em between Japanese and Latin letters or digits; Paragraph panel menu › Top-to-Top / Bottom-to-Bottom Leading measures leading from em box top to top (area type's first line touches the frame) or from baseline to baseline (new type in a Japanese interface starts top to top, with em box centre character alignment, #432); Paragraph panel menu › Burasagari None / Regular / Force (`text.setFormat {burasagari: "none"|"standard"|"forced"}`) hangs an East Asian comma or full stop (、。,.、。) ending an area type line outside it, Regular (new type's default) when it doesn't fit and Force always (the rest of the line then fills the measure; closing brackets and Latin punctuation don't hang); Character panel menu › Character Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {charAlign}`) lines characters smaller than the largest on their line up on the Roman baseline, the em box top/right, centre or bottom/left, or the ICF (ideographic character face) top/right or bottom/left, from the font's BASE table or, without one, the average ink box of some ideographs and kana; Proportional Metrics (the same menu; `{proportionalMetrics}`) sets full-width glyphs on the font's proportional widths (OpenType `palt`) in horizontal type and upright glyphs on its proportional heights (`vpal`, shaped top to bottom; fonts without vertical metrics keep their cells) in vertical type, and Line-end Punctuation Half Width takes nothing more off the punctuation they re-spaced; Type ▸ Type Orientation switches existing text; caret, selection, hit testing and arrow keys follow the writing direction. Vertical text exports to PDF as real text and to SVG as outlines. The interface is available in Polish (`pl`): menus, panels, dialogs and messages, with one/few/many plurals; AI-drafted, native review pending (#1498). +- **Interface languages, vertical type:** Preferences ▸ User Interface (or VectorCraft ▸ Language on macOS) picks Automatic (the system locale) or a registered language, persisted as `interfaceLanguage`. Translations come from per-language catalogs (`i18n/*.tsv`): Traditional and Simplified Chinese, Japanese, German (every `de-*` locale), Spanish (neutral international Spanish, for every `es-*` locale), French (every `fr-*` locale), Italian (every `it-*` locale), Russian (every `ru-*` locale) and Ukrainian (every `uk-*` locale), Catalan (every `ca-*` locale) and Polish (every `pl-*` locale; AI-drafted, native review pending) cover the whole interface, Czech every menu label; Czech, German, Greek, Spanish, French, Georgian, Hindi, Hungarian, Italian, Japanese, Korean, Vietnamese, Polish, Brazilian Portuguese, Russian, Simplified Chinese, Traditional Chinese, Swedish, Ukrainian, Finnish, Turkish, Catalan, Dutch and Danish also translate status-bar and error messages as they are shown (`@msg` templates, every message literal tested; the messages themselves stay English for agents); untranslated text stays English. Japanese and Chinese glyphs come from the craft-fonts build input (release builds) or the installed fonts, Czech, German, Spanish, French, Italian, Russian and Ukrainian ones from the bundled UI fonts. The web app follows the browser's languages (or `?lang=`). The Basic toolbar's Type button holds Vertical Type in its flyout. Vertical Type, Vertical Area Type and Vertical Type on a Path create vertical text (columns right to left, upright CJK glyphs and marks with `vert` alternates, Latin and longer numbers on their side, two- and three-digit numbers set as tate-chu-yoko in one em of the column (kept whole when justified), upright glyphs centred on the column (tracked or justified too), point type's anchor on the first column's centre line; on a vertical path, upright glyphs and tate-chu-yoko blocks face the path's start, and letters on their side are a quarter turn clockwise from them (with Skew, 3D Ribbon and Stair Step only on a path that runs to the right), in one column that Align to Path Baseline or Center centers on the path and that the caret and selection span); kinsoku applies to horizontal and vertical Japanese (Paragraph panel › Kinsoku Set, `text.setFormat {kinsoku}`: Hard, the default, keeps closing marks, iteration marks, the prolonged sound mark and small kana off the line start and opening brackets off its end; Soft lets 々, ー and small kana start a line as JLREQ's level 3 rules do; None turns it off), and justified Japanese lines spread their room between characters (not inside Latin words); Paragraph panel › Mojikumi Set (shown with Preferences › Type › Show East Asian Options, `text.setFormat {mojikumi}`): None or Line-end Punctuation Half Width (new type's default, as in Illustrator; older documents and imported text keep None) shares one half-em space between consecutive punctuation, sets a closing mark ending a line half width and an opening bracket starting a line flush with its start (a paragraph's first line at its first-line indent, JIS X 4051's principle in JLREQ 3.1.5), and puts a quarter em between Japanese and Latin letters or digits; Paragraph panel menu › Top-to-Top / Bottom-to-Bottom Leading measures leading from em box top to top (area type's first line touches the frame) or from baseline to baseline (new type in a Japanese interface starts top to top, with em box centre character alignment, #432); Paragraph panel menu › Burasagari None / Regular / Force (`text.setFormat {burasagari: "none"|"standard"|"forced"}`) hangs an East Asian comma or full stop (、。,.、。) ending an area type line outside it, Regular (new type's default) when it doesn't fit and Force always (the rest of the line then fills the measure; closing brackets and Latin punctuation don't hang); Character panel menu › Character Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {charAlign}`) lines characters smaller than the largest on their line up on the Roman baseline, the em box top/right, centre or bottom/left, or the ICF (ideographic character face) top/right or bottom/left, from the font's BASE table or, without one, the average ink box of some ideographs and kana; Proportional Metrics (the same menu; `{proportionalMetrics}`) sets full-width glyphs on the font's proportional widths (OpenType `palt`) in horizontal type and upright glyphs on its proportional heights (`vpal`, shaped top to bottom; fonts without vertical metrics keep their cells) in vertical type, and Line-end Punctuation Half Width takes nothing more off the punctuation they re-spaced; Type ▸ Type Orientation switches existing text; caret, selection, hit testing and arrow keys follow the writing direction. Vertical text exports to PDF as real text and to SVG as outlines. The interface is available in Polish (`pl`): menus, panels, dialogs and messages, with one/few/many plurals; AI-drafted, native review pending (#1498). With Line-end Punctuation Half Width, both composers measure a line with its last character set as narrow as Mojikumi sets it ([the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/use-mojikumi-for-japanese-text-composition.html)): a closing bracket, comma or full stop that fits at half width ends the line, and the character before it no longer goes to the next line with it. A mark that already lost its half to the punctuation after it and a line that ends in a hyphen take nothing more off, and the quarter em between Japanese and Latin text counts only where the line ends there. Kinsoku Shori Type and Burasagari Regular measure lines the same way; right-to-left lines and Mojikumi None break as before. In a frame that is not a rectangle, or with text wrap, a line's first word is measured as it is set (an opening bracket at its start flush, its last character narrowed) when layout looks for a line wide enough for it, and it ends only where the line may break, so kinsoku keeps an opening bracket with the character after it and a No Break run counts whole (`crates/text/src/layout/wrapping_tests.rs`, `crates/text/src/tests/vertical.rs`). Scores and estimates are unchanged. The Paragraph panel's Mojikumi Set lists the five predefined sets the help page names (None, YakumonoHankaku, GyomatsuYakumonoHankaku, GyomatsuYakumonoZenkaku and YakumonoZenkaku), then Line-end Punctuation Half Width, and `text.setFormat {mojikumi}` takes each of them. YakumonoHankaku sets every bracket, comma and full stop half width and takes a quarter em off each side of a middle dot; GyomatsuYakumonoHankaku keeps punctuation full width inside a line, sets an opening bracket flush at a line's start and a closing mark half width at its end, and takes the quarter em after a middle dot off at a line's end; GyomatsuYakumonoZenkaku keeps punctuation full width and adds a quarter em between Japanese and Latin text; YakumonoZenkaku sets characters as None does. These widths are VectorCraft's own rules, from the help page's one-line description of each set. Both composers and vertical type measure each line as it is set, the sets save with the document and paragraph styles, and a `.ai` save reports the new sets as left out (`crates/text/src/tests/vertical.rs`, `crates/ui-egui/src/panels/paragraph/tests.rs`). Scores and estimates are unchanged. Interface text in characters the interface's fonts lack, drawn in a bundled Japanese, Georgian or Devanagari face or in an installed font that covers them, sits on the baseline of the Latin text beside it, monospace text included (#5816; `crates/ui-egui/src/ui_fonts.rs`, `crates/ui-egui/src/theme.rs`). Character panel menu › Standard Vertical Roman Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {standardVerticalRoman}`, off by default) stands the selected Latin letters, digits and other half-width characters upright one below the other in vertical type instead of rotating them ([formatting Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)); spaces keep their width, tate-chu-yoko blocks stay across the column, and Character Style Options gives it its own checkbox beside Character Alignment. + The Glyphs panel menu (with the East Asian options) offers Traditional, Expert, JIS 04, JIS 90, JIS 78 and JIS 83 Forms, Monospaced Full-Width, Half-Width, Third-Width and Quarter-Width Forms, and Revert To Default Forms ([formatting Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)); each draws the selected characters with the font's OpenType feature for that form (`trad`, `expt`, `jp04`, `jp90`, `jp78`, `jp83`, `fwid`, `hwid`, `twid`, `qwid`), one form at a time, and a form none of the faces that draw the selected text has a feature for is disabled. `text.setFormat` and `text.setRangeStyle {glyphForm}` set it; the native file, character styles, the canvas, PDF and SVG (`font-feature-settings`) keep it (`tests::typo::glyph_forms_draw_the_fonts_east_asian_forms`, `typecmd::area_tests::glyph_form_is_one_character_attribute_saved_only_when_set`, `panels::glyphs` tests). Character panel menu › Tate-chu-yoko Settings… (with the East Asian options; `ui.tateChuYokoSettings`, `text.setFormat` or `text.setRangeStyle {tcyUpDown, tcyLeftRight}`, in points, 0 by default) moves a marked tate-chu-yoko block in vertical type up by a positive Up/Down and right by a positive Left/Right ([format East Asian characters in vertical text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/format-east-asian-characters-in-vertical-text.html), [formatting Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)); the block moves as one piece with its first character's values and keeps its one em down the column, on a vertical path it moves toward the path's start and to the path's left, automatic digit blocks do not move, Reset Panel sets both back to 0, and character styles and the native file keep them. A file whose character styles hold a Tate-chu-yoko Up/Down or Left/Right offset past the coordinate limit (`MAX_COORD`) either way opens with the nearer end, as the type's own offsets do; an offset within it stays as saved. Character panel › Insert Aki Left and Insert Aki Right (with the East Asian options; `text.setFormat` or `text.setRangeStyle {akiLeft, akiRight}`, thousandths of an em from 0 to 1000, 0 by default) add space before and after each selected character, measured as tracking is, and kept as set through justification ([the help page](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)); before and after follow the reading order in vertical and right-to-left type, character styles carry both values (Character Style Options › Advanced Character Formats edits them), and a file holding a value outside the range opens with the nearer end. + Insert Aki Left and Right open from an `.ai` file's text document (read in thousandths of an em, the unit the [scripting reference](https://web.archive.org/web/20160410092022/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/pdf/illustrator/pdfs/illustrator_scripting_reference_applescript.pdf#page=90) gives `aki left` and `aki right`; VectorCraft's own rule for the stored value) from the run, its character style, the styles that one is based on, `[Normal Character Style]` and the document's defaults in that order. A negative value or one that is not a number opens as 0, and a value past 1000 opens as 1000. An `.ai` save writes each run's nonzero values in the form that reader reads. A legacy `.ai` save writes type with Insert Aki as text without it and reports that it is left out; type it writes as outlines keeps the space. Character panel › Tsume (with the East Asian options; `text.setFormat` or `text.setRangeStyle {tsume}`) narrows the space around each selected character ([the help page](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)); by VectorCraft's own rule the value is a percentage from 0 to 100, 0 by default, of the blank space on each side of the character's ink that horizontal type takes away without changing the glyph's shape, with tracking, kerning and Insert Aki added after it. Character styles carry it (Character Style Options › Advanced Character Formats edits it), and a file holding a value outside the range opens with the nearer end. The Character panel's All Caps, Underline and Strikethrough buttons and its menu's All Caps, Underline, Strikethrough, Proportional Metrics, Tate-chu-yoko and No Break show off while only some of the selected characters have the attribute, and choosing one then turns it on for all of them, as `type.underline` (Cmd+Shift+U) does for underlining; the Character Alignment and Digits submenus check no item while the selected characters differ. `text.setFormat` refuses a value that is not true or false for its on/off attributes, as `text.setRangeStyle` does. - **Transparency:** opacity masks (clip/invert/disable/link), exported as SVG `<mask>` and PDF soft masks. The constant alpha soft mask that PDF and `.ai` export draw a CMYK page with transparency through is white, so applications that read every soft mask by its luminosity show the page too (#1359, part of #1286). @@ -1422,8 +1466,10 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Linked opacity masks follow geometry effects, the Free Transform distort and envelopes:** when masked art moves, a linked opacity mask moves with it and an unlinked one stays in place ([Transparency and blending modes](https://helpx.adobe.com/illustrator/using/transparency-blending-modes-alt.html)). Applying that rule when art is reshaped, as below, is VectorCraft's own rule. When a group's or layer's geometry effects (Transform, Free Distort, the Warp effects and the others) reshape its members, the linked masks of the paths, compound paths and groups inside it take the same effects, nested and inverted masks included, with the type and live objects in a mask's art outlined first. Each Transform copy of a masked path carries its own mask. An image or symbol instance that a group's Transform effect moves carries its linked mask too, and with Scale Strokes & Effects on, the mask's strokes scale as a path's mask's do. With Transform Objects off, a member's mask takes the effect's stroke and pattern changes as the member does. The linked masks in the art of a symbol instance in perspective are projected with that art. A Free Transform tool distort drag (`object.distort`) warps a linked mask with its object, in a group too, in the same undo step. An envelope bends only a linked mask. When a mask can't take an effect as the art it masks does (a path in either would pass the geometry budget, the mask would get fewer Transform copies, the mask's art holds an image or symbol instance and the effect is not Transform, a Warp effect would bend an image that has a linked mask, or the effect is a live-effect plug-in that paints its pieces), the art and its masks keep their shape under that effect. The copies of a masked path count the art of its mask against the budget. Existing documents draw differently in four cases: a geometry effect on a group whose members have linked masks moves those masks; an envelope no longer bends an unlinked mask; art with linked masks keeps its shape under an effect that its masks can't take; and a Transform effect can make fewer copies of a masked path near the budget (effects `group::tests::a_groups_geometry_effects_reshape_a_members_linked_mask_with_it`, `group::tests::a_groups_geometry_effects_reshape_nested_and_inverted_masks`, `group::tests::a_compound_paths_and_a_layers_members_masks_take_the_effects`, `group::tests::a_groups_effects_reshape_a_live_object_in_a_members_mask`, `group::tests::each_transform_copy_of_a_masked_member_carries_its_mask`, `group::tests::a_groups_transform_moves_an_image_members_linked_mask`, `group::tests::a_groups_transform_moves_a_symbol_instance_members_linked_mask`, `group::tests::a_groups_transform_moves_a_linked_mask_whose_art_is_an_image`, `group::tests::art_whose_mask_holds_an_image_keeps_its_shape_under_a_warp`, `group::tests::art_with_a_masked_image_keeps_its_shape_under_a_warp`, `group::tests::a_transform_with_scale_strokes_scales_the_masks_of_images_and_paths_alike`, `group::tests::a_transform_of_strokes_only_scales_a_members_mask_strokes`, `group::tests::perspective_projects_the_masks_in_a_symbols_art`, `group::tests::a_mask_whose_art_passes_the_budget_stays_whole`, `group::tests::art_whose_mask_would_take_fewer_copies_keeps_its_shape`, `group::tests::transform_copies_count_the_art_of_their_masks`, `group::tests::the_mask_of_a_masks_art_copied_whole_counts_against_the_budget`; engine `xform::distort_command_warps_a_linked_opacity_mask_with_its_object`, `xform::distort_command_warps_the_linked_mask_of_a_path_in_a_group`, `envelope_distort::an_envelope_bends_a_linked_opacity_mask_and_leaves_an_unlinked_one`, `plugins::a_painted_group_effect_leaves_art_with_a_linked_mask_as_it_is`). Scores and hours unchanged. - **Image Trace, thin closed outlines:** generated `fit::snap_area_tests` verify nonzero interiors after straightening, opposite closed-boundary winding and Noise controls; see [quality notes](image-trace-quality.md#thin-closed-outlines-with-snap-curves-to-lines). Scores and hours unchanged; open-piece fitting is unchanged. - **Image Trace, curve fitting tolerance:** the outline fitter keeps cutting a run while a point stays farther than the tolerance from its curve, so a run of fewer than six points or one cut 14 times no longer keeps a piece over the tolerance. Pieces already within the tolerance do not change, and noisy art can get more anchors. Tests: `logo::bezier::tests`, `logo::outline::tests`. Scores and hours unchanged. -- **Image Trace, gray photos:** Color and Grayscale smooth a gray photo within its tones before choosing its colors, as they do a color photo. A picture with at least 95% of its opaque pixels within 8 levels across their channels counts as continuous tone when 8 colors leave an error of more than 6 levels and more than 0.065 of the error of one color, instead of 0.1, unless 16 colors leave at most a fifth of the error of 8 (VectorCraft's own values). That exception keeps gray flat art of up to 16 clean levels on its old route; anti-aliased or noisy gray flat art can now count as continuous tone too. Most gray photos the change reaches, and very noisy gray scans of flat art, trace with fewer specks and fewer staircase edges. Some 16 Colors and High Fidelity Photo palettes of gray photos grow toward the requested count, with more anchors and regions. Some gray illustrations and sketches get more anchors and staircase edges at 16 Colors and High Fidelity Photo, and some 6 Colors traces get more staircase edges. Tests: `tests::a_gray_photo_is_continuous_tone_as_its_color_original_is`, `tests::a_gray_photo_is_smoothed_before_it_is_traced`. Scores and hours unchanged. -- **Image Trace, tinted photos:** Color and Grayscale smooth a sepia, single-hue or duotone photo within its tones before choosing its colors, as they do a gray photo. A picture with at least 95% of its opaque pixels within 6 levels of its tone curve counts as continuous tone under the same 0.065 rule as a neutral picture. The tone curve runs through the median color of each 8-level stretch along the direction in which the picture's colors spread the most, and a pixel on it must also lie within 6 levels of the plane the colors spread along most, so art in several unrelated colors is not counted (VectorCraft's own rule and values). The neutral rule's exception for 16 colors leaving at most a fifth of the error of 8 applies to it too. Clean tinted bands of 2, 3 and 9 levels and tinted scans of flat art with up to 8 levels of noise stay on the flat-art route. On the synthetic tinted photos the 16 Colors trace keeps 12 to 15 colors instead of 6 to 13, with 525 to 708 anchors instead of up to 1,402. A duotone with strong noise on each channel can still miss the curve and stay unsmoothed. Tests: `tests::a_tinted_photo_is_continuous_tone_as_a_gray_photo_is`, `tests::small_accents_of_other_colors_leave_a_tinted_photo_continuous_tone`, `tests::tinted_flat_art_stays_flat_art`, `tests::pictures_without_tones_are_not_continuous_tone`, `tests::a_tinted_photo_is_smoothed_before_it_is_traced`. Scores and hours unchanged. +- **Image Trace, gray photos:** Color and Grayscale smooth a gray photo within its tones before choosing its colors, as they do a color photo. A picture with at least 95% of its opaque pixels within 8 levels across their channels counts as continuous tone when 8 colors leave an error of more than 6 levels and more than 0.065 of the error of one color, instead of 0.1, unless 16 colors leave at most a tenth of the error of 8 (VectorCraft's own values). That exception keeps gray flat art of up to 16 clean levels on its old route; anti-aliased or noisy gray flat art can now count as continuous tone too. Most gray photos the change reaches, and very noisy gray scans of flat art, trace with fewer specks and fewer staircase edges. Some 16 Colors and High Fidelity Photo palettes of gray photos grow toward the requested count, with more anchors and regions. Some gray illustrations and sketches get more anchors and staircase edges at 16 Colors and High Fidelity Photo, and some 6 Colors traces get more staircase edges. Tests: `tests::a_gray_photo_is_continuous_tone_as_its_color_original_is`, `tests::a_gray_photo_is_smoothed_before_it_is_traced`. Scores and hours unchanged. +- **Image Trace, tinted photos:** Color and Grayscale smooth a sepia, single-hue or duotone photo within its tones before choosing its colors, as they do a gray photo. A picture with at least 95% of its opaque pixels within 6 levels of its tone curve counts as continuous tone under the same 0.065 rule as a neutral picture. The tone curve runs through the median color of each 8-level stretch along the direction in which the picture's colors spread the most, and a pixel on it must also lie within 6 levels of the plane the colors spread along most, so art in several unrelated colors is not counted (VectorCraft's own rule and values). The neutral rule's exception for 16 colors leaving at most a tenth of the error of 8 applies to it too. Clean tinted bands of 2, 3 and 9 levels and tinted scans of flat art with up to 8 levels of noise stay on the flat-art route. On the synthetic tinted photos the 16 Colors trace keeps 12 to 15 colors instead of 6 to 13, with 525 to 708 anchors instead of up to 1,402. A duotone with strong noise on each channel can still miss the curve and stay unsmoothed. Tests: `tests::a_tinted_photo_is_continuous_tone_as_a_gray_photo_is`, `tests::small_accents_of_other_colors_leave_a_tinted_photo_continuous_tone`, `tests::tinted_flat_art_stays_flat_art`, `tests::pictures_without_tones_are_not_continuous_tone`, `tests::a_tinted_photo_is_smoothed_before_it_is_traced`. Scores and hours unchanged. +- **Image Trace, flat art of 10 to 16 levels:** the exception for 16 colors leaving at most a tenth of the error of 8 also applies to a neutral or tinted picture whose 8-color error is more than 0.1 of the error of one color (VectorCraft's own values), so Color and Grayscale trace clean gray, sepia, single-hue and duotone art of 10 to 16 evenly spaced levels as flat art, without smoothing it first. At 16 Colors, 16 gray or sepia levels crossed by two 1 px lines trace as the 35 regions the lines cut them into instead of 33, and Automatic traces 16 clean sepia levels in 9 colors instead of 4. Tests: `tests::flat_art_of_up_to_sixteen_clean_levels_stays_flat_art`, `tests::thin_lines_on_flat_art_of_up_to_sixteen_clean_levels_are_traced`. Scores and hours unchanged. +- **Image Trace, clean gray photos:** the exception for flat art of up to 16 clean levels now applies when 16 colors leave at most a tenth of the error of 8, instead of a fifth (VectorCraft's own values). On the synthetic gray photo with 0 to 2 levels of noise, 16 colors leave 0.19 of the error of 8, so Color and Grayscale now count it as continuous tone and smooth it before tracing, as they do its color original. Clean gray, sepia, single-hue and duotone art of up to 16 levels, where 16 colors leave no error, stays on the flat-art route. Test: `tests::a_clean_gray_photo_is_continuous_tone_as_its_color_original_is`. Scores and hours unchanged. - **Image Trace, JPEG blocks:** Color, Grayscale and Black and White traces smooth the edges of a JPEG's 8 × 8 blocks before tracing, so a dark ground whose tone changes slowly is no longer traced as staircases along the block edges. The block grid is found in the image itself: the mean step between neighboring pixels must peak at one position in eight, across and down. A cropped JPEG and a JPEG saved in another format are smoothed too. A picture of flat 8 × 8 cells is left as it is, and art made of 8 × 8 cells with slight texture inside each cell is smoothed as a JPEG copy would be. A small step at a block edge, with no edge in the eight pixels around it, is spread over those eight pixels, and larger steps are kept, as the deblocking filters of ITU-T H.263 Annex J and MPEG-4 Part 2 Annex F.3.1 do. Black and White smooths only the smallest steps, and traces of more than 16 colors move every row of a stretch of eight by the same amount (VectorCraft's own rule and values). On a 4000 × 3000 photo saved as JPEG, the straight outline segments that lie on the block grid fall from 52% and 51% (across and down) to 24% and 29% at 16 Colors, and from 54% and 51% to 43% and 42% at High Fidelity Photo; staircase runs fall from 83 to 67 (16 Colors), 11 to 1 (6 Colors), 30 to 13 (Black and White Logo) and 428 to 403 (High Fidelity Photo). A 600 px photo saved as a quality-40 JPEG has 4 staircase runs instead of 2 at 16 Colors. Images without a block grid trace as before. Tests: `tests::a_jpegs_blocks_are_not_traced_as_steps`, `deblock::tests`. Scores and hours unchanged. - **Image Trace, Document Library color groups:** with Document Swatches, the panel's Colors menu and `"colorGroup"` trace with one color group's colors instead of every swatch, as the public panel documentation describes Document Library; code-drawn tests in `crates/engine` and the panel. - **Image Trace, Document Library colors:** with Document Swatches, traced fills and strokes use the displayed colors of process, global, spot and tint swatches without links, so editing a swatch leaves the trace unchanged; swatch-library colors are also unlinked; code-drawn tests in `crates/engine`. @@ -1437,6 +1483,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Image Trace, Flat Logo working size:** Flat Logo traces at most 1024 px on a side; a larger decoded raster (the 64-megapixel copy for a bigger image) is averaged down in whole-number blocks first, and the trace's `warnings` name the size it was traced at and the image's own size, in place of the slower-trace and 64-megapixel notes; code-drawn 1024 and 1025 px tests in `crates/trace` and `crates/engine`. - **Image Trace, Flat Logo working size:** Flat Logo traces at most 1024 px on a side; a larger image is averaged down by a whole factor first, and the trace's `warnings` name the size it was traced at and the image's own size, in place of the slower-trace and 64-megapixel notes; code-drawn 1024 and 1025 px tests in `crates/trace` and `crates/engine`. - **Image Trace, Preview:** the Image Trace panel's Preview checkbox, before Trace, is on by default, and a setting change traces the selected Image Trace object again at once. Off, changes wait in the panel until Trace applies them as one undo step, or until Preview is turned on again. Changes stay with the object they were made for while another object is selected. When Preview is turned on with that object not selected, the object is traced with its changes when it is selected again. Preview is kept with the UI preferences, and Reset to Default leaves it. The `imageTrace.preview` command turns it on or off. +- **Image Trace, traces made off the UI thread stay with their document:** a trace made away from the command (`TraceRun`) applies only in the document it was made in. In another open document with the same image, object and settings, `imageTrace.make` and `imageTrace.makeAndExpand` drop it and trace that document's image, as one undo step (VectorCraft's own rule). Test: `a_trace_run_applies_only_in_its_own_document` in `crates/engine`. Scores and hours unchanged. - **Image Trace small contours:** closed fits too small to form an editable subpath retain their positioned outline, including holes. Source-generated island, hole/winding and stepped-region regressions cover Corners and Noise; defaults, parity scores and estimates are unchanged. - **Image Trace, custom presets:** Manage Presets next to the Image Trace panel's Preset dropdown saves the panel's settings as a new preset under a name (Save as New Preset…) and renames or deletes the saved preset shown; built-in presets don't change. Saved presets are kept with the preferences and follow the built-in ones in the panel, Control bar and Properties preset lists. `imageTrace.presets.save` and `imageTrace.presets.delete` save, rename and delete them, `imageTrace.presets` lists them, and `imageTrace.make {preset}` traces with one by name. - **Image Trace, preset buttons:** six buttons above the Image Trace panel's Preset dropdown choose a preset as the dropdown does, for the options the [help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/image-trace-panel-options.html) lists before Preset. The presets each button chooses are VectorCraft's own: Auto Color chooses Auto Color, High Color chooses High Fidelity Photo, Low Color chooses Low Fidelity Photo, Grayscale chooses Shades of Gray, Black and White chooses Black and White Logo, and Outline chooses Outline. With Preview on, a click traces the selected Image Trace object again as one undo step; with nothing traced selected, it changes the panel's settings only. The button of the panel's preset shows as selected. @@ -1451,15 +1498,18 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Image Trace, cut-out edges:** in Color and Grayscale, a semi-transparent pixel (alpha 128 to 254) on the edge of a cut-out image, beside a pixel that is less than half opaque, traces as a color of the fully opaque pixels within two pixels of it when its own color is that color or a darker shade of it, and of several such colors, as the one the most of those pixels have (art across a transparent gap does not count), so a darkened edge tone no longer traces as a 1 px sliver of an unrelated palette color, while a thin semi-transparent outline of another color keeps its own; code-drawn cut-out, opaque-edge and thin-outline tests in `crates/trace`. - **Image Trace, cut-out edges choose no color:** in Color and Grayscale, the edge pixels that take the color beside them, and the semi-transparent pixels within two pixels of them whose color is also the opaque art's color blended with the background, do not count when the palette or the grays are chosen, so the edge of a cut-out image no longer adds a second shade of a color to Auto Color's palette, takes away an outline's color or takes a gray of its own; beside those pixels, the anti-aliasing between a color and an outline drawn along the edge is no color of Auto Color's own when it lies at least 0.45 of the way from the color to the outline and at least one in 32 of its pixels has both around it (edge pixels that choose no color count when they lie within 2.5 Oklab × 100 of the nearest of those colors): its pixels trace as the outline, so a thin outline stays a ring of few pieces, except beside an outline along the edge with a region of 8 pixels of its own, where each takes the nearer of the two, so a wider outline is not drawn wider; an outline over the edge in the color of other art traces in that color, while an opaque rim drawn along the edge keeps its color, also where other art reaches it; a thin semi-transparent outline of another color still counts, and opaque images trace as before; code-drawn cut-out outline, rim, opaque line and grayscale edge tests in `crates/trace`. - **Image Trace, blurred edges:** in Color with a Limited palette of at most 16 colors (3 Colors, 6 Colors, 16 Colors) and in Grayscale with at most 16 grays (Shades of Gray), by VectorCraft's own rule (RGB distances, 0 to 255 a channel), a blend pixel with no unblended pixel of its own color within 4 pixels takes the nearer side of the pair of colors within 8 pixels that it is best a blend of, of the 8 colors within 8 pixels nearest to its color, 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; it keeps its color when it is one of the pair. Grayscale compares lightness. The in-between tones of an edge blurred over several pixels no longer trace as rings around it. High Fidelity Photo, Low Fidelity Photo and Black and White trace as before, and so do Automatic, Full Tone and Document Library palettes. Noisy and textured images settle more of their pixels. By `crates/trace/tests/quality` (256 px variants), 16 Colors on blurred flat art went from 9.0 paths to 3.0, 158 anchors to 34 and 0.239 px off to 0.069, and 6 Colors from 6.0 paths to 3.0 and 0.226 px off to 0.071; askew shapes take up to 11 px more area in colors the art does not have, and with 16 Colors the largest distance from a thin line's outline to the trace goes from 23.5 px to 45.3 (see [quality notes](image-trace-quality.md#blurred-edges)). Code-drawn blurred-disc and grayscale ramp tests in `crates/trace`. +- **Image Trace, preset Paths, Corners and Noise:** every built-in preset but Auto Color and Flat Logo traces at Paths 50, and so do their enhanced versions; among those presets, Corners is 100 in Technical Drawing, 75 in Default, Black and White Logo, Line Art and Outline and 50 in the other eight, and Noise is 1 to 90 px by preset. Palettes and color counts are unchanged. Figures for these presets in the other Image Trace entries were measured at the earlier values. By `crates/trace/tests/quality`, High Fidelity Photo goes from 5,494 anchors to 3,136 and Black and White Logo from 27 to 14, while 16 Colors on flat art goes from 0.100 px off to 0.123 (see [quality notes](image-trace-quality.md#preset-paths-corners-and-noise)). Test `presets_have_their_paths_corners_and_noise` in `crates/trace`. - **Image Trace, simpler contour walk:** `contour::trace_mask` works out each turn from the pixels during the walk, with no precomputed direction table and no assertion; identical loops to the previous walk on every 4 × 4 mask (see [quality notes](image-trace-quality.md#a-simpler-contour-walk)). - **Image Trace, measured:** `crates/trace/tests/quality` traces drawings made from known vector art with every preset and [`image-trace-quality.md`](image-trace-quality.md) records the numbers against the baseline. Black and White, Grayscale and Color place each edge by the blend of the pixels across it (to a fraction of a pixel on anti-aliased and blurred images; hard-edged images are read as staircases) and fit outlines as Flat Logo does. *Measured* on each preset's own inputs, all sizes and variants: Default's outlines went from 0.31 px off on average to 0.09 (largest 1.51 to 1.02), Black and White Logo's from 0.27 to 0.06 with 0.3 kinks per trace where it had 15, and the gaps between abutting paths from 64 px to 22. On clean curved shapes Black and White Logo is 0.02 px off (the open tracer measured beside it: 0.20). The palette is made of the picture's own colours (blends along edges take none of it, colours that noise made of one colour merge, a blend pixel goes to one of the two colours it lies between; #1504): 16 Colors on flat art, all variants, went from 70 paths to 4.2 and from 5.1 px off to 0.13, with no path left in a colour the art doesn't have (5.9 before). Photos are smoothed within their tones before they are quantised and stacked layers go by lightness (#1516): High Fidelity Photo went from 3,653 paths to 121 with its colour error down from 2.30 to 1.75, and a 16 megapixel photo-like image is traced in 3.5 s where 4 megapixels were refused. Since then, by the same harness: outlines are cut at their junctions and each shared piece is fitted once (#1535: gaps and overlaps between abutting paths 22 to 50 px of area down to under 2); layers are traced within the box of their pixels and a few at a time (#1546: a 16 megapixel photo 3.9 GB to 0.9 GB); black and white are read against the image's own black and the paper near each edge (#1563, for thin lines in blurred and scanned art); Ignore Color and the Auto Color and Outline presets (#1574); Snap Curves To Lines levels lines within 2.5 degrees of level or upright (#1593, the angle our choice); Create: Strokes puts centre lines in the middle of their ink and makes them as wide as it (#1595: Outline 0.295 to 0.052 px from the true centre line, 18.4 to 2.7 anchors a stroke); sharp corners whose pixel is mostly outside the shape stay corners (#1609: Default 69% to 76% kept). Three options, each off unless asked for as the legacy presets have them: Shapes (#1609: 57 to 62% of plain circles, ellipses, rectangles and regular polygons come out as live shapes, rounded rectangles rarely), Auto Grouping (#1618: paths grouped with what lies inside them, the same picture) and Gradients (#1627: linear gradients traced as one gradient-filled path; on gradient inputs 6 Colors' colour error 2.12 to 0.62 with 6.4 to 3.4 paths, none found in flat art). Snap Curves To Lines moves no end of a line by more than 1.6 px, so long lines a degree or two off stay as the image has them (#1647: Technical Drawing's largest distance 4.21 px to 1.46). Flat Logo takes the tones a scan's uneven paper makes of one colour for one colour (#1657: on scans 470 paths and 21 px off to 8.5 paths and 0.09 px). Shapes finds rounded rectangles and shapes in aliased, blurred and scanned art (#1845: 57 to 62% of the plain shapes up to 98 to 100%, no false shape but one line 2 px wide). Stroked lines get square caps where their ink is cut square, and a wide end that turned towards a corner goes back on its line (#1846: Outline's largest distance 2.94 px to 0.88, 14 anchors to 10). Each of the 14 documented presets has an enhanced version with Auto Grouping and, in all but High Fidelity Photo, Shapes (#1847), measured beside its preset: equal or better within 0.005 px and 1% of edge ΔE on every preset's own inputs (Default 0.091 to 0.083 px); Auto Grouping keeps traced order in its groups, which removed a light seam along the counters of letters. Gradients grows a gradient over the pixels noise and soft rims took off it (#1848: blurred and noisy linear gradients 3 to 11 paths beside the gradient down to 0.5 with 6 Colors, 24 to 56 down to 0.5 to 1.5 with High Fidelity Photo). Silhouettes is 0.52 px off because its threshold is 200 (0.11 px at 128). Still weak, by the same numbers: rounded rectangles and other line-and-arc outlines take 12 to 16 anchors (the fitter does not split lines from arcs), blurred and scanned polygons lose corners, hairlines under half a pixel are lost to the threshold, aliased art is about 0.25 px off, a scan's uneven paper splits into tones when more colours are asked for than the art has, stroke junctions stay at their skeleton pixels, a three-stop gradient in a small or scanned disc is not found, radial gradients stay bands (a draft, #1849, traces them; the documented option is for linear ones, so it waits for a decision), near-regular polygons a few dozen pixels across are made regular with Shapes (up to 0.5 px off), and aliased stroked lines are 0.8 px off at worst. - **Gradient mesh from an image:** Object › Create Gradient Mesh (`object.mesh.create`) on an embedded image makes a mesh of 1 to 50 rows and columns over the picture's rectangle, placed with the image's transform; each point takes the alpha-weighted average colour and the opacity of the area around it, and Appearance and Highlight apply. A linked image is refused with a message to embed it (#1676). Scores and hours unchanged. - **Gradient mesh keeps the object's outline (#2752):** Create Gradient Mesh, a Mesh tool click and Expand of a gradient to a mesh lay the mesh's border on the path's outline: each border edge is the piece of the outline between its two points, and where the outline bends through an anchor (a star's points, an L-shape's inner corner, a rounded rectangle's arcs) no single curve follows, the mesh takes a line through that anchor, up to 256 each way. Holes and other subpaths of a compound path are still left out. Public reference: [About mesh objects and Create mesh objects, CS3 user guide, pages 184 to 185](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf) (mesh lines carry anchor points as well as mesh points). Tests: `a_mesh_keeps_the_outline_of_every_shape` and `a_mesh_takes_lines_only_where_the_outline_needs_them` in `crates/doc/src/live.rs`, `a_mesh_tool_click_keeps_a_stars_points` in `crates/engine/src/tests/live.rs`. Scores and hours unchanged. - **A point on a mesh's outline is on the mesh:** a point exactly on the outline of a gradient mesh (within a millionth of a point) locates on the edge it lies on, on all four sides alike and with no tolerance, as it already did on the top and left edges, so `object.mesh.addLine` and Create Gradient Mesh `at` a point on the bottom or right edge add their lines there instead of reporting the point outside, and the Eyedropper samples the mesh's color there; a point just outside still needs `tolerance`. Tests: `mesh_locate_takes_a_point_on_any_side_of_the_outline` in `crates/doc/src/live.rs`, `mesh_add_line_exactly_on_the_edge_needs_no_tolerance` in `crates/engine/src/tests/live.rs`. Scores and hours unchanged. - **Several mesh points at once (#4207, #4208, #4170):** the Mesh tool and Direct Selection pick several points of a gradient mesh or mesh envelope: Shift-click adds a point or takes a picked one away, Direct Selection's marquee picks the points inside it (Shift toggles them) and selects their meshes, and its click on a mesh line picks the line's two ends and one inside a patch the four points around it. The picked points show filled; dragging one moves them all as one undo step and the arrow keys nudge them (`object.mesh.movePoints {id, points, dx, dy}` or `{items, dx, dy}`), and a click on one of several picked points picks it alone. A solid fill colour (`paint.setFill`: Color panel, Swatches, Eyedropper) recolours every picked point, and the Transparency panel's Opacity fades them instead of the object, the panel showing their opacity (blank when it differs); `object.mesh.setPointColor` takes `points` or `items`. Public reference: [Edit mesh objects](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-meshes/edit-mesh-objects.html) (Shift selects multiple mesh points; a fill colour colours the selected point), [Macworld, gradient mesh](https://www.macworld.com/article/202693/gmesh2.html) (Direct Selection: a mesh line selects the points at both ends, a patch the points around it, Shift-click adds or removes points), [Peachpit](https://www.peachpit.com/articles/article.aspx?p=1638270) (each mesh point can have its own colour or transparency). Tests: `shift_clicks_pick_mesh_points_that_drag_and_nudge_together` and `direct_selection_picks_mesh_points_by_marquee_line_and_patch` in `crates/tools/src/meshedit.rs`, `picked_mesh_points_take_the_fill_opacity_and_drag_together` in `crates/engine/src/tests/editcolors.rs`, `mesh_points_move_and_colour_together` in `crates/engine/src/tests/live.rs`. Scores and hours unchanged. +- **Picked mesh points in the panels** (VectorCraft's own rule): with points of a gradient mesh picked by the Mesh tool, Direct Selection or the Lasso, the Fill proxy, the Color panel and the Color Wheel show the first picked point's color, so their sliders keep the color a drag sets, and "?" shows when the picked points' colors differ. The Control bar shows the first picked point's opacity. Tests: `the_fill_proxy_shows_the_picked_mesh_points_color`, `the_fill_proxy_follows_where_the_fill_goes_with_an_appearance_row_active` and `the_fill_proxy_counts_picked_mesh_points_beside_other_objects` in `crates/engine/src/tests/xform.rs`, `picked_mesh_points_are_the_color_the_panel_shows_and_edits` in `crates/ui-egui/src/panels/color/tests.rs`, `picking_mesh_points_shows_their_opacity` in `crates/ui-egui/src/panels/transparency.rs`. Scores and hours unchanged. - **Image Trace Flat Logo mode:** a fourth mode beside Black and White, Grayscale and Color, for flat-colour logos. Each pixel is read as a blend of the logo's colours (found automatically or named), the blend is interpolated smoothly and every outline is placed where two colours are equally present, so edges are accurate to a fraction of a pixel. Outlines are then cleaned: corners the blur rounded are put back, near-straight runs and near-circular arcs become exact lines and arcs, the rest is fitted with as few Béziers as the tolerance allows, touching colours overlap by a hair so no gap opens, and an outline that strays from the raw contour is fitted plainly instead. Gradients and photos are refused with advice to use Color. Line art whose only solid area is white paper (strokes a pixel or two wide) takes its colours from the strokes' cores, with the lighter shades along a stroke's anti-aliased edge folded into its ink; a page whose ink (a channel at least 48 below white) covers under 1% of it traces to nothing, as blank paper does. *Measured* (a local experiment, not run in CI): a flat-colour logo's vector original was rendered down to a soft 199 × 100 px transparent PNG, traced, and the result compared with the original at 1600 px wide. The built-in colour presets (6 Colors, 16 Colors, High Fidelity Photo, Low Fidelity Photo) had a mean edge error of 2.5 to 3.4 px and region overlap of 0.88 to 0.91; Flat Logo had 0.78 px and 0.966 (0.48 px and 0.975 from a crisp source), in about 0.1 s. Limits: flat-colour art only; needle-thin sharp tips are shortened by about 1.7 source pixels because the blur erases them; it works at no more than 1024 px on the long side (larger images are averaged down first); only one logo family has been scored against a vector original. - **Image Trace, Flat Logo named colors only:** with `logoColors` named, `"logoWhite": false` traces those colors only, so white areas take the nearest of them and no white is added; a named white is kept, and enclosed transparent areas stay holes; code-drawn tests in `crates/trace` and `crates/engine`. - **Image Trace, Flat Logo flat-art check with named colors:** with `logoColors` named, whether the image is flat art is judged by its own colors, as many as are named, with white, or as the Colors setting gives, whichever is more. Named colors 20 levels off a flat badge's colors still trace it, a hatch on a light ground gives the same result with close and far named colors, a gradient's refusal score does not depend on how far the named colors are from it, and areas of colors that were not named are traced in the named colors instead of being refused; code-drawn tests in `crates/trace`. +- **Image Trace, Flat Logo with a color between two others:** an anti-aliased edge pixel between black and white is read as a blend of black and white, not of black and a gray that lies between them, when the flat areas around it and the pixels beside it show that edge, so a black disc beside a gray square on white, with sharp edges or edges blurred by up to about half a pixel, traces with one gray path, the square, instead of the square plus 8 to 24 gray slivers around the disc with the colors found or named exactly (an edge blurred by a pixel or more, or pixel noise of a level or more, can still leave gray slivers); gray strokes two and three pixels wide beside black stay gray (a soft-edged gray stroke about two pixels wide that touches black traces as black and white, and a short one about three pixels wide can lose most or all of its gray), and a one-pixel gray line of at least 13 touching pixels between black and white stays gray (a shorter one, or one that falls between pixels or is blurred, traces as black and white); code-drawn tests in `crates/trace`. - **Image Trace, Keep Colors:** `"keepColors": ["#rrggbb", …]` traces only the palette colors near a listed color (Abutting: each with the paths the trace of every color gives it; Overlapping: not reaching under the colors left out), in Black and White, Grayscale and Color; code-drawn tests in `crates/trace` and `crates/engine`. - **Advanced art:** live Blends (steps/distance/smooth colour, editable spine, anchor-targeted Blend tool, faithful interpolation, knockout), Envelope Distort (warp/mesh/top object, Reset, full Envelope Options, mesh handles, Edit Contents; type, images, symbols, gradients, patterns and appearance distorted everywhere), Liquify tools with options and pen pressure, Puppet Warp with rotating pins, Perspective Grid with presets, movable planes and projected type (choosing a perspective tool shows the grid; Hide Grid hides it with the tool still chosen), Gradient Mesh, Shape Builder (stroke-only open paths and lines cut the regions they cross and enclose regions of their own, and regions they bound merge without seams where the lines cross at rounded coordinates (#893); filled open paths count as closed; erase mode while Alt/Option is held: a minus pointer, red highlights of what will go, a click or drag deletes the regions touched, the pieces of open lines and the edges (outline pieces between the points where paths meet, opening their paths there) it passes over, one undo step, `shapeBuilder.merge {erase}` and `shapeBuilder.regions` edges over MCP), Live Paint (every path an edge, open lines included), Image Trace (12 presets, colour layers traced in parallel; a trace past two million anchor points is refused with advice rather than running out of memory, an image over 64 megapixels is traced scaled down to that size (aspect kept, paths at the image's own size) and one over 192 megapixels is refused, and a selection too large to outline shows its bounds (#525); Object › Image Trace › Make and Make and Expand trace at once with the Default preset, #543; with an image selected the Control bar and the Properties panel show Image Trace, whose arrow traces with any preset, Mask (`object.maskImage`: a clipping path on the image's outline, selected so its handles crop), Crop Image (a crop box on the image, starting on its part over the artboard, dragged by its handles or inside it, the outside dimmed, with X/Y/W/H, Apply and Cancel in the Control bar, Enter and Escape, #734; an image that isn't turned or skewed, isn't CMYK and can be read at its recorded size is cut from its own pixels when the crop edges fall on its pixel grid, copied as they are without resampling; any other image is drawn, #5534; `object.cropImage {rect}` for agents, `{trim: true}` cuts an image to its pixels that aren't fully transparent, pixel for pixel) and Embed or Unembed in place of Fill and Stroke; with an Image Trace object selected, its Preset (choosing another traces again), View, the Image Trace panel and Expand, plus Release in Properties; the five View modes (Tracing Result, with Outlines, Outlines, Outlines with Source Image, Source Image) redraw a trace on screen without tracing again, are saved with it and `imageTrace.setView` sets them, while exports and Expand keep the result; the panel's Advanced section is a header that stays open or closed as it was left (part of #641); Color mode's Palette: Limited, Full Tone (as many colours as the tones need, Less … More), Automatic (flat art with its own colours, else Full Tone; a heuristic) and Document Library (the most used colours of the document's swatches or a swatch library, filled with the swatch colours as they are), part of #641; Advanced › Create: Fills and/or Strokes, where lines up to the Stroke width trace as stroked centre lines (distance transform, thinning, a skeleton graph with spurs pruned, curve fitting; one width per line; without Fills, wider areas become stroked outlines), part of #641), pattern swatches with pattern editing mode, live Repeat (radial/grid/mirror). A single selected mirror repeat shows a prominent axis with a center move handle and two rotation handles. Drag the line or center to change spacing, or an end to change angle; Shift snaps rotation to 45°. The original artwork stays in place, the reflected copy previews live, Escape cancels and each drag takes one undo step through `object.repeat.options`. Controls follow zoom/view rotation and hide with edges or the bounding box. Engine and headless canvas regressions passed for gestures, history and visibility; native move, rotation and Escape screenshots were reviewed. [Public mirror-repeat reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-mirror-repeat-options.html). A single selected grid repeat shows a handle below the grid for rows, one right of it for columns and one past its bottom-right corner for both, and sliders between its first two columns and rows for the horizontal and vertical spacing; the source keeps its size, each drag is one undo step and Escape cancels it ([public grid-repeat reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html), #2691). Object › Expand turns radial, grid and mirror repeats into groups of their instances (#1765, #1756). Choosing the Blend tool again while it is active (its toolbar button, W or `tool.select`) finishes the blend: the object clicked first is dropped and the next click no longer adds to the blend just made, so the click after it starts a new blend ([Blending objects](https://web.archive.org/web/20241217212108/https://helpx.adobe.com/illustrator/using/blending-objects.html)). @@ -1479,9 +1529,11 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Object › Live Paint › Merge adds the other selected paths and Live Paint groups to the bottom selected Live Paint group ([Live Paint groups](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/live-paint-groups.html)), which keeps its id, the paint of its faces and edges, and its name, lock, visibility, transparency, appearance, opacity mask and graphic style link. Object › Live Paint › Make with a Live Paint group selected, and a Live Paint Bucket click on a selected path beside a selected Live Paint group, add the paths to that group the same way. Make, Merge and the Live Paint Bucket take paths, compound paths and groups of them; with type, an image or another object among the selection they report that it has to be converted to paths first and change nothing, as type and raster images can't go into a Live Paint group directly ([Create Live Paint groups](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/create-live-paint-groups.html)); before, such an object went among the group's hidden sources and vanished from the canvas. Evidence: `tests_build::live_paint_refuses_type_and_images_and_changes_nothing`. With the Live Paint Bucket selected, Alt-click on vector art samples its fill, stroke and stroke weight into the paint defaults ([Paint with the Live Paint Bucket tool](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html)). On a placed image it samples the image pixel as a solid fill with no stroke. Alt+Shift-click samples only the color under the pointer, including an intermediate gradient color or image pixels, into the active fill or stroke ([Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). Neither click paints or changes the selection or selected art, and the next Bucket click paints with the sampled paint. Evidence: `tests_build::live_paint_bucket_alt_sample_paints_next_face_without_changing_selection`. Double-clicking the Live Paint Bucket opens Live Paint Bucket Options ([Paint with the Live Paint Bucket tool](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html)): Paint Fills (on) and Paint Strokes (off) set whether a click paints faces, edges or both, Highlight turns the outline of the face or edge under the pointer on or off, and Color and Width set it (red and 4 px by default). Faces are outlined at the Width and edges at half of it, as the page says faces are highlighted with a thick line and edges with a thin line. With both on, a click paints the edge within 4 px of the pointer, else the face, and Shift switches to Paint Fills only; with one on, Shift switches to the other. The options last across tool switches and are saved with the preferences (`tool.setOption {tool: "livePaintBucket"}`). Evidence: `builder::tests::{bucket_options_choose_what_a_click_paints, bucket_options_set_the_highlight, bucket_highlights_an_edge_thinner_than_a_face}`, `dialogs::live_paint_bucket::tests::double_clicking_the_tool_opens_its_options_and_ok_sets_them`. + Live Paint Bucket double-click and triple-click, as [the help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html) describes them: a double-click on a face fills it and the faces reached across edges that draw no stroke, and on an edge it paints the edges joined to it with the same stroke; a triple-click fills every face of the group with the face's fill, or paints every edge with the edge's stroke (`livePaint.fill` and `livePaint.strokeEdge` `{scope: "connected" | "samePaint", match?}`; `pointer_gesture` and `ui.pointer` take `tripleclick`). Each click paints as it arrives, as its own undo step, and the paint compared is the one the face or edge had before the first of its clicks that painted it; a first click that made the Live Paint group counts when the face it filled is the clicked face. With Space held for the view tools, a click, double-click or triple-click paints nothing and no face or edge is outlined, and with Cmd/Ctrl held a double-click or triple-click paints nothing. Which faces and edges join and which paints match are VectorCraft's own rules. Evidence: `tests_build::{live_paint_bucket_double_click_floods_across_unstroked_edges, live_paint_bucket_double_click_floods_curved_and_narrow_faces, live_paint_bucket_double_click_floods_across_hidden_edges_and_past_gaps, live_paint_bucket_triple_click_fills_every_face_of_the_same_fill, live_paint_bucket_triple_click_after_making_the_group_matches_the_made_fill, live_paint_bucket_double_and_triple_click_paint_joined_and_same_stroke_edges, live_paint_scope_and_match_are_checked}`, `builder::tests::{bucket_double_and_triple_click_widen_what_a_click_paints, bucket_triple_click_after_making_the_group_on_another_face_matches_its_own_face, bucket_triple_click_with_a_click_on_another_face_between_matches_the_first_fill, bucket_highlights_nothing_with_space_held}`, `tests::build::{live_paint_scoped_fill_and_stroke_skip_parts_with_the_paint, live_paint_bucket_cmd_double_and_triple_click_paint_nothing}`, `tests::livepaint::{a_triple_click_fills_every_face_of_the_same_fill, clicks_with_space_held_paint_nothing}` (MCP). Live Paint Bucket Options has Cursor Swatch Preview, as the [help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html) lists: with the Bucket selected, the active fill or stroke shows above the pointer between the color swatches before and after it in the Swatches panel, and the Left and Right arrow keys pick the swatch before or after it, as the page describes. The selected art keeps its paint. As VectorCraft's own rules, the option is on at first, the arrows step the stroke when the Stroke proxy is in front, they wrap around at the ends and still step with the preview off, a color that is no swatch shows alone until Right picks the first swatch or Left the last, and the arrows do nothing during a fill drag or with no color swatch. Evidence: `tests::build::{live_paint_bucket_arrow_keys_step_the_active_paint_through_the_swatches, live_paint_bucket_arrow_keys_handle_unmatched_paint_few_swatches_and_drags, live_paint_bucket_arrow_keys_pass_swatches_of_the_same_color_for_fill_and_stroke, swatch_arrow_keys_leave_modified_arrows_to_the_shortcuts}`. Live Paint Make preserves the front-most covering source's fill when compound paths share a curved boundary, and Expand keeps the face fills. Regression evidence: `planar::tests::coincident_curves_keep_their_source_faces` checks source order, winding, fill rules and nearby boundaries; `tests::build::live_paint_make_and_expand_keep_abutting_compound_colors` checks native compound paths, Make, Expand and Undo/Redo. This preserves VectorCraft's source-fill rule without changing arrangement precision. Object › Live Paint › Expand keeps the faces and edges that draw on the canvas, with all their fill and stroke rows, so the expanded paths look as the painted group did ([Create Live Paint groups](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/create-live-paint-groups.html)). As VectorCraft's own rule, a face or edge draws when it is shown, its opacity is above 0, and any of its fill or stroke rows is shown, has paint and an opacity above 0 (a stroke also needs a weight above 0), whichever row is on top: a painted lower row under an unpainted top row is kept, and a part whose only painted row is hidden is removed. Merge copies the fill and stroke rows, visibility, opacity and blending mode of each face that draws by this rule, and of each edge, to the rebuilt parts, with their gradients kept at their fit on the old outline and without the strokes' pen pressure, tilt, bearing and rotation. Evidence: `tests::build::{live_paint_expand_keeps_the_faces_and_edges_that_draw, live_paint_merge_carries_the_faces_that_draw, live_paint_merge_leaves_pen_pressure_behind, live_paint_merge_keeps_the_fit_of_carried_gradients, live_paint_merge_keeps_the_visibility_opacity_and_blending_of_carried_parts}`. + `livePaint.info` lists every fill and stroke row of each face and edge, bottom first, with its paint, opacity, visibility, weight for a stroke, and whether it draws by the rule above, beside the top fill, stroke and weight it already reported. Evidence: `tests::build::live_paint_info_lists_every_appearance_row`. Live Paint Gap Options (Object › Live Paint › Gap Options…, `livePaint.gapOptions`): with Gap Detection on, paint stops at the gaps that run from a loose end of a path to the nearest path, up to Small (3 pt), Medium (6 pt), Large (12 pt) or a custom size; Close Gaps With Paths adds an unpainted path across each gap; Preview applies the options live and draws the gaps in the Gap Preview Color. The options are saved, copied and undone with the group, and Merge keeps the bottom group's options when its Gap Detection is on, or else turns Gap Detection on with Small when another merged group has it on. When Gap Detection is off in every merged group, it stays off. View › Show Live Paint Gaps (`view.livePaintGaps`) draws the gaps of the selected Live Paint groups up to their Paint Stops At size, each in its group's Gap Preview Color, until Hide Live Paint Gaps or Hide Edges hides them ([Live Paint gaps](https://web.archive.org/web/20260105111201/https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/find-and-close-gaps-in-live-paint-groups.html)). Double-clicking the Live Paint Selection tool opens its Tool Options ([Live Paint Selection tool options](https://web.archive.org/web/20250904012025/https://helpx.adobe.com/illustrator/using/selecting-objects.html)): with Select Fills off, a click selects an edge instead of a face; with Select Strokes off, Alt-click selects a face instead of an edge; Color and Width set the color and width of the highlight on the face or edge under the pointer (red and 4 px by default). The options last across tool switches and are saved with the preferences (`tool.setOption {tool: "livePaintSelection"}`). @@ -1490,6 +1542,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur As VectorCraft's own rule, `tool.setOption` for the Live Paint Bucket and the Live Paint Selection tool, chosen or not, checks every value before it sets any: a switch that is not `true` or `false`, a `color` that is not an RGB color or a layer color's name, or that has an alpha part, a `width` that is not a number and an option the tool does not have give an error naming the option, and nothing is set or saved. A `width` outside 1 to 20 px is still set to the nearest end of that range. Saved settings that hold an invalid value still load, and the tool keeps its default for that option. Evidence: `tests::build::{live_paint_tool_options_refuse_invalid_values_and_change_nothing, live_paint_tool_options_take_rgb_colors_and_clamp_the_width, live_paint_tools_load_saved_settings_with_invalid_values}`. As VectorCraft's own rule, `tool.setOption` for the Shape Builder, chosen or not, checks every value the same way: a switch that is not `true` or `false`, a `pickColorFrom` or `selection` that is not one of its names, a `gapLength` that is not a number, a `highlightColor` that is not an RGB color or a layer color's name, or that has an alpha part, and an option the tool does not have give an error naming the option, and nothing is set or saved. A `gapLength` outside 0 to 72 pt is still set to the nearest end of that range. Evidence: `tests::build::{shape_builder_tool_options_refuse_invalid_values_and_change_nothing, shape_builder_tool_options_take_valid_values_and_clamp_the_gap}`. A drag of 3 screen pixels or more with the Live Paint Selection tool draws a marquee and selects the faces and edges it touches, partly enclosed ones included, and a Shift-drag adds them to the selection or removes them from it ([Modify Live Paint groups](https://web.archive.org/web/20261006115247/https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/modify-live-paint-groups.html)). A click and a marquee change the selection on release, and Escape before the release leaves the selection as it was. Locked Live Paint groups, those on a locked layer or artboard, and in isolation mode those outside the isolated art are not highlighted or selected. + A double-click with the Live Paint Selection tool on a face selects it and the faces of its group that no stroked edge parts from it ([the help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/modify-live-paint-groups.html)), and on an edge selects it and the edges joined to it end to end that have its stroke paint ([the help page](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)); Shift-double-click adds them to the selection or removes them from it. Triple-click is not handled yet. When the object the Blend tool picked first is deleted or undone away before the second click, the next click on an object picks that object first instead of doing nothing. Regression tests: `blend_tool_picks_again_when_its_first_pick_is_gone` in `meshblend.rs` and `the_blend_tool_picks_again_when_its_first_pick_is_deleted` in `tests/blendopts.rs`. Window › Blend opens the Blend panel: Make, the selected blend's Spacing and Orientation (with no blend selected, the options new blends start with), Reverse Front to Back, Reverse Spine, Replace Spine, Expand and Release, each running its Object › Blend command. Make is dimmed until two or more objects are selected. Spacing and Orientation are dimmed until a blend or two or more objects are selected, and the other buttons are dimmed until a blend is selected. The Blend panel's Create Spine menu (Auto, Always, Never; `object.blend.createSpine`) sets whether new blends get a spine, from the Blend tool, Make and `object.blend.make` alike ([Blend panel overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blend-panel-overview.html)). Auto and Always give every new blend a straight spine, as before; Never makes blends without one, which keep their steps on the straight lines between the keys, have Type and Ramp dimmed, refuse Reverse Spine and spine edits, release without a spine path, and get a spine from Replace Spine. The setting is kept with the preferences and leaves blends already made as they are; Auto as the starting value and keeping the setting across sessions are VectorCraft's own rules. Builds on #5177 by adambelis. Evidence: `tests::blendopts::{create_spine_sets_whether_new_blends_get_a_spine, a_blend_without_a_spine_has_none_to_edit_reverse_ease_or_release, whether_a_blend_has_a_spine_is_saved_and_old_blends_have_one}` and `panels::tests_blend::create_spine_sets_what_new_blends_get_whatever_is_selected`. @@ -1503,10 +1556,10 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Paint and appearance (M3):** - **CSS swatch libraries:** fractional linear and radial gradient stop positions are preserved, so nearby stops such as 12.5% and 12.890625% remain distinct instead of collapsing to 13%. Reference: [CSS Images 3 color stops](https://www.w3.org/TR/css-images-3/#color-stop-syntax). The original synthetic regression is `palette_io::tests::css_preserves_fractional_gradient_stop_positions` in `crates/color/src/palette_io.rs`. Scores and hours are unchanged. - **Swatches:** names follow the colour model and are unique; Swatch Options (process/spot, Global, Gray/RGB/HSB/CMYK/Web, live preview); editing a global or spot swatch recolours every linked fill, stroke and text run in one undo step; multi-select and delete with confirmation; New Swatch and New Color Group dialogs (a group from the selected artwork's colours); swatches in colour groups convert, separate and count like any other. The Swatches panel selects ranges and whole groups, has a find field, and drags swatches to reorder, regroup or paint art; Add Used Colors, Select All Unused, Merge, Ungroup and Sort by Kind; a CMYK document keeps applied colours in CMYK. Swatch libraries: nine generated colour libraries, seven gradient libraries (among them Organic Fades, soft perceptually mixed multi-stop fades that thin out to transparent, and Holographic, seven opaque linear foils of narrow pastel and pearl bands and seven radial glows that fade out to a clear edge) and three pattern libraries (Geometric Patterns; Grit Textures with eight seamless grain, speckle, stipple, scratch and fleck tiles; and Optical Effects with eight of VectorCraft's own seamless wave, ring, warped-check, stripe, chevron and lens tiles; their swatches bring their patterns) in a library panel, saved as `.vcswatches`, `.gpl`, swatch exchange (`.ase`) or CSS, and loaded from `.vcswatches`, `.gpl` and `.ase` files (`.ase` both ways: RGB, CMYK, Lab and Gray; global, spot and process; groups) and from color books (`.acb`, read only: the RGB, CMYK or Lab colors of a book such as a Pantone book a user owns, named with its prefix and suffix, spot unless it says process, #831); `swatch.library.copyToUser` copies a loaded library into the User Defined folder without replacing a file, and a file with the same extension and bytes as a User Defined library opens as that library. Tints of global and spot colours ("Name 40%") stay linked and separate as a percentage of their plate. Spot colours can be defined in Lab (Spot Colors options). A built-in [Registration] swatch prints on every plate. - Right-clicking a swatch in either list or thumbnail view selects it without applying paint and offers Swatch Options…, Duplicate Swatch and Delete Swatch for that item. None, [Registration] and missing swatches disable these actions. Existing active-item multiselection is retained; actions still target only the clicked item. Evidence: `panels::swatches::tests::context_menu` harness tests cover all five views, selection, dialog dispatch, duplicate/delete and Undo. All 39 Swatches tests pass; the regression fails with the menu hooks removed. Rendered headless list and thumbnail menus were inspected, and a fresh local deep CodeRabbit review reported zero findings. Full workspace CI passed on Linux/WSL (all 13 gates); native Windows full CI has two unchanged engine-test failures. Scores and estimates unchanged. + Right-clicking a swatch in either list or thumbnail view selects it without applying paint and offers Swatch Options…, Duplicate Swatch and Delete Swatch for that item. None, [Registration] and missing swatches disable these actions. Existing active-item multiselection is retained; actions still target only the clicked item. Evidence: `panels::swatches::tests::context_menu` harness tests cover all five views, selection, dialog dispatch, duplicate/delete and Undo. All 39 Swatches tests pass; the regression fails with the menu hooks removed. Rendered headless list and thumbnail menus were inspected, and a fresh local deep CodeRabbit review reported zero findings. Full workspace CI passed on Linux/WSL for feature commit `6f4a651c0` (all 13 gates); validation after merging main stops at the upstream test-helper compile error tracked in #7727; native Windows full CI has two unchanged engine-test failures. Scores and estimates unchanged. Validation on 2026-11-15: native Windows formatting, workspace Clippy and all 39 focused Swatches tests passed. Windows full CI stopped at unchanged engine tests `tests::package::a_confined_package_names_files_outside_the_read_root_by_name` (slash-sensitive report assertion) and `tests::plugins::plugin_storage_behind_a_link_is_left_alone` (storage-link setup returned AlreadyExists). Both cases pass in the Linux/WSL full CI run, which passed all 13 gates. No engine or CI workflow changes are included. Editing, renaming, deleting or merging a global swatch also changes the colors linked to it in graph designs, the art of brushes and the tile that pattern editing's Cancel puts back, in the same undo step as the rest of the art; Default Swatches with replace unlinks them there too. - A swatch step in `command.batch` (Delete, Swatch Options, Merge, Edit Color Group) changes the fill and stroke for new art as the command run on its own does, so art drawn later in the batch or after it takes the same paint; a batch that fails, and a canceled batch preview, put back the paints it started with, and a canceled Swatch Options preview leaves them as they were. These swatch commands also change the fills and strokes of the appearance new art takes, and Undo and Redo of the command or the batch put the paints for new art back with the swatches. Evidence: `swatch_steps_in_a_batch_change_the_new_art_paints_as_commands_do`, `undo_and_redo_of_a_swatch_edit_put_back_the_new_art_paints`, `swatch_edits_reach_the_paints_of_the_new_art_template`, `a_failed_batch_puts_back_the_new_art_paints_a_swatch_step_changed` and `canceling_a_swatch_options_preview_keeps_the_new_art_paints` in `crates/engine/src/tests/swatches.rs`. + A swatch step in `command.batch` (Delete, Swatch Options, Merge, Edit Color Group) changes the fill and stroke for new art as the command run on its own does, so art drawn later in the batch or after it takes the same paint; a batch that fails, and a canceled batch preview, put back the paints it started with, and a canceled Swatch Options preview leaves them as they were. These swatch commands also change the fills and strokes of the appearance new art takes, and Undo and Redo of the command or the batch put the paints for new art back with the swatches. Spot Colors options (`swatch.spotOptions`) and Default Swatches with replace (`swatch.resetDefaults {replace: true}`) as `command.batch` steps also change the fill and stroke for new art as each command run on its own does: a fill or stroke linked to a Lab spot swatch keeps its link and tint and takes the Lab values or their CMYK equivalent, and one linked to a swatch the replace removes keeps its color and loses the link. Evidence: `swatch_steps_in_a_batch_change_the_new_art_paints_as_commands_do`, `spot_colors_options_in_a_batch_change_the_new_art_paints_as_the_command_does`, `default_swatches_replace_in_a_batch_unlinks_the_new_art_paints_as_the_command_does`, `undo_and_redo_of_a_swatch_edit_put_back_the_new_art_paints`, `swatch_edits_reach_the_paints_of_the_new_art_template`, `a_failed_batch_puts_back_the_new_art_paints_a_swatch_step_changed` and `canceling_a_swatch_options_preview_keeps_the_new_art_paints` in `crates/engine/src/tests/swatches.rs`. Add Used Colors (`swatch.addUsedColors`) and Select All Unused (`swatch.unused`) look colors, swatch names, links, tints and gradients up in hash sets instead of searching every swatch and color for each color or linked paint (New Color Group from artwork too), and New Swatch with several colors (`swatch.new`), New Color Group (`swatch.newGroup`) and Edit Color Group (`swatch.editGroup`) name their new swatches from one set of the names already taken. The new swatches keep their names, order and links, and Select All Unused lists the same swatches. Evidence: `add_used_colors_adds_each_new_color_once_with_free_names`, `add_used_colors_global_links_every_paint_of_a_new_color`, `unused_matches_links_tints_colors_gradients_and_patterns_exactly`, `new_swatches_from_colors_are_numbered_after_names_already_taken`, `new_color_group_numbers_its_colors_after_the_group_and_its_moved_swatches`, `new_color_group_from_artwork_lists_each_color_once_with_free_names` and `edit_color_group_numbers_extra_colors_after_the_names_it_keeps` in `crates/engine/src/tests/swatchcmds.rs`; `free_swatch_names_match_naming_each_swatch_as_it_is_added` and `free_swatch_names_match_new_swatch_names_as_swatches_are_added` in `crates/doc/src/swatches.rs`. - **Colorized images (#1466):** a fill color applied to a selected grayscale or 1-bit image (`paint.setFill`) colorizes it with black, white, a process color or a spot color, and refuses a process color when the image has an alpha channel ([Convert color modes](https://web.archive.org/web/20251220223850/https://helpx.adobe.com/illustrator/desktop/manage-colors/select-and-adjust-colors/convert-color-modes.html), "Colorize Grayscale or 1-bit images"); black and white are accepted there too. The canvas draws each pixel in the color as far as the pixel is dark, with white pixels transparent; PDF export writes the image in the color (a spot color as its ink, Registration in every ink) with the image as its soft mask; Separations Preview and printed separations show it on its color's plates; native files keep the color. SVG writes the fill color through a coverage mask (or a colorized PNG in Tiny 1.2); EPS writes binary coverage as an image mask in the color's ink, and a grayscale image as ink samples scaled by coverage, with white pixels left out at Level 3 and gray midtones written over white. The prompt for deleting several swatches and groups uses the interface language's plural form for the count. Evidence: `deleting_several_swatches_uses_each_count_form` in `crates/ui-egui/src/panels/swatches/tests.rs`. @@ -1544,6 +1597,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Sample Color from Screen:** an eyedropper button in the Color Picker and `ui.sampleScreenColor` (which can be given a key in Keyboard Shortcuts) pick a color anywhere on the screen with the system's sampler: `NSColorSampler` on macOS, the XDG desktop portal's [PickColor](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Screenshot.html) on Linux, and the EyeDropper API in browsers that have it. The color becomes the fill or the stroke as one undo step, or the Color Picker's color, converted from display sRGB into the working RGB space. On Linux, a session without a portal that has PickColor, a portal that does not return from the call within 25 seconds (VectorCraft's own limit) or leaves the bus before it answers, and a portal that ends the request another way each show a status message and end the wait. Windows, the BSDs and other browsers have no sampler yet; the button is gray there. - **Stroke visibility (#1253):** adding paint to a previously unpainted zero-width stroke restores the existing 1 pt default (`PaintDefaults::default`, `Appearance::set_stroke`), for the selected appearance item, the new-art defaults and Swap Fill/Stroke. Positive widths are kept; recoloring a painted zero-width stroke keeps its explicit zero. A real Eyedropper-to-new-shape sequence reproduces the zero-width inheritance. Five engine regressions cover creation, defaults, targeted items, preserved widths and one-step Undo/Redo (`crates/engine/tests/it/stroke_visibility.rs`). - **Gradients:** lossless, validated gradient params; gradients follow rotate, reflect, shear, non-uniform scale and distortions; the Gradient tool edits the fill or stroke of the active proxy, type included; an interactive on-canvas annotator (move, length/angle, rotate, add/move/delete/duplicate stops, midpoints, a stop popover, Delete and arrow keys). The Gradient panel has the Fill/Stroke proxy, a gradient-swatch dropdown with Save to Swatches, midpoint locations, Alt-drag to copy or swap stops, swatch drops on the ramp and a stop eyedropper; copied appearances and graphic styles place gradients on each target's own bounds; gradient handles, both ends of a vector drawn on the art and the start of a clicked one snap as other drawn points do (path segments, construction guides and View › Snap to Glyph's guides included) and honour Constrain Angle. Gradient stops stay linked to global and spot swatches. Freeform gradients (points and lines) are edited on the canvas; radial gradients have an extent ellipse, an aspect handle and an off-centre focal point (SVG `fx`/`fy`, PDF two-point radials). A stroke's gradient runs within, along or across it. Object ▸ Expand turns gradients into N objects or a gradient mesh. + A gradient stop that loses its link to a spot swatch (the swatch deleted, a recolor or adjustment that unlinks it, a library gradient, or a library character style linked to a swatch the document lacks) keeps the color it shows at full tint and drops the process plates it printed with that ink, as a stop given a plain color does; this is VectorCraft's own rule. Evidence: `tests::mapping_links_drops_the_process_plates_of_unlinked_stops` in `crates/color`, `tests::linked_stops::deleting_a_spot_swatch_takes_the_process_plates_of_the_stops_it_unlinks` and `tests::library::library_stops_unlinked_from_their_swatch_keep_no_process_plates` in `crates/engine`. - The Gradient panel's Delete Stop sits at the right end of the ramp, level with it, so a panel too short to show the stop fields still shows it; it deletes the selected stop (never below two), as dragging a stop down off the ramp does (#5403). - Conic gradients, VectorCraft's own gradient type: the stops sweep once around the center from the vector, clockwise on the page (a negative aspect, or a reflection, turns the sweep the other way), with a Conic button in the Gradient panel's Type row and the Gradient tool's extent ellipse and aspect handle; they follow transforms, Expand into wedges or a mesh, open from `.af` files, and export to PDF as a function-based shading that PDF import reads back as a conic gradient; SVG, EPS and legacy `.ai` files get solid wedges, and CSS a `conic-gradient`. - Diamond gradients, VectorCraft's own gradient type: the stops run from the center out to a square with a corner at the end of the vector (the aspect stretches it into a rhombus), with a Diamond button in the Gradient panel's Type row and the Gradient tool's square and aspect handle; they follow transforms, Expand into nested squares or a mesh, and export to PDF, SVG, EPS and legacy `.ai` as four linear gradients, one for each quarter of the square (an image in PDF and SVG for translucent stops, a dithered fill, the Perceptual method other than spot color shadings in PDF, or a square with no area), and on type characters in SVG as a radial gradient; PDF import reads a function-based shading whose color is the same along each square about its origin as a diamond gradient. @@ -1590,13 +1644,15 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Outline Object on an image's own fill or stroke follows the outline of the image's opaque area, and the image's frame when the image has no transparency. Path effects apply to a fill or stroke added to a bitmap object ([archived reference manual, page 561](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=561)), and with Outline Object such a stroke follows the boundary of the art when the image has transparent areas and the image's frame when it has none ([CreativePro article on strokes for placed images](https://web.archive.org/web/20250815214529/https://creativepro.com/add-strokes-placed-images-illustrator/)). VectorCraft's own rules: the opaque area is the pixels at least 50% opaque, and its outline is traced as Image Trace's Black and White mode traces at threshold 128 and fitted with curves. Evidence: `tests::imageoutline` (vectorcraft-effects), `opaque::tests` (vectorcraft-trace), `tests::containers::an_images_stroke_with_outline_object_follows_its_opaque_area` and `tests::containers::an_images_outline_object_stroke_exports_selects_and_measures_along_its_opaque_area` (vectorcraft-engine), `tests::objectfx::an_images_outline_object_stroke_follows_new_pixels_under_the_same_key` (vectorcraft-render). A geometry effect on one of type's own fills or strokes reshapes the whole outline that the fill or stroke paints, on the canvas and in exports; PDF, SVG, EPS and the other vector exports write such type as paths. On type that holds inline graphics, those effects are drawn and exported only when the type has a geometry effect or perspective of its own. A geometry effect on a symbol instance's fill reshapes the filled shapes of the symbol's art and leaves their strokes as they are; one on the instance's stroke reshapes the stroked shapes and leaves their fills as they are. The shapes keep their colors. Only the instance's topmost fill and topmost stroke count, and only while they are visible with an opacity above 0. The canvas and Object › Expand Appearance use the same art, SVG and PDF export bake the same shapes, and Expand Appearance turns the instance into an editable group in one undo step. A group's own fills and strokes in the art take the effects too. An instance inside the art passes the effects on to its own art, and a dynamic symbol's instance reshapes the fills and strokes it paints on the art. How the effects map onto the symbol's art is VectorCraft's own rule. The help page <https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/apply-and-modify-effects.html> describes effects on one fill or stroke, and the help page <https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/expand-objects.html> describes Expand Appearance (engine `expand::a_symbol_instance_fill_effect_reshapes_its_filled_art_and_expands`, `a_symbol_instance_stroke_effect_reshapes_its_stroked_art_and_expands`, `a_stroke_effect_reshapes_a_stroke_a_dynamic_instance_adds`, `a_fill_effect_reshapes_the_fill_of_a_group_in_the_art`, `only_the_topmost_visible_instance_fill_reshapes_the_art`, `a_nested_symbol_instance_takes_the_outer_fill_effect`, `export_bakes_a_symbol_instance_fill_effect`, `a_fill_effect_on_an_instance_of_a_symbol_that_holds_itself_ends`). Existing documents with a geometry effect on a symbol instance's fill or stroke draw differently: before, the effect drew nothing. + Live effects inside a symbol's art (geometry effects, color adjustments and the rest that export bakes) are written where each instance places the art in PDF, print, EPS and DXF, as the canvas draws them: the art is placed first and its effects are applied after, so an instance that scales its art does not scale the distance a Transform effect moves it. Symbols nested in the art, a dynamic symbol instance's own paint changes and the stain an instance's fill gives its art are kept, and the art is stained before its effects apply. A linked instance's PDF link covers its art where the effects draw it. A symbol whose art holds itself stops at the nesting limit, and the symbols' own art keeps its effects. An instance stays an instance in these exports when the objects its art makes once baked (the copies a Transform effect makes included) would take the export's placed symbol art past 16,000,000 objects, or when its baked art would draw deeper than the 128 levels a document may draw; these are VectorCraft's own limits. Art baked for an instance that then stays an instance still counts toward that limit, and while an instance's art bakes, the art's own objects are held in the limit for the instances nested in it. Instances the export leaves out (hidden ones, those in hidden groups, on template layers, and on hidden layers or layers that do not print when the export leaves those out) are not placed and do not count toward that limit. Before, these exports wrote the art without its effects (effects `bake::placing_symbols_bakes_their_art_where_each_instance_places_it`, `placing_symbols_reaches_the_art_of_nested_instances`, `placing_a_symbol_that_holds_itself_stops`, `placing_symbols_keeps_dynamic_instances_changes`, `placing_symbols_keeps_the_instances_stain`, `placing_symbols_counts_the_baked_art`, `placing_symbols_counts_nested_art_once`, `placing_symbols_holds_the_outer_art_while_it_bakes`, `placing_symbols_counts_the_art_it_drops`, `placing_symbols_counts_art_dropped_for_depth_against_later_baked_art`, `placing_symbols_keeps_the_baked_art_within_the_drawn_depth`, `placing_symbols_skips_instances_the_export_leaves_out`; doc `depth::tests::drawn_heights_measure_objects_outside_the_layers`; PDF, print, EPS and DXF `symbol_art_effects_are_written_where_they_draw`, `symbol_art_effects_print_where_they_draw`; PDF `a_stained_instance_keeps_its_stain_when_its_art_has_effects`, `a_linked_instance_keeps_its_link_when_its_art_has_effects`). A raster effect (Drop Shadow, Outer Glow, Gaussian Blur and the other effects that paint pixels) on a symbol instance's topmost fill draws on each filled shape of the symbol's art, and one on its topmost stroke draws on each stroked shape, after any geometry effects listed before it, under the same rules as geometry effects: only a visible fill or stroke with an opacity above 0 counts, a group's own fills and strokes in the art take the effect, and an instance inside the art passes it on. Each shape gets its own shadow or glow, which is VectorCraft's own rule. The canvas, Use Preview Bounds and the drawn bounds, SVG and PDF export draw it, and Object › Expand Appearance is enabled for such an instance and makes the effect an image at the document's raster effects resolution, in one undo step (engine `expand::a_symbol_instance_fill_shadow_shadows_its_filled_art`, `a_symbol_instance_stroke_shadow_shadows_only_its_stroked_art`, `a_symbol_instance_fill_shadow_follows_the_fill_offset_before_it`, `a_nested_symbol_instance_takes_the_outer_fill_shadow`, `export_draws_a_symbol_instance_fill_shadow`). Existing documents with a raster effect on a symbol instance's fill or stroke draw differently: before, the effect drew nothing. The Appearance panel's inline effect editor labels each parameter as the effect dialogs' generic fields do, without the colon ("Max. Radius", "Channel 1", "Create New Fields by"). Roughen's and Zig Zag's Points, Offset Path's Joins, Inner Glow's Source and the menus of Radial Blur, Smart Blur, Sprayed Strokes, Glass, Mezzotint, Halftone Pattern, Grain, Texturizer and De-Interlace are dropdowns with the dialog's labels that send the dialog's values, and a plug-in's choice is a dropdown of the plug-in's values. Revolve's edge, Extrude & Bevel's bevel, every Warp style's orientation, Rasterize's Color Model, Background and Anti-aliasing and the channel of Levels and Curves are dropdowns too, with the labels their own dialogs show. `effect.apply` and `effect.setParams` refuse a Levels or Curves `channel` other than `rgb`, `red`, `green` or `blue` (or `r`, `g` and `b`, in any letter case). Object › Expand Appearance keeps each stroke of a path a stroke (weight, caps, joins, dashes, arrowheads, alignment and width profile) on a copy of the path with the geometry effects baked in, and Object › Expand… is dimmed, with a tooltip, while the selection has appearance attributes, so a stroked line with Zig Zag becomes a stroked zig-zag line and only Expand then outlines it, the two steps the [Expand objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/expand-objects.html) help page describes (#3089). Brushed strokes still become their brush art; `object.expand` still bakes and outlines in one step for agents. - **Masks and clipping:** opacity-mask controls work while the mask is being edited; transparency commands take ids and work without a selection; clipping sets clip by compound paths, even-odd paths, text and groups on screen and in raster export, matching SVG/PDF. Alt-click shows only the mask; SVG masks keep Clip and Invert; the transparency grid is per-document state; a clipping path's own fill and stroke paint behind and over the clipped art; layers can be clipping masks. - **Masks and clipping:** opacity-mask controls work while the mask is being edited; transparency commands take ids and work without a selection; clipping sets clip by compound paths, even-odd paths, text and groups on screen and in raster export, matching SVG/PDF. Alt-click shows only the mask; SVG masks keep Clip and Invert; the transparency grid is per-document view state saved in native files (#1968); a clipping path's own fill and stroke paint behind and over the clipped art; layers can be clipping masks. - The geometry effects of a clipping path (Roughen, Transform and the other effects that reshape a path), of its fills and strokes, and of the members of a group used as one, shape the area it clips to on the canvas and in raster export, as in SVG and PDF export: a roughened clipping path clips by its roughened outline. They apply before the geometry effects of the clip group or of a group around it, on the canvas and in every export, and type used as a clipping path keeps them when a group's effect outlines it. Raster effects such as Gaussian Blur leave that area as it is. `effects::tests::clipfx` and the renderer's `tests::clip` cover it. + The geometry effects of a clipping path (Roughen, Transform and the other effects that reshape a path), of its fills and strokes, and of the members of a group used as one, shape the area it clips to on the canvas and in raster export, as in SVG and PDF export: a roughened clipping path clips by its roughened outline. They apply before the geometry effects of the clip group or of a group around it, on the canvas and in every export. When the clipping path has a fill or stroke of its own, the geometry effects of those fills and strokes apply after the group's geometry effects instead. Type used as a clipping path keeps its geometry effects when a group's effect outlines it. Raster effects such as Gaussian Blur leave that area as it is. `effects::tests::clipfx` and the renderer's `tests::clip` cover it. + Clicks, Select Behind, the Unlock submenu, marquees and the Enclosing Lasso inside a clip group or a clipping layer follow that area too: the clipped art is found where the effects moved it and not where they took it away. The clipping path itself is still found by its own outline and anchors. A hidden member of a group used as a clipping path does not clip, and a geometry effect on it does not change where clicks land. Outline view and layers with Preview off draw the plain clipping path, and clicks and marquees there count it. Direct Selection picks and outlines an object of a dynamic symbol's art by the same rules. `doc::hit::tests` and the engine's `tests::clip` cover it. - **Transparency:** three-state Knockout Group (on, neutral, off), Opacity & Mask Define Knockout Shape, Page Isolated Blending and Page Knockout Group, on screen and in SVG/PDF. SVG export writes a knockout group of opaque art plainly, without masks, so shapes meeting edge to edge leave no seam; translucent, blended, masked or brushed art knocks out through masks. Blend modes match the standard formulas on screen, in SVG and in PDF, and non-isolated groups blend with the art below. Flatten Transparency with presets, a dialog and a Flattener Preview panel. Flattening for files without transparency (PDF/X-1a, PDF/X-3) in a CMYK document keeps the inks where it rasterizes, as under an image with see-through pixels: the images it makes hold ink amounts, not screen colours the file would separate again, so a C100 M6 Y41 K3 panel stays C100 M6 Y41 K3 there (#2160, `engine/src/cmd/fileio/tests_pdfx.rs`). On the canvas, the renderer no longer draws the picture of the art below back as an image each time it copies the backdrop of a non-isolated group that blends: it keeps that picture and draws the art that follows over it. At 2880 × 1800, 50 translucent groups with Multiply members take 65 ms a frame instead of 299 ms on 8 threads (`vectorcraft-cli bench`), and the frames have the same pixels. Type inside a group, layer, symbol instance, blend or repeat keeps its opacity, blend mode, opacity mask, Opacity & Mask Define Knockout Shape, own effects, perspective and visibility when the effects on the container outline it. Hidden type with a geometry effect of its own is left out of exports. @@ -1650,6 +1706,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur PDF export measures each member of a plain group or layer once to leave out what is off the page: the group or layer is measured through its members (`Node::visual_of_members`), and each member uses that box when it is written. The elements of a knockout group are measured twice, once for the group's box and once to choose the elements on the page (`pdf/src/tests/measuring.rs` counts the measures). A local byte comparison with the previous build found identical output on one open path of 200,000 anchors, 20,000 rectangles in 200 groups of 100, 5,000 point type objects and a document of plain, see-through, clipping and knockout groups. The walk that writes link annotations measures only an object with a URL that opens and a clipping group (`links.rs`), and its output on a document of linked objects in plain and clipping groups is the same byte for byte as when it measured every object. Invisible text in a PDF (rendering mode 3, which carries a scanned page's recognized text over the scan) opens as type with no fill or stroke, a run of its own beside visible text on the same line; text that can't come in as type (opened as outlines, Type 3 fonts) is left out with a warning. PDF export, and printing, write characters with no fill or stroke as real text in rendering mode 3, so they draw nothing but stay selectable and searchable, also in PDF/X-1a and PDF/A-2b (#2675, `pdf/src/tests/import_fidelity.rs`, `pdf/src/tests/realtext.rs`). A PDF, or a `.ai` read through its PDF part, whose spot inks have the same values but different names opens with a spot swatch for each ink. The solid fills and strokes of paths and type, and the stops of gradients on paths, link to the swatch of the ink they are painted in, the points of a gradient mesh in one of these inks keep the ink's color, and PDF export writes each of these inks as its own separation (`pdf/src/tests/import_color.rs`). Paint in these inks inside pattern cells, soft masks and type 3 glyphs, and gradients on type in these inks, still import as RGB. Type in one of these inks can also import as RGB when type in another Separation or DeviceN ink is shown with no path drawn between them. The stops of an axial or radial shading in a DeviceN space that mixes one spot ink with process plates (a spot ink over a constant cyan, for example) link to the ink's swatch at its tint and keep the process plates, and PDF and EPS (Level 3) export write those stops in a DeviceN space of the ink and those plates, so the spot plate is not lost (#3235, `import_color::a_device_n_gradient_of_a_spot_ink_over_a_process_plate_keeps_both_inks`). Solid fills that mix a spot ink with process plates, and stops that mix several spot inks, still import as RGB, with the spot inks kept as swatches. + Print separations and Separations Preview print such a stop's process plates on the Cyan, Magenta, Yellow and Black plates beside its tint on the spot plate; with spots printed as process, each process plate prints the stop's plate layered with the spot tint's process equivalent. A freeform gradient's points separate into plates as its stops do, and converting the document's color mode converts them (`print::a_spot_gradient_stop_prints_its_process_plates`, `print::a_freeform_gradients_points_separate_into_plates`, `colorize::separations_preview_shows_a_spot_gradient_stops_process_plates`, `colormgmt::rgb_cmyk_converts_each_freeform_point`). A `.ai` or EPS opened from its editing data keeps both swatches when a pattern's name, or a named color's, is also another swatch's: a pattern's swatch named as a default swatch, a named color or a palette color becomes "Name 2", and a named color named as a gradient or pattern swatch of the palette becomes "Name 2", with the fills, strokes and gradient stops linked to it following it (`ai::tests::a_pattern_swatch_named_as_another_swatch_is_numbered`, `ai::tests::a_color_named_as_a_palette_gradient_or_pattern_is_numbered`). PDF export writes a linear or radial gradient that mixes a spot color with process colors, or two spot colors, as a DeviceN shading of the spot inks and the process inks its stops use, so each spot ink prints on its own plate; an off-center midpoint is written as a stop with the inks halfway between its two stops. A gradient that mixes a spot color with RGB or Lab colors is still written without the spot ink, with a warning. A CMYK document, or an export that converts colors to a CMYK destination profile, writes RGB and Lab stops in CMYK first (unless the export converts colors to an RGB destination profile), so there such a gradient, Classic or Perceptual, is written as a DeviceN shading that keeps the spot ink. A Perceptual gradient of spot inks is written as a Separation or DeviceN shading of the stops on its curve; a dithered gradient fill, and a Perceptual gradient with RGB or Lab stops other than white or more than 4,096 stops on its curve, are written as images in process colors, with a warning. A Lab spot color in such a shading is named by the same Separation space, with the Lab alternate, as its flat fills (`engine/src/tests/linked_stops.rs`, `engine/src/tests/labspots.rs`). PDF and EPS export name a spot ink in a gradient's Separation or DeviceN space, and EPS in `%%DocumentCustomColors`, only when a stop linked to it at a tint above 0, or with process plates, colors part of the gradient (VectorCraft's own rule): a stop out of order whose neighboring stretches have no width, and in PDF a stop whose stretches are fully transparent, adds no ink and no empty plate. EPS writes every stop opaque, so there a transparent spot stop keeps its ink (`crates/pdf/src/tests/output.rs`, `crates/eps/src/tests.rs`). @@ -1675,6 +1732,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A gap between glyphs of two sizes is measured against the smaller one, so a word set beside a much larger one with no space glyph between them (a browser's margin between two sizes, as in `≤ 4` and a small `hours`) keeps its word space (#3623). SVG import's style cascade, used for hidden objects, non-scaling strokes and type, tests each element only against the `<style>` rules for its id, its classes and its element name, and the rules whose selector ends in none of these (`*`, `[x]`). SVG import places right-to-left point type and type on a path as [SVG 2's `text-anchor`](https://www.w3.org/TR/SVG2/text.html#TextAnchoringProperties) says: with `direction: rtl`, `start` puts the right edge of the text at its position (on a path, the text ends at `startOffset`) and `end` puts the left edge there. Each line and each absolutely placed chunk is anchored by the `text-anchor` and `direction` of the element holding its first character, a `<tspan>`'s own included, and each line starts at its own `x`. An absolutely placed chunk is anchored by the left and right edges of its glyphs as they are drawn, so a chunk of several right-to-left characters, whose first character is drawn at its right, sits on its anchor too. A letter-spaced right-to-left line keeps the tracking of all its letters inside the advance it anchors (`rtl_point_text_start_and_end_use_directional_edges`, `rtl_type_on_a_path_starts_at_its_directional_edge`, `rtl_letter_spaced_lines_stay_on_their_anchor`, `rtl_lines_use_each_chunk_first_character_direction_and_anchor`, `each_line_starts_at_its_own_x`, `absolutely_placed_chunks_use_their_own_rtl_anchor` and `absolutely_placed_rtl_chunks_of_several_characters_anchor_by_their_visual_edges` in `crates/svg/tests/it/import_text.rs`). + SVG import puts each absolutely placed character of right-to-left text on its own `x`, as [SVG 1.1's text chunks](https://www.w3.org/TR/SVG11/text.html#TextLayoutIntroduction) require, also when the characters run right to left on a later line: in `<text direction="rtl" font-size="20">`, `<tspan x="100 160" y="80 80">אב</tspan>` after a first line puts the right edges of `א` and `ב` at 100 and 160, where import put the right edge of `א` at 393.48 before. Chunks that overlap keep their own anchors, and characters stretched by `lengthAdjust="spacingAndGlyphs"` land on their `x` too. A left-to-right character drawn between two absolutely placed right-to-left characters leaves the one after it where the line puts it, and the import warns about it (`absolutely_placed_right_to_left_characters_sit_on_their_own_x` in `crates/svg/tests/it/import_text.rs`). SVG import places type on a path of one closed subpath as [SVG 2's `startOffset` attribute](https://www.w3.org/TR/SVG2/text.html#TextPathElementStartOffsetAttribute) describes: text anchored to start before the path's start point, or offset past its end, wraps around the path, so text with `text-anchor="end"` at `startOffset` 0 ends at the start point, and a negative `startOffset` counts back from the end. Text longer than the loop draws its first characters whatever its anchor. A path of several subpaths, and an open path, still start the text at the path's start or end (`text_on_a_closed_path_wraps_past_the_path_start` in `crates/svg/tests/it/import_text.rs`). SVG import reads the bidi embedding of a `<tspan>`, `<textPath>` or `<a>` inside a `<text>` as [SVG 1.1's bidi section](https://www.w3.org/TR/SVG11/text.html#RelationshipWithBi-directionality) describes: with `unicode-bidi: embed` its characters take its `direction` as their Character Direction, an element with `normal` stays in its parent's embedding, and the `<text>` keeps its own paragraph direction, so a run that SVG export writes with `direction` and `unicode-bidi="embed"` opens with its Character Direction again. Character Direction holds one level of embedding, so `bidi-override`, `isolate` and `isolate-override` are imported as embeddings in their `direction`, `plaintext` as an embedding in the direction of its first strong character, and an embedding inside another as an embedding of its own, each with an import warning. With `unicode-bidi: plaintext` on the `<text>`, each of its paragraphs runs, and each chunk is anchored, in the direction of its first strong character (`a_tspan_bidi_embedding_becomes_its_character_direction`, `unicode_bidi_is_not_inherited_and_reads_from_the_cascade` and `unicode_bidi_values_the_text_model_cannot_hold_are_reported` in `crates/svg/tests/it/import_text.rs`; `character_direction_reads_back` in `crates/svg/tests/it/text_layout.rs`). A `.svgz` file copied in a file manager pastes as its art, as a copied `.svg` file does. @@ -1683,16 +1741,18 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur SVG import reads each `<circle>` and `<ellipse>` as the ellipse VectorCraft draws: four smooth anchors on the axes, starting at the right, with handles of the standard length, so an ellipse exported as `<ellipse>` comes back with the anchors it was written from and draws the same (`circles_and_ellipses_import_as_the_ellipse_drawn` in `crates/svg/tests/it/basic_shapes.rs`, `filled_ellipse_on_the_artboard_edge_survives_visually` in `prop_svg.rs`). SVG import keeps attributes in other applications' XML namespaces (`plotter:pen="2"`) on the objects and layers they belong to, as it keeps their `data-*` attributes: copies, duplicates and `.vectorcraft` files keep them, and SVG export writes them back with each namespace declared once on the root (the rest of #522; `crates/svg/tests/it/foreign_attributes.rs`, `tests/attributes.rs`). A PDF-compatible `.ai` saved with Include Editing Data for Other Apps defines every symbol in its editing copy with its art, registration point and place in the Symbols panel's order, and writes its instances as symbol instances, which VectorCraft's `.ai` reader opens as symbols and instances again (`symbols_and_their_instances_are_read_back` in `crates/eps/src/ai_editing/tests.rs`; [file-format-parity.md](file-format-parity.md) lists the instances written as their art). - A PDF-compatible `.ai` saved with Include Editing Data for Other Apps keeps envelopes made with a warp, a mesh or a top object editable: its editing copy holds each envelope's contents, shape, Fidelity, Envelope Options and Edit Contents state in the form VectorCraft's `.ai` envelope reader reads, beside its distorted art, so the file opens with the same live envelope, Edit Contents still switching between the contents and the envelope ([Edit the contents of envelopes](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/edit-the-contents-of-envelopes.html)). Envelopes of type, envelopes in opacity masks, pattern tiles or another envelope's contents, and envelopes the reader would open with another shape or other settings (a Fidelity that isn't a whole number, bounds margins kept with Distort Appearance off), and envelopes after the first 256 in a file are written as their distorted art, with a warning (`envelopes_are_read_back_live` and `envelopes_the_reader_cannot_open_live_are_written_as_their_art` in `crates/eps/src/ai_editing/tests.rs`). + A PDF-compatible `.ai` saved with Include Editing Data for Other Apps keeps envelopes made with a warp, a mesh or a top object editable: its editing copy holds each envelope's contents, shape, Fidelity, Envelope Options and Edit Contents state in the form VectorCraft's `.ai` envelope reader reads, beside its distorted art, so the file opens with the same live envelope, Edit Contents still switching between the contents and the envelope ([Edit the contents of envelopes](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/edit-the-contents-of-envelopes.html)). Envelopes of type, envelopes in opacity masks, pattern tiles or another envelope's contents, and envelopes the reader would open with another shape or other settings (a Fidelity that isn't a whole number, bounds margins kept with Distort Appearance off), and envelopes after the first 256 envelopes and images with a Warp in a file are written as their distorted art, with a warning (`envelopes_are_read_back_live` and `envelopes_the_reader_cannot_open_live_are_written_as_their_art` in `crates/eps/src/ai_editing/tests.rs`). A PDF-compatible `.ai` saved with Include Editing Data for Other Apps writes eligible paths, compound paths and groups with live effects with an art style when the writer supports their appearance and effects (not a filled path that uses the even-odd rule, and none on a large canvas), which VectorCraft's `.ai` reader opens as the same appearance with its effects live (`objects_with_live_effects_are_read_back` and `every_effect_setting_written_on_an_object_is_read_back` in `crates/eps/src/ai_editing/tests.rs`; [file-format-parity.md](file-format-parity.md) lists the objects written without one and the effects they lose). The same holds for the objects of an opacity mask's art, a mask inside another mask's art and a hidden art root included, so a mask whose art has Offset Path opens drawing the image it masks as it did, with the effect live; geometry effects that no art style holds on a mask's art, such as Roughen, are written applied to the art, which opens drawing what it drew (`a_masked_image_with_live_offset_path_round_trips`, `hidden_and_nested_mask_art_keep_live_offset_path` and `a_masks_art_with_an_effect_no_style_holds_is_written_as_it_draws` in `crates/eps/src/ai_editing/tests.rs`). A PDF-compatible `.ai` saved with Include Editing Data for Other Apps writes point type, area type and type on a path as type in its editing copy, and objects next to it keep their own transparency (`crates/eps/src/ai_editing/tests.rs`, `cmd::fileio::tests_pdfedit::type_comes_back_from_the_editing_copy`; [file-format-parity.md](file-format-parity.md) lists what is written as outlines). A PDF-compatible `.ai` saved with Include Editing Data for Other Apps keeps the document's variables, data sets and the bindings of objects to variables in its editing copy, in the form the variable library reader above reads, so they come back when the file is opened. Bindings to layers, to type written as outlines, to graphs and to linked images written as other objects, data set values of graphs, and variables, data sets, bindings and values past the writer's limits are left out with a warning (#6024; `crates/eps/src/ai_editing/tests.rs` `variables_data_sets_and_bindings_are_read_back`; `crates/eps/src/ai_editing/writer/variables.rs` lists what is left out). A PDF-compatible `.ai` saved with Include Editing Data for Other Apps keeps each wrap object's Text Wrap Options in its editing copy: the Offset, positive or negative, and Invert Wrap ([the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/add-manage-text/wrap-or-unwrap-text-around-objects.html)), in the form the `.ai` reader reads them (`text_wrap` in `crates/eps/src/import/ai/read/document.rs`), so they come back when the file is opened. An offset past the -1000 to 1000 pt the reader keeps is written as the nearer end of that range. On a large canvas the offset is written at the art's scale and comes back at its size. Art the writer draws for an object, such as a blend's steps or a symbol instance written as its art, has only that object's options, and a clipping path written as its fills and its strokes has its options once (`crates/eps/src/ai_editing/tests.rs` `text_wrap_options_are_written_and_read_back`, `drawn_art_keeps_only_its_objects_text_wrap`, `text_wrap_offsets_on_a_large_canvas_come_back_at_their_size`, `text_wrap_options_of_type_and_envelopes_are_read_back`, `a_clipping_path_written_as_its_paint_keeps_one_text_wrap`). + Type written as its outlines in the editing copy still wraps area type by its bounds, not by its glyphs, when the file is opened: the outlines' group ends with an unpainted rectangle at the type's bounds that carries its Text Wrap Options, in the form the `.ai` reader reads a path's options (`text_wrap` in `crates/eps/src/import/ai/read/document.rs`), and the group keeps the type's name (`crates/eps/src/ai_editing/tests.rs` `type_written_as_outlines_keeps_wrapping_by_its_bounds`). In a `.ai` or EPS opened from its editing data, type has its text object's opacity, blend mode and knockout shape flag, whether it is made from the file's text document or taken from the page, and type made from the text document takes its text object's lock. Where such type has transparency and comes in with other art (the rest of its look, or page type and strokes that go with it), a group of them has it. Where the page draws its type, or the strokes around it, with transparency that is neither its text object's nor its text object's combined with that of the objects around it, the page's type and strokes keep their own instead (`crates/eps/src/import/tests_native.rs`). Where the page draws type of no text object over text objects made from the text document, with their words in any case, that type is theirs as the page draws it and is left out; the page's other type of no text object goes only to text objects whose type the text document can't make, or else is left out with a warning. `.ai` editing-data import restores the document's listed graphic styles in panel order and links objects that use a listed style; unsupported appearances keep their drawn look (`crates/eps/src/import/ai/tests.rs`). A `.ai` or EPS graphic style library, whose editing data holds the styles and their list but no layers, opens with those styles in list order. Other Library… loads another document's graphic styles ([Apply graphic styles](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/apply-graphic-styles.html)) and lists such a library's styles in a library panel. A `.ai` or EPS read as its PDF part or page because its layers can't be used also gets the styles of its list in place of the default ones (`crates/eps/src/import/tests_native.rs`, `cmd::fileio::tests_aiimport::a_graphic_style_library_in_a_ai_file_without_layers_loads_its_styles`). A `.ai` or EPS symbol library, whose editing data holds symbol definitions and their list but no layers, opens with those symbols in list order, each with its registration point. Other Library… in the Symbols panel's Symbol Libraries Menu imports the symbols of the file you pick ([Create or import symbol libraries](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html)) and lists such a library's symbols in a library panel. A `.ai` or EPS read as its PDF part or page because its layers can't be used also gets the symbols defined before its layers (`crates/eps/src/import/tests_native.rs`, `crates/eps/src/import/ai/tests.rs`, `cmd::fileio::tests_aiimport::a_symbol_library_in_a_ai_file_without_layers_loads_its_symbols`). + In a large canvas `.ai` or EPS ([Large canvas FAQ](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/start-a-new-file/large-canvas-faq.html)), or a `.ai` whose page is in larger units, opened from its editing data, VectorCraft reads the symbol definitions in the same units as the layers. When the file opens at its full size, each symbol's art, strokes and effects are scaled with the layers, and each instance keeps its own scale and rotation and draws where and as large as before. A new instance comes in at the symbol's full size, the size of an instance at 100% in the file. A symbol library from such a file comes in at the same size, and opacity masks on the layers that don't move with their object are scaled with the layers too. Editing data that VectorCraft wrote keeps its symbols and those masks at their own size, as its `.ai` save writes them (`tests_native::a_large_canvas_eps_keeps_its_symbols_at_the_pages_size`, `a_large_canvas_ai_keeps_its_symbols_at_the_pages_size`, `a_large_canvas_ai_vectorcraft_wrote_keeps_its_symbols_at_their_own_size`, `a_symbol_library_in_larger_units_comes_in_at_the_pages_size`, `build::candidate_tests::scaling_the_symbols_keeps_their_instances_in_place`, `scaling_a_read_document_scales_unlinked_opacity_masks`). A `.ai` or EPS opened from its editing data whose text document makes the type of every text object that shows takes all its type from the text document: each text object stays in its own group, frame and layer, the page's type isn't matched with them, a file of more than 5,000 text objects still opens with its layers, and type the page draws differently (in another font) keeps the layers, with a warning. A line break inside a paragraph stays a line break in it (`crates/eps/src/import/tests_native.rs`, `crates/eps/src/import/ate.rs`). In SVG export without Fewer `<tspan>` Elements, each character of live type that justification or Mojikumi moves (the letter gaps of a Justify All line without word spaces, the gaps between the characters of a justified Japanese line, closed-up punctuation, the space between Japanese and Latin letters) starts its own positioned `<tspan>`, and type scaled horizontally on a justified line is stretched to its own width (`crates/svg/tests/it/text_layout.rs`). To find those characters, SVG export lays a type object out a second time only when the second layout can differ from the first: point type with Line-end Punctuation Half Width and no Japanese punctuation or letters, the setting new type gets, is laid out once. Exporting 5,000 such objects takes a median of 109.4 ms instead of 171.5 ms on Windows 11, with the same SVG (`crates/svg/src/export/text/tests.rs`). @@ -1731,6 +1791,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Export As PDF with Use Artboards off also opens the Save PDF dialog, without its Artboards section, and writes one page of the visible art's bounds with the dialog's options (`document.exportPdf {useArtboards: false}`; `crates/ui-egui/src/dialogs/tests_export.rs`, `crates/engine/src/cmd/fileio/tests_pdf.rs`). `document.exportSelection` run without params (a shortcut) takes the same route after its save panel: a picked PDF opens the Save PDF dialog without its Artboards section, and SVG, the raster formats, EPS, DXF, text and exporter plug-ins with parameters open their options, whose OK writes the selection alone, cropped to it, with the chosen options (`crates/ui-egui/src/dialogs/tests_export_selection.rs`). A `.ai` export with Use Artboards off writes one page of the visible art's bounds without the native document or the editing copy for other apps, with a warning, so the file does not reopen with one artboard in place of the document's; without PDF content it is refused (`crates/engine/src/cmd/fileio/tests_pdfedit.rs`). + That page, and an HP-GL plot of the art's bounds, are measured on the art the file draws: non-printing layers the PDF or `.ai` file leaves out do not make it larger, and nor do the non-printing layers, objects at 0% opacity, placed images, clear gradient meshes and unpainted paths a plot leaves out; Export As refuses an HP-GL plot of nothing it draws before the save dialog (`crates/engine/src/cmd/fileio/tests_pdf.rs`, `crates/engine/src/cmd/fileio/tests_hpgl.rs`, `crates/ui-egui/src/dialogs/tests_export.rs`). PDF export warns when a PDF/X file has no bleed on a side where the document's bleed has one, and writes the file as asked. In a PDF without a standard, the warning for a page longer than 14,400 pt written with a `UserUnit` names "Write pages longer than 200 in at full size in points" (`crates/engine/src/cmd/fileio/tests_pdf.rs`). A PDF/A-2b export at PDF 1.4 with a page longer than 14,400 pt is written as PDF 1.6 with a `UserUnit` and a warning, whether or not `longPagesInPoints` is on, so its page boundaries stay within PDF/A-2's limit of 14,400 units (ISO 19005-2, 6.1.13) unless the page is too narrow for that (`crates/pdf/src/tests/marks.rs`). @@ -1764,11 +1825,13 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - HEIC and HEIF images open and place from `.heic` and `.heif`, as the [supported file formats](https://helpx.adobe.com/illustrator/kb/supported-file-formats-illustrator.html) list High Efficiency Image under both Open and Place (and [Fix HEIF file import errors on Windows](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/fix-heif-file-import-errors-on-windows.html) covers both ways of bringing HEIF files in): HEVC-coded single pictures and grids of tiles, 8 to 10 bits, with an alpha image, decoded by heic-rs in the engine's default `heif` feature. The container's rotation, mirror and crop are applied. Without an `nclx` box, the HEVC stream's video signal type gives the samples' matrix and range. An RGB ICC profile, or Display P3 with the sRGB curve named by an `nclx` box or, without a color box, by the stream, is converted to sRGB; the EXIF resolution tags size the image, or 72 ppi. Image sequences, other codings and grids of cropped tiles are refused with a message, and so is every HEIF file in a build without the feature. The decoder checks image size before allocating (`crates/engine/src/cmd/fileio/tests_heifread.rs`). - HP-GL/2 plot files (`.plt`, `.hpgl`, `.hgl`, `.hpg`, or a name no other format reads when the file starts with plotter instructions) open and place as paths on one layer, the artboard round the art: each line drawn with the pen down is a stroked path in its pen's color and width, line types become dash patterns, circles, arcs, wedges and Bézier curves are curves, filled and edged rectangles, wedges and polygons (polygon mode) are filled or stroked paths, and encoded polylines, scaling points, user units and rotation are read. Labels, symbol mode's symbols, raster images and hatching aren't drawn and are listed in the warnings (`crates/cad/src/hpgl/tests.rs`, `crates/engine/src/cmd/fileio/tests_hpgl.rs`). - PICT pictures (`.pct`, `.pic`, and `.pict` as VectorCraft's own name) open and place, as [the help page](https://helpx.adobe.com/archive/illustrator/illustrator-cs5-5-troubleshooting.pdf) lists Macintosh PICT under both opening and placing: versions 1 and 2, with or without the file's 512 bytes of application data, read by the opcodes of Apple's [Opcodes in Pictures](https://dev.os9.ca/techpubs/mac/QuickDraw/QuickDraw-461.html). Lines, rectangles, rounded rectangles, ovals, arcs, polygons and regions become paths in their pen and pattern colors, text becomes point type in the font the picture names, bitmaps, pixel maps and QuickTime JPEG images become images, and the clip region clips what follows it; File › Place places the picture as one group clipped to its frame. Inverted shapes, other transfer modes and other QuickTime formats come back as warnings, and a picture cut short keeps what came before it (`crates/metafile/src/tests/pict.rs`, `crates/engine/src/cmd/fileio/tests_pict.rs`). + - EMF and WMF files are read by the shared `craft-metafile` reader and open, place and paste as editable paths, clipping groups, images and point type: an EMF drawn with EMF+ records (on their own, or beside plain records) is read from them instead of opening empty, and hatched and pattern brushes fill with their average color (`crates/metafile/src/tests/import.rs`). - Export As › HP-GL (`document.export {format: "hpgl"}`) writes a `.plt` plot of an artboard, each artboard or the art for pen plotters and cutters: each visible path once along its line in plotter units from the artboard's bottom-left corner or center, a pen per color or a pen table, curves flattened to a tolerance, type as outlines, clipping masks and the artboard's edges applied, and HP-GL or HP-GL/2 (pen colors and encoded polylines); plots read back by the HP-GL reader give the same lines (`crates/cad/src/hpgl/write/tests.rs`, `crates/engine/src/cmd/fileio/tests_hpgl.rs`). - HP-GL export's `insideFirst` cuts each pen's paths inside before outside: a path is drawn only after the pen's paths that lie inside it (a letter's counter, a part's holes, rings within rings), touching outlines counted as inside and crossing ones not, in paint order or nearest first with `sortPaths`, within the plot's work budget; these order rules are VectorCraft's own (`crates/cad/src/hpgl/write/nest.rs`, `crates/cad/src/hpgl/write/tests.rs`, `crates/engine/src/cmd/fileio/tests_hpgl.rs`). - EPS and DXF in and out, EMF/WMF in and out; PNG (with PNG-8), JPEG, WebP, GIF, TIFF, BMP, Targa and layered PSD export; grayscale TIFFs with an alpha channel or other extra channels place, relink and open, the alpha as the image's transparency (#1466 in part); PSD and PSB files open and place, linked or embedded, as their merged image in every colour mode and depth (#918). EPS import runs a PostScript Level 3 interpreter written from the PostScript Language Reference: resource categories and `resourceforall`, local and global VM (`currentglobal`/`setglobal`/`gcheck`), `clipsave`/`cliprestore`, subarrays and substrings that share storage, the standard dictionaries in `systemdict`, `dictstack`, `internaldict`, executable filters and strings, `load` by any key, `//name` immediate names, `token`, `execform`, user paths, `cshow`, `rootfont`, `cachestatus`, colour rendering and halftone queries, file `status` and data read with `flushfile`, and `pdfmark` marks dropped (Discord feedback, #466, #469, #474). Masked images (`ImageType 3` in its three interleavings) and reusable streams are read, and an image's several data sources are read in turn, as the reference defines (procedures that read one file get their own rows: such images came in banded, #498). `restore` puts dictionaries back as they were at the `save`, so programs that count their saves in a dictionary read to their end (part of #505). Tiling patterns come in as pattern swatches, uncoloured ones too; Type 3 fonts' glyphs as their outlines, spaced by `ashow`/`widthshow`/`xshow`/`kshow`; mesh and function-based shadings (types 1, 4–7) as gradient meshes; sampled functions (type 0) and Flate/LZW predictors are read. It is tested with programs written from the specification in the ways common generators use these features; Inkscape/cairo EPS files open as vectors. When a file's PostScript still can't be read, it opens as its TIFF preview, its Windows metafile preview (as vectors) or its EPSI preview, and the warning (in the status bar, `document.open`/`app.open`/MCP `open_file` replies and `vectorcraft-cli info`) names the error, the operator that raised it and the procedures it ran in. Legacy PostScript `.ai` files (Illustrator 3–8, written with the prolog that defines their operators) keep their groups and nested groups (`u` … `U`), between and inside clipping groups; EPS and EMF/WMF import nest clips (and groups) at most 128 deep, so a hostile file can't exhaust the stack. DXF TEXT justified Fit or Aligned spans its two points (stretched, or scaled as a whole). PDF export writes type as real, searchable text in embedded subset fonts by default, as Illustrator's PDF presets do (Convert Text to Outlines is an option; printer's marks stay shapes), so text-heavy PDFs stay small (#733). DXF export writes each fill as its outlines followed by its hatch, so laser and cutter software, which skips hatches, gets filled art and type too (#546). - TIFFs that store each channel as its own plane (PlanarConfiguration 2) place, relink and open as the same image stored pixel by pixel does, 8 and 16 bits: grayscale with an alpha channel or other extra channels, and CMYK with or without them. A planar CMYK TIFF keeps its ink amounts and is stored as a CMYK TIFF with each pixel's inks together, at the file's resolution. A TIFF whose header claims more strips or tiles than can be counted is refused as too large to draw (#1466 in part; `crates/engine/src/cmd/fileio/tests.rs`). - A 16-bit CMYK or grayscale TIFF with an alpha channel is converted from its 16-bit samples, and only the resulting color and alpha are rounded to 8 bits; associated alpha is divided out at 16 bits, and a pixel whose associated alpha is zero has no color. [TIFF 6.0](https://printtechnologies.org/standards/files/tiff-v6.pdf) gives extra samples the depth in BitsPerSample, and its Associated Alpha Handling section states the arithmetic and the zero-alpha rule for RGB data; applying them to CMYK and gray samples is VectorCraft's own rule. Each sample was cut to its high byte first, so a faint ink or a low alpha could be lost (`crates/doc/src/cmyk.rs`, `crates/engine/src/cmd/fileio/tests.rs`). + - A CMYK or grayscale TIFF whose alpha channel comes after another extra channel places and opens with that alpha, 8 and 16 bits, chunky or planar, and the other extra channels are left out. A channel that the file does not mark as alpha is not read as transparency, even when its ExtraSamples tag has fewer values than the file has extra channels. A CMYK TIFF with two or more extra channels past its ExtraSamples values, or with no ExtraSamples tag, opens opaque when none of them is marked as alpha, and a white-is-zero grayscale TIFF with an alpha channel opens too. A document saved with such a CMYK TIFF as a CMYK image keeps it as one, with its ink amounts. Such a TIFF is read when its samples take more than 256 MiB, as long as its samples, the copy a planar file needs, the row the decoder reads each strip or tile into and the RGBA pixels together fit the decoding allowance; a TIFF whose SamplesPerPixel is more than 64 is not read, which is VectorCraft's own limit, and both checks run on the file's tags before any decoding. [TIFF 6.0](https://printtechnologies.org/standards/files/tiff-v6.pdf) gives each extra channel its own ExtraSamples value, in order (pp. 31–32), and tells readers to skip extra channels they do not use (p. 27); reading the first channel marked as alpha is VectorCraft's own rule (`crates/doc/src/cmyk.rs`, `crates/engine/src/cmd/fileio/tests.rs`). - 1-bit TIFFs compressed with CCITT Group 3 (ITU-T T.4) place, relink and open: Compression 2 (modified Huffman) and Compression 3 with one-dimensional rows or, with T4Options bit 0, two-dimensional ones, with or without fill bits, in strips or tiles, with either FillOrder and either polarity. Rows in T.4's uncompressed mode are not read. A file whose pixels would take more than the decoding allowance as RGBA is refused as too large to draw (#1466 in part; `crates/engine/src/cmd/fileio/tests.rs`). - EPS and PostScript import keeps a CMYK image's ink amounts, as PDF import does: the samples of `image` and `colorimage` in a CMYK color space, and of a CMYK JPEG read through `DCTDecode`, come in as a CMYK TIFF, read through the image's Decode array, and the pixels a `MaskColor` or `ImageType 3` mask hides become a grayscale opacity mask (`crates/eps/src/import/tests_images.rs`). Such images came in as RGB PNGs. - EPS and PostScript import reads image data through `CCITTFaxDecode`: Group 4 (ITU-T T.6) and Group 3 one-dimensional and mixed (ITU-T T.4) data, with the filter's `K`, `Columns`, `Rows`, `EndOfBlock`, `EndOfLine`, `EncodedByteAlign` and `BlackIs1` parameters, decodes to 1-bit rows for `image` and `imagemask`. Damaged data keeps the rows decoded before it (damage in the first row is a PostScript `ioerror`), and parameters out of range or past the 256 MiB limit on decoded data are refused (`crates/eps/src/import/tests_images.rs`). Reading such a file stopped at an error naming the filter, and the file opened from a fallback, such as its preview or the art drawn before the image, or did not open. @@ -1797,35 +1860,47 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - A Word paragraph justified with a low, medium or high kashida length places justified with Insert Kashidas set to Short, Medium or Long (`file.place`, `crates/engine/src/tests/textimport.rs`). - File › Place reads Word 97-2003 `.doc` documents as area type with the same formatting, read from the main text's pieces, the style sheet's paragraph and character styles and direct formatting. Table rows are paragraphs with their cells separated by tabs and fields place as their results; fields without a result, hidden and deleted text, pictures, headers, footers, notes, comments and text boxes are left out, and `warnings` names each kind left out or changed. Encrypted documents, documents last saved with fast save and Word 6.0 and Word 95 documents are refused (`file.place`, `crates/engine/src/tests/textimport.rs`). - Placing a Word 97-2003 `.doc` document works out each style's formatting once and each property run's once, and refuses property pages that are out of order, listed twice or overlap, a style sheet that holds fewer styles than it counts, styles based on each other in a loop, and more than 100,000 runs of character or of paragraph properties, 16 MiB of properties or 100,000 paragraphs, hidden ones included (`file.place`, `crates/engine/src/tests/textimport.rs`). + - File › Place of a text file with the Unicode character set reads UTF-16 without a byte-order mark by the rule Import Data Sets… uses (at least half of its two-byte units hold a NUL byte; the byte order that reads a line break; valid UTF-16 with no NUL character), instead of reading it as UTF-8 with other characters in place of those outside U+0001 to U+00FF (`file.place`, `crates/engine/src/tests/textimport.rs`). - On the desktop, File › Place reads and decodes files off the UI thread, one at a time, and places each once it is read, with "Placing" in the status bar and the busy spinner until then: the Place dialog's OK, a file dropped on the canvas, a click or drag of the place cursor, and the OK of the PDF, DXF and text import options. The files and thumbnails the place cursor is loaded with are read the same way, and the Place dialog's lines about its files are read on a thread of their own. Files are placed in the order they were started; a file is not placed while a dialog is open or a drag is under way, and a file whose document was closed meanwhile is not placed. `file.place` and `file.place.queue` over MCP and scripts reply as before. - A file read for `file.place`, or files read for the place cursor, apart from the session (`Session::place_read`, `Session::place_queue_read`) go only into the document they were read for: while another document is active, or once that document is closed, they are refused with "the document it was prepared for is no longer active" and no document, selection, tool or undo step changes (`crates/engine/src/tests/place.rs`). - On the desktop, Paste from a menu or shortcut captures another app's bitmap or reads a copied image file on the UI thread, then decodes the image on the file-reading worker. The status bar shows "Pasting" until the image is pasted. Windows device-independent bitmaps and Linux clipboard images are encoded as PNG on that worker. A Copy or Cut made while the image is read keeps its internal clipboard. `edit.paste*` over MCP and scripts reads the bitmap at once. - File › Revert also drops what was started for the content it discards: a file being read for Place, for the place cursor or dropped on the canvas, a bitmap being read for Paste, and a paste waiting at its Swatch Conflict dialog are not placed or pasted in the reverted document, and the status bar says the document was reverted. Edits made while a file is read, a Revert that fails or that a batch rolls back, and a Revert of another document leave the read to finish as before (`crates/ui-egui/src/placing/tests.rs`). - The pixels of a PNG, JPEG, GIF or WebP file that Place decodes to check them are kept in the image store the renderers share, so the canvas's first frame with the placed image draws them without decoding the file again on the UI thread: File › Place, a file dropped on the canvas, a click or drag of the place cursor, `file.place`, and Paste of such an image. A CMYK JPEG is still decoded when it is first drawn (`crates/ui-egui/src/placing.rs`, `crates/render/src/tests.rs`). - A photo whose EXIF orientation turns or flips it (a camera held upright or upside down) is placed and opened upright, as it was taken; the image is stored as it is seen (#4284). A quarter turn swaps the resolution's axes, so the image keeps its physical size. TIFFs read without the image decoder (grayscale with extra channels, CCITT Group 3, CMYK with one plane per ink) follow their Orientation tag too, and a turned CMYK JPEG or TIFF keeps its inks, at the 8 or 16 bits the file has, as a CMYK TIFF. + - PDF export writes a CMYK image that keeps its numbers in an `ICCBased` color space holding, byte for byte, the CMYK profile the image carries (a CMYK TIFF's tag 34675, or a CMYK JPEG's `ICC_PROFILE` APP2 segments) when `output.profiles` is `all` or `taggedSource`, and in PDF/A-2b, PDF/X-3 and PDF/X-4 unless it is `destination` ([the help page](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/pdf-marks-bleeds-and-color-output-options.html)). This covers a CMYK JPEG embedded as it is, one the Compression settings resample or compress again, a TIFF written again, and an image written with its mask as its soft mask. With `none`, and in PDF/X-1a, the image is DeviceCMYK and a JPEG's own profile is left out, so PDF/X-1a export writes a CMYK JPEG that carries a profile. Pixels the Output settings convert are never tagged with the profile of their old numbers. A profile tags an image only when its size, signature, class, CMYK color space and tag table are well formed and it is at most 16 MiB (VectorCraft's own limit). Transparency in a tagged CMYK document blends in the document's CMYK profile; when the file holds no space of that profile it blends in DeviceCMYK, or keeps its RGB space in PDF/A, and never in an image's own profile (`crates/pdf/src/tests/cmykimages.rs`, `export::writer::tests`). - An image that Open and Place store again keeps the ICC profile its file embeds and its 16-bit samples. A turned PNG, JPEG, WebP or TIFF stored as PNG, and a TIFF the image decoder reads, keep their gray or RGB samples at 8 or 16 bits with their gray or RGB profile in the PNG's `iCCP` chunk ([PNG specification, iCCP](https://www.w3.org/TR/png-3/#11iCCP)). A CMYK TIFF stored with one plane per ink and a turned CMYK JPEG or TIFF keep their CMYK profile as TIFF tag 34675, a JPEG's put together from all its APP2 segments ([ICC image-format guide](https://github.com/InternationalColorConsortium/iccDEV/blob/master/iccdev-mcp/docs/icc-format-guide.md)). A profile whose color space differs from the stored samples' is left out. The profile is kept in the stored image; how CMYK inks are drawn and exported to PDF does not change (`crates/engine/src/cmd/fileio/tests.rs`). + - PDF export writes a stored gray or RGB TIFF in an `ICCBased` color space that holds the gray or RGB profile of its tag 34675, at 16 bits a sample from PDF 1.5 on and 8 before, with its alpha as a soft mask only when some pixel is not opaque ([ISO 32000-1, §8.6.5.5](https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf#page=157)). A gray or RGB image, a PNG included, that the Compression settings resample or compress with JPEG keeps its profile too, and gray pixels in an RGB profile stay RGB. Pixels the Output settings convert, a profile whose color space differs from the samples', and a malformed profile, a PNG's or JPEG's kept as it is included, are written without it; such a JPEG keeps its JPEG data. PDF/X-1a allows no ICC-based color spaces, so there a gray image with a gray profile, kept as it is, resampled or compressed with JPEG, is written in DeviceGray without the profile, a JPEG kept as JPEG with its JPEG data unchanged, and RGB images are converted to CMYK as before. CMYK images are unchanged (`crates/pdf/src/tests/compression.rs`). - SVG import shows a raster `<image>` whose EXIF orientation or TIFF Orientation tag turns or flips it upright, linked or as a data URL, and inside an SVG shown as an image: the pixels are stored turned, the width and height swap, and the `<image>` box fits the turned image under `preserveAspectRatio`, as CSS `image-orientation: from-image` describes (<https://www.w3.org/TR/css-images-3/#the-image-orientation>). A turned CMYK JPEG or TIFF keeps its inks as a CMYK TIFF, as does a CMYK TIFF that is not turned. TIFF data URLs (`image/tiff`, or untyped TIFF bytes) are read, and TIFFs with an alpha or other extra channel, CCITT Group 3 TIFFs and CMYK TIFFs stored one plane per ink are read as Open and Place read them. The pixels are decoded within the decode allowance, and a TIFF claiming more strips or tiles than the decoder can count is refused before it is decoded (`crates/svg/tests/it/image_orientation.rs`). + - An image that SVG import stores again, as PNG or as a CMYK TIFF, keeps the resolution its PNG, JPEG, TIFF, WebP or BMP file declares, as Open and Place keep it: in a PNG `pHYs` chunk (<https://www.w3.org/TR/png-3/#11pHYs>) or the TIFF's resolution tags, with the horizontal and vertical values swapped when the image turns a quarter. An image that declares no resolution is stored without one (`a_turned_raster_keeps_its_resolution`, `an_upright_tiff_keeps_its_resolution` and `a_cmyk_tiff_keeps_its_resolution_turned_or_not` in `crates/svg/tests/it/image_orientation.rs`). - SVG import leaves out an SVG shown as an image that it can't read (text that isn't XML, an SVG without a size) and goes on with the images after it, as SVG 2's error processing describes (<https://www.w3.org/TR/SVG2/conform.html>). Only images that decode count toward the 256 nested SVG images an SVG may show, so an image after many broken ones is imported. Every nested SVG image read, decoded or not, counts toward VectorCraft's own limits of 1,024 reads and 512 MB of text per import; past them, nested SVG images are left out with a warning (`crates/svg/tests/it/import_details.rs`). + - SVG import measures what an SVG expands to before the SVG reader builds it: every copy a `<use>` shows (<https://www.w3.org/TR/SVG2/struct.html#UseElement>), chains of `<use>`s included, and the style values each copy gets from its `style` attribute and from the style sheet rules that match it. An SVG that expands to more than 999,999 elements (500,000 on the web) or to more than 64 MB of copied style values is refused with an error, and so is a loop of `<use>` references that would be copied without end. The declarations the import's own style cascade keeps count toward the 64 MB too, once for each element a rule matches, including those of rules the reader drops, such as ones with `:not()`. Matching the style sheets' selectors against those elements may take at most 50,000,000 tests; past that the SVG is refused, so a selector that never matches can't keep the import busy. These limits are VectorCraft's own. An SVG shown as an image, from a data URL or a linked SVG file, counts toward the same limits as the SVG showing it, and one past any of them refuses the whole import (`crates/svg/src/import/budget.rs`, `crates/svg/tests/it/import_details.rs`). + - SVG import reads the files that a linked SVG file's own `<image>` elements link to, relative paths from that file's folder (<https://www.rfc-editor.org/rfc/rfc3986#section-5.1.3>), as it reads the imported SVG's links: a raster stays linked, an SVG file imports as vector art, and one that can't be read gets the placeholder, its link and a warning. SVG 2 tells a viewer not to load these links (<https://www.w3.org/TR/SVG2/conform.html#secure-static-mode>); reading them is VectorCraft's own rule. The same href in SVG files of two folders names two files. A link that leads back to an SVG file showing it gets the placeholder and a warning, and reading the links of linked SVG files stops at the nesting depth cap and at 1,024 reads and 512 MB per import, the same limits decoded nested SVG images have, counted separately from them. The text of every linked SVG file read counts, and so does every file read for the links of a linked SVG file, raster or SVG; rasters the imported SVG links to don't. Once either limit is passed, no file linked from a linked SVG file is read and its image is left out with a warning, and an SVG file the imported SVG links to is still shown, without the files its own links name, with a warning. Another href to an SVG file already read, spelled differently or in another SVG file, does not read it again, unless a link back or the depth cap changes what it shows there (`crates/svg/tests/it/import_details.rs`, `crates/svg/src/import/files.rs`). - File › Place and a file dropped on the canvas refuse a PNG, JPEG, GIF or WebP file whose pixels can't be read, such as one cut short by a download or a sync still running, and the status bar shows "Couldn't place <name>: the image's pixels can't be read". Paste and Relink refuse such an image too, and Update Links, or Open when it reads the file again, counts it as missing. A JPEG cut short still places when its pixels can be decoded (`file.place`, `crates/engine/src/tests_place.rs`). - On the desktop, Copy and Cut make the system clipboard's formats (text, SVG, PDF, PNG) from a copy of the clipboard on the thread that writes background saves and exports, and write them when they are ready; while that thread has a save, an export, a print or a recovery copy to finish, they are made and written at once. Until they are written, Paste in VectorCraft takes the internal clipboard, and while a text field or the Type tool has the keyboard the app waits for them. Another Copy or Cut, or a copy of text in VectorCraft, drops them. - In the Linux Flatpak on GNOME, where the clipboard goes through the compositor's core Wayland protocol, one Copy offers the PNG (`image/png`), the SVG (`image/svg+xml`, with Include SVG Code on) and the text, and Paste takes another app's SVG, text or PNG in that order, a picture over blank text or text that only names it; the Paste menu item is enabled by the types offered (`clipboard::wayland` tests in `apps/vectorcraft/src/clipboard.rs`; not yet run in the Flatpak on a GNOME session). - On that core Wayland clipboard, a paste from an app that leaves its pipe open and sends no data for 2 s fails and pastes nothing, and a paste of VectorCraft's Copy by an app that takes no data for 2 s is stopped and its pipe closed, so later pastes and copies are read and sent again; the 2 s limit is VectorCraft's own and starts again after each byte that moves (`clipboard::wayland::tests::a_read_from_an_app_that_stops_sending_fails_and_closes_the_pipe` and `a_send_to_an_app_that_stops_reading_fails_and_frees_its_thread`). + - On that core Wayland clipboard, files copied in a file manager paste as the first one that is art, before the clipboard's other types, as on the other platforms: Paste reads the `text/uri-list` the file manager offers (RFC 2483), else GNOME Files' `x-special/gnome-copied-files`, off the UI thread, and takes the `file:` URIs with no host or `localhost` (RFC 8089), percent escapes decoded; other URIs are skipped, and a list of more than 1,024 URIs, VectorCraft's own limit, names no file. The Paste menu item is enabled when a file list is offered (`clipboard::wayland::tests::files_copied_in_a_file_manager_paste_as_their_art`; not yet run in the Flatpak on a GNOME session). - On the desktop with Enable Background Export on (Preferences › File Handling), File › Package… collects the linked files and fonts and writes the package from the document as it was at OK on the thread that writes background saves and exports, with "Packaging" in the status bar and the busy spinner until it is written; a save of unsaved changes that Package starts is written first. `file.package` over MCP and scripts replies as before. - On the desktop with Enable Background Export on, Export for Screens and the Asset Export panel's Export encode and write their files (into the folder, or one ZIP in it) from the document as it was at OK on the thread that writes background saves and exports, with "Exporting" in the status bar and the export progress dialog, which counts the files and whose Cancel stops before the next file. `document.exportForScreens` and `assets.export` over MCP and scripts reply as before. - With Enable Background Export on, an Export for Screens with no folder of its own also writes in the background into the folder its `exportPreset` keeps, with the same progress dialog and Cancel, and the status bar names that folder. When that folder is outside an MCP client's read roots, the reply, its errors and the status bar name it by its own name, as for an export made at once (`dialogs::tests_screens::an_export_into_a_presets_folder_writes_in_the_background`, `fileio::tests_screens::a_prepared_export_into_a_presets_folder_outside_the_read_root_leaves_it_out`). Behavior reference: the help page, https://helpx.adobe.com/illustrator/using/exporting-artwork.html (exports run in the background by default). - Missing linked files can be looked for in a folder and its subfolders: Find in Folder… in the Linked File Not Found dialog and in the Links panel menu lists the files with each one's name, those with the size and contents saved with the link first, and relinks the files chosen, copying an image's file into the document's folder when asked, without replacing a file there (`links.findFiles`, `links.relink {copy}`). In the Links panel it looks for the selected linked files when any are selected. - The Links panel's Relink… opens a Relink dialog whose Replace menu picks which links take the new file: Selected Instances (the selected images, as before), All Instances (every image linked to the same file), Missing Links from This Folder (then every other missing link whose file name is in the new file's folder) and Each Link Separately (a file for each selected link in turn). Each relinks as one undo step (`links.relink {scope}`, `ui.relinkDialog`). Relink to Folder… stays as it is. + - The Links panel menu's Copy Info ([Links panel](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/links-panel-in-illustrator.html)) copies the selected link's file name to the clipboard (`links.copyInfo`). VectorCraft's own rules: with several rows selected it copies one name per line in the order the panel shows them, an embedded image gives the name its row shows, and the item is off with no row selected. - Linked files inside symbols, graph designs, patterns and opacity masks are saved with their paths relative to the document, as linked files in the layers are, so they are found after the document and its files move to another folder together; on open each of those links takes the path where its file was found. Update Links, and opening with Update Links: Automatically, read a modified file again for that art too, and saving a document refreshes its placed copies inside symbols and patterns of the other open documents. Evidence: `links_outside_the_layers_find_their_files_after_the_folder_moves`, `update_links_reads_files_again_inside_symbols_patterns_and_masks`, `saving_a_document_refreshes_its_placed_copies_inside_symbols_and_patterns`. - A linked file that is missing when a moved document is saved keeps the folder its relative path names, instead of a relative path worked out from the out-of-date absolute path, also for a `.ai` file another app wrote (such as `src/`), so the file is found once it is back in that folder. Evidence: `a_missing_link_keeps_its_relative_path_when_the_moved_document_is_saved`, `links_of_an_imported_file_are_found_by_their_relative_folder`, `a_missing_link_of_a_moved_document_keeps_its_relative_place`. - On Windows, a document opened from a mapped network drive finds its links stored with the share's own path (`\\server\share\…`), as the same document opened from the share does; links on other computers stay missing. - On Windows, a link on a drive mapped to a network share other than the document's (`Y:\…`) is missing, with the reason that the path is on another computer, as a link stored with that share's own path is; links on this computer's drives and on the document's share are followed. - In the Links panel, Shift-click selects a range of links and Ctrl/Cmd-click adds or removes one. + - The Links panel menu's Sort by Size ([Links panel](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/links-panel-in-illustrator.html)) lists the links by file size, smallest first (`links.list {sort: "size"}`). VectorCraft's own rules: a file's size is the one Link Info shows, rows without one (embedded images, a missing file whose size the document does not keep) come last, and equal sizes go by name. - When a document opens with notes and with linked files that changed on disk (Update Links: Manually) or, on the web, can't be read, the status bar shows the line about the linked files, then counts the notes and names the first, and hovering it lists the notes. The same holds when the line about modified files follows the Linked File Not Found dialog, and File › New from Template… shows the notes of the file it opens as File › Open does (`an_open_with_modified_links_keeps_link_notice_and_import_notes_reachable`, `new_from_template_preserves_open_warnings`, `an_open_with_unreadable_links_keeps_import_notes_reachable`, `modified_links_after_the_missing_ones_keep_the_open_notes`, `combined_open_and_link_status_lists_notes_on_hover_and_for_accessibility`). + - On the web, when a document opens with linked files that can't be read and linked files that changed on disk (Update Links: Manually), the status bar shows the line about the unreadable files, and the line about the changed files is the first of the notes its hover lists, ahead of the open's notes. With Ask When Modified the update question opens and the line about the unreadable files stays (`a_web_open_with_unreadable_and_modified_links_keeps_both_lines`). - Linked images and placed documents kept only in symbols, graph designs, patterns or opacity masks are listed in the Links panel after the layers' own, one row per stored object, with their status in its Missing and Modified filters, in Check Links, in the missing and modified files reported when a document opens, in the link watch and in Find in Folder; Relink, Update, Embed, Placement Options and Link Info act on them, and Go To says they have no place on the canvas. Opening a document gives such an object whose id is 0 or repeats another object's a new id. + - Linked images and placed documents in the art of the stored brushes (a scatter or art brush's art, a pattern brush's tiles) get Links panel rows of their own the same way, one per linked or placed object in each brush tile, naming the brush; Relink, Update, Embed, Placement Options, Link Info and Go To act on that art and write it back into the brush library, and the ids they are listed by are kept there. Evidence: `links_in_stored_brush_art_are_listed_and_checked_with_ids`, `links_commands_act_on_images_in_stored_brush_art_by_id`, `links_in_stored_brush_art_open_by_id_and_unreadable_entries_stay`. - Linked files another app changes while their document is open follow Preferences › File Handling › Update Links, as they do when it opens: Automatically reads them again (an Update Links undo step), Ask When Modified offers to, Manually leaves them modified in the Links panel. The desktop app compares the active document’s linked files by size and modification time every two seconds and when its window comes back to the front, on a worker thread; a file still being written is tried again (`links.updateChanged`). - A look at the linked files whose worker thread ends without a result, such as after a panic, no longer stops later looks: the app clears it, stops asking for a frame every 100 ms, and the next look starts on schedule (`crates/engine/src/tests/linkwatch.rs`, `crates/ui-egui/src/tests/place.rs`). - Import and paste, 2026-10-13: a multi-artboard `.ai` with notes beside its artboards opens from its editing data, a page's art past its artboard no longer lying over the page before it (#1528); a `.ai` gradient whose stops are listed upwards keeps each midpoint on the stop that starts its part of the ramp (#1530); SVG text on a path follows basic shapes (circle, ellipse, rect, line, polyline, polygon) as their SVG 2 equivalent paths (#1531, fixes #1527); PDFs whose alpha soft masks are drawn as images import with the mask instead of empty art (#1551); EPS and PostScript type set in Type 42 (TrueType) fonts imports at its size instead of 1000 times too large (#1553); PDF and EPS import keep a clipping path whose bounding box covers the page but whose shape doesn't (#1544, fixes #1542). Opening or placing a file with an image too large to decode says so, and the Links panel shows it on the row (#1540, part of #1479). Paste takes a PDF or EPS another app copied as editable vector art: from the macOS pasteboard (with SVG), EPS on Windows beside PDF, and `.eps` files copied in a file manager, with the new command `clipboard.importEps` (#1538, fixes #1499). - A `.ai` or `.ait` file copied in a file manager pastes as its art: one that holds a PDF pastes the objects of its editing data, and one saved as PostScript pastes as a copied `.eps` file does. + - Paste checks the size of a file copied in a file manager before reading it: a file of more than 64 MiB, VectorCraft's own limit, is skipped and the next copied file that is art pastes. A file that grows past the limit while it is read is skipped too, after at most one byte more than the limit is read. - A copied `.ai` or `.ait` file that holds a PDF pastes the objects of its editing data as File › Open reads them: every layer's objects go into the active layer in their stacking order, with their names, hidden objects and type objects, instead of the PDF page's art with its type as outlines. When the editing data can't be read, the file pastes its page as before (`clipboard.importPdf {editingData}`). The objects of a hidden layer come in hidden, from a pasted EPS too. - Import and export, later 2026-10-13 merges: SVGs that move objects with a CSS transform (`translate(100px, 0)`, `rotate(45deg)`) or style type with the `font` shorthand import as drawn (#1565); SVG symbols whose shapes use percentage lengths import at the size and place they are drawn, the percentages being of the symbol's `viewBox` (#1596); Inkscape's flowed text (`flowRoot`) opens as area type in its rectangle, a paragraph per `flowPara`, instead of being dropped, and a region that can't be read is left out with a warning (#1569, fixes #1568); the warning for an unsupported SVG filter names the filter, its primitives and the object, and says the object is drawn without it (#1599, fixes #1598); the pages of an Inkscape multi-page SVG become artboards, named by their labels (#1603, fixes #1601); SVG export with CSS classes or style entities stays fast in documents with many distinct styles (#1567); PDF and `.ai` import: evenly letter-spaced or tightened type on a path keeps its length along the path instead of closing up to the font's advances (#1586), and type on a path whose stroke is written glyph by glyph comes in as one text object with its stroke, not one object per glyph (#1585); the ICC profiles embedded in JPEG, TIFF and PSD exports have every tag on a 4-byte boundary (ICC.1 §7.1.2), so strict readers accept them (#1589, fixes #1584); GIF, PNG-8 and other indexed exports find each pixel's palette colour through an index instead of a scan, with identical output (#1576); a zero-length subpath draws its round cap as a dot and its projecting cap as a square, so dots in imported `.ai` and SVG files show (#1619, fixes #1613). - Files and untrusted input, 2026-10-14 merges: EPS import: a stitched shading keeps its hard colour changes (#1654, #1653). WMF/EMF import refuses an oversized embedded PNG or JPEG from its header, before any pixels are decoded (#1776). PDF open no longer takes exponential time on a crafted name tree with shared nodes when it looks for the editing data (#1781). The size limits on a native file's embedded data also apply to files read from memory, not only streamed ones (#1783). Saving over a private file on Unix no longer leaves a readable temporary copy beside it while the file is written (#1778). An Export for Screens suffix can no longer place files outside the export folder (#1777). Package refuses a folder where it would overwrite the open document or one of its linked files (#1786). ruzstd 0.9.1 fixes a decompression bomb (RUSTSEC-2026-0344) reachable from EPS/`.ai` and Affinity import (#1807). File Info dates are stamped only after a save succeeds, so a failed save no longer changes them (#1774). Linked files that change during a drag are updated after the drag instead of being missed (#1773). @@ -1881,6 +1956,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With the Perspective Selection tool, Ctrl+Alt-drag (Command+Option-drag on macOS) also copies objects on their perspective plane; Alt/Option-drag continues to do so. With the Perspective Selection tool, holding Shift while moving or copying constrains each object's displacement to the nearest axis or 45° diagonal of its own plane; releasing Shift resumes the raw pointer position, and 5 still moves perpendicular to the plane. Snap to Grid follows the constrained line on the first object's plane and depth. With Snap to Grid on, a move of objects on one perspective plane at different depths moves them all by the same offset on the plane, so they keep their spacing. Without Shift, on each axis, the edge of their joint bounds nearer a gridline lands on it when that edge ends within a quarter cell of the gridline. With Shift, an edge also lands only when it ends within a quarter cell of a gridline: a horizontal or vertical move can land only an edge on its own axis, and a 45° move lands the edge on the axis whose nonzero correction is smaller. When no edge on those axes is that close, the move does not snap. A move perpendicular to the plane does not snap. Regression: `snap_moves_objects_at_different_depths_by_one_plane_offset` in `crates/engine/src/tests/persp_select.rs`. + Perspective Grid Options has Automatic Plane Positioning with its two checkboxes, Anchor Point of Perspective Artwork and Intersection of Gridlines. With the Perspective Selection tool, Shift held over an anchor point of art in perspective, or over a gridline intersection, moves the active plane to that height or depth and hides the other planes; a plane made active then passes through the same point, and the planes are back in place once an object is drawn or placed there (`perspective.plane.infer`). VectorCraft's own rules: both options are on by default and kept with the preferences, the pointer counts as over a target within 6 screen pixels, an anchor point wins over an intersection, and Shift positions the plane only while no button is down. Tests: `crates/engine/src/tests/persp_infer.rs`. When the desktop app opens a document on a thread of its own (#1245), that thread also reads the document's linked files and lays out its type, and the UI thread only adds the finished document: in release builds, the step left on the UI thread takes 0.02 ms instead of 1.04 s for a document with 12 linked 3000 × 2000 TIFFs, and it takes 0.1 ms instead of 0.85 s for one with 300 Auto Size area type objects, every second one in three columns. Laying out type keeps each font face's shaping plans, at most 32 per face, so type objects of the same font, script, direction, language and features share one plan: the layouts of a document of 5,000 short point type objects take 59 ms instead of 73 ms in a release build, and the glyphs, bounds and baselines do not change. Laying out type looks up the font face of each style run once and uses it for the run's glyphs and for the line metrics of a paragraph that starts in that run: the layouts of a document of 5,000 short point type objects take a median of 215 million CPU cycles instead of 236 million in a release build (11 alternating runs of each build on Windows 11, measured while other builds were running), and the glyphs, bounds and baselines do not change. @@ -1901,7 +1977,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Raster-effect resolution in PDF:** when the 64 million pixel cap on an effect image renders an object's raster effects below the document's raster effects resolution, PDF export warns once per object with the requested and the lowest achieved ppi (`crates/engine/src/tests/pdfraster.rs`). - **Rasterize effect:** Effect › Rasterize… (`rasterize`) draws an object as an image of square pixels at its own resolution or the document's raster effects resolution, with Object › Rasterize's color model, background, anti-aliasing, clipping mask and room around the object, while its paths stay editable. Expand Appearance and PDF and SVG export of an object whose only raster effect is Rasterize give the image Object › Rasterize gives (`crates/engine/src/tests/rastersettings.rs`, `crates/render/src/tests/rasterize.rs`). Behavior reference: [How to save artwork in Illustrator](https://helpx.adobe.com/illustrator/using/saving-artwork.html), [Work with effects](https://helpx.adobe.com/illustrator/using/effects.html). - **Rasterize colour models:** Object › Rasterize with the Grayscale colour model makes a grayscale image (a gray PNG, with alpha over a transparent background), and with Bitmap a 1-bit image (a TIFF), or a black-and-white gray PNG with alpha over a transparent background; `image.info` and the Control bar say Grayscale, and a fill color colorizes the image, in RGB and CMYK documents (#6969). Expand Appearance and PDF export of a Rasterize effect make the same images. Regression coverage: `rasterize_to_grayscale_or_bitmap_makes_a_grayscale_image` (`crates/engine/src/tests/rastersettings.rs`) and `gray_and_bilevel_images_store_gray` (`crates/render/src/encode/tests.rs`). Scores and estimates unchanged. -- **SVG filters:** Effect › SVG Filters lists the document's own SVG filters below Apply SVG Filter… and Import SVG Filter…, and choosing one applies it to the selection as a live effect in one undo step (`svgFilter.apply`). Apply SVG Filter applies the selected filter, New and Edit open its code, and Delete and Import… remove filters or add those of an SVG file (`svgFilter.define`, `svgFilter.delete`, `svgFilter.import`). VectorCraft ships no default filters. The canvas, raster export and PDF draw the filter at the Document Raster Effects resolution; SVG export writes it as a `<filter>` element when it is the object's last effect and otherwise draws the object as an image; SVG import keeps filters the other live effects can't express as this effect instead of leaving them out; the native format keeps the filters (`crates/engine/src/tests/svgfilter.rs`, `crates/effects/src/svg_filter/tests.rs`). Behavior reference: [Apply SVG filter effects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/apply-svg-filter-effects.html), [CS5 help, Apply SVG effects](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=402), [SVG 1.1 Filter Effects](https://www.w3.org/TR/SVG11/filters.html). +- **SVG filters:** Effect › SVG Filters lists 14 default SVG filters and then the document's own below Apply SVG Filter… and Import SVG Filter…, and choosing one applies it to the selection as a live effect in one undo step (`svgFilter.apply`). Apply SVG Filter applies the selected filter, New and Edit open its code, and Delete and Import… remove filters or add those of an SVG file (`svgFilter.define`, `svgFilter.delete`, `svgFilter.import`). The public page names no default set: the defaults (Soft Blur to Hue Shift, `crates/effects/src/svg_filter/defaults.rs`) are VectorCraft's own, written with SVG 1.1 primitives. A default is copied into the document when it is applied or edited, and Delete does not remove a default. The canvas, raster export and PDF draw the filter at the Document Raster Effects resolution; SVG export writes it as a `<filter>` element when it is the object's last effect and otherwise draws the object as an image; SVG import keeps filters the other live effects can't express as this effect instead of leaving them out; the native format keeps the filters (`crates/engine/src/tests/svgfilter.rs`, `crates/effects/src/svg_filter/tests.rs`). Behavior reference: [Apply SVG filter effects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/apply-svg-filter-effects.html), [CS5 help, Apply SVG effects](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=402), [SVG 1.1 Filter Effects](https://www.w3.org/TR/SVG11/filters.html). - **Pattern tiles:** the renderer keeps a tile of each pattern for each scale it rasterizes the pattern at, until the tiles fill the tile cache's budget, and then drops the least recently used tiles first. Objects that show one pattern at different scales, such as a pattern scaled to 25% with Transform Pattern Tiles next to the same pattern at 100%, draw from tiles kept between frames. @@ -1931,6 +2007,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Smart Blur modes:** Effect › Blur › Smart Blur… has a Mode menu with Normal, Edge Only and Overlay Edge (`blurMode`: `normal`, `edgeOnly` or `overlayEdge`; an effect saved without it draws as Normal). Edge Only draws the edges in white on black, and Overlay Edge draws them in white over the Normal blur. A pixel is on an edge when one of the pixels the search reads within Radius of it differs from it by more than Threshold in a channel and its channels, alpha included, add up to at least that pixel's. The search reads neighbors as the Normal blur does, kept within Radius, and always the four nearest pixels, so a color step gives a line about as wide as Radius, and at least one pixel wide, on the side with the larger sum (lines on both sides when the sums are equal). The white and the black keep each pixel's coverage. Behavior reference: [Summary of effects](https://helpx.adobe.com/illustrator/using/summary-effects.html). +- **Radial Blur center:** Effect › Blur › Radial Blur… has a Blur Center box. A press or a drag in the box sets the point the spin or zoom starts from, and the arrow keys move it 1% (10% with Shift). Horizontal and Vertical fields beside the box take the same position in percent. The effect stores the point as `centerX` and `centerY`, from 0 to 1 across and down the object's bounds (0.5 each by default, VectorCraft's own form), so it moves and scales with the object. An effect saved without them draws about the object's center as before, and `effect.apply` and `effect.setParams` refuse a value outside 0 to 1. Tests: `radial_blur_turns_about_its_blur_center` in `crates/effects/src/pixel/tests.rs` and `radial_blur_center_is_stored_drawn_and_checked` in `crates/engine/src/cmd/effectcmd/tests.rs`. Behavior reference: [Summary of effects](https://helpx.adobe.com/illustrator/using/summary-effects.html). + - **Dragging objects with raster effects when zoomed in (#2558):** during a drag with a tool on the canvas, the renderer draws filtered content (Gaussian Blur, Feather and the Photoshop-style filters) within 1,000,000 pixels, at a lower resolution where it would need more, unless it can draw the content from an earlier frame's raster. In the desktop app it does the same for drop shadows, outer glows and inner glows. No raster made that way is kept. The frame after the drag renders them as a still frame does, and a dialog's preview, exports and printing render as before. `zoomed_drag_perf` times a drag's frames at 100% to 6400%. - **Dragging other art over a wide blur (#2558):** an effect raster too large to keep whole (a wide blur, a shadow or glow, or any blur zoomed in) is cropped to what can show in the view, or made at a lower resolution and resampled to the view's pixels, and kept while the view stays the same, so dragging other art over the object draws its effects from the still frame instead of re-rendering them at the drag's lower resolution. A drag stays on the render worker once the worker drew the frame shown, since only that renderer holds the rasters. `tests_viewraster` covers each effect, and `a_drag_over_a_wide_blur_draws_the_blur_from_the_still_frame` the canvas on and off the worker. Not yet: a worker frame shows one display frame after the overlays, and the first frame of an interaction can land on the renderer that has not made the rasters yet (follow-up: render every canvas frame on the worker, waiting briefly for fast ones). - **Opening a heavy document (#4155):** the canvas renders a document's first frame (when it opens, or its tab is chosen) on the render worker, as it renders the frames of a slow document, instead of on the UI thread, where a heavy one froze the window until it was done. The UI thread waits for it up to 16 ms (`FIRST_FRAME_GRACE`), so a light document's art shows in the same frame as before, without a frame of bare paper; otherwise the document's paper and artboards show, the window stays live, and the art shows when it lands. The web build, which has no worker, renders it as before. Measured on an M3 Pro, one run each, from launch with the file: the file of #4155 kept the UI thread busy for 8.7 s at a stretch, now at most 64 ms (its art lands as before, after about 9 s of rendering); a 50,000-path SVG 1.4 s, now 62 ms. `a_documents_first_frame_renders_on_the_worker` and `the_render_worker_waits_for_a_frame_only_as_long_as_asked` (`crates/ui-egui/src/canvas/tests.rs`). @@ -1965,6 +2043,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Objects on Path measures its path once:** placing the objects, finding one object's place and transforming the group flatten each path once and use it both for the path's length and for the points along it, where they flattened it two or three times before; a request for an object past the last one returns nothing without flattening the path, and a move of the group flattens no path. A path whose length adds up past the largest finite number no longer counts as one objects can be attached to. Evidence: `objects_on_path::tests::{stops_and_stop_flatten_the_path_once, transforming_the_group_flattens_each_path_once, placing_the_objects_flattens_the_path_once, a_path_too_long_to_measure_is_not_attachable}` in `crates/doc`. +- **Objects on Path widgets measure the path once:** with one Objects on Path group selected, finding where its Rotate All, Space, Move All and Select/Move widgets go, testing whether the pointer is over one and starting a drag flatten the group's path once, and the canvas draws all four widgets from that one flattening. Before, each widget flattened the path two or three times, and one pointer move over the group could flatten it eleven times. A drag of the Space, Move All or Select/Move widget keeps the measurement it started with and measures again only when the path changes, where it flattened the path twice on every pointer move. The widgets' places, what the pointer hits, the cursors and what each drag changes stay the same. Evidence: `objects_on_path::tests::{each_widget_lookup_flattens_the_path_once, the_widgets_of_a_group_share_one_flattening, a_widget_drag_flattens_the_path_once, a_widget_drag_follows_a_path_that_changed}` in `crates/tools`. + - **Blend, mesh and envelope numbers given as text:** `object.blend.make` and `object.blend.options` (`steps`, `distance`, `value`), `object.envelope.makeWithWarp`, `resetWithWarp` and `options` (`bend`, `h`, `v`, `horizontalDistortion`, `verticalDistortion`), `object.envelope.makeWithMesh` and `resetWithMesh` (`rows`, `cols`, `columns`), `object.envelope.options` (`fidelity`), `object.mesh.create` (`rows`, `cols`, `columns`, `highlight`) and `object.mesh.setPointColor` (`opacity`) refuse a value other than a number or null, such as `"8"`, and change nothing. `object.mesh.create` refuses an `at` that is not `[x, y]`. - **Blend and envelope options given as text:** `object.blend.make` and `object.blend.options` (`smooth`), `object.blend.spine.moveAnchor` (`independent`) and `reshapeSegment` (`perpendicular`), `object.envelope.makeWithWarp`, `resetWithWarp` and `options` (`horizontal`), `object.envelope.resetWithMesh` (`maintainShape`), `object.envelope.options` (`antiAlias`, `distortAppearance`, `distortLinearGradients`, `distortPatternFills`) and `object.envelope.editContents` (`editing`) refuse a value other than true, false or null, such as `"false"`, and leave the document and its undo history as they were. @@ -1994,6 +2074,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **A dialog's OK runs what it was opened for:** `ui.dialog.set`, and MCP's `answer_dialog` through it, can set a `__` field only when it is a control of that kind of dialog (a section or tab shown, a link between two fields, a name or search being typed). Every other `__` field, such as the `__command` and `__params` of a confirmation or the generic parameter dialog, a plug-in command dialog's `__command` and `__plugin`, or the paste a swatch conflict waits to finish, is refused with "the `<kind>` dialog cannot set protected field `<field>`"; the request sets no field, and with `action: "confirm"` OK does not run. Regressions: `crates/ui-egui/src/tests/automation.rs`, `crates/ui-egui/src/control/tests.rs`. Scores and hours unchanged. - **Only an approval records a plug-in grant (G17):** `vectorcraft_plugins::registry::grant` takes a `GrantToken`, which the engine makes after an approval and when it loads `grants.json`, and `registry::install`, `install_bytes` and folder loads refuse a module that lists permissions no recorded grant gives this very module (`Error::NeedsApproval`), leaving the plug-in under its id and the revision as they were. A module without `permissions`, or with an empty list, installs as before. `docs/plugins.md` says what the approval does not protect against (native code linked into the app, another program running as the same user, the unsigned `grants.json`). Regressions: `crates/plugins/src/registry.rs`, `crates/plugins/tests/grant_sites.rs`, `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. - **A refused plug-in install writes nothing (G17):** `plugin.install` checks the plug-in installed under the module's id and its grant again while it records the grant and installs the module (`registry::install_checked`), and only then writes the module and its grant to the `Plug-ins` folder, attaches its settings and cache and turns a disabled plug-in on. When another session installed a plug-in with the id that would need `replace: true`, or changed the grant the checks relied on, the install is refused and the folder, `grants.json`, the disabled list and the installed plug-in stay as they were. Without a plug-in store, the approval comes from the grant the install checks again. A `plugin.remove`, or a load of the folder or of a plug-ins folder, in another session waits until the install has written the folder. VectorCraft's own rule. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. +- **Windows and processes take turns on the Plug-ins folder:** each one locks `disabled.lock` in the `Plug-ins` folder while it reads and changes the stored modules, `grants.json`, `disabled.json` and the plug-ins' settings and caches, so two installs of one id keep each module with its own grant, and grants or settings written by two processes are all kept. When the file can't be locked, `plugin.install` and `plugin.remove` fail and change nothing. VectorCraft's own rule. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. - **Plug-in approval waits before OK (G17):** the approval dialog's OK stays disabled until its question has been on screen in the focused window for half a second, VectorCraft's own value; a click, Enter, Space, or a press begun before then installs nothing, and the dialog stays open. The wait starts over for every new question, even one that reads the same, and when the window gets the focus back, so a question swapped in just before a click is not approved by it. Cancel works at once. Regressions: `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. - **An install automation asked for needs the person to start it (G17):** an approval question that a control request, MCP, injected input or a file dialog one of them opened leads to keeps OK disabled and refuses every confirm, a person's click included; it says to choose Object › Plug-ins › Install Plug-in…, and `ui.installPlugin` answers `approval: "personMustStartInstall"`. The person's own Install Plug-in…, File › Open or drop inspects the module again and asks a new question. Automation's `replace: true` no longer skips the question about taking another module's place, and that question now opens in the approval dialog for everyone. VectorCraft's own rule. Regressions: `crates/ui-egui/src/tests/automation.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. - **A plug-in with no permissions ends its id's grant (G17):** installing a module that lists no permissions under a granted id forgets the grant, in the process and in `grants.json`, so the formerly approved bytes need a new approval. Attaching a `Plug-ins` folder whose module for that id lists no permissions forgets it too, and plug-in folders forget the process's grant. A refused install leaves the grant. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_safe_mode.rs`. Scores and hours unchanged. @@ -2007,6 +2088,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Live-effect plug-ins paint their output (G17, #121):** a live effect whose manifest has `"api": 2` and `"paintOutput": true` returns pieces, each drawn by itself in order with fills and strokes of its own in the filter's paint forms (a piece without them keeps the object's; an empty list paints none; an effect on a fill returns only fills, one on a stroke only strokes). The whole result is checked first: limits, numbers in range with nothing clamped, known keys only, and the swatches and patterns it names in the document; one fault draws that step of the stack unchanged, keeps the effect record and puts the plug-in's name and the field in `plugin.info`'s `lastError`. The pieces are drawn, measured and exported to PDF and SVG from the appearance stack without changing the document, and Expand Appearance writes them as ordinary paths in one undo step. Effects without the key behave as before. Regressions: `crates/plugins/src/painted/tests.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`. Scores and hours unchanged. - **Later effects on every fill or stroke a painted effect returns (G17):** when a painted effect on a fill or stroke returns several fills or strokes, a later live-effect plug-in in that fill's or stroke's stack, and a later geometry effect on strokes, runs once on each of them in paint order, given its own paint and its own `_context.item` among them. Each run's pieces replace only that fill or stroke. A run that fails, is refused, is deferred or would pass the effects' budget leaves only its own fill or stroke as it was, and the others still run; a deferred stage is listed once, at the source fill's or stroke's place. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/effects/src/tests/painted.rs`. Scores and hours unchanged. - **Painted pieces with brushed strokes are culled and measured by their brush art (G17):** a piece that keeps the object's brushed stroke draws the brush along the piece's own path at the piece's stroke width. Culling leaves VectorCraft's usual room for brush art (16 × the stroke width + 8 pt) past each piece, from the piece's width rather than the object's, and so does culling of a group, layer, symbol instance, blend, envelope or repeat that holds the object. A group or layer also leaves that room for each brushed path among its members, painted or not. Object › Rasterize takes the brush art drawn along each piece and leaves out the object's own brush art, which is not drawn. Pieces without a brush are culled as before. Regressions: `crates/render/src/tests/paintedbrush.rs`. Scores and hours unchanged. +- **Brushed paths just off the page are exported and printed:** PDF and EPS export keep a path or compound path whose brush art reaches the page while the path lies just off it, alone or in a group, by leaving the canvas's room for brush art (16 × the widest stroke + 8 pt, VectorCraft's own value) past its box. Skip Blank Artboards keeps an artboard such brush art reaches, and Print with Ignore Artboards frames the page with that room around brushed paths and around instances whose art holds brushed strokes. A clip group leaves room only for its clipping path. Art without brushed strokes is written as before. Regressions: `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/print.rs`, `crates/eps/src/tests.rs`. Scores and hours unchanged. - **Live-effect plug-ins while a document opens (G17):** the live-effect plug-in runs of a document's first view on screen share a 2,000 ms budget (VectorCraft's own value). A stage left out for time, or one that times out, fails, has no plug-in or meets Safe Mode, draws its input unchanged and is deferred; the status bar says how many, `effect.deferredStatus` lists them with their object, effect and reason, and Effect › Refresh Deferred Effects (`effect.refreshDeferred`) runs them again with a fresh budget. Each document has its own budget, an edit runs the stages it changes, and exports, Expand Appearance and commands run every stage under the 5 s limit of each run. The web build times the budget and each run's limit with the page's `performance.now()`. Regressions: `crates/plugins/src/deferred.rs`, `crates/plugins/src/effect.rs`, `crates/plugins/src/host.rs`, `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/canvas/tests.rs`. Scores and hours unchanged. - **Refreshing many deferred effects (G17):** Refresh Deferred Effects (`effect.refreshDeferred`) looks up the objects asked for, the stages reached, the objects drawn whole and the inputs that ran in hash sets, so its time no longer grows with the square of the number of deferred stages. The deferred records are indexed by stage and input, so asking whether a stage stays deferred, replacing a stage's records when it runs, and ending a drawing after the first view look at that stage's records only, and the records keep the order they were made in. With 40,000 deferred stages, one refresh in a release build took 38 ms, down from 1,036 ms, and asking about and running each stage once took 16 ms, down from 2,287 ms (wall-clock time on a computer busy with other builds, one run each). Regressions: `crates/plugins/src/deferred.rs`. Scores and hours unchanged. - **Refresh Deferred Effects by object (G17):** `effect.refreshDeferred` takes `ids`, or `id` for one, naming objects in the layers or in the art of a symbol, pattern, brush or opacity mask, the objects `effect.deferredStatus` lists; an object without a deferred stage adds nothing to the counts, and an id of no object in the document is an error. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. @@ -2023,7 +2105,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur `xtask/src/pngsuite.rs` verifies each file from the pinned PngSuite mirror against `xtask/pngsuite.sha256` before it reaches the corpus. Seven synthetic regressions cover substitution, oversize, cache repair, failure cleanup, nonregular targets, stale staging and manifest limits. The opt-in corpus remains gitignored; no PNGs are committed. -Evidence for the shared light Color: geometry tests in `tests_lighting`, effect paint tests, command/save/undo/expand and SVG/PDF checks in `three_d_light_color`, and headless picker/reset/preview tests in `tests_revolve`. Revolve keeps smooth colored vector ramps and continuous flat-lit caps. Inflate geometry tests check spherical lighting, shared vertex/edge continuity, concave cell coverage, puffed backs at perspective and legacy single-light/list equivalence; rendered command/export regressions cover smooth shading and editable expansion. Four legacy white-light PNGs matched main byte for byte when this was measured (2026-10-17); since every 3D seam took round joins (2026-11-12), white-light output is expected to differ from them at facet corners ([Seams](three-d.md#seams)); the four scenes were not exported again to measure it; [release measurements](3d-lighting-performance.md) record the colored solid-fill batch and the remaining source-gradient cost. +Evidence for the shared light Color: geometry tests in `tests_lighting`, effect paint tests, command/save/undo/expand and SVG/PDF checks in `three_d_light_color`, and headless picker/reset/preview tests in `tests_revolve`. Revolve keeps smooth colored vector ramps and continuous flat-lit caps. Inflate geometry tests check spherical lighting, shared vertex/edge continuity, concave cell coverage, puffed backs at perspective and legacy single-light/list equivalence; rendered command/export regressions cover smooth shading and editable expansion. Four legacy white-light PNGs matched main byte for byte when this was measured (2026-10-17); since every 3D seam took round joins (2026-11-12), white-light output is expected to differ from them at facet corners ([Seams](three-d.md#seams)); the four scenes were not exported again to measure it; [release measurements](3d-lighting-performance.md) record the colored solid-fill batch and the remaining source-gradient cost. Colored Inflate's facets lie over an underlay of themselves under one clip, so their shared edges show neither the black channel backdrop nor the background ([Seams](three-d.md#seams)); `three_d_light_color::colored_light_surfaces_match_supersampling_at_internal_facet_edges` compares 1:1 with 3x averaged down, and `colored_light_seams_stay_closed_in_svg_pdf_and_expansion` checks SVG, PDF and Expand Appearance. ## Eyedropper character dimensions (2026-11-11) @@ -2099,6 +2181,11 @@ Line / Paragraph Breaks, Set Alignment, Keep Position, Reset Text Transform and refusals), `addons::cleanup::tests` in `vectorcraft-ui-egui` (the submenu and the panel's Text row run them) and `cleanup_text_tools_with_junk_editing_ranges` in the command sweep. +With `ids`, the text tools act on the type the ids name even when it, or its group or layer, is locked or hidden, as +`text.convertListToText` does; from the selection they still take only type that can be edited (VectorCraft's own +rule). Tests: `named_locked_and_hidden_type`, `remove_breaks_named_locked_and_hidden_type` and +`remove_breaks_named_story_with_a_locked_frame` in `cmd::addons::cleanup::text::tests`. + ## Path Precision Tools add-on (2026-10-30) A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Path Precision Tools, @@ -2271,6 +2358,10 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov A VectorCraft addition, so no area score moves. Object › Plug-ins › Cutting Tools › Banner Hems and Grommets… (`addon.cutting.banner`) marks where a printed banner is hemmed ([hem](https://en.wikipedia.org/wiki/Hem)) and where its grommets go ([grommet](https://en.wikipedia.org/wiki/Grommet)). The rest is VectorCraft's own: the banner is the selected art's bounds or each artboard; each chosen side gets a hem line at a set depth inside its edge (1 in by default) and grommet marks at a set inset (0.5 in), one at each end of the side and the rest spread evenly at most a set spacing apart (24 in), with one grommet at a shared corner. Each grommet mark is a circle with a cross through its center. The marks are stroked in a chosen swatch ([Registration] by default), in one group named Banner Marks per banner on top of the current layer, added as one undo step. The dialog has Preview. Tests: `cmd::addons::cutting::banner::tests` in `vectorcraft-engine`, `banner_hems_and_grommets_previews_cancels_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Cutting Tools add-on › Banner Hems and Grommets. +## Cutting Tools add-on: Nest Shapes (2026-11-14) + +A VectorCraft addition, so no area score moves. Object › Plug-ins › Cutting Tools › Nest Shapes… (`addon.cutting.nest`) moves the selected objects close together onto a sheet or a roll of material ([packing problems](https://en.wikipedia.org/wiki/Packing_problems)). The rest is VectorCraft's own: the sheet is an artboard, or a set width and height from its top-left corner, and a roll is a set width with no end; a margin is kept inside the edges and a spacing between objects. Objects are packed by their bounding boxes, with or without strokes and effects (shadows, glows and blurs included), the tallest first, each where its bottom edge is highest and then furthest left; with Rotate an object may turn 90° where that places it higher or where only the turned object fits. Objects that do not fit go in a column to the right of the sheet, in stacking order. The command is one undo step, and its result gives the length of material used. The dialog has Preview. Tests: `cmd::addons::cutting::nest::tests` in `vectorcraft-engine`, `nest_shapes_previews_cancels_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Cutting Tools add-on › Nest Shapes. + ## Path Precision Tools add-on: Divide into Dashes (2026-11-01) A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Path Precision Tools › Divide into Dashes… cuts the selected paths into separate open paths along the curve (arc length, not straight distance): each `dash` long (0.01 to 1000000 pt, 10 by default) with `gap` between them (0 by default: the pieces touch); the gap pieces are left out unless Remove Gaps is off. With direct-selected segments (or anchors) only those runs are divided, the pattern running on across segments that follow one another, and the rest of such a path stays as pieces of its own. Fit to Corners and Ends gives every run between corners and ends a whole number of dashes, all stretched or squeezed alike so it starts and ends on a dash (a closed path without corners holds whole periods); otherwise the lengths are exact and each run's last piece is what is left. Every piece keeps the path's appearance and is selected; one undo step; at most 100000 pieces (more is refused). The dialog takes lengths in any unit and previews on the canvas. Tests: `dashes::tests` in `vectorcraft-pathops` (exact and fitted lengths, curves measured along them, picked segments on open and closed paths, the piece cap and bad patterns), `divide_into_dashes_*` in `cmd::addons::pathtools::tests` in `vectorcraft-engine` (gaps removed or kept, fitted lengths, the stroke kept, one undo step, selected segments only, bad params and too many pieces refused), `divide_into_dashes_opens_its_dialog_previews_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Path Precision Tools add-on. @@ -2401,7 +2492,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | Date | Change | Summary | |---|---|---| -| 2026-11-15 | minor | G12: Swatches item menus validated in all five views: 39 focused tests passed, regression fails without the menu hooks, rendered list/thumbnail layouts inspected, and fresh local deep CodeRabbit review found zero issues. Full workspace CI passed on Linux/WSL (all 13 gates); native Windows full CI has two unchanged engine-test failures. Scores and estimates unchanged. | +| 2026-11-15 | minor | G12: Swatches item menus validated in all five views: 39 focused tests passed, regression fails without the menu hooks, rendered list/thumbnail layouts inspected, and fresh local deep CodeRabbit review found zero issues. Full workspace CI passed on Linux/WSL for feature commit `6f4a651c0` (all 13 gates); validation after merging main stops at the upstream test-helper compile error tracked in #7727; native Windows full CI has two unchanged engine-test failures. Scores and estimates unchanged. | | 2026-11-14 | minor | G12: Swatches item context menus implemented in list and thumbnail views, with clicked-item actions and reserved/missing-swatch guards. Harness tests added; execution and visual verification pending. Scores and estimates unchanged. | | 2026-11-14 | minor | G5: Weather Icons joins Basic Shapes, UI Frames, Map Markers, Inventory Icons and Skill Icons as a sixth built-in symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow; original procedural vector symbols generated in code, no default 9-slice); area score and estimate unchanged. | | 2026-11-14 | minor | Gujarati (#6613): contributor proofreading completed for all 387 additions, with 11 wording corrections; 4,673 reviewed catalog rows. Status/error messages remain partial; web selection requires a bundled Gujarati face. Scores and estimates unchanged. | @@ -2429,6 +2520,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | 2026-11-11 | minor | Bundled content: built-in Energy Beams brush library (Laser Bolt, Plasma Arc, Charge Wave, Spark Trail); brush libraries evidence updated; ~44% → ~46%; more built-in brush libraries remain. | | 2026-11-11 | minor | Bundled content: built-in Skill Icons symbol library (Attack, Defend, Heal, Buff, Ult); symbol libraries evidence updated; ~42% → ~44%; more built-in symbol libraries remain. | | 2026-11-11 | minor | Bundled content: built-in Status Effects graphic style library; style libraries evidence updated; ~40% → ~42%; MCP Symbol libraries list UI Frames and Map Markers; more built-in graphic-style libraries remain. | +| 2026-11-14 | minor | Symbols panel context menu: right-click on a symbol in thumbnail or list view displays a context menu (Place Symbol Instance, Edit Symbol, Duplicate Symbol, Delete Symbol, Break Link to Symbol, Select All Instances), selecting the symbol first if unselected; scores and estimates unchanged. | | 2026-11-11 | minor | Bundled content: built-in Inventory Icons symbol library (Sword, Shield, Potion, Key, Gem); symbol libraries evidence updated; ~38% → ~40%; more built-in symbol libraries remain. | | 2026-11-11 | minor | Guides and snapping: a Shift move slides the selection along its line onto a ruler guide by its edges and centre, as a move without Shift does (#4312); a guide a nearly parallel line only reaches a long way off pulls nothing. Score and hours unchanged (estimated). | | 2026-11-10 | minor | Automation: MCP tool count 33; headless `command_list` lists `UI_COMMANDS` (`ui: true`); eight prompts; effect-id vs command-id clarified (#6460); scores and hours unchanged. | diff --git a/docs/three-d.md b/docs/three-d.md index 6de07fc2fe..f12ca4675c 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -85,8 +85,10 @@ object is where the art was. | Bevel Inside | The bevel carved into the shape (the front face shrinks) instead of added around it (the walls stand outside the art). | | Bevel both sides | The back is bevelled too. | -Holes stay holes, with walls of their own. Bevels move each corner along its bisector (mitres are limited to four -times the width), so a bevel wider than a narrow part of the shape folds over itself. Each facet has a seam ([Seams](#seams)). +Holes stay holes, with walls of their own. Bevels move each corner along its bisector. A corner the bevel opens (a +sharp point with the bevel outside, a narrow notch with it inside) whose miter would reach past four times the width is +cut square across instead; at the other corners the miter is limited to four times the width. A bevel wider than a +narrow part of the shape folds over itself. Each facet has a seam ([Seams](#seams)). ## Inflate @@ -119,6 +121,14 @@ How a facet carries its seam depends on the lights and the paint: groups clipped to the union of its facets, so no seam reaches past the surface; a gradient fill, and a solid-color fill or stroke whose faces share one depth order with another solid's, fills each facet's ramps through a clip of the facet and its seam, outlined with round joins. + The facets of a surface drawn this way lie over an underlay + of themselves whose seams are 2 pt wide, reaching 1 pt past each edge, and one clip to the union of the facets and + their seams removes what the underlay paints past the surface. Where two facets' antialiased edges meet, the + underlay fills the pixels they leave partly uncovered with the neighbors' own light, so no black channel backdrop + or background shows there. Compared with the same art drawn at 3x and averaged down, away from the surface's outline + and from places where the light changes sharply, a pixel drawn at 1:1 is opaque where the 3x art is opaque, and + otherwise its alpha is within 3 levels. Inflate seen straight on with an opaque fill also has each color channel + within 3 levels (VectorCraft's own measure). - Extrude & Bevel (Classic), Rotate (Classic) and Revolve (Classic): a path and a seam for every face; gradient and pattern faces seam only the base paint, and the shading and highlight layers cover the face alone. The Wireframe surface draws edges only, with no seam. @@ -153,7 +163,8 @@ The rest is our reading: depths where they overlap, with caps on or off. A fill wall in a gap stays in its own depth order. Inflate's curved surfaces follow this only as closely as their flat facets do. A solid painted with a gradient that has transparent stops under a light that is not white is drawn with an opacity mask: its faces keep their places in - this order, in runs that each carry the mask, and so do its graphics. A member of a 3D group with its own opacity + this order, in runs that each carry the mask, and a graphic drawn after one of its faces carries the mask too + ([Graphics](#graphics)). A member of a 3D group with its own opacity mask or blending mode draws its fill's and strokes' faces in this order inside that mask or blending mode when they are opaque with Normal blending. Otherwise each solid is drawn on its own with its opacity and blending, the lower item's first. With a light that is not white, a puffed, shaded Inflate surface in a solid color takes its @@ -169,6 +180,10 @@ The rest is our reading: once their faces pass it no later solid is built: the object draws its source art, and applying or editing the effect, Export 3D Object and **Expand as Wireframes** report that the 3D surface is too complex. A stroke left out for its own limits does not count. +- Inflate works out how high every shape puffs before it builds the first solid, because the highest puff sets + how far away the eye is. At a Volume of 0 % no shape puffs, so each shape's puff is worked out only when its + solid is built, and none is worked out for the solids after the limit stops. The shadow builds no solid for a + fill or stroke that is fully transparent. ## Groups @@ -375,8 +390,11 @@ These rules are VectorCraft's own: turned, foreshortened by the perspective and twisted and tapered with the face, and clipped to it. It is shaded with the face's light: each color is multiplied by the light that falls on the face, except in pattern tiles, which keep their own colors. It is drawn with the - opacity and blending mode of the fill or stroke the face is painted with. A graphic on a face turned away from - the viewer is not drawn. + opacity and blending mode of the fill or stroke the face is painted with. Solids whose fills and strokes have the + same opacity and blending mode share one graphic on each face, clipped to their faces there and drawn after the + last of them. An object's fill and stroke share it when the fill is drawn with an opacity mask too, and the + graphic takes the mask of the solid it is drawn after; members of a 3D group drawn with a mask keep graphics of + their own. A graphic on a face turned away from the viewer is not drawn. - On the back cap, X runs to the right as the back is seen from behind, so the graphic reads the right way round there. - On Revolve a graphic lies on the swept side, which has one face (Front), unrolled flat. X runs around the axis: diff --git a/docs/type-parity.md b/docs/type-parity.md index 31a835772d..57578e454b 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -39,7 +39,7 @@ against Illustrator's public documentation; **estimated** unless noted. | Full font-name matching (OpenType name ID 4) | done | #1258: loaded/cataloged faces and Missing Fonts searches; localized names and variable default faces; Windows font-service QA pending | | Variable fonts | done | named instances as styles; Character panel › Variable Font sets each axis (`fontAxes`); the font menu's Font Technology › Variable lists only variable font families, with the script, kind and ★ filters ([Find, apply, and adjust variable fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/find-apply-and-adjust-variable-fonts.html)); a family with a variable file beside static ones counts as variable. Evidence: `font_menu::tests::the_variable_filter_lists_only_variable_families`, `tests_axes::a_family_with_variation_axes_is_variable`, `tests_sysfonts::a_family_with_a_variable_file_beside_static_ones_is_variable` | | Fallback glyphs keep the text's weight and slant | done | #2491: a character from a fallback face is set in that family's face nearest the run's weight and slant; Bold Italic of a missing family is drawn Bold (Source Sans 3 has no Bold Italic) rather than Italic; a letter and its combining marks (a grapheme cluster) are drawn in one face, the first that has all of them, so marks the text's font lacks attach to their letter instead of drawing as missing glyphs (#4491). Vietnamese letters with two marks (Ể, Ứ, Ự) sit on their letter whether typed precomposed, decomposed or as a vowel plus a tone mark, built from GPOS mark-to-mark in fonts without the precomposed letters. Evidence: `tests::vietnamese` | -| Colour fonts (bitmap, COLR, OpenType SVG) | partial | bitmap glyphs (`sbix`, `CBDT`) done: the largest strike's PNG, transformed with the type, fill and stroke ignored; PDF Type 3 glyphs or images, SVG images with outlined text (live text leaves emoji to the viewer, their fonts not embedded), EPS and legacy `.ai` images, Create Outlines images; not `sbix` duplicate, flipped, JPEG or TIFF glyphs, or `CBDT` BGRA or mask data, or ruby; in envelopes they warp as images do, and a Warp effect moves them without bending them. COLR (v0 and v1) done: a glyph's layers as vector art (solid colours, linear and radial gradients that pad, repeat or reflect (the [COLR specification](https://learn.microsoft.com/en-us/typography/opentype/spec/colr)'s extend modes), clip glyphs and boxes, blend modes, transforms, palette 0, the foreground colour from the run's fill, variable fonts at the face's instance), transformed with the type; drawn on the canvas, written as paths in SVG, EPS, legacy `.ai` and PDF with outlined text, as text in PDF (Type 3 glyphs), and Create Outlines makes groups of editable paths. Paints documents have no form for draw the glyph as an image (256 px per em): sweep gradients, Porter-Duff compositing, radial gradients from a circle that isn't the centre, radial gradients that repeat or reflect and start at a circle, gradients that repeat or reflect with a stop whose color isn't in the palette. Not ruby. COLR and SVG glyphs also go with type that geometry effects reshape (on the canvas and in exports), into Expand Appearance and EMF/WMF export, as their art, and bitmap glyphs as images. OpenType SVG done: a glyph's SVG document (its element `glyph<gid>`) is read by the SVG importer into vector art in font units, `currentColor` in the run's fill (and the legacy `context-fill` and `context-stroke` in its fill and stroke), a `viewBox` mapped onto the em square, and then drawn, exported and outlined as COLR glyphs are; in PDF real text such glyphs are text that draws nothing, with their art drawn where they sit. Images in glyph documents are in the art, holding their pixels until a document takes them in; text, scripts and embedded content are left out, as the table rules them out. Not CPAL palette variables. Evidence: `tests_svg_glyphs`, `svg/tests/it/svg_glyphs.rs`, `tests_colourfonts::svg_glyph_images_draw_and_outline`, `tests_colourfonts::create_outlines_turns_svg_glyphs_into_groups`, `tests_colourfonts::pdf_real_text_draws_svg_glyphs_as_art_and_keeps_their_characters`, `tests_colourfonts::expand_appearance_keeps_the_colour_glyphs_of_type_with_effects`, `render::tests_colrglyphs::colour_glyphs_go_with_type_that_a_geometry_effect_reshapes`, `tests_bitmaps`, `tests_colr`, `render::tests_bitmapglyphs`, `render::tests_colrglyphs`, `pdf::tests::colour_bitmap_glyphs_export_as_images`, `pdf::tests::colr_glyphs_export_as_vector_art`, `svg/tests/it/colour_glyphs.rs`, `eps` `colour_bitmap_glyphs_*` and `colr_glyphs_*`, `tests_pathops::create_outlines_turns_bitmap_glyphs_into_images`, `tests_pathops::create_outlines_turns_colr_glyphs_into_layer_groups` | +| Colour fonts (bitmap, COLR, OpenType SVG) | partial | bitmap glyphs (`sbix`, `CBDT`) done: the largest strike's PNG, transformed with the type, fill and stroke ignored; PDF Type 3 glyphs or images, SVG images with outlined text (live text leaves emoji to the viewer, their fonts not embedded), EPS and legacy `.ai` images, Create Outlines images; not `sbix` duplicate, flipped, JPEG or TIFF glyphs, or `CBDT` BGRA or mask data, or ruby; in envelopes they warp as images do, and a Warp effect moves them without bending them. COLR (v0 and v1) done: a glyph's layers as vector art (solid colours, linear and radial gradients that pad, repeat or reflect (the [COLR specification](https://learn.microsoft.com/en-us/typography/opentype/spec/colr)'s extend modes), clip glyphs and boxes, blend modes, transforms, palette 0, the foreground colour from the run's fill, variable fonts at the face's instance), transformed with the type; drawn on the canvas, written as paths in SVG, EPS, legacy `.ai` and PDF with outlined text, as text in PDF (Type 3 glyphs), and Create Outlines makes groups of editable paths. Paints documents have no form for draw the glyph as an image (256 px per em): sweep gradients, Porter-Duff compositing, radial gradients from a circle that isn't the centre, radial gradients that repeat or reflect and start at a circle, gradients that repeat or reflect with a stop whose color isn't in the palette. Not ruby. COLR and SVG glyphs also go with type that geometry effects reshape (on the canvas and in exports), into Expand Appearance and EMF/WMF export, as their art, and bitmap glyphs as images. OpenType SVG done: a glyph's SVG document (its element `glyph<gid>`) is read by the SVG importer into vector art in font units, `currentColor` in the run's fill (and the legacy `context-fill` and `context-stroke` in its fill and stroke), a `viewBox` mapped onto the em square, and then drawn, exported and outlined as COLR glyphs are; in PDF real text such glyphs are text that draws nothing, with their art drawn where they sit. Images in glyph documents are in the art, holding their pixels until a document takes them in; text, scripts and embedded content are left out, as the table rules them out. Not CPAL palette variables. Evidence: `tests_svg_glyphs`, `svg/tests/it/svg_glyphs.rs`, `tests_colourfonts::svg_glyph_images_draw_and_outline`, `tests_colourfonts::create_outlines_turns_svg_glyphs_into_groups`, `tests_colourfonts::pdf_real_text_draws_svg_glyphs_as_art_and_keeps_their_characters`, `tests_colourfonts::expand_appearance_keeps_the_colour_glyphs_of_type_with_effects`, `render::tests_colrglyphs::colour_glyphs_go_with_type_that_a_geometry_effect_reshapes`, `tests_bitmaps`, `tests_colr`, `render::tests_bitmapglyphs`, `render::tests_colrglyphs`, `pdf::tests::colour_bitmap_glyphs_export_as_images`, `pdf::tests::colr_glyphs_export_as_vector_art`, `svg/tests/it/colour_glyphs.rs`, `eps` `colour_bitmap_glyphs_*`, `colr_glyphs_*` and `type_taken_back_for_the_page_limit_takes_its_glyph_images_with_it`, `tests_pathops::create_outlines_turns_bitmap_glyphs_into_images`, `tests_pathops::create_outlines_turns_colr_glyphs_into_layer_groups` | | Every-line and Single-line composers | done | tuned by eye, never compared side by side | | Optical Margin Alignment | done | Type › Optical Margin Alignment, `type.opticalMarginAlignment`: per type object, with one setting for all the frames of a thread, in point and area type of left-to-right paragraphs, and at the brackets of type on a path whose first paragraph runs left to right; right-to-left paragraphs of point and area type, and type on a path whose first paragraph runs right to left, do not hang | | System Layout | done | Character panel menu › System Layout, `type.systemLayout`: the whole document, off by default and for documents from before it, saved only when on. On, every text object advances by whole points (at least one when a character takes space). New point, area and path type, threaded frames, placed text, graph and dimension labels and pasted plain text inherit it. Evidence: `tests::system_layout_rounds_positive_advances_to_whole_points`, `typecmd::area_tests::system_layout_sets_the_document_and_every_text_object`, `panels::character::tests::system_layout_menu_item_toggles_the_document` | @@ -51,7 +51,7 @@ against Illustrator's public documentation; **estimated** unless noted. | Tab stops and leaders; Tabs panel | partial | Tabs panel and stops with leaders in the model (`text.tabs.set`); a stop drags from where the press landed (#1458); leaders fill the tab's gap, repeated on a grid so they line up from line to line (#1877); Ctrl-dragging a stop (Command on macOS) moves all the stops together; in right-aligned area type the text before a line's last tab sits at its stops, from the left edge, and the text after it against the right edge, as Illustrator's own layout in a user's `.ai` sets a price list (evidence: `tests::right_aligned_area_type_sets_the_text_after_its_last_tab_against_the_edge`; centred lines are still aligned as a whole); in justified area type the text up to a line's last tab keeps its spacing and its tabs their stops, and the text after the last tab takes the line's room to the far edge, VectorCraft's own rule (evidence: `tests::justify::a_justified_line_with_a_tab_spreads_the_text_after_it_to_the_edge` and the other tab tests in `crates/text/src/tests/justify.rs`) | | Hidden characters (Show Hidden Characters) | done | `type.hiddenCharacters` | | Spell check (Check Spelling, Auto Spell Check, custom dictionary) | partial | the engine (#4936): `text.spelling.check` lists the unknown words of the document's type, each run in its Language, at the bytes `text.editRange` changes, and `text.spelling.suggest` gives suggestions, both from craft-proof, each paragraph on its own (English from the first dictionary it finds: a Hunspell dictionary in the user's dictionaries folder, the SCOWL dictionary built in from craft-i18n, a system Hunspell dictionary, and last the public-domain Moby word list built into it; other languages from the dictionaries craft-proof finds for them). The custom dictionary commands are done: `text.spelling.addWord`, `removeWord` and `changeWord` (Add, and Edit Custom Dictionary's Add, Delete and Change), and `text.spelling.dictionary` lists the words, saved to `Custom Dictionary.txt` beside the preferences; Ignore All: `text.spelling.ignoreAll` skips a word in the active document while it is open. Auto Spell Check is done: Edit › Spelling › Auto Spell Check (`edit.autoSpellCheck`, off at first, saved with the view settings) draws a red wavy line under the unknown words of the visible type, leaves out type with effects, and follows edits, the custom dictionary and Ignore All. A right-click on an underlined word lists the words its dictionary suggests (each replaces it in one undo step, `text.editRange`), or No Suggestions, then Ignore All and Add to Dictionary, and a right-click on type has Spelling › Auto Spell Check, checked while it is on. Edit › Edit Custom Dictionary… lists the custom dictionary's words, with an Entry field and Add, Delete and Change, applied on Done (Cancel leaves the dictionary as it was). The Check Spelling dialog remains. Evidence: `crates/engine/src/tests/spelling.rs`, `crates/ui-egui/src/canvas/tests.rs` (`auto_spell_check_*`), `crates/ui-egui/src/tests/contextmenu.rs` (the right-click), `crates/ui-egui/src/dialogs/custom_dictionary.rs` (the dialog). | -| Smart Punctuation, Change Case, Find & Replace | done | | +| Smart Punctuation, Change Case, Find & Replace | done | Type › Smart Punctuation… opens a dialog with the ff, fi, ffi and ff, fl, ffl ligatures, Smart Quotes, Smart Spaces, En, Em Dashes, Ellipses and Expert Fractions, Replace In and Report Results, which lists the count of each replacement; ligatures and fractions are written only where the font has a glyph for them. Evidence: `tests::menucmds::smart_punctuation_ligatures_spaces_and_fractions_are_counted`, `smart_punctuation_skips_ligatures_and_fractions_the_font_lacks`, `smart_spaces_keeps_one_space_after_a_period`, `dialogs::smart_punctuation::tests::menu_item_opens_the_dialog_and_ok_reports_the_counts` | | Alt + numeric-keypad codes while typing (Windows: `Alt+0176` → °) | partial | #5108: on Windows the character Windows posts when Alt comes up after keypad digits is typed at the caret like any other, in the typing's undo step, and the keypad digits typed with Alt run no shortcut. With NumLock off the keypad keys (Insert, End, arrows, Clear, Home, Page Up/Down without the extended-key flag) count as digits too and don't move the caret (`windows_alt_codes` unit tests; neither NumLock on nor off has been tried on a Windows machine yet). `type.insert {code}` (Windows Alt+0 code, Windows-1252 for 128–159) and `{unicode}` (hex code point) insert a character by its code (`menucmds::insert_a_character_by_its_code`). macOS and Linux have no such system convention and egui reports a keypad digit as the top-row digit, so there it does nothing; a floating panel window doesn't receive the character | | Caret: the arrows and Delete step over whole clusters (Thai consonant with its marks, combining accents, emoji); Backspace removes one character | done | in text with right-to-left characters the arrows move in visual order and stop on both sides of a character drawn with no width, such as a zero width non-joiner | | Touch Type tool | done | moves, scales and rotates one character through its kerning, baseline shift, scales and rotation (`text.touchType`); a character with a preceding logical character on the same line can move along the line in either reading direction; the first logical character moves only up and down. Positive `dx` follows reading order. These direction rules are VectorCraft's choices. | @@ -69,6 +69,7 @@ against Illustrator's public documentation; **estimated** unless noted. | CJK: East Asian Type units (Q, Ha) | done | Preferences › Units › East Asian Type (`unitsAsianType`, Points by default) offers every unit and Q and Ha, a quarter of a millimetre each ([Scripting Guide](https://ai-scripting.docsforadobe.dev/scripting/measurementUnits/): 0.709 pt per Q; [InDesign's unit notation](https://helpx.adobe.com/in/indesign/desktop/layout-and-grid-tools/rulers-and-measure-tools/change-ruler-measurement-units.html): `q`, `h`). The public pages do not say which fields follow it, so no field uses it yet and that waits for a source. Evidence: `q_and_ha_are_a_quarter_millimetre`, `east_asian_type_unit_*` | | CJK: manual tate-chu-yoko | done | Character panel menu › Tate-chu-yoko (`text.setFormat` / `text.setRangeStyle {tateChuYoko}`), with Show East Asian Options: marked characters stand side by side across one em of a vertical column, squeezed to the em when wider; two or three half-width digits still do so without the mark; horizontal type keeps the mark and does not move them. Tate-chu-yoko Settings… (`ui.tateChuYokoSettings`, `{tcyUpDown, tcyLeftRight}` in points) moves a marked block up or down and right or left as one piece. Evidence: `tests_vertical::manual_tate_chu_yoko_sets_marked_characters_across_one_em`, `tests_vertical::tate_chu_yoko_settings_move_a_marked_block_up_down_left_and_right`, `typecmd::tate_chu_yoko_is_a_character_attribute_saved_only_when_on`, `typecmd::tate_chu_yoko_settings_are_character_attributes_saved_only_when_set`, `dialogs::tate_chu_yoko::tests` | | CJK: Standard Vertical Roman Alignment | done | Character panel menu › Standard Vertical Roman Alignment (`text.setFormat` / `text.setRangeStyle {standardVerticalRoman}`), with Show East Asian Options, off by default: in vertical type the marked half-width characters (Latin letters, digits and other characters that would lie on their side) stand upright one below the other, each in its upright cell; spaces keep their width and tate-chu-yoko blocks stay across the column; horizontal type keeps the mark and does not change. Character Style Options has its own checkbox for it. Evidence: `tests_vertical::standard_vertical_roman_alignment_stands_half_width_characters_upright`, `typecmd::standard_vertical_roman_is_a_character_attribute_saved_only_when_on` | +| CJK: East Asian glyph forms | done | Glyphs panel menu › Traditional Forms, Expert Forms, JIS 04, JIS 90, JIS 78 and JIS 83 Forms, Monospaced Full-Width, Half-Width, Third-Width and Quarter-Width Forms, and Revert To Default Forms, with Show East Asian Options ([Format East Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)): the selected characters are drawn with the font's OpenType feature for that form (`trad`, `expt`, `jp04`, `jp90`, `jp78`, `jp83`, `fwid`, `hwid`, `twid`, `qwid`; [feature list](https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist)), one form at a time (`text.setFormat` / `text.setRangeStyle {glyphForm}`); a form none of the faces that draw the selected text (fallback faces included) has a feature for is disabled, and Revert To Default Forms draws the default glyphs. Saved natively only when set, carried by character styles, drawn on the canvas and in PDF, and written to SVG as `font-feature-settings`. Character Style Options has no field for it. Evidence: `tests::typo::glyph_forms_draw_the_fonts_east_asian_forms`, `typecmd::area_tests::glyph_form_is_one_character_attribute_saved_only_when_set`, `panels::glyphs::tests::east_asian_glyph_forms_in_the_panel_menu_set_the_selected_characters_form` | | CJK: warichu | done | Character panel menu › Warichu and Warichu Settings… (`text.setFormat` / `text.setRangeStyle {warichu, warichuLines, warichuGap, warichuScale, warichuAlign}`, `ui.warichuSettings`), with Show East Asian Options ([Format East Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)): marked characters set at a percentage of their size and stacked on 1 to 6 lines inside their line, one above the other in horizontal type and side by side in vertical type, with a line gap and eight alignments; a block stays whole on one line. Saved natively, carried by character styles, drawn on the canvas and in every export (SVG, PDF and `.ai` write such type as outlines). Type on a path sets the characters at their own size. Evidence: `tests::warichu`, `dialogs::warichu::tests`, `typecmd::area_tests::warichu_is_a_character_attribute_set_saved_and_exported` | | CJK: composite fonts | partial | Type › Composite Fonts… (`type.compositeFonts.set`), with Show East Asian Options: a font made of a font per class of character (Kanji, Kana, Punctuation, Symbols, Roman, Numerals), each with its own style, size and baseline in percent of the type's size, Kana, Roman and Numerals with horizontal and vertical scale, and Kana with Scale at Center; New, Delete Font, Import… and Export… (`.vccomposite`, `type.compositeFonts.import` and `.export`) ([Creating composite fonts](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=347)). Composite fonts are listed first in the font menus, saved with the document, and their type is laid out per class; SVG and legacy `.ai` write it as outlines. Not yet: custom character sets, the Units menu, Show Sample. Evidence: `text::composite::tests::characters_fall_in_their_classes`, `tests::composite::composite_type_draws_each_class_in_its_font`, `compositefonts::tests`, `dialogs::composite_fonts::tests` | | CJK: ruby | partial | ruby (ふりがな) for live text (`type.ruby`): a reading over a byte range, above (right of the column in vertical type) or below, start/centre/end alignment, size, overhang or squeeze; saved natively, laid out with its line growing, drawn on the canvas, in SVG and PDF (as outlines where ruby is present), in EPS, EMF/WMF and legacy `.ai` (legacy `.ai` writes type with ruby as outlines), and kept by Create Outlines, Expand Appearance and flattening, each glyph where the layout puts it (`typecmd::ruby_tests::create_outlines_keeps_the_ruby_where_it_is_laid_out`) | #633 | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 8d32ecba59..354037795a 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-15 · **Change:** minor (G12: Swatches item menus tested and rendered; Linux full CI passed; Windows engine baseline failures noted; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; 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: 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: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag 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: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #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; 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; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-15 · **Change:** minor (G12: Swatches item menus tested and rendered; original feature Linux CI passed; integration blocked by upstream #7727; Windows engine baseline failures noted; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; 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: 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: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag 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: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #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; 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; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Vector Halftone preview update (2026-11-10): temporary dot selection marks are hidden, and the bounding box stays available (#6369). > @@ -51,8 +51,9 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| -| 2026-11-15 | minor | G12: Swatches item menus validated in all five views: 39 focused tests passed, regression fails without the menu hooks, rendered list/thumbnail layouts inspected, and fresh local deep CodeRabbit review found zero issues. Full workspace CI passed on Linux/WSL (all 13 gates); native Windows full CI has two unchanged engine-test failures. Scores and estimates unchanged. | +| 2026-11-15 | minor | G12: Swatches item menus validated in all five views: 39 focused tests passed, regression fails without the menu hooks, rendered list/thumbnail layouts inspected, and fresh local deep CodeRabbit review found zero issues. Full workspace CI passed on Linux/WSL for feature commit `6f4a651c0` (all 13 gates); validation after merging main stops at the upstream test-helper compile error tracked in #7727; native Windows full CI has two unchanged engine-test failures. Scores and estimates unchanged. | | 2026-11-14 | minor | Layers panel: right-clicking a layer/group/object row shows a context menu with Options…, Duplicate, Delete, Lock/Hide Others, Locate Object, and Collect for Export — matching standard desktop layer panel conventions. Scores unchanged. | +| 2026-11-13 | minor | Pencil cursors: the continuation cursor (a short rising line) shows over an open end of a selected path before any press, freehand too, and while a continuing stroke nears another selected path's open end it connects to; the straight-line cursor is a short level line; a continued path, a straight line too, shows the closing cursor and closes within Close Paths When Ends Are Within of its other end, and with Alt at the release. Scores and estimates unchanged. | | 2026-11-13 | minor | Graphic Styles: in a panel made taller the list fills the space above the footer instead of stopping at 220 pt (#2992; `the_list_fills_a_tall_panel_above_its_footer` in `crates/ui-egui/src/panels/graphic_styles.rs`). Scores and estimates unchanged. | | 2026-11-13 | minor | Library panels (swatch, Color Book, brush, symbol and graphic style libraries): in a panel made taller the list fills the space above the footer instead of scrolling inside 220 or 280 pt (#2992; `the_list_fills_a_tall_panel_above_its_footer` in `crates/ui-egui/src/panels/library_panel/tests.rs`). Scores and estimates unchanged. | | 2026-11-13 | minor | Swatches: in a panel made taller the swatch list fills the space above the footer instead of scrolling inside 150 or 200 pt (#1638). Scores unchanged. | @@ -179,7 +180,7 @@ tools, never checked side by side) isn't captured row by row. | Blend spine Anchor Point conversion and handle editing (#2544) | implemented | symmetric handles, independent drag/retraction, visible-handle policy and selection/stacking covered by tool and engine regressions; Windows native canvas checks and screenshots reviewed in PR #2643 | | Several blend spine points picked and dragged together (#5285) | done | with Direct Selection, Shift-click picks more points of a selected blend's spine or takes one away, as on a path; dragging any picked point moves them all, and the key objects on them, in one undo step (`object.blend.spine.moveAnchor {with}`); a marquee doesn't pick spine points yet | | Add/Delete/Anchor Point tools; Anchor Point tool drags segments to reshape | done | #2267: a click on a handle end retracts that handle and leaves the anchor a corner with the other one; Shift held at the press on an anchor moves it, handles and all (Shift kept down: at 45° steps) instead of pulling out handles | -| Pencil: Fidelity, Keep selected, Alt to Smooth, edit selected paths, close by proximity | done | Fidelity is in screen pixels, the same at any zoom, and goes down to 0.01 px in the dialog and the tool, which sends `path.freehand` the value in points at the current zoom (#5729; the Smooth tool keeps 0.05 pt); its slider runs across the Tool Options row on a logarithmic rail from 0.01 to 20 px, the field shows hundredths, and the slider's and the field's arrow keys step hundredths up to 0.1 px, tenths up to 1 px and whole pixels above (Shift ×10) (#3328); Alt key toggles to Smooth Tool (#2001); Shift held at the press draws a straight line at 45° steps from the Constrain Angle, and Alt held at the press (with Alt key toggles to Smooth Tool off) a straight line at any angle (#3799), with a straight-line cursor while Shift or Alt is held before the press, and a path-continuation cursor over an end of a selected open path, where the line continues the path; Edit Selected Paths continues a selected path from an end and, from a stroke that starts and ends on a selected path, redraws the section between (the shorter way round a closed path, #2850); with Keep selected (Pencil and Paintbrush, on by default) on, a stroke selects the path it draws or continues and replaces the earlier selection, and off a new stroke leaves nothing selected, the earlier selection included, while a continued or redrawn path is deselected and the rest of the selection stays; a filled Pencil path keeps a stroke of None (#1804, part of #1679); while a freehand stroke is drawn back to within Close Paths When Ends Are Within of its start, the Pencil and the Paintbrush show the closing cursor, and a release there closes the path; a Pencil stroke from an end of one selected open path to an end of another connects the two into one path | +| Pencil: Fidelity, Keep selected, Alt to Smooth, edit selected paths, close by proximity | done | Fidelity is in screen pixels, the same at any zoom, and goes down to 0.01 px in the dialog and the tool, which sends `path.freehand` the value in points at the current zoom (#5729; the Smooth tool keeps 0.05 pt); its slider runs across the Tool Options row on a logarithmic rail from 0.01 to 20 px, the field shows hundredths, and the slider's and the field's arrow keys step hundredths up to 0.1 px, tenths up to 1 px and whole pixels above (Shift ×10) (#3328); Alt key toggles to Smooth Tool (#2001); Shift held at the press draws a straight line at 45° steps from the Constrain Angle, and Alt held at the press (with Alt key toggles to Smooth Tool off) a straight line at any angle (#3799), with a straight-line cursor (a short level line) while Shift or Alt is held before the press, and a path-continuation cursor (a short rising line) over an end of a selected open path, where the stroke continues the path, freehand or straight, and while a continuing stroke ends near an open end of another selected path it connects to; Edit Selected Paths continues a selected path from an end and, from a stroke that starts and ends on a selected path, redraws the section between (the shorter way round a closed path, #2850); with Keep selected (Pencil and Paintbrush, on by default) on, a stroke selects the path it draws or continues and replaces the earlier selection, and off a new stroke leaves nothing selected, the earlier selection included, while a continued or redrawn path is deselected and the rest of the selection stays; a filled Pencil path keeps a stroke of None (#1804, part of #1679); while a freehand stroke is drawn back to within Close Paths When Ends Are Within of its start, or a stroke continuing a selected path (a straight line too) to within it of that path's other end, the Pencil and the Paintbrush show the closing cursor, and a release there closes the path; a Pencil stroke from an end of one selected open path to an end of another connects the two into one path | | Drop Shadow, Outer Glow and Inner Glow: Opacity, the offsets, Blur and Darkness have spinner arrows that step by one (a unit for distances), repeat when held and stop at the fields' ends (#5367, #5368) | done | dialogs::effect test drop_shadow_and_outer_glow_fields_have_spinner_arrows; other effect dialogs' number fields still have none | | Effect dialogs' colour fields: a swatch beside the hex follows typed values, and a double-click opens the Color Picker over the dialog, whose OK fills it and Cancel comes back unchanged (#5365) | done | dialogs::effect tests outer_glow_colour_swatch_opens_the_color_picker and drop_shadow_colour_swatch_opens_the_color_picker (Drop Shadow's Color, #5364); the picker previews nothing itself, the effect dialog previews the returned colour | | Join tool scrubbing, Average, Join | done | Join merges the direct-selected anchors lying on one another along a path, as after Average, into one (#1533); the Join tool trims two crossing open paths whose overhanging ends it scrubs over and joins them at the crossing, instead of drawing a segment between their ends (#5844) | @@ -252,7 +253,7 @@ tools, never checked side by side) isn't captured row by row. | A double-click on a ruler adds a guide at the pointer: a vertical one on the top ruler, a horizontal one on the left ruler (swapped in a view turned 90°, where the rulers read the other document axis; the nearer axis in between), exactly where the pointer is (no snapping), shown even with guides hidden, one undo step (`guide.add`); both clicks of the pair must be on that ruler, and the first adds nothing. The [public page on rulers](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/use-rulers.html) doesn't describe this gesture, so it follows the request in #5239 | done | #5239; an artboard guide with the Artboard tool, as a drag from a ruler makes one; `canvas/tests.rs` `double_clicking_a_ruler_adds_a_guide_at_that_position`, `a_canvas_click_then_a_ruler_click_adds_no_guide`, `a_ruler_double_click_follows_a_rotated_view` | | Escape cancels an existing ruler-guide press, move or copy | done | Selection and Direct/Group Selection; app-input regressions cover preselected guides, document/interaction-start selection, Undo/Redo and saved state, later on-canvas motion/release and temporary borrowing from idle Pen. All eight checks and the Direct Selection Escape control passed in current full CI. [Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area) | | Ruler origin: corner drag with preview, snapped as a drawn point is (Smart Guides, Snap to Point and the ruler guides, pixels, the grid), double-click reset to the active artboard, relative X/Y fields, native save/reopen | done | #1212; `document.setRulerOrigin`, `document.resetRulerOrigin`; geometry and command coordinates stay absolute | -| Ruler guides as Layers rows: shown, hidden, locked and deleted with their layer; rows dragged to another layer; each row's own eye and lock; a row dropped on the trash deletes its guide | done | `guide.setLayer`; guides from older files go on a layer; `layer.setProps` on a guide's id hides or locks it alone; Object › Lock/Hide › Selection, Unlock All and Show All reach guides; `guide.remove {indexes}` | +| Ruler guides as Layers rows: shown, hidden, locked and deleted with their layer; rows dragged to another layer; each row's own eye and lock; a row dropped on the trash deletes its guide; a plain click on another row lets go of the guide | done | `guide.setLayer`; guides from older files go on a layer; `layer.setProps` on a guide's id hides or locks it alone; Object › Lock/Hide › Selection, Unlock All and Show All reach guides; `guide.remove {indexes}`; #7340 | | Objects made into guides: drawn in the guide colour and style of Preferences; Lock Guides locks them too (no select, move or delete); a dragged selection snaps to ruler guides with Smart Guides on, by the nearest point of the path when pressed on its stroke or beside its edge, so the path lands exactly on the guide | done | #1534 (#1543, #1583); #3701 | | A selected ruler guide's X or Y in the Transform panel; typing a value moves it | not scored | #1659 (part of #1597); several guides move together; not in Properties or the Control bar. Not established by the documentation we could find: the help pages on guides, rulers and the Transform, Control and Properties panels (read again on 2026-10-14) don't describe it, and the one public statement is a user's [community answer](https://community.adobe.com/questions-652/adding-a-new-custom-guide-785586), which is not documentation. Kept as a convenience pending the owner's decision; no parity claim | | Alt swaps a ruler guide's orientation while dragging | missing | Alt-drag copies the selected guides ([Use rulers](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/use-rulers.html)); `guide.move` `{copy: true}` | @@ -385,7 +386,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po |---|---|---| | Effect > Warp Options: style previews, orientation choices and percent controls | done | #1760; focused input, mixed-style and history checks passed; original captures reviewed. No geometry or optional Properties changes. | | Command search: Up and Down move through the results, Enter runs the highlighted one | done | #1798 (#1757) | -| Learn panel: Window › Learn and Explore tutorials on the app bar open it; For you holds a Quick skill guide card, Skills lists VectorCraft's own skills with tutorial counts and empty progress rings, a tutorial shows its numbered steps, Back goes up a level; a tool's name in a step is a link that marks the tool where the toolbars show it (its button, its group's flyout, a torn-off strip, a toolbar made with New Toolbar or the All Tools drawer) without choosing it; View more opens the tutorial's practice sample as a new untitled document, Finish tutorial then marks it finished, and Next Up shows the next tutorial in the same skill (no video) | done | [the help page](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/learn-skills-quick-skill-guide.html); `learn.list`, `learn.skills`, `learn.show`, `learn.locateTool`, `learn.openSample`, `learn.finish`, `learn.next`; the mark's look and 3-second lifetime are VectorCraft's own rules; `panels::learn::tests`, `toolbar::tests` | +| Learn panel: Window › Learn and Explore tutorials on the app bar open it; For you holds a Quick skill guide card, Skills lists VectorCraft's own skills with progress rings that fill and counts of tutorials finished, a tutorial shows its numbered steps with a check box each that marks the step done once its sample is open, a finished tutorial has a check mark, Back goes up a level; a tool's name in a step is a link that marks the tool where the toolbars show it (its button, its group's flyout, a torn-off strip, a toolbar made with New Toolbar or the All Tools drawer) without choosing it; View more opens the tutorial's practice sample as a new untitled document, Finish tutorial then marks it finished with all its steps, and Next Up shows the next tutorial in the same skill; Reset progress clears the progress (no video) | done | [the help page](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/learn-skills-quick-skill-guide.html); `learn.list`, `learn.tab`, `learn.skills`, `learn.skill`, `learn.show`, `learn.back`, `learn.locateTool`, `learn.openSample`, `learn.markStep`, `learn.finish`, `learn.next`, `learn.resetProgress`; the mark's look and 3-second lifetime, marking steps by hand, keeping the progress in the preferences and Reset progress are VectorCraft's own rules; `panels::learn::tests`, `toolbar::tests` | | Pathfinder panel: a group selected alone counts its nested shapes, so an expanded stroked object keeps the Shape Modes enabled | done | #1642 (#1635) | | Selected Grid Repeat shows row, column and corner handles and spacing sliders; bounding-box handles take priority where they meet | done | #2691, `tools/src/repeat_grid.rs`; [public behavior reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html); drags preview and commit `object.repeat.options` as one undo step, Escape cancels; Radial Repeat has no handles yet | | Grid Repeat Options (Object › Repeat › Options…) has a Preview checkbox: the repeat on the canvas follows the fields while the dialog is open, Cancel puts the original back without a history step, OK keeps the previewed values as one undo step | done | #2651; [public behavior reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html) lists the Preview option for the grid options only, so Radial and Mirror Repeat Options have none; `dialogs/command.rs` tests | @@ -419,7 +420,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Actions panel: Delete Selection (bottom bar) deletes the selected set with its actions and keeps the other sets ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html)) | partial | `ui.actionSet.delete`; `panels/actions.rs` tests. VectorCraft's own rules, which the overview does not cover: deleting a set asks first (a selected action is still deleted at once), Shift-click on a set's name selects a range of sets, ≡ › Delete does the same as the button, and Default Actions and the last set can be deleted. Undo does not restore a deleted set, and recorded commands cannot be selected or deleted | | Actions panel: ≡ › Duplicate copies the selected action or set ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html)) | partial | `ui.actionSet.duplicate`; `panels/actions.rs` tests. VectorCraft's own rules, which the overview does not cover: the copy goes right after the original, is named after it with " copy" added and is selected, and a copied set holds copies of all its actions. Undo does not remove the copy, and recorded commands cannot be duplicated | | Properties panel per context (every selection type's Quick Actions) | partial | one clip group: Edit Clipping Path and Edit Contents, at the top of the panel rather than in Quick Actions (G1); the overview's additional controls ([Properties panel overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/properties-panel-overview.html)): Blend Options (one blend selected, with any tool, #4817), Repeat Options (one radial, grid or mirror repeat selected: Object › Repeat › Options, #5181; the overview does not list it) and Merge Live Paint (a Live Paint group with more) in Quick Actions, the Width Profile list (Width tool or a variable-width stroke) and an applied effect's Delete icon in Appearance, Corner and Corner Radius for corners selected with Direct Selection; Variable Font was already there; Edit Artboards: a Transform section (reference point, X, Y, W, H, preset, orientation) above the Artboards section (#5219) | -| Select › Start Global Edit / Stop Global Edit; Properties › Quick Actions with the Global Edit Options popover (Match: Appearance, Size; On Artboards: All Artboards or a range, Include Objects On Canvas; Result(s)); Escape stops it; the matched objects are highlighted in their layer colour while it runs; a Shift-click on a highlighted match leaves it out | partial | #3521, `select.globalEdit` / `select.globalEditOptions` / `select.globalEditExclude`, `crates/engine/src/tests/globaledit.rs`; paths, compound paths, symbol instances and groups of them (similar groups, #4939: edits inside one group reach the same object in the others; [public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-groups-with-similar-objects.html)); a group holding type or an image is not taken, as Global Edit does not take images or text; Shift-click to leave a match out ([public source](https://helpx.adobe.com/ph_fil/illustrator/how-to/global-editing-sensei.html)); the Control bar's Global Edit Options dropdown opens the same options; the matches are highlighted before the start (`selecting_one_object_highlights_the_similar_objects_before_global_edit_starts`); rotated copies remain ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-similar-objects.html)) | +| Select › Start Global Edit / Stop Global Edit; Properties › Quick Actions with the Global Edit Options popover (Match: Appearance, Size; On Artboards: All Artboards or a range, Include Objects On Canvas; Result(s)); Escape stops it; the matched objects are highlighted in their layer colour while it runs; a Shift-click on a highlighted match leaves it out | partial | #3521, `select.globalEdit` / `select.globalEditOptions` / `select.globalEditExclude`, `crates/engine/src/tests/globaledit.rs`; paths, compound paths, symbol instances and groups of them (similar groups, #4939: edits inside one group reach the same object in the others; [public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-groups-with-similar-objects.html)); a group holding type or an image is not taken, as Global Edit does not take images or text; Shift-click to leave a match out ([public source](https://helpx.adobe.com/ph_fil/illustrator/how-to/global-editing-sensei.html)); the Control bar's Global Edit Options dropdown opens the same options; the matches are highlighted before the start (`selecting_one_object_highlights_the_similar_objects_before_global_edit_starts`); rotated copies are matched and take an edit turned by their angle ([public source](https://helpx.adobe.com/vn_vi/illustrator/how-to/modern-logo-design.html); `start_global_edit_takes_rotated_copies_and_an_edit_reaches_each_turned_by_its_angle`); reflected copies are not matched (VectorCraft's own rule) | | Contextual task bar | done | | | Control bar with Transform and Stroke popovers | done | | | Stroke panel: custom arrowheads after the built-in ones in both arrowhead menus, from the arrowheads file that the panel menu's Edit Arrowheads… opens; saving the file reloads the menus, and a stroke keeps a copy of its custom head's art | done | [Apply stroke on an object](https://helpx.adobe.com/illustrator/using/stroke-object.html) (Customize arrowheads); the file's layout (one symbol per head, pointing right, tip at the registration point, height drawn as wide as the built-in heads) is VectorCraft's own; `stroke.arrowheads.edit`, `stroke.arrowheads.list`, `stroke.arrowheads.reload`, `stroke.set` `{custom: name}`; engine `tests::arrowheads`, `stroke::tests_arrows::custom_heads_draw_their_own_art_at_the_tip` | @@ -439,7 +440,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Pathfinder panel: compound shapes (Make, Release and Expand Compound Shape in the panel menu, Alt-click a Shape Mode, a Shape Mode for selected members, the Expand button) | partial | #4522; `object.compoundShape.make`/`setMode`/`release`/`expand`; members stay editable, the area draws, exports and saves; the button of the members' shared mode is lit; blends, envelopes and warped objects are members as they draw; [spec](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/create-compound-shapes-with-pathfinder.html); missing: question marks for mixed modes, hit-testing by the area | | Canvas context menu | done | Right-clicking type opens the canvas menu, with Bullets and Numbering and Spelling. Artboard rows, library groups and items, the rulers and floating toolbar grips have menus too. Gaps: guide and blend spine rows have no menu, and other panels have none | | Layers panel row context menu | done | Right-clicking a layer/group/object row shows a context menu with Options…, Duplicate, Delete, Lock/Hide Others, Locate Object, and Collect for Export — matching standard desktop layer panel conventions. | -| Swatches item context menu (G12) | done | List and thumbnail items offer Swatch Options…, Duplicate Swatch and Delete Swatch for the clicked item. Right-click selects without applying paint; reserved/missing items disable actions. All 39 Swatches tests pass, including all five views and Undo; the regression fails with the menu hooks removed. Rendered headless menus inspected. Full workspace CI passed on Linux/WSL (all 13 gates); native Windows full CI has two unchanged engine-test failures. | +| Swatches item context menu (G12) | done | List and thumbnail items offer Swatch Options…, Duplicate Swatch and Delete Swatch for the clicked item. Right-click selects without applying paint; reserved/missing items disable actions. All 39 Swatches tests pass, including all five views and Undo; the regression fails with the menu hooks removed. Rendered headless menus inspected. Full workspace CI passed on Linux/WSL for feature commit `6f4a651c0` (all 13 gates); validation after merging main stops at the upstream test-helper compile error tracked in #7727; native Windows full CI has two unchanged engine-test failures. | | SVG Interactivity panel: JavaScript for each object's events and the document's linked JavaScript files, written to SVG and read back as text | done | `svgInteractivity.*`, `ui.javascriptFilesDialog` | | Retype, Comments, Version History panels | missing | the last two are cloud features (out of scope) | | Blend panel (30.7) | partial | Window › Blend provides Type (Ease In, Ease Out, Ease In Out, Ease Out In), Ramp 0–100% and independent color Shift, alongside the existing blend controls. Easing is disabled without a spine. Original polynomial distributions approximate the publicly documented behavior. On-canvas Appearance and Easing widgets set Shift and Ramp; a blend without a spine shows the Appearance widget alone. [Public source](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blend-panel-overview.html) | @@ -540,7 +541,7 @@ before release (#6373). [Paint faces and edges](https://helpx.adobe.com/illustra | Date | Change | Summary | |---|---|---| -| 2026-11-15 | minor | G12: Swatches item menus validated in all five views: 39 focused tests passed, regression fails without the menu hooks, rendered list/thumbnail layouts inspected, and fresh local deep CodeRabbit review found zero issues. Full workspace CI passed on Linux/WSL (all 13 gates); native Windows full CI has two unchanged engine-test failures. Scores and estimates unchanged. | +| 2026-11-15 | minor | G12: Swatches item menus validated in all five views: 39 focused tests passed, regression fails without the menu hooks, rendered list/thumbnail layouts inspected, and fresh local deep CodeRabbit review found zero issues. Full workspace CI passed on Linux/WSL for feature commit `6f4a651c0` (all 13 gates); validation after merging main stops at the upstream test-helper compile error tracked in #7727; native Windows full CI has two unchanged engine-test failures. Scores and estimates unchanged. | | 2026-11-14 | minor | G12: Swatches item context menus implemented in list and thumbnail views, with clicked-item actions and reserved/missing-swatch guards. Harness tests added; execution and visual verification pending. Scores and estimates unchanged. | | 2026-11-12 | minor | Numeric fields: a focus click released more than 1 pt from its press keeps the caret; a tap within 1 pt still selects the whole value (#6659, follow-up to #1326). Scores and estimates unchanged. | | 2026-11-12 | minor | Remove Background for a selected image in the Contextual Task Bar, Properties › Quick Actions and the Control bar, which runs at once with its defaults. Scores and estimates unchanged. |