diff --git a/Cargo.lock b/Cargo.lock index f8dffe6f78..96158329f3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -508,6 +508,12 @@ dependencies = [ "serde", ] +[[package]] +name = "bit_field" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb2907cc03d08cdb1c6724ad0670ce67c4a71e1c45a6d7635224011714cfc4b1" + [[package]] name = "bitflags" version = "1.3.2" @@ -981,7 +987,7 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2#6d620e971e820b517b11a99cad040ebac670e1e2" +source = "git+https://github.com/storytold/craft-libs?rev=8bd1412eaa7c0b58f3f9c401495d35fe12d6d85e#8bd1412eaa7c0b58f3f9c401495d35fe12d6d85e" [[package]] name = "craft-docpath" @@ -991,7 +997,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7 [[package]] name = "craft-dxf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2#6d620e971e820b517b11a99cad040ebac670e1e2" +source = "git+https://github.com/storytold/craft-libs?rev=8bd1412eaa7c0b58f3f9c401495d35fe12d6d85e#8bd1412eaa7c0b58f3f9c401495d35fe12d6d85e" dependencies = [ "craft-codepage", "encoding_rs", @@ -1033,6 +1039,36 @@ dependencies = [ "writeable", ] +[[package]] +name = "craft-image-codecs" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991" +dependencies = [ + "craft-jpeg", + "exr", + "flate2", + "half", + "image", + "image-webp", + "jpeg-encoder", + "png 0.18.1", + "rayon", + "serde_json", + "thiserror 2.0.21", + "tiff", + "zune-core 0.5.3", + "zune-jpeg 0.5.15", + "zune-jpegxl", +] + +[[package]] +name = "craft-jpeg" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991" +dependencies = [ + "thiserror 2.0.21", +] + [[package]] name = "craft-keymap" version = "0.1.0" @@ -1090,12 +1126,23 @@ dependencies = [ "unicode-normalization", ] +[[package]] +name = "craft-psd" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991" +dependencies = [ + "encoding_rs", + "flate2", + "rayon", + "thiserror 2.0.21", +] + [[package]] name = "craft-svg" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2#6d620e971e820b517b11a99cad040ebac670e1e2" dependencies = [ - "craft-xml", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2)", "flate2", "kurbo 0.13.1", "roxmltree 0.21.2", @@ -1105,6 +1152,15 @@ dependencies = [ "vectorcraft-pathops 0.18.0", ] +[[package]] +name = "craft-tiff" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991" +dependencies = [ + "serde", + "thiserror 2.0.21", +] + [[package]] name = "craft-ui" version = "0.1.0" @@ -1203,6 +1259,15 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-xml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991" +dependencies = [ + "quick-xml 0.41.0", + "thiserror 2.0.21", +] + [[package]] name = "crc32fast" version = "1.5.3" @@ -1715,6 +1780,22 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "exr" +version = "1.74.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb29d0be702adf92c645d9b2f93472906ba83d400e59f98adb3770ce5c18c2f6" +dependencies = [ + "bit_field", + "half", + "lebe", + "miniz_oxide 0.8.9", + "multiversion", + "rayon-core", + "smallvec", + "zune-inflate", +] + [[package]] name = "fastrand" version = "2.5.0" @@ -2747,6 +2828,7 @@ dependencies = [ "moxcms", "num-traits", "png 0.18.1", + "qoi", "tiff", "zune-core 0.5.3", "zune-jpeg 0.5.15", @@ -3200,6 +3282,12 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" +[[package]] +name = "lebe" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a79a3332a6609480d7d0c9eab957bca6b455b91bb84e66d19f5ff66294b85b8" + [[package]] name = "libc" version = "0.2.191" @@ -3399,6 +3487,28 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "multiversion" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb8a68be21d0755f83bfe47e79b896cc732687cf1903f0e50585e8d6ecc53076" +dependencies = [ + "multiversion-macros", + "target-features", +] + +[[package]] +name = "multiversion-macros" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a05e0c3c3e4edaa21d87c645852ed0b0c3663752bcc6ec43353bd6189dce35e1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "target-features", +] + [[package]] name = "multiversion_no_op" version = "1.0.0" @@ -4349,21 +4459,21 @@ dependencies = [ "unarray", ] -[[package]] -name = "psd" -version = "0.3.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a25f9b8cfffd65d911baf31a033239f7a0facb755faa2481575b70db5dc9195" -dependencies = [ - "thiserror 1.0.69", -] - [[package]] name = "pxfm" version = "0.1.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" +[[package]] +name = "qoi" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f6d64c71eb498fe9eae14ce4ec935c555749aef511cca85b5568910d6e48001" +dependencies = [ + "bytemuck", +] + [[package]] name = "quick-error" version = "1.2.3" @@ -5734,6 +5844,12 @@ dependencies = [ "xattr", ] +[[package]] +name = "target-features" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1bbb9f3c5c463a01705937a24fdabc5047929ac764b2d5b9cf681c1f5041ed5" + [[package]] name = "tempfile" version = "3.27.0" @@ -6546,6 +6662,7 @@ dependencies = [ "chrono", "craft-docpath", "craft-proof", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e2dc681a3)", "crc32fast", "flate2", "hayro-jpeg2000", @@ -6558,7 +6675,6 @@ dependencies = [ "log", "proptest", "rayon", - "roxmltree 0.21.2", "rustix 1.1.6", "ruzstd", "same-file", @@ -6734,6 +6850,7 @@ dependencies = [ "aes", "chrono", "craft-pdf", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e2dc681a3)", "flate2", "getrandom 0.4.3", "image", @@ -6744,7 +6861,6 @@ dependencies = [ "md-5", "objc2-core-foundation", "objc2-core-graphics", - "roxmltree 0.21.2", "serde", "serde_json", "sha2", @@ -6785,16 +6901,16 @@ dependencies = [ name = "vectorcraft-render" version = "0.24.1" dependencies = [ + "craft-image-codecs", + "craft-psd", + "craft-tiff", "flate2", "gif 0.14.2", "image", "jpeg-encoder", "log", - "png 0.18.1", "proptest", - "psd", "serde_json", - "tiff", "unicode-general-category", "vectorcraft-brush", "vectorcraft-color", @@ -6917,6 +7033,7 @@ dependencies = [ name = "vectorcraft-trace" version = "0.24.1" dependencies = [ + "craft-image-codecs", "image", "kurbo 0.13.1", "serde", @@ -6930,6 +7047,7 @@ name = "vectorcraft-ui-egui" version = "0.24.1" dependencies = [ "bytemuck", + "chrono", "craft-keymap", "craft-ui", "craft-update", @@ -8370,6 +8488,15 @@ version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" +[[package]] +name = "zune-inflate" +version = "0.2.54" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73ab332fe2f6680068f3582b16a24f90ad7096d5d39b974d1c0aff0125116f02" +dependencies = [ + "simd-adler32", +] + [[package]] name = "zune-jpeg" version = "0.4.21" diff --git a/Cargo.toml b/Cargo.toml index 610e2b462c..76104004f2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -30,9 +30,14 @@ craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). 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" } +craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "8bd1412eaa7c0b58f3f9c401495d35fe12d6d85e" } # WMF, EMF and EMF+ reader (craft-libs#778). craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" } +craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" } 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/README.md b/README.md index 7e49943a31..b04c91e066 100644 --- a/README.md +++ b/README.md @@ -252,11 +252,12 @@ speaks English, German, Japanese, Korean, Vietnamese, Traditional and Simplified The scores are self-assessed from our code against public documentation; [target-app-parity.md](docs/target-app-parity.md#how-this-was-measured-2026-10-10) explains how far to trust them. +All 57 approximated Photoshop-style raster filters are available. The Effect Gallery includes filter thumbnails and an in-dialog preview. + **What's missing:** - reliable exchange of .ai files (layer structure in real files; the editing copy a save writes keeps live effects only on paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports (see [docs/file-format-parity.md](docs/file-format-parity.md)), leaves out other objects' effects other than geometry effects, and writes live objects as their art); - an interaction-fidelity pass covering every tool's modifiers and small behaviours; - 3D and Materials beyond the initial live Revolve (Extrude & Bevel, Inflate, Rotate, materials); -- filter thumbnails and a preview area inside the Effect Gallery (the gallery itself and all 57 Photoshop-style raster filters, approximated, are in); - CJK composition for vertical type (vertical type itself has initial support, with a Japanese interface); - scripting, and the rest of Variables (image and graph kinds, dataset import); - generative AI features. diff --git a/ROADMAP.md b/ROADMAP.md index ec3f6e9c76..0ad26e8789 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -102,14 +102,14 @@ Weights, evidence and the missing items per area: [target-app-parity.md](docs/ta | Arabic | `ar` | none (no right-to-left interface) | 0% | | French | `fr` | full | 100% | | Portuguese (Brazil) | `pt-br` | full | 100% | -| Indonesian | `id` | none | 0% | +| Indonesian | `id` | 6,947 catalog rows; status and error messages partial | most dialogs and tooltips | | Japanese | `ja` | full | 100% | | German | `de` | full | 98% | | Korean | `ko` | full | 100% | | Bosnian | `bs` | full (AI-assisted, native review pending) | 100% | | Vietnamese | `vi` | full | 100% | -Also shipped: Traditional Chinese (partial, 80%), Bulgarian, Finnish, Greek, Hungarian, Italian, Polish, Russian, Swedish, Ukrainian and Georgian (full), Catalan (full; AI-drafted, native review welcome), Czech (catalog complete; render-site gaps reduced; native review pending). +Also shipped: Traditional Chinese (partial, 80%), Bulgarian, Finnish, Greek, Hungarian, Italian, Polish, Russian, Swedish, Ukrainian, Georgian, Dutch, Danish and Turkish (full), Catalan (full; AI-drafted, native review welcome), Czech (catalog complete; render-site gaps reduced; native review pending). The Georgian catalog has had a native speaker's review; no other catalog has. Details: [localization-parity.md](docs/localization-parity.md). ## Upcoming @@ -133,6 +133,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 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-14: Packaging Tools add-on (Object › Plug-ins › Packaging Tools): fold line roles for dielines (Cut, Crease, Partial Cut, Perforation), each carried by the swatch on a path's top stroke through a per-document role table that native files keep; PDF prints a role line on its swatch's separation when that swatch is a spot color, as the default role swatches are, and SVG, DXF and HP-GL keep the stroke's color. Make Cut Line, Make Crease Line, Make Partial Cut Line and Make Perforation Line give the selected paths a role, overprinting by default, and make a missing role swatch; the Fold Lines panel counts each role in the selection or the document, and its Role Swatches… picks another swatch for a role (`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch`). A VectorCraft addition: headline numbers 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. - 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`). - 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. diff --git a/apps/vectorcraft/src/clipboard.rs b/apps/vectorcraft/src/clipboard.rs index ec6256a114..0624b85d95 100644 --- a/apps/vectorcraft/src/clipboard.rs +++ b/apps/vectorcraft/src/clipboard.rs @@ -155,6 +155,12 @@ fn copied_file(paths: Vec, mimes: &[&'static str]) -> Option { copied_file_within(paths, mimes, MAX_BYTES) } +/// Whether a paste of one of `mimes` can take a copied file: one of them is not text. +#[cfg_attr(windows, allow(dead_code))] +fn takes_files(mimes: &[&'static str]) -> bool { + mimes.iter().any(|&m| m != TEXT) +} + /// [`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| { @@ -727,7 +733,7 @@ mod portable { use std::sync::atomic::{AtomicBool, Ordering}; use std::time::{Duration, Instant}; - use super::{BITMAP, ClipboardRead, Flavour, PNG, SystemClipboard, TEXT, copied_file, decode_png, png_flavour, text_of}; + use super::{BITMAP, ClipboardRead, Flavour, PNG, SystemClipboard, TEXT, copied_file, decode_png, png_flavour, takes_files, text_of}; /// What our last write put on the clipboard. #[derive(Clone)] @@ -741,7 +747,7 @@ mod portable { } /// A read of arboard's clipboard. - #[derive(Clone, Copy, PartialEq, Eq)] + #[derive(Clone, Copy, PartialEq, Eq, Debug)] enum Request { Text, Image, @@ -813,6 +819,19 @@ mod portable { } } + /// Whether a paste of one of `mimes` can take what `cb` holds: text that is not empty when one + /// of `mimes` is text (`text` reads it), else files copied in a file manager when one of `mimes` + /// is not text (`files` reads the list). The list is read only when the text doesn't do, and no + /// copied file is opened: Paste checks the files themselves. + fn arboard_has( + mimes: &[&'static str], + cb: &mut B, + text: impl FnOnce(&mut B) -> Result, + files: impl FnOnce(&mut B) -> Vec, + ) -> bool { + (mimes.contains(&TEXT) && text(cb).is_ok_and(|t| !t.is_empty())) || (takes_files(mimes) && !files(cb).is_empty()) + } + /// `request` read on `reads`' worker, waiting `wait` at most. #[cfg(test)] fn read_within(reads: &mut super::loads::Loads, request: Request, wait: Duration) -> Answer { @@ -1441,10 +1460,11 @@ mod portable { read } - /// Text, on macOS vector art or a bitmap (by the pasteboard's types), and on the Wayland - /// core protocol copied files, SVG, text or PNG (by the types offered, nothing read). + /// Text or files copied in a file manager (their list read, no file opened: + /// [`arboard_has`]), on macOS vector art or a bitmap (by the pasteboard's types), and on the + /// Wayland 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. + /// the paste keys take it, the menu item waits for text or copied files. fn has(&mut self, mimes: &[&'static str]) -> bool { #[cfg(target_os = "macos")] if super::mac::has(mimes) { @@ -1455,7 +1475,7 @@ mod portable { if let Backend::Wayland(wl) = cb { return wl.has(mimes); } - mimes.contains(&TEXT) && cb.get_text().is_ok_and(|t| !t.is_empty()) + arboard_has(mimes, cb, Backend::get_text, Backend::file_list) } } @@ -1619,6 +1639,40 @@ mod portable { assert!(Answer::Text(Ok("art.svg".into())).files().is_empty()); } + #[test] + fn paste_is_available_for_files_copied_in_a_file_manager() { + use vectorcraft_engine::cmd::clipboard::{PASTE_ORDER, SVG}; + /// What the clipboard holds, and which reads [`arboard_has`] made. + struct Held { + text: Option, + files: Vec, + reads: Vec, + } + fn has(mimes: &[&'static str], text: Option<&str>, files: &[&str]) -> (bool, Vec) { + let mut held = Held { text: text.map(String::from), files: files.iter().map(PathBuf::from).collect(), reads: vec![] }; + let text = |h: &mut Held| { + h.reads.push(Request::Text); + h.text.clone().ok_or_else(|| "no text".to_string()) + }; + let files = |h: &mut Held| { + h.reads.push(Request::Files); + h.files.clone() + }; + let has = arboard_has(mimes, &mut held, text, files); + (has, held.reads) + } + // Files a file manager copied, with no text: the Paste menu item is available. + assert_eq!(has(&PASTE_ORDER, None, &["/tmp/art.svg"]), (true, vec![Request::Text, Request::Files])); + assert_eq!(has(&PASTE_ORDER, Some(""), &["/tmp/art.svg"]), (true, vec![Request::Text, Request::Files])); + assert_eq!(has(&[SVG], None, &["/tmp/art.svg"]), (true, vec![Request::Files])); + // Text does, and the list is not read. + assert_eq!(has(&PASTE_ORDER, Some("hello"), &[]), (true, vec![Request::Text])); + // An empty list and no text: nothing to paste. + assert_eq!(has(&PASTE_ORDER, None, &[]), (false, vec![Request::Text, Request::Files])); + // A paste of text alone can't take copied files, and their list is not read. + assert_eq!(has(&[TEXT], None, &["/tmp/art.svg"]), (false, vec![Request::Text])); + } + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] #[test] fn arboards_reads_run_on_its_reader_and_wait_by_kind() { @@ -1925,7 +1979,7 @@ 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, MAX_BYTES, PNG, PathBuf, SVG, TEXT, copied_file, gnome_copied_paths, uri_list_paths}; + use super::{BITMAP, Flavour, MAX_BYTES, PNG, PathBuf, SVG, TEXT, copied_file, gnome_copied_paths, takes_files, 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`. @@ -2016,11 +2070,6 @@ 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) diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index c55785cfdf..69f807f615 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -1,7 +1,8 @@ //! VectorCraft desktop app. //! //! Usage: `vectorcraft [--control [--automation-read-root ]... [--automation-write-root ]...] -//! [--in-window-menus] [--new-instance] [--safe-mode] [--] [files…]`, `vectorcraft --version`, `vectorcraft --help` (or `-h`) +//! [--in-window-menus] [--new-instance] [--safe-mode] [--present-mode ] [--frame-latency ] [--] [files…]`, +//! `vectorcraft --version`, `vectorcraft --help` (or `-h`) //! //! Any other argument starting with '-' (not `-` alone) is an error; after `--`, every argument is //! a file. @@ -19,6 +20,9 @@ //! `--automation-write-root` (or `VECTORCRAFT_AUTOMATION_READ_ROOT` / `_WRITE_ROOT`) confine the //! files its requests read and write (`vectorcraft_engine::file_access`); the person at the //! keyboard isn't confined. +//! +//! `--present-mode` and `--frame-latency` (or `VECTORCRAFT_PRESENT_MODE` / `_FRAME_LATENCY`) change +//! how the window's frames reach the display (`presentation`). #![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")] mod automation_args; @@ -59,6 +63,7 @@ mod portal_request; #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd", test))] mod portal_save; mod prefs_dir; +mod presentation; mod printing; #[cfg(not(any(target_os = "macos", windows)))] mod quit_windows; @@ -158,6 +163,14 @@ Options: --safe-mode Start without plug-ins: none loads or runs until VectorCraft starts normally (Help › Safe Mode); the files open in a new window, as with --new-instance + --present-mode How frames reach the display: fifo (vsync), + autovsync (the default; relaxed vsync where the + driver offers it) or novsync + (or VECTORCRAFT_PRESENT_MODE) + --frame-latency Frames the display may queue, 1 to 3 (the default + is 1) (or VECTORCRAFT_FRAME_LATENCY); with either + one set, the files open in a new window, as with + --new-instance --version Print the version and exit -h, --help Print this help and exit -- Treat every argument after it as a file @@ -177,13 +190,16 @@ struct CommandLine { safe_mode: bool, } -/// Reads the arguments after the program name. The automation roots and the control port go into -/// `roots_args` and `control`. `Err` is the exit code when the process ends here: `--version` and -/// `--help` print and succeed; a bad automation option or an unknown option prints an error and fails. +/// Reads the arguments after the program name. The automation roots, the control port and the +/// presentation overrides (with `VECTORCRAFT_PRESENT_MODE` and `VECTORCRAFT_FRAME_LATENCY` filling +/// what the flags leave unset) go into `roots_args`, `control` and `presentation`. `Err` is the exit code +/// when the process ends here: `--version` and `--help` print and succeed; a bad automation or +/// presentation option or an unknown option prints an error and fails. fn read_command_line( mut args: impl Iterator, control: &mut automation_args::ControlArg, roots_args: &mut automation_args::AutomationArgs, + presentation: &mut presentation::Overrides, ) -> Result { let mut files = Vec::new(); let mut in_window_menus = std::env::var_os("VECTORCRAFT_IN_WINDOW_MENUS").is_some_and(|v| !v.is_empty() && v != "0"); @@ -196,7 +212,11 @@ fn read_command_line( files.extend(args.by_ref()); break; } - match roots_args.consume(&a, &mut args).and_then(|root| if root { Ok(true) } else { control.consume(&a, &mut args) }) { + match roots_args + .consume(&a, &mut args) + .and_then(|root| if root { Ok(true) } else { control.consume(&a, &mut args) }) + .and_then(|taken| if taken { Ok(true) } else { presentation.consume(&a, &mut args) }) + { Ok(true) => continue, Ok(false) => {} Err(e) => { @@ -235,6 +255,14 @@ fn read_command_line( eprintln!("vectorcraft: unknown option {a}; see vectorcraft --help, or put -- before a file whose name starts with '-'"); return Err(std::process::ExitCode::FAILURE); } + // After the arguments: the flags, `--version` and `--help` win over a bad environment value. + match presentation.with_env(std::env::var_os("VECTORCRAFT_PRESENT_MODE"), std::env::var_os("VECTORCRAFT_FRAME_LATENCY")) { + Ok(overrides) => *presentation = overrides, + Err(e) => { + eprintln!("vectorcraft: {e}"); + return Err(std::process::ExitCode::FAILURE); + } + } Ok(CommandLine { files, in_window_menus, new_instance, safe_mode }) } @@ -253,8 +281,9 @@ fn main() -> std::process::ExitCode { let root_env = |name: &str| std::env::var_os(name).filter(|v| !v.is_empty()).map(std::path::PathBuf::from); let mut roots_args = automation_args::AutomationArgs::new(root_env("VECTORCRAFT_AUTOMATION_READ_ROOT"), root_env("VECTORCRAFT_AUTOMATION_WRITE_ROOT")); + let mut presentation = presentation::Overrides::default(); let CommandLine { files, in_window_menus, new_instance, safe_mode: safe_mode_flag } = - match read_command_line(std::env::args().skip(1), &mut control, &mut roots_args) { + match read_command_line(std::env::args().skip(1), &mut control, &mut roots_args, &mut presentation) { Ok(command_line) => command_line, Err(code) => return code, }; @@ -275,7 +304,8 @@ fn main() -> std::process::ExitCode { // Files opened from the file manager while VectorCraft runs open in its window (#4892). Before // the log file is attached: a launch that hands its files over leaves the running app's log be. #[cfg(not(target_os = "macos"))] - match single_instance::start(control_port.is_some(), new_instance, safe_mode_flag, &files) { + // A launch that sets the presentation runs as its own app: a running app keeps its own surface. + match single_instance::start(control_port.is_some(), new_instance || presentation.is_set(), safe_mode_flag, &files) { single_instance::Start::Forwarded => return std::process::ExitCode::SUCCESS, single_instance::Start::Running(primary) => single_instance::hold(primary), } @@ -427,7 +457,10 @@ fn main() -> std::process::ExitCode { let mut options = options; // One frame queued, not two: the canvas is rasterized on the CPU and the GPU only // composites it, so the window answers the pointer a frame sooner (#444). - options.wgpu_options.surface = eframe::egui_wgpu::SurfaceConfig::LOW_LATENCY; + // `--present-mode` and `--frame-latency` change it for a launch (`presentation`). + options.wgpu_options.surface = presentation.apply(eframe::egui_wgpu::SurfaceConfig::LOW_LATENCY); + // What the app asks for: the driver picks novsync's mode and may clamp the latency. + log::info!("requested window surface: {}", presentation::describe(&options.wgpu_options.surface, &presentation)); // Only adapters that can show the window, in the order `gpu` gives (#306, #502). if let eframe::egui_wgpu::WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup { create.native_adapter_selector = Some(gpu::selector(power, displays, compositor, left_out.adapters.clone(), startup.clone())); @@ -458,6 +491,10 @@ fn main() -> std::process::ExitCode { } options }; + #[cfg(not(feature = "wgpu"))] + if presentation != presentation::Overrides::default() { + log::warn!("--present-mode and --frame-latency set the wgpu renderer's window surface: ignored without it"); + } #[cfg(feature = "wgpu")] gpu::watch_panics(); #[cfg(feature = "wgpu")] diff --git a/apps/vectorcraft/src/presentation.rs b/apps/vectorcraft/src/presentation.rs new file mode 100644 index 0000000000..3910984c93 --- /dev/null +++ b/apps/vectorcraft/src/presentation.rs @@ -0,0 +1,242 @@ +//! `--present-mode ` (or `VECTORCRAFT_PRESENT_MODE`) and `--frame-latency ` (or +//! `VECTORCRAFT_FRAME_LATENCY`) set how the window's frames reach the display for one launch. The +//! modes are `fifo` (vsync), `autovsync` (the default: wgpu picks relaxed vsync, which tears a late +//! frame, else vsync, by what the driver offers) and `novsync` (wgpu picks Immediate, else Mailbox, +//! else Fifo). A mode the driver may not offer is never requested. The latency is the number of +//! frames the swap chain may queue, 1 to 3. Unset, the app keeps its own surface settings. A flag +//! overrides its variable; a value that isn't one of these stops the app with a message, as +//! `--control` does. A launch that sets either one runs as its own app, as with `--new-instance`. +//! The surface the app asks for is logged at start-up. + +use std::ffi::OsString; + +/// A present mode the command line or the environment can ask for. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Mode { + Fifo, + AutoVsync, + NoVsync, +} + +/// The present mode and frame latency this launch asked for (`None`: the app's own setting). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Overrides { + pub mode: Option, + pub latency: Option, +} + +/// A present mode named by `name` (the flag or the variable): `fifo`, `autovsync` or `novsync`, any case. +fn mode(name: &str, value: Option<&str>) -> Result { + let need = format!("{name} needs fifo, autovsync or novsync"); + let Some(v) = value else { return Err(need) }; + match v.trim().to_ascii_lowercase().as_str() { + "fifo" => Ok(Mode::Fifo), + "autovsync" => Ok(Mode::AutoVsync), + "novsync" => Ok(Mode::NoVsync), + _ => Err(format!("{need}, not `{v}`")), + } +} + +/// A frame latency named by `name`: 1, 2 or 3. +fn latency(name: &str, value: Option<&str>) -> Result { + let need = format!("{name} needs 1, 2 or 3 frames"); + let Some(v) = value else { return Err(need) }; + v.trim().parse().ok().filter(|n| (1..=3).contains(n)).ok_or(format!("{need}, not `{v}`")) +} + +/// The value of `--flag ` or `--flag=` when `arg` is that flag; `None` when it isn't. +fn flag_value(flag: &str, arg: &str, args: &mut impl Iterator) -> Option> { + match arg.strip_prefix(flag)? { + "" => Some(args.next()), + rest => rest.strip_prefix('=').map(|v| Some(v.to_owned())), + } +} + +impl Overrides { + /// Whether a flag or a variable set the present mode or the frame latency. + pub fn is_set(&self) -> bool { + *self != Self::default() + } + + /// Returns whether this argument is `--present-mode` or `--frame-latency`. The next argument is + /// its value whatever it is, as with `--control`. + pub fn consume(&mut self, arg: &str, args: &mut impl Iterator) -> Result { + if let Some(value) = flag_value("--present-mode", arg, args) { + if self.mode.is_some() { + return Err("--present-mode given twice".into()); + } + self.mode = Some(mode("--present-mode", value.as_deref())?); + return Ok(true); + } + if let Some(value) = flag_value("--frame-latency", arg, args) { + if self.latency.is_some() { + return Err("--frame-latency given twice".into()); + } + self.latency = Some(latency("--frame-latency", value.as_deref())?); + return Ok(true); + } + Ok(false) + } + + /// Fills what the flags left unset from `VECTORCRAFT_PRESENT_MODE` and `VECTORCRAFT_FRAME_LATENCY`. + /// Unset or empty is no override; a variable is not read when its flag was given. + pub fn with_env(self, mode_var: Option, latency_var: Option) -> Result { + let set = |v: Option| v.filter(|v| !v.is_empty()).map(|v| v.to_string_lossy().into_owned()); + let mode = match (self.mode, set(mode_var)) { + (Some(m), _) => Some(m), + (None, Some(v)) => Some(mode("VECTORCRAFT_PRESENT_MODE", Some(&v))?), + (None, None) => None, + }; + let latency = match (self.latency, set(latency_var)) { + (Some(n), _) => Some(n), + (None, Some(v)) => Some(latency("VECTORCRAFT_FRAME_LATENCY", Some(&v))?), + (None, None) => None, + }; + Ok(Self { mode, latency }) + } + + /// `surface` with the overrides applied. + #[cfg(feature = "wgpu")] + pub fn apply(&self, surface: eframe::egui_wgpu::SurfaceConfig) -> eframe::egui_wgpu::SurfaceConfig { + use eframe::wgpu::PresentMode; + let present_mode = match self.mode { + Some(Mode::Fifo) => PresentMode::Fifo, + Some(Mode::AutoVsync) => PresentMode::AutoVsync, + Some(Mode::NoVsync) => PresentMode::AutoNoVsync, + None => surface.present_mode, + }; + eframe::egui_wgpu::SurfaceConfig { present_mode, desired_maximum_frame_latency: self.latency.or(surface.desired_maximum_frame_latency) } + } +} + +/// The present mode and frame latency `surface` asks for, for the start-up log: +/// "autovsync, frame latency 1", with "(override)" +/// after a value a flag or variable set. +#[cfg(feature = "wgpu")] +pub fn describe(surface: &eframe::egui_wgpu::SurfaceConfig, overrides: &Overrides) -> String { + use eframe::wgpu::PresentMode; + let mode = match surface.present_mode { + PresentMode::AutoVsync => "autovsync", + PresentMode::AutoNoVsync => "novsync", + PresentMode::Fifo => "fifo", + PresentMode::FifoRelaxed => "fiforelaxed", + PresentMode::Immediate => "immediate", + PresentMode::Mailbox => "mailbox", + }; + let latency = surface.desired_maximum_frame_latency.map_or("default".to_string(), |n| n.to_string()); + let tag = |set: bool| if set { " (override)" } else { "" }; + format!("{mode}{}, frame latency {latency}{}", tag(overrides.mode.is_some()), tag(overrides.latency.is_some())) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn parse(args: &[&str]) -> Result { + let mut overrides = Overrides::default(); + let mut args = args.iter().map(|a| a.to_string()); + while let Some(a) = args.next() { + assert!(overrides.consume(&a, &mut args)?, "{a}"); + } + Ok(overrides) + } + + #[test] + fn flags_take_the_three_modes_and_latencies_from_1_to_3() { + assert_eq!(parse(&[]), Ok(Overrides::default())); + assert_eq!(parse(&["--present-mode", "fifo"]).map(|o| o.mode), Ok(Some(Mode::Fifo))); + assert_eq!(parse(&["--present-mode=AutoVsync"]).map(|o| o.mode), Ok(Some(Mode::AutoVsync))); + assert_eq!(parse(&["--present-mode", " novsync "]).map(|o| o.mode), Ok(Some(Mode::NoVsync))); + for n in 1..=3 { + assert_eq!(parse(&["--frame-latency", &n.to_string()]).map(|o| o.latency), Ok(Some(n))); + } + assert_eq!(parse(&["--frame-latency=2", "--present-mode", "fifo"]), Ok(Overrides { mode: Some(Mode::Fifo), latency: Some(2) })); + } + + #[test] + fn bad_flag_values_are_errors() { + let modes = "--present-mode needs fifo, autovsync or novsync"; + assert_eq!(parse(&["--present-mode"]), Err(modes.into())); + for bad in ["mailbox", "immediate", "vsync", "fast", ""] { + assert_eq!(parse(&["--present-mode", bad]), Err(format!("{modes}, not `{bad}`"))); + assert_eq!(parse(&[&format!("--present-mode={bad}")]), Err(format!("{modes}, not `{bad}`"))); + } + assert_eq!(parse(&["--present-mode", "--frame-latency"]), Err(format!("{modes}, not `--frame-latency`"))); + let frames = "--frame-latency needs 1, 2 or 3 frames"; + assert_eq!(parse(&["--frame-latency"]), Err(frames.into())); + for bad in ["0", "4", "-1", "one", "1.5", "99999999999", ""] { + assert_eq!(parse(&["--frame-latency", bad]), Err(format!("{frames}, not `{bad}`"))); + } + assert_eq!(parse(&["--present-mode", "fifo", "--present-mode=novsync"]), Err("--present-mode given twice".into())); + assert_eq!(parse(&["--frame-latency=1", "--frame-latency", "2"]), Err("--frame-latency given twice".into())); + } + + #[test] + fn other_arguments_are_not_presentation_flags() { + let mut overrides = Overrides::default(); + let mut args = ["fifo".to_owned()].into_iter(); + for other in ["--present-modes", "--present", "--frame-latency-2", "drawing.svg", "--control"] { + assert!(!overrides.consume(other, &mut args).unwrap(), "{other}"); + } + assert_eq!(args.next().as_deref(), Some("fifo")); + assert_eq!(overrides, Overrides::default()); + } + + #[test] + fn variables_fill_what_the_flags_leave_unset_and_bad_values_are_errors() { + let none = Overrides::default(); + assert_eq!(none.with_env(None, None), Ok(none)); + assert_eq!(none.with_env(Some("".into()), Some("".into())), Ok(none)); + assert_eq!(none.with_env(Some("FIFO".into()), Some("2".into())), Ok(Overrides { mode: Some(Mode::Fifo), latency: Some(2) })); + assert_eq!( + none.with_env(Some("mailbox".into()), None), + Err("VECTORCRAFT_PRESENT_MODE needs fifo, autovsync or novsync, not `mailbox`".into()) + ); + assert_eq!(none.with_env(None, Some("0".into())), Err("VECTORCRAFT_FRAME_LATENCY needs 1, 2 or 3 frames, not `0`".into())); + // A flag wins, and its variable is not read, so a bad value there doesn't stop the app. + let flags = Overrides { mode: Some(Mode::NoVsync), latency: Some(3) }; + assert_eq!(flags.with_env(Some("bad".into()), Some("9".into())), Ok(flags)); + let mode_only = Overrides { mode: Some(Mode::AutoVsync), latency: None }; + assert_eq!(mode_only.with_env(Some("bad".into()), Some("1".into())), Ok(Overrides { mode: Some(Mode::AutoVsync), latency: Some(1) })); + // Either value set makes the launch run as its own app. + assert!(!none.is_set()); + assert!(mode_only.is_set()); + assert!(Overrides { mode: None, latency: Some(1) }.is_set()); + } + + /// `--help` states the app's own surface as the default, so it changes with it. + #[cfg(feature = "wgpu")] + #[test] + fn the_usage_names_the_app_surface_as_the_default() { + let app = eframe::egui_wgpu::SurfaceConfig::LOW_LATENCY; + let usage = crate::USAGE.split_whitespace().collect::>().join(" "); + assert_eq!(app.present_mode, eframe::wgpu::PresentMode::AutoVsync, "the usage calls autovsync the default"); + assert!(usage.contains("autovsync (the default"), "{usage}"); + let Some(frames) = app.desired_maximum_frame_latency else { panic!("the usage gives a default frame latency") }; + assert!(usage.contains(&format!("(the default is {frames})")), "{usage}"); + } + + #[cfg(feature = "wgpu")] + #[test] + fn overrides_change_only_what_they_set_on_the_app_surface() { + use eframe::egui_wgpu::SurfaceConfig; + use eframe::wgpu::PresentMode; + let app = SurfaceConfig::LOW_LATENCY; + // No override: the surface the app asks for is unchanged. + assert_eq!(Overrides::default().apply(app), app); + let latency = Overrides { mode: None, latency: Some(2) }; + let s = latency.apply(app); + assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::AutoVsync, Some(2))); + assert_eq!(describe(&s, &latency), "autovsync, frame latency 2 (override)"); + let fifo = Overrides { mode: Some(Mode::Fifo), latency: None }; + let s = fifo.apply(app); + assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::Fifo, app.desired_maximum_frame_latency)); + // Never a mode the driver may lack: no vsync lets wgpu fall back by support. + let novsync = Overrides { mode: Some(Mode::NoVsync), latency: Some(3) }; + let s = novsync.apply(app); + assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::AutoNoVsync, Some(3))); + assert_eq!(describe(&s, &novsync), "novsync (override), frame latency 3 (override)"); + let unset = SurfaceConfig { present_mode: PresentMode::Fifo, desired_maximum_frame_latency: None }; + assert_eq!(describe(&unset, &Overrides::default()), "fifo, frame latency default"); + } +} diff --git a/apps/vectorcraft/tests/it/help.rs b/apps/vectorcraft/tests/it/help.rs index d82475b9ff..5f53f920b4 100644 --- a/apps/vectorcraft/tests/it/help.rs +++ b/apps/vectorcraft/tests/it/help.rs @@ -52,7 +52,17 @@ fn prints_usage(args: &[&str], env: &[(&str, &str)]) { assert!(out.status.success(), "{args:?}: {}", String::from_utf8_lossy(&out.stderr)); assert!(out.stderr.is_empty(), "{args:?}: {}", String::from_utf8_lossy(&out.stderr)); assert!(stdout.starts_with("Usage: vectorcraft "), "{args:?}: {stdout}"); - for flag in ["--control", "--automation-read-root", "--automation-write-root", "--in-window-menus", "--safe-mode", "--version", "--help"] { + for flag in [ + "--control", + "--automation-read-root", + "--automation-write-root", + "--in-window-menus", + "--safe-mode", + "--present-mode", + "--frame-latency", + "--version", + "--help", + ] { assert!(stdout.contains(flag), "{args:?}: usage doesn't mention {flag}: {stdout}"); } // Headless work is the CLI's: the usage says where to go. @@ -73,6 +83,32 @@ fn help_wins_over_a_bad_control_port_variable() { prints_usage(&["--help"], &[("VECTORCRAFT_CONTROL_PORT", "abc")]); } +/// A bad presentation variable stops the app with a message before it starts; `--help` and the +/// matching flag win over it. A run that gets past it stops at the control port `run` makes fail. +#[test] +fn a_bad_presentation_variable_is_an_error_unless_help_or_its_flag_is_given() { + for (var, value, need) in [ + ("VECTORCRAFT_FRAME_LATENCY", "0", "needs 1, 2 or 3 frames, not `0`"), + ("VECTORCRAFT_PRESENT_MODE", "mailbox", "needs fifo, autovsync or novsync, not `mailbox`"), + ] { + let out = run(&[], &[(var, value)]); + assert!(!out.status.success(), "{var}"); + assert_eq!(String::from_utf8(out.stderr).unwrap(), format!("vectorcraft: {var} {need}\n")); + prints_usage(&["--help"], &[(var, value)]); + } + for (args, env) in [ + (&["--frame-latency", "2"][..], ("VECTORCRAFT_FRAME_LATENCY", "0")), + (&["--present-mode=fifo"], ("VECTORCRAFT_PRESENT_MODE", "mailbox")), + (&[], ("VECTORCRAFT_FRAME_LATENCY", "3")), + ] { + let stderr = String::from_utf8(run(args, &[env]).stderr).unwrap(); + assert!(stderr.contains("VECTORCRAFT_CONTROL_PORT") && !stderr.contains(env.0), "{args:?}: {stderr}"); + } + let out = run(&["--frame-latency", "4"], &[]); + assert!(!out.status.success()); + assert_eq!(String::from_utf8(out.stderr).unwrap(), "vectorcraft: --frame-latency needs 1, 2 or 3 frames, not `4`\n"); +} + /// An option the app doesn't know (a typo of `--safe-mode`) is an error, not a file to open with /// plug-ins; a later `--help` still wins. #[test] diff --git a/crates/cad/Cargo.toml b/crates/cad/Cargo.toml index e529e1d4e2..4084e75d24 100644 --- a/crates/cad/Cargo.toml +++ b/crates/cad/Cargo.toml @@ -3,7 +3,7 @@ name = "vectorcraft-cad" version.workspace = true edition.workspace = true license.workspace = true -description = "VectorCraft CAD interchange: a hand-written ASCII DXF writer (R12 to 2018) and an HP-GL/2 plot file reader and writer" +description = "VectorCraft CAD interchange: DXF export through craft-dxf and an HP-GL/2 plot file reader and writer" [lints] workspace = true diff --git a/crates/cad/src/lib.rs b/crates/cad/src/lib.rs index bb752267aa..de9e7aea25 100644 --- a/crates/cad/src/lib.rs +++ b/crates/cad/src/lib.rs @@ -1,4 +1,4 @@ -//! CAD interchange: a hand-written ASCII DXF writer (versions R12 to 2018) and a reader on +//! CAD interchange: a DXF writer (versions R12 to 2018) on `craft_dxf::drawing` and a reader on //! `craft_dxf::model`, and an HP-GL/2 plot file reader and writer. //! //! [`export`] writes the visible art of a document into one DXF drawing: each layer becomes a DXF @@ -15,7 +15,7 @@ //! [`hpgl::import`] reads an HP-GL plotter file, and [`hpgl::export`] writes one: see [`hpgl`]. //! //! - `aci`: the 256-colour index palette and the nearest index of a colour. -//! - `writer`: group codes, handles and the file's sections, tables and objects. +//! - The ASCII file around those entities is written by `craft_dxf::drawing`. //! - `scene`: the document walk that turns objects into entities. //! - `import`: the reader, entities to art, blocks to symbols. //! - `hpgl`: the HP-GL reader, the pen's moves to paths, and the writer, paths to pen moves. @@ -24,7 +24,6 @@ mod aci; pub mod hpgl; pub mod import; mod scene; -mod writer; use vectorcraft_doc::{Document, Unit}; use vectorcraft_geom::Rect; @@ -136,11 +135,27 @@ impl DxfVersion { self >= Self::R2004 } /// Text is UTF-8 (earlier versions escape what isn't ASCII as `\U+XXXX`). - fn utf8(self) -> bool { + pub fn utf8(self) -> bool { self >= Self::R2007 } } +impl From for craft_dxf::drawing::Format { + fn from(v: DxfVersion) -> Self { + match v { + DxfVersion::R12 => Self::R12, + DxfVersion::R13 => Self::R13, + DxfVersion::R14 => Self::R14, + DxfVersion::R2000 => Self::R2000, + DxfVersion::R2004 => Self::R2004, + DxfVersion::R2007 => Self::R2007, + DxfVersion::R2010 => Self::R2010, + DxfVersion::R2013 => Self::R2013, + DxfVersion::R2018 => Self::R2018, + } + } +} + /// How many colours entities may use: indexed colours of the 256-colour palette, or true colour /// (with the nearest index for apps that read only the index). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] diff --git a/crates/cad/src/scene.rs b/crates/cad/src/scene.rs index ea3c962053..a5e229c2a4 100644 --- a/crates/cad/src/scene.rs +++ b/crates/cad/src/scene.rs @@ -14,8 +14,8 @@ use vectorcraft_effects::stroke; use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, Vec2}; use crate::aci::nearest_aci; -use crate::writer::{Codes, Drawing, EntityStyle, Handle, ImageDef, Layer, LineType, fixed}; use crate::{CAP_HEIGHT, ColorDepth, DxfImage, DxfOptions, DxfOutput, MAX_NEST, Preserve, RasterFormat}; +use craft_dxf::drawing::{Codes, Drawing, EntityStyle, Handle, ImageDef, Layer, LineType, STANDARD_STYLE, fixed}; /// Curves are flattened to within this distance (points) where DXF needs straight segments /// (hatch boundaries, R12 polylines). @@ -543,7 +543,7 @@ impl<'a> Scene<'a> { o, to_dxf: Affine::new([k, 0.0, 0.0, -k, -r.x0 * k, r.y1 * k]), k, - e: Codes::new(o.version), + e: Codes::new(o.version.into()), next: fixed::FIRST_FREE, layers: vec![], layer_names: Names::with(&["0", "Defpoints"]), @@ -551,7 +551,7 @@ impl<'a> Scene<'a> { flags: LayerFlags { off: false, locked: false, plot: true }, linetypes: vec![], styles: vec![], - style_names: Names::with(&[crate::writer::STANDARD_STYLE]), + style_names: Names::with(&[STANDARD_STYLE]), images: vec![], files: vec![], by_key: HashMap::new(), @@ -579,7 +579,7 @@ impl<'a> Scene<'a> { let one = (self.o.scale - 1.0).abs() < 1e-12; let insunits = if one { crate::insunits_code(self.o.unit).unwrap_or(0) } else { 0 }; let drawing = Drawing { - version: self.o.version, + version: self.o.version.into(), layers: self.layers, linetypes: self.linetypes, styles: self.styles, diff --git a/crates/cad/src/tests.rs b/crates/cad/src/tests.rs index 84e547709d..48f6010925 100644 --- a/crates/cad/src/tests.rs +++ b/crates/cad/src/tests.rs @@ -1451,3 +1451,23 @@ fn symbols_fanning_out_into_empty_symbols_stop_at_the_symbol_budget() { assert!(entities(&out).is_empty()); assert!(out.warnings.iter().any(|w| w.contains("symbols placed inside symbols")), "{:?}", out.warnings); } + +#[test] +fn export_bytes_match_shared_writer_goldens() { + use std::path::PathBuf; + let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/data"); + let cases: [(&str, DxfVersion, Document); 2] = + [("shapes_r12.dxf", DxfVersion::R12, shapes_doc()), ("shapes_r2018.dxf", DxfVersion::R2018, shapes_doc())]; + for (name, version, doc) in cases { + let out = export(&doc, &DxfOptions { version, ..opts(&doc) }).unwrap(); + let got = std::str::from_utf8(&out.bytes).expect("UTF-8 DXF"); + let path = dir.join(name); + if std::env::var_os("WRITE_DXF_GOLDENS").is_some() { + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(&path, got).unwrap(); + continue; + } + let expected = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {}: {e}", path.display())); + assert_eq!(got, expected, "DXF bytes changed versus {}", path.display()); + } +} diff --git a/crates/cad/src/writer.rs b/crates/cad/src/writer.rs deleted file mode 100644 index 6ba7e5a35d..0000000000 --- a/crates/cad/src/writer.rs +++ /dev/null @@ -1,674 +0,0 @@ -//! The ASCII DXF file: group codes, handles, and the sections, tables and objects around the -//! entities. DXF R13 and later give every object a handle and subclass markers; R2000 and later -//! add layouts and plot styles, which CAD apps expect to find. - -use std::fmt::Write as _; - -use crate::DxfVersion; - -/// An object handle (written in hex). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) struct Handle(pub u32); - -/// The handles of the fixed objects every drawing has. Entities and table entries count up from -/// [`FIRST_FREE`]. -pub(crate) mod fixed { - use super::Handle; - pub const LAYER_TABLE: Handle = Handle(0x1); - pub const LTYPE_TABLE: Handle = Handle(0x2); - pub const APPID_TABLE: Handle = Handle(0x3); - pub const DIMSTYLE_TABLE: Handle = Handle(0x4); - pub const STYLE_TABLE: Handle = Handle(0x5); - pub const UCS_TABLE: Handle = Handle(0x6); - pub const VIEW_TABLE: Handle = Handle(0x7); - pub const VPORT_TABLE: Handle = Handle(0x8); - pub const BLOCK_RECORD_TABLE: Handle = Handle(0x9); - pub const ROOT: Handle = Handle(0xA); - pub const GROUPS: Handle = Handle(0xB); - pub const LAYOUTS: Handle = Handle(0xC); - pub const MODEL_RECORD: Handle = Handle(0xD); - pub const PAPER_RECORD: Handle = Handle(0xE); - pub const MODEL_BLOCK: Handle = Handle(0xF); - pub const MODEL_END: Handle = Handle(0x10); - pub const PAPER_BLOCK: Handle = Handle(0x11); - pub const PAPER_END: Handle = Handle(0x12); - pub const MODEL_LAYOUT: Handle = Handle(0x13); - pub const PAPER_LAYOUT: Handle = Handle(0x14); - pub const ACTIVE_VPORT: Handle = Handle(0x15); - pub const ACAD_APPID: Handle = Handle(0x16); - pub const STANDARD_DIMSTYLE: Handle = Handle(0x17); - pub const IMAGE_DICT: Handle = Handle(0x18); - pub const IMAGE_VARS: Handle = Handle(0x19); - pub const PLOT_STYLES: Handle = Handle(0x1A); - pub const PLOT_NORMAL: Handle = Handle(0x1B); - pub const FIRST_FREE: u32 = 0x30; -} - -/// A number as DXF writes it: up to 6 decimals, no trailing zeros, 0 for anything not finite. -pub(crate) fn num(v: f64) -> String { - if !v.is_finite() { - return "0".into(); - } - let s = format!("{v:.6}"); - let s = s.trim_end_matches('0').trim_end_matches('.'); - if s == "-0" || s.is_empty() { "0".into() } else { s.into() } -} - -/// Text as a DXF string value: one line, `^` escaped, and before DXF 2007 (which reads UTF-8) -/// every character outside ASCII as `\U+XXXX`. -pub(crate) fn text(s: &str, utf8: bool) -> String { - let mut out = String::with_capacity(s.len()); - for c in s.chars() { - match c { - '\r' | '\n' | '\t' => out.push(' '), - c if c.is_control() => {} - '^' => out.push_str("^ "), - c if !utf8 && !c.is_ascii() => match u16::try_from(u32::from(c)) { - Ok(u) => _ = write!(out, "\\U+{u:04X}"), - Err(_) => out.push('?'), - }, - c => out.push(c), - } - } - out -} - -/// Group-code/value pairs in the order they are written. -pub(crate) struct Codes { - pub v: DxfVersion, - out: String, -} - -impl Codes { - pub fn new(v: DxfVersion) -> Self { - Self { v, out: String::new() } - } - - pub fn into_string(self) -> String { - self.out - } - - pub fn append(&mut self, other: &str) { - self.out.push_str(other); - } - - /// A value written as it is (names and keywords the writer itself chose). - pub fn raw(&mut self, code: u16, value: &str) { - _ = writeln!(self.out, "{code:>3}\n{value}"); - } - - /// Text from the document, encoded for the version (see [`text`]). - pub fn str(&mut self, code: u16, value: &str) { - let t = text(value, self.v.utf8()); - self.raw(code, &t); - } - - pub fn int(&mut self, code: u16, value: i64) { - _ = writeln!(self.out, "{code:>3}\n{value}"); - } - - pub fn num(&mut self, code: u16, value: f64) { - _ = writeln!(self.out, "{code:>3}\n{}", num(value)); - } - - pub fn handle(&mut self, code: u16, h: Handle) { - _ = writeln!(self.out, "{code:>3}\n{:X}", h.0); - } - - /// A 2D point at `code` (x), `code + 10` (y). - pub fn xy(&mut self, code: u16, x: f64, y: f64) { - self.num(code, x); - self.num(code + 10, y); - } - - /// A 3D point at `code`, `code + 10`, `code + 20` (z = 0). - pub fn xyz(&mut self, code: u16, x: f64, y: f64) { - self.xy(code, x, y); - self.num(code + 20, 0.0); - } - - /// The extrusion direction of planar entities: the z axis. - pub fn normal(&mut self) { - self.num(210, 0.0); - self.num(220, 0.0); - self.num(230, 1.0); - } - - /// The start of an object: its type, and from R13 its handle, owner and first subclass. - fn object(&mut self, kind: &str, h: Handle, owner: Handle, subclass: &str) { - self.raw(0, kind); - if self.v.handles() { - self.handle(if kind == "DIMSTYLE" { 105 } else { 5 }, h); - self.handle(330, owner); - self.raw(100, subclass); - } - } - - /// A table entry: the shared record subclass, then the table's own (from R13). - fn record(&mut self, kind: &str, h: Handle, table: Handle, subclass: &str) { - self.object(kind, h, table, "AcDbSymbolTableRecord"); - if self.v.handles() { - self.raw(100, subclass); - } - } - - fn section(&mut self, name: &str) { - self.raw(0, "SECTION"); - self.raw(2, name); - } - - fn end_section(&mut self) { - self.raw(0, "ENDSEC"); - } - - fn table(&mut self, name: &str, h: Handle, count: usize) { - self.raw(0, "TABLE"); - self.raw(2, name); - if self.v.handles() { - self.handle(5, h); - self.raw(330, "0"); - self.raw(100, "AcDbSymbolTable"); - } - self.int(70, count as i64); - if name == "DIMSTYLE" && self.v.r2000() { - self.raw(100, "AcDbDimStyleTable"); - } - } - - fn end_table(&mut self) { - self.raw(0, "ENDTAB"); - } -} - -/// How an entity is drawn: its colour index, true colour, lineweight, linetype and transparency. -#[derive(Clone, Debug, Default)] -pub(crate) struct EntityStyle { - pub aci: u8, - /// `0xRRGGBB` (DXF 2004 and later). - pub rgb: Option, - /// Hundredths of a millimetre (DXF 2000 and later). - pub lineweight: Option, - pub linetype: Option, - /// Opacity 0–255 (DXF 2004 and later; opaque is left out). - pub alpha: Option, -} - -impl Codes { - /// The start of an entity of `kind` owned by `owner` (model space, or a polyline for its - /// vertices) on `layer` with its style, ending with `subclass` (none when empty). - pub fn entity(&mut self, kind: &str, h: Handle, owner: Handle, layer: &str, style: &EntityStyle, subclass: &str) { - self.object(kind, h, owner, "AcDbEntity"); - self.str(8, layer); - if let Some(lt) = &style.linetype { - self.str(6, lt); - } - self.int(62, i64::from(style.aci.max(1))); - if self.v.r2000() - && let Some(lw) = style.lineweight - { - self.int(370, i64::from(lw)); - } - if self.v.true_color() { - if let Some(rgb) = style.rgb { - self.int(420, i64::from(rgb)); - } - if let Some(a) = style.alpha { - self.int(440, 0x0200_0000 | i64::from(a)); - } - } - if self.v.handles() && !subclass.is_empty() { - self.raw(100, subclass); - } - } -} - -/// A DXF layer. -#[derive(Clone, Debug)] -pub(crate) struct Layer { - pub name: String, - pub aci: u8, - /// Switched off (a hidden layer). - pub off: bool, - pub locked: bool, - /// Plotted (printable). - pub plot: bool, -} - -/// A dash pattern: dash, gap, dash… lengths in drawing units. -#[derive(Clone, Debug)] -pub(crate) struct LineType { - pub name: String, - pub pattern: Vec, -} - -/// A placed image file and the image entities that show it. -#[derive(Clone, Debug)] -pub(crate) struct ImageDef { - pub name: String, - pub size: (u32, u32), - pub handle: Handle, - /// `(reactor, image entity)` per image entity. - pub reactors: Vec<(Handle, Handle)>, -} - -/// Everything around the entities, collected while they were written. -pub(crate) struct Drawing { - pub version: DxfVersion, - pub layers: Vec, - pub linetypes: Vec, - /// Text styles: (style name, font family). - pub styles: Vec<(String, String)>, - pub images: Vec, - /// The entities' group codes. - pub entities: String, - /// `[x0, y0, x1, y1]` of everything written (drawing units). - pub extents: [f64; 4], - /// The export region (drawing units). - pub limits: [f64; 4], - /// `$INSUNITS`. - pub insunits: u8, - pub metric: bool, - /// The next free handle. - pub next: u32, -} - -/// The text style every drawing has. -pub(crate) const STANDARD_STYLE: &str = "Standard"; - -impl Drawing { - /// The whole file. - pub fn write(self) -> String { - let v = self.version; - let mut c = Codes::new(v); - // Table entries get the handles after the entities'. - let mut next = self.next; - let mut take = |n: usize| { - let start = next; - next = next.saturating_add(u32::try_from(n).unwrap_or(u32::MAX)); - start - }; - let ltype_base = take(3 + self.linetypes.len()); - let layer_base = take(1 + self.layers.len()); - let style_base = take(1 + self.styles.len()); - self.header(&mut c, next); - if v.handles() { - self.classes(&mut c); - } - c.section("TABLES"); - self.vport(&mut c); - self.ltypes(&mut c, ltype_base); - self.layer_table(&mut c, layer_base); - self.style_table(&mut c, style_base); - if v.handles() { - for (name, h) in [("VIEW", fixed::VIEW_TABLE), ("UCS", fixed::UCS_TABLE)] { - c.table(name, h, 0); - c.end_table(); - } - c.table("APPID", fixed::APPID_TABLE, 1); - c.record("APPID", fixed::ACAD_APPID, fixed::APPID_TABLE, "AcDbRegAppTableRecord"); - c.raw(2, "ACAD"); - c.int(70, 0); - c.end_table(); - c.table("DIMSTYLE", fixed::DIMSTYLE_TABLE, 1); - c.record("DIMSTYLE", fixed::STANDARD_DIMSTYLE, fixed::DIMSTYLE_TABLE, "AcDbDimStyleTableRecord"); - c.raw(2, "Standard"); - c.int(70, 0); - c.end_table(); - c.table("BLOCK_RECORD", fixed::BLOCK_RECORD_TABLE, 2); - for (name, h, layout) in - [("*Model_Space", fixed::MODEL_RECORD, fixed::MODEL_LAYOUT), ("*Paper_Space", fixed::PAPER_RECORD, fixed::PAPER_LAYOUT)] - { - c.record("BLOCK_RECORD", h, fixed::BLOCK_RECORD_TABLE, "AcDbBlockTableRecord"); - c.raw(2, name); - if v.r2000() { - c.handle(340, layout); - c.int(70, 0); - c.int(280, 1); - c.int(281, 0); - } - } - c.end_table(); - } - c.end_section(); - if v.handles() { - c.section("BLOCKS"); - for (name, record, begin, end) in [ - ("*Model_Space", fixed::MODEL_RECORD, fixed::MODEL_BLOCK, fixed::MODEL_END), - ("*Paper_Space", fixed::PAPER_RECORD, fixed::PAPER_BLOCK, fixed::PAPER_END), - ] { - c.object("BLOCK", begin, record, "AcDbEntity"); - c.raw(8, "0"); - c.raw(100, "AcDbBlockBegin"); - c.raw(2, name); - c.int(70, 0); - c.xyz(10, 0.0, 0.0); - c.raw(3, name); - c.raw(1, ""); - c.object("ENDBLK", end, record, "AcDbEntity"); - c.raw(8, "0"); - c.raw(100, "AcDbBlockEnd"); - } - c.end_section(); - } - c.section("ENTITIES"); - c.append(&self.entities); - c.end_section(); - if v.handles() { - self.objects(&mut c); - } - c.raw(0, "EOF"); - c.into_string() - } - - fn header(&self, c: &mut Codes, handseed: u32) { - let v = self.version; - let var = |c: &mut Codes, name: &str| c.raw(9, name); - c.section("HEADER"); - var(c, "$ACADVER"); - c.raw(1, v.acadver()); - var(c, "$DWGCODEPAGE"); - c.raw(3, "ANSI_1252"); - var(c, "$INSBASE"); - c.xyz(10, 0.0, 0.0); - let [x0, y0, x1, y1] = self.extents; - var(c, "$EXTMIN"); - c.xyz(10, x0, y0); - var(c, "$EXTMAX"); - c.xyz(10, x1, y1); - let [lx0, ly0, lx1, ly1] = self.limits; - var(c, "$LIMMIN"); - c.xy(10, lx0, ly0); - var(c, "$LIMMAX"); - c.xy(10, lx1, ly1); - if v.r2000() { - var(c, "$LWDISPLAY"); - c.int(290, 1); - var(c, "$INSUNITS"); - c.int(70, i64::from(self.insunits)); - var(c, "$MEASUREMENT"); - c.int(70, i64::from(self.metric)); - } - if v.handles() { - var(c, "$HANDSEED"); - c.handle(5, Handle(handseed)); - } - c.end_section(); - } - - fn classes(&self, c: &mut Codes) { - let mut classes: Vec<(&str, &str, &str, i64, bool)> = vec![]; - if self.version.r2000() { - classes.extend([ - ("ACDBDICTIONARYWDFLT", "AcDbDictionaryWithDefault", "ObjectDBX Classes", 0, false), - ("ACDBPLACEHOLDER", "AcDbPlaceHolder", "ObjectDBX Classes", 0, false), - ("LAYOUT", "AcDbLayout", "ObjectDBX Classes", 0, false), - ]); - } - if !self.images.is_empty() { - classes.extend([ - ("RASTERVARIABLES", "AcDbRasterVariables", "ISM", 0, false), - ("IMAGE", "AcDbRasterImage", "ISM", 2175, true), - ("IMAGEDEF", "AcDbRasterImageDef", "ISM", 0, false), - ("IMAGEDEF_REACTOR", "AcDbRasterImageDefReactor", "ISM", 1, false), - ]); - } - c.section("CLASSES"); - for (name, cpp, app, flags, entity) in classes { - c.raw(0, "CLASS"); - c.raw(1, name); - c.raw(2, cpp); - c.raw(3, app); - c.int(90, flags); - if self.version.true_color() { - c.int(91, 0); - } - c.int(280, 0); - c.int(281, i64::from(entity)); - } - c.end_section(); - } - - /// The active viewport, zoomed to the drawing's extents. - fn vport(&self, c: &mut Codes) { - let [x0, y0, x1, y1] = self.extents; - c.table("VPORT", fixed::VPORT_TABLE, 1); - c.record("VPORT", fixed::ACTIVE_VPORT, fixed::VPORT_TABLE, "AcDbViewportTableRecord"); - c.raw(2, if self.version.handles() { "*Active" } else { "*ACTIVE" }); - c.int(70, 0); - c.xy(10, 0.0, 0.0); - c.xy(11, 1.0, 1.0); - c.xy(12, (x0 + x1) / 2.0, (y0 + y1) / 2.0); - c.xy(13, 0.0, 0.0); - c.xy(14, 1.0, 1.0); - c.xy(15, 10.0, 10.0); - // The view direction looks down the z axis: (0, 0, 1), each code once. - c.xy(16, 0.0, 0.0); - c.num(36, 1.0); - c.xyz(17, 0.0, 0.0); - let (w, h) = ((x1 - x0).abs(), (y1 - y0).abs()); - // The view's height, with a margin; its width follows from the aspect ratio. - c.num(40, (h.max(w / 1.5) * 1.1).max(1.0)); - c.num(41, 1.5); - c.num(42, 50.0); - c.num(43, 0.0); - c.num(44, 0.0); - c.num(50, 0.0); - c.num(51, 0.0); - for (code, value) in [(71, 0), (72, 1000), (73, 1), (74, 3), (75, 0), (76, 0), (77, 0), (78, 0)] { - c.int(code, value); - } - if self.version.r2000() { - c.int(281, 0); - c.int(65, 0); - c.num(146, 0.0); - } - c.end_table(); - } - - fn ltypes(&self, c: &mut Codes, base: u32) { - c.table("LTYPE", fixed::LTYPE_TABLE, 3 + self.linetypes.len()); - let solid = [("ByBlock", ""), ("ByLayer", ""), ("Continuous", "Solid line")]; - let rows = solid.iter().map(|(n, d)| (*n, *d, &[][..])).chain(self.linetypes.iter().map(|l| (l.name.as_str(), "", l.pattern.as_slice()))); - for (i, (name, desc, pattern)) in rows.enumerate() { - c.record("LTYPE", Handle(base.saturating_add(i as u32)), fixed::LTYPE_TABLE, "AcDbLinetypeTableRecord"); - c.str(2, name); - c.int(70, 0); - c.str(3, if pattern.is_empty() { desc } else { "Dashed" }); - c.int(72, 65); - c.int(73, pattern.len() as i64); - c.num(40, pattern.iter().map(|v| v.abs()).sum()); - for v in pattern { - c.num(49, *v); - if self.version.handles() { - c.int(74, 0); - } - } - } - c.end_table(); - } - - fn layer_table(&self, c: &mut Codes, base: u32) { - let zero = Layer { name: "0".into(), aci: 7, off: false, locked: false, plot: true }; - c.table("LAYER", fixed::LAYER_TABLE, 1 + self.layers.len()); - for (i, l) in std::iter::once(&zero).chain(&self.layers).enumerate() { - c.record("LAYER", Handle(base.saturating_add(i as u32)), fixed::LAYER_TABLE, "AcDbLayerTableRecord"); - c.str(2, &l.name); - c.int(70, if l.locked { 4 } else { 0 }); - // A negative colour switches the layer off. - let aci = i64::from(l.aci.max(1)); - c.int(62, if l.off { -aci } else { aci }); - c.raw(6, "Continuous"); - if self.version.r2000() { - c.int(290, i64::from(l.plot)); - c.int(370, -3); - c.handle(390, fixed::PLOT_NORMAL); - } - } - c.end_table(); - } - - fn style_table(&self, c: &mut Codes, base: u32) { - c.table("STYLE", fixed::STYLE_TABLE, 1 + self.styles.len()); - let standard = (STANDARD_STYLE.to_string(), String::new()); - for (i, (name, family)) in std::iter::once(&standard).chain(&self.styles).enumerate() { - c.record("STYLE", Handle(base.saturating_add(i as u32)), fixed::STYLE_TABLE, "AcDbTextStyleTableRecord"); - c.str(2, name); - c.int(70, 0); - c.num(40, 0.0); - c.num(41, 1.0); - c.num(50, 0.0); - c.int(71, 0); - c.num(42, 2.5); - // The font file; from 2000 the family name too, which is how CAD apps find a TrueType font. - if family.is_empty() { - c.raw(3, "txt"); - } else { - c.str(3, &format!("{family}.ttf")); - } - c.raw(4, ""); - if self.version.r2000() && !family.is_empty() { - c.raw(1001, "ACAD"); - c.str(1000, family); - c.int(1071, 0); - } - } - c.end_table(); - } - - fn objects(&self, c: &mut Codes) { - let v = self.version; - let images = !self.images.is_empty(); - c.section("OBJECTS"); - let dict = |c: &mut Codes, h: Handle, owner: Handle, entries: &[(&str, Handle)]| { - c.object("DICTIONARY", h, owner, "AcDbDictionary"); - c.int(281, 1); - for (name, e) in entries { - c.str(3, name); - c.handle(350, *e); - } - }; - let mut root = vec![("ACAD_GROUP", fixed::GROUPS)]; - if images { - root.extend([("ACAD_IMAGE_DICT", fixed::IMAGE_DICT), ("ACAD_IMAGE_VARS", fixed::IMAGE_VARS)]); - } - if v.r2000() { - root.extend([("ACAD_LAYOUT", fixed::LAYOUTS), ("ACAD_PLOTSTYLENAME", fixed::PLOT_STYLES)]); - } - dict(c, fixed::ROOT, Handle(0), &root); - dict(c, fixed::GROUPS, fixed::ROOT, &[]); - if v.r2000() { - dict(c, fixed::LAYOUTS, fixed::ROOT, &[("Layout1", fixed::PAPER_LAYOUT), ("Model", fixed::MODEL_LAYOUT)]); - c.object("ACDBDICTIONARYWDFLT", fixed::PLOT_STYLES, fixed::ROOT, "AcDbDictionary"); - c.int(281, 1); - c.raw(3, "Normal"); - c.handle(350, fixed::PLOT_NORMAL); - c.raw(100, "AcDbDictionaryWithDefault"); - c.handle(340, fixed::PLOT_NORMAL); - // A placeholder has no data and no subclass marker of its own. - c.raw(0, "ACDBPLACEHOLDER"); - c.handle(5, fixed::PLOT_NORMAL); - c.handle(330, fixed::PLOT_STYLES); - self.layout(c, fixed::MODEL_LAYOUT, "Model", 0, fixed::MODEL_RECORD); - self.layout(c, fixed::PAPER_LAYOUT, "Layout1", 1, fixed::PAPER_RECORD); - } - if images { - c.object("RASTERVARIABLES", fixed::IMAGE_VARS, fixed::ROOT, "AcDbRasterVariables"); - c.int(90, 0); - c.int(70, 0); - c.int(71, 1); - c.int(72, 0); - let entries: Vec<(&str, Handle)> = self.images.iter().map(|i| (i.name.as_str(), i.handle)).collect(); - dict(c, fixed::IMAGE_DICT, fixed::ROOT, &entries); - for img in &self.images { - c.raw(0, "IMAGEDEF"); - c.handle(5, img.handle); - c.raw(102, "{ACAD_REACTORS"); - c.handle(330, fixed::IMAGE_DICT); - for (reactor, _) in &img.reactors { - c.handle(330, *reactor); - } - c.raw(102, "}"); - c.handle(330, fixed::IMAGE_DICT); - c.raw(100, "AcDbRasterImageDef"); - c.int(90, 0); - c.str(1, &img.name); - c.xy(10, f64::from(img.size.0), f64::from(img.size.1)); - c.xy(11, 1.0, 1.0); - c.int(280, 1); - c.int(281, 0); - for (reactor, image) in &img.reactors { - c.object("IMAGEDEF_REACTOR", *reactor, *image, "AcDbRasterImageDefReactor"); - c.int(90, 2); - c.handle(330, *image); - } - } - } - c.end_section(); - } - - /// A layout (DXF 2000 and later): its plot settings, then the layout itself. - fn layout(&self, c: &mut Codes, h: Handle, name: &str, tab: i64, record: Handle) { - let [x0, y0, x1, y1] = self.extents; - c.object("LAYOUT", h, fixed::LAYOUTS, "AcDbPlotSettings"); - c.raw(1, ""); - c.raw(2, "none_device"); - c.raw(4, ""); - c.raw(6, ""); - for code in 40..=49 { - c.num(code, 0.0); - } - c.num(140, 0.0); - c.num(141, 0.0); - c.num(142, 1.0); - c.num(143, 1.0); - // Plot flags; 1024 marks the model space layout. - c.int(70, if record == fixed::MODEL_RECORD { 688 | 1024 } else { 688 }); - c.int(72, 1); - c.int(73, 0); - c.int(74, 5); - c.raw(7, ""); - c.int(75, 16); - if self.version.true_color() { - // Shade plot mode (as displayed), resolution level (normal) and custom DPI. - c.int(76, 0); - c.int(77, 2); - c.int(78, 300); - } - c.num(147, 1.0); - // The paper image origin is 148 (x) and 149 (y), not a point at 148 and 158. - c.num(148, 0.0); - c.num(149, 0.0); - c.raw(100, "AcDbLayout"); - c.raw(1, name); - c.int(70, 1); - c.int(71, tab); - let [lx0, ly0, lx1, ly1] = self.limits; - c.xy(10, lx0, ly0); - c.xy(11, lx1, ly1); - c.xyz(12, 0.0, 0.0); - c.xyz(14, x0, y0); - c.xyz(15, x1, y1); - c.num(146, 0.0); - c.xyz(13, 0.0, 0.0); - c.xyz(16, 1.0, 0.0); - c.xyz(17, 0.0, 1.0); - c.int(76, 1); - c.handle(330, record); - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn numbers_and_text_are_written_plainly() { - assert_eq!(num(1.5), "1.5"); - assert_eq!(num(-0.0000001), "0"); - assert_eq!(num(2.0), "2"); - assert_eq!(num(f64::NAN), "0"); - assert_eq!(text("a^b\nc", true), "a^ b c"); - assert_eq!(text("Größe 😀", false), "Gr\\U+00F6\\U+00DFe ?"); - assert_eq!(text("Größe", true), "Größe"); - } -} diff --git a/crates/cad/tests/data/shapes_r12.dxf b/crates/cad/tests/data/shapes_r12.dxf new file mode 100644 index 0000000000..96ea7b638e --- /dev/null +++ b/crates/cad/tests/data/shapes_r12.dxf @@ -0,0 +1,448 @@ + 0 +SECTION + 2 +HEADER + 9 +$ACADVER + 1 +AC1009 + 9 +$DWGCODEPAGE + 3 +ANSI_1252 + 9 +$INSBASE + 10 +0 + 20 +0 + 30 +0 + 9 +$EXTMIN + 10 +10 + 20 +20 + 30 +0 + 9 +$EXTMAX + 10 +180 + 20 +90 + 30 +0 + 9 +$LIMMIN + 10 +0 + 20 +0 + 9 +$LIMMAX + 10 +200 + 20 +100 + 0 +ENDSEC + 0 +SECTION + 2 +TABLES + 0 +TABLE + 2 +VPORT + 70 +1 + 0 +VPORT + 2 +*ACTIVE + 70 +0 + 10 +0 + 20 +0 + 11 +1 + 21 +1 + 12 +95 + 22 +55 + 13 +0 + 23 +0 + 14 +1 + 24 +1 + 15 +10 + 25 +10 + 16 +0 + 26 +0 + 36 +1 + 17 +0 + 27 +0 + 37 +0 + 40 +124.666667 + 41 +1.5 + 42 +50 + 43 +0 + 44 +0 + 50 +0 + 51 +0 + 71 +0 + 72 +1000 + 73 +1 + 74 +3 + 75 +0 + 76 +0 + 77 +0 + 78 +0 + 0 +ENDTAB + 0 +TABLE + 2 +LTYPE + 70 +3 + 0 +LTYPE + 2 +ByBlock + 70 +0 + 3 + + 72 +65 + 73 +0 + 40 +0 + 0 +LTYPE + 2 +ByLayer + 70 +0 + 3 + + 72 +65 + 73 +0 + 40 +0 + 0 +LTYPE + 2 +Continuous + 70 +0 + 3 +Solid line + 72 +65 + 73 +0 + 40 +0 + 0 +ENDTAB + 0 +TABLE + 2 +LAYER + 70 +2 + 0 +LAYER + 2 +0 + 70 +0 + 62 +7 + 6 +Continuous + 0 +LAYER + 2 +LAYER_1 + 70 +0 + 62 +171 + 6 +Continuous + 0 +ENDTAB + 0 +TABLE + 2 +STYLE + 70 +1 + 0 +STYLE + 2 +Standard + 70 +0 + 40 +0 + 41 +1 + 50 +0 + 71 +0 + 42 +2.5 + 3 +txt + 4 + + 0 +ENDTAB + 0 +ENDSEC + 0 +SECTION + 2 +ENTITIES + 0 +POLYLINE + 8 +LAYER_1 + 62 +1 + 66 +1 + 10 +0 + 20 +0 + 30 +0 + 70 +1 + 0 +VERTEX + 8 +LAYER_1 + 62 +1 + 10 +10 + 20 +90 + 30 +0 + 0 +VERTEX + 8 +LAYER_1 + 62 +1 + 10 +110 + 20 +90 + 30 +0 + 0 +VERTEX + 8 +LAYER_1 + 62 +1 + 10 +110 + 20 +40 + 30 +0 + 0 +VERTEX + 8 +LAYER_1 + 62 +1 + 10 +10 + 20 +40 + 30 +0 + 0 +SEQEND + 8 +LAYER_1 + 62 +1 + 0 +POLYLINE + 8 +LAYER_1 + 62 +7 + 66 +1 + 10 +0 + 20 +0 + 30 +0 + 70 +1 + 40 +1 + 41 +1 + 0 +VERTEX + 8 +LAYER_1 + 62 +7 + 10 +10 + 20 +90 + 30 +0 + 0 +VERTEX + 8 +LAYER_1 + 62 +7 + 10 +110 + 20 +90 + 30 +0 + 0 +VERTEX + 8 +LAYER_1 + 62 +7 + 10 +110 + 20 +40 + 30 +0 + 0 +VERTEX + 8 +LAYER_1 + 62 +7 + 10 +10 + 20 +40 + 30 +0 + 0 +SEQEND + 8 +LAYER_1 + 62 +7 + 0 +POLYLINE + 8 +LAYER_1 + 62 +5 + 66 +1 + 10 +0 + 20 +0 + 30 +0 + 70 +1 + 40 +2 + 41 +2 + 0 +VERTEX + 8 +LAYER_1 + 62 +5 + 10 +120 + 20 +50 + 30 +0 + 42 +-2.414214 + 0 +VERTEX + 8 +LAYER_1 + 62 +5 + 10 +150 + 20 +20 + 30 +0 + 42 +-0.414214 + 0 +SEQEND + 8 +LAYER_1 + 62 +5 + 0 +ENDSEC + 0 +EOF diff --git a/crates/cad/tests/data/shapes_r2018.dxf b/crates/cad/tests/data/shapes_r2018.dxf new file mode 100644 index 0000000000..c29b89a037 --- /dev/null +++ b/crates/cad/tests/data/shapes_r2018.dxf @@ -0,0 +1,1146 @@ + 0 +SECTION + 2 +HEADER + 9 +$ACADVER + 1 +AC1032 + 9 +$DWGCODEPAGE + 3 +ANSI_1252 + 9 +$INSBASE + 10 +0 + 20 +0 + 30 +0 + 9 +$EXTMIN + 10 +10 + 20 +20 + 30 +0 + 9 +$EXTMAX + 10 +180 + 20 +90 + 30 +0 + 9 +$LIMMIN + 10 +0 + 20 +0 + 9 +$LIMMAX + 10 +200 + 20 +100 + 9 +$LWDISPLAY +290 +1 + 9 +$INSUNITS + 70 +0 + 9 +$MEASUREMENT + 70 +0 + 9 +$HANDSEED + 5 +3A + 0 +ENDSEC + 0 +SECTION + 2 +CLASSES + 0 +CLASS + 1 +ACDBDICTIONARYWDFLT + 2 +AcDbDictionaryWithDefault + 3 +ObjectDBX Classes + 90 +0 + 91 +0 +280 +0 +281 +0 + 0 +CLASS + 1 +ACDBPLACEHOLDER + 2 +AcDbPlaceHolder + 3 +ObjectDBX Classes + 90 +0 + 91 +0 +280 +0 +281 +0 + 0 +CLASS + 1 +LAYOUT + 2 +AcDbLayout + 3 +ObjectDBX Classes + 90 +0 + 91 +0 +280 +0 +281 +0 + 0 +ENDSEC + 0 +SECTION + 2 +TABLES + 0 +TABLE + 2 +VPORT + 5 +8 +330 +0 +100 +AcDbSymbolTable + 70 +1 + 0 +VPORT + 5 +15 +330 +8 +100 +AcDbSymbolTableRecord +100 +AcDbViewportTableRecord + 2 +*Active + 70 +0 + 10 +0 + 20 +0 + 11 +1 + 21 +1 + 12 +95 + 22 +55 + 13 +0 + 23 +0 + 14 +1 + 24 +1 + 15 +10 + 25 +10 + 16 +0 + 26 +0 + 36 +1 + 17 +0 + 27 +0 + 37 +0 + 40 +124.666667 + 41 +1.5 + 42 +50 + 43 +0 + 44 +0 + 50 +0 + 51 +0 + 71 +0 + 72 +1000 + 73 +1 + 74 +3 + 75 +0 + 76 +0 + 77 +0 + 78 +0 +281 +0 + 65 +0 +146 +0 + 0 +ENDTAB + 0 +TABLE + 2 +LTYPE + 5 +2 +330 +0 +100 +AcDbSymbolTable + 70 +3 + 0 +LTYPE + 5 +34 +330 +2 +100 +AcDbSymbolTableRecord +100 +AcDbLinetypeTableRecord + 2 +ByBlock + 70 +0 + 3 + + 72 +65 + 73 +0 + 40 +0 + 0 +LTYPE + 5 +35 +330 +2 +100 +AcDbSymbolTableRecord +100 +AcDbLinetypeTableRecord + 2 +ByLayer + 70 +0 + 3 + + 72 +65 + 73 +0 + 40 +0 + 0 +LTYPE + 5 +36 +330 +2 +100 +AcDbSymbolTableRecord +100 +AcDbLinetypeTableRecord + 2 +Continuous + 70 +0 + 3 +Solid line + 72 +65 + 73 +0 + 40 +0 + 0 +ENDTAB + 0 +TABLE + 2 +LAYER + 5 +1 +330 +0 +100 +AcDbSymbolTable + 70 +2 + 0 +LAYER + 5 +37 +330 +1 +100 +AcDbSymbolTableRecord +100 +AcDbLayerTableRecord + 2 +0 + 70 +0 + 62 +7 + 6 +Continuous +290 +1 +370 +-3 +390 +1B + 0 +LAYER + 5 +38 +330 +1 +100 +AcDbSymbolTableRecord +100 +AcDbLayerTableRecord + 2 +Layer 1 + 70 +0 + 62 +171 + 6 +Continuous +290 +1 +370 +-3 +390 +1B + 0 +ENDTAB + 0 +TABLE + 2 +STYLE + 5 +5 +330 +0 +100 +AcDbSymbolTable + 70 +1 + 0 +STYLE + 5 +39 +330 +5 +100 +AcDbSymbolTableRecord +100 +AcDbTextStyleTableRecord + 2 +Standard + 70 +0 + 40 +0 + 41 +1 + 50 +0 + 71 +0 + 42 +2.5 + 3 +txt + 4 + + 0 +ENDTAB + 0 +TABLE + 2 +VIEW + 5 +7 +330 +0 +100 +AcDbSymbolTable + 70 +0 + 0 +ENDTAB + 0 +TABLE + 2 +UCS + 5 +6 +330 +0 +100 +AcDbSymbolTable + 70 +0 + 0 +ENDTAB + 0 +TABLE + 2 +APPID + 5 +3 +330 +0 +100 +AcDbSymbolTable + 70 +1 + 0 +APPID + 5 +16 +330 +3 +100 +AcDbSymbolTableRecord +100 +AcDbRegAppTableRecord + 2 +ACAD + 70 +0 + 0 +ENDTAB + 0 +TABLE + 2 +DIMSTYLE + 5 +4 +330 +0 +100 +AcDbSymbolTable + 70 +1 +100 +AcDbDimStyleTable + 0 +DIMSTYLE +105 +17 +330 +4 +100 +AcDbSymbolTableRecord +100 +AcDbDimStyleTableRecord + 2 +Standard + 70 +0 + 0 +ENDTAB + 0 +TABLE + 2 +BLOCK_RECORD + 5 +9 +330 +0 +100 +AcDbSymbolTable + 70 +2 + 0 +BLOCK_RECORD + 5 +D +330 +9 +100 +AcDbSymbolTableRecord +100 +AcDbBlockTableRecord + 2 +*Model_Space +340 +13 + 70 +0 +280 +1 +281 +0 + 0 +BLOCK_RECORD + 5 +E +330 +9 +100 +AcDbSymbolTableRecord +100 +AcDbBlockTableRecord + 2 +*Paper_Space +340 +14 + 70 +0 +280 +1 +281 +0 + 0 +ENDTAB + 0 +ENDSEC + 0 +SECTION + 2 +BLOCKS + 0 +BLOCK + 5 +F +330 +D +100 +AcDbEntity + 8 +0 +100 +AcDbBlockBegin + 2 +*Model_Space + 70 +0 + 10 +0 + 20 +0 + 30 +0 + 3 +*Model_Space + 1 + + 0 +ENDBLK + 5 +10 +330 +D +100 +AcDbEntity + 8 +0 +100 +AcDbBlockEnd + 0 +BLOCK + 5 +11 +330 +E +100 +AcDbEntity + 8 +0 +100 +AcDbBlockBegin + 2 +*Paper_Space + 70 +0 + 10 +0 + 20 +0 + 30 +0 + 3 +*Paper_Space + 1 + + 0 +ENDBLK + 5 +12 +330 +E +100 +AcDbEntity + 8 +0 +100 +AcDbBlockEnd + 0 +ENDSEC + 0 +SECTION + 2 +ENTITIES + 0 +LWPOLYLINE + 5 +30 +330 +D +100 +AcDbEntity + 8 +Layer 1 + 62 +1 +420 +16711680 +100 +AcDbPolyline + 90 +4 + 70 +1 + 10 +10 + 20 +90 + 10 +110 + 20 +90 + 10 +110 + 20 +40 + 10 +10 + 20 +40 + 0 +HATCH + 5 +31 +330 +D +100 +AcDbEntity + 8 +Layer 1 + 62 +1 +420 +16711680 +100 +AcDbHatch + 10 +0 + 20 +0 + 30 +0 +210 +0 +220 +0 +230 +1 + 2 +SOLID + 70 +1 + 71 +0 + 91 +1 + 92 +3 + 72 +0 + 73 +1 + 93 +4 + 10 +10 + 20 +90 + 10 +110 + 20 +90 + 10 +110 + 20 +40 + 10 +10 + 20 +40 + 97 +0 + 75 +0 + 76 +1 + 98 +0 + 0 +LWPOLYLINE + 5 +32 +330 +D +100 +AcDbEntity + 8 +Layer 1 + 62 +7 +370 +35 +420 +0 +100 +AcDbPolyline + 90 +4 + 70 +1 + 10 +10 + 20 +90 + 10 +110 + 20 +90 + 10 +110 + 20 +40 + 10 +10 + 20 +40 + 0 +CIRCLE + 5 +33 +330 +D +100 +AcDbEntity + 8 +Layer 1 + 62 +5 +370 +70 +420 +255 +100 +AcDbCircle + 10 +150 + 20 +50 + 30 +0 + 40 +30 +210 +0 +220 +0 +230 +1 + 0 +ENDSEC + 0 +SECTION + 2 +OBJECTS + 0 +DICTIONARY + 5 +A +330 +0 +100 +AcDbDictionary +281 +1 + 3 +ACAD_GROUP +350 +B + 3 +ACAD_LAYOUT +350 +C + 3 +ACAD_PLOTSTYLENAME +350 +1A + 0 +DICTIONARY + 5 +B +330 +A +100 +AcDbDictionary +281 +1 + 0 +DICTIONARY + 5 +C +330 +A +100 +AcDbDictionary +281 +1 + 3 +Layout1 +350 +14 + 3 +Model +350 +13 + 0 +ACDBDICTIONARYWDFLT + 5 +1A +330 +A +100 +AcDbDictionary +281 +1 + 3 +Normal +350 +1B +100 +AcDbDictionaryWithDefault +340 +1B + 0 +ACDBPLACEHOLDER + 5 +1B +330 +1A + 0 +LAYOUT + 5 +13 +330 +C +100 +AcDbPlotSettings + 1 + + 2 +none_device + 4 + + 6 + + 40 +0 + 41 +0 + 42 +0 + 43 +0 + 44 +0 + 45 +0 + 46 +0 + 47 +0 + 48 +0 + 49 +0 +140 +0 +141 +0 +142 +1 +143 +1 + 70 +1712 + 72 +1 + 73 +0 + 74 +5 + 7 + + 75 +16 + 76 +0 + 77 +2 + 78 +300 +147 +1 +148 +0 +149 +0 +100 +AcDbLayout + 1 +Model + 70 +1 + 71 +0 + 10 +0 + 20 +0 + 11 +200 + 21 +100 + 12 +0 + 22 +0 + 32 +0 + 14 +10 + 24 +20 + 34 +0 + 15 +180 + 25 +90 + 35 +0 +146 +0 + 13 +0 + 23 +0 + 33 +0 + 16 +1 + 26 +0 + 36 +0 + 17 +0 + 27 +1 + 37 +0 + 76 +1 +330 +D + 0 +LAYOUT + 5 +14 +330 +C +100 +AcDbPlotSettings + 1 + + 2 +none_device + 4 + + 6 + + 40 +0 + 41 +0 + 42 +0 + 43 +0 + 44 +0 + 45 +0 + 46 +0 + 47 +0 + 48 +0 + 49 +0 +140 +0 +141 +0 +142 +1 +143 +1 + 70 +688 + 72 +1 + 73 +0 + 74 +5 + 7 + + 75 +16 + 76 +0 + 77 +2 + 78 +300 +147 +1 +148 +0 +149 +0 +100 +AcDbLayout + 1 +Layout1 + 70 +1 + 71 +1 + 10 +0 + 20 +0 + 11 +200 + 21 +100 + 12 +0 + 22 +0 + 32 +0 + 14 +10 + 24 +20 + 34 +0 + 15 +180 + 25 +90 + 35 +0 +146 +0 + 13 +0 + 23 +0 + 33 +0 + 16 +1 + 26 +0 + 36 +0 + 17 +0 + 27 +1 + 37 +0 + 76 +1 +330 +E + 0 +ENDSEC + 0 +EOF diff --git a/crates/doc/src/cmyk.rs b/crates/doc/src/cmyk.rs index 6339f0a4ca..60a6db4074 100644 --- a/crates/doc/src/cmyk.rs +++ b/crates/doc/src/cmyk.rs @@ -664,9 +664,6 @@ pub fn jpeg_with_icc(bytes: &[u8], icc: &[u8]) -> Option> { const CHUNK: usize = 0xFFFF - 2 - ICC_SEGMENT.len() - 2; let chunks: Vec<&[u8]> = icc.chunks(CHUNK).collect(); let count = u8::try_from(chunks.len()).ok().filter(|n| *n > 0)?; - if !bytes.starts_with(&[0xFF, 0xD8]) { - return None; - } let mut segments = Vec::with_capacity(icc.len() + 18 * chunks.len()); for (i, chunk) in chunks.iter().enumerate() { let len = u16::try_from(chunk.len() + 2 + ICC_SEGMENT.len() + 2).ok()?; @@ -676,6 +673,23 @@ pub fn jpeg_with_icc(bytes: &[u8], icc: &[u8]) -> Option> { segments.extend_from_slice(&[u8::try_from(i + 1).ok()?, count]); segments.extend_from_slice(chunk); } + with_icc_segments(bytes, segments) +} + +/// JPEG `bytes` without the ICC profile they carry: every `ICC_PROFILE` APP2 segment before the +/// scan taken out, and the other segments and the scan as they are. `None` for bytes whose +/// segments before the scan can't be read. +pub fn jpeg_without_icc(bytes: &[u8]) -> Option> { + with_icc_segments(bytes, vec![]) +} + +/// JPEG `bytes` with every `ICC_PROFILE` APP2 segment before the scan taken out and `segments` +/// written after the leading application segments; `None` when the bytes don't start a JPEG or +/// their segments before the scan can't be read. +fn with_icc_segments(bytes: &[u8], segments: Vec) -> Option> { + if !bytes.starts_with(&[0xFF, 0xD8]) { + return None; + } let mut out = Vec::with_capacity(bytes.len() + segments.len()); out.extend_from_slice(&[0xFF, 0xD8]); let mut icc_segments = Some(segments); diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index 04b48634ed..85182e9f36 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -266,6 +266,7 @@ pub fn hit_test_visible_skipping(doc: &Document, p: Point, opt: HitOptions, skip /// (`opt.scope`) or on a locked artboard. On a layer whose Preview is off it counts by its /// outline, as a click there hits it. pub fn selected_hidden_at(doc: &Document, p: Point, opt: HitOptions, selected: &[NodeId]) -> Option { + let _walk = ArtWalk::open(); let symbols = doc.symbol_boxes(); let locks = doc.locked_artboards(); selected.iter().rev().copied().find(|&id| { @@ -322,30 +323,31 @@ fn path_options(nodes: &[&Node], chain: &[NodeId], opt: HitOptions) -> Option) -> Vec { + let _walk = ArtWalk::open(); let opt = HitOptions { scope: scope.or(opt.scope), ..opt }; // Normally one hit test per *object* suffices: layers and sublayers aren't selectable, // while a group (including a clipping group) is selected as one object. Repeatedly // searching the full tree for each hit made a stack of n overlapping paths O(n^2). // Isolation and Edit Contents change where selection groups begin; keep the original // traversal for those cases rather than change their Select Behind semantics. - if opt.scope.is_some() { + // Malformed files may contain non-layer roots; let the general traversal handle them. + if opt.scope.is_some() || doc.layers.iter().any(|l| !l.is_layer()) { return objects_at_repeated(doc, p, opt, scope); } let mut tops = Vec::new(); let mut seen = HashSet::new(); let symbols = doc.symbol_boxes(); for layer in doc.layers.iter().rev() { - // Malformed files may contain non-layer roots; let the general traversal handle them. - if !layer.is_layer() { - return objects_at_repeated(doc, p, opt, scope); - } if !layer.visible || layer.locked || layer.is_template() || doc.pattern_edit.as_ref().is_some_and(|e| e.layer != layer.id) { continue; } if !objects_at_layer(layer, p, opt, &symbols, &mut tops, &mut seen) { // An envelope in Edit Contents may expose objects *within* a top-level group. - // The repeated traversal handles that mixed hierarchy precisely. - return objects_at_repeated(doc, p, opt, scope); + // The repeated traversal handles that mixed hierarchy precisely. The objects found + // so far lie above the envelope and stay first; the repeated traversal finds the + // rest with what is left of the limit of symbol art to walk. + tops = objects_at_repeated_after(doc, p, opt, scope, tops); + break; } } // The objects on a locked artboard can't be selected, as `hit_test_skipping` passes over them. @@ -409,7 +411,11 @@ fn objects_at_layer(layer: &Node, p: Point, opt: HitOptions, symbols: &SymbolBox /// The general selection order also handles isolation and nested Edit Contents. fn objects_at_repeated(doc: &Document, p: Point, opt: HitOptions, scope: Option) -> Vec { - let mut tops: Vec = vec![]; + objects_at_repeated_after(doc, p, opt, scope, vec![]) +} + +/// [`objects_at_repeated`] after `tops`, the topmost objects under `p` already found. +fn objects_at_repeated_after(doc: &Document, p: Point, opt: HitOptions, scope: Option, mut tops: Vec) -> Vec { // Each round leaves out the objects found so far (and everything inside them). while let Some(top) = hit_test_skipping(doc, p, opt, &|id| tops.contains(&id), true).map(|h| h.top_object(scope)) { if tops.contains(&top) { @@ -429,6 +435,7 @@ pub const MAX_LOCKED_AT: usize = 20; /// out. While a pattern is edited only its tile layer is searched, and in isolation mode /// (`opt.scope`) only what is inside the isolated group or object. pub fn locked_objects_at(doc: &Document, p: Point, opt: HitOptions) -> Vec { + let _walk = ArtWalk::open(); let symbols = doc.symbol_boxes(); let mut out = Vec::new(); if let Some(scope) = opt.scope @@ -506,6 +513,7 @@ fn object_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, editab /// an isolated group on one ([`crate::LockedArtboards::holds`]). Symbol instances are measured by their art /// ([`Node::geometric_bounds_with`]), and are also hit outside that box where their art paints. fn hit_test_skipping(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(NodeId) -> bool, editable_only: bool) -> Option { + let _walk = ArtWalk::open(); let finish = |mut h: Hit| { h.contents_of = h.ancestry.iter().rev().copied().find(|a| doc.node(*a).is_some_and(edits_contents)); h.layers = h.ancestry.iter().take_while(|a| doc.node(**a).is_some_and(Node::is_layer)).count(); @@ -1059,9 +1067,10 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio n.geometric_bounds_with(symbols).filter(|b| b.inflate(opt.tol, opt.tol).contains(p)).map(|_| HitKind::Bounds) } // A symbol instance is hit within its bounds, and outside them where its art paints - // ([`instance_art_hit`]). + // ([`instance_art_hit`]). In the art of another instance walked outside that instance's + // bounds, it is hit only where its own art paints ([`ArtOnly`]). NodeKind::SymbolInstance { .. } => { - if n.geometric_bounds_with(symbols).is_some_and(|b| b.inflate(opt.tol, opt.tol).contains(p)) { + if !ArtOnly::on() && n.geometric_bounds_with(symbols).is_some_and(|b| b.inflate(opt.tol, opt.tol).contains(p)) { return Some(HitKind::Bounds); } instance_art_hit(n, p, opt, symbols) @@ -1113,10 +1122,12 @@ fn on_type_path(n: &Node, t: &crate::TextObject, p: Point, tol: f64) -> bool { stroke_contains(&path.to_bezpath(), 0.0, tol, p) } -/// Hit anywhere in an evaluated subtree (groups recurse; leaves use [`hit_leaf`]). +/// Hit anywhere in an evaluated subtree (groups recurse; leaves use [`hit_leaf`]). In symbol art +/// placed by [`FindPart`], each object visited takes one object of the [`ArtWalk`] limit, and +/// nothing more is tested once the limit is used up. fn hit_any(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option { // Hidden art does not hit. - if !n.visible { + if !n.visible || ArtWalk::charged() && !ArtWalk::take(1) { return None; } // Nor art whose reach does not hold `p`, as in [`may_hit`]: a blend's steps far from `p` are @@ -1172,6 +1183,15 @@ impl<'a> InstanceArt<'a> { whole.or_else(|| self.map.as_ref()?.one_cell_with(n, &self.boxes)) } + /// How many objects placing the whole art makes: the objects of the art with their opacity + /// masks' art ([`Node::count_with_masks`]), or, through the guides, the most that + /// [`crate::NineSliceMap::most_placed_with`] counts. + fn size(&self) -> u64 { + self.map + .as_ref() + .map_or_else(|| u64::try_from(self.art.count_with_masks()).unwrap_or(u64::MAX), |m| m.most_placed_with(&self.art, &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 @@ -1219,6 +1239,7 @@ fn moved(n: &Node, xf: vectorcraft_geom::Affine) -> Node { /// 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> { + let _walk = ArtWalk::open(); let art = InstanceArt::of(doc, inst)?; let symbols = doc.symbol_boxes(); let mut path = vec![]; @@ -1239,8 +1260,12 @@ struct FindPart<'a> { } impl FindPart<'_> { + /// What a click at `p` hits on object `n` of the art, placed. [`hit_any`] takes `n` and each + /// object it visits inside `n` from the [`ArtWalk`] limit. fn hit(&self, n: &Node, whole: Option, opt: HitOptions) -> Option { - self.art.place(n, whole).and_then(|n| hit_any(&n, self.p, opt, self.symbols)) + let placed = self.art.place(n, whole)?; + let _charged = ArtWalk::charge(); + hit_any(&placed, self.p, opt, self.symbols) } fn skips_guide(&self, n: &Node) -> bool { @@ -1250,7 +1275,7 @@ impl FindPart<'_> { /// What a click at `p` hits on object `n` of the art, with `path` the child indices that lead /// to what it hits. `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) -> Option { - if !n.visible || !self.whole_instance && (n.locked || n.is_template()) || self.skips_guide(n) { + if !n.visible || !self.whole_instance && (n.locked || n.is_template()) || self.skips_guide(n) || ArtWalk::used_up() { return None; } let outline = outline || previews_off(n); @@ -1259,6 +1284,9 @@ impl FindPart<'_> { if path.len() >= crate::symbol_overrides::MAX_PATH_DEPTH { return self.hit(n, whole, opt); } + if !ArtWalk::take(1) { + return None; + } let whole = self.art.whole(n, whole); if n.clips() && let Some(first) = children.first() @@ -1298,17 +1326,146 @@ impl FindPart<'_> { /// Outline, [`HitOptions::outline`]): its strokes, and the art that the live geometry effects of a /// clipping path in it show past the art's box. `None` for an instance of a missing symbol, of a /// symbol that holds an instance of itself or nests too deep ([`SymbolBoxes::art`]), and of art past -/// the 9-slice object limit ([`InstanceArt::of`]). +/// the 9-slice object limit ([`InstanceArt::of`]), when `p` is outside the instance's reach +/// ([`Node::reach_bounds_with`]), and once the click has visited as many objects of symbol art as +/// [`ArtWalk`] allows. fn instance_art_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option { let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return None }; - if opt.outline || symbols.art(symbol).is_none() { + if opt.outline || symbols.art(symbol).is_none() || !n.reach_bounds_with(symbols).is_some_and(|b| b.inflate(opt.tol, opt.tol).contains(p)) { + return None; + } + let _walk = ArtWalk::open(); + if ArtWalk::used_up() { return None; } let art = InstanceArt::of(symbols.document(), n)?; + #[cfg(test)] + ARTS_WALKED.with(|c| c.set(c.get() + 1)); let opt = HitOptions { clip_outlines: false, ..opt }; + let _art_only = ArtOnly::set(); FindPart { art: &art, p, opt, symbols, whole_instance: true }.find(&art.art, &mut vec![], None, false) } +thread_local! { + /// Whether a symbol instance's art is being walked outside the instance's box ([`ArtOnly`]). + static ART_ONLY: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// While a guard lives, a symbol instance is hit ([`hit_leaf`]) and touched by a marquee +/// ([`marquee_with`]) only where its own art is, by the same rule at every level, and not anywhere +/// in its box. [`instance_art_hit`] and the marquee's walk of an instance's art hold one: they walk +/// the art outside the instance's box, where the box of an instance nested in the art can reach +/// past it over empty space. +struct ArtOnly { + was: bool, +} + +impl ArtOnly { + fn set() -> Self { + Self { was: ART_ONLY.replace(true) } + } + + fn on() -> bool { + ART_ONLY.get() + } +} + +impl Drop for ArtOnly { + fn drop(&mut self) { + ART_ONLY.set(self.was); + } +} + +thread_local! { + /// How many more objects of symbol art the click or marquee under way may visit ([`ArtWalk`]), + /// `None` outside one. + static ART_WALK_LEFT: std::cell::Cell> = const { std::cell::Cell::new(None) }; + /// Whether [`hit_any`] is testing symbol art that [`FindPart`] placed ([`ArtWalk::charge`]). + static ART_WALK_CHARGED: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +#[cfg(test)] +thread_local! { + /// The number of objects [`ArtWalk::open`] allows on this thread in place of + /// [`crate::MAX_SYMBOL_NODES`]. + static ART_WALK_LIMIT: std::cell::Cell> = const { std::cell::Cell::new(None) }; + /// How many symbol instances' art clicks and marquees walked on this thread. + static ARTS_WALKED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The objects of symbol art that one click or one marquee may visit: [`crate::MAX_SYMBOL_NODES`] +/// in all, the art of the instances nested in that art included, at every level. The first +/// [`ArtWalk::open`] of a click or a marquee sets the limit, and the walks opened while its guard +/// lives share it. Once the limit is used up, an instance is no longer hit or touched outside its +/// box; inside its box it still is. +struct ArtWalk { + outermost: bool, +} + +impl ArtWalk { + fn open() -> Self { + let walk = Self { outermost: ART_WALK_LEFT.get().is_none() }; + walk.restart(); + walk + } + + /// For the outermost guard, sets what is left back to the whole limit. + fn restart(&self) { + if self.outermost { + #[cfg(test)] + let limit = ART_WALK_LIMIT.get().unwrap_or(crate::MAX_SYMBOL_NODES); + #[cfg(not(test))] + let limit = crate::MAX_SYMBOL_NODES; + ART_WALK_LEFT.set(Some(limit)); + } + } + + /// Is nothing left? + fn used_up() -> bool { + ART_WALK_LEFT.get() == Some(0) + } + + /// Takes `n` objects from what is left. `false` when fewer are left, and nothing is left after. + fn take(n: u64) -> bool { + let Some(left) = ART_WALK_LEFT.get() else { return true }; + let rest = left.checked_sub(n); + ART_WALK_LEFT.set(Some(rest.unwrap_or(0))); + rest.is_some() + } + + /// While the guard lives, each object [`hit_any`] visits takes one object from what is left: + /// [`FindPart`] holds one while it tests a placed object of symbol art, so that the members of an + /// Intertwine group, and the objects of groups nested deeper than + /// [`crate::symbol_overrides::MAX_PATH_DEPTH`], count toward the limit. + fn charge() -> ArtWalkCharge { + ArtWalkCharge { was: ART_WALK_CHARGED.replace(true) } + } + + /// Does [`hit_any`] take the objects it visits from what is left ([`Self::charge`])? + fn charged() -> bool { + ART_WALK_CHARGED.get() + } +} + +impl Drop for ArtWalk { + fn drop(&mut self) { + if self.outermost { + ART_WALK_LEFT.set(None); + } + } +} + +/// The guard of [`ArtWalk::charge`]. +struct ArtWalkCharge { + was: bool, +} + +impl Drop for ArtWalkCharge { + fn drop(&mut self) { + ART_WALK_CHARGED.set(self.was); + } +} + /// 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. @@ -1502,6 +1659,7 @@ fn previews_off(n: &Node) -> bool { } fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, whole_compounds: bool, outline: bool) -> Vec { + let _walk = ArtWalk::open(); let mut out = Vec::new(); // The objects the marquee may touch ([`Top`]). let tops: Vec = match scope.and_then(|s| doc.node(s)) { @@ -1613,8 +1771,9 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh 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 symbol instance is touched by its box, and outside it where the live geometry - // effects of a clipping path in its art show the art. - NodeKind::SymbolInstance { .. } => box_touches(n, s, r) || !outline && instance_art_touches(n, s, r, whole_compounds), + // effects of a clipping path in its art show the art. In the art of another instance + // walked outside that instance's box, it is touched only by its own art ([`ArtOnly`]). + NodeKind::SymbolInstance { .. } => !ArtOnly::on() && box_touches(n, s, r) || !outline && instance_art_touches(n, s, r, whole_compounds), _ => box_touches(n, s, r), } } @@ -1628,15 +1787,26 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh } /// Does the marquee `r` touch the art of symbol instance `n` placed as the canvas draws it, as /// it touches a group of that art? Only for art whose clipping paths have live geometry effects - /// ([`SymbolBoxes::art`]), and only when `r` meets the instance's reach - /// ([`Node::reach_bounds_with`]): elsewhere the art lies within the instance's box. + /// ([`SymbolBoxes::art`]), or for any art while [`ArtOnly`] is on, and only when `r` meets the + /// instance's reach ([`Node::reach_bounds_with`]): elsewhere the art lies within the instance's + /// box. Not once the marquee has placed as many objects of symbol art as [`ArtWalk`] allows. fn instance_art_touches(n: &Node, s: &SymbolBoxes, r: Rect, whole_compounds: bool) -> bool { let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return false }; let meets = |b: Rect| b.x0 <= r.x1 && r.x0 <= b.x1 && b.y0 <= r.y1 && r.y0 <= b.y1; - if s.art(symbol).is_none_or(|a| a.reshaped.is_none()) || !n.reach_bounds_with(s).is_some_and(meets) { + if s.art(symbol).is_none_or(|a| a.reshaped.is_none() && !ArtOnly::on()) || !n.reach_bounds_with(s).is_some_and(meets) { + return false; + } + let _walk = ArtWalk::open(); + if ArtWalk::used_up() { return false; } let Some(art) = InstanceArt::of(s.document(), n) else { return false }; + if !ArtWalk::take(art.size()) { + return false; + } + #[cfg(test)] + ARTS_WALKED.with(|c| c.set(c.get() + 1)); + let _art_only = ArtOnly::set(); art.place(&art.art, None).is_some_and(|placed| placed.visible && touches(&placed, s, r, None, whole_compounds, false)) } fn collect_leaves(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option, whole_compounds: bool, outline: bool, out: &mut Vec) { diff --git a/crates/doc/src/hit/tests.rs b/crates/doc/src/hit/tests.rs index 1c817f2bf1..9ca784c1f4 100644 --- a/crates/doc/src/hit/tests.rs +++ b/crates/doc/src/hit/tests.rs @@ -1452,6 +1452,76 @@ fn objects_at_edit_contents_uses_general_order() { assert_eq!(objects_at(&d, p, opt, None), vec![b, a]); } +/// Select Behind keeps one limit of symbol art to walk when it falls back to the general +/// traversal, for an envelope in Edit Contents and for a root that is not a layer: the fallback +/// walks no more art than what the first pass left, and keeps what the first pass found. +#[test] +fn select_behind_keeps_one_art_limit_when_it_falls_back() { + // 60 instances of `Clipped` with the rectangle hidden, which a click at (150, 50) walks the art + // of and misses: each walk takes 3 objects of the 100. + let stack = |d: &mut Document, count: usize| { + let l = d.layers[0].id; + for _ in 0..count { + let inst = instance_of(d, "Clipped"); + d.insert(Some(l), usize::MAX, Arc::unwrap_or_clone(inst)).unwrap(); + } + }; + // An envelope in Edit Contents at the bottom of the layer, its contents under (150, 50). + let envelope = |d: &mut Document| { + let inner = |id| Arc::new(Node::path(id, shapes::rectangle(Rect::new(120.0, 20.0, 180.0, 80.0)), Appearance::default_art())); + let (a, b) = (d.alloc_id(), d.alloc_id()); + let e = Node::new( + d.alloc_id(), + NodeKind::Envelope { + content: vec![inner(a), inner(b)], + kind: Box::new(crate::live::EnvelopeKind::Warp { style: "arc".to_string(), bend: 0.0, h: 0.0, v: 0.0, horizontal: true, version: 0 }), + fidelity: 100.0, + editing: true, + options: Default::default(), + frame: Box::new(vectorcraft_geom::Affine::IDENTITY), + }, + ); + let l = d.layers[0].id; + d.insert(Some(l), 0, e).unwrap(); + (a, b) + }; + let p = Point::new(150.0, 50.0); + let mut d = Document::new(600.0, 400.0); + clipped_symbol(&mut d, false); + let (a, b) = envelope(&mut d); + stack(&mut d, 60); + let (behind, _, arts) = with_art_limit(100, || objects_at(&d, p, HitOptions::default(), None)); + assert_eq!(behind, vec![b, a]); + assert!(arts <= 34, "envelope in Edit Contents: {arts} instances' art walked"); + // An instance that the first pass hits by its art, the limit then used up, stays in the list: + // `Shown` is `Clipped` with its rectangle shown, below 32 instances of `Clipped`. + let mut d = Document::new(600.0, 400.0); + clipped_symbol(&mut d, false); + let (a, b) = envelope(&mut d); + let (mut mask, art) = half_clipped(&mut d); + mask.appearance.effects.push(test_move()); + let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(art)]); + clip.set_clips(true); + group_symbol(&mut d, "Shown", vec![Arc::new(clip)]); + let hit = instance_of(&mut d, "Shown"); + let hit_id = hit.id; + let l = d.layers[0].id; + d.insert(Some(l), usize::MAX, Arc::unwrap_or_clone(hit)).unwrap(); + stack(&mut d, 32); + let (behind, _, arts) = with_art_limit(100, || objects_at(&d, p, HitOptions::default(), None)); + assert_eq!(behind, vec![hit_id, b, a], "hit before the fallback"); + assert!(arts <= 34, "hit before the fallback: {arts} instances' art walked"); + // A root that is not a layer, below the layer. + let mut d = Document::new(600.0, 400.0); + clipped_symbol(&mut d, false); + stack(&mut d, 60); + let root = Arc::new(Node::group(d.alloc_id(), vec![])); + d.layers.insert(0, root); + let (behind, _, arts) = with_art_limit(100, || objects_at(&d, p, HitOptions::default(), None)); + assert!(behind.is_empty()); + assert!(arts <= 34, "root that is not a layer: {arts} instances' art walked"); +} + #[test] fn locked_and_hidden_skip() { let mut d = Document::new(200.0, 200.0); @@ -1961,6 +2031,216 @@ fn a_symbol_instance_is_hit_on_the_stroke_of_its_art_past_its_box() { assert_eq!(at(108.0, HitOptions { outline: true, ..HitOptions::default() }), None, "Outline view"); } +/// Outside a symbol instance's box, an instance nested in its art counts where its own art is, not +/// anywhere in its box: a click or a marquee on empty space in the nested box, where a moved +/// clipping path shows the art past the outer box, selects nothing, and on art drawn there it +/// selects the outer instance. +#[test] +fn a_nested_symbol_instances_box_past_the_outer_box_is_not_a_hit() { + set_clip_region(moved_clip_region); + // `Two` draws squares at the corners of 0..200 × 0..100, and with `middle` one at 140..160 × + // 40..60. The outer symbol clips an instance of it to 0..100 × 0..100, which `test.move` moves + // to 100..200: the outer box is 0..100, the nested box 0..200. + let build = |middle: bool| { + let mut d = Document::new(600.0, 400.0); + let l = d.layers[0].id; + let square = |d: &mut Document, r: Rect| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(r), Appearance::default_art())); + let mut squares = vec![square(&mut d, Rect::new(0.0, 0.0, 10.0, 10.0)), square(&mut d, Rect::new(190.0, 90.0, 200.0, 100.0))]; + if middle { + squares.push(square(&mut d, Rect::new(140.0, 40.0, 160.0, 60.0))); + } + group_symbol(&mut d, "Two", squares); + let (mut mask, _) = half_clipped(&mut d); + mask.appearance.effects.push(test_move()); + let nested = instance_of(&mut d, "Two"); + let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), nested]); + clip.set_clips(true); + group_symbol(&mut d, "Outer", vec![Arc::new(clip)]); + let inst = d.alloc_id(); + d.insert(Some(l), 0, Node::new(inst, NodeKind::SymbolInstance { symbol: "Outer".into(), xf: vectorcraft_geom::Affine::IDENTITY })).unwrap(); + (d, inst) + }; + let at = |d: &Document, x: f64, y: f64| hit_test(d, Point::new(x, y), HitOptions::default()).map(|h| h.leaf); + let inside = Rect::new(145.0, 45.0, 155.0, 55.0); + let (d, inst) = build(false); + assert_eq!(at(&d, 150.0, 50.0), None, "empty space in the nested box"); + assert!(marquee(&d, inside, None, false).is_empty(), "marquee on empty space in the nested box"); + assert_eq!(at(&d, 195.0, 95.0), Some(inst), "on the nested art past the outer box"); + assert_eq!(at(&d, 50.0, 50.0), Some(inst), "in the outer box"); + let (d, inst) = build(true); + assert_eq!(at(&d, 150.0, 50.0), Some(inst), "on the nested art"); + // Across the middle square's left edge. + assert_eq!(marquee(&d, Rect::new(135.0, 45.0, 145.0, 55.0), None, false), [inst], "marquee on the nested art"); +} + +/// Adds the symbol `Clipped`: a clip group whose clipping path's region `test.move` moves to +/// 100..200 × 0..100, past the 0..100 box, over a 0..200 × 0..100 rectangle shown when `shown`. +/// A click at (150, 50) hits an instance of it on the rectangle, or, with the rectangle hidden, +/// walks its art and finds nothing. +fn clipped_symbol(d: &mut Document, shown: bool) { + set_clip_region(moved_clip_region); + let (mut mask, mut art) = half_clipped(d); + mask.appearance.effects.push(test_move()); + art.visible = shown; + let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(art)]); + clip.set_clips(true); + let root = Node::group(d.alloc_id(), vec![Arc::new(clip)]); + d.symbols.push(crate::Symbol { dynamic: false, name: "Clipped".into(), art: Arc::new(root) }); +} + +/// A symbol named `name` whose art is a group of `members`. +fn group_symbol(d: &mut Document, name: &str, members: Vec>) { + let root = Node::group(d.alloc_id(), members); + d.symbols.push(crate::Symbol { dynamic: false, name: name.into(), art: Arc::new(root) }); +} + +/// An instance of the symbol named `symbol`, not moved. +fn instance_of(d: &mut Document, symbol: &str) -> Arc { + Arc::new(Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: symbol.into(), xf: vectorcraft_geom::Affine::IDENTITY })) +} + +/// 30 small squares at the origin, which a click at (150, 50) passes by. +fn far_squares(d: &mut Document) -> Vec> { + (0..30).map(|_| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), Appearance::default_art()))).collect() +} + +/// Runs `f` with [`ArtWalk`] allowing `limit` objects, and returns its result with how many +/// leaves [`hit_leaf`] tested and how many instances' art was walked meanwhile. +fn with_art_limit(limit: u64, f: impl FnOnce() -> R) -> (R, usize, usize) { + ART_WALK_LIMIT.with(|c| c.set(Some(limit))); + LEAVES_TESTED.with(|c| c.set(0)); + ARTS_WALKED.with(|c| c.set(0)); + let r = f(); + ART_WALK_LIMIT.with(|c| c.set(None)); + (r, LEAVES_TESTED.with(std::cell::Cell::get), ARTS_WALKED.with(std::cell::Cell::get)) +} + +/// One click visits at most the art walk's limit of objects in a chain of nested symbol +/// instances, though each level's art alone is well within it. A click on the art of an +/// instance nested in another is still found. +#[test] +fn a_click_walks_a_chain_of_nested_symbol_instances_within_one_limit() { + // Level 0 is `Clipped`; each level above holds an instance of the level below and 30 squares: + // 32 objects to visit at each level. + let chain = |shown: bool| { + let mut d = Document::new(600.0, 400.0); + let l = d.layers[0].id; + clipped_symbol(&mut d, shown); + for level in 1..12 { + let below = if level == 1 { "Clipped".to_string() } else { format!("Level {}", level - 1) }; + let mut members = vec![instance_of(&mut d, &below)]; + members.extend(far_squares(&mut d)); + group_symbol(&mut d, &format!("Level {level}"), members); + } + let inst = instance_of(&mut d, "Level 11"); + let id = inst.id; + d.insert(Some(l), 0, Arc::unwrap_or_clone(inst)).unwrap(); + (d, id) + }; + let at = |d: &Document, x: f64| hit_test(d, Point::new(x, 50.0), HitOptions::default()).map(|h| h.leaf); + // Without one limit for the click, the miss walks the art of all 12 levels. + let (d, inst) = chain(false); + let (hit, _, arts) = with_art_limit(100, || at(&d, 150.0)); + assert_eq!(hit, None); + assert!(arts <= 4, "{arts} levels walked"); + assert_eq!(with_art_limit(100, || at(&d, 50.0)).0, Some(inst), "in the box"); + // Past the limit, a click that the art would take finds only the box. + let (d, inst) = chain(true); + assert_eq!(with_art_limit(100, || at(&d, 150.0)).0, None, "past the limit"); + assert_eq!(at(&d, 150.0), Some(inst), "within the limit"); + // Two levels: a click on the inner instance's art is found within the limit. + let mut d = Document::new(600.0, 400.0); + let l = d.layers[0].id; + clipped_symbol(&mut d, true); + let inner = instance_of(&mut d, "Clipped"); + group_symbol(&mut d, "Outer", vec![inner]); + let inst = instance_of(&mut d, "Outer"); + let id = inst.id; + d.insert(Some(l), 0, Arc::unwrap_or_clone(inst)).unwrap(); + assert_eq!(with_art_limit(100, || at(&d, 150.0)).0, Some(id), "nested"); +} + +/// One click, and one marquee, visit at most the art walk's limit of objects in art that repeats +/// one nested instance many times, though the art of each instance alone is well within it. A +/// click on one of the nested instances' art is still found. +#[test] +fn a_click_and_a_marquee_walk_repeated_nested_symbol_instances_within_one_limit() { + // 50 instances of `Clipped` in one symbol's art, its rectangle shown when `shown`. + let repeated = |shown: bool| { + let mut d = Document::new(600.0, 400.0); + let l = d.layers[0].id; + clipped_symbol(&mut d, shown); + let members = (0..50).map(|_| instance_of(&mut d, "Clipped")).collect(); + group_symbol(&mut d, "Repeated", members); + let inst = instance_of(&mut d, "Repeated"); + let id = inst.id; + d.insert(Some(l), 0, Arc::unwrap_or_clone(inst)).unwrap(); + (d, id) + }; + let (d, inst) = repeated(false); + // Without one limit for the click, the miss walks the art of all 51 instances. The outer art + // takes 1 object of the 100, and each nested instance with its art 4. + let (hit, _, arts) = with_art_limit(100, || hit_test(&d, Point::new(150.0, 50.0), HitOptions::default()).map(|h| h.leaf)); + assert_eq!(hit, None); + assert!(arts <= 26, "{arts} instances' art walked"); + // Select Behind over 60 instances of `Clipped` on the layer shares one limit too: each walk + // takes 3 objects of the 100. + let mut stack = Document::new(600.0, 400.0); + let l = stack.layers[0].id; + clipped_symbol(&mut stack, false); + for _ in 0..60 { + let inst = instance_of(&mut stack, "Clipped"); + stack.insert(Some(l), 0, Arc::unwrap_or_clone(inst)).unwrap(); + } + let (behind, _, arts) = with_art_limit(100, || objects_at(&stack, Point::new(150.0, 50.0), HitOptions::default(), None)); + assert!(behind.is_empty()); + assert!(arts <= 34, "Select Behind: {arts} instances' art walked"); + // Without one limit for the marquee, it places the art of all 51 instances, inside the moved + // region (within each instance's reach and outside its box). Placing the outer art takes 51 + // objects of the 100, and each nested art 4. + let inside = Rect::new(140.0, 40.0, 160.0, 60.0); + let (touched, _, arts) = with_art_limit(100, || marquee(&d, inside, None, false)); + assert!(touched.is_empty()); + assert!(arts <= 14, "{arts} instances' art placed"); + assert_eq!(with_art_limit(100, || marquee(&d, Rect::new(40.0, 40.0, 60.0, 60.0), None, false)).0, [inst], "in the box"); + // A click and a marquee on the nested instances' art are found within the limit. + let (d, inst) = repeated(true); + assert_eq!(with_art_limit(100, || hit_test(&d, Point::new(150.0, 50.0), HitOptions::default()).map(|h| h.leaf)).0, Some(inst), "click"); + let edge = Rect::new(140.0, -5.0, 160.0, 5.0); + assert_eq!(with_art_limit(100, || marquee(&d, edge, None, false)).0, [inst], "marquee across the art's edge"); +} + +/// The members of an Intertwine group in symbol art count toward the art walk's limit of objects +/// for a click, as the members of a plain group do. A click on a member's path past the instance's +/// box is still found within the limit. +#[test] +fn a_click_counts_the_members_of_an_intertwine_group_in_symbol_art_toward_one_limit() { + set_clip_region(moved_clip_region); + // A clip group whose clipping region `test.move` moves to 100..200 × 0..100, past the 0..100 + // box, over an Intertwine group of 200 squares at 140..160 × 40..60. + let mut d = Document::new(600.0, 400.0); + let l = d.layers[0].id; + let (mut mask, _) = half_clipped(&mut d); + mask.appearance.effects.push(test_move()); + let squares = (0..200) + .map(|_| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(140.0, 40.0, 160.0, 60.0)), Appearance::default_art()))) + .collect(); + let woven = Arc::new(Node::new(d.alloc_id(), NodeKind::Intertwine { children: squares })); + let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), woven]); + clip.set_clips(true); + group_symbol(&mut d, "Woven", vec![Arc::new(clip)]); + let inst = instance_of(&mut d, "Woven"); + let id = inst.id; + d.insert(Some(l), 0, Arc::unwrap_or_clone(inst)).unwrap(); + let opt = HitOptions { path_only: true, ..HitOptions::default() }; + let at = |x: f64| hit_test(&d, Point::new(x, 50.0), opt).map(|h| h.leaf); + // Inside the squares and away from their paths, every member is tested and none is hit. + let (hit, leaves, _) = with_art_limit(100, || at(150.0)); + assert_eq!(hit, None); + assert!(leaves <= 100, "{leaves} leaves tested"); + assert_eq!(with_art_limit(100, || at(140.0)).0, Some(id), "on the squares' paths"); +} + /// 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. diff --git a/crates/doc/src/mem.rs b/crates/doc/src/mem.rs index 464e1b3f65..68aaedd68e 100644 --- a/crates/doc/src/mem.rs +++ b/crates/doc/src/mem.rs @@ -281,7 +281,13 @@ fn node_bytes(n: &Node, other: Option<&Node>, counted: &mut HashSet) -> u }); } b += match &n.kind { - NodeKind::Path { path, live, .. } => path_bytes(path) + boxed(live), + NodeKind::Path { path, live, .. } => { + let was = other.and_then(|o| match &o.kind { + NodeKind::Path { path, .. } => Some(path), + _ => None, + }); + path_bytes_besides(path, was) + boxed(live) + } NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Compound { children, .. } @@ -298,8 +304,30 @@ fn node_bytes(n: &Node, other: Option<&Node>, counted: &mut HashSet) -> u } fn path_bytes(p: &PathData) -> usize { - let anchors: usize = - p.subpaths.iter().map(|s| if s.anchors.capacity() == 0 { 0 } else { ALLOC + s.anchors.capacity() * size_of::() }).sum(); + path_bytes_besides(p, None) +} + +/// [`path_bytes`] without the anchor chunks that `other` (another version of the path) holds too: +/// a version made by changing one anchor shares every chunk but the one it changed. +fn path_bytes_besides(p: &PathData, other: Option<&PathData>) -> usize { + let mut shared: Vec = + other.map(|o| o.subpaths.iter().flat_map(|s| s.anchors.chunk_allocations()).map(|(id, _)| id).collect()).unwrap_or_default(); + shared.sort_unstable(); + let chunk = ALLOC + ARC + size_of::>() + ALLOC; + let anchors: usize = p + .subpaths + .iter() + .map(|s| { + let table = s.anchors.table_bytes(); + let own: usize = s + .anchors + .chunk_allocations() + .filter(|(id, _)| shared.binary_search(id).is_err()) + .map(|(_, capacity)| chunk + capacity * size_of::()) + .sum(); + if table == 0 { own } else { ALLOC + table + own } + }) + .sum(); anchors + if p.subpaths.capacity() == 0 { 0 } else { ALLOC + p.subpaths.capacity() * size_of::() } } diff --git a/crates/doc/src/recolor.rs b/crates/doc/src/recolor.rs index 0efa82296a..f25340b29f 100644 --- a/crates/doc/src/recolor.rs +++ b/crates/doc/src/recolor.rs @@ -16,6 +16,11 @@ pub trait ColorVisitor { fn color(&mut self, c: Color) -> Color; /// The key of embedded image `key` recoloured, `None` when it stays as it is. fn image(&mut self, key: &str) -> Option; + /// Whether the pass recolors child `n` of a container: false leaves `n` and everything inside + /// it as they are. + fn enters(&mut self, _n: &Node) -> bool { + true + } } /// What a recolouring pass reaches: fills (including colorized image fills and gradient-mesh @@ -82,6 +87,9 @@ pub fn recolor_node(n: &mut Node, reach: Reach, v: &mut dyn ColorVisitor) -> usi } _ => { for c in n.children_mut().into_iter().flatten() { + if !v.enters(c) { + continue; + } let mut m = (**c).clone(); let k = recolor_node(&mut m, reach, v); if k > 0 { diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index d165a086fb..3964542939 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, GlyphForm, MAX_AKI, MAX_TSUME, MAX_WARICHU_GAP, ScriptMetrics, - WARICHU_LINES, WARICHU_SCALE, WarichuAlign, + CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, GlyphForm, MAX_AKI, MAX_DIACRITIC_POSITION, 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, CUSTOM_CHARS_MAX, CUSTOM_SETS_MAX, CharClass, diff --git a/crates/doc/src/text/char_style.rs b/crates/doc/src/text/char_style.rs index 41fbf168ae..a8fdfbe535 100644 --- a/crates/doc/src/text/char_style.rs +++ b/crates/doc/src/text/char_style.rs @@ -48,8 +48,10 @@ pub struct CharStyle { /// of the character's ink, inside its own width, that is taken away, 0 to [`MAX_TSUME`]. 50 /// halves that space and 100 sets the ink edge to edge; the glyph itself is not scaled. A /// cluster takes the value of its first character. Tracking, kerning and Insert Aki are added - /// after it. Horizontal type only. + /// after it. In vertical type an upright character is measured above and below its ink, inside + /// its cell down the column. /// + /// #[serde(default, skip_serializing_if = "crate::skip::is_default")] pub tsume: f64, /// Use glyph shapes for automatic pair spacing; false uses font metrics. @@ -180,6 +182,18 @@ pub struct CharStyle { /// these characters are drawn in, whatever digits were typed. #[serde(default, skip_serializing_if = "crate::skip::is_default")] pub digits: Digits, + /// Adjust Horizontal Diacritic Position (Character panel, Middle Eastern options): the font's + /// mark glyphs among these characters (GDEF class 3, such as Arabic harakat and Hebrew points) + /// move right by a positive value and left by a negative one, relative to their letters, in + /// 1/1000 em of the size, from -[`MAX_DIACRITIC_POSITION`] to [`MAX_DIACRITIC_POSITION`]. + /// Saved only when not 0. + /// + #[serde(default, rename = "diacriticHorizontal", skip_serializing_if = "crate::skip::is_default")] + pub diacritic_horizontal: f64, + /// Adjust Vertical Diacritic Position: the mark glyphs move up by a positive value and down by + /// a negative one, as [`Self::diacritic_horizontal`] moves them across. + #[serde(default, rename = "diacriticVertical", skip_serializing_if = "crate::skip::is_default")] + pub diacritic_vertical: f64, /// Font height reference (Character panel menu › Show Font Height Options): the height of the /// font that [`Self::size`] measures, the em box by default. #[serde(default, rename = "fontHeightReference", skip_serializing_if = "crate::skip::is_default")] @@ -553,6 +567,10 @@ pub const MAX_AKI: f64 = 1000.0; /// The largest Tsume ([`CharStyle::tsume`]), in percent: all the blank space beside the ink. pub const MAX_TSUME: f64 = 100.0; +/// The largest Adjust Horizontal or Vertical Diacritic Position either way +/// ([`CharStyle::diacritic_horizontal`]), in 1/1000 em: one em. +pub const MAX_DIACRITIC_POSITION: f64 = 1000.0; + /// The number of lines a warichu block may be stacked on ([`CharStyle::warichu_lines`]). pub const WARICHU_LINES: std::ops::RangeInclusive = 1..=6; @@ -684,6 +702,8 @@ impl Default for CharStyle { warichu_align: WarichuAlign::Auto, small_caps: None, digits: Digits::Default, + diacritic_horizontal: 0.0, + diacritic_vertical: 0.0, font_height_reference: FontHeightReference::EmBox, no_break: false, language: None, @@ -707,7 +727,8 @@ impl CharStyle { /// same way. The Warichu Settings Lines and Scale /// are kept to [`WARICHU_LINES`] and [`WARICHU_SCALE`]; a gap or scale that is not a number becomes its default. The gap is kept to 0 to /// [`crate::MAX_COORD`], as the baseline shift is, since a scaled type object holds it in its - /// own units. + /// own units. The Adjust Horizontal and Vertical Diacritic Positions are kept within + /// [`MAX_DIACRITIC_POSITION`] either way, and one that is not a number becomes 0. pub fn keep_dimensions_in_range(&mut self) { let default = Self::default(); let within = |v: f64, or: f64| if v > 0.0 { v.min(crate::MAX_COORD) } else { or }; @@ -723,6 +744,9 @@ impl CharStyle { self.aki_left = aki(self.aki_left); self.aki_right = aki(self.aki_right); self.tsume = if self.tsume.is_nan() { 0.0 } else { self.tsume.clamp(0.0, MAX_TSUME) }; + let diacritic = |v: f64| if v.is_nan() { 0.0 } else { v.clamp(-MAX_DIACRITIC_POSITION, MAX_DIACRITIC_POSITION) }; + self.diacritic_horizontal = diacritic(self.diacritic_horizontal); + self.diacritic_vertical = diacritic(self.diacritic_vertical); self.warichu_lines = self.warichu_lines.clamp(*WARICHU_LINES.start(), *WARICHU_LINES.end()); self.warichu_gap = if self.warichu_gap.is_nan() { default.warichu_gap } else { self.warichu_gap.clamp(0.0, crate::MAX_COORD) }; self.warichu_scale = diff --git a/crates/doc/src/text/object.rs b/crates/doc/src/text/object.rs index b787cebfe0..46f86b68ca 100644 --- a/crates/doc/src/text/object.rs +++ b/crates/doc/src/text/object.rs @@ -511,6 +511,8 @@ impl crate::Document { st.aki_left = num("akiLeft").unwrap_or(st.aki_left); st.aki_right = num("akiRight").unwrap_or(st.aki_right); st.tsume = num("tsume").unwrap_or(st.tsume); + st.diacritic_horizontal = num("diacriticHorizontal").unwrap_or(st.diacritic_horizontal); + st.diacritic_vertical = num("diacriticVertical").unwrap_or(st.diacritic_vertical); st.warichu_gap = num("warichuGap").unwrap_or(st.warichu_gap); st.warichu_scale = num("warichuScale").unwrap_or(st.warichu_scale); st.keep_dimensions_in_range(); @@ -537,6 +539,8 @@ impl crate::Document { ("akiLeft", Some(st.aki_left)), ("akiRight", Some(st.aki_right)), ("tsume", Some(st.tsume)), + ("diacriticHorizontal", Some(st.diacritic_horizontal)), + ("diacriticVertical", Some(st.diacritic_vertical)), ("leading", st.leading), ]; for (k, v) in kept { diff --git a/crates/doc/src/text/para_style.rs b/crates/doc/src/text/para_style.rs index 45cf181f18..c3db242ed0 100644 --- a/crates/doc/src/text/para_style.rs +++ b/crates/doc/src/text/para_style.rs @@ -17,22 +17,52 @@ pub enum Justify { JustifyAll, } -/// Paragraph composer (Paragraph panel menu): how lines are broken. +/// Paragraph composer (Paragraph panel menu): how lines are broken, and whether complex scripts +/// (Indic, Arabic, Hebrew) are shaped. `SingleLine` and `EveryLine` are the Middle Eastern & South +/// Asian composers: they shape complex scripts with the font's layout tables, as all type is set +/// here, and are what documents saved before the four composers existed use. The `Standard` +/// composers break lines the same way but set a complex script glyph by glyph as the font maps its +/// characters, with no conjuncts, marks placed or joining forms: what fonts that keep a script's +/// glyphs on Latin character codes (legacy ANSI Indic fonts) need. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum Composer { - /// Break each line as soon as it is full. + /// Middle Eastern & South Asian Single-line Composer: break each line as soon as it is full. SingleLine, - /// Total fit over the whole paragraph (Illustrator's default): justified lines get even word - /// spacing, ragged lines an even rag. + /// Middle Eastern & South Asian Every-line Composer: total fit over the whole paragraph + /// (Illustrator's default): justified lines get even word spacing, ragged lines an even rag. #[default] EveryLine, + /// Standard Single-line Composer: [`Composer::SingleLine`]'s breaks, complex scripts not shaped. + StandardSingleLine, + /// Standard Every-line Composer: [`Composer::EveryLine`]'s breaks, complex scripts not shaped. + StandardEveryLine, } impl Composer { fn is_default(&self) -> bool { *self == Self::default() } + + /// Does this composer break lines one at a time (as opposed to a total fit)? + pub fn is_single_line(self) -> bool { + matches!(self, Self::SingleLine | Self::StandardSingleLine) + } + + /// Does this composer shape complex scripts ([`Composer::SingleLine`], [`Composer::EveryLine`])? + pub fn shapes_complex_scripts(self) -> bool { + matches!(self, Self::SingleLine | Self::EveryLine) + } + + /// The same shaping with the other line breaking (`single_line`: one line at a time). + pub fn with_breaking(self, single_line: bool) -> Self { + match (single_line, self.shapes_complex_scripts()) { + (true, true) => Self::SingleLine, + (true, false) => Self::StandardSingleLine, + (false, true) => Self::EveryLine, + (false, false) => Self::StandardEveryLine, + } + } } /// A paragraph's hyphenation options (Paragraph panel menu › Hyphenation…): which words automatic diff --git a/crates/doc/src/text/tests.rs b/crates/doc/src/text/tests.rs index 0976edbb93..a5230d5d86 100644 --- a/crates/doc/src/text/tests.rs +++ b/crates/doc/src/text/tests.rs @@ -129,6 +129,42 @@ fn insert_aki_is_saved_only_when_set() { assert_eq!((d.char_styles[0].attrs["akiLeft"].as_f64(), d.char_styles[0].attrs["akiRight"].as_f64()), (Some(MAX_AKI), Some(0.0))); } +/// Adjust Horizontal and Vertical Diacritic Position are 0 by default and saved only when not 0, +/// each on its own; styles written before them read as 0, and a value out of range from a file is +/// kept within one em either way. +#[test] +fn diacritic_positions_are_saved_only_when_set() { + let st = CharStyle::default(); + assert_eq!((st.diacritic_horizontal, st.diacritic_vertical), (0.0, 0.0)); + let saved = serde_json::to_value(&st).unwrap(); + assert!(saved.get("diacriticHorizontal").is_none() && saved.get("diacriticVertical").is_none()); + for set in [ + CharStyle { diacritic_horizontal: -250.0, ..CharStyle::default() }, + CharStyle { diacritic_vertical: 500.0, ..CharStyle::default() }, + CharStyle { diacritic_horizontal: 12.5, diacritic_vertical: -1000.0, ..CharStyle::default() }, + ] { + let saved = serde_json::to_value(&set).unwrap(); + assert_eq!(saved.get("diacriticHorizontal").and_then(serde_json::Value::as_f64).unwrap_or(0.0), set.diacritic_horizontal); + assert_eq!(saved.get("diacriticVertical").and_then(serde_json::Value::as_f64).unwrap_or(0.0), set.diacritic_vertical); + assert_eq!(saved.get("diacriticHorizontal").is_some(), set.diacritic_horizontal != 0.0); + assert_eq!(saved.get("diacriticVertical").is_some(), set.diacritic_vertical != 0.0); + assert_eq!(serde_json::from_value::(saved).unwrap(), set); + } + let mut damaged = CharStyle { diacritic_horizontal: -4000.0, diacritic_vertical: 4000.0, ..CharStyle::default() }; + damaged.keep_dimensions_in_range(); + assert_eq!((damaged.diacritic_horizontal, damaged.diacritic_vertical), (-MAX_DIACRITIC_POSITION, MAX_DIACRITIC_POSITION)); + let mut damaged = CharStyle { diacritic_horizontal: f64::NAN, diacritic_vertical: f64::NEG_INFINITY, ..CharStyle::default() }; + damaged.keep_dimensions_in_range(); + assert_eq!((damaged.diacritic_horizontal, damaged.diacritic_vertical), (0.0, -MAX_DIACRITIC_POSITION)); + // A character style from a file is kept in range the same way. + let mut d = crate::Document::new(100.0, 100.0); + let attrs = serde_json::json!({"diacriticHorizontal": 5000, "diacriticVertical": -5000}); + d.char_styles.push(TextStyleDef { name: "Moved".into(), attrs: attrs.as_object().cloned().unwrap_or_default() }); + d.keep_type_values_in_range(); + let kept = |key: &str| d.char_styles[0].attrs[key].as_f64(); + assert_eq!((kept("diacriticHorizontal"), kept("diacriticVertical")), (Some(MAX_DIACRITIC_POSITION), Some(-MAX_DIACRITIC_POSITION))); +} + /// Tsume is 0 by default and saved only when not 0; styles written before it read as 0, and a /// value out of range from a file, in a run or a character style, is kept from 0 to 100. #[test] diff --git a/crates/effects/src/bake.rs b/crates/effects/src/bake.rs index d8f3ae0fe4..67388c0d72 100644 --- a/crates/effects/src/bake.rs +++ b/crates/effects/src/bake.rs @@ -117,6 +117,11 @@ 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) }; + /// The objects in the baked art of the instances inside the art of other instances that + /// [`bake_node`] baked for one export and then left as they are, counted with + /// [`NESTED_NODES`] against [`crate::SYMBOL_ART_MAX_NODES`] before more art is baked. Never + /// given back. + static NESTED_DROPPED: 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) }; @@ -369,17 +374,29 @@ fn bake_object(d: &mut Document, n: &Node) -> Option { }; // Instances baked inside the art of others stop at the depth limit, or once their art // passes the objects one export bakes that way: an instance of a symbol whose art holds - // instances of itself is kept as it is there. + // instances of itself is kept as it is there. The symbol's art is held in the count while + // it bakes, so the instances inside it bake only within what is left; the art it bakes to, + // with what its effects add, then takes its place in the count. When that art does not + // fit, the instance stays as it is, and the art baked for it, with the art dropped for the + // instances inside it, still counts against the instances after it. let instance = matches!(n.kind, NodeKind::SymbolInstance { .. }); - if instance && INSTANCE_DEPTH.with(|c| c.get()) > 0 { + let nested = instance && INSTANCE_DEPTH.with(|c| c.get()) > 0; + let before = NESTED_NODES.with(|c| c.get()); + if nested { let count = symbol.as_ref().map_or(0, |a| a.count() as u64); - let spent = NESTED_NODES.with(|c| c.get()).saturating_add(count); - if INSTANCE_DEPTH.with(|c| c.get()) >= vectorcraft_doc::depth::MAX_DEPTH || spent > crate::SYMBOL_ART_MAX_NODES { + let spent = before.saturating_add(count); + let dropped = NESTED_DROPPED.with(|c| c.get()); + if INSTANCE_DEPTH.with(|c| c.get()) >= vectorcraft_doc::depth::MAX_DEPTH || spent.saturating_add(dropped) > crate::SYMBOL_ART_MAX_NODES { return None; } NESTED_NODES.with(|c| c.set(spent)); } - let m = reshape(Some(d), n, symbol.as_ref())?; + let Some(m) = reshape(Some(d), n, symbol.as_ref()) else { + if nested { + NESTED_NODES.with(|c| c.set(before)); + } + return None; + }; if instance { INSTANCE_DEPTH.with(|c| c.set(c.get() + 1)); } @@ -387,7 +404,17 @@ fn bake_object(d: &mut Document, n: &Node) -> Option { if instance { INSTANCE_DEPTH.with(|c| c.set(c.get() - 1)); } - return Some(baked.unwrap_or(m)); + let baked = baked.unwrap_or(m); + if nested { + let spent = before.saturating_add(baked.count() as u64); + if spent.saturating_add(NESTED_DROPPED.with(|c| c.get())) > crate::SYMBOL_ART_MAX_NODES { + NESTED_NODES.with(|c| c.set(before)); + NESTED_DROPPED.with(|c| c.set(c.get().saturating_add(baked.count() as u64))); + return None; + } + NESTED_NODES.with(|c| c.set(spent)); + } + return Some(baked); } // 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 @@ -1068,6 +1095,7 @@ fn bake(doc: &Document, placing: Option<(bool, u64, WrittenLayers)>) -> Option Node { + let mut n = instance(id, symbol, vectorcraft_geom::Affine::IDENTITY); + n.appearance.effects.push(fx("path.offsetPath", json!({"offset": 1.0}))); + n +} + +/// `n` baked as an instance inside another instance's art, with `spent` objects of nested symbol +/// art already baked: the baked object, and the objects counted after it, art baked and dropped +/// included. +fn bake_nested(d: &mut Document, n: &Node, spent: u64) -> (Option, u64) { + INSTANCE_DEPTH.with(|c| c.set(1)); + NESTED_NODES.with(|c| c.set(spent)); + NESTED_DROPPED.with(|c| c.set(0)); + let out = bake_node(d, n); + INSTANCE_DEPTH.with(|c| c.set(0)); + (out, NESTED_NODES.with(|c| c.replace(0)).saturating_add(NESTED_DROPPED.with(|c| c.replace(0)))) +} + +/// The object with id `id` in `n`'s subtree. +fn find(n: &Node, id: u64) -> Option<&Node> { + if n.id == NodeId(id) { + return Some(n); + } + n.children().into_iter().flatten().find_map(|c| find(c, id)) +} + +/// Is `n` an object other than a symbol instance? +fn baked(n: Option<&Node>) -> bool { + n.is_some_and(|n| !matches!(n.kind, NodeKind::SymbolInstance { .. })) +} + +/// An instance baked inside another instance's art counts the art it bakes to, the copies its +/// symbol's effects make included: art that fits exactly takes the last of the budget, and art +/// whose symbol fits but whose baked art does not leaves the instance as it is and still counts. +#[test] +fn nested_reshape_counts_baked_art() { + let mut d = Document::new(400.0, 400.0); + add_symbol(&mut d, "Inner", gradient_copies(800)); + let n = offset_instance(900, "Inner"); + let source = d.symbols[0].art.count() as u64; + let (all, spent) = bake_nested(&mut d, &n, 0); + let baked = all.map_or(0, |m| m.count() as u64); + assert!(baked > source + 1, "the copies are objects of their own: {baked} > {source} + 1"); + assert_eq!(spent, baked, "the baked art is counted in place of the symbol's art"); + let max = crate::SYMBOL_ART_MAX_NODES; + let (exact, spent) = bake_nested(&mut d, &n, max - baked); + assert!(exact.is_some(), "{baked} objects fit in {baked}"); + assert_eq!(spent, max); + let (short, spent) = bake_nested(&mut d, &n, max - baked + 1); + assert!(short.is_none(), "the symbol's {source} objects fit, the {baked} baked ones do not"); + assert_eq!(spent, max + 1, "the art baked for the instance left as it is still counts"); +} + +/// An instance left as it is because its baked art does not fit still counts the art baked for +/// it: an instance after it is left as it is too, before its art bakes. +#[test] +fn nested_reshape_refusal_keeps_its_work_counted() { + let mut d = Document::new(400.0, 400.0); + add_symbol(&mut d, "Big", gradient_copies(800)); + add_symbol(&mut d, "Small", moved_square(810)); + let (big, small) = (offset_instance(900, "Big"), offset_instance(901, "Small")); + let count = |d: &mut Document, n: &Node| bake_nested(d, n, 0).0.map_or(0, |m| m.count() as u64); + let (b, s) = (count(&mut d, &big), count(&mut d, &small)); + assert!(s < b, "{s} < {b}"); + let first = crate::SYMBOL_ART_MAX_NODES - b + 1; + let (refused, spent) = bake_nested(&mut d, &big, first); + assert!(refused.is_none(), "the big art passes the budget"); + assert_eq!(spent, first + b, "the big art baked and dropped counts"); + let (later, after) = bake_nested(&mut d, &small, spent); + assert!(later.is_none(), "the small art does not fit after the dropped art"); + assert_eq!(after, spent, "the small instance is refused before it bakes"); +} + +/// Sibling instances inside other instances' art whose baked art each passes what is left: the +/// first is baked and dropped, and its art counts, so the others are left as they are before +/// their art bakes. With room for all of them, every one is baked. +#[test] +fn nested_reshape_refused_siblings_bake_once() { + let mut d = Document::new(400.0, 400.0); + add_symbol(&mut d, "Big", gradient_copies(800)); + let one = offset_instance(900, "Big"); + let b = bake_nested(&mut d, &one, 0).0.map_or(0, |m| m.count() as u64); + let siblings: Vec> = (0..16).map(|i| Arc::new(offset_instance(1000 + i, "Big"))).collect(); + let group = Node::group(NodeId(999), siblings); + let first = crate::SYMBOL_ART_MAX_NODES - b + 1; + let (refused, spent) = bake_nested(&mut d, &group, first); + let refused = refused.unwrap_or_else(|| group.clone()); + assert!((0..16).all(|i| !baked(find(&refused, 1000 + i))), "no sibling fits: {refused:?}"); + assert_eq!(spent, first + b, "only the first sibling's art is baked and counted: {spent}"); + let (room, spent) = bake_nested(&mut d, &group, 0); + let room = room.unwrap_or_else(|| panic!("the siblings are baked")); + assert!((0..16).all(|i| baked(find(&room, 1000 + i))), "every sibling is baked"); + assert_eq!(spent, 16 * b); +} + +/// An instance inside another instance's art whose own art holds a reshaped instance counts that +/// instance's baked art once: a budget of exactly the outer art's baked objects bakes both, and +/// with one object less the art baked and dropped still counts. +#[test] +fn nested_reshape_counts_successful_descendants_once() { + let mut d = Document::new(400.0, 400.0); + add_symbol(&mut d, "Inner", gradient_copies(800)); + let square = Node::path(NodeId(803), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()); + add_symbol(&mut d, "Outer", Node::group(NodeId(801), vec![Arc::new(offset_instance(802, "Inner")), Arc::new(square)])); + let outer = offset_instance(900, "Outer"); + let (all, spent) = bake_nested(&mut d, &outer, 0); + let all = all.unwrap_or_else(|| panic!("the outer instance is baked")); + assert!(baked(find(&all, 802)), "the inner instance is baked: {all:?}"); + let total = all.count() as u64; + assert_eq!(spent, total); + let max = crate::SYMBOL_ART_MAX_NODES; + let (exact, spent) = bake_nested(&mut d, &outer, max - total); + let exact = exact.unwrap_or_else(|| panic!("{total} objects fit in {total}")); + assert!(baked(find(&exact, 802)), "the inner instance is baked too"); + assert_eq!(spent, max); + let (short, spent) = bake_nested(&mut d, &outer, max - total + 1); + assert!(short.as_ref().is_none_or(|m| !baked(find(m, 802))), "with one object less, not both are baked"); + assert!(spent > max, "the art baked and dropped counts: {spent}"); + assert!(spent <= max - total + 1 + 2 * total, "at most the outer and the inner art are dropped: {spent}"); +} diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index 2a5ce5fd9d..313d4f65ed 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -267,7 +267,7 @@ pub fn effect_catalog() -> Vec { "distort.transform", "Transform…", DT, - "{scaleH: % (100), scaleV: % (100), moveH: pt (0; right = +), moveV: pt (0; down = +), rotate: deg (0; counter-clockwise; when the effect turns, reflects or scales the object unevenly, a gradient fitted to the object is fixed to its fit and turns with the object and with each copy), copies: 0..1000 (0; each copy transforms the last again and is painted below it, the object on top; a group's copies each hold all its members, and a group with a member that carries a geometry, Pathfinder or 3D effect copies each member in its place; placed gradients transform with the object and with each copy), reflectX: bool (false; flips left to right), reflectY: bool (false; flips top to bottom), reference: 0..8 (4; the point of the bounds' 9-point grid it scales, rotates and reflects about: 0 top left, 4 centre, 8 bottom right), random: bool (false; each scale goes a random share of the way from 100 % to its value, each move and the angle a random share of theirs, differently for each object and the same on every redraw), objects: bool (true; Transform Objects: off, the geometry stays where it is and makes no copies, and only the two options below apply, once; on, without copies or random, the raster effects listed before this effect (Rasterize and SVG filters excepted) transform with the art whatever strokes says: their sizes scale by the mean scale and a Drop Shadow's offset turns, reflects and scales, while the angles and light directions of pixel filters stay as they are; so do the raster effects of the object's fills and strokes and, on a group, those of its members, of their fills and strokes and of their linked opacity masks' art, after their own Transform effects, including those that a member's own Transform effect with copies or random holds back), patterns: bool (false; Transform Patterns: pattern fills and strokes transform along; with copies the original keeps its pattern and copy k takes the transformation k times), strokes: bool (false; Scale Strokes & Effects: stroke weights and dashes, and the distances of the effects on the fills and strokes, scale by the mean scale √|scaleH·scaleV|, copy k by its k-th power; raster effects that transform with the art are not scaled again; on a fill or stroke, the effects listed after this effect in that fill's or stroke's own list keep their distances and apply to the transformed art, and with objects off so do the effects before it)}", + "{scaleH: % (100), scaleV: % (100), moveH: pt (0; right = +), moveV: pt (0; down = +), rotate: deg (0; counter-clockwise; when the effect turns, reflects or scales the object unevenly, a gradient fitted to the object is fixed to its fit and turns with the object and with each copy), copies: 0..1000 (0; each copy transforms the last again and is painted below it, the object on top; a group's copies each hold all its members, and a group with a member that carries a geometry, Pathfinder or 3D effect copies each member in its place; placed gradients transform with the object and with each copy), reflectX: bool (false; flips left to right), reflectY: bool (false; flips top to bottom), reference: 0..8 (4; the point of the bounds' 9-point grid it scales, rotates and reflects about: 0 top left, 4 centre, 8 bottom right), random: bool (false; each scale goes a random share of the way from 100 % to its value, each move and the angle a random share of theirs, differently for each object and the same on every redraw), objects: bool (true; Transform Objects: off, the geometry stays where it is and makes no copies, and only the two options below apply, once; on, without copies or random, the raster effects listed before this effect (Rasterize and SVG filters excepted) transform with the art whatever strokes says: their sizes scale by the mean scale, a Drop Shadow's offset turns, reflects and scales, a pixel filter's lightDirection or strokeDirection turns and reflects to the nearest choice (at a tie, the one clockwise of it; VectorCraft's own rule), and Color Halftone's channel angles turn and reflect with the art (0 to 360); so do the raster effects of the object's fills and strokes and, on a group, those of its members, of their fills and strokes and of their linked opacity masks' art, after their own Transform effects, including those that a member's own Transform effect with copies or random holds back), patterns: bool (false; Transform Patterns: pattern fills and strokes transform along; with copies the original keeps its pattern and copy k takes the transformation k times), strokes: bool (false; Scale Strokes & Effects: stroke weights and dashes, and the distances of the effects on the fills and strokes, scale by the mean scale √|scaleH·scaleV|, copy k by its k-th power; raster effects that transform with the art are not scaled again; on a fill or stroke, the effects listed after this effect in that fill's or stroke's own list keep their distances and apply to the transformed art, and with objects off so do the effects before it)}", json!({"scaleH": 100.0, "scaleV": 100.0, "moveH": 0.0, "moveV": 0.0, "rotate": 0.0, "copies": 0, "reflectX": false, "reflectY": false, "reference": 4, "random": false, "objects": true, "patterns": false, "strokes": false}), ), g( @@ -859,7 +859,7 @@ pub fn effect_catalog() -> Vec { crate::SVG_FILTER, "SVG Filter", &["Effect", "SVG Filters"], - "{name: string (the filter's id), xml: string (one SVG element with an id and 1..64 primitives, at most 64 KB), scale: number 0.001..1000 (1; points per unit of the filter's user space), origin: [x, y] pt ([0, 0]; where the filter's user space starts in the document)} runs the SVG filter on the object's pixels, its lengths in points times scale, at the Document Raster Effects resolution or finer; svgFilter.apply applies one of the document's filters (svgFilter.list)", + "{name: string (the filter's id), xml: string (one SVG element with an id and 1..64 primitives, at most 64 KB), scale: number 0.001..1000 (1; points per unit of the filter's user space), origin: [x, y] pt ([0, 0]; where the filter's user space starts in the document), axes?: [a, b, c, d] (absent or [1, 0, 0, 1]: the document's axes, and not null; the document directions of one unit along the filter's x axis [a, b] and y axis [c, d] before scale, each -1000..1000, with a·d - b·c at least 0.001 from 0; a turned, skewed or unevenly scaled user space, as SVG import gives a filtered element under a rotate, skew or uneven scale; the filter's offsets, blurs and region run along these axes; moving, turning or skewing the object moves origin and leaves axes)} runs the SVG filter on the object's pixels, its lengths in points times scale, at the Document Raster Effects resolution or finer; svgFilter.apply applies one of the document's filters (svgFilter.list)", json!({"scale": 1.0, "origin": [0.0, 0.0]}), )); v diff --git a/crates/effects/src/group.rs b/crates/effects/src/group.rs index d2a6687dd7..94c5509938 100644 --- a/crates/effects/src/group.rs +++ b/crates/effects/src/group.rs @@ -853,7 +853,11 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option { } if !fx.is_empty() { m = crate::reshape::outlined_members(doc, &m); - members_as_drawn(doc, &mut m); + { + // The members' raster effects then follow the group's own Transform effects as well. + let _later = crate::raster::LaterGroups::enter(&n.appearance.effects); + members_as_drawn(doc, &mut m); + } let carry = crate::reshape::reshape_leaves_carrying(&mut m, &fx, &n.appearance.effects, doc); // The group's own fills and strokes paint the members as a whole: their gradients follow // the effects as the members' do. diff --git a/crates/effects/src/lighting.rs b/crates/effects/src/lighting.rs index 257576822a..7e73594d89 100644 --- a/crates/effects/src/lighting.rs +++ b/crates/effects/src/lighting.rs @@ -321,6 +321,22 @@ pub(crate) fn opaque_paint(paint: &Paint) -> (Paint, Option) { (base, transparent.then_some(mask)) } +/// [`opaque_paint`] for a surface of several faces under one opacity mask. A transparent gradient +/// without a placement (or a freeform gradient without points) is first pinned to `bounds`, the +/// faces' bounds together grown by 1 pt, so every face's color and the mask share one placement. +/// An opaque gradient is returned as [`opaque_paint`] returns it. +pub(crate) fn opaque_surface_paint(paint: &Paint, bounds: impl FnOnce() -> vectorcraft_geom::Rect) -> (Paint, Option) { + let (base, mask) = opaque_paint(paint); + if mask.is_none() || !matches!(paint, Paint::Gradient(_)) { + return (base, mask); + } + let mut pinned = paint.clone(); + if let Paint::Gradient(g) = &mut pinned { + g.pin(bounds().inflate(1.0, 1.0)); + } + opaque_paint(&pinned) +} + fn composed_art(id: vectorcraft_doc::NodeId, path: &vectorcraft_geom::PathData, paint: &Paint, light: Ramp, seam: f64) -> vectorcraft_doc::Node { use std::sync::Arc; use vectorcraft_doc::color::BlendMode; diff --git a/crates/effects/src/pixel.rs b/crates/effects/src/pixel.rs index f2c49dadd7..f6c33079c0 100644 --- a/crates/effects/src/pixel.rs +++ b/crates/effects/src/pixel.rs @@ -29,6 +29,8 @@ mod sketch_ink; mod texture; mod video; +use std::f64::consts::{PI, TAU}; + use serde_json::Value; use vectorcraft_geom::{Affine, Point, Rect, Vec2}; @@ -332,6 +334,9 @@ pub struct PixelSpace { pub extent: f64, } +/// Color Halftone's screen angle parameters with their defaults (degrees). +const SCREEN_ANGLES: [(&str, f64); 4] = [("channel1", 108.0), ("channel2", 162.0), ("channel3", 90.0), ("channel4", 45.0)]; + /// Effect `id`'s parameters `p` (defaults merged in) as a [`PixelFx`]; `None` for other effects. pub(crate) fn parse(id: &str, p: &Value) -> Option { let quality = |levels: [(&str, u32); 3], default: u32| { @@ -565,8 +570,7 @@ pub(crate) fn parse(id: &str, p: &Value) -> Option { }, "pixelate.colorHalftone" => PixelFx::ColorHalftone { max_radius: num(p, "maxRadius", 8.0).clamp(4.0, 127.0), - angles: [("channel1", 108.0), ("channel2", 162.0), ("channel3", 90.0), ("channel4", 45.0)] - .map(|(k, d)| num(p, k, d).clamp(-360.0, 360.0)), + angles: SCREEN_ANGLES.map(|(k, d)| num(p, k, d).clamp(-360.0, 360.0)), }, "pixelate.crystallize" => PixelFx::Crystallize { cell: num(p, "cellSize", 10.0).clamp(3.0, 300.0) }, "pixelate.mezzotint" => PixelFx::Mezzotint { kind: Mezzotint::parse(text(p, "type", "fineDots")) }, @@ -855,6 +859,113 @@ fn pick(table: &[(&str, &str)], all: &[T], value: &str, default: T) -> table.iter().zip(all).find(|((_, v), _)| v.eq_ignore_ascii_case(value)).map_or(default, |(_, t)| t.clone()) } +/// The shortest that a direction's unit vector may become under a Transform effect and still give +/// a direction ([`turned_directions`]). +const MIN_TURNED: f64 = 1e-9; + +/// How close (radians) two directions' angles to a turned direction must be to count as equally +/// near ([`nearest`]). +const TIE: f64 = 1e-9; + +/// The parameters of pixel filter `id` (params `p`, defaults not merged in) that set a direction +/// on the page, as `a` turns them: `a` is the linear part of a Transform effect listed after the +/// filter, which turns, reflects and scales what the filter paints. A light direction or stroke +/// direction becomes the one nearest to where `a` takes it, the one clockwise of it when two are +/// equally near ([`snapped`]); `later` is the map the filter still goes through when it is drawn, +/// after `a`. Color Halftone's screen angles (degrees counterclockwise from the page's horizontal) +/// turn with `a`, from 0 up to 360. A direction that `a` takes to no direction (a zero scale) stays +/// as it is. Empty for filters with no such parameter. +pub(crate) fn turned_directions(id: &str, p: &Value, a: Affine, later: Affine) -> Vec<(&'static str, Value)> { + enum Kind { + Light(&'static str), + Stroke, + Screens, + } + let kind = match id { + "sketch.basRelief" => Kind::Light("bottom"), + "artistic.underpainting" | "artistic.roughPastels" | "sketch.conteCrayon" | "sketch.plaster" | "texture.texturizer" => Kind::Light("top"), + "brushStrokes.sprayedStrokes" | "sketch.graphicPen" => Kind::Stroke, + "pixelate.colorHalftone" => Kind::Screens, + _ => return Vec::new(), + }; + let p = crate::merged_params(id, p); + match kind { + Kind::Light(default) => { + let light = Light::parse(text(&p, "lightDirection", default)); + snapped(&Light::ALL, Light::toward, light, a, later, false) + .and_then(|t| name_of(&LIGHT_DIRECTIONS, &Light::ALL, t)) + .map(|name| vec![("lightDirection", Value::from(name))]) + .unwrap_or_default() + } + Kind::Stroke => { + let direction = StrokeDirection::parse(text(&p, "strokeDirection", "rightDiagonal")); + snapped(&StrokeDirection::ALL, StrokeDirection::along, direction, a, later, true) + .and_then(|t| name_of(&STROKE_DIRECTIONS, &StrokeDirection::ALL, t)) + .map(|name| vec![("strokeDirection", Value::from(name))]) + .unwrap_or_default() + } + // A screen at θ° runs along (cos θ, −sin θ) on the page (y down). + Kind::Screens => SCREEN_ANGLES + .iter() + .filter_map(|&(key, default)| { + let t = num(&p, key, default).clamp(-360.0, 360.0).to_radians(); + let v = mapped(a, Vec2::new(t.cos(), -t.sin()))?; + let degrees = ((-v.y).atan2(v.x).to_degrees() * 1e6).round() / 1e6; + Some((key, Value::from(degrees.rem_euclid(360.0) + 0.0))) + }) + .collect(), + } +} + +/// Where the linear part of `a` takes direction `v`; `None` when it takes it to no direction. +fn mapped(a: Affine, v: Vec2) -> Option { + let w = (a * v.to_point()) - (a * Point::ORIGIN); + (w.is_finite() && w.hypot() > MIN_TURNED).then_some(w) +} + +/// The entry of `all` to store for `from` (directions `dir`) once `a` turns it: the one nearest to +/// where `a` takes it ([`nearest`]). When the stored entry is still to be mapped by `later` and +/// rounded again as it is drawn, it is the entry nearest to that among those that `later` takes to +/// the entry nearest to where `later` after `a` takes `from`, so that the drawn direction is +/// rounded once. `None` when `a` takes `from` to no direction. +fn snapped(all: &[T], dir: fn(T) -> Vec2, from: T, a: Affine, later: Affine, axis: bool) -> Option { + let v = mapped(a, dir(from))?; + let turned = nearest(all, dir, v, axis)?; + if later == Affine::IDENTITY { + return Some(turned); + } + let Some(target) = mapped(later * a, dir(from)).and_then(|w| nearest(all, dir, w, axis)) else { return Some(turned) }; + let fits: Vec = all.iter().copied().filter(|&t| mapped(later, dir(t)).and_then(|w| nearest(all, dir, w, axis)) == Some(target)).collect(); + nearest(&fits, dir, v, axis).or(Some(turned)) +} + +/// The entry of `all` whose direction (`dir`, page axes with y down) is nearest to `v` by angle, +/// a direction and its opposite counting as the same with `axis`. Of two equally near, the one +/// clockwise of `v` on the page. +fn nearest(all: &[T], dir: impl Fn(T) -> Vec2, v: Vec2, axis: bool) -> Option { + let period = if axis { PI } else { TAU }; + let at = v.atan2(); + let mut best: Option<(T, f64)> = None; + for &t in all { + // How far clockwise of `v` the entry lies, within half a period either way. + let d = (dir(t).atan2() - at).rem_euclid(period); + let d = if d > period / 2.0 { d - period } else { d }; + let better = match best { + None => true, + Some((_, b)) => d.abs() < b.abs() - TIE || (d.abs() <= b.abs() + TIE && d > b), + }; + if better { + best = Some((t, d)); + } + } + best.map(|(t, _)| t) +} + +/// The value in `table` of entry `t` of `all` (the same order). +fn name_of(table: &[(&'static str, &'static str)], all: &[T], t: T) -> Option<&'static str> { + table.iter().zip(all).find(|(_, u)| **u == t).map(|((_, v), _)| *v) +} + /// `data` as `w` × `h` RGBA pixels, `None` when it isn't that size (or is empty). fn pixels(data: &mut [u8], w: usize, h: usize) -> Option<&mut [[u8; 4]]> { let (px, rest) = data.as_chunks_mut::<4>(); diff --git a/crates/effects/src/pixel/brushstrokes.rs b/crates/effects/src/pixel/brushstrokes.rs index 100d4e2497..ca5c0a9b48 100644 --- a/crates/effects/src/pixel/brushstrokes.rs +++ b/crates/effects/src/pixel/brushstrokes.rs @@ -43,7 +43,7 @@ pub enum StrokeDirection { } impl StrokeDirection { - const ALL: [StrokeDirection; 4] = + pub(super) const ALL: [StrokeDirection; 4] = [StrokeDirection::RightDiagonal, StrokeDirection::Horizontal, StrokeDirection::LeftDiagonal, StrokeDirection::Vertical]; /// The direction of `value` (a [`STROKE_DIRECTIONS`] value, any case); Right Diagonal @@ -53,7 +53,7 @@ impl StrokeDirection { } /// The unit vector along the strokes (document axes, y down). - fn along(self) -> Vec2 { + pub(super) fn along(self) -> Vec2 { match self { StrokeDirection::RightDiagonal => RIGHT, StrokeDirection::Horizontal => Vec2::new(1.0, 0.0), diff --git a/crates/effects/src/pixel/texture.rs b/crates/effects/src/pixel/texture.rs index a408454530..e041256dc0 100644 --- a/crates/effects/src/pixel/texture.rs +++ b/crates/effects/src/pixel/texture.rs @@ -137,7 +137,7 @@ pub enum Light { } impl Light { - const ALL: [Light; 8] = + pub(super) const ALL: [Light; 8] = [Light::Bottom, Light::BottomLeft, Light::Left, Light::TopLeft, Light::Top, Light::TopRight, Light::Right, Light::BottomRight]; /// The direction of `value` (a [`LIGHT_DIRECTIONS`] value, any case); Top otherwise. diff --git a/crates/effects/src/raster.rs b/crates/effects/src/raster.rs index f24a5dd2ee..ef8b32d56e 100644 --- a/crates/effects/src/raster.rs +++ b/crates/effects/src/raster.rs @@ -452,7 +452,7 @@ pub(crate) fn followed(effects: &[Effect]) -> Cow<'_, [Effect]> { let Some(a) = after.filter(|a| *a != Affine::IDENTITY && follows(&e.id)) else { continue }; let list = out.get_or_insert_with(|| effects.to_vec()); if let Some(e) = list.get_mut(i) { - follow_transform(e, a); + follow_transform(e, a, Affine::IDENTITY); } } out.map_or(Cow::Borrowed(effects), Cow::Owned) @@ -472,7 +472,7 @@ pub(crate) fn follow_one(effects: &mut [Effect], t: &Effect) -> bool { let Some(a) = transform_step(t).filter(|a| *a != Affine::IDENTITY) else { return false }; let mut changed = false; for e in effects.iter_mut().filter(|e| follows(&e.id)) { - follow_transform(e, a); + follow_transform(e, a, Affine::IDENTITY); changed = true; } changed @@ -519,7 +519,7 @@ pub(crate) fn follow_contents(effects: &mut [Effect], a: Affine, outer: Affine) let det = b.determinant(); let c = if b == Affine::IDENTITY || !(det.is_finite() && det.abs() > 1e-12) { a } else { b.inverse() * a * b }; if c.is_finite() { - follow_transform(e, c); + follow_transform(e, c, b); changed = true; } } @@ -666,11 +666,44 @@ pub(crate) fn follows(id: &str) -> bool { crate::is_raster(id) && id != crate::SVG_FILTER && id != RASTERIZE } +thread_local! { + /// The linear part of the Transform effects of the groups and layers whose members are being + /// evaluated ([`LaterGroups`]), which those groups apply to the members' raster effects once + /// the members are evaluated: the members' light and stroke directions are rounded for them as + /// well ([`follow_transform`]). + static LATER_GROUPS: std::cell::Cell = const { std::cell::Cell::new(Affine::IDENTITY) }; +} + +/// The Transform effects of a group or layer whose members are being evaluated before the group's +/// own effects are applied to them, added to [`LATER_GROUPS`] until it is dropped. +pub(crate) struct LaterGroups(Affine); + +impl LaterGroups { + /// Add the Transform effects of `owner`, a group's or layer's own effects ([`contents_step`]), + /// to those the members will still go through. + pub(crate) fn enter(owner: &[Effect]) -> Self { + let was = LATER_GROUPS.with(|l| l.get()); + if let Some(step) = contents_step(owner) { + LATER_GROUPS.with(|l| l.set(was * step)); + } + LaterGroups(was) + } +} + +impl Drop for LaterGroups { + fn drop(&mut self) { + LATER_GROUPS.with(|l| l.set(self.0)); + } +} + /// Make raster effect `e` follow `a`, the linear part of a Transform effect listed after it, as /// that effect transforms what `e` paints: its distances and raster sizes scale by `a`'s mean -/// scale ([`crate::scale_effect`]), and a Drop Shadow's offset turns, reflects and scales with -/// `a`. Effects that [`follows`] leaves out stay as they are. -fn follow_transform(e: &mut Effect, a: Affine) { +/// scale ([`crate::scale_effect`]), a Drop Shadow's offset turns, reflects and scales with `a`, +/// and a pixel filter's light direction, stroke direction or screen angles turn and reflect with +/// it ([`pixel::turned_directions`]; `later` is the map `e` still goes through when it is drawn, +/// before the Transform effects of the groups around it in [`LATER_GROUPS`]). Effects that +/// [`follows`] leaves out stay as they are. +fn follow_transform(e: &mut Effect, a: Affine, later: Affine) { if !follows(&e.id) { return; } @@ -678,15 +711,22 @@ fn follow_transform(e: &mut Effect, a: Affine) { let p = merged_params(&e.id, &e.params); a * Point::new(num(&p, "x", 7.0), num(&p, "y", 7.0)) }); + let turned = pixel::turned_directions(&e.id, &e.params, a, LATER_GROUPS.with(|l| l.get()) * later); if let Some(k) = vectorcraft_doc::Scaling::factor(a) { crate::scale_effect(e, k); } - if let Some(o) = offset.filter(|o| o.x.is_finite() && o.y.is_finite()) { + let mut set = |key: &str, value: Value| { if !e.params.is_object() { e.params = Value::Object(Map::new()); } - e.params["x"] = json!(o.x); - e.params["y"] = json!(o.y); + e.params[key] = value; + }; + if let Some(o) = offset.filter(|o| o.x.is_finite() && o.y.is_finite()) { + set("x", json!(o.x)); + set("y", json!(o.y)); + } + for (key, value) in turned { + set(key, value); } } diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index 4c8191fd2b..c3238199a2 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -515,18 +515,62 @@ fn laid_out(t: &vectorcraft_doc::TextObject) -> (Vec, kurbo::Bez /// 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) { +/// +/// When `xf` is not a similarity (it scales unevenly, shears or flattens), one weight can't give +/// the stroke the thickness the canvas paints in each direction: `piece` keeps only the run's fill, +/// and the returned path is the area the run's stroke paints around `piece` in text space +/// ([`crate::stroke::outline_region`]: dashes, caps, joins and alignment), placed by `xf` and +/// filled with the stroke's paint, to paint over `piece`. `None` under a similarity and for a run +/// without a stroke. +pub fn paint_type_piece(piece: &mut Node, style: &vectorcraft_doc::CharStyle, bounds: Rect, xf: Affine) -> Option { + let scaling = vectorcraft_doc::Scaling { strokes: true, patterns: true, ..Default::default() }; let mut ap = style.appearance(); ap.pin_gradients(bounds); + let stroke = if is_similarity(xf) { None } else { filled_stroke(piece, &mut ap) }; piece.appearance = ap.into(); - piece.transform(xf, vectorcraft_doc::Scaling { strokes: true, patterns: true, ..Default::default() }); + piece.transform(xf, scaling); + stroke.map(|mut s| { + s.transform(xf, scaling); + s + }) +} + +/// Does `xf` keep angles and scale every direction alike (a move, a rotation, a uniform scale or a +/// reflection), without flattening? +fn is_similarity(xf: Affine) -> bool { + let [a, b, c, d, ..] = xf.as_coeffs(); + let (x, y) = (a.hypot(b), c.hypot(d)); + let tol = 1e-9 * x.max(y); + x.is_finite() && y.is_finite() && x > 0.0 && y > 0.0 && (x - y).abs() <= tol && (a * c + b * d).abs() <= tol * x.max(y) +} + +/// Takes the stroke out of `ap`, the appearance of `piece` (a path or compound path in text space), +/// and returns the area it paints there as a path filled with its paint, opacity, blend mode, +/// effects and overprint, with `piece`'s id. `None` when `ap` has no stroke or it paints nothing. +fn filled_stroke(piece: &Node, ap: &mut Appearance) -> Option { + let i = ap.items.iter().position(|i| matches!(i, AppearanceItem::Stroke(_)))?; + let AppearanceItem::Stroke(st) = ap.items.remove(i) else { return None }; + let path = PathData::from_bezpath(&piece.stroke_path()?); + let region = crate::stroke::outline_region(&path, FillRule::NonZero, &st); + if region.is_empty() { + return None; + } + let fill = vectorcraft_doc::FillLayer { + opacity: st.opacity, + blend: st.blend, + effects: st.effects.clone(), + overprint: st.overprint, + ..vectorcraft_doc::FillLayer::new(st.paint.stroke_as_fill()) + }; + Some(Node::path(piece.id, region, Appearance { items: vec![AppearanceItem::Fill(fill)], ..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 /// the renderer paints them. Each run's path is placed by the type's transform, which also scales its stroke -/// weights and dashes and transforms its pattern tiles; its unplaced gradients are first fixed to +/// weights and dashes and transforms its pattern tiles (a transform that is not a similarity puts +/// the run's stroke on a filled path over it, [`paint_type_piece`]); its unplaced gradients are first fixed to /// the layout's bounds in text space. The object's own unplaced gradients are fixed to the /// bounding box of those bounds in the document. The group is marked as type's outlines /// ([`vectorcraft_doc::NodeExtras::type_outlines`]). @@ -542,8 +586,9 @@ pub fn outline_text(n: &Node) -> Option { continue; } let mut piece = Node::path(n.id, PathData::from_bezpath(bp), Appearance::default()); - paint_type_piece(&mut piece, &run.style, bounds, t.xf); + let stroke = paint_type_piece(&mut piece, &run.style, bounds, t.xf); children.push(Arc::new(piece)); + children.extend(stroke.map(Arc::new)); } if !n.appearance.items.is_empty() && !all.elements().is_empty() { let (below, above) = n.appearance.split_contents(); diff --git a/crates/effects/src/revolve.rs b/crates/effects/src/revolve.rs index 47b1c83206..a49e817ef2 100644 --- a/crates/effects/src/revolve.rs +++ b/crates/effects/src/revolve.rs @@ -171,7 +171,7 @@ pub(crate) fn validate_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value) } } } - let casting = shapes.iter().filter(|s| surface_item(&s.items).is_some_and(|i| paint_of(i).1 * s.opacity > 0.0)); + let casting = shapes.iter().filter(|s| surface_item(&s.items).is_some_and(|i| crate::solids::shadow::casts(paint_of(i).1 * s.opacity))); return check_shadow(p, casting.map(|s| &s.path), b, options); } let (path, _) = object_profile(n, "Revolve")?; @@ -350,8 +350,8 @@ fn geometry(path: &PathData, fx: &[Effect], ctx: &GeomContext) -> PathData { /// The shadow of Revolve `fx` cast by the surface of `path` in `item`'s paint about the axis of /// `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. +/// the shadow off, when `item` is fully transparent or its opacity is not a finite number, or when +/// it casts nothing, and an error when the surface it is cast from is past the limits. /// /// `kept` holds the faces the surface drawn kept for its shadow ([`surface`]); without them the /// surface is swept again for its shadow alone. @@ -366,7 +366,7 @@ fn shadow_of( ) -> 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 { + if !crate::solids::shadow::casts(opacity) { return Ok(None); } let mut caster = vectorcraft_three_d::ShadowCaster::new(); @@ -377,7 +377,7 @@ fn shadow_of( /// 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() + crate::solids::shadow::casts(opacity) && 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 @@ -420,9 +420,9 @@ fn group_shadow( 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. + // A member whose surface is fully transparent, or whose opacity is not a finite number, casts nothing. let ink = crate::solids::shadow::Ink { opacity: opacity * s.opacity, blend }; - if ink.opacity <= 0.0 { + if !ink.casts() { continue; } let faces = cast_surface(&mut caster, &s.path, b, options, kept)?; @@ -1861,6 +1861,55 @@ mod tests { } } } + + /// A surface whose fill, or whose member, is at NaN or infinite opacity casts no shadow, as one + /// at 0 % does, whether the shadow is cast from the surface drawn or swept for it alone; the + /// member beside it still casts its part. + #[test] + fn a_surface_whose_opacity_is_not_a_finite_number_casts_no_shadow() { + let fx = crate::new_effect(REVOLVE, &json!({"shadow": true})).unwrap(); + let group = |opacity: f32| { + let mut other = profile_node(); + other.id = NodeId(2); + other.transform(Affine::translate((120.0, 0.0)), false); + other.opacity = opacity; + let mut g = Node::group(NodeId(9), vec![Arc::new(profile_node()), Arc::new(other)]); + g.appearance.effects.push(fx.clone()); + g + }; + let group_shadows = |g: &Node| { + 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(); + [group_shadow(g.id, &fx, &shapes, b, options, kept).unwrap(), group_shadow(g.id, &fx, &shapes, b, options, vec![]).unwrap()] + .map(|art| format!("{art:?}")) + }; + let expected = group_shadows(&group(0.0)); + for bad in [f32::NAN, f32::INFINITY] { + let mut n = profile_node(); + if let AppearanceItem::Fill(f) = &mut n.appearance.items[0] { + f.opacity = bad; + } + let (path, _) = profile(&n).unwrap(); + let b = path.bounds().unwrap(); + let item = surface_item(&n.appearance.items).unwrap(); + assert!(!casts(&fx, bad), "{bad}: the surface keeps no faces for a shadow"); + let (_, kept) = object_surface(None, &n, &path, &fx, item, false, &mut Copies::default()).unwrap(); + assert_eq!(shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), kept).unwrap(), None, "{bad} drawn"); + assert_eq!(shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), None).unwrap(), None, "{bad} alone"); + let shadows = group_shadows(&group(bad)); + assert!(!expected[0].is_empty() && expected[0] != "[]", "the opaque member casts"); + assert_eq!(shadows, expected, "{bad}: only the opaque member casts"); + } + } } #[cfg(test)] diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index 953768d298..e10771a8d0 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -324,8 +324,7 @@ fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at: reshape_members(n, before, &mut shapes); let b = union_bounds(&shapes).ok_or_else(|| format!("{label} requires a group holding a shape with at least two anchors"))?; check_profiles(id, p, &shapes, b)?; - check_solids(id, p, &shapes)?; - return check_cast(id, p, &shapes); + return check_solids(id, p, &shapes); } let (path, rule) = object_profile(n, label)?; let anchors = || format!("{label} requires a shape with at least two anchors"); @@ -342,38 +341,68 @@ fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at: let b = path.bounds().ok_or_else(anchors)?; let shapes = [Profile { path, rule, items, opacity: 1.0, scopes: vec![] }]; check_profiles(id, p, &shapes, b)?; - check_solids(id, p, &shapes)?; - check_cast(id, p, &shapes) + check_solids(id, p, &shapes) } -/// With the shadow of 3D effect `id` with parameters `p` on, an error when the shadow of `shapes` -/// is past the limits ([`cast_shadow`]). In wireframe mode no shadow is drawn, and none is checked. -fn check_cast(id: &str, p: &Value, shapes: &[Profile]) -> Result<(), String> { - if wireframe::wireframe_params(id, p) { - return Ok(()); - } - cast_shadow(id, p, shapes).map(|_| ()) +/// Does 3D effect `id` with parameters `p` cast a shadow: is it Extrude & Bevel, Inflate or Rotate +/// with Shadows on, shaded? In wireframe mode no shadow is drawn, and none is checked. +fn casts_shadow(id: &str, p: &Value) -> bool { + !is_classic_three_d(id) && shadow::options(p).is_some() && !wireframe::wireframe_params(id, p) +} + +/// Does `item` of a shape with opacity `member` paint anything, and so cast a shadow? +fn visible(item: &AppearanceItem, member: f32) -> bool { + paint_of(item, member).1 > 0.0 } /// Do the solids 3D effect `id` with parameters `p` builds from the profiles of `shapes` about `b` -/// build? Only the profiles no solid of [`check_solids`] is built from are built here: every -/// shape's for Rotate, and for Extrude & Bevel and Inflate the profile of a shape with no fill, -/// whose solids are its strokes' outlines or none. A filled shape's profile is its fill's solid, -/// which [`check_solids`] builds once, about the bounds the effect draws it about. +/// build? Only the profiles no solid of [`check_solids`] is built from are built here: for Rotate +/// every shape's, except with its shadow cast that of a shape with a visible fill, whose plane is +/// the fill's; for Extrude & Bevel and Inflate the profile of a shape with no fill, whose solids +/// are its strokes' outlines or none. A filled shape's profile is its fill's solid, which +/// [`check_solids`] builds once, about the bounds the effect draws it about. fn check_profiles(id: &str, p: &Value, shapes: &[Profile], b: Rect) -> Result<(), String> { - shapes - .iter() - .filter(|s| is_plane(id) || !s.items.iter().any(|i| matches!(i, AppearanceItem::Fill(_)))) - .try_for_each(|s| facets(id, &s.path, s.rule, b, p).map(|_| ())) + let cast = casts_shadow(id, p); + let fill = |s: &Profile| s.items.iter().any(|i| matches!(i, AppearanceItem::Fill(_)) && (!is_plane(id) || visible(i, s.opacity))); + shapes.iter().filter(|s| if is_plane(id) { !(cast && fill(s)) } else { !fill(s) }).try_for_each(|s| facets(id, &s.path, s.rule, b, p).map(|_| ())) } /// Do the solids 3D effect `id` with parameters `p` builds from the fills and strokes of `shapes` -/// fit, each on its own and all of them together ([`built_solids`])? Rotate's planes are not -/// counted. +/// fit, each on its own and all of them together ([`built_solids`]), and with its shadow cast, does +/// the shadow fit? The shadow is cast from the faces those same builds kept ([`cast_built`]), as +/// [`art_for`] casts it: Extrude & Bevel and Inflate build each solid once, and Rotate builds the +/// plane of each visible fill and stroke once. Rotate's planes are not counted, and without its +/// shadow Rotate builds no plane here. fn check_solids(id: &str, p: &Value, shapes: &[Profile]) -> Result<(), String> { - let Some(b) = union_bounds(shapes).filter(|_| !is_plane(id)) else { return Ok(()) }; + let Some(b) = union_bounds(shapes) else { return Ok(()) }; + let cast = casts_shadow(id, p); + if is_plane(id) { + if !cast { + return Ok(()); + } + let mut built = vec![]; + for s in shapes { + for item in &s.items { + if !visible(item, s.opacity) { + built.push(None); + continue; + } + let (area, rule) = region(&s.path, s.rule, item); + #[cfg(test)] + SOLIDS_BUILT.with(|n| n.set(n.get() + 1)); + built.push(facets_and_faces(ROTATE, &area, rule, b, p, true)?.1); + } + } + return cast_built(id, p, shapes, built).map(|_| ()); + } let (parts, bounds) = solid_parts(shapes, b); - built_solids(id, p, &parts, bounds, MAX_OBJECT_FACES).try_for_each(|r| r.map(|_| ())) + if !cast { + return built_solids(id, p, &parts, bounds, MAX_OBJECT_FACES).try_for_each(|r| r.map(|_| ())); + } + let built = built_solids_cast(id, p, &parts, bounds, MAX_OBJECT_FACES, true) + .map(|r| r.map(|solid| solid.and_then(|(_, faces)| faces))) + .collect::, String>>()?; + cast_built(id, p, shapes, built).map(|_| ()) } /// [`profile`], or the error a command reports for object `n`: type with no outlines to build from @@ -596,7 +625,9 @@ pub fn validate_three_d_params(id: &str, p: &Value) -> Result<(), String> { /// blend mode (so overlapping facets don't add up their transparency). Under colored lights a solid /// color with smooth facets is one composite of all its facets ([`composites_facets`]) unless /// `faces`: then each facet is a face of its own, as in a gradient, so the faces can go in one order -/// with the faces of other solids. +/// with the faces of other solids. Under colored lights a gradient with transparent stops is drawn +/// opaque under one mask of its transparency, placed once on all the facets when it has no +/// placement of its own ([`crate::lighting::opaque_surface_paint`]). fn surface(n: &Node, facets: Vec, paint: &Paint, opacity: f32, blend: BlendMode, colored: bool, faces: bool) -> Node { if !faces && composites_facets(&facets, paint, colored) { let mut group = crate::lighting::solid_surface(n.id, &facets, paint); @@ -605,7 +636,7 @@ fn surface(n: &Node, facets: Vec, paint: &Paint, opacity: f32, blend: Ble return group; } // Preserve existing white-light paints and alpha composition exactly. - let (opaque, mask) = if colored { crate::lighting::opaque_paint(paint) } else { (paint.clone(), None) }; + let (opaque, mask) = if colored { crate::lighting::opaque_surface_paint(paint, || facets_bounds(&facets)) } else { (paint.clone(), None) }; let paint = &opaque; let children = facets .into_iter() @@ -642,6 +673,11 @@ fn surface(n: &Node, facets: Vec, paint: &Paint, opacity: f32, blend: Ble group } +/// The bounds of every facet of `facets` together (`Rect::ZERO` when none has any). +pub(crate) fn facets_bounds(facets: &[Facet]) -> Rect { + facets.iter().filter_map(|f| f.path().bounds()).reduce(|a, c| a.union(c)).unwrap_or(Rect::ZERO) +} + /// 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. @@ -733,7 +769,8 @@ thread_local! { /// 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. + /// [`built_solids`] have built on this thread, for the tests. The solids built to cast a shadow + /// ([`cast_shadow`]) count too. static SOLID_GEOMETRY_BUILT: std::cell::Cell = const { std::cell::Cell::new(0) }; } @@ -1435,7 +1472,7 @@ fn art_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile]) -> return Some((vec![], wireframe::wire_surfaces(n.id, 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 cast = casts_shadow(&fx.id, &p); 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`]). @@ -1474,8 +1511,8 @@ fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result = vec![]; let ink = |item: &AppearanceItem, member: f32| { let (_, opacity, blend) = paint_of(item, member); @@ -1483,7 +1520,7 @@ fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result 0.0) { + for item in s.items.iter().filter(|i| ink(i, s.opacity).casts()) { let (area, rule) = region(&s.path, s.rule, item); #[cfg(test)] SOLIDS_BUILT.with(|n| n.set(n.get() + 1)); @@ -1497,21 +1534,25 @@ 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(); + let casts: Vec = inks.iter().map(|i| i.casts()).collect(); #[cfg(test)] SOLIDS_BUILT.with(|n| n.set(n.get() + shapes.len())); + #[cfg(test)] + SOLID_GEOMETRY_BUILT.with(|n| n.set(n.get() + casts.iter().filter(|c| **c).count())); 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) }); + SOLIDS_BUILT.with(|n| n.set(n.get() + usize::from(ink.casts()))); + #[cfg(test)] + SOLID_GEOMETRY_BUILT.with(|n| n.set(n.get() + usize::from(ink.casts()))); + added.push(if ink.casts() { caster.extrude(area, *rule, bounds, extrude_options(p), view) } else { Ok(0..0) }); } added }; for (((item, _, _, _, scopes, _), ink), faces) in parts.iter().zip(inks).zip(added) { - if ink.opacity <= 0.0 { + if !ink.casts() { continue; } // A stroke whose own solid is past the limits is left out; past the shadow's limit for @@ -1529,16 +1570,14 @@ 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| { @@ -1552,42 +1591,25 @@ fn cast_built<'a>(id: &str, p: &Value, shapes: &'a [Profile], built: Vec 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)); + let Some(kept) = kept else { continue }; + cast.push((s.scopes.as_slice(), ink, caster.add_solid(kept)?)); } 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())) { + let (parts, _) = solid_parts(shapes, b); + if parts.len() != built.len() { 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) - } - }; + for ((item, member, _, _, scopes, _), kept) in parts.iter().zip(built) { + let ink = ink(item, *member); + // A fully transparent solid, or a stroke's solid left out of the art, casts nothing. + let Some(kept) = kept.filter(|_| ink.casts()) else { continue }; // 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 { + let faces = match caster.add_solid(kept) { Ok(faces) => faces, Err(e) if matches!(item, AppearanceItem::Stroke(_)) && e != vectorcraft_three_d::TOO_COMPLEX_SHADOW => continue, Err(e) => return Err(e), diff --git a/crates/effects/src/solids/classic.rs b/crates/effects/src/solids/classic.rs index f48b94bce9..0d867462fc 100644 --- a/crates/effects/src/solids/classic.rs +++ b/crates/effects/src/solids/classic.rs @@ -231,14 +231,15 @@ pub(crate) fn stroke_width(face: &Facet, p: &Value) -> f64 { /// for each facet: the edges of the faces on Wireframe, else each face filled in its paint shaded by /// its tone and highlight (with Preserve Spot Colors, a color linked to a swatch as [`linked_face`] /// draws it). A gradient with transparent stops is shaded opaque and then masked by -/// its own transparency, so the shading follows the gradient's coverage. +/// its own transparency, so the shading follows the gradient's coverage; without a placement of its +/// own, it is placed once on all the faces ([`crate::lighting::opaque_surface_paint`]). pub(crate) fn surface(n: &Node, facets: Vec, source: &Paint, opacity: f32, blend: BlendMode, p: &Value) -> Node { let shading = classic_shading(p); let lights = lights(p); let shade = shading_color(p); let preserve = preserves_spot_colors(p); let wire = shading.surface == ClassicSurface::Wireframe; - let (paint, mask) = if wire { (source.clone(), None) } else { crate::lighting::opaque_paint(source) }; + let (paint, mask) = if wire { (source.clone(), None) } else { crate::lighting::opaque_surface_paint(source, || super::facets_bounds(&facets)) }; let paint = &paint; let children = facets .into_iter() diff --git a/crates/effects/src/solids/shadow.rs b/crates/effects/src/solids/shadow.rs index 3906ac2d3c..81542a3722 100644 --- a/crates/effects/src/solids/shadow.rs +++ b/crates/effects/src/solids/shadow.rs @@ -50,6 +50,19 @@ pub(crate) struct Ink { pub(crate) blend: BlendMode, } +impl Ink { + /// Whether art in this ink casts part of a shadow ([`casts`]). + pub(crate) fn casts(self) -> bool { + casts(self.opacity) + } +} + +/// Whether art at `opacity` casts part of a shadow: its opacity is a finite number above zero. +/// Art at zero, negative, NaN or infinite opacity casts nothing. +pub(crate) fn casts(opacity: f32) -> bool { + opacity.is_finite() && opacity > 0.0 +} + /// The shadow of the faces in `caster` as a path of object `id`, cast by art in `ink`: filled /// black at [`SHADOW_OPACITY`] times its opacity, in its blending mode, with the nonzero rule; /// `None` when it casts nothing. diff --git a/crates/effects/src/solids/tests.rs b/crates/effects/src/solids/tests.rs index de1ec75de3..319cdf2949 100644 --- a/crates/effects/src/solids/tests.rs +++ b/crates/effects/src/solids/tests.rs @@ -1082,7 +1082,8 @@ fn geometry_builds(check: impl FnOnce() -> Result<(), String>) -> (usize, Result /// The check builds each solid the effect draws once, about the bounds it draws it about: one for /// a fill and one for each stroke, on an object, on a group's members and on an appearance item, -/// with the shadow on or off. +/// with the shadow on or off. With the shadow on, the shadow is cast from the faces those builds +/// kept, so no solid is built again for it. #[test] fn the_check_builds_each_drawn_solid_once() { for id in [EXTRUDE, CLASSIC_EXTRUDE, INFLATE] { @@ -1098,6 +1099,11 @@ fn the_check_builds_each_drawn_solid_once() { assert_eq!(geometry_builds(|| validate_three_d_at(&n, id, &json!({}), (Some(0), 0))), (1, Ok(())), "{id}: on the fill"); let shadow = json!({"shadow": true}); assert_eq!(geometry_builds(|| validate_solid(&n, id, &shadow)), (2, Ok(())), "{id}: with the shadow on"); + let mut other = square_node(); + other.id = NodeId(2); + let g = Node::group(NodeId(9999), vec![Arc::new(square_node()), Arc::new(other)]); + assert_eq!(geometry_builds(|| validate_solid(&g, id, &shadow)), (4, Ok(())), "{id}: a group with the shadow on"); + assert_eq!(geometry_builds(|| validate_three_d_at(&n, id, &shadow, (Some(0), 0))), (1, Ok(())), "{id}: the fill with the shadow on"); } } @@ -1954,6 +1960,57 @@ fn classic_shading_keeps_a_gradients_transparency() { } } +/// A gradient without a placement and with a transparent stop, under colored lights or classic +/// shading, is placed once for the whole surface: every face's color and the surface's opacity mask +/// share one placement, so the color and transparency ramps line up across the faces. A gradient +/// placed in the document keeps its placement. +#[test] +fn a_transparent_unplaced_gradient_has_one_placement_for_color_and_mask() { + use vectorcraft_doc::color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop}; + // The source's stops carry an unusual midpoint, so its color and mask copies can be told from + // the light ramps. + const MARK: f32 = 0.37; + let mut first = GradientStop::new(0.0, RED); + first.midpoint = MARK; + let mut end = GradientStop::new(1.0, Color::BLACK); + end.opacity = 0.25; + let unplaced = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![first, end])); + let placed = GradientGeom { start: Point::new(90.0, 100.0), end: Point::new(230.0, 140.0), aspect: 1.0, focal: None }; + // The placement of each copy of the source gradient: its own, else its fit on the path it fills. + fn placements(n: &Node, out: &mut Vec) { + n.walk(&mut |c| { + if let Some(mask) = &c.extras().mask { + placements(&mask.art, out); + } + let bounds = c.path_data().and_then(|p| p.bounds()).unwrap_or(Rect::ZERO); + for item in &c.appearance.items { + if let Paint::Gradient(g) = paint_ref(item) + && g.gradient.stops.first().is_some_and(|s| s.midpoint == MARK) + { + out.push(g.resolve(bounds)); + } + } + }); + } + let lit = json!({"lights": [{"color": "#ff8080"}]}); + for (id, params) in [(EXTRUDE, lit.clone()), (INFLATE, lit.clone()), (ROTATE, lit), (CLASSIC_EXTRUDE, json!({}))] { + for geom in [None, Some(placed)] { + let mut n = square_node(); + n.appearance.items = vec![AppearanceItem::Fill(FillLayer::new(Paint::Gradient(Box::new(GradientPaint { geom, ..unplaced.clone() }))))]; + n.appearance.effects.push(fx(id, params.clone())); + let art = solid_art(&n).unwrap_or_else(|| panic!("{id}")); + let mut masks = 0; + art.walk(&mut |c| masks += usize::from(c.extras().mask.is_some())); + assert!(masks > 0, "{id}: the surface carries the gradient's transparency as a mask"); + let mut found = vec![]; + placements(&art, &mut found); + assert!(found.len() > 2, "{id}: the faces' colors and the mask"); + let expected = geom.unwrap_or(found[0]); + assert!(found.iter().all(|g| *g == expected), "{id} {geom:?}: {found:?}"); + } + } +} + /// A group member in a gradient with transparent stops keeps the shared back-to-front order of /// every member's faces: its faces go in runs that carry its opacity mask, and the other member's /// faces are drawn between them where they are in front of some and behind others. Here a square diff --git a/crates/effects/src/solids/tests_shadow.rs b/crates/effects/src/solids/tests_shadow.rs index 4d62961612..d24cd6e86f 100644 --- a/crates/effects/src/solids/tests_shadow.rs +++ b/crates/effects/src/solids/tests_shadow.rs @@ -312,3 +312,125 @@ fn the_shadow_cast_from_the_solids_drawn_is_the_shadow_of_solids_built_for_it() } } } + +/// A stroke's solid left out of the art (past its own limits) keeps no faces, and the shadow cast +/// from the faces the solids kept leaves it out without building it: it casts nothing, as it draws +/// nothing, and the fill's solid still casts. +#[test] +fn a_stroke_left_out_of_the_art_casts_no_shadow() { + for id in [EXTRUDE, INFLATE] { + let n = stroked_square(1, 0.0, 1.0); + let (path, rule) = profile(&n).unwrap(); + let shapes = [Profile { path, rule, items: solid_paints(&n), opacity: 1.0, scopes: vec![] }]; + let p = crate::merged_params(id, &json!({"shadow": true})); + let (parts, bounds) = solid_parts(&shapes, union_bounds(&shapes).unwrap()); + let mut built: Vec> = + built_solids_cast(id, &p, &parts, bounds, MAX_OBJECT_FACES, true).map(|r| r.unwrap().and_then(|(_, faces)| faces)).collect(); + let stroke = parts.iter().position(|(item, ..)| matches!(item, AppearanceItem::Stroke(_))).unwrap(); + assert!(built.len() == 2 && built.iter().all(Option::is_some), "{id}"); + let (both, _, cast) = cast_built(id, &p, &shapes, built.clone()).unwrap().unwrap(); + assert_eq!(cast.len(), 2, "{id}: the fill and the stroke cast"); + built[stroke] = None; + let start = SOLIDS_BUILT.with(std::cell::Cell::get); + let (fill, _, cast) = cast_built(id, &p, &shapes, built).unwrap().unwrap(); + assert_eq!(SOLIDS_BUILT.with(std::cell::Cell::get), start, "{id}: no solid is built for the shadow"); + assert_eq!(cast.len(), 1, "{id}: the stroke left out casts nothing"); + assert!(!fill.is_empty() && fill.len() < both.len(), "{id}: only the fill's faces are cast"); + } +} + +/// A command accepts each shadowed object that draws with its shadow, and with Rotate builds the +/// plane of each visible fill and stroke once for the shadow: a fully transparent one casts nothing. +#[test] +fn the_check_accepts_the_shadowed_objects_that_draw() { + for id in [EXTRUDE, INFLATE, ROTATE] { + for params in shadow_settings(id) { + for n in shadowed(id, ¶ms) { + let mut drawn = 0; + art(&n, id).unwrap().walk(&mut |c| drawn += usize::from(shadow_opacity(c).is_some())); + assert!(drawn > 0, "{id} {params}"); + assert_eq!(validate_solid(&n, id, ¶ms), Ok(()), "{id} {params}"); + } + } + } + let shadow = json!({"shadow": true}); + for (stroke, planes) in [(1.0, 2), (0.5, 2), (0.0, 1)] { + let n = stroked_square(1, 0.0, stroke); + let start = SOLIDS_BUILT.with(std::cell::Cell::get); + assert_eq!(validate_solid(&n, ROTATE, &shadow), Ok(()), "{stroke}"); + assert_eq!(SOLIDS_BUILT.with(std::cell::Cell::get) - start, planes, "Rotate, a stroke at {stroke}"); + } +} + +/// In wireframe mode no shadow is drawn, so the check casts none: with Shadows on, Rotate builds no +/// plane for a shadow, and Extrude & Bevel and Inflate build each solid once, as with the shadow off. +#[test] +fn the_check_casts_no_shadow_in_wireframe_mode() { + let n = stroked_square(1, 0.0, 1.0); + let wire = json!({"shadow": true, "render": {"mode": "wireframe"}}); + for (id, solids) in [(ROTATE, 0), (EXTRUDE, 2), (INFLATE, 2)] { + let start = SOLIDS_BUILT.with(std::cell::Cell::get); + assert_eq!(validate_solid(&n, id, &wire), Ok(()), "{id}"); + assert_eq!(SOLIDS_BUILT.with(std::cell::Cell::get) - start, solids, "{id}"); + } +} + +/// The opacity of each part of the shadow of `n` (its 3D effect's shadow on) and the shadow's art, +/// as [`cast_shadow`] casts it from solids built for the shadow alone and as [`cast_built`] casts +/// it from the faces the solids drawn kept. +fn cast_parts(n: &Node) -> [(Vec, String); 2] { + 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 p = crate::merged_params(&fx.id, &fx.params); + let (_, built) = surfaces_for(None, n, fx, &shapes, true).unwrap(); + [cast_shadow(&fx.id, &p, &shapes), cast_built(&fx.id, &p, &shapes, built)].map(|c| { + let (caster, settings, cast) = c.unwrap().unwrap(); + let inks = cast.iter().map(|(_, ink, _)| ink.opacity).collect(); + (inks, format!("{:?}", shadow::scoped_art(n.id, &caster, settings, cast, has_masks(&shapes)))) + }) +} + +/// A fill, a stroke or a member whose opacity is NaN or infinite casts no part of the shadow, as one +/// at 0 % does, whether the shadow is cast from solids built for it or from the solids drawn; the +/// art beside it still casts its part. +#[test] +fn art_whose_opacity_is_not_a_finite_number_casts_no_shadow() { + // The art with opacity `opacity` in one place: a square's stroke, the fill of a group's second + // member, and a group's second member. + let objects = |opacity: f32| { + let mut fill = square_node(2, 200.0); + for item in &mut fill.appearance.items { + if let AppearanceItem::Fill(f) = item { + f.opacity = opacity; + } + } + let mut member = square_node(2, 200.0); + member.opacity = opacity; + [ + stroked_square(1, 0.0, opacity), + Node::group(NodeId(9), vec![Arc::new(square_node(1, 0.0)), Arc::new(fill)]), + Node::group(NodeId(9), vec![Arc::new(square_node(1, 0.0)), Arc::new(member)]), + ] + }; + for id in [EXTRUDE, INFLATE, ROTATE] { + for bad in [f32::NAN, f32::INFINITY] { + for (i, (mut n, mut clear)) in objects(bad).into_iter().zip(objects(0.0)).enumerate() { + n.appearance.effects.push(crate::new_effect(id, &json!({"shadow": true})).unwrap()); + clear.appearance.effects.push(crate::new_effect(id, &json!({"shadow": true})).unwrap()); + let expected = cast_parts(&clear); + for (k, (inks, shadow)) in cast_parts(&n).into_iter().enumerate() { + assert_eq!(inks, vec![1.0], "{id} {bad} object {i} cast {k}: only the opaque art casts"); + assert_eq!(shadow, expected[k].1, "{id} {bad} object {i} cast {k}"); + } + let mut opacities = vec![]; + art(&n, id).unwrap().walk(&mut |c| opacities.extend(shadow_opacity(c))); + assert_eq!(opacities, vec![0.5], "{id} {bad} object {i}"); + } + } + } +} diff --git a/crates/effects/src/svg_filter.rs b/crates/effects/src/svg_filter.rs index 0c4bff0f1d..67826614e1 100644 --- a/crates/effects/src/svg_filter.rs +++ b/crates/effects/src/svg_filter.rs @@ -1,7 +1,8 @@ //! Effect › SVG Filters (`svg.filter`): an SVG `` element applied as a live raster effect. //! The filter runs on the object's pixels as SVG 1.1 describes it //! (), drawn by resvg. Its lengths are in points times -//! the effect's `scale`, its user space starts at the effect's `origin`, its object bounding box is the box of the drawn pixels, and it runs at the +//! the effect's `scale`, its user space starts at the effect's `origin`, its axes point as the effect's `axes` say (a turned or +//! skewed user space), its object bounding box is the box of the drawn pixels, and it runs at the //! Document Raster Effects resolution when the view shows the object at a finer one. use std::sync::Arc; @@ -1224,13 +1225,16 @@ fn region_length(v: Option<&str>, default: f64, user: bool) -> Length { } /// An SVG filter effect: the filter's XML, how many points one of its units is, where its user -/// space's origin lies in the document, and its region. +/// space's origin lies in the document, which way its axes point, and its region. #[derive(Clone, Debug, PartialEq)] pub struct SvgFilterFx { /// The filter as it is drawn and written ([`rebuilt`]). xml: Arc, scale: f64, origin: Vec2, + /// The directions of the user space's axes in the document, before `scale` ([`axes_param`]): + /// the identity unless the user space is turned, skewed or scaled unevenly. + axes: Affine, /// Its region (filter effects region): x, y, width, height. region: [Length; 4], /// Is the region in user space with a length measured against the object's box? It is then @@ -1250,11 +1254,92 @@ fn origin_param(p: &Value) -> Vec2 { Vec2::new(at(0), at(1)) } +/// The largest magnitude of an entry of an SVG filter effect's `axes`. +pub const MAX_AXIS: f64 = 1000.0; + +/// The smallest magnitude of the determinant of an SVG filter effect's `axes`. +pub const MIN_AXES_DET: f64 = 0.001; + +/// The `axes` of an SVG filter effect's parameters `p`: `[a, b, c, d]`, the document directions +/// of one unit along the filter's x axis (`[a, b]`) and its y axis (`[c, d]`), before `scale`. +/// The identity when absent; `None` when it isn't four numbers from -[`MAX_AXIS`] to [`MAX_AXIS`] +/// whose determinant is at least [`MIN_AXES_DET`] across ([`valid_axes`]). +fn axes_param(p: &Value) -> Option { + match p.get("axes") { + None | Some(Value::Null) => Some(Affine::IDENTITY), + Some(v) => valid_axes(v), + } +} + +/// `v` as the linear map of an SVG filter effect's `axes` ([`axes_param`]), when it is one. +pub fn valid_axes(v: &Value) -> Option { + let n: Vec = v.as_array()?.iter().map(Value::as_f64).collect::>()?; + axes_of(<[f64; 4]>::try_from(n).ok()?) +} + +/// `[a, b, c, d]` as the linear map of an SVG filter effect's `axes`, when the effect takes it ([`valid_axes`]). +fn axes_of([a, b, c, d]: [f64; 4]) -> Option { + let det = a * d - b * c; + ([a, b, c, d].iter().all(|v| v.is_finite() && v.abs() <= MAX_AXIS) && det.abs() >= MIN_AXES_DET).then(|| Affine::new([a, b, c, d, 0.0, 0.0])) +} + +/// A filter's user space as the SVG filter effect stores it ([`user_space`]). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct UserSpace { + /// The effect's `scale`. + pub scale: f64, + /// The effect's `origin`. + pub origin: [f64; 2], + /// The effect's `axes`; `None` when the axes are the document's. + pub axes: Option<[f64; 4]>, +} + +/// `ts`, a user space mapped to the document, as the SVG filter effect's `scale` (the square root +/// of its area scale), `origin` and, when it turns, skews or scales unevenly, `axes`. `None` when +/// it can't be stored: not finite, `scale` outside 0.001..1000, or `axes` the effect refuses +/// ([`valid_axes`]). +pub fn user_space(ts: Affine) -> Option { + let [a, b, c, d, e, f] = ts.as_coeffs(); + if ![a, b, c, d, e, f].iter().all(|v| v.is_finite()) { + return None; + } + let scale = ts.determinant().abs().sqrt(); + if !(0.001..=1000.0).contains(&scale) { + return None; + } + let even = b == 0.0 && c == 0.0 && a > 0.0 && (a - d).abs() <= 1e-9 * a.max(1.0); + if even { + return Some(UserSpace { scale: a, origin: [e, f], axes: None }); + } + let axes = [a, b, c, d].map(|v| v / scale); + axes_of(axes)?; + Some(UserSpace { scale, origin: [e, f], axes: Some(axes) }) +} + +/// The longest a unit vector becomes under the linear part of `a` (its largest singular value). +fn stretch(a: Affine) -> f64 { + let [a, b, c, d, _, _] = a.as_coeffs(); + let sum = a * a + b * b + c * c + d * d; + let det = a * d - b * c; + (0.5 * (sum + (sum * sum - 4.0 * det * det).max(0.0).sqrt())).sqrt() +} + +/// The share of a raster pixel, `space.px` points wide, that a pixel of the Document Raster Effects +/// resolution is (at most 1). +fn raster_resolution(space: &PixelSpace) -> f64 { + if space.line.is_finite() && space.line > 0.0 && space.px.is_finite() && space.px > 0.0 { (space.px / space.line).min(1.0) } else { 1.0 } +} + +/// How many times the raster's pixels a turned filter's canvas may hold ([`SvgFilterFx::turned_canvas`]). +const TURNED_ROOM: f64 = 4.0; + impl SvgFilterFx { - /// The effect's parameters `p` (defaults merged in): `xml`, the `` element, `scale` - /// and `origin`. `None` when `xml` isn't a filter [`check`] takes, however the effect came to - /// hold it (an opened file, a script): the object is then drawn, printed and exported without it. + /// The effect's parameters `p` (defaults merged in): `xml`, the `` element, `scale`, + /// `origin` and `axes`. `None` when `xml` isn't a filter [`check`] takes, or `axes` isn't + /// valid ([`axes_param`]), however the effect came to hold it (an opened file, a script): the + /// object is then drawn, printed and exported without it. pub(crate) fn parse(p: &Value) -> Option { + let axes = axes_param(p)?; let xml = checked(text(p, "xml", ""))?; let (wrapped, _) = wrap(&xml); let doc = roxmltree::Document::parse(&wrapped).ok()?; @@ -1273,7 +1358,17 @@ impl SvgFilterFx { let (window, blur) = (largest(&["radius", "kernelUnitLength"]), largest(&["stdDeviation"])); let box_units = f.attribute("primitiveUnits").is_some_and(|u| u.trim() == "objectBoundingBox"); let scale = num(p, "scale", 1.0).clamp(1e-3, 1e3); - Some(Self { xml, scale, origin: origin_param(p), region, measured, window, blur, box_units }) + Some(Self { xml, scale, origin: origin_param(p), axes, region, measured, window, blur, box_units }) + } + + /// The filter's user space → the document: moved to `origin`, scaled by `scale`, along `axes`. + pub fn to_doc(&self) -> Affine { + Affine::translate(self.origin) * Affine::scale(self.scale) * self.axes + } + + /// The box of `bounds` (document units) in the filter's user space. + fn user_box(&self, bounds: Rect) -> Rect { + self.to_doc().inverse().transform_rect_bbox(bounds) } /// The filter's region in its user space for an object whose box there is `b`: lengths in user @@ -1308,11 +1403,11 @@ impl SvgFilterFx { with_attributes(xml, &[("x", r.x0), ("y", r.y0), ("width", r.width()), ("height", r.height())]) } - /// The filter as SVG output writes it (one unit a point, [`Self::in_points`]) for an object - /// whose box in the document is `bounds`: in its SVG 1.1 form ([`svg11`]), `None` when SVG 1.1 - /// can't hold it ([`Self::writes_as_svg11`]). - pub fn written_xml(&self, bounds: Rect) -> Option { - let out = self.with_region(&self.svg11_form()?, (bounds - self.origin).scale_from_origin(1.0 / self.scale))?; + /// The filter as SVG output writes it, in its user space ([`Self::to_doc`]), for an object + /// whose box in that user space is `user_box`: in its SVG 1.1 form ([`svg11`]), `None` when SVG + /// 1.1 can't hold it ([`Self::writes_as_svg11`]). + pub fn written_xml(&self, user_box: Rect) -> Option { + let out = self.with_region(&self.svg11_form()?, user_box)?; (written_len(&out) <= MAX_WRITTEN_XML).then_some(out) } @@ -1345,10 +1440,11 @@ impl SvgFilterFx { if !(space.px.is_finite() && space.px > 0.0) { return 1.0; } - let mut s: f64 = if space.line.is_finite() && space.line > 0.0 { (space.px / space.line).min(1.0) } else { 1.0 }; - // A length spans length × scale / px raster pixels, or a fraction of the box. + let mut s = raster_resolution(space); + // A length spans at most length × scale × the axes' stretch / px raster pixels, or a fraction of the box. + let reach = self.scale * stretch(self.axes); for (length, most) in [(self.window, MAX_WINDOW_PX), (self.blur, MAX_BLUR_PX)] { - let px = if self.box_units { length * box_px.max(0.0) } else { length * self.scale / space.px }; + let px = if self.box_units { length * box_px.max(0.0) } else { length * reach / space.px }; if px * s > most { s = most / px; } @@ -1374,15 +1470,21 @@ impl SvgFilterFx { self.measured } - /// Does one unit of the filter's user space measure one point (its `scale` is 1)? - pub fn in_points(&self) -> bool { - self.scale == 1.0 + /// Is the filter's user space the document's, only moved: one unit a point, its axes the + /// document's (`scale` 1, no `axes`)? + pub fn moves_only(&self) -> bool { + self.scale == 1.0 && self.axes == Affine::IDENTITY + } + + /// Can SVG import store the filter's user space ([`Self::to_doc`]) again ([`user_space`])? Its + /// `scale` and `axes` together can scale it past what one of them holds alone. + pub fn opens_again(&self) -> bool { + user_space(self.to_doc()).is_some() } /// How far beyond `bounds` (document units) the filter can draw: its region's reach past them. pub fn outset(&self, bounds: Rect) -> f64 { - let b = (bounds - self.origin).scale_from_origin(1.0 / self.scale); - let region = self.region_in(b).scale_from_origin(self.scale) + self.origin; + let region = self.to_doc().transform_rect_bbox(self.region_in(self.user_box(bounds))); let reach = [bounds.x0 - region.x0, bounds.y0 - region.y0, region.x1 - bounds.x1, region.y1 - bounds.y1].into_iter().fold(0.0, f64::max); if reach.is_finite() { reach.min(MAX_OUTSET) } else { 0.0 } } @@ -1397,20 +1499,40 @@ impl SvgFilterFx { } // Art that draws no pixels still has a box: the whole raster stands for it. let (x0, y0, x1, y1) = drawn_box(data, w, h).unwrap_or((0, 0, w, h)); - let s = self.resolution(space, (x1 - x0).max(y1 - y0) as f64); - let (sw, sh) = ((w as f64 * s).ceil().max(1.0) as u32, (h as f64 * s).ceil().max(1.0) as u32); - let Some(png) = png_of(data, w, x0, y0, x1, y1).map(Arc::new) else { return }; - let k = self.scale; - // Filter user space → the small canvas, and the image's pixels → filter user space. - let outer = Affine::scale(s) * space.to_doc.inverse() * Affine::translate(self.origin) * Affine::scale(k); - let place = Affine::scale(1.0 / k) * Affine::translate(-self.origin) * space.to_doc * Affine::translate(Vec2::new(x0 as f64, y0 as f64)); - let b = place.transform_rect_bbox(Rect::new(0.0, 0.0, (x1 - x0) as f64, (y1 - y0) as f64)); + let user = self.to_doc(); + // Filter user space → the small canvas, and the small canvas → the raster's pixels. + let (sw, sh, outer, back) = if self.axes == Affine::IDENTITY { + let s = self.resolution(space, (x1 - x0).max(y1 - y0) as f64); + let (sw, sh) = ((w as f64 * s).ceil().max(1.0) as u32, (h as f64 * s).ceil().max(1.0) as u32); + (sw, sh, Affine::scale(s) * space.to_doc.inverse() * user, Affine::scale(1.0 / s)) + } else { + // The canvas measures the costly lengths in its own pixels. + let drawn = Rect::new(x0 as f64, y0 as f64, x1 as f64, y1 as f64); + let Some(canvas) = self.turned_canvas(w, h, raster_resolution(space), drawn, space) else { return }; + canvas + }; + // The source as an image, its size, and the map from its pixels to filter user space. The + // object's box in user space is the image's box there, which resvg measures the region and + // a primitive's lengths in the object's box against. In a turned or skewed user space the + // source is first drawn onto the canvas's pixels, whose rows and columns run along the user + // space's axes, and cut to the pixels it draws there: the image then lies along those axes, + // and its box is the box of the art in the user space, not of the raster's box turned into it. + let source = if self.axes == Affine::IDENTITY { + let place = user.inverse() * space.to_doc * Affine::translate(Vec2::new(x0 as f64, y0 as f64)); + png_of(data, w, x0, y0, x1, y1).map(|png| (png, x1 - x0, y1 - y0, place)) + } else { + on_canvas(data, w, h, sw, sh, outer * user.inverse() * space.to_doc) + .map(|(png, cx, cy, iw, ih)| (png, iw, ih, outer.inverse() * Affine::translate(Vec2::new(cx as f64, cy as f64)))) + }; + let Some((png, iw, ih, place)) = source else { return }; + let png = Arc::new(png); + let b = place.transform_rect_bbox(Rect::new(0.0, 0.0, iw as f64, ih as f64)); let Some(drawn) = self.drawn_xml(b).and_then(|xml| with_id(&xml, DRAWN_ID)) else { return }; let svg = format!( "{drawn}", matrix(outer), - x1 - x0, - y1 - y0, + iw, + ih, matrix(place), base64(&png) ); @@ -1420,19 +1542,65 @@ impl SvgFilterFx { } let Some(mut small) = tiny_skia::Pixmap::new(sw, sh) else { return }; resvg::render(&tree, tiny_skia::Transform::identity(), &mut small.as_mut()); - let out = if s < 1.0 { + let out = if back == Affine::IDENTITY { + small + } else { let Some(mut full) = tiny_skia::Pixmap::new(w as u32, h as u32) else { return }; let paint = tiny_skia::PixmapPaint { quality: tiny_skia::FilterQuality::Bilinear, ..Default::default() }; - let up = (1.0 / s) as f32; - full.draw_pixmap(0, 0, small.as_ref(), &paint, tiny_skia::Transform::from_scale(up, up), None); + let [a, b, c, d, e, f] = back.as_coeffs().map(|v| v as f32); + full.draw_pixmap(0, 0, small.as_ref(), &paint, tiny_skia::Transform::from_row(a, b, c, d, e, f), None); full - } else { - small }; if out.data().len() == data.len() { data.copy_from_slice(out.data()); } } + + /// The canvas a filter whose user space is turned, skewed or scaled unevenly runs on, for a + /// `w` × `h` raster lying in the document as `space` says, at resolution `s` + /// ([`raster_resolution`]), whose art draws within `drawn` (raster pixels): its axes are the user + /// space's, so the filter's offsets, blurs and other lengths run along them as SVG 1.1 measures + /// them, and it covers what the raster shows. Along each of its axes its pixels are about as + /// large as the raster's at `s`, and coarser when it would hold more than [`TURNED_ROOM`] times + /// as many pixels as the raster does at `s`, and when a morphology radius or kernel unit would + /// span more than 32 of its pixels or a blur's standard deviation more than 512 (a length in the + /// object's box measured against the art's box on the canvas). Returns its size, the map from + /// user space to it, and the map from it to the raster's pixels; `None` when the spaces can't + /// be measured. + fn turned_canvas(&self, w: usize, h: usize, s: f64, drawn: Rect, space: &PixelSpace) -> Option<(u32, u32, Affine, Affine)> { + let to_px = space.to_doc.inverse() * self.to_doc(); + let from_px = to_px.inverse(); + let ub = from_px.transform_rect_bbox(Rect::new(0.0, 0.0, w as f64, h as f64)); + let most = ((w as f64 * s).ceil().max(1.0) * (h as f64 * s).ceil().max(1.0) * TURNED_ROOM).max(1.0); + // Canvas pixels a unit along each axis of the user space: as many as the raster's at `s`. + let [a, b, c, d, _, _] = to_px.as_coeffs(); + let (mut qx, mut qy) = (s * a.hypot(b), s * c.hypot(d)); + let pixels = ub.width() * qx * ub.height() * qy; + if pixels > most { + let k = (most / pixels).sqrt(); + (qx, qy) = (qx * k, qy * k); + } + // A length along an axis spans length × q canvas pixels, or length × the art's box on the + // canvas along that axis: both shrink with q. + let art = from_px.transform_rect_bbox(drawn); + for (length, cap) in [(self.window, MAX_WINDOW_PX), (self.blur, MAX_BLUR_PX)] { + let px = if self.box_units { length * (art.width() * qx).max(art.height() * qy) } else { length * qx.max(qy) }; + if px > cap { + let k = cap / px; + (qx, qy) = (qx * k, qy * k); + } + } + if !(qx.is_finite() && qx > 0.0 && qy.is_finite() && qy > 0.0 && ub.is_finite()) { + return None; + } + let (cw, ch) = ((ub.width() * qx).ceil().max(1.0), (ub.height() * qy).ceil().max(1.0)); + // Rounding up adds at most a row and a column. + if cw * ch > most + cw + ch + 1.0 { + return None; + } + let outer = Affine::scale_non_uniform(qx, qy) * Affine::translate(Vec2::new(-ub.x0, -ub.y0)); + Some((cw as u32, ch as u32, outer, to_px * outer.inverse())) + } } /// The farthest a filter's region reaches beyond the object, in points. @@ -1450,6 +1618,22 @@ fn drawn_box(data: &[u8], w: usize, h: usize) -> Option<(usize, usize, usize, us (x1 > x0 && y1 > y0).then_some((x0, y0, x1, y1)) } +/// The pixels of `data` (premultiplied RGBA8, `w` × `h`) drawn onto a `cw` × `ch` canvas through +/// `to_canvas` (the raster's pixels → the canvas's), cut to the box of the canvas pixels that aren't +/// transparent (the whole canvas when all are): a PNG of them, the box's corner on the canvas, and +/// its size. +fn on_canvas(data: &[u8], w: usize, h: usize, cw: u32, ch: u32, to_canvas: Affine) -> Option<(Vec, usize, usize, usize, usize)> { + let size = tiny_skia::IntSize::from_wh(u32::try_from(w).ok()?, u32::try_from(h).ok()?)?; + let raster = tiny_skia::Pixmap::from_vec(data.to_vec(), size)?; + let mut canvas = tiny_skia::Pixmap::new(cw, ch)?; + let paint = tiny_skia::PixmapPaint { quality: tiny_skia::FilterQuality::Bilinear, ..Default::default() }; + let [a, b, c, d, e, f] = to_canvas.as_coeffs().map(|v| v as f32); + canvas.draw_pixmap(0, 0, raster.as_ref(), &paint, tiny_skia::Transform::from_row(a, b, c, d, e, f), None); + let (cw, ch) = (cw as usize, ch as usize); + let (x0, y0, x1, y1) = drawn_box(canvas.data(), cw, ch).unwrap_or((0, 0, cw, ch)); + Some((png_of(canvas.data(), cw, x0, y0, x1, y1)?, x0, y0, x1 - x0, y1 - y0)) +} + /// The pixels of `data` (premultiplied RGBA8, `w` wide) in columns x0..x1 and rows y0..y1, as a PNG. fn png_of(data: &[u8], w: usize, x0: usize, y0: usize, x1: usize, y1: usize) -> Option> { use image::ImageEncoder; diff --git a/crates/effects/src/svg_filter/tests.rs b/crates/effects/src/svg_filter/tests.rs index f93cb53124..4ab6328359 100644 --- a/crates/effects/src/svg_filter/tests.rs +++ b/crates/effects/src/svg_filter/tests.rs @@ -222,6 +222,154 @@ fn user_space_starts_at_the_origin() { assert!((filter(json!({ "xml": half, "origin": [-10.0, 0.0] })).outset(b) - 10.0).abs() < 1e-9); } +/// The opacity of `data` (`w` wide) after the filter `xml` with `params` runs on a blue square +/// over 10..20 pt of a 40 pt raster one point a pixel, at each of `points`. +fn turned_run(xml: &str, params: serde_json::Value, points: &[(usize, usize)]) -> Vec { + let w = 40; + let mut data = image(w, w, |x, y| if (10..20).contains(&x) && (10..20).contains(&y) { [0, 0, 255, 255] } else { [0; 4] }); + let mut p = params; + p["xml"] = json!(xml); + filter(p).apply(&mut data, w, w, &space(w, w, 1.0, 1.0)); + points.iter().map(|&(x, y)| at(&data, w, x, y)[3]).collect() +} + +const SHIFT_X: &str = r#""#; + +/// With `axes`, the filter runs in its turned or skewed user space: an offset along its x axis +/// moves the art along that axis in the document (SVG 1.1 measures a primitive's lengths in the +/// user space of the element the filter is on). +#[test] +fn a_turned_user_space_moves_the_art_along_its_own_axes() { + // The square spans 10..20 pt; moved 4 pt along x it covers 14..24 across. + let points = [(22, 15), (15, 22), (12, 11)]; + assert_eq!(turned_run(SHIFT_X, json!({}), &points), [255, 0, 0], "the document's axes: to the right"); + // Turned a quarter turn: the filter's x axis points down the page. + let down = turned_run(SHIFT_X, json!({ "axes": [0.0, 1.0, -1.0, 0.0] }), &points); + assert_eq!(down, [0, 255, 0], "moved down, not to the right"); + // Skewed: one unit along y is one across and one down, so dy 4 moves the art 4 pt each way. + let shift_y = r#""#; + let skewed = turned_run(shift_y, json!({ "axes": [1.0, 0.0, 1.0, 1.0] }), &[(22, 22), (11, 22), (11, 11)]); + assert!(skewed[0] > 200 && skewed[1] < 60 && skewed[2] < 60, "moved across and down: {skewed:?}"); +} + +#[test] +fn axes_the_effect_cannot_measure_are_not_drawn() { + for axes in [json!([0, 0, 0, 0]), json!([1, 2]), json!([1, 0, 0, "1"]), json!([2000, 0, 0, 1]), json!([0.01, 0, 0, 0.01]), json!("turned")] { + let e = Effect { id: SVG_FILTER.into(), params: json!({ "xml": SHIFT_X, "axes": axes }), visible: true }; + assert!(raster_effects(&[e]).is_empty(), "{axes}: drawn without it"); + assert!(valid_axes(&axes).is_none(), "{axes}"); + } + assert_eq!(valid_axes(&json!([0, 1, -1, 0])), Some(Affine::new([0.0, 1.0, -1.0, 0.0, 0.0, 0.0]))); +} + +/// A region measured against the object's box is measured against its box in the turned user +/// space: a diamond turned an eighth of a turn is a square there, and a flood over 0..100% of it +/// covers the diamond alone. +#[test] +fn a_turned_region_is_measured_against_the_box_in_its_user_space() { + let w = 40; + let diamond = |x: usize, y: usize| (x as f64 - 19.5).abs() + (y as f64 - 19.5).abs() <= 10.0; + let mut data = image(w, w, |x, y| if diamond(x, y) { [0, 0, 255, 255] } else { [0; 4] }); + let flood = r##""##; + let h = std::f64::consts::FRAC_1_SQRT_2; + filter(json!({ "xml": flood, "axes": [h, h, -h, h] })).apply(&mut data, w, w, &space(w, w, 1.0, 1.0)); + assert_eq!(at(&data, w, 20, 20), [255, 0, 0, 255], "inside the diamond"); + assert!(at(&data, w, 12, 12)[3] < 40, "outside the diamond, inside its box on the page: {:?}", at(&data, w, 12, 12)); +} + +/// In a turned user space, a region in the object's bounding box (the default `filterUnits`) and a +/// primitive's lengths in it (`primitiveUnits="objectBoundingBox"`) are measured against the +/// object's box there: on a diamond turned an eighth of a turn, a flood over 0..100% of the box +/// covers the diamond alone. +#[test] +fn a_turned_filter_measures_box_units_against_the_box_in_its_user_space() { + let w = 40; + let h = std::f64::consts::FRAC_1_SQRT_2; + let region = r##""##; + let primitive = r##""##; + for xml in [region, primitive] { + let diamond = |x: usize, y: usize| (x as f64 - 19.5).abs() + (y as f64 - 19.5).abs() <= 10.0; + let mut data = image(w, w, |x, y| if diamond(x, y) { [0, 0, 255, 255] } else { [0; 4] }); + filter(json!({ "xml": xml, "axes": [h, h, -h, h] })).apply(&mut data, w, w, &space(w, w, 1.0, 1.0)); + assert_eq!(at(&data, w, 20, 20), [255, 0, 0, 255], "{xml}: inside the diamond"); + assert!(at(&data, w, 12, 12)[3] < 40, "{xml}: outside the diamond, inside its box on the page: {:?}", at(&data, w, 12, 12)); + } +} + +/// SVG import stores a filter's user space again only when `scale` and `axes` together stay within +/// what it holds: each alone can be valid while their product is not. +#[test] +fn a_user_space_opens_again_only_within_what_import_stores() { + let opens = |scale: f64, axes: serde_json::Value| filter(json!({ "xml": SHIFT_X, "scale": scale, "axes": axes })).opens_again(); + assert!(opens(1000.0, json!(null))); + assert!(opens(2.0, json!([0.0, 1.0, -1.0, 0.0]))); + assert!(!opens(1000.0, json!([2.0, 0.0, 0.0, 2.0])), "scale 2000 across"); + assert!(!opens(0.001, json!([0.5, 0.0, 0.0, 0.5])), "scale 0.0005 across"); + let space = user_space(Affine::new([0.0, 2.0, -2.0, 0.0, 5.0, 6.0])).unwrap(); + assert_eq!((space.scale, space.origin, space.axes), (2.0, [5.0, 6.0], Some([0.0, 1.0, -1.0, 0.0]))); +} + +/// The region of a turned filter reaches as far as its turned box does. +#[test] +fn a_turned_region_reaches_along_the_turned_axes() { + let b = Rect::new(0.0, 0.0, 50.0, 50.0); + let user = r#""#; + assert!((filter(json!({ "xml": user })).outset(b) - 45.0).abs() < 1e-9, "45 pt below the box"); + // A quarter turn: user y runs to the left of the page, so -5..95 of it lies 95 pt left of the box. + assert!((filter(json!({ "xml": user, "axes": [0.0, 1.0, -1.0, 0.0] })).outset(b) - 95.0).abs() < 1e-9); +} + +/// A filter skewed as far as `axes` allows runs on a canvas no larger than four times the raster's +/// pixels, however far the skew spreads the raster's box in its user space. +#[test] +fn a_skewed_filter_runs_within_its_pixel_budget() { + let (w, h) = (64, 48); + let f = filter(json!({ "xml": SHIFT_X, "axes": [1.0, 0.0, 999.0, 1.0] })); + let all = Rect::new(0.0, 0.0, w as f64, h as f64); + let (cw, ch, ..) = f.turned_canvas(w, h, 1.0, all, &space(w, h, 1.0, 1.0)).unwrap(); + let (cw, ch) = (f64::from(cw), f64::from(ch)); + assert!(cw * ch <= TURNED_ROOM * (w * h) as f64 + cw + ch + 1.0, "{cw} × {ch}"); + // It still draws. + let mut data = image(w, h, |x, y| if (20..40).contains(&x) && (10..30).contains(&y) { [0, 0, 255, 255] } else { [0; 4] }); + f.apply(&mut data, w, h, &space(w, h, 1.0, 1.0)); + // A plain quarter turn keeps the raster's own pixel size. + let turned = filter(json!({ "xml": SHIFT_X, "axes": [0.0, 1.0, -1.0, 0.0] })); + let (cw, ch, outer, _) = turned.turned_canvas(w, h, 1.0, all, &space(w, h, 1.0, 1.0)).unwrap(); + assert_eq!((cw, ch), (48, 64)); + assert!((outer.determinant() - 1.0).abs() < 1e-9); + // Stretched 100 times across and squeezed 100 times down: each canvas axis keeps the raster's + // detail along it, not one column of it. + let stretched = filter(json!({ "xml": SHIFT_X, "axes": [100.0, 0.0, 0.0, 0.01] })); + let (cw, ch, ..) = stretched.turned_canvas(100, 100, 1.0, Rect::new(0.0, 0.0, 100.0, 100.0), &space(100, 100, 1.0, 1.0)).unwrap(); + assert_eq!((cw, ch), (100, 100)); +} + +/// On a far skewed canvas, a radius or a standard deviation in the object's box spans no more +/// canvas pixels than the caps allow: it is measured against the art's box on the canvas, which the +/// skew spreads far wider than the art's box in the raster. +#[test] +fn a_skewed_filter_keeps_box_lengths_within_the_caps_on_its_canvas() { + let (w, h) = (64, 48); + let sp = space(w, h, 1.0, 1.0); + let drawn = Rect::new(20.0, 10.0, 40.0, 30.0); + for (xml, length, cap) in [ + ("", 1.5, MAX_WINDOW_PX), + ("", 20.0, MAX_BLUR_PX), + ] { + let f = filter(json!({ "xml": xml, "axes": [1.0, 0.0, 999.0, 1.0] })); + let (_, _, outer, _) = f.turned_canvas(w, h, 1.0, drawn, &sp).unwrap(); + // The art's box on the canvas: the drawn pixels taken into user space, then onto the canvas. + let art = (outer * f.to_doc().inverse() * sp.to_doc).transform_rect_bbox(drawn); + let px = length * art.width().max(art.height()); + assert!(px <= cap + 1e-6, "{xml}: {px} canvas pixels"); + } + // A user-space radius spans no more than 32 canvas pixels along either axis. + let f = filter(json!({ "xml": "", "scale": 1000.0, "axes": [1.0, 0.0, 999.0, 1.0] })); + let (_, _, outer, _) = f.turned_canvas(w, h, 1.0, drawn, &sp).unwrap(); + let [qx, _, _, qy, _, _] = outer.as_coeffs(); + assert!(100.0 * qx.max(qy) <= MAX_WINDOW_PX + 1e-6, "{qx} {qy}"); +} + #[test] fn runs_no_finer_than_the_raster_effects_resolution() { let w = 16; @@ -448,7 +596,8 @@ fn a_region_measured_against_the_box_is_written_out() { let far = r#""#; let f = filter(json!({ "xml": far, "origin": [10.0, 0.0] })); assert_eq!( - f.written_xml(Rect::new(10.0, 0.0, 30.0, 10.0)).as_deref(), + // The object over 10..30 pt of the page: 0..20 of the user space that starts at the origin. + f.written_xml(Rect::new(0.0, 0.0, 20.0, 10.0)).as_deref(), Some(r#""#) ); let plain = filter(json!({ "xml": RED_FLOOD })); diff --git a/crates/effects/src/tests.rs b/crates/effects/src/tests.rs index c605b6461f..ac340224c6 100644 --- a/crates/effects/src/tests.rs +++ b/crates/effects/src/tests.rs @@ -11,6 +11,7 @@ mod rasterfollow; mod scale; mod solidcontext; mod transformfx; +mod typestroke; fn fx(id: &str, params: Value) -> Effect { Effect { id: id.into(), params, visible: true } diff --git a/crates/effects/src/tests/rasterfollow.rs b/crates/effects/src/tests/rasterfollow.rs index 9fbb37a39d..586481d9b5 100644 --- a/crates/effects/src/tests/rasterfollow.rs +++ b/crates/effects/src/tests/rasterfollow.rs @@ -7,7 +7,8 @@ use vectorcraft_doc::{Appearance, Document, Effect, Node, NodeId}; use vectorcraft_geom::{Affine, Anchor, PathData, Point, Rect, SubPath, shapes}; use crate::geometry::{Budget, MAX_EFFECT_LINES, apply_geometry_carrying_within}; -use crate::{Carry, GeomContext, RasterFx, apply_geometry_carrying, bake_document, expand_outlined, raster_effects}; +use crate::pixel::{Light, StrokeDirection}; +use crate::{Carry, GeomContext, PixelFx, RasterFx, apply_geometry_carrying, bake_document, expand_outlined, raster_effects}; fn fx(id: &str, params: Value) -> Effect { Effect { id: id.into(), params, visible: true } @@ -436,6 +437,230 @@ fn pixel_filter_sizes_scale_with_the_transform_after_them() { assert!(matches!(drawn.get(1), Some(RasterFx::Pixel(crate::PixelFx::PaintDaubs { size, .. })) if (size - 20.0).abs() < 1e-9), "{drawn:?}"); } +/// The light direction of the first pixel filter `effects` draw, if it has one. +fn drawn_light(effects: &[Effect]) -> Option { + raster_effects(effects).into_iter().find_map(|r| match r { + RasterFx::Pixel( + PixelFx::Underpainting { light, .. } + | PixelFx::RoughPastels { light, .. } + | PixelFx::ConteCrayon { light, .. } + | PixelFx::BasRelief { light, .. } + | PixelFx::Plaster { light, .. } + | PixelFx::Texturizer { light, .. }, + ) => Some(light), + _ => None, + }) +} + +/// The stroke direction of the first pixel filter `effects` draw, if it has one. +fn drawn_strokes(effects: &[Effect]) -> Option { + raster_effects(effects).into_iter().find_map(|r| match r { + RasterFx::Pixel(PixelFx::SprayedStrokes { direction, .. } | PixelFx::GraphicPen { direction, .. }) => Some(direction), + _ => None, + }) +} + +/// The screen angles of the first Color Halftone `effects` draw. +fn drawn_screens(effects: &[Effect]) -> [f64; 4] { + match raster_effects(effects).into_iter().next() { + Some(RasterFx::Pixel(PixelFx::ColorHalftone { angles, .. })) => angles, + other => panic!("expected a Color Halftone, got {other:?}"), + } +} + +/// A Bas Relief lit from `light`, then a Transform effect with `params`: the light it draws with. +fn relief_then(light: &str, params: Value) -> Option { + drawn_light(&[fx("sketch.basRelief", json!({ "lightDirection": light })), transform(params)]) +} + +/// A light direction before a Transform effect turns and reflects with the art (y down on the +/// page), to the nearest of the eight directions, the clockwise one at a tie. +#[test] +fn bas_relief_light_follows_rotation_and_reflection() { + assert_eq!(relief_then("top", json!({"rotate": 90})), Some(Light::Left)); + assert_eq!(relief_then("top", json!({"reflectY": true})), Some(Light::Bottom)); + assert_eq!(relief_then("top", json!({"reflectX": true})), Some(Light::Top)); + assert_eq!(relief_then("left", json!({"reflectX": true})), Some(Light::Right)); + // 22.5° clockwise lies halfway between Top and Top Right; 22.5° counterclockwise halfway + // between Top and Top Left. + assert_eq!(relief_then("top", json!({"rotate": -22.5})), Some(Light::TopRight)); + assert_eq!(relief_then("top", json!({"rotate": 22.5})), Some(Light::Top)); + assert_eq!(relief_then("top", json!({"rotate": 30})), Some(Light::TopLeft)); + // A turn of 90° counterclockwise, from each direction. + for (from, to) in [ + ("bottom", Light::Right), + ("bottomLeft", Light::BottomRight), + ("left", Light::Bottom), + ("topLeft", Light::BottomLeft), + ("top", Light::Left), + ("topRight", Light::TopLeft), + ("right", Light::Top), + ("bottomRight", Light::TopRight), + ] { + assert_eq!(relief_then(from, json!({"rotate": 90})), Some(to), "{from}"); + } + // Every filter with a light direction, and Bas Relief's default light (Bottom). + for id in ["artistic.underpainting", "artistic.roughPastels", "sketch.conteCrayon", "sketch.basRelief", "sketch.plaster", "texture.texturizer"] { + let effects = [fx(id, json!({"lightDirection": "top"})), transform(json!({"rotate": 90}))]; + assert_eq!(drawn_light(&effects), Some(Light::Left), "{id}"); + } + assert_eq!(drawn_light(&[fx("sketch.basRelief", json!({})), transform(json!({"rotate": 90}))]), Some(Light::Right)); + // The Transform effects after the filter turn it together, with one rounding at the end. + let twice = [fx("sketch.basRelief", json!({"lightDirection": "top"})), transform(json!({"rotate": -22.5})), transform(json!({"rotate": -22.5}))]; + assert_eq!(drawn_light(&twice), Some(Light::TopRight)); +} + +/// A stroke direction before a Transform effect turns and reflects with the art, to the nearest +/// of the four, a stroke and its reverse being the same, the clockwise one at a tie. +#[test] +fn stroke_axis_follows_transform() { + let strokes = |id: &str, way: Option<&str>, params: Value| { + let p = way.map_or(json!({}), |w| json!({ "strokeDirection": w })); + drawn_strokes(&[fx(id, p), transform(params)]) + }; + let sprayed = "brushStrokes.sprayedStrokes"; + let pen = "sketch.graphicPen"; + assert_eq!(strokes(sprayed, Some("horizontal"), json!({"rotate": 90})), Some(StrokeDirection::Vertical)); + assert_eq!(strokes(sprayed, Some("vertical"), json!({"rotate": 90})), Some(StrokeDirection::Horizontal)); + assert_eq!(strokes(pen, Some("rightDiagonal"), json!({"rotate": 90})), Some(StrokeDirection::LeftDiagonal)); + assert_eq!(strokes(pen, Some("rightDiagonal"), json!({"reflectX": true})), Some(StrokeDirection::LeftDiagonal)); + assert_eq!(strokes(pen, Some("leftDiagonal"), json!({"reflectY": true})), Some(StrokeDirection::RightDiagonal)); + assert_eq!(strokes(pen, None, json!({"rotate": 90})), Some(StrokeDirection::LeftDiagonal)); + assert_eq!(strokes(sprayed, Some("horizontal"), json!({"rotate": -22.5})), Some(StrokeDirection::LeftDiagonal)); + assert_eq!(strokes(sprayed, Some("horizontal"), json!({"rotate": 22.5})), Some(StrokeDirection::Horizontal)); + assert_eq!(strokes(sprayed, Some("horizontal"), json!({"rotate": -44})), Some(StrokeDirection::LeftDiagonal)); + assert_eq!(strokes(sprayed, Some("horizontal"), json!({"rotate": 180})), Some(StrokeDirection::Horizontal)); +} + +fn near4(a: [f64; 4], b: [f64; 4]) -> bool { + a.iter().zip(b).all(|(p, q)| (p - q).abs() < 1e-6) +} + +/// Color Halftone's screen angles before a Transform effect turn and reflect with the art. +#[test] +fn halftone_channels_follow_rotation_and_reflection() { + let screens = |p: Value, transforms: &[Value]| { + let mut effects = vec![fx("pixelate.colorHalftone", p)]; + effects.extend(transforms.iter().cloned().map(transform)); + drawn_screens(&effects) + }; + let defaults = screens(json!({}), &[json!({"rotate": 90})]); + assert!(near4(defaults, [198.0, 252.0, 180.0, 135.0]), "{defaults:?}"); + let reflected = screens(json!({"channel1": 45, "channel2": 30, "channel3": 0, "channel4": 270}), &[json!({"reflectX": true})]); + assert!(near4(reflected, [135.0, 150.0, 180.0, 270.0]), "{reflected:?}"); + let flipped = screens(json!({"channel1": 45, "channel2": 30, "channel3": 0, "channel4": 270}), &[json!({"reflectY": true})]); + assert!(near4(flipped, [315.0, 330.0, 0.0, 90.0]), "{flipped:?}"); + // One Transform effect reflects, then turns; two apply in the order they are listed. + let p = json!({"channel1": 10.5, "channel2": -30, "channel3": 0, "channel4": 359.25}); + let one = screens(p.clone(), &[json!({"rotate": 30, "reflectX": true})]); + assert!(near4(one, [199.5, 240.0, 210.0, 210.75]), "{one:?}"); + let two = screens(p, &[json!({"rotate": 30}), json!({"reflectX": true})]); + assert!(near4(two, [139.5, 180.0, 150.0, 150.75]), "{two:?}"); +} + +/// Only the visible Transform effects listed after a filter that move the art once turn its +/// direction; a hidden filter turns too, and a zero scale leaves it as it is. +#[test] +fn only_earlier_visible_single_map_effects_follow() { + let relief = fx("sketch.basRelief", json!({"lightDirection": "top"})); + assert_eq!(drawn_light(&[transform(json!({"rotate": 90})), relief.clone()]), Some(Light::Top)); + for params in [ + json!({"rotate": 90, "objects": false}), + json!({"rotate": 90, "copies": 1}), + json!({"rotate": 90, "random": true}), + json!({"scaleH": 0, "scaleV": 0}), + ] { + assert_eq!(drawn_light(&[relief.clone(), transform(params.clone())]), Some(Light::Top), "{params}"); + } + let mut hidden = transform(json!({"rotate": 90})); + hidden.visible = false; + assert_eq!(drawn_light(&[relief.clone(), hidden]), Some(Light::Top)); + let zero = [fx("pixelate.colorHalftone", json!({"channel1": 20})), transform(json!({"scaleH": 0, "scaleV": 0}))]; + assert!(near4(drawn_screens(&zero), [20.0, 162.0, 90.0, 45.0]), "{:?}", drawn_screens(&zero)); + // A hidden filter kept when the Transform effect is applied draws turned once it is shown. + let mut off = relief; + off.visible = false; + let kept = crate::raster::without_geometry(&[off, transform(json!({"rotate": 90}))]); + assert_eq!(kept.len(), 1); + let mut shown = kept[0].clone(); + shown.visible = true; + assert_eq!(drawn_light(&[shown]), Some(Light::Left)); +} + +/// The light direction of every Bas Relief drawn on `n` and the nodes under it, from the object's +/// effects and from each fill's and stroke's. +fn lights_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 { + out.extend(drawn_light(list)); + } + }); + out +} + +/// The canvas, a fill's own effects, a group's members and export turn the light the same way. +#[test] +fn nested_and_baked_directions_match_canvas() { + let relief = || fx("sketch.basRelief", json!({"lightDirection": "top"})); + let turn = || transform(json!({"rotate": 90})); + // A fill's own Transform effect, and the object's Transform effect over its fill. + let fill = fill_square(31, vec![relief(), turn()]); + let item = fill.appearance.items.first().unwrap(); + assert_eq!(drawn_light(item.effects()), Some(Light::Left)); + let mut over = fill_square(32, vec![relief()]); + over.appearance.effects = vec![turn()]; + let item = over.appearance.items.first().unwrap(); + assert_eq!(drawn_light(&crate::item_effects_in(&over.appearance.effects, item.effects())), Some(Light::Left)); + // A fill's own turn of 30° and the object's turn of 30° make 60°, rounded once: Top Left, not + // Left (Top Left after the first turn, then Left after the second). + let thirty = || transform(json!({"rotate": 30})); + let mut both = fill_square(37, vec![relief(), thirty()]); + both.appearance.effects = vec![thirty()]; + let item = both.appearance.items.first().unwrap(); + assert_eq!(drawn_light(&crate::item_effects_in(&both.appearance.effects, item.effects())), Some(Light::TopLeft)); + // A group's Transform effect over a member's own filter and its fill's. + let g = group(33, vec![square(34, vec![relief()]), fill_square(35, vec![relief()])], vec![turn()]); + let art = crate::evaluate_container(None, &g).unwrap(); + assert_eq!(lights_in(&art), vec![Light::Left; 2]); + // Baked for export: the Transform effect is applied and the filter keeps the turned light. + let mut d = Document::new(800.0, 800.0); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, square(36, vec![relief(), turn()])).unwrap(); + d.insert(Some(layer), 1, g).unwrap(); + let baked = bake_document(&d).unwrap(); + let b = baked.node(NodeId(36)).unwrap(); + assert!(!b.appearance.effects.iter().any(|e| e.id == "distort.transform"), "{:?}", b.appearance.effects); + assert_eq!(drawn_light(&b.appearance.effects), Some(Light::Left)); + for id in [34, 35] { + assert_eq!(lights_in(baked.node(NodeId(id)).unwrap()), vec![Light::Left], "{id}"); + } +} + +/// A member's light under two nested groups that each turn 30° turns 60° in all, rounded once: +/// Top Left, not Left (Top Left after the inner group's turn, then Left after the outer one's). +#[test] +fn nested_group_turns_round_the_light_once() { + let relief = || fx("sketch.basRelief", json!({"lightDirection": "top"})); + let thirty = || transform(json!({"rotate": 30})); + let inner = group(41, vec![square(42, vec![relief()]), fill_square(43, vec![relief()])], vec![thirty()]); + let outer = group(40, vec![inner], vec![thirty()]); + let art = crate::evaluate_container(None, &outer).unwrap(); + assert_eq!(lights_in(&art), vec![Light::TopLeft; 2]); + let mut d = Document::new(800.0, 800.0); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, outer).unwrap(); + let baked = bake_document(&d).unwrap(); + for id in [42, 43] { + assert_eq!(lights_in(baked.node(NodeId(id)).unwrap()), vec![Light::TopLeft], "{id}"); + } + // Three groups make 90°: Left, not Bottom Left. + let three = group(44, vec![group(45, vec![group(46, vec![square(47, vec![relief()])], vec![thirty()])], vec![thirty()])], vec![thirty()]); + let art = crate::evaluate_container(None, &three).unwrap(); + assert_eq!(lights_in(&art), vec![Light::Left]); +} + /// A Transform effect after a 3D effect that makes copies or moves at random holds back the shadow /// before the 3D effect, as it does without the 3D effect. #[test] diff --git a/crates/effects/src/tests/typestroke.rs b/crates/effects/src/tests/typestroke.rs new file mode 100644 index 0000000000..d6c8e82cec --- /dev/null +++ b/crates/effects/src/tests/typestroke.rs @@ -0,0 +1,123 @@ +//! Character strokes of outlined type under the type's transform ([`paint_type_piece`]): a live +//! stroke with a scaled weight under a similarity, otherwise the area the stroke paints in text +//! space, placed by the transform and filled. + +use vectorcraft_color::{Color, Gradient, GradientKind, GradientPaint, GradientStop, Paint}; +use vectorcraft_doc::{Appearance, CharStyle, Dash, LineJoin, Node, NodeId, StrokeAlign}; +use vectorcraft_geom::{Affine, FillRule, Rect, shapes}; + +use crate::*; + +const BOX: Rect = Rect::new(0.0, 0.0, 10.0, 10.0); + +fn red() -> Color { + Color::rgb(1.0, 0.0, 0.0) +} + +/// A black run with a red stroke of `width` and round joins. +fn style(width: f64) -> CharStyle { + CharStyle { + fill: Paint::solid(Color::BLACK), + stroke: Paint::solid(red()), + stroke_width: width, + stroke_join: LineJoin::Round, + ..CharStyle::default() + } +} + +/// A 10 x 10 square in text space standing in for a glyph. +fn square() -> Node { + Node::path(NodeId(7), shapes::rectangle(BOX), Appearance::default()) +} + +fn area(n: &Node) -> f64 { + vectorcraft_pathops::area(n.path_data().unwrap(), FillRule::NonZero).abs() +} + +fn near(a: Rect, b: Rect) -> bool { + [a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().all(|d| d.abs() < 0.05) +} + +#[test] +fn an_uneven_scale_fills_the_stroke_the_canvas_paints() { + let mut piece = square(); + let stroke = paint_type_piece(&mut piece, &style(4.0), BOX, Affine::scale_non_uniform(3.0, 1.0)).expect("a filled stroke"); + assert!(piece.appearance.stroke().is_none(), "the piece keeps only its fill"); + assert_eq!(piece.appearance.fill_paint(), Paint::solid(Color::BLACK)); + assert_eq!(piece.geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 30.0, 10.0)); + assert!(stroke.appearance.stroke().is_none()); + assert_eq!(stroke.appearance.fill_paint(), Paint::solid(red())); + assert_eq!(stroke.id, NodeId(7)); + // 4 pt across in text space: 12 pt across the upright sides and 4 pt across the level ones. + let b = stroke.geometric_bounds().unwrap(); + assert!(near(b, Rect::new(-6.0, -2.0, 36.0, 12.0)), "{b:?}"); + // The ring of a 10 pt square stroked 4 pt with round joins (180 + 4π outside, 36 inside), 3 times as wide. + let ring = 180.0 + 4.0 * std::f64::consts::PI - 36.0; + assert!((area(&stroke) - 3.0 * ring).abs() < 0.5, "{}", area(&stroke)); +} + +#[test] +fn a_similarity_keeps_the_live_stroke_with_a_scaled_weight() { + for (xf, weight) in [ + (Affine::translate((5.0, 5.0)), 4.0), + (Affine::scale(2.0), 8.0), + (Affine::rotate(0.5) * Affine::scale(2.0), 8.0), + (Affine::scale_non_uniform(-2.0, 2.0), 8.0), + ] { + let mut piece = square(); + assert!(paint_type_piece(&mut piece, &style(4.0), BOX, xf).is_none(), "{xf:?}"); + let st = piece.appearance.stroke().expect("a live stroke"); + assert!((st.width - weight).abs() < 1e-9, "{xf:?}: {}", st.width); + assert_eq!(st.join, LineJoin::Round); + } +} + +#[test] +fn shears_and_flattening_transforms_fill_the_stroke() { + // A shear keeps the area. + let mut piece = square(); + let stroke = paint_type_piece(&mut piece, &style(4.0), BOX, Affine::skew(0.5, 0.0)).expect("a filled stroke"); + let ring = 180.0 + 4.0 * std::f64::consts::PI - 36.0; + assert!((area(&stroke) - ring).abs() < 0.5, "{}", area(&stroke)); + // Flattened to a line or a point: no division by the determinant, nothing non-finite. + for xf in [Affine::scale_non_uniform(2.0, 0.0), Affine::scale(0.0)] { + let mut piece = square(); + let stroke = paint_type_piece(&mut piece, &style(4.0), BOX, xf).expect("a filled stroke"); + assert!(piece.appearance.stroke().is_none()); + if let Some(b) = stroke.geometric_bounds() { + assert!([b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()) && b.height().abs() < 1e-9, "{xf:?}: {b:?}"); + } + } +} + +#[test] +fn the_stroke_options_shape_the_filled_stroke_in_text_space() { + let xf = Affine::scale_non_uniform(3.0, 1.0); + let filled = |st: CharStyle| paint_type_piece(&mut square(), &st, BOX, xf); + // No stroke, or no weight: nothing is filled. + assert!(filled(style(0.0)).is_none()); + assert!(filled(CharStyle { stroke: Paint::None, ..style(4.0) }).is_none()); + // Inside and outside alignment are kept to their side of the square before it is scaled. + let inside = filled(CharStyle { stroke_align: StrokeAlign::Inside, ..style(4.0) }).unwrap(); + assert!(near(inside.geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 30.0, 10.0))); + assert!((area(&inside) - 3.0 * (100.0 - 4.0)).abs() < 0.5, "{}", area(&inside)); + let outside = filled(CharStyle { stroke_align: StrokeAlign::Outside, ..style(4.0) }).unwrap(); + assert!(near(outside.geometric_bounds().unwrap(), Rect::new(-12.0, -4.0, 42.0, 14.0)), "{:?}", outside.geometric_bounds()); + // Dashes are laid out along the square in text space: half of each 10 pt is painted. + let solid = area(&filled(style(1.0)).unwrap()); + let dash = Dash { pattern: vec![5.0, 5.0], ..Default::default() }; + let dashed = area(&filled(CharStyle { stroke_dash: Some(dash), ..style(1.0) }).unwrap()); + assert!(dashed < 0.7 * solid && dashed > 0.3 * solid, "{dashed} of {solid}"); +} + +#[test] +fn a_gradient_on_the_stroke_stays_where_the_stroke_had_it() { + let stops = vec![GradientStop::new(0.0, red()), GradientStop::new(1.0, Color::BLACK)]; + let ramp = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops)))); + let mut piece = square(); + let stroke = paint_type_piece(&mut piece, &CharStyle { stroke: ramp, ..style(4.0) }, BOX, Affine::scale_non_uniform(3.0, 1.0)).unwrap(); + let Paint::Gradient(g) = stroke.appearance.fill_paint() else { panic!("a gradient fill") }; + // Fitted across the stroke's box in text space (the square grown by half the weight), then scaled. + let geom = g.geom.expect("placed"); + assert!((geom.start.x + 6.0).abs() < 1e-6 && (geom.end.x - 36.0).abs() < 1e-6, "{geom:?}"); +} diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 0fccbcdecb..b46678804b 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -53,7 +53,7 @@ heic-rs = { version = "=0.1.4", default-features = false, features = ["std"], op flate2 = { workspace = true } chrono = { workspace = true } # The XML parts of Word documents placed as type (place/docx.rs). -roxmltree = "0.21" +craft-xml = { workspace = true } # The compound file that holds a Word 97-2003 document placed as type (place/doc.rs). cfb = "0.15" kurbo = { workspace = true } diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index c6aed0a644..ae67281995 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -98,6 +98,8 @@ pub(crate) mod symboledit; pub mod symbollib; pub(crate) mod tabs; mod textedit; +mod xmlattrs; + pub use textedit::effective_kerning; pub mod textstyles; pub(crate) mod textwrap; diff --git a/crates/engine/src/cmd/actionset.rs b/crates/engine/src/cmd/actionset.rs index b6a9118380..ad23db1c64 100644 --- a/crates/engine/src/cmd/actionset.rs +++ b/crates/engine/src/cmd/actionset.rs @@ -9,8 +9,9 @@ //! text. Each action is an `/action-N` block with a hexadecimal `/name`; each step is an `/event-N` //! block inside one, with its `/internalName` in parentheses, the `/localizedName` it is shown with //! as hexadecimal text, and `/isOn` 0 when it is left out of playback; each value a step was -//! recorded with is a `/parameter-N` block inside it, which is counted, and whose hexadecimal -//! `/value` is checked against its byte count. The set's `/actionCount`, an action's `/eventCount` +//! recorded with is a `/parameter-N` block inside it, which is counted, whose `/key` (a number), +//! `/type` (text in parentheses) and `/value` (a number, text in parentheses or hexadecimal text) are +//! kept, and whose hexadecimal `/value` is checked against its byte count. The set's `/actionCount`, an action's `/eventCount` //! and a step's `/parameterCount` give how many actions, steps and recorded values follow. //! The layout follows the README of Inventsable's Redesigning-Illustrator-Actions-in-Scripting //! (https://github.com/Inventsable/Redesigning-Illustrator-Actions-in-Scripting), the forum post @@ -40,6 +41,8 @@ const MAX_STEPS: usize = 10_000; /// The most steps read in the set: a small text can hold hundreds of thousands of empty steps, and /// the answer holds an object for each. const MAX_SET_STEPS: usize = 100_000; +/// The most recorded values kept in the set; the others are counted but not kept. +const MAX_VALUES: usize = 100_000; /// The longest name kept (bytes). const MAX_NAME: usize = 1024; /// The most tokens listed as unread. @@ -56,7 +59,7 @@ pub fn specs() -> Vec { "Read Action Set File", [], None, - "{path? | data?: the file's text | dataBase64?, name?: the file's name (default: the path's)} read an action set another app saved as text (.aia, starting \"/version\") without changing anything → {set: the set's /name (else the file's name without its extension, else empty), version, actions: [{name, steps: [{name: the step's /internalName, label: its /localizedName, or null when it has none or it is blank, on: false when /isOn is 0, params: how many /parameter blocks it has, line}]}], unread: [{line, text}] (tokens that aren't read, at most 1000), truncated: true when a cap stopped the reading (8 MiB, 16 open blocks, 1,000 actions, 10,000 steps in an action, 100,000 steps in the set; names past 1,024 bytes are cut), when the text ends inside a block or a value or after a field's name, when /actionCount, /eventCount or a step's /parameterCount differs from the actions, steps or recorded values read (a negative count, one too large for a number and one that isn't a number always differ), or when a hexadecimal name, label or recorded /value isn't as many bytes as its count says}. Give exactly one of path, data and dataBase64. Text that doesn't start with /version and a number is an error", + "{path? | data?: the file's text | dataBase64?, name?: the file's name (default: the path's)} read an action set another app saved as text (.aia, starting \"/version\") without changing anything → {set: the set's /name (else the file's name without its extension, else empty), version, actions: [{name, steps: [{name: the step's /internalName, label: its /localizedName, or null when it has none or it is blank, on: false when /isOn is 0, params: how many /parameter blocks it has, values: [{key: the block's /key, or null, type: its /type, or null, value: its /value when it is a number, or text that is UTF-8 (else null), bytes?: the text's length in bytes}] (the first 100,000 recorded values in the set), line}]}], unread: [{line, text}] (tokens that aren't read, at most 1000), truncated: true when a cap stopped the reading (8 MiB, 16 open blocks, 1,000 actions, 10,000 steps in an action, 100,000 steps in the set; names past 1,024 bytes are cut), when the text ends inside a block or a value or after a field's name, when /actionCount, /eventCount or a step's /parameterCount differs from the actions, steps or recorded values read (a negative count, one too large for a number and one that isn't a number always differ), or when a hexadecimal name, label or recorded /value isn't as many bytes as its count says}. Give exactly one of path, data and dataBase64. Text that doesn't start with /version and a number is an error", always, read )] @@ -73,12 +76,33 @@ pub struct AiaStep { pub on: Option, /// How many `/parameter-N` blocks it has. pub params: usize, + /// Its `/parameter-N` blocks, in order, while the set keeps at most [`MAX_VALUES`]. + pub values: Vec, /// Its `/parameterCount`, if it has one. pub declared: Option, /// The line its block opens on (from 1). pub line: usize, } +/// A value a step was recorded with: a `/parameter-N` block. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct AiaValue { + /// Its `/key`, if it has one that fits an `i64`. + pub key: Option, + /// Its `/type`, read as UTF-8 with replacement characters, if it has one. + pub kind: Option, + /// Its `/value`, if it is a number that fits an `i64` or text. + pub value: Option, +} + +/// A recorded `/value` that is kept. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum AiaData { + Int(i64), + /// The bytes of text in parentheses or of hexadecimal text. + Text(Vec), +} + /// An action: an `/action-N` block. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct AiaAction { @@ -106,6 +130,8 @@ pub struct AiaSet { pub truncated: bool, /// How many steps were read in all the actions. steps: usize, + /// How many recorded values were kept in all the steps. + values: usize, } /// A token of the text. @@ -252,7 +278,8 @@ fn hex_bytes(digits: &[u8]) -> Option> { enum Kind { Action, Step, - Param, + /// A recorded value, and whether it is kept. + Param(bool), /// A block that isn't read, or one past a cap. Other, } @@ -315,12 +342,18 @@ fn open_block(set: &mut AiaSet, stack: &[Kind], name: &[u8], line: usize) -> Kin } }, Some(Kind::Step) if numbered(name, b"parameter-") => { + let mut kept = false; if let Some(s) = set.actions.last_mut().and_then(|a| a.steps.last_mut()) { s.params += 1; + if set.values < MAX_VALUES { + s.values.push(AiaValue::default()); + set.values += 1; + kept = true; + } } - Kind::Param + Kind::Param(kept) } - Some(Kind::Param | Kind::Other) => Kind::Other, + Some(Kind::Param(_) | Kind::Other) => Kind::Other, _ => { unread(set, line, format!("/{} {{", String::from_utf8_lossy(name))); Kind::Other @@ -355,12 +388,23 @@ fn set_hex(set: &mut AiaSet, kind: Option<&Kind>, name: Option<&[u8]>, bytes: Op } } -/// Mark `set` truncated when the hexadecimal `/value` on `line` isn't as many bytes as its count -/// says. -fn check_value(set: &mut AiaSet, bytes: Option>, line: usize) { - if bytes.is_none() { +/// Set the field `name` of the recorded value open on `line` to `token`: its `/key`, `/type` or +/// `/value`, when the value is `kept`. A hexadecimal `/value` that isn't as many bytes as its count +/// says marks `set` truncated, kept or not. +fn set_param(set: &mut AiaSet, kept: bool, name: Option<&[u8]>, token: Token, line: usize) { + if name == Some(b"value".as_slice()) && matches!(token, Token::Hex(None)) { set.truncated = true; unread(set, line, BAD_HEX); + return; + } + let value = set.actions.last_mut().and_then(|a| a.steps.last_mut()).and_then(|s| s.values.last_mut()); + let Some(v) = value.filter(|_| kept) else { return }; + match (name, token) { + (Some(b"key"), Token::Int(key)) => v.key = key, + (Some(b"type"), Token::Text(t)) => v.kind = Some(String::from_utf8_lossy(&t).into_owned()), + (Some(b"value"), Token::Int(Some(n))) => v.value = Some(AiaData::Int(n)), + (Some(b"value"), Token::Text(t) | Token::Hex(Some(t))) => v.value = Some(AiaData::Text(t)), + _ => {} } } @@ -448,13 +492,13 @@ pub fn read_aia(bytes: &[u8]) -> std::result::Result { unread(&mut set, line, "}"); } } - Token::Hex(bytes) if matches!(stack.last(), Some(Kind::Param)) => { - if field(&mut pending).as_deref() == Some(b"value".as_slice()) { - check_value(&mut set, bytes, line); - } + _ if matches!(stack.last(), Some(Kind::Param(_))) => { + let kept = matches!(stack.last(), Some(Kind::Param(true))); + let name = field(&mut pending); + set_param(&mut set, kept, name.as_deref(), token, line); } - // The other values inside a recorded value, or a block that isn't read. - _ if matches!(stack.last(), Some(Kind::Param | Kind::Other)) => { + // The values inside a block that isn't read. + _ if matches!(stack.last(), Some(Kind::Other)) => { pending = None; } Token::Hex(bytes) => { @@ -521,6 +565,21 @@ pub fn read_aia(bytes: &[u8]) -> std::result::Result { Ok(set) } +/// A recorded value in `actionSet.read`'s answer: `{key, type, value, bytes?}`, the value a number, +/// text that is UTF-8 (else null) with its length in bytes, or null. +fn value_json(v: &AiaValue) -> Value { + let mut out = json!({ "key": v.key, "type": v.kind, "value": null }); + match &v.value { + Some(AiaData::Int(n)) => out["value"] = json!(n), + Some(AiaData::Text(t)) => { + out["value"] = json!(std::str::from_utf8(t).ok()); + out["bytes"] = json!(t.len()); + } + None => {} + } + out +} + fn read(_: &mut Session, p: &Value) -> Result { const C: &str = "actionSet.read"; let (path, data, b64) = (text_param(p, "path", C)?, text_param(p, "data", C)?, text_param(p, "dataBase64", C)?); @@ -544,7 +603,8 @@ fn read(_: &mut Session, p: &Value) -> Result { .iter() .map(|s| { let label = s.label.clone().filter(|l| !l.trim().is_empty()); - json!({ "name": s.name, "label": label, "on": s.on != Some(0), "params": s.params, "line": s.line }) + let values: Vec = s.values.iter().map(value_json).collect(); + json!({ "name": s.name, "label": label, "on": s.on != Some(0), "params": s.params, "values": values, "line": s.line }) }) .collect(); json!({ "name": a.name, "steps": steps }) diff --git a/crates/engine/src/cmd/addons.rs b/crates/engine/src/cmd/addons.rs index 66c67651a3..8c310878fd 100644 --- a/crates/engine/src/cmd/addons.rs +++ b/crates/engine/src/cmd/addons.rs @@ -8,6 +8,7 @@ mod contour; mod cutting; mod document; mod image; +mod packaging; mod pathtools; mod pen; mod select; @@ -15,6 +16,7 @@ mod shapes; mod typetools; pub(crate) use image::{DecodedImages, refresh_color_masks}; +pub(crate) use packaging::{role_swatch_edited, role_swatches_merged}; use super::CommandSpec; @@ -27,6 +29,7 @@ pub fn specs() -> Vec { v.extend(cutting::specs()); v.extend(document::specs()); v.extend(image::specs()); + v.extend(packaging::specs()); v.extend(pathtools::specs()); v.extend(pen::specs()); v.extend(select::specs()); diff --git a/crates/engine/src/cmd/addons/packaging.rs b/crates/engine/src/cmd/addons/packaging.rs new file mode 100644 index 0000000000..7e262c3869 --- /dev/null +++ b/crates/engine/src/cmd/addons/packaging.rs @@ -0,0 +1,18 @@ +//! Packaging Tools (`addon.packaging.*`), a built-in add-on for the dielines of boxes and other +//! folded packaging. A path is a fold line when its top stroke is painted with the swatch of a line +//! role: Cut, Crease, Partial Cut or Perforation ([`roles`]). The document's role table maps each +//! role to its swatch, so every format that keeps the stroke's swatch keeps the role. Its submenu +//! (Object › Plug-ins › Packaging Tools) and its Fold Lines panel are the UI's. + +mod roles; + +pub(crate) use roles::{role_swatch_edited, role_swatches_merged}; + +use super::super::CommandSpec; + +pub fn specs() -> Vec { + roles::specs() +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/addons/packaging/roles.rs b/crates/engine/src/cmd/addons/packaging/roles.rs new file mode 100644 index 0000000000..010384c6c2 --- /dev/null +++ b/crates/engine/src/cmd/addons/packaging/roles.rs @@ -0,0 +1,454 @@ +//! Fold line roles (`addon.packaging.setRole`, `addon.packaging.roles`, +//! `addon.packaging.setRoleSwatch`). A path, compound path or live shape has a role when its top +//! stroke is painted with the swatch the document's role table gives that role, at any tint. The +//! table lives in [`Document::unknown`] under [`ROLES_KEY`], `{cut, crease, partialCut, +//! perforation}` each naming a swatch; a role it leaves out, or names with something other than a +//! string, takes its default swatch, named after the role. + +use serde_json::{Map, Value, json}; +use vectorcraft_color::swatch::REGISTRATION; +use vectorcraft_color::{Color, Paint, Swatch}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; + +use super::super::super::overprint::edit_counted; +use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, switch_or, text_param}; +use crate::{Result, Session}; + +/// Document unknown key: the role table, `{role id: swatch name}`. +pub(crate) const ROLES_KEY: &str = "packagingRoles"; + +const SET_ROLE: &str = "addon.packaging.setRole"; +const ROLES: &str = "addon.packaging.roles"; +const SET_ROLE_SWATCH: &str = "addon.packaging.setRoleSwatch"; + +/// What a fold line does when the blank is cut and folded. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Role { + /// Separates the material. + Cut, + /// A fold. + Crease, + /// A fold cut part way through the board. + PartialCut, + /// A fold along a line of cuts. + Perforation, +} + +impl Role { + pub(crate) const ALL: [Role; 4] = [Role::Cut, Role::Crease, Role::PartialCut, Role::Perforation]; + + /// The role's id in params and in the role table. + pub(crate) fn id(self) -> &'static str { + match self { + Role::Cut => "cut", + Role::Crease => "crease", + Role::PartialCut => "partialCut", + Role::Perforation => "perforation", + } + } + + /// The role's name, which is also its default swatch's name. + pub(crate) fn name(self) -> &'static str { + match self { + Role::Cut => "Cut", + Role::Crease => "Crease", + Role::PartialCut => "Partial Cut", + Role::Perforation => "Perforation", + } + } + + pub(crate) fn from_id(id: &str) -> Option { + Role::ALL.into_iter().find(|r| r.id() == id) + } + + /// The color a missing role swatch is made with (VectorCraft's own values): Cut 100% magenta, + /// Crease 100% cyan, Partial Cut 100% yellow, Perforation 50% magenta and 50% cyan. + fn color(self) -> Color { + match self { + Role::Cut => Color::cmyk(0.0, 1.0, 0.0, 0.0), + Role::Crease => Color::cmyk(1.0, 0.0, 0.0, 0.0), + Role::PartialCut => Color::cmyk(0.0, 0.0, 1.0, 0.0), + Role::Perforation => Color::cmyk(0.5, 0.5, 0.0, 0.0), + } + } + + fn index(self) -> usize { + Role::ALL.iter().position(|r| *r == self).unwrap_or(0) + } +} + +/// The swatch each role is carried by, in [`Role::ALL`] order. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct RoleTable([String; 4]); + +impl RoleTable { + /// The document's role table, with each missing or damaged entry at its default. When a damaged + /// table names one swatch for two roles, the later role takes its default name instead, or + /// "Crease 2" and so on when an earlier role has that. + pub(crate) fn of(d: &Document) -> RoleTable { + let stored = d.unknown.get(ROLES_KEY).and_then(Value::as_object); + let mut names: Vec = Vec::with_capacity(Role::ALL.len()); + for r in Role::ALL { + let name = match stored.and_then(|m| m.get(r.id())).and_then(Value::as_str) { + Some(name) if !name.is_empty() && !names.iter().any(|n| n == name) => name.to_string(), + _ => { + let base = r.name(); + std::iter::once(base.to_string()) + .chain((2..).map(|i| format!("{base} {i}"))) + .find(|n| !names.contains(n)) + .unwrap_or_else(|| base.to_string()) + } + }; + names.push(name); + } + RoleTable(Role::ALL.map(|r| names.get(r.index()).cloned().unwrap_or_else(|| r.name().to_string()))) + } + + /// The swatch of `role`. + pub(crate) fn swatch(&self, role: Role) -> &str { + self.0.get(role.index()).map_or("", String::as_str) + } + + /// The role swatch `name` carries. + pub(crate) fn role_of_swatch(&self, name: &str) -> Option { + Role::ALL.into_iter().find(|r| self.swatch(*r) == name) + } + + /// The role of object `n`: the role of the swatch its top stroke is painted with. + pub(crate) fn role_of(&self, n: &Node) -> Option { + if !can_carry(n) { + return None; + } + match &n.appearance.stroke()?.paint { + Paint::Solid { swatch: Some(name), .. } => self.role_of_swatch(name), + _ => None, + } + } + + fn to_value(&self) -> Value { + Value::Object(Role::ALL.into_iter().map(|r| (r.id().to_string(), json!(self.swatch(r)))).collect::>()) + } +} + +/// Swatch `from` of `d` is now named `to`, and `global` says whether it is still a global color. +/// A role it carried keeps it under the new name, as the strokes linked to it do; when it stopped +/// being global, which unlinks those strokes, the role moves to a new name that `setRole` makes a +/// swatch for. Another role that named `to` without such a swatch moves to a new name too, so no +/// two roles share a swatch. +pub(crate) fn role_swatch_edited(d: &mut Document, from: &str, to: &str, global: bool) { + let before = RoleTable::of(d); + let mut table = before.clone(); + for r in Role::ALL { + let name = table.swatch(r).to_string(); + let moved = if name == from && global { + Some(to.to_string()) + } else if name == from || (name == to && from != to) { + Some(free_role_name(d, &table, r)) + } else { + None + }; + if let (Some(new), Some(slot)) = (moved, table.0.get_mut(r.index())) { + *slot = new; + } + } + if table != before { + d.unknown.insert(ROLES_KEY.to_string(), table.to_value()); + } +} + +/// Swatches `merged` of `d` were merged into swatch `kept`, and `linked` says whether their strokes +/// now link to it (it is a global color). When `kept` carries no role, it takes the role of the +/// first merged swatch that carried one, so the lines of that role keep it; a merged swatch's other +/// role keeps its name, which the next `setRole` makes a swatch for. +pub(crate) fn role_swatches_merged(d: &mut Document, merged: &[String], kept: &str, linked: bool) { + let mut table = RoleTable::of(d); + if !linked || table.role_of_swatch(kept).is_some() { + return; + } + let Some(role) = merged.iter().find_map(|m| table.role_of_swatch(m)) else { return }; + if let Some(slot) = table.0.get_mut(role.index()) { + *slot = kept.to_string(); + } + d.unknown.insert(ROLES_KEY.to_string(), table.to_value()); +} + +/// A name for `role`'s swatch that no swatch, color group or other role of `table` uses: the +/// role's name, else "Cut 2", "Cut 3"… The document holds finitely many names, so the search +/// always ends at a free one. +fn free_role_name(d: &Document, table: &RoleTable, role: Role) -> String { + let free = |n: &str| !d.swatch_name_taken(n) && Role::ALL.into_iter().all(|r| r == role || table.swatch(r) != n); + let base = role.name(); + if free(base) { + return base.to_string(); + } + (2usize..).map(|i| format!("{base} {i}")).find(|n| free(n)).unwrap_or_else(|| base.to_string()) +} + +/// Whether `n` can carry a role: a path (a live shape too) that is neither a clipping path nor a +/// guide, or a compound path. +fn can_carry(n: &Node) -> bool { + match &n.kind { + NodeKind::Path { clipping, guide, .. } => !clipping && !guide, + NodeKind::Compound { .. } => true, + _ => false, + } +} + +/// The objects under the outermost objects `roots` that can carry a role, through groups and clip +/// groups, each once, and +/// how many of `roots` and their members can't (text, images, symbol instances and other objects). +/// With `editable`, objects that are locked or hidden, are in a locked or hidden group or layer, or +/// are on a locked artboard are left out and counted as skipped. +fn role_targets(d: &Document, roots: &[NodeId], editable: bool) -> (Vec, usize) { + fn walk(n: &Node, out: &mut Vec, skipped: &mut usize) { + match &n.kind { + NodeKind::Group { children, .. } => { + for c in children { + // A group's clipping path draws no stroke: it is skipped. + if matches!(c.kind, NodeKind::Path { clipping: true, .. }) { + *skipped += 1; + } else { + walk(c, out, skipped); + } + } + } + _ if can_carry(n) => out.push(n.id), + _ => *skipped += 1, + } + } + let (mut out, mut skipped) = (vec![], 0); + // A path of a compound path is painted with the compound's appearance: the compound takes the + // role. `roots` come from `checked_ids_or_selection`, which keeps only outermost objects, so a + // group and its member are never both roots. + let mut seen = std::collections::HashSet::new(); + let compound_of = |id: NodeId| d.parent_of(id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))); + for n in roots.iter().map(|id| compound_of(*id).unwrap_or(*id)).filter(|id| seen.insert(*id)).filter_map(|id| d.node(id)) { + walk(n, &mut out, &mut skipped); + } + if editable { + // Named directly or not, a locked or hidden object, or one in a locked or hidden group or + // layer or on a locked artboard, stays as it is. + let ok = d.editable(); + let before = out.len(); + out.retain(|id| ok(*id)); + skipped += before - out.len(); + } + (out, skipped) +} + +/// Every object of the document that can carry a role, through layers and groups. +fn document_targets(d: &Document) -> Vec { + fn walk(n: &Node, out: &mut Vec) { + match &n.kind { + NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().for_each(|c| walk(c, out)), + _ if can_carry(n) => out.push(n.id), + _ => {} + } + } + let mut out = vec![]; + d.layers.iter().for_each(|l| walk(l, &mut out)); + out +} + +pub fn specs() -> Vec { + vec![ + cmd!( + "addon.packaging.setRole", + "Make Fold Line", + ["Object", "Plug-ins", "Packaging Tools"], + None, + "{role: cut|crease|partialCut|perforation|none, ids?: [id…] (default: the selection), overprint?: bool (true)} give each path, compound path and live shape among the objects (through groups and clip groups; objects that are locked or hidden, in a locked or hidden group or layer, or on a locked artboard are left out and counted as skipped, even when named in ids) a fold line role: its top stroke is painted with the role's swatch (addon.packaging.roles) at 100% and shown, a path without a stroke gets a 1 pt stroke, and the stroke overprints, or with overprint: false does not. A missing role swatch is made as a global spot swatch (Cut 100% magenta, Crease 100% cyan, Partial Cut 100% yellow, Perforation 50% magenta and 50% cyan, in the document's color mode; named \"Cut 2\" and so on, in the role table too, when a color group or a swatch that can't carry a role, such as a process color that is not global, has the name). none takes the role away: a role stroke keeps the color it shows, no longer linked to the swatch, and stops overprinting. Text, images, symbol instances and other objects are skipped and counted. One undo step, none when nothing changes → {ids (the objects that can carry a role), changed, skipped}", + has_selection, + set_role + ), + cmd!( + query "addon.packaging.roles", + "Fold Lines", + [], + None, + "{ids?: [id…] (default: the selection)} the fold line roles → {roles: [{role: cut|crease|partialCut|perforation, name, swatch (the swatch that carries it), exists (the document has the swatch), count}], scope: ids|selection|document, selected (objects given or selected)}; count is how many of the paths, compound paths and live shapes among the objects (through groups, locked and hidden members included, each object once) have the role, or among every object of the document while nothing is selected and ids is left out", + has_doc, + roles + ), + cmd!( + "addon.packaging.setRoleSwatch", + "Role Swatches…", + ["Object", "Plug-ins", "Packaging Tools"], + None, + "{role: cut|crease|partialCut|perforation, swatch: a global or spot color swatch's name} make the swatch carry the role, in the document's role table, as one undo step (none when it already does). Objects stroked with the role's old swatch keep their color and no longer have the role. Refused: a missing swatch, a gradient or pattern swatch, a process color that is not global, a tint swatch, [None], [Registration], and a swatch another role has → {role, swatch, changed}", + has_doc, + set_role_swatch + ), + ] +} + +/// The role `p` gives: `Some(None)` for `none` when `none` is allowed. +fn role_param(p: &Value, cmd: &str, none: bool) -> Result> { + let id = text_param(p, "role", cmd)?.ok_or_else(|| bad(cmd, "missing `role`"))?; + match Role::from_id(id) { + Some(r) => Ok(Some(r)), + None if none && id == "none" => Ok(None), + None if none => Err(bad(cmd, format!("unknown role `{id}`: cut, crease, partialCut, perforation or none"))), + None => Err(bad(cmd, format!("unknown role `{id}`: cut, crease, partialCut or perforation"))), + } +} + +/// Why swatch `name` of `d` can't carry a role, if it can't. +fn unfit_swatch(d: &Document, name: &str) -> Option { + if name == REGISTRATION || name == "[None]" { + return Some(format!("`{name}` can't carry a role")); + } + let Some(sw) = d.swatch(name) else { return Some(format!("no swatch `{name}`")) }; + match &sw.paint { + Paint::Solid { swatch: Some(_), .. } => Some(format!("`{name}` is a tint swatch: pick its base or another global or spot color")), + Paint::Solid { .. } if sw.global => None, + Paint::Solid { .. } => Some(format!("`{name}` is a process color: pick a global or spot color")), + _ => Some(format!("`{name}` isn't a color swatch")), + } +} + +/// `role`'s swatch in `d`, made as a global spot swatch in the document's color mode when `d` +/// lacks it → its paint at 100%. When a color group or a swatch that can't carry a role (a process +/// color that is not global, a tint, a gradient) has the swatch's name, the swatch is made under a +/// free name, which the role table then gives the role. +fn role_paint(d: &mut Document, role: Role) -> Result { + let mut table = RoleTable::of(d); + let current = table.swatch(role); + let taken = match d.swatch(current) { + Some(_) => unfit_swatch(d, current).is_some(), + None => d.swatch_name_taken(current), + }; + if taken { + let free = free_role_name(d, &table, role); + if let Some(slot) = table.0.get_mut(role.index()) { + *slot = free; + } + d.unknown.insert(ROLES_KEY.to_string(), table.to_value()); + } + let name = table.swatch(role); + if d.swatch(name).is_none() { + let model = d.color_mode.model(); + let color = role.color(); + let color = if color.model() == model { + color + } else { + let cms = vectorcraft_color::cms::active(); + cms.convert(&color, model, cms.settings().intent) + }; + d.swatches.push(Swatch { name: name.to_string(), paint: Paint::solid(color), global: true, spot: true }); + } + if let Some(why) = unfit_swatch(d, name) { + return Err(bad(SET_ROLE, format!("{why} (the {} role's swatch; addon.packaging.setRoleSwatch picks another)", role.name()))); + } + d.tint_paint(name, 1.0).ok_or_else(|| bad(SET_ROLE, format!("`{name}` isn't a global or spot color"))) +} + +/// Gives object `id` of `d` `role`'s `paint` (`None`: takes its role away) → whether it changed. +fn give_role(d: &mut Document, table: &RoleTable, id: NodeId, paint: Option<&Paint>, overprint: bool) -> bool { + let Some(n) = d.node_mut(id) else { return false }; + let had = table.role_of(n); + let mut a = (*n.appearance).clone(); + match paint { + Some(paint) => { + a.set_stroke(paint.clone()); + if let Some(st) = a.stroke_mut() { + if st.width <= 0.0 { + st.width = 1.0; + } + // A hidden stroke would carry the role without drawing or printing the line. + st.visible = true; + st.overprint = overprint; + } + } + None => { + if had.is_none() { + return false; + } + if let Some(st) = a.stroke_mut() { + if let Paint::Solid { color, .. } = st.paint { + st.paint = Paint::solid(color); + } + st.overprint = false; + } + } + } + if a == *n.appearance { + return false; + } + n.appearance = vectorcraft_doc::Shared::new(a); + true +} + +fn set_role(s: &mut Session, p: &Value) -> Result { + let role = role_param(p, SET_ROLE, true)?; + let overprint = switch_or(p, "overprint", true, SET_ROLE)?; + let roots = checked_ids_or_selection(s, p, SET_ROLE)?; + let (ids, skipped) = role_targets(&s.doc()?.doc, &roots, true); + if ids.is_empty() { + return Err(bad(SET_ROLE, "select a path that is neither locked nor hidden: text, images and symbol instances can't have a fold line role")); + } + let label = role.map_or("Remove Fold Line Role", |_| "Make Fold Line"); + let mut changed = 0; + edit_counted(s, label, |d| { + let before = (d.swatches.len(), d.unknown.get(ROLES_KEY).cloned()); + let paint = role.map(|r| role_paint(d, r)).transpose()?; + // A role swatch made again (its strokes may still name it) is a change of its own. + let made = (d.swatches.len(), d.unknown.get(ROLES_KEY).cloned()) != before; + let table = RoleTable::of(d); + changed = ids.iter().filter(|id| give_role(d, &table, **id, paint.as_ref(), overprint)).count(); + Ok(changed + usize::from(made)) + })?; + Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>(), "changed": changed, "skipped": skipped })) +} + +fn roles(s: &mut Session, p: &Value) -> Result { + let given = p.get("ids").is_some_and(|v| !v.is_null()); + let roots = checked_ids_or_selection(s, p, ROLES)?; + let d = &s.doc()?.doc; + let (scope, ids) = match (given, roots.is_empty()) { + (true, _) => ("ids", role_targets(d, &roots, false).0), + (false, false) => ("selection", role_targets(d, &roots, false).0), + (false, true) => ("document", document_targets(d)), + }; + let table = RoleTable::of(d); + let mut counts = [0usize; 4]; + for r in ids.iter().filter_map(|id| d.node(*id)).filter_map(|n| table.role_of(n)) { + if let Some(c) = counts.get_mut(r.index()) { + *c += 1; + } + } + let rows: Vec = Role::ALL + .into_iter() + .zip(counts) + .map(|(r, count)| { + let swatch = table.swatch(r); + json!({ "role": r.id(), "name": r.name(), "swatch": swatch, "exists": d.swatch(swatch).is_some(), "count": count }) + }) + .collect(); + Ok(json!({ "roles": rows, "scope": scope, "selected": roots.len() })) +} + +fn set_role_swatch(s: &mut Session, p: &Value) -> Result { + let Some(role) = role_param(p, SET_ROLE_SWATCH, false)? else { return Err(bad(SET_ROLE_SWATCH, "missing `role`")) }; + let name = text_param(p, "swatch", SET_ROLE_SWATCH)?.ok_or_else(|| bad(SET_ROLE_SWATCH, "missing `swatch`"))?; + let d = &s.doc()?.doc; + if let Some(why) = unfit_swatch(d, name) { + return Err(bad(SET_ROLE_SWATCH, why)); + } + let mut table = RoleTable::of(d); + if let Some(other) = Role::ALL.into_iter().find(|r| *r != role && table.swatch(*r) == name) { + return Err(bad(SET_ROLE_SWATCH, format!("`{name}` already carries the {} role", other.name()))); + } + if let Some(slot) = table.0.get_mut(role.index()) { + *slot = name.to_string(); + } + let value = table.to_value(); + let changed = RoleTable::of(d) != table; + if changed { + s.edit("Role Swatches", |d, _| { + d.unknown.insert(ROLES_KEY.to_string(), value); + Ok(()) + })?; + } + Ok(json!({ "role": role.id(), "swatch": name, "changed": changed })) +} diff --git a/crates/engine/src/cmd/addons/packaging/tests.rs b/crates/engine/src/cmd/addons/packaging/tests.rs new file mode 100644 index 0000000000..07a8bd3a30 --- /dev/null +++ b/crates/engine/src/cmd/addons/packaging/tests.rs @@ -0,0 +1,540 @@ +//! Tests for Packaging Tools: fold line roles, their swatches and the role table. + +use std::collections::BTreeSet; + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{AppearanceItem, Node, NodeKind}; + +use crate::*; + +fn session(mode: &str) -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400, "colorMode": mode})).unwrap(); + s +} + +fn id_of(v: &Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +fn rect(s: &mut Session, x: f64) -> NodeId { + id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": 20, "width": 40, "height": 40})).unwrap()) +} + +fn node(s: &Session, id: NodeId) -> Node { + s.doc().unwrap().doc.node(id).cloned().unwrap() +} + +fn steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn set_role(s: &mut Session, p: Value) -> Value { + s.execute("addon.packaging.setRole", &p).unwrap() +} + +fn err(s: &mut Session, cmd: &str, p: Value) -> String { + s.execute(cmd, &p).unwrap_err().to_string() +} + +fn b64(v: &Value) -> Vec { + vectorcraft_format::base64_decode(v["dataBase64"].as_str().expect("dataBase64")).unwrap() +} + +/// The `roles` query's counts, in role order. +fn counts(s: &mut Session, p: Value) -> Vec { + let r = s.execute("addon.packaging.roles", &p).unwrap(); + r["roles"].as_array().unwrap().iter().map(|r| r["count"].as_u64().unwrap()).collect() +} + +#[test] +fn set_role_makes_the_spot_swatch_and_links_the_top_stroke() { + let mut s = session("cmyk"); + let a = rect(&mut s, 20.0); + assert!(s.doc().unwrap().doc.swatch("Cut").is_none()); + let before = steps(&s); + let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0]})); + assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(1), Some(0))); + assert_eq!(steps(&s), before + 1, "one undo step"); + let d = &s.doc().unwrap().doc; + let sw = d.swatch("Cut").unwrap(); + assert!(sw.global && sw.spot, "{sw:?}"); + assert_eq!(sw.paint, Paint::solid(Color::cmyk(0.0, 1.0, 0.0, 0.0)), "100% magenta in a CMYK document"); + let st = node(&s, a).appearance.stroke().cloned().unwrap(); + assert!(matches!(&st.paint, Paint::Solid { swatch: Some(n), tint, .. } if n == "Cut" && *tint == 1.0), "{:?}", st.paint); + assert!(st.overprint, "role strokes overprint by default"); + // Again: nothing changes, and no undo step is recorded. + let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0]})); + assert_eq!(r["changed"].as_u64(), Some(0)); + assert_eq!(steps(&s), before + 1); + // Undo takes the swatch away with the role. + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.swatch("Cut").is_none()); +} + +#[test] +fn each_role_gets_its_own_swatch_color_in_the_document_s_mode() { + let mut s = session("rgb"); + for (i, role) in ["cut", "crease", "partialCut", "perforation"].into_iter().enumerate() { + let id = rect(&mut s, 20.0 + 60.0 * i as f64); + set_role(&mut s, json!({"role": role, "ids": [id.0]})); + } + let d = &s.doc().unwrap().doc; + let colors: Vec = ["Cut", "Crease", "Partial Cut", "Perforation"].iter().map(|n| d.swatch(n).unwrap().paint.color().unwrap()).collect(); + assert!(colors.iter().all(|c| matches!(c, Color::Rgb { .. })), "an RGB document's swatches are RGB: {colors:?}"); + assert_eq!(colors.iter().map(|c| c.to_hex()).collect::>().len(), 4, "four colors: {colors:?}"); +} + +#[test] +fn a_path_without_a_stroke_gets_one_and_overprint_can_be_left_off() { + let mut s = session("cmyk"); + let a = rect(&mut s, 20.0); + s.edit("strip", |d, _| { + let n = d.node_mut(a).unwrap(); + n.appearance.items.retain(AppearanceItem::is_fill); + Ok(()) + }) + .unwrap(); + assert!(node(&s, a).appearance.stroke().is_none()); + set_role(&mut s, json!({"role": "crease", "ids": [a.0], "overprint": false})); + let st = node(&s, a).appearance.stroke().cloned().unwrap(); + assert_eq!(st.width, 1.0, "a 1 pt stroke"); + assert!(!st.overprint); + assert!(matches!(&st.paint, Paint::Solid { swatch: Some(n), .. } if n == "Crease")); + assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "cut", "ids": [a.0], "overprint": "yes"})).contains("overprint")); +} + +#[test] +fn none_takes_the_role_away_and_keeps_the_color() { + let mut s = session("cmyk"); + let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 100.0)); + set_role(&mut s, json!({"role": "perforation", "ids": [a.0]})); + let shown = node(&s, a).appearance.stroke().unwrap().paint.color().unwrap(); + let before = steps(&s); + let r = set_role(&mut s, json!({"role": "none", "ids": [a.0, b.0]})); + assert_eq!(r["changed"].as_u64(), Some(1), "the plain rectangle has no role to take away"); + assert_eq!(steps(&s), before + 1); + let st = node(&s, a).appearance.stroke().cloned().unwrap(); + assert_eq!(st.paint, Paint::solid(shown)); + assert!(!st.overprint); + assert_eq!(counts(&mut s, json!({"ids": [a.0, b.0]})), [0, 0, 0, 0]); + // Nothing left with a role: no undo step. + set_role(&mut s, json!({"role": "none", "ids": [a.0, b.0]})); + assert_eq!(steps(&s), before + 1); +} + +#[test] +fn bad_roles_and_targets_are_refused() { + let mut s = session("cmyk"); + let a = rect(&mut s, 20.0); + assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "fold", "ids": [a.0]})).contains("unknown role")); + assert!(err(&mut s, "addon.packaging.setRole", json!({"ids": [a.0]})).contains("role")); + assert!(err(&mut s, "addon.packaging.setRole", json!({"role": 3, "ids": [a.0]})).contains("role")); + s.execute("select.none", &json!({})).unwrap(); + assert!(s.execute("addon.packaging.setRole", &json!({"role": "cut"})).is_err(), "nothing selected"); + let t = id_of(&s.execute("text.create", &json!({"x": 20, "y": 200, "text": "Lid", "size": 20})).unwrap()); + let before = steps(&s); + assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "cut", "ids": [t.0]})).contains("select a path")); + assert_eq!(steps(&s), before); + assert!(s.doc().unwrap().doc.swatch("Cut").is_none(), "a refused run makes no swatch"); + // Text beside a path is skipped and counted. + let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0, t.0]})); + assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(1), Some(1))); +} + +#[test] +fn groups_are_walked_and_their_locked_and_hidden_members_left_out() { + let mut s = session("cmyk"); + let (a, b, c) = (rect(&mut s, 20.0), rect(&mut s, 100.0), rect(&mut s, 180.0)); + s.execute("select.set", &json!({"ids": [a.0, b.0, c.0]})).unwrap(); + let g = id_of(&s.execute("object.group", &json!({})).unwrap()); + s.edit("lock", |d, _| { + d.node_mut(b).unwrap().locked = true; + d.node_mut(c).unwrap().visible = false; + Ok(()) + }) + .unwrap(); + let r = set_role(&mut s, json!({"role": "crease", "ids": [g.0]})); + assert_eq!(r["ids"], json!([a.0])); + assert_eq!(r["skipped"].as_u64(), Some(2), "the locked and the hidden member"); + assert_eq!(counts(&mut s, json!({"ids": [g.0]})), [0, 1, 0, 0]); + // Named directly, a locked or hidden path is left out too. + let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0, b.0, c.0]})); + assert_eq!((r["ids"].clone(), r["skipped"].as_u64()), (json!([a.0]), Some(2))); + let before = steps(&s); + assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "cut", "ids": [b.0]})).contains("locked")); + assert_eq!(steps(&s), before); + assert_eq!(counts(&mut s, json!({"ids": [b.0, c.0]})), [0, 0, 0, 0]); +} + +#[test] +fn a_clip_group_s_clipping_path_is_skipped_and_counted() { + let mut s = session("cmyk"); + let (art, mask) = (rect(&mut s, 20.0), rect(&mut s, 30.0)); + s.execute("select.set", &json!({"ids": [art.0, mask.0]})).unwrap(); + let g = id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap()); + let r = set_role(&mut s, json!({"role": "cut", "ids": [g.0]})); + assert_eq!((r["ids"].clone(), r["skipped"].as_u64()), (json!([art.0]), Some(1)), "the clipping path is left out and counted"); +} + +#[test] +fn a_group_and_its_member_count_once_and_locked_lines_count_in_every_scope() { + let mut s = session("cmyk"); + let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 100.0)); + set_role(&mut s, json!({"role": "cut", "ids": [b.0]})); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = id_of(&s.execute("object.group", &json!({})).unwrap()); + let r = set_role(&mut s, json!({"role": "crease", "ids": [g.0, a.0]})); + assert_eq!(r["ids"], json!([a.0, b.0]), "each path once"); + assert_eq!(counts(&mut s, json!({"ids": [g.0, a.0]})), [0, 2, 0, 0]); + set_role(&mut s, json!({"role": "cut", "ids": [b.0]})); + s.edit("lock", |d, _| { + d.node_mut(b).unwrap().locked = true; + Ok(()) + }) + .unwrap(); + // A locked line keeps its role and is counted, whether its group is selected or not. + assert_eq!(counts(&mut s, json!({"ids": [g.0]})), [1, 1, 0, 0]); + s.execute("select.none", &json!({})).unwrap(); + assert_eq!(counts(&mut s, json!({})), [1, 1, 0, 0]); +} + +#[test] +fn a_process_swatch_named_like_a_role_swatch_keeps_its_name() { + let mut s = session("cmyk"); + let a = rect(&mut s, 20.0); + s.execute("swatch.new", &json!({"name": "Cut", "color": "#ff0000"})).unwrap(); + set_role(&mut s, json!({"role": "cut", "ids": [a.0]})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.unknown.get("packagingRoles").unwrap()["cut"], json!("Cut 2")); + assert!(d.swatch("Cut 2").is_some_and(|w| w.spot), "the role swatch is made beside it"); + assert!(d.swatch("Cut").is_some_and(|w| !w.global), "the process swatch is left as it was"); + assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [1, 0, 0, 0]); +} + +#[test] +fn the_free_role_swatch_name_is_searched_past_ten_thousand() { + let mut s = session("cmyk"); + let a = rect(&mut s, 20.0); + let taken = std::iter::once("Cut".to_string()).chain((2..10_000).map(|i| format!("Cut {i}"))).chain(["Cut 10004".to_string()]); + let process = |name: String| vectorcraft_color::Swatch { name, paint: Paint::solid(Color::rgb(1.0, 0.0, 0.0)), global: false, spot: false }; + Arc::make_mut(&mut s.doc_mut().unwrap().doc).swatches.extend(taken.map(process)); + set_role(&mut s, json!({"role": "cut", "ids": [a.0]})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.unknown.get("packagingRoles").unwrap()["cut"], json!("Cut 10000")); + assert!(d.swatch("Cut 10000").is_some_and(|w| w.spot), "the role swatch is made under the first free name"); + assert!(d.swatch("Cut 10004").is_some_and(|w| !w.global), "a taken name is left as it was"); +} + +#[test] +fn a_merged_role_swatch_hands_its_role_to_the_kept_swatch() { + let mut s = session("cmyk"); + let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 100.0)); + set_role(&mut s, json!({"role": "cut", "ids": [a.0]})); + set_role(&mut s, json!({"role": "crease", "ids": [b.0]})); + s.execute("swatch.new", &json!({"name": "Die", "color": {"model": "cmyk", "c": 0, "m": 0.8, "y": 0.2, "k": 0}, "spot": true})).unwrap(); + s.execute("swatch.merge", &json!({"names": ["Die", "Cut"]})).unwrap(); + assert_eq!(s.doc().unwrap().doc.unknown.get("packagingRoles").unwrap()["cut"], json!("Die")); + assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [1, 0, 0, 0], "the cut line is still a cut line"); + // A kept swatch that already carries a role keeps it; the merged role's lines take it. + s.execute("swatch.merge", &json!({"names": ["Crease", "Die"]})).unwrap(); + let table = s.doc().unwrap().doc.unknown.get("packagingRoles").cloned().unwrap(); + assert_eq!((&table["cut"], &table["crease"]), (&json!("Die"), &json!("Crease")), "{table}"); + assert_eq!(counts(&mut s, json!({"ids": [a.0, b.0]})), [0, 2, 0, 0]); + // The next Make Cut Line makes the Cut role's swatch again. + set_role(&mut s, json!({"role": "cut", "ids": [a.0]})); + assert!(s.doc().unwrap().doc.swatch("Die").is_some_and(|w| w.spot)); + assert_eq!(counts(&mut s, json!({"ids": [a.0, b.0]})), [1, 1, 0, 0]); +} + +#[test] +fn a_global_process_swatch_can_carry_a_role() { + let mut s = session("cmyk"); + let a = rect(&mut s, 20.0); + s.execute("swatch.new", &json!({"name": "Die", "color": {"model": "cmyk", "c": 0, "m": 0.8, "y": 0.2, "k": 0}, "global": true})).unwrap(); + s.execute("addon.packaging.setRoleSwatch", &json!({"role": "partialCut", "swatch": "Die"})).unwrap(); + set_role(&mut s, json!({"role": "partialCut", "ids": [a.0]})); + assert!(matches!(&node(&s, a).appearance.stroke().unwrap().paint, Paint::Solid { swatch: Some(n), .. } if n == "Die")); + assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [0, 0, 1, 0]); +} + +#[test] +fn roles_counts_the_selection_or_the_whole_document() { + let mut s = session("cmyk"); + let (a, b, c) = (rect(&mut s, 20.0), rect(&mut s, 100.0), rect(&mut s, 180.0)); + set_role(&mut s, json!({"role": "cut", "ids": [a.0, b.0]})); + set_role(&mut s, json!({"role": "partialCut", "ids": [c.0]})); + s.execute("select.set", &json!({"ids": [a.0, c.0]})).unwrap(); + let r = s.execute("addon.packaging.roles", &json!({})).unwrap(); + assert_eq!((r["scope"].as_str(), r["selected"].as_u64()), (Some("selection"), Some(2))); + assert_eq!(counts(&mut s, json!({})), [1, 0, 1, 0]); + s.execute("select.none", &json!({})).unwrap(); + let r = s.execute("addon.packaging.roles", &json!({})).unwrap(); + assert_eq!((r["scope"].as_str(), r["selected"].as_u64()), (Some("document"), Some(0))); + assert_eq!(counts(&mut s, json!({})), [2, 0, 1, 0]); + let rows = r["roles"].as_array().unwrap(); + assert_eq!(rows[0], json!({"role": "cut", "name": "Cut", "swatch": "Cut", "exists": true, "count": 2})); + assert_eq!(rows[1]["exists"], json!(false), "no Crease swatch yet"); +} + +#[test] +fn role_swatches_maps_a_role_to_another_swatch() { + let mut s = session("cmyk"); + let a = rect(&mut s, 20.0); + set_role(&mut s, json!({"role": "cut", "ids": [a.0]})); + s.execute("swatch.new", &json!({"name": "Die", "color": {"model": "cmyk", "c": 0, "m": 0.8, "y": 0.2, "k": 0}, "spot": true})).unwrap(); + let before = steps(&s); + let r = s.execute("addon.packaging.setRoleSwatch", &json!({"role": "cut", "swatch": "Die"})).unwrap(); + assert_eq!(r["changed"], json!(true)); + assert_eq!(steps(&s), before + 1); + assert_eq!(s.doc().unwrap().doc.unknown.get("packagingRoles").unwrap()["cut"], json!("Die")); + // The old swatch's objects keep their color and lose the role. + assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [0, 0, 0, 0]); + set_role(&mut s, json!({"role": "cut", "ids": [a.0]})); + assert!(matches!(&node(&s, a).appearance.stroke().unwrap().paint, Paint::Solid { swatch: Some(n), .. } if n == "Die")); + // The same mapping again changes nothing. + let steps_now = steps(&s); + let r = s.execute("addon.packaging.setRoleSwatch", &json!({"role": "cut", "swatch": "Die"})).unwrap(); + assert_eq!((r["changed"].clone(), steps(&s)), (json!(false), steps_now)); +} + +#[test] +fn a_renamed_role_swatch_keeps_its_role() { + let mut s = session("cmyk"); + let a = rect(&mut s, 20.0); + set_role(&mut s, json!({"role": "crease", "ids": [a.0]})); + s.execute("swatch.edit", &json!({"name": "Crease", "newName": "Score"})).unwrap(); + assert_eq!(s.doc().unwrap().doc.unknown.get("packagingRoles").unwrap()["crease"], json!("Score")); + assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [0, 1, 0, 0]); + // A swatch that carries no role leaves the table alone. + s.execute("swatch.new", &json!({"name": "Ink", "color": {"model": "cmyk", "c": 0, "m": 1, "y": 1, "k": 0}, "spot": true})).unwrap(); + s.execute("swatch.edit", &json!({"name": "Ink", "newName": "Red Ink"})).unwrap(); + let table = s.doc().unwrap().doc.unknown.get("packagingRoles").cloned().unwrap(); + assert_eq!(table, json!({"cut": "Cut", "crease": "Score", "partialCut": "Partial Cut", "perforation": "Perforation"})); + // Undo puts the old name back in the table with the swatch. + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.unknown.get("packagingRoles").is_none()); + assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [0, 1, 0, 0]); +} + +#[test] +fn a_role_swatch_renamed_to_another_role_s_name_leaves_each_role_its_own_swatch() { + let mut s = session("cmyk"); + let a = rect(&mut s, 20.0); + set_role(&mut s, json!({"role": "cut", "ids": [a.0]})); + // No Crease swatch exists yet, so the name is free for the Cut swatch. + s.execute("swatch.edit", &json!({"name": "Cut", "newName": "Crease"})).unwrap(); + let table = s.doc().unwrap().doc.unknown.get("packagingRoles").cloned().unwrap(); + assert_eq!((&table["cut"], &table["crease"]), (&json!("Crease"), &json!("Crease 2")), "{table}"); + assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [1, 0, 0, 0], "the line is still a cut line"); +} + +#[test] +fn a_role_swatch_that_stops_being_global_hands_its_role_to_a_new_swatch() { + let mut s = session("cmyk"); + let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 100.0)); + set_role(&mut s, json!({"role": "perforation", "ids": [a.0]})); + s.execute("swatch.edit", &json!({"name": "Perforation", "spot": false, "global": false})).unwrap(); + assert_eq!(s.doc().unwrap().doc.unknown.get("packagingRoles").unwrap()["perforation"], json!("Perforation 2")); + assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [0, 0, 0, 0], "the unlinked stroke has no role"); + set_role(&mut s, json!({"role": "perforation", "ids": [b.0]})); + assert!(s.doc().unwrap().doc.swatch("Perforation 2").is_some_and(|w| w.spot)); + assert_eq!(counts(&mut s, json!({"ids": [b.0]})), [0, 0, 0, 1]); +} + +#[test] +fn a_color_group_named_like_a_role_swatch_keeps_its_name() { + let mut s = session("cmyk"); + let a = rect(&mut s, 20.0); + s.execute("swatch.newGroup", &json!({"name": "Cut", "colors": ["#ff0000"]})).unwrap(); + set_role(&mut s, json!({"role": "cut", "ids": [a.0]})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.unknown.get("packagingRoles").unwrap()["cut"], json!("Cut 2")); + assert!(d.swatch("Cut 2").is_some_and(|w| w.spot) && d.swatch("Cut").is_none()); + assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [1, 0, 0, 0]); +} + +#[test] +fn set_role_makes_a_deleted_role_swatch_again_for_strokes_that_still_name_it() { + let mut s = session("cmyk"); + let a = rect(&mut s, 20.0); + set_role(&mut s, json!({"role": "cut", "ids": [a.0]})); + s.execute("swatch.delete", &json!({"name": "Cut", "unlink": false})).unwrap(); + assert!(s.doc().unwrap().doc.swatch("Cut").is_none()); + let before = steps(&s); + let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0]})); + assert_eq!(r["changed"].as_u64(), Some(0), "the stroke already names the swatch"); + assert!(s.doc().unwrap().doc.swatch("Cut").is_some_and(|w| w.spot), "the swatch is back"); + assert_eq!(steps(&s), before + 1, "as one undo step"); +} + +#[test] +fn a_hidden_stroke_is_shown_when_it_takes_a_role() { + let mut s = session("cmyk"); + let a = rect(&mut s, 20.0); + s.edit("hide", |d, _| { + if let Some(AppearanceItem::Stroke(st)) = d.node_mut(a).unwrap().appearance.items.iter_mut().find(|i| !i.is_fill()) { + st.visible = false; + } + Ok(()) + }) + .unwrap(); + set_role(&mut s, json!({"role": "cut", "ids": [a.0]})); + assert!(node(&s, a).appearance.stroke().unwrap().visible); +} + +#[test] +fn role_swatches_refuses_swatches_that_cannot_carry_a_role() { + let mut s = session("cmyk"); + let ramp = json!({"type": "linear", "stops": [{"offset": 0, "color": "#000000"}, {"offset": 1, "color": "#ffffff"}]}); + s.execute("swatch.new", &json!({"name": "Ramp", "gradient": ramp})).unwrap(); + s.execute("swatch.new", &json!({"name": "Plain", "color": "#336699"})).unwrap(); + s.execute("swatch.new", &json!({"name": "Ink", "color": {"model": "cmyk", "c": 0, "m": 1, "y": 1, "k": 0}, "spot": true})).unwrap(); + s.execute("swatch.new", &json!({"name": "Ink Tint", "swatch": "Ink", "tint": 0.5})).unwrap(); + s.execute("swatch.new", &json!({"name": "Crease", "color": {"model": "cmyk", "c": 1, "m": 0, "y": 0, "k": 0}, "spot": true})).unwrap(); + let before = steps(&s); + for (swatch, says) in [ + ("Nope", "no swatch"), + ("Ramp", "isn't a color swatch"), + ("Plain", "process color"), + ("Ink Tint", "tint swatch"), + ("[None]", "can't carry a role"), + ("[Registration]", "can't carry a role"), + ("Crease", "already carries the Crease role"), + ] { + let e = err(&mut s, "addon.packaging.setRoleSwatch", json!({"role": "cut", "swatch": swatch})); + assert!(e.contains(says), "{swatch}: {e}"); + } + assert!(err(&mut s, "addon.packaging.setRoleSwatch", json!({"role": "none", "swatch": "Ink"})).contains("unknown role")); + assert!(err(&mut s, "addon.packaging.setRoleSwatch", json!({"role": "cut"})).contains("swatch")); + assert_eq!(steps(&s), before, "no refusal records an undo step"); +} + +#[test] +fn a_damaged_role_table_reads_as_the_defaults() { + let mut s = session("cmyk"); + s.edit("damage", |d, _| { + d.unknown.insert("packagingRoles".into(), json!({"cut": 5, "crease": "", "partialCut": null, "extra": "x"})); + Ok(()) + }) + .unwrap(); + let r = s.execute("addon.packaging.roles", &json!({})).unwrap(); + let swatches: Vec<&str> = r["roles"].as_array().unwrap().iter().map(|r| r["swatch"].as_str().unwrap()).collect(); + assert_eq!(swatches, ["Cut", "Crease", "Partial Cut", "Perforation"]); + s.edit("not an object", |d, _| { + d.unknown.insert("packagingRoles".into(), json!("Cut")); + Ok(()) + }) + .unwrap(); + let a = rect(&mut s, 20.0); + set_role(&mut s, json!({"role": "cut", "ids": [a.0]})); + assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [1, 0, 0, 0]); + // One swatch named for two roles: the later role takes its own default. + s.edit("duplicate", |d, _| { + d.unknown.insert("packagingRoles".into(), json!({"cut": "Crease", "crease": "Crease", "partialCut": "Cut"})); + Ok(()) + }) + .unwrap(); + let r = s.execute("addon.packaging.roles", &json!({})).unwrap(); + let swatches: Vec<&str> = r["roles"].as_array().unwrap().iter().map(|r| r["swatch"].as_str().unwrap()).collect(); + assert_eq!(swatches, ["Crease", "Crease 2", "Cut", "Perforation"]); + let b = rect(&mut s, 100.0); + set_role(&mut s, json!({"role": "crease", "ids": [b.0]})); + assert_eq!(counts(&mut s, json!({"ids": [b.0]})), [0, 1, 0, 0], "the crease line is a crease line"); +} + +#[test] +fn native_save_and_open_keep_the_role_table_and_the_roles() { + let mut s = session("cmyk"); + let a = rect(&mut s, 20.0); + s.execute("swatch.new", &json!({"name": "Die", "color": {"model": "cmyk", "c": 0, "m": 0.8, "y": 0.2, "k": 0}, "spot": true})).unwrap(); + s.execute("addon.packaging.setRoleSwatch", &json!({"role": "cut", "swatch": "Die"})).unwrap(); + set_role(&mut s, json!({"role": "cut", "ids": [a.0]})); + let saved = s.execute("document.export", &json!({"format": "vectorcraft"})).unwrap(); + s.execute("document.open", &json!({"name": "box.vectorcraft", "dataBase64": saved["dataBase64"]})).unwrap(); + assert_eq!(s.doc().unwrap().doc.unknown.get("packagingRoles").unwrap()["cut"], json!("Die")); + s.execute("select.none", &json!({})).unwrap(); + assert_eq!(counts(&mut s, json!({})), [1, 0, 0, 0]); +} + +/// A document with one rectangle of each of Cut and Crease. +fn two_roles() -> Session { + let mut s = session("cmyk"); + let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 100.0)); + set_role(&mut s, json!({"role": "cut", "ids": [a.0]})); + set_role(&mut s, json!({"role": "crease", "ids": [b.0]})); + s +} + +fn export(s: &mut Session, format: &str) -> String { + String::from_utf8_lossy(&b64(&s.execute("document.export", &json!({"format": format})).unwrap())).into_owned() +} + +#[test] +fn pdf_prints_each_role_on_its_swatch_s_separation_and_overprints_it() { + let mut s = two_roles(); + let c = rect(&mut s, 180.0); + set_role(&mut s, json!({"role": "partialCut", "ids": [c.0]})); + let bytes = vectorcraft_pdf::export( + &s.doc().unwrap().doc, + &vectorcraft_pdf::PdfOptions { created: Some(0), ..vectorcraft_pdf::PdfOptions::uncompressed() }, + ) + .unwrap(); + let pdf = String::from_utf8_lossy(&bytes); + assert!(pdf.contains("/Separation/Cut"), "the Cut line prints on the Cut plate"); + assert!(pdf.contains("/Separation/Crease")); + assert!(pdf.contains("/Separation/Partial#20Cut"), "a name with a space"); + assert!(pdf.contains("/OP true"), "the role strokes overprint"); + // Without overprint, nothing in the file overprints. + let mut plain = session("cmyk"); + let (a, b) = (rect(&mut plain, 20.0), rect(&mut plain, 100.0)); + set_role(&mut plain, json!({"role": "cut", "ids": [a.0], "overprint": false})); + set_role(&mut plain, json!({"role": "crease", "ids": [b.0], "overprint": false})); + let bytes = vectorcraft_pdf::export( + &plain.doc().unwrap().doc, + &vectorcraft_pdf::PdfOptions { created: Some(0), ..vectorcraft_pdf::PdfOptions::uncompressed() }, + ) + .unwrap(); + assert!(!String::from_utf8_lossy(&bytes).contains("/OP true")); + assert!(!export(&mut s, "pdf").is_empty()); +} + +#[test] +fn svg_dxf_and_hpgl_keep_the_default_role_swatches_apart() { + let mut s = two_roles(); + let svg = export(&mut s, "svg"); + let strokes: BTreeSet<&str> = svg.split("stroke=\"").skip(1).filter_map(|t| t.split('"').next()).filter(|c| c.starts_with('#')).collect(); + let strokes = if strokes.is_empty() { + svg.split("stroke:").skip(1).filter_map(|t| t.split([';', '"', '}']).next()).filter(|c| c.starts_with('#')).collect() + } else { + strokes + }; + assert_eq!(strokes.len(), 2, "two stroke colors: {svg}"); + let dxf = export(&mut s, "dxf"); + let lines: Vec<&str> = dxf.lines().map(str::trim).collect(); + // The rectangles' white fills come out as true colors too. + let colors: BTreeSet<&str> = lines.windows(2).filter(|w| w[0] == "420" && w[1] != "16777215").map(|w| w[1]).collect(); + assert_eq!(colors.len(), 2, "two stroke true colors: {colors:?}"); + let plot = s.execute("document.export", &json!({"format": "hpgl", "hpglVersion": "hpgl2"})).unwrap(); + let plot = String::from_utf8_lossy(&b64(&plot)).into_owned(); + assert!(plot.contains("SP1") && plot.contains("SP2"), "a pen per role swatch color: {plot}"); +} + +#[test] +fn compound_paths_carry_a_role() { + let mut s = session("cmyk"); + let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 30.0)); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let c = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap()); + assert!(matches!(node(&s, c).kind, NodeKind::Compound { .. })); + let r = set_role(&mut s, json!({"role": "cut", "ids": [c.0]})); + assert_eq!(r["ids"], json!([c.0])); + assert_eq!(counts(&mut s, json!({"ids": [c.0]})), [1, 0, 0, 0]); + // A member named by id gives its compound the role. + let r = set_role(&mut s, json!({"role": "crease", "ids": [a.0, b.0]})); + assert_eq!((r["ids"].clone(), r["changed"].as_u64()), (json!([c.0]), Some(1))); + assert_eq!(counts(&mut s, json!({"ids": [c.0]})), [0, 1, 0, 0]); +} diff --git a/crates/engine/src/cmd/addons/pathtools/tests.rs b/crates/engine/src/cmd/addons/pathtools/tests.rs index afa232a7ce..7d11eedd1a 100644 --- a/crates/engine/src/cmd/addons/pathtools/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/tests.rs @@ -1225,7 +1225,7 @@ fn expand_dashes_keeps_the_fill_below_and_follows_aligned_corners() { let mut centred = 0; for id in ids(&r) { let sp = path(&s, id).subpaths[0].clone(); - if let [a, b, c] = sp.anchors.as_slice() + if let [a, b, c] = &*sp.anchors.to_vec() && corners.iter().any(|k| b.p.distance(*k) < 1e-6) { assert!((a.p.distance(b.p) - 5.0).abs() < 1e-6 && (c.p.distance(b.p) - 5.0).abs() < 1e-6, "{sp:?}"); diff --git a/crates/engine/src/cmd/addons/select.rs b/crates/engine/src/cmd/addons/select.rs index b2ab59d851..c9ae29a303 100644 --- a/crates/engine/src/cmd/addons/select.rs +++ b/crates/engine/src/cmd/addons/select.rs @@ -14,8 +14,9 @@ use vectorcraft_doc::{LockedArtboards, Node, NodeId, NodeKind}; use vectorcraft_geom::Point; use super::super::links::{Status, statuses}; +use super::super::panelcmds::listed_artboards; use super::super::select::{is_selectable, on_artboard, selectable}; -use super::super::{CommandSpec, bad, checked_ids_param, cmd, has_doc, point_indices, switch_or, text_param}; +use super::super::{CommandSpec, bad, checked_ids_param, cmd, has_doc, switch_or, text_param}; use crate::{DocState, Result, Session}; /// How Select by Artboards relates an object to the chosen artboards (`relation`). @@ -33,7 +34,7 @@ pub fn specs() -> Vec { "Select by Artboards", ["Object", "Plug-ins", "Selection Tools"], None, - "{artboards: [index…] (0-based, at least one), relation?: \"overlap\" (default: on at least one of them, as select.allOnArtboard takes it: the bounds overlap the artboard or the centre is on it) | \"inside\" (the bounds lie wholly within one of them, edges included) | \"outside\" (on none of them)} select those objects among the ones Select All takes (in isolation mode, the isolated container's); hidden and locked objects, objects on hidden, locked or template layers and art held by a locked artboard are left out. Bounds are geometric, a symbol instance's measured by its art → {count}", + "{artboards: [index…] (0-based whole numbers, at least one), relation?: \"overlap\" (default: on at least one of them, as select.allOnArtboard takes it: the bounds overlap the artboard or the centre is on it) | \"inside\" (the bounds lie wholly within one of them, edges included) | \"outside\" (on none of them)} select those objects among the ones Select All takes (in isolation mode, the isolated container's); hidden and locked objects, objects on hidden, locked or template layers and art held by a locked artboard are left out. Bounds are geometric, a symbol instance's measured by its art → {count}", has_doc, by_artboards ), @@ -58,13 +59,12 @@ fn by_artboards(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "`relation` must be overlap, inside or outside")); } let listed = p.get("artboards").ok_or_else(|| bad(C, "missing `artboards`"))?; - let indices = point_indices(listed).ok_or_else(|| bad(C, "`artboards` must be a list of artboard indices"))?; - if indices.is_empty() { + if listed.as_array().is_some_and(Vec::is_empty) { return Err(bad(C, "choose at least one artboard")); } let st = s.doc()?; - let rects = - indices.iter().map(|i| st.doc.artboards.get(*i).map(|a| a.rect)).collect::>>().ok_or_else(|| bad(C, "no such artboard"))?; + let rects: Vec<_> = + listed_artboards(&st.doc, listed, "artboards", C)?.into_iter().filter_map(|i| st.doc.artboards.get(i)).map(|a| a.rect).collect(); let symbols = st.doc.symbol_boxes(); let ids: Vec = selectable(&st.doc, st.isolation) .into_iter() diff --git a/crates/engine/src/cmd/addons/select/tests.rs b/crates/engine/src/cmd/addons/select/tests.rs index c97b278258..09106a3652 100644 --- a/crates/engine/src/cmd/addons/select/tests.rs +++ b/crates/engine/src/cmd/addons/select/tests.rs @@ -108,6 +108,35 @@ fn bad_params_are_errors_and_leave_the_selection() { } } +/// A malformed `artboards` entry is refused as one, naming the parameter, before any entry is +/// looked up; a value that is not a list, an empty list, a left-out list and a whole number past +/// the last artboard each have their own error. +#[test] +fn artboard_errors_say_what_is_wrong() { + let mut s = three_boards(); + let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + let entries = "invalid parameters for `addon.select.byArtboards`: `artboards` must contain whole numbers"; + let not_a_list = "invalid parameters for `addon.select.byArtboards`: `artboards` must be a list of artboard indices"; + for (p, want) in [ + (json!({"artboards": ["1"]}), entries), + (json!({"artboards": [-1]}), entries), + (json!({"artboards": [1.5]}), entries), + (json!({"artboards": [true]}), entries), + (json!({"artboards": [9, "1"]}), entries), + (json!({"artboards": "0"}), not_a_list), + (json!({"artboards": null}), not_a_list), + (json!({"artboards": []}), "invalid parameters for `addon.select.byArtboards`: choose at least one artboard"), + (json!({}), "invalid parameters for `addon.select.byArtboards`: missing `artboards`"), + (json!({"artboards": [9]}), "no such artboard"), + (json!({"artboards": [0, 9]}), "no such artboard"), + ] { + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + assert_eq!(s.execute(C, &p).unwrap_err().to_string(), want, "{p}"); + assert_eq!(s.doc().unwrap().selection.objects, vec![a], "{p}"); + } + assert_eq!(pick(&mut s, json!({"artboards": [0, 0]})), vec![a]); +} + #[test] fn a_symbol_instance_is_measured_by_its_art() { // The symbol's art, (100, 60) to (140, 80), drawn 50 pt up and left: (50, 10) to (90, 30), on diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index 256e585923..04a36e556f 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -446,7 +446,7 @@ pub(crate) fn rows_per_target(d: &Document, of: Option, ids: &[NodeId], } /// Whether the `target` param asks for the contents of groups and layers (see the module docs). -fn targets_contents(p: &Value) -> Result { +pub(crate) fn targets_contents(p: &Value) -> Result { match p.get("target") { None | Some(Value::Null) => Ok(false), Some(v) => match v.as_str() { @@ -508,6 +508,20 @@ pub(crate) fn drop_design_art(d: &Document, mut ids: Vec) -> Vec ids } +/// [`drop_design_art`] for an edit of the `item` rows of `ids` (`fill`: fill rows): an explicit `item` that a design's +/// art has no row of that kind for is still an error of `cmd`, as on any other object. +pub(crate) fn drop_design_art_rows(s: &Session, ids: Vec, item: ItemTarget, fill: bool, cmd: &str) -> Result> { + let d = &s.doc()?.doc; + for (id, it) in ids.iter().zip(item.per_target(s, &ids)) { + if let (Some(it), Some(n)) = (it, d.node(*id)) + && super::graph::is_design_art(d, *id) + { + it.resolve(&n.appearance, fill, cmd)?; + } + } + Ok(drop_design_art(d, ids)) +} + /// The outermost art of graph designs drawn in graph series inside `roots`: the objects directly in a series group that /// [`super::graph::is_design_art`] accepts. pub(crate) fn design_art_in(d: &Document, roots: &[NodeId]) -> Vec { @@ -720,7 +734,10 @@ pub(crate) fn edits_stroke(s: &Session, p: &Value, item: ItemTarget, default: bo let holder = match reference_of(s, p, item, cmd)? { Some(of) => Some(of), None => { - let ids = drop_design_art(d, appearance_targets(s, p)?); + let all = appearance_targets(s, p)?; + // The art of a graph design is left out, unless it is all there is: the item is then a row of that art. + let kept = drop_design_art(d, all.clone()); + let ids = if kept.is_empty() { all } else { kept }; ids.get(item.anchor(s, &ids)).copied() } }; diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index d523577ae8..6ad6d1099e 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -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), 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 has its strokes replaced by one stroke with the paint and width, shown, fully opaque and blending normally, in the place of its topmost stroke and with the dashes, caps and arrowheads of its topmost shown stroke (a new stroke above the fills when it has none; none leaves one stroke of none), and its fills stay as they are; when every edge it reaches already has only that one stroke (at any width for none), nothing changes (no undo step, and the recent colors stay as they are) → {group, edge, count (edges reached)}", + "{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), through?: [id…] (scope connected only; at most 4096 edges counted as drawing with stroke paint match whatever they draw with, such as the edge a double-click's first click painted), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point, skipping hidden edges: each edge reached has its strokes replaced by one stroke with the paint and width, shown, fully opaque and blending normally, in the place of its topmost stroke and with the dashes, caps and arrowheads of its topmost shown stroke (a new stroke above the fills when it has none; none leaves one stroke of none), and its fills stay as they are; when every edge it reaches already has only that one stroke (at any width for none), nothing changes (no undo step, and the recent colors stay as they are) → {group, edge, count (edges reached)}", has_doc, lp_stroke_edge ), @@ -144,7 +144,7 @@ pub fn specs() -> Vec { "Make", ["Object", "Image Trace"], None, - "{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px, method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" clip group under the paths holds strokes along the edges two filled paths share, 1.5 image pixels wide (VectorCraft's own width), in the color of the lower path (on an image stretched more one way than another, each stroke's outline in image pixels as a filled path), clipped to the image's box within the traced paths' box; paths that became live shapes get none; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}", + "{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px (an area smaller than this joins the color it shares the longest border with; when that color is far from its own and the area is 2 px or more, or a single pixel whose longest border is not tied between colors, it joins the neighboring color nearest its pixels among those sharing at least a tenth of that border), method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" clip group under the paths holds strokes along the edges two filled paths share, 1.5 image pixels wide (VectorCraft's own width), in the color of the lower path (on an image stretched more one way than another, each stroke's outline in image pixels as a filled path), clipped to the image's box within the traced paths' box; paths that became live shapes get none; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}", has_selection_or_ids, |s, p| trace_make(s, p, false) ), diff --git a/crates/engine/src/cmd/buildcmds/live_paint.rs b/crates/engine/src/cmd/buildcmds/live_paint.rs index 6784f36294..46a2d37555 100644 --- a/crates/engine/src/cmd/buildcmds/live_paint.rs +++ b/crates/engine/src/cmd/buildcmds/live_paint.rs @@ -567,6 +567,16 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result { let tol = number_or(p, "tolerance", 4.0, C)?.clamp(0.0, 1000.0); let scope = scope_param(p, C)?; let like = match_param(p, C, scope != LpScope::One, "\"connected\" or \"samePaint\"")?; + let through: Vec = match p.get("through") { + None => vec![], + Some(_) if scope != LpScope::Connected => return Err(bad(C, "through applies to scope \"connected\"")), + Some(v) => { + let ids = v.as_array().filter(|ids| ids.len() <= 4096).ok_or_else(|| bad(C, "through must be an array of at most 4096 edge ids"))?; + ids.iter() + .map(|id| id.as_u64().map(NodeId).ok_or_else(|| bad(C, "through must be an array of at most 4096 edge ids"))) + .collect::>()? + } + }; 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")))?; @@ -575,7 +585,7 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result { 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::Connected => b::connected_edges_through(n, eid, &like, &through), 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(), diff --git a/crates/engine/src/cmd/buildcmds/trace.rs b/crates/engine/src/cmd/buildcmds/trace.rs index a2ac857903..203fd62338 100644 --- a/crates/engine/src/cmd/buildcmds/trace.rs +++ b/crates/engine/src/cmd/buildcmds/trace.rs @@ -12,6 +12,7 @@ use super::{ thread_local! { static BOX_TESTS: std::cell::Cell = const { std::cell::Cell::new(0) }; static CANDIDATE_VISITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static TRACES_ON_THIS_THREAD: std::cell::Cell = const { std::cell::Cell::new(0) }; } // ---------- Image Trace ---------- @@ -562,15 +563,20 @@ fn color_groups(cmd: &str, d: &mut Document, items: Vec>) -> Result, /// The settings traced with, as JSON. @@ -639,7 +645,8 @@ 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 { doc: s.doc()?.uid, target, image, params: traced_with, swatches: params.swatches.clone(), bytes }; + let st = s.doc()?; + let inputs = TraceInputs { doc: st.uid, reverts: st.reverts, target, image, params: traced_with, swatches: params.swatches.clone(), bytes }; Ok(Prepared { inputs, trace: params, view, params_json, preset_label, library }) } @@ -655,7 +662,8 @@ pub struct Traced { impl Traced { /// 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. + /// other trace drops it and traces again, a trace in another document included, and so does + /// the command after File › Revert replaced the document's content. pub fn hand_in(self, s: &mut Session) { s.trace_hand_off = Some(self); } @@ -664,6 +672,8 @@ impl Traced { /// Decode the image bytes of `inputs` and trace them with `params`, telling `steps` how far it has /// got ([`tr::trace_watched`]); [`EngineError::Cancelled`] once `steps` answers `false`. fn trace_now(inputs: &TraceInputs, params: &tr::TraceParams, steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result { + #[cfg(test)] + TRACES_ON_THIS_THREAD.with(|n| n.set(n.get() + 1)); // An image over the tracer's size is traced scaled down (the paths are scaled back). let raster = tr::Raster::decode_to_fit(&inputs.bytes).map_err(|e| EngineError::Other(e.to_string()))?; if !steps(0, 0) { @@ -848,17 +858,30 @@ impl TraceRun { } /// Does it still apply: would the command trace the same object, image, pixels and settings - /// now, in the document it was prepared in? + /// now, in the document it was prepared in, with no File › Revert since? pub fn current(&self, s: &Session) -> bool { prepare(s, self.command, &self.params).is_ok_and(|now| now.inputs == self.prepared.inputs) } + /// Has File › Revert replaced the content of the document it was prepared in since then? False + /// when that document is no longer open. + pub fn reverted(&self, s: &Session) -> bool { + let TraceInputs { doc, reverts, .. } = self.prepared.inputs; + s.documents().iter().any(|st| st.uid == doc && st.reverts != reverts) + } + /// Decode and trace the image, telling `steps` how far it has got → what it traced, or why it /// failed or stopped ([`EngineError::Cancelled`] once `steps` answers `false`). It touches no /// document, so it can run on any thread. pub fn run(&self, steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result { trace_now(&self.prepared.inputs, &self.prepared.trace, steps) } + + /// How many images this thread has decoded and traced so far. + #[cfg(test)] + pub(crate) fn traces_on_this_thread() -> usize { + TRACES_ON_THIS_THREAD.with(std::cell::Cell::get) + } } pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result { diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index f457712415..f9050779eb 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -595,6 +595,8 @@ struct Relink { styles: BTreeMap, /// Swatch (its name in the document) → the colour linked colours show at 100 %. colors: BTreeMap, + /// Leave graphic style links as they are ([`Clipboard::show_merged_colors`]). + keep_styles: bool, } impl Relink { @@ -674,7 +676,9 @@ impl Relink { /// Relink a node tree (the mirror of [`node_refs`]). fn node(&self, n: &mut Node) { self.appearance(&mut n.appearance); - n.extras_mut().graphic_style = n.extras().graphic_style.and_then(|id| self.styles.get(&id).copied()); + if !self.keep_styles { + n.extras_mut().graphic_style = n.extras().graphic_style.and_then(|id| self.styles.get(&id).copied()); + } if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) { self.node(Arc::make_mut(&mut m.art)); } @@ -1031,10 +1035,13 @@ impl Imported { self.relink.renames.entry(r).or_default().insert(from.to_string(), to.clone()); } } - /// Point a pasted copy at the document's resources. + /// Point a pasted copy at the document's resources. A pie's legend labels in wedges that now show a color of the + /// other darkness take the contrast a redraw sets there. pub(crate) fn apply(&self, n: &mut Node) { if self.relinks { + let shades = super::super::graph::wedge_shades(n); self.relink.node(n); + super::super::graph::follow_wedge_shades(n, &shades); } } } @@ -1109,6 +1116,30 @@ impl Clipboard { self.import_used(d, &self.used(), choices, same_doc) } + /// Give the objects' colors linked to a global or spot swatch whose conflict with `d` + /// `choices` merge the color that swatch has in `d`, as pasting into `d` gives them (Paste + /// without Formatting sets its pie legend labels' contrast from the wedge colors before it + /// pastes). Nothing changes for the document the objects came from (`same_doc`). + pub(crate) fn show_merged_colors(&mut self, d: &Document, choices: &SwatchChoices, same_doc: bool) { + if same_doc { + return; + } + let used = self.used(); + let colors: BTreeMap = self + .conflicts(d, &used) + .into_iter() + .filter(|(w, _)| choices.of(&w.name) == SwatchChoice::Merge) + .filter_map(|(w, _)| d.global_color(&w.name).map(|c| (w.name.clone(), c))) + .collect(); + if colors.is_empty() { + return; + } + let relink = Relink { colors, keep_styles: true, ..Default::default() }; + for n in &mut self.nodes { + relink.node(n); + } + } + /// [`Self::import_into`] for the resources `used` names. Each style, symbol, pattern and brush /// comes after the styles, symbols, patterns and brushes it uses ([`use_order`]), so that it is /// compared and relinked with their names here, and each loop of definitions that use each diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index 8377822094..9006b1f4be 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -221,6 +221,8 @@ pub(crate) struct Recolor<'a> { patterns: HashMap>, new_images: Vec<(String, ImageBlob)>, new_patterns: Vec, + /// Objects inside the recolored ones that keep their colors, with everything inside them. + skip: HashSet, changed: usize, } @@ -236,6 +238,7 @@ impl<'a> Recolor<'a> { patterns: HashMap::new(), new_images: vec![], new_patterns: vec![], + skip: HashSet::new(), changed: 0, } } @@ -254,7 +257,7 @@ impl<'a> Recolor<'a> { /// A pass that maps colors as this one does, with nothing recolored yet. fn again(&self) -> Self { - Self { links: self.links, gray_images: self.gray_images, remake: self.remake, ..Self::new(self.scope, self.f) } + Self { links: self.links, gray_images: self.gray_images, remake: self.remake, skip: self.skip.clone(), ..Self::new(self.scope, self.f) } } /// The entries of `objects` (ids, each with a flag) whose object this pass would change, other @@ -440,12 +443,20 @@ impl ColorVisitor for Visit<'_, '_> { fn image(&mut self, key: &str) -> Option { self.pass.image(self.d, key) } + fn enters(&mut self, n: &Node) -> bool { + !self.pass.skip.contains(&n.id) + } } pub(crate) fn recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color) -> Result { run_pass(s, p, cmd, label, Recolor::new(Scope::of(p, cmd)?, f)) } +/// [`recolor`] that leaves the objects `skip` inside the recolored ones, and everything inside them, as they are. +pub(crate) fn recolor_except(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color, skip: HashSet) -> Result { + run_pass(s, p, cmd, label, Recolor { skip, ..Recolor::new(Scope::of(p, cmd)?, f) }) +} + /// [`recolor`] where `f` gives gray colors, so embedded images are stored with one gray channel. fn recolor_gray(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color) -> Result { run_pass(s, p, cmd, label, Recolor { gray_images: true, ..Recolor::new(Scope::of(p, cmd)?, f) }) diff --git a/crates/engine/src/cmd/cut.rs b/crates/engine/src/cmd/cut.rs index 48f2c31e62..43f3aec881 100644 --- a/crates/engine/src/cmd/cut.rs +++ b/crates/engine/src/cmd/cut.rs @@ -356,7 +356,8 @@ fn mirror_open(sp: &SubPath, axis: &Axis, m: Affine) -> Vec { if !end_on { run.reverse(); } - let Some((last, body)) = run.anchors.split_last() else { return vec![] }; + let run = run.anchors.into_vec(); + let Some((last, body)) = run.split_last() else { return vec![] }; let q = axis.project(last.p); let mut anchors = body.to_vec(); anchors.push(Anchor::with_handles(q, last.h_in, m * last.h_in)); diff --git a/crates/engine/src/cmd/docmenu.rs b/crates/engine/src/cmd/docmenu.rs index ae48ba02e6..3b1e8a7666 100644 --- a/crates/engine/src/cmd/docmenu.rs +++ b/crates/engine/src/cmd/docmenu.rs @@ -10,6 +10,7 @@ use vectorcraft_doc::{CharStyle, Guide, Node, NodeId, NodeKind, SavedSelection, use vectorcraft_geom::Vec2; use super::edit::selected_roots; +use super::panelcmds::artboard_at; use super::pathops::Beside; use super::select::{first_selectable, is_selectable, selectable_ids, walk_selectable}; use super::{ @@ -201,7 +202,7 @@ pub fn specs() -> Vec { "Add Guide", [], None, - "{vertical: bool, pos: pt (x for vertical, y for horizontal), artboard?: index (an artboard guide: it runs across that artboard only and moves, is copied and is deleted with it; default a canvas guide, across the whole canvas), layer?: id (the layer it is on, shown, hidden, locked and deleted with it; default the current layer)} → {index}", + "{vertical: bool, pos: pt (x for vertical, y for horizontal), artboard?: index (0-based whole number; an artboard guide: it runs across that artboard only and moves, is copied and is deleted with it; default, or null, a canvas guide, across the whole canvas), layer?: id (the layer it is on, shown, hidden, locked and deleted with it; default the current layer)} → {index}", has_doc, guide_add ), @@ -767,15 +768,8 @@ fn clear_guides(s: &mut Session, _: &Value) -> Result { fn guide_add(s: &mut Session, p: &Value) -> Result { let pos = f64_req(p, "pos", "guide.add")?; let vertical = switch_or(p, "vertical", false, "guide.add")?; - let artboard = match p.get("artboard").filter(|v| !v.is_null()) { - Some(v) => { - let boards = &s.doc()?.doc.artboards; - let ab = v.as_u64().and_then(|i| boards.get(usize::try_from(i).ok()?)).ok_or_else(|| EngineError::Other("no such artboard".into()))?; - Some(ab.id) - } - None => None, - }; let st = s.doc()?; + let artboard = artboard_at(&st.doc, p, "artboard", "guide.add")?.and_then(|i| st.doc.artboards.get(i)).map(|a| a.id); let layer = match id_param(p, "layer") { Some(l) if st.doc.node(l).is_some_and(Node::is_layer) => Some(l), Some(_) => return Err(bad("guide.add", "layer must name a layer or sublayer")), diff --git a/crates/engine/src/cmd/draw2/freehand.rs b/crates/engine/src/cmd/draw2/freehand.rs index 45c25eb72c..55f5fe267b 100644 --- a/crates/engine/src/cmd/draw2/freehand.rs +++ b/crates/engine/src/cmd/draw2/freehand.rs @@ -46,7 +46,7 @@ fn fit_freehand(pts: &[Point], tol: f64, closed: bool) -> SubPath { let sp = vectorcraft_tools::draw2::catmull_rom(&marked, false); if sp.anchors.len() < 3 { // Two anchors closed would run back over the line itself. - return SubPath::new(sp.anchors, closed && n > 2); + return SubPath::of(sp.anchors, closed && n > 2); } let fitted = po::simplify_with( &PathData::single(sp.clone()), @@ -62,7 +62,7 @@ fn fit_freehand(pts: &[Point], tol: f64, closed: bool) -> SubPath { f.h_in = f.p; } } - SubPath::new(anchors, closed) + SubPath::of(anchors, closed) } /// The path of a freehand stroke: fitted at `tol` ([`fit_freehand`]), or with no `tol` the points @@ -133,13 +133,13 @@ fn redraw_section(pd: &PathData, pts: &[Point], tol: Option, within: f64) - *s0 = s1.p; let (Some(e0), Some(e1)) = (stroke.last_mut(), sp.anchors.get(end)) else { return None }; *e0 = e1.p; - let fit = stroke_subpath(&stroke, tol, false).anchors; + let fit = stroke_subpath(&stroke, tol, false).anchors.into_vec(); let (Some(f0), Some(f1)) = (fit.first().copied(), fit.last().copied()) else { return None }; let inner = fit.get(1..fit.len().saturating_sub(1)).unwrap_or_default(); let (before, after): (Vec, Vec) = if sp.closed { ((0..=(start + n - end) % n).filter_map(|k| sp.anchors.get((end + k) % n).copied()).collect(), vec![]) } else { - (sp.anchors.get(..=start)?.to_vec(), sp.anchors.get(end..)?.to_vec()) + (sp.anchors.get_range(..=start)?, sp.anchors.get_range(end..)?) }; let mut anchors = before; if let Some(a) = anchors.last_mut() { @@ -227,12 +227,18 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s let Some(p0) = pts.first_mut() else { return Err(bad(C, "needs points")) }; *p0 = end; if pts.len() < 2 { - // No stroke to add: the brush alone changes, when it is not the path's already. + // No stroke to add: the brush alone changes, when it is not the path's already, and the + // path is selected or deselected as a longer continuation leaves it. if let Some(name) = brush_name && s.doc()?.doc.node(target).and_then(|n| n.appearance.stroke()).is_some_and(|st| st.brush.as_deref() != Some(name)) { - s.edit("Paintbrush", |d, _| { + s.edit("Paintbrush", |d, sel| { set_brush(d, target, name); + if keep_selected { + sel.set([id]); + } else { + sel.remove(id); + } Ok(()) })?; } @@ -316,12 +322,12 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s // outgoing handle. let mut other_len = 0.0; if let Some((_, _, y, _)) = &connect - && let Some((y0, rest)) = y.anchors.split_first() + && let Some(y0) = y.anchors.first() { if let Some(last) = sp.anchors.last_mut() { *last = Anchor::with_handles(y0.p, last.h_in + (y0.p - last.p), y0.h_out); } - sp.anchors.extend_from_slice(rest); + sp.anchors.extend(y.anchors.iter().skip(1)); other_len = subpath_len(y); } // What the pen recorded along the path (in the direction it is continued in), followed by diff --git a/crates/engine/src/cmd/draw2/smooth.rs b/crates/engine/src/cmd/draw2/smooth.rs index be7db9a1ae..d0f480d132 100644 --- a/crates/engine/src/cmd/draw2/smooth.rs +++ b/crates/engine/src/cmd/draw2/smooth.rs @@ -117,11 +117,10 @@ fn smooth_corners(anchors: &[Anchor], closed: bool, reach: f64) -> Vec { // 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]; + // The lengths along the path ahead and back, measured once when an anchor needs them. + let (mut ahead, mut back) = (None, None); if closed { - let mut total = 0.0; - for i in 0..n { - total += walk(anchors, closed, (i, true), [f64::INFINITY; 2], reach, 1).1; - } + let total = ahead.get_or_insert_with(|| walk_blocks(anchors, closed, true, reach)).first().map_or(0.0, |lens| lens.iter().take(n).sum()); if !(total.is_finite() && total > 0.0) { return corners; } @@ -137,8 +136,10 @@ fn smooth_corners(anchors: &[Anchor], closed: bool, reach: f64) -> Vec { 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 }; + let back = back.get_or_insert_with(|| walk_blocks(anchors, closed, false, reach)); + let [Some(back_near), Some(back_far)] = spans.map(|r| point_along(anchors, closed, (i, false), r, back, reach)) else { continue }; + let ahead = ahead.get_or_insert_with(|| walk_blocks(anchors, closed, true, reach)); + let [Some(ahead_near), Some(ahead_far)] = spans.map(|r| point_along(anchors, closed, (i, true), r, ahead, reach)) 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)); @@ -146,9 +147,54 @@ fn smooth_corners(anchors: &[Anchor], closed: bool, reach: f64) -> Vec { 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; +/// The lengths [`walk`] measures along the segments of `anchors`, in the order a walk ahead +/// (`forward`) or back passes them, twice round, starting at the first anchor ahead or the last +/// anchor back, and added up in blocks: element `l` holds the lengths of each run of 2^`l` +/// segments that starts at a multiple of 2^`l`. Each block adds up only its own segments, so a short +/// stretch keeps its length next to very long ones. The segment past an open path's end has no +/// length. +fn walk_blocks(anchors: &[Anchor], closed: bool, forward: bool, reach: f64) -> Vec> { + let n = anchors.len(); + let lens: Vec = + (0..n).map(|k| walk(anchors, closed, (if forward { k } else { n - 1 - k }, forward), [f64::INFINITY; 2], reach, 1).1).collect(); + let mut blocks = vec![(0..2 * n).map(|k| lens[k % n]).collect::>()]; + while let Some(last) = blocks.last().filter(|b| b.len() > 1) { + let next = last.as_chunks::<2>().0.iter().map(|[a, b]| a + b).collect(); + blocks.push(next); + } + blocks +} + +/// The point `dist` along the path `anchors` from anchor `from.0`, ahead when `from.1` and back +/// otherwise, as [`walk`] finds it: an open path's end for a distance beyond the end, and `None` +/// when a length is not a number or is too large to add. The walk skips whole blocks of `blocks` +/// ([`walk_blocks`] in the same direction) that end no more than `dist` along the path, so a path of +/// very many short segments is not walked one segment at a time from each anchor. +fn point_along(anchors: &[Anchor], closed: bool, from: (usize, bool), dist: f64, blocks: &[Vec], reach: f64) -> Option { + let (n, (i, forward)) = (anchors.len(), from); + let start = if forward { i } else { n - 1 - i }; + let end = start + + if closed { + n + } else if forward { + n - 1 - i + } else { + i + }; + let (mut pos, mut gone) = (start, 0.0); + // The largest block that starts at `pos`, stays within the walk and ends within `dist`, until + // none does; a block whose length is not a number is never skipped. + while let Some((size, len)) = blocks.iter().enumerate().rev().find_map(|(l, lens)| { + let size = 1usize << l; + let len = lens.get(pos >> l).copied()?; + (pos % size == 0 && pos + size <= end && gone + len <= dist).then_some((size, len)) + }) { + pos += size; + gone += len; + } + let at = if forward { pos % n } else { n - 1 - pos % n }; + walk(anchors, closed, (at, forward), [(dist - gone).max(0.0); 2], reach, n).0[0] +} /// 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 @@ -274,7 +320,7 @@ fn refit_run(anchors: &[Anchor], tol: f64, sigma: f64, free: [bool; 2]) -> Vec Vec { "Paste", ["Edit"], Some("Cmd+V"), - "{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers and sublayers they came from (by the names of the layer and the layers around it in another document; a missing sublayer is made inside its layer; a hidden or locked one is an error and nothing is pasted). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}", + "{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch; legend labels in a pie's wedges that it turns dark or light take a redraw's contrast, unless their fill is their own) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers and sublayers they came from (by the names of the layer and the layers around it in another document; a missing sublayer is made inside its layer; a hidden or locked one is an error and nothing is pasted). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}", has_clipboard, |s, p| paste(s, p, PasteMode::Offset) ), diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index 42113c9578..1f471d84a3 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -367,7 +367,8 @@ fn edit_effects( /// [`edit_effects`] for several effects of one list (`indices`): `f` gets each target's list and /// the positions of `indices` there, ascending; with `aligned`, a position a target doesn't share -/// is left out of it, and a target sharing none of them is left out. +/// is left out of it, and a target sharing none of them is left out. A position no target has is +/// an error with `none`, and nothing changes. #[allow(clippy::too_many_arguments)] fn edit_effects_at( s: &mut Session, @@ -396,7 +397,12 @@ fn edit_effects_at( // Each target's list and the positions in it, in the order the targets first come up. let mut targets: Vec<(NodeId, Option, Vec)> = vec![]; for &index in indices { - for (id, at, i) in effect_targets(s, p, item, index, cmd)? { + let found = effect_targets(s, p, item, index, cmd)?; + // An aligned effect of a design's art that no other object has is refused, as it is given alone. + if found.is_empty() { + return Err(EngineError::Other(none.into())); + } + for (id, at, i) in found { match targets.iter_mut().find(|t| t.0 == id && t.1 == at) { Some(t) => t.2.push(i), None => targets.push((id, at, vec![i])), @@ -972,15 +978,18 @@ fn raster_image(d: &mut Document, n: &Node) -> Option<(Node, bool)> { /// Expand the pieces of `m`, art evaluated from the object of the same id (its pieces share that /// id): those made from its own fills and strokes, or with `all` every member. The other members /// that repeat an id ([`repeats_an_id`]) and hold a random Transform effect ([`has_seeded`]) are -/// expanded as well ([`expand_in_place`]). Then the members get ids of their own. Random in a -/// Transform effect takes its seed from the id, and the canvas draws the pieces with the ids they -/// have before that. Returns what each of those other members' expansions lists, by the member's -/// new id. +/// expanded as well ([`expand_in_place`]), except the objects `skip` lists. Then the members get ids +/// of their own. Random in a Transform effect takes its seed from the id, and the canvas draws the +/// pieces with the ids they have before that. `kept` gets the new id of each object in them that +/// had an id `skip` lists before. Returns what each of those other members' expansions lists, by +/// the member's new id. fn expand_pieces( d: &mut Document, m: &mut Node, all: bool, brushes: &[vectorcraft_brush::Brush], + skip: &[NodeId], + kept: &mut Vec, stroke_art: effects::StrokeArt, ) -> std::collections::HashMap> { let id = m.id; @@ -996,9 +1005,23 @@ fn expand_pieces( if all || c.id == id { effects::expand_art(d, c, stroke_art); } else if has_seeded(c) && repeats_an_id(c, &seen) { - listed = Some(expand_in_place(d, c, brushes)); + listed = Some(expand_in_place(d, c, brushes, skip)); + } + let mut was = vec![]; + if !skip.is_empty() { + c.walk(&mut |n| was.push(n.id)); } fresh_ids_listed(d, c, &mut seen, listed.as_deref_mut().unwrap_or_default()); + if !was.is_empty() { + // A copy of an object `skip` lists is left as it is too. + let mut at = 0; + c.walk(&mut |n| { + if was.get(at).is_some_and(|old| *old != n.id && skip.contains(old)) { + kept.push(n.id); + } + at += 1; + }); + } if let Some(listed) = listed { expanded.insert(c.id, listed); } @@ -1052,9 +1075,9 @@ fn repeats_an_id(n: &Node, seen: &std::collections::HashSet) -> bool { type Listed = (NodeId, usize); /// [`expanded_node`] of `c` in place. Returns what the expansion lists, by places in the walk of `c`. -fn expand_in_place(d: &mut Document, c: &mut Node, brushes: &[vectorcraft_brush::Brush]) -> Vec { +fn expand_in_place(d: &mut Document, c: &mut Node, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId]) -> Vec { let mut listed = vec![]; - if let Some(e) = expanded_node(d, c.clone(), brushes, &mut listed) { + if let Some(e) = expanded_node(d, c.clone(), brushes, skip, &mut listed) { *c = e; } listed @@ -1078,9 +1101,16 @@ fn fresh_ids_listed(d: &mut Document, c: &mut Node, seen: &mut std::collections: /// geometry effects are baked, raster effects become an embedded image, and the object keeps its /// transparency. pub(crate) fn expand_node(d: &mut Document, id: NodeId, brushes: &[vectorcraft_brush::Brush], out: &mut Vec) { + expand_node_except(d, id, brushes, &[], out); +} + +/// [`expand_node`], leaving the objects `skip` lists, and what they hold, as they are. A geometry +/// effect of a group or layer around one still reshapes it with the rest of its members, and the +/// copies of it that such an effect makes are left as they are too. +fn expand_node_except(d: &mut Document, id: NodeId, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId], out: &mut Vec) { let Some(n) = d.node(id).cloned() else { return }; let mut listed = vec![]; - let m = expanded_node(d, n, brushes, &mut listed); + let m = expanded_node(d, n, brushes, skip, &mut listed); out.extend(listed.into_iter().map(|(id, _)| id)); if let Some(mut m) = m { // Art made from type takes its emoji's pixels into the document. @@ -1093,10 +1123,10 @@ pub(crate) fn expand_node(d: &mut Document, id: NodeId, brushes: &[vectorcraft_b /// [`expand_node`] of `n`, which need not be in `d`: `n` with its appearance expanded, `None` when /// it has nothing to expand. `out` gets the objects whose appearance expands, by places in the walk -/// of the expanded `n`, `n`'s first when its own does. -fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Brush], out: &mut Vec) -> Option { +/// of the expanded `n`, `n`'s first when its own does. The objects `skip` lists are not expanded. +fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId], out: &mut Vec) -> Option { let id = n.id; - if !expandable(&n) { + if skip.contains(&id) || !expandable(&n) { return None; } // Colour adjustments: the colours inside become the adjusted ones (an embedded image a @@ -1133,7 +1163,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br for (i, c) in m.children_mut().into_iter().flatten().enumerate() { let c = Arc::make_mut(c); if i == 0 { - expanded = expand_in_place(d, c, brushes); + expanded = expand_in_place(d, c, brushes, skip); fresh_ids_listed(d, c, &mut seen, &mut expanded); } else { effects::fresh_ids(d, c, &mut seen); @@ -1163,6 +1193,8 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br |d: &mut Document, path: &PathData, rule: FillRule, st: &StrokeLayer| super::pathops::outlined_stroke(d, brushes, path, rule, st); // Members of a group or layer that `expand_pieces` expanded, by id, with what their expansion lists. let mut members = std::collections::HashMap::new(); + // New ids of the copies of objects `skip` lists among those members. + let mut kept = vec![]; let expanded = match image { // Blur, feather and inner glow change the object itself: it becomes the image (a layer // keeps it as its only member). @@ -1174,7 +1206,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br } else if container { // A group's or layer's own fills and strokes become art among its members. effects::evaluate_container(Some(&*d), &v).map(|mut m| { - members = expand_pieces(d, &mut m, false, brushes, &mut stroke_art); + members = expand_pieces(d, &mut m, false, brushes, skip, &mut kept, &mut stroke_art); m }) } else if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) @@ -1195,7 +1227,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br effects::expand_outlined(Some(&*d), &v, symbol.as_ref()).map(|mut m| { let mut budget = vectorcraft_doc::MAX_SYMBOL_NODES; expand_nested_instances(d, &mut m, 1, &mut budget); - expand_pieces(d, &mut m, true, brushes, &mut stroke_art); + expand_pieces(d, &mut m, true, brushes, skip, &mut kept, &mut stroke_art); m }) }; @@ -1217,6 +1249,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br } } if container { + let skip = if kept.is_empty() { std::borrow::Cow::Borrowed(skip) } else { std::borrow::Cow::Owned([skip, &kept].concat()) }; // The place of each member in the walk of `n`: after `n` and the members before it. let mut at = 1; for c in n.children_mut().into_iter().flatten() { @@ -1229,7 +1262,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br match members.remove(&c.id) { Some(listed) => out.extend(listed), None => { - if let Some(e) = expanded_node(d, (**c).clone(), brushes, out) { + if let Some(e) = expanded_node(d, (**c).clone(), brushes, &skip, out) { *c = Arc::new(e); changed = true; } @@ -1274,9 +1307,20 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result { // geometry it hasn't changed. if vectorcraft_plugins::safe_mode::active() { // A dimension selected with the art it measures is left as it is, and so is the art of a graph design in a - // series. + // series, unless an effect of a group around it, the selected graph or series group or one inside it, draws it + // with that group: an effect of the group's own, or a raster effect of one of its fills or strokes (the group + // then becomes an image of all of it). let mut d = super::dimension::without_kept(&s.doc()?.doc, &roots); - let designs = super::appearance::design_art_in(&d, &roots); + let draws_members = |g: &Node| g.appearance.effects.iter().any(|e| e.visible) || !rasterfx::raster_fx(g).is_empty(); + let designs: Vec = super::appearance::design_art_in(&d, &roots) + .into_iter() + .filter(|art| { + !d.ancestry(*art).is_some_and(|up| { + let from = up.iter().position(|a| roots.contains(a)).unwrap_or(up.len()); + up.get(from..up.len().saturating_sub(1)).is_some_and(|around| around.iter().filter_map(|a| d.node(*a)).any(draws_members)) + }) + }) + .collect(); if !designs.is_empty() { let view = d.to_mut(); for id in designs { @@ -1307,16 +1351,7 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result { let mut out = vec![]; let threaded = super::threads::frames(d); for id in &roots { - expand_node(d, *id, &brushes, &mut out); - } - for id in &designs { - if let (Some(was), Some(slot)) = (before.node(*id), d.node_mut(*id)) { - *slot = was.clone(); - } - } - if !designs.is_empty() { - // A mark that expands into a group stays listed: only what lies in the restored art is left out. - out.retain(|id| d.node(*id).is_some() && !d.ancestry(*id).is_some_and(|up| up.iter().any(|a| designs.contains(a)))); + expand_node_except(d, *id, &brushes, &designs, &mut out); } super::dimension::put_back(d, lifted); // A dimension whose source was replaced stays where it was, no longer linked. diff --git a/crates/engine/src/cmd/expand.rs b/crates/engine/src/cmd/expand.rs index 43975fe4e4..a17a02ed15 100644 --- a/crates/engine/src/cmd/expand.rs +++ b/crates/engine/src/cmd/expand.rs @@ -265,18 +265,21 @@ 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 with its unplaced gradients fitted to the layout's bounds, has one +/// bars, each painted as its run with its unplaced gradients fitted to the layout's bounds, or the +/// path filled with its run's stroke under a transform that is not a similarity, 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(_))) { + let gradient = + |st: &vectorcraft_doc::CharStyle| matches!(st.fill, Paint::Gradient(_)) || (st.has_stroke() && matches!(st.stroke, Paint::Gradient(_))); + if !t.runs.iter().any(|r| gradient(&r.style)) { 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_or(&first, |r| &r.style); - if !matches!(style.fill, Paint::Gradient(_)) { + if !gradient(style) { return false; } let path = PathData::from_bezpath(outline); @@ -284,8 +287,8 @@ fn text_gradient_expands(d: &Document, t: &TextObject) -> bool { return false; } 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 stroke = vectorcraft_render::effects::paint_type_piece(&mut piece, style, lay.bounds, t.xf); + gradient_expands(d, &piece) || stroke.is_some_and(|s| gradient_expands(d, &s)) }; 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 28cd71804a..fc5be365d5 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -54,6 +54,7 @@ pub mod ppi; pub mod progress; mod psdlayers; pub mod psdread; +mod psdslices; mod pxrread; mod save; mod screens; @@ -93,6 +94,9 @@ pub(crate) use native::preview_png; pub use native::with_compression_pref; pub(crate) use pdfimport::opened_page_document; pub use pdfimport::{LoadOptions, page_document}; +pub(crate) use psdlayers::import_active as psd_layers; +pub use psdlayers::{PsdInfo, info as psd_info}; +pub(crate) use psdslices::over as psd_slices; pub(crate) use save::job_for; pub(crate) use save::save as save_document; pub use save::{ @@ -240,6 +244,8 @@ mod tests_psd; mod tests_psdlayers; #[cfg(test)] mod tests_psdread; +#[cfg(test)] +mod tests_psdslices; #[cfg(test)] mod tests_heifread; diff --git a/crates/engine/src/cmd/fileio/access.rs b/crates/engine/src/cmd/fileio/access.rs index cb5b4e85cc..856656f564 100644 --- a/crates/engine/src/cmd/fileio/access.rs +++ b/crates/engine/src/cmd/fileio/access.rs @@ -149,7 +149,9 @@ pub(crate) const IMAGE_OUTSIDE: &str = "a linked image file is outside the read /// file with SVG Options › Images set to Link, and with Embed when the document holds no pixels for /// the image, for the images of the art each file draws (with chosen artboards, the art over each /// one; hidden layers and objects only with `hiddenLayers`, template layers and the opacity-mask -/// and symbol editing layers never) and of the symbols, patterns and brushes that art uses; with +/// and symbol editing layers never, opacity masks not with SVG Tiny 1.2, and objects with effects +/// SVG has no filters for as the images the file draws of them), of the art the file draws for each +/// placed document, and of the symbols, patterns and brushes that art uses; with /// Preserve Editing Capabilities, the native document the file carries names every linked file, the relative paths kept of them /// and each data set's image. The error names no file or folder. pub fn check_linked_images(cmd: &str, format: &str, st: &crate::DocState, d: &vectorcraft_doc::Document, p: &Value) -> Result<()> { @@ -162,21 +164,27 @@ pub(crate) fn check_images_in(cmd: &str, format: &str, d: &vectorcraft_doc::Docu if !matches!(format, "svg" | "svgz") || crate::file_access::current().is_none() { return Ok(()); } - // Options that don't read as the encoder's choices count as Link, Preserve Editing and hidden - // layers kept: the encoder refuses them anyway. - let (link, preserve, hidden) = match super::svg::options_map(p) { + // Options that don't read as the encoder's choices count as Link, Preserve Editing, hidden + // layers kept and SVG 1.1: the encoder refuses them anyway. + let (link, preserve, hidden, tiny) = match super::svg::options_map(p) { Ok(m) => { let on = |k: &str| m.get(k).is_some_and(|v| v.as_bool() != Some(false)); - (m.get("images").is_some_and(|v| v.as_str() != Some("embed")), on("preserveEditing"), on("hiddenLayers")) + let tiny = m.get("profile").and_then(Value::as_str) == Some("tiny12"); + (m.get("images").is_some_and(|v| v.as_str() != Some("embed")), on("preserveEditing"), on("hiddenLayers"), tiny) } - Err(_) => (true, true, true), + Err(_) => (true, true, true, false), }; // The opacity-mask and symbol editing layers are never written. let d = &*d.without_edit_modes(); - let names = |d: &vectorcraft_doc::Document| crate::cmd::links::svg_names_hidden_image(d, base, link, hidden); - if preserve && crate::cmd::links::names_hidden_file(d, base) - || names(d) && super::svg::drawn(d, p).is_none_or(|files| files.iter().any(|f| names(f))) - { + let names = |d: &vectorcraft_doc::Document| crate::cmd::links::svg_names_hidden_image(d, base, link, hidden, tiny); + // The SVG draws the objects with effects it has no filters for as images of them, as the + // encoder and the clipboard prepare them. + let drawing_names = || { + let flat = crate::cmd::rasterfx::flatten_pixel_effects_for(d, !tiny); + let d = flat.as_ref().unwrap_or(d); + names(d) && super::svg::drawn(d, p).is_none_or(|files| files.iter().any(|f| names(f))) + }; + if preserve && crate::cmd::links::names_hidden_file(d, base) || names(d) && drawing_names() { return Err(bad(cmd, IMAGE_OUTSIDE)); } Ok(()) diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index 505c87cc8b..657cab3060 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -1,6 +1,6 @@ use super::access::file_list; use super::formats::formats; -use super::{CommandSpec, action_batch, always, batch, cmd, export, has_doc, has_selection, load, pdfimport, save, screens}; +use super::{CommandSpec, action_batch, always, batch, cmd, export, has_doc, has_selection, load, pdfimport, psdlayers, save, screens}; pub fn specs() -> Vec { vec![ @@ -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, through the profiles the document keeps after the color management policies of edit.colorSettings, 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; a blank page: its crop box; a PDF-compatible .ai: its trim box for crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), 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}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; 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, and the artboards are 36 pt apart plus that bleed on both sides; 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), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), 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, through the profiles the document keeps after the color management policies of edit.colorSettings, 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; a blank page: its crop box; a PDF-compatible .ai: its trim box for crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), 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}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; 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 ), @@ -139,6 +139,15 @@ pub fn specs() -> Vec { always, pdfimport::pdf_info ), + cmd!( + query "document.psdInfo", + "PSD Info", + [], + None, + "{path} or {name?, dataBase64} what a PSD or PSB file holds, read from its header, slices and layer records without decoding pixels → {format: psd|psb, width, height (the canvas, px), layers (group markers not counted), hiddenLayers (the hidden ones among them), groups, slices (those importSlices brings in; 0 when the file has none or they can't be read)}; a file without layer records, or whose layer records can't be read, has layers: 0 and opens and places as its merged image; a file that is not a PSD or PSB file is an error", + always, + psdlayers::psd_info + ), cmd!( "document.exportForOffice", "Save for Office Documents…", diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index 2ff393b685..22d7f5dad9 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -528,17 +528,26 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result } // A PSD or PSB file's layers become layers (`layers`, default on); without layers, or with // `layers: false`, its merged image opens. Layers that can't be read leave the merged image. - "psd" | "psb" if opts.layers => { - let cms = vectorcraft_color::cms::active(); - match super::psdlayers::import(bytes, opts.hidden_layers, MAX_RASTER_ALLOC, |c| cms.cmyk_to_srgb(c, false)) { - Ok(Some((doc, warnings))) => (doc, warnings, false), - Ok(None) => (raster_doc(&title, bytes)?, vec![], false), - Err(e) => (raster_doc(&title, bytes)?, vec![format!("the layers can't be read ({e}): the file opened as its merged image")], false), - } - } + "psd" | "psb" if opts.layers => match super::psdlayers::import_active(bytes, opts.hidden_layers) { + Ok(Some((doc, warnings))) => (doc, warnings, false), + Ok(None) => (raster_doc(&title, bytes)?, vec![], false), + Err(e) => (raster_doc(&title, bytes)?, vec![format!("the layers can't be read ({e}): the file opened as its merged image")], false), + }, _ if format.raster => (raster_doc(&title, bytes)?, vec![], false), _ => return Err(err(format!("{} files can't be opened yet", format.label))), }; + // A PSD or PSB file's slices become user slices over its canvas (`importSlices`, default on), + // whether its layers or its merged image came in. + if matches!(format.id, "psd" | "psb") + && opts.import_slices + && let Some(canvas) = doc.artboards.first().map(|a| a.rect) + { + let (slices, notes) = super::psd_slices(bytes, canvas); + for (rect, options) in slices { + crate::cmd::slices::add_slice(&mut doc, rect, options); + } + warnings.extend(notes); + } // A PDF, `.ai` or `.ait` read from its pages or its editing copy, not restored from the document // it carries, opens with the File Info it gives (a PostScript `.ai` gives none). if matches!(format.id, "pdf" | "ai" | "ait") @@ -885,12 +894,19 @@ pub(crate) fn too_large_note(bytes: &[u8]) -> Option { if let Some((w, h)) = vectorcraft_doc::cmyk::oversized_tiff(bytes) { return Some(format!("an image of {w} × {h} pixels is too large to draw")); } - let d = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?.into_decoder().ok()?; + let reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?; + let format = reader.format()?; + let d = reader.into_decoder().ok()?; let (w, h) = d.dimensions(); // The allowance also counts the pixels as RGBA: an image of fewer than 4 bytes a pixel (gray, // gray with alpha, RGB) takes more than the decoder counts (#1717). let rgba_over = u64::from(w) * u64::from(h) > MAX_RASTER_ALLOC / 4; - (rgba_over || d.total_bytes() > MAX_RASTER_ALLOC).then(|| format!("an image of {w} × {h} pixels is too large to draw")) + let samples_over = d.total_bytes() > MAX_RASTER_ALLOC; + // The renderer can stream a non-interlaced PNG a row at a time when those buffers fit. Its + // full decoded byte count can exceed the allowance even though drawing it at native size is + // safe; use the renderer's decision for that case instead of warning from total_bytes alone. + let png_streams_at_size = samples_over && format == image::ImageFormat::Png && vectorcraft_render::reduced_size(bytes) == Some((w, h)); + (rgba_over || (samples_over && !png_streams_at_size)).then(|| format!("an image of {w} × {h} pixels is too large to draw")) } /// What Open, Place and the Links panel say of encoded image `bytes` that [`too_large_note`] is diff --git a/crates/engine/src/cmd/fileio/pdf.rs b/crates/engine/src/cmd/fileio/pdf.rs index 77902b4a15..5fe3211e2b 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 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, and with destination and an sRGB destination a gray or RGB image tagged with an ICC profile is converted from it and written untagged; with destination and a CMYK destination, or another RGB one images are converted to (not when colours are ICC-tagged), an RGB image tagged with one is converted from it through sRGB; 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", + "{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, and with destination and an sRGB destination a gray or RGB image tagged with an ICC profile is converted from it and written untagged; with destination and a CMYK destination, or another RGB one images are converted to (not when colours are ICC-tagged), an RGB image tagged with one is converted from it through sRGB; any other image whose colors are converted but whose pixels can't be decoded or written that way is left out with a warning; 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; images are written without the ICC profiles they carry, a JPEG without its ICC_PROFILE segments, but in PDF/A, pdfX3 and pdfX4)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile)|default (not set, the default; \"default\" unsets a preset's value, null keeps it: device colours, and gray and RGB images keep the profiles they carry, but in pdfX1a) (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 ), diff --git a/crates/engine/src/cmd/fileio/pdfimport.rs b/crates/engine/src/cmd/fileio/pdfimport.rs index 00eef89a11..189274a31f 100644 --- a/crates/engine/src/cmd/fileio/pdfimport.rs +++ b/crates/engine/src/cmd/fileio/pdfimport.rs @@ -36,6 +36,8 @@ pub struct LoadOptions { pub layers: bool, /// A PSD or PSB file's hidden layers come in, hidden (`hiddenLayers`; else they are left out). pub hidden_layers: bool, + /// A PSD or PSB file's slices become user slices (`importSlices`; else they are left out). + pub import_slices: bool, /// How a DXF drawing comes in (the `dxf` param, see [`super::dxfimport`]). pub dxf: vectorcraft_cad::ImportOptions, /// An Illustrator EPS or `.ai` that carries the editing copy of its art opens from it (its @@ -67,6 +69,7 @@ impl Default for LoadOptions { text_as: TextAs::default(), layers: true, hidden_layers: false, + import_slices: true, dxf: Default::default(), editing_data: true, trust_editing_data: false, @@ -81,7 +84,7 @@ impl LoadOptions { /// From command params: `pages` (`"2-3, 5"`, a page number or `"all"`), `page` (one page, when /// `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`), + /// `importSlices` (true | false), `editingData` (true | false | `always`), /// `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 { @@ -111,6 +114,10 @@ impl LoadOptions { None => false, Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "hiddenLayers must be true or false"))?, }; + let import_slices = match p.get("importSlices").filter(|v| !v.is_null()) { + None => true, + Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "importSlices must be true or false"))?, + }; let (editing_data, trust_editing_data) = match p.get("editingData").filter(|v| !v.is_null()) { None => (true, false), Some(Value::String(s)) if s.eq_ignore_ascii_case("always") => (true, true), @@ -137,6 +144,7 @@ impl LoadOptions { text_as, layers, hidden_layers, + import_slices, dxf, editing_data, trust_editing_data, diff --git a/crates/engine/src/cmd/fileio/psdlayers.rs b/crates/engine/src/cmd/fileio/psdlayers.rs index c3c45029a0..ea5cf63aa2 100644 --- a/crates/engine/src/cmd/fileio/psdlayers.rs +++ b/crates/engine/src/cmd/fileio/psdlayers.rs @@ -43,6 +43,7 @@ use std::cell::Cell; use std::sync::Arc; use image::RgbaImage; +use serde_json::{Value, json}; use vectorcraft_color::BlendMode; use vectorcraft_color::blend::{blend_rgb, composite}; use vectorcraft_color::cms::{Lab, lab::lab_to_srgb}; @@ -51,6 +52,7 @@ use vectorcraft_geom::Affine; use super::load::{RasterImage, as_png}; use super::psdread::{Header, Reader, byte, header, layer_channel, layer_info, long_key, row_bytes, sample, to_rgb}; +use crate::cmd::Session; use crate::cmd::place::text::mac_roman; /// Most layer groups inside one another. @@ -1527,3 +1529,65 @@ pub(super) fn import( doc.limit_depth_noting(&mut warnings); Ok(Some((doc, warnings))) } + +/// [`import`] within the memory allowed for one image, CMYK converted with the active color +/// settings: what `document.open` and `file.place` read a PSD or PSB file's layers with. +pub(crate) fn import_active(bytes: &[u8], hidden: bool) -> Result)>, String> { + let cms = vectorcraft_color::cms::active(); + import(bytes, hidden, super::MAX_RASTER_ALLOC, |c| cms.cmyk_to_srgb(c, false)) +} + +/// What a PSD or PSB file holds (`document.psdInfo`, the PSD Import Options dialog). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct PsdInfo { + /// The large document format. + pub psb: bool, + /// The canvas, in pixels. + pub width: u32, + pub height: u32, + /// The layers, group markers left out. + pub layers: usize, + /// The layers among them that are hidden. + pub hidden: usize, + /// The layer groups. + pub groups: usize, + /// The slices that come in with `importSlices` (those generated automatically, and those + /// outside the canvas, left out). + pub slices: usize, +} + +/// What PSD or PSB file `bytes` holds, read from its header, its slices and its layer records +/// without decoding any pixels. A file without layer records, or whose layer records can't be read, has no layers: it +/// opens and places as its merged image. +pub fn info(bytes: &[u8]) -> Result { + let mut r = Reader::new(bytes); + let h = header(&mut r)?; + let records = layer_info(h.layers, h.psb).filter(|info| info.len() > 2).and_then(|info| records(info, h.psb).ok()).unwrap_or_default(); + let layers = records.iter().filter(|r| r.divider == 0); + Ok(PsdInfo { + psb: h.psb, + width: h.width, + height: h.height, + layers: layers.clone().count(), + hidden: layers.filter(|r| r.hidden).count(), + groups: records.iter().filter(|r| matches!(r.divider, 1 | 2)).count(), + slices: super::psdslices::count(bytes), + }) +} + +const INFO: &str = "document.psdInfo"; + +/// `document.psdInfo`. +pub(super) fn psd_info(_: &mut Session, p: &Value) -> crate::cmd::Result { + let bytes = super::source(p, INFO)?.bytes; + let i = info(&bytes).map_err(super::load::err)?; + Ok(json!({ + "format": if i.psb { "psb" } else { "psd" }, + "width": i.width, + "height": i.height, + "layers": i.layers, + "hiddenLayers": i.hidden, + "groups": i.groups, + "slices": i.slices, + })) +} diff --git a/crates/engine/src/cmd/fileio/psdread.rs b/crates/engine/src/cmd/fileio/psdread.rs index 28b44d6197..8571a19e4e 100644 --- a/crates/engine/src/cmd/fileio/psdread.rs +++ b/crates/engine/src/cmd/fileio/psdread.rs @@ -105,7 +105,7 @@ pub(super) struct Header<'a> { /// Colour mode data: an indexed image's palette (256 reds, then greens, then blues). palette: &'a [u8], /// The image resources. - resources: &'a [u8], + pub(super) resources: &'a [u8], /// The layer and mask information. pub(super) layers: &'a [u8], } @@ -172,25 +172,50 @@ pub fn resolution(bytes: &[u8]) -> Option<(f64, f64)> { /// The image resource blocks of `resources`, in file order: each one's id, name (the bytes of its /// Pascal string) and data. Stops at the first block that is cut short. With `signed`, only the /// blocks whose signature is `8BIM` are given. -fn resources(resources: &[u8], signed: bool) -> impl Iterator { +pub(super) fn resources(resources: &[u8], signed: bool) -> impl Iterator { let mut r = Reader::new(resources); - std::iter::from_fn(move || { - if r.rest().is_empty() { - return None; + std::iter::from_fn(move || if r.rest().is_empty() { None } else { block(&mut r).ok() }) + .filter(move |(ours, ..)| *ours || !signed) + .map(|(_, id, name, data)| (id, name, data)) +} + +/// The data of the first `8BIM` image resource block `id` of `resources`. `None` when there is +/// none before the blocks end or before a block that is cut short ahead of it. An error when +/// that block itself is cut short. +pub(super) fn resource(resources: &[u8], id: u16) -> Result, String> { + let mut r = Reader::new(resources); + while !r.rest().is_empty() { + match block(&mut r) { + Ok((true, i, _, data)) if i == id => return Ok(Some(data)), + Ok(_) => {} + Err(Some((true, i))) if i == id => return Err(TRUNCATED.into()), + Err(_) => return Ok(None), } - let ours = r.take(4).ok()? == b"8BIM"; - let id = r.u16().ok()?; + } + Ok(None) +} + +/// An image resource block: whether its signature is `8BIM`, its id, its name (the bytes of its +/// Pascal string) and its data. +type Block<'a> = (bool, u16, &'a [u8], &'a [u8]); + +/// The image resource block that `r` starts with. When it is cut short, the error gives whether +/// its signature is `8BIM` and its id, when those were read. +fn block<'a>(r: &mut Reader<'a>) -> Result, Option<(bool, u16)>> { + let ours = r.take(4).map_err(|_| None)? == b"8BIM"; + let id = r.u16().map_err(|_| None)?; + let mut rest = || -> Result<(&'a [u8], &'a [u8]), String> { // A Pascal string padded to an even size, length byte included. - let len = usize::from(r.u8().ok()?); - let name = r.take(len).ok()?; - r.take((len + 1) % 2).ok()?; - let size = usize::try_from(r.u32().ok()?).ok()?; - let data = r.take(size).ok()?; - r.take(size % 2).ok()?; - Some((ours, id, name, data)) - }) - .filter(move |(ours, ..)| *ours || !signed) - .map(|(_, id, name, data)| (id, name, data)) + let len = usize::from(r.u8()?); + let name = r.take(len)?; + r.take((len + 1) % 2)?; + let size = usize::try_from(r.u32()?).map_err(|_| TRUNCATED.to_string())?; + let data = r.take(size)?; + r.take(size % 2)?; + Ok((name, data)) + }; + let (name, data) = rest().map_err(|_| Some((ours, id)))?; + Ok((ours, id, name, data)) } /// The resource naming the document's clipping path. diff --git a/crates/engine/src/cmd/fileio/psdslices.rs b/crates/engine/src/cmd/fileio/psdslices.rs new file mode 100644 index 0000000000..cf5506ff3b --- /dev/null +++ b/crates/engine/src/cmd/fileio/psdslices.rs @@ -0,0 +1,446 @@ +//! The slices a Photoshop document (PSD or PSB) stores, for `document.open` and `file.place` +//! with `importSlices`: image resource 1050, read from the "Slices resource format" of Adobe's +//! public Photoshop File Formats Specification +//! (). Version 6 stores the slices +//! as records; versions 7 and 8 store them in a descriptor. The descriptor's keys, and the meaning +//! of the origin, type and background values, are read as the MIT-licensed ag-psd reads them +//! (, `src/imageResources.ts` and `src/descriptor.ts`), +//! which agrees with psd.rb (, +//! `lib/psd/resources/slices.rb`) on the keys both read. +//! +//! A slice the file marks as generated automatically is left out: the document lays out its own +//! auto slices around the others. A slice that follows a layer comes in as a user slice over the +//! rectangle the file stores for it. Each slice keeps its name, its type (Image or No Image), its +//! link, target, message, alternative text, cell text and background color; text alignment isn't +//! read. The file is untrusted: every read is checked, and the slice count, the strings and the +//! descriptor's nesting and item count are capped. + +use vectorcraft_doc::{SliceKind, SliceOptions}; +use vectorcraft_geom::Rect; + +use super::psdread::{Reader, TRUNCATED, header, resource}; + +/// The image resource that holds the slices. +const SLICES: u16 = 1050; + +/// The most slices one file brings in. +const MAX_SLICES: usize = 10_000; + +/// The deepest descriptor objects and lists nest. +const MAX_DEPTH: usize = 16; + +/// The most values the descriptors of one slices resource hold together, nested ones included. +const MAX_VALUES: usize = 200_000; + +/// The error of descriptors that hold more than [`MAX_VALUES`]. +const TOO_MANY_VALUES: &str = "the slices' descriptor holds too many values"; + +/// One slice as the file stores it. +#[derive(Clone, Debug, PartialEq)] +struct PsdSlice { + /// Left, top, right and bottom, in the canvas's pixels. + rect: [i64; 4], + options: SliceOptions, +} + +/// The slices a file stores, those generated automatically left out, and its canvas. +struct Stored { + slices: Vec, + /// The canvas's width and height, in pixels. + size: (u32, u32), +} + +/// The slices PSD or PSB file `bytes` stores. `None` when it stores none (no `8BIM` resource 1050 +/// before the image resources end, or before a block that is cut short ahead of it). An error when +/// the file isn't a PSD or PSB file, resource 1050 is cut short, or its slices can't be read. +fn read(bytes: &[u8]) -> Result, String> { + let mut r = Reader::new(bytes); + let h = header(&mut r)?; + let Some(data) = resource(h.resources, SLICES)? else { return Ok(None) }; + Ok(Some(Stored { slices: decode(data)?, size: (h.width, h.height) })) +} + +/// The slices of resource 1050's `data`. +fn decode(data: &[u8]) -> Result, String> { + let mut r = Reader::new(data); + // The values every descriptor of the resource may hold together. + let mut budget = MAX_VALUES; + match r.u32()? { + 6 => version_6(&mut r, &mut budget), + 7 | 8 => { + if r.u32()? != 16 { + return Err("the slices' descriptor has a version other than 16".into()); + } + let d = descriptor(&mut r, 0, &mut budget)?; + from_descriptor(&d) + } + v => Err(format!("the slices are stored in version {v}, which isn't read")), + } +} + +/// Version 6: the bounds of all the slices, the group's name, the count, then each slice's record. +/// The descriptors that follow the records spend one `budget` of values between them. +fn version_6(r: &mut Reader<'_>, budget: &mut usize) -> Result, String> { + r.take(16)?; + unicode(r)?; + let count = r.u32()? as usize; + if count > MAX_SLICES { + return Err(format!("the file has {count} slices, more than the {MAX_SLICES} read")); + } + let one_after_another = records_one_after_another(Reader::new(r.rest()), count, *budget); + let mut out = vec![]; + for i in 0..count { + // The ID and group ID. + r.take(8)?; + let origin = r.u32()?; + // A slice that follows a layer gives the layer's ID. + if origin == 1 { + r.take(4)?; + } + let name = unicode(r)?; + let kind = if r.u32()? == 0 { SliceKind::NoImage } else { SliceKind::Image }; + let mut rect = [0i64; 4]; + for v in &mut rect { + *v = i64::from(r.u32()? as i32); + } + let (url, target, message, alt) = (unicode(r)?, unicode(r)?, unicode(r)?, unicode(r)?); + let html = r.u8()? != 0; + let cell = unicode(r)?; + // The horizontal and vertical alignment. + r.take(8)?; + let [a, red, green, blue] = r.array::<4>()?; + let background = if a == 0 && red == 0 && green == 0 && blue == 0 { + String::new() + } else if a == 0 { + "matte".into() + } else { + format!("#{red:02x}{green:02x}{blue:02x}") + }; + // Photoshop 7 and later may follow a record with a descriptor (version 16); a record that + // doesn't start one is the next slice. When the records follow one another, only the + // last one may be followed by a descriptor. A descriptor read that uses up the budget is + // an error. + if (!one_after_another || i + 1 == count) && r.rest().starts_with(&16u32.to_be_bytes()) { + let mut ahead = Reader::new(r.rest()); + ahead.u32()?; + match descriptor(&mut ahead, 0, budget) { + Ok(_) => { + let used = r.rest().len() - ahead.rest().len(); + r.take(used)?; + } + Err(e) if e == TOO_MANY_VALUES => return Err(e), + Err(_) => {} + } + } + // Origin 0 is a slice generated automatically. + if origin != 0 { + let options = SliceOptions { kind, name, url, target, message, alt, text: cell_text(cell, html), background, ..Default::default() }; + out.push(PsdSlice { rect, options: for_kind(options) }); + } + } + Ok(out) +} + +/// Whether `r` holds `count` version 6 records one after another, followed by nothing or by one +/// descriptor (version 16) that reads within `budget`, as ag-psd writes them. A record whose ID is +/// 16 then isn't taken for a descriptor. Otherwise each record may be followed by a descriptor. +fn records_one_after_another(mut r: Reader<'_>, count: usize, mut budget: usize) -> bool { + if !(0..count).all(|_| skip_record(&mut r).is_ok()) { + return false; + } + r.rest().is_empty() || (r.rest().starts_with(&16u32.to_be_bytes()) && r.u32().is_ok() && descriptor(&mut r, 0, &mut budget).is_ok()) +} + +/// Reads past the version 6 record `r` starts with, in the layout [`version_6`] reads. Its strings +/// are checked and read past without being decoded. +fn skip_record(r: &mut Reader<'_>) -> Result<(), String> { + // The ID and group ID. + r.take(8)?; + if r.u32()? == 1 { + r.take(4)?; + } + units(r)?; + // The type and the rectangle. + r.take(20)?; + for _ in 0..4 { + units(r)?; + } + r.take(1)?; + units(r)?; + // The alignments and the background color. + r.take(12)?; + Ok(()) +} + +/// Versions 7 and 8: the descriptor's `slices` list, each slice an object. +fn from_descriptor(d: &[(String, Value)]) -> Result, String> { + let Some(Value::List(list)) = field(d, "slices") else { return Err("the slices' descriptor has no list of slices".into()) }; + if list.len() > MAX_SLICES { + return Err(format!("the file has {} slices, more than the {MAX_SLICES} read", list.len())); + } + let mut out = vec![]; + for s in list { + let Value::Object(s) = s else { return Err("the slices' descriptor lists something other than a slice".into()) }; + if matches!(field(s, "origin"), Some(Value::Enum(_, v)) if v == "autoGenerated") { + continue; + } + let Some(Value::Object(b)) = field(s, "bounds") else { return Err("a slice in the slices' descriptor has no bounds".into()) }; + let edge = |k: &str| number(field(b, k)).ok_or_else(|| "a slice's bounds in the slices' descriptor aren't numbers".to_string()); + let rect = [edge("Left")?, edge("Top ")?, edge("Rght")?, edge("Btom")?]; + let text = |k: &str| match field(s, k) { + Some(Value::Text(t)) => t.clone(), + _ => String::new(), + }; + let kind = if matches!(field(s, "Type"), Some(Value::Enum(_, v)) if v == "noImage") { SliceKind::NoImage } else { SliceKind::Image }; + let html = matches!(field(s, "cellTextIsHTML"), Some(Value::Bool(true))); + let background = match field(s, "bgColorType") { + Some(Value::Enum(_, v)) if v == "matte" => "matte".into(), + Some(Value::Enum(_, v)) if v == "Clr " => match field(s, "bgColor") { + Some(Value::Object(c)) => { + let channel = |k: &str| number(field(c, k)).map(|v| v.clamp(0, 255)); + match (channel("Rd "), channel("Grn "), channel("Bl ")) { + (Some(r), Some(g), Some(b)) => format!("#{r:02x}{g:02x}{b:02x}"), + _ => String::new(), + } + } + _ => String::new(), + }, + _ => String::new(), + }; + let options = SliceOptions { + kind, + name: text("Nm "), + url: text("url"), + target: text("null"), + message: text("Msge"), + alt: text("altTag"), + text: cell_text(text("cellText"), html), + background, + ..Default::default() + }; + out.push(PsdSlice { rect, options: for_kind(options) }); + } + Ok(out) +} + +/// `o` with only the options of its slice type: an Image slice's cell text isn't shown, and a No +/// Image slice has no link, target, message or alternative text. +fn for_kind(mut o: SliceOptions) -> SliceOptions { + if o.kind == SliceKind::Image { + o.text.clear(); + } else { + for s in [&mut o.url, &mut o.target, &mut o.message, &mut o.alt] { + s.clear(); + } + } + o +} + +/// A cell's text as the HTML a No Image slice shows: plain text has `&`, `<` and `>` escaped. +fn cell_text(text: String, html: bool) -> String { + if html { text } else { text.replace('&', "&").replace('<', "<").replace('>', ">") } +} + +/// The longest text one string, key or class ID holds (UTF-16 units or bytes). +const MAX_TEXT: usize = 65_536; + +/// An error unless `n`, the length a string or ID declares, is at most [`MAX_TEXT`]. +fn text_len(n: usize) -> Result { + if n > MAX_TEXT { + return Err(format!("a text in the slices has more than the {MAX_TEXT} characters read")); + } + Ok(n) +} + +/// A Unicode string: a count of UTF-16 units, then the units; trailing NULs dropped. +fn unicode(r: &mut Reader<'_>) -> Result { + let bytes = units(r)?; + let units: Vec = bytes.as_chunks::<2>().0.iter().map(|u| u16::from_be_bytes(*u)).collect(); + Ok(String::from_utf16_lossy(&units).trim_end_matches('\0').to_string()) +} + +/// A Unicode string's units, as bytes: a count of UTF-16 units, then the units. +fn units<'a>(r: &mut Reader<'a>) -> Result<&'a [u8], String> { + let n = text_len(r.u32()? as usize)?; + r.take(n.checked_mul(2).ok_or(TRUNCATED)?) +} + +/// A descriptor's value, as far as the slices need it. +#[derive(Clone, Debug, PartialEq)] +enum Value { + Long(i32), + Double(f64), + Bool(bool), + Text(String), + /// An enumeration's type and value. + Enum(String, String), + Object(Vec<(String, Value)>), + List(Vec), + /// A value of another type, read past. + Other, +} + +/// The value with key `key`. +fn field<'a>(d: &'a [(String, Value)], key: &str) -> Option<&'a Value> { + d.iter().find(|(k, _)| k == key).map(|(_, v)| v) +} + +/// A whole number: a long, or a finite double rounded. +fn number(v: Option<&Value>) -> Option { + match v? { + Value::Long(n) => Some(i64::from(*n)), + Value::Double(d) if d.is_finite() && d.abs() < 1e12 => Some(d.round() as i64), + _ => None, + } +} + +/// A key or class ID: a length, then that many characters, or four when the length is 0. +fn id(r: &mut Reader<'_>) -> Result { + let n = text_len(r.u32()? as usize)?; + let b = r.take(if n == 0 { 4 } else { n })?; + Ok(String::from_utf8_lossy(b).into_owned()) +} + +/// A class: its Unicode name, then its ID. +fn class(r: &mut Reader<'_>) -> Result<(), String> { + unicode(r)?; + id(r)?; + Ok(()) +} + +/// A descriptor: its class, the count of its items, then each item's key, type and value. +fn descriptor(r: &mut Reader<'_>, depth: usize, budget: &mut usize) -> Result, String> { + if depth > MAX_DEPTH { + return Err("the slices' descriptor nests too deep".into()); + } + class(r)?; + let count = r.u32()? as usize; + let mut out = vec![]; + for _ in 0..count { + let key = id(r)?; + let kind = r.array::<4>()?; + out.push((key, value(r, &kind, depth, budget)?)); + } + Ok(out) +} + +/// A value of type `kind`. +fn value(r: &mut Reader<'_>, kind: &[u8; 4], depth: usize, budget: &mut usize) -> Result { + *budget = budget.checked_sub(1).ok_or(TOO_MANY_VALUES)?; + Ok(match kind { + b"long" => Value::Long(r.u32()? as i32), + b"doub" => Value::Double(f64::from_be_bytes(r.array()?)), + b"UntF" => { + r.take(4)?; + Value::Double(f64::from_be_bytes(r.array()?)) + } + b"UnFl" => { + r.take(4)?; + Value::Double(f64::from(f32::from_be_bytes(r.array()?))) + } + b"bool" => Value::Bool(r.u8()? != 0), + b"TEXT" => Value::Text(unicode(r)?), + b"enum" => Value::Enum(id(r)?, id(r)?), + b"Objc" | b"GlbO" => Value::Object(descriptor(r, depth + 1, budget)?), + b"VlLs" => { + if depth >= MAX_DEPTH { + return Err("the slices' descriptor nests too deep".into()); + } + let count = r.u32()? as usize; + let mut items = vec![]; + for _ in 0..count { + let kind = r.array::<4>()?; + items.push(value(r, &kind, depth + 1, budget)?); + } + Value::List(items) + } + b"comp" => { + r.take(8)?; + Value::Other + } + b"type" | b"GlbC" => { + class(r)?; + Value::Other + } + b"tdta" | b"alis" => { + let n = r.u32()? as usize; + r.take(n)?; + Value::Other + } + b"obj " => { + let count = r.u32()? as usize; + for _ in 0..count { + *budget = budget.checked_sub(1).ok_or(TOO_MANY_VALUES)?; + match &r.array::<4>()? { + b"prop" => { + class(r)?; + id(r)?; + } + b"Clss" => class(r)?, + b"Enmr" => { + class(r)?; + id(r)?; + id(r)?; + } + b"rele" => { + class(r)?; + r.take(4)?; + } + b"Idnt" | b"indx" => { + r.take(4)?; + } + b"name" => { + class(r)?; + unicode(r)?; + } + k => return Err(format!("the slices' descriptor has a reference of an unknown kind ({})", String::from_utf8_lossy(k))), + } + } + Value::Other + } + k => return Err(format!("the slices' descriptor has a value of an unknown type ({})", String::from_utf8_lossy(k))), + }) +} + +/// The slices of PSD or PSB file `bytes` laid over `canvas`, the box its canvas takes (points), +/// each clipped to the canvas, with warnings: for slices that lie wholly outside it or have no +/// size, and for slices that can't be read (the file comes in without them). Empty, without a +/// warning, when the file stores no slices. +pub(crate) fn over(bytes: &[u8], canvas: Rect) -> (Vec<(Rect, SliceOptions)>, Vec) { + match read(bytes) { + Ok(None) => (vec![], vec![]), + Ok(Some(s)) => laid_over(&s.slices, s.size, canvas), + Err(e) => (vec![], vec![format!("the slices can't be read ({e}) and were left out")]), + } +} + +/// `slices` of a canvas of `size` pixels laid over `canvas` (points). +fn laid_over(slices: &[PsdSlice], (w, h): (u32, u32), canvas: Rect) -> (Vec<(Rect, SliceOptions)>, Vec) { + let (sx, sy) = (canvas.width() / f64::from(w.max(1)), canvas.height() / f64::from(h.max(1))); + let mut out = vec![]; + for s in slices { + let [l, t, r, b] = s.rect; + let (l, r) = (l.clamp(0, i64::from(w)), r.clamp(0, i64::from(w))); + let (t, b) = (t.clamp(0, i64::from(h)), b.clamp(0, i64::from(h))); + if l < r && t < b { + let x = |v: i64| canvas.x0 + v as f64 * sx; + let y = |v: i64| canvas.y0 + v as f64 * sy; + out.push((Rect::new(x(l), y(t), x(r), y(b)), s.options.clone())); + } + } + let warnings = match slices.len() - out.len() { + 0 => vec![], + 1 => vec!["1 slice lies outside the canvas or has no size and was left out".to_string()], + n => vec![format!("{n} slices lie outside the canvas or have no size and were left out")], + }; + (out, warnings) +} + +/// How many slices of PSD or PSB file `bytes` come in (`document.psdInfo`): 0 when it stores none +/// or they can't be read. +pub(crate) fn count(bytes: &[u8]) -> usize { + match read(bytes) { + Ok(Some(Stored { slices, size: (w, h) })) => laid_over(&slices, (w, h), Rect::new(0.0, 0.0, f64::from(w), f64::from(h))).0.len(), + _ => 0, + } +} diff --git a/crates/engine/src/cmd/fileio/tests_pdfoutput.rs b/crates/engine/src/cmd/fileio/tests_pdfoutput.rs index 04726fee46..c98a121ded 100644 --- a/crates/engine/src/cmd/fileio/tests_pdfoutput.rs +++ b/crates/engine/src/cmd/fileio/tests_pdfoutput.rs @@ -38,3 +38,19 @@ fn export_pdf_converts_colours_writes_the_output_intent_and_real_text() { let bad = s.execute("document.exportPdf", &json!({"output": {"conversion": "destination", "destination": "Missing"}})); assert!(matches!(bad, Err(crate::EngineError::BadParams { .. })), "{bad:?}"); } + +/// Over a saved preset whose Profiles setting is `none`, `"default"` leaves the setting unset, +/// while `null` keeps the preset's value; an unknown value is a bad parameter. +#[test] +fn profiles_default_unsets_a_presets_profiles_setting() { + use vectorcraft_pdf::{PdfPreset, PdfSettings, ProfileInclusion}; + let mut settings = PdfSettings::default(); + settings.output.profiles = Some(ProfileInclusion::None); + let saved = [PdfPreset { name: "No profiles".into(), description: String::new(), settings }]; + let resolve = |output: Value| pdf::resolve("document.exportPdf", &json!({"preset": "No profiles", "output": output}), &saved); + assert_eq!(resolve(json!({"profiles": "default"})).unwrap().output.profiles, None); + assert_eq!(resolve(json!({"profiles": null})).unwrap().output.profiles, Some(ProfileInclusion::None)); + assert_eq!(resolve(json!({"profiles": "all"})).unwrap().output.profiles, Some(ProfileInclusion::All)); + let bad = resolve(json!({"profiles": "sometimes"})); + assert!(matches!(bad, Err(crate::EngineError::BadParams { .. })), "{bad:?}"); +} diff --git a/crates/engine/src/cmd/fileio/tests_psdlayers.rs b/crates/engine/src/cmd/fileio/tests_psdlayers.rs index 31f670d7ff..298f3d22dc 100644 --- a/crates/engine/src/cmd/fileio/tests_psdlayers.rs +++ b/crates/engine/src/cmd/fileio/tests_psdlayers.rs @@ -1,7 +1,8 @@ //! Opening PSD and PSB files with their layers as layers (`document.open`'s `layers` and //! `hiddenLayers`): names, visibility, opacity, blend modes, groups, layer masks, clipped layers //! and blend modes VectorCraft lacks merged, 16-bit and PSB files, VectorCraft's own PSD export -//! read back, and damaged files read without a panic. +//! read back, and damaged files read without a panic. Placing them with their layers as objects +//! (`file.place`'s `layers` and `hiddenLayers`), and `document.psdInfo`. use serde_json::{Value, json}; use vectorcraft_color::BlendMode; @@ -967,10 +968,12 @@ fn damaged_layers_never_panic() { let mut f = good.clone(); f[i] = v; let _ = psdlayers::import(&f, true, 1 << 30, cms); + let _ = psdlayers::info(&f); } } for n in 0..good.len() { let _ = psdlayers::import(&good[..n], true, 1 << 30, cms); + let _ = psdlayers::info(&good[..n]); } // A layer past the memory allowed is refused, not read. assert!(psdlayers::import(&good, true, 64, cms).unwrap_err().contains("too large")); @@ -1015,3 +1018,186 @@ fn merges_keep_pass_through_groups_blending_with_what_is_below() { assert!(px.iter().zip([75, 150, 38, 255]).all(|(&a, b)| a.abs_diff(b) <= 1), "{px:?}"); } } + +/// `file.place` of `f` with `p` into a new 100 × 100 pt document, centred on (50, 50). +fn place(f: &[u8], p: Value) -> (Session, crate::cmd::Result) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let r = s.execute("file.place", &merge(json!({"name": "layers.psd", "dataBase64": vectorcraft_format::base64_encode(f), "at": [50, 50]}), p)); + (s, r) +} + +/// The one object `file.place` placed. +fn placed(s: &Session, r: &Value) -> Node { + let id = vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap()); + s.doc().unwrap().doc.node(id).unwrap().clone() +} + +#[test] +fn placing_with_layers_embeds_the_layers_as_one_group() { + let f = file(8, 8, &stack(), 8, false, false); + let (mut s, r) = place(&f, json!({"layers": true})); + let r = r.unwrap(); + assert_eq!((&r["format"], &r["linked"], &r["warnings"]), (&json!("psd"), &json!(false), &json!([HIDDEN_1])), "{r}"); + let g = placed(&s, &r); + assert!(matches!(g.kind, NodeKind::Group { clip: false, .. }), "one group, unclipped: its layers lie on the canvas"); + assert_eq!(name(&g), "layers.psd"); + let kids = g.children().unwrap(); + assert_eq!(kids.iter().map(|c| name(c)).collect::>(), ["Bottom", "Folder", "Screens", "Faded"], "bottom first"); + // A layer is its image, where the merged image would put it: the 8 pt canvas centred on (50, 50). + let ((x, y), px) = pixels_of(&s, &kids[0]); + assert_eq!(((x, y), px.dimensions(), px.get_pixel(3, 3).0), ((46.0, 46.0), (8, 8), [255, 0, 0, 255])); + // A group is a group of its layers; a pass-through group isn't isolated, another mode's is. + let folder = &kids[1]; + assert!(matches!(folder.kind, NodeKind::Group { .. }) && !folder.isolate && folder.blend == BlendMode::Normal); + let inner = folder.children().unwrap(); + assert_eq!(inner.iter().map(|c| name(c)).collect::>(), ["Inner A"], "the hidden layer is left out"); + assert!(matches!(inner[0].kind, NodeKind::Image(_)) && inner[0].blend == BlendMode::Multiply && (inner[0].opacity - 128.0 / 255.0).abs() < 1e-6); + let screens = &kids[2]; + assert!(screens.isolate && screens.blend == BlendMode::Screen); + let ((x, y), px) = pixels_of(&s, &screens.children().unwrap()[0]); + assert_eq!(((x, y), px.get_pixel(0, 0).0), ((48.0, 48.0), [10, 20, 30, 128])); + assert!((kids[3].opacity - 102.0 / 255.0).abs() < 1e-6, "fill opacity: {}", kids[3].opacity); + // One undo step. + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.layers.iter().all(|l| l.children().is_none_or(Vec::is_empty))); + // Hidden layers come in hidden when asked for. + let (s, r) = place(&f, json!({"layers": true, "hiddenLayers": true})); + let r = r.unwrap(); + assert_eq!(r["warnings"], json!([]), "{r}"); + let g = placed(&s, &r); + let inner: Vec<(&str, bool)> = g.children().unwrap()[1].children().unwrap().iter().map(|c| (name(c), c.visible)).collect(); + assert_eq!(inner, [("Inner A", true), ("Inner B", false)]); + // Without `layers`, the merged image, in the same box. + let (s, r) = place(&f, json!({})); + let r = r.unwrap(); + let flat = placed(&s, &r); + let ((x, y), px) = pixels_of(&s, &flat); + assert_eq!(((x, y), px.dimensions(), px.get_pixel(0, 0).0), ((46.0, 46.0), (8, 8), [128, 128, 128, 255]), "{r}"); +} + +#[test] +fn placed_layers_keep_their_masks_and_are_clipped_to_the_canvas() { + let mut masked = layer("Masked", [0, 0, 8, 8], [255, 255, 255, 255]); + masked.mask = Some(([2, 2, 4, 4], 0, 0, vec![255, 128, 0, 255])); + let (s, r) = place(&file(8, 8, &[masked], 8, false, false), json!({"layers": true})); + let g = placed(&s, &r.unwrap()); + let kids = g.children().unwrap(); + assert!(matches!(kids[0].kind, NodeKind::Image(_)), "the layer is its image"); + let m = kids[0].extras().mask.as_deref().expect("the layer mask as the image's opacity mask"); + let ((x, y), px) = pixels_of(&s, &m.art); + assert_eq!(((x, y), px.dimensions(), m.clip), ((48.0, 48.0), (2, 2), true), "the mask moves with its layer"); + // A layer that reaches past the canvas: the group is clipped to the canvas, as the merged + // image shows only the canvas. + let over = layer("Over", [-2, -2, 6, 6], [0, 255, 0, 255]); + let (s, r) = place(&file(8, 8, &[layer("Bottom", [0, 0, 8, 8], [255, 0, 0, 255]), over], 8, false, false), json!({"layers": true})); + let r = r.unwrap(); + let g = placed(&s, &r); + assert!(matches!(g.kind, NodeKind::Group { clip: true, .. }), "{r}"); + let kids = g.children().unwrap(); + let b = kids[0].geometric_bounds_with(&s.doc().unwrap().doc.symbol_boxes()).unwrap(); + assert!(matches!(kids[0].kind, NodeKind::Path { clipping: true, .. })); + assert_eq!((b.x0, b.y0, b.x1, b.y1), (46.0, 46.0, 54.0, 54.0), "the clipping path is the canvas"); + assert_eq!(kids[1..].iter().map(|c| name(c)).collect::>(), ["Bottom", "Over"]); + assert_eq!(pixels_of(&s, &kids[2]).0, (44.0, 44.0)); + // A hidden layer that reaches past the canvas clips the group too, so showing it later draws + // only the canvas. Left out, it doesn't. + let mut hidden = layer("Hidden", [-2, -2, 6, 6], [0, 255, 0, 255]); + hidden.hidden = true; + let f = file(8, 8, &[layer("Bottom", [0, 0, 8, 8], [255, 0, 0, 255]), hidden], 8, false, false); + let (s, r) = place(&f, json!({"layers": true, "hiddenLayers": true})); + let r = r.unwrap(); + let g = placed(&s, &r); + assert!(matches!(g.kind, NodeKind::Group { clip: true, .. }), "{r}"); + assert_eq!(g.children().unwrap()[1..].iter().map(|c| (name(c), c.visible)).collect::>(), [("Bottom", true), ("Hidden", false)]); + let (s, r) = place(&f, json!({"layers": true})); + assert!(matches!(placed(&s, &r.unwrap()).kind, NodeKind::Group { clip: false, .. })); +} + +#[test] +fn placing_with_layers_never_links_and_refuses_values_it_cant_use() { + let f = file(8, 8, &stack(), 8, false, false); + let dir = std::env::temp_dir().join(format!("vc-psd-place-layers-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("layers.psd"); + std::fs::write(&path, &f).unwrap(); + let from_path = |p: Value| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let r = s.execute("file.place", &merge(json!({"path": path.to_str().unwrap()}), p)); + (s, r) + }; + // From a path, `layers` embeds: `link` is then false unless given, and `link: true` is refused. + let (s, r) = from_path(json!({"layers": true})); + let r = r.unwrap(); + assert_eq!(r["linked"], json!(false), "{r}"); + assert!(matches!(placed(&s, &r).kind, NodeKind::Group { .. })); + let (s, r) = from_path(json!({"layers": true, "link": true})); + assert!(r.unwrap_err().to_string().contains("a linked PSD file is placed as its flat image")); + assert!(s.doc().unwrap().doc.layers.iter().all(|l| l.children().is_none_or(Vec::is_empty)), "nothing is placed"); + // Without `layers` the file is linked as before. + let (s, r) = from_path(json!({})); + let r = r.unwrap(); + assert_eq!(r["linked"], json!(true), "{r}"); + assert!(matches!(placed(&s, &r).kind, NodeKind::Image(_))); + // A file without layers is embedded as its merged image, without a warning. + let flat = { + let mut f = file(2, 2, &[layer("x", [0, 0, 2, 2], [9, 9, 9, 255])], 8, false, false); + let at = 26 + 8; + let len = u32::from_be_bytes(f[at..at + 4].try_into().unwrap()) as usize; + f.splice(at..at + 4 + len, 0u32.to_be_bytes()); + f + }; + std::fs::write(&path, &flat).unwrap(); + let (s, r) = from_path(json!({"layers": true})); + let r = r.unwrap(); + assert_eq!((&r["linked"], &r["warnings"]), (&json!(false), &json!([])), "{r}"); + assert!(matches!(placed(&s, &r).kind, NodeKind::Image(_))); + // Layers that are all left out: the merged image, with the importer's warnings. + let mut gone = layer("Gone", [0, 0, 2, 2], [9, 9, 9, 255]); + gone.hidden = true; + let (s, r) = place(&file(2, 2, &[gone], 8, false, false), json!({"layers": true})); + let r = r.unwrap(); + assert_eq!((&r["linked"], r["warnings"].as_array().map(Vec::len)), (&json!(false), Some(1)), "{r}"); + assert!(matches!(placed(&s, &r).kind, NodeKind::Image(_))); + // Layers that can't be read: the merged image, with a warning. + let mut cut = file(4, 4, &[layer("x", [0, 0, 4, 4], [9, 9, 9, 255])], 8, false, false); + let at = cut.windows(4).position(|w| w == [0, 0, 0, 18]).unwrap(); + cut[at..at + 4].copy_from_slice(&1000u32.to_be_bytes()); + let (s, r) = place(&cut, json!({"layers": true})); + let r = r.unwrap(); + assert!(r["warnings"][0].as_str().unwrap().starts_with("the layers can't be read"), "{r}"); + assert!(matches!(placed(&s, &r).kind, NodeKind::Image(_))); + // Values the command can't use are errors, and nothing is placed. + for (p, why) in [ + (json!({"hiddenLayers": true}), "hiddenLayers applies to a PSD file placed with layers: true"), + (json!({"layers": true, "link": true}), "a linked PSD file is placed as its flat image"), + (json!({"layers": "yes"}), "layers must be true or false"), + (json!({"layers": true, "hiddenLayers": 1}), "hiddenLayers must be true or false"), + ] { + let (s, r) = place(&f, p.clone()); + assert!(r.unwrap_err().to_string().contains(why), "{p}"); + assert!(s.doc().unwrap().doc.layers.iter().all(|l| l.children().is_none_or(Vec::is_empty)), "{p}"); + } + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let q = s.execute("file.place.queue", &json!({"paths": [path.to_str().unwrap()], "layers": "yes"})); + assert!(q.unwrap_err().to_string().contains("`layers` must be true or false")); + std::fs::remove_dir_all(&dir).ok(); +} + +#[test] +fn psd_info_counts_the_layers_without_opening_the_file() { + let mut s = Session::new(); + let info = |s: &mut Session, f: &[u8]| s.execute("document.psdInfo", &json!({"dataBase64": vectorcraft_format::base64_encode(f)})); + let r = info(&mut s, &file(8, 8, &stack(), 8, false, false)).unwrap(); + assert_eq!(r, json!({"format": "psd", "width": 8, "height": 8, "layers": 5, "hiddenLayers": 1, "groups": 2, "slices": 0})); + let r = info(&mut s, &file(4, 2, &[layer("x", [0, 0, 2, 2], [9, 9, 9, 255])], 16, true, true)).unwrap(); + assert_eq!((&r["format"], &r["width"], &r["height"], &r["layers"]), (&json!("psb"), &json!(4), &json!(2), &json!(1)), "{r}"); + // Layer records that can't be read count as no layers: the file opens as its merged image. + let mut cut = file(4, 4, &[layer("x", [0, 0, 4, 4], [9, 9, 9, 255])], 8, false, false); + let at = cut.windows(4).position(|w| w == [0, 0, 0, 18]).unwrap(); + cut[at..at + 4].copy_from_slice(&1000u32.to_be_bytes()); + assert_eq!(info(&mut s, &cut).unwrap()["layers"], json!(0)); + assert!(info(&mut s, b"not a psd").unwrap_err().to_string().contains("not a PSD file")); +} diff --git a/crates/engine/src/cmd/fileio/tests_psdslices.rs b/crates/engine/src/cmd/fileio/tests_psdslices.rs new file mode 100644 index 0000000000..2d8d0c951f --- /dev/null +++ b/crates/engine/src/cmd/fileio/tests_psdslices.rs @@ -0,0 +1,508 @@ +//! A PSD or PSB file's slices (image resource 1050) opened and placed as user slices +//! (`document.open`'s and `file.place`'s `importSlices`): version 6 records and version 7 and 8 +//! descriptors, built from the Photoshop File Formats Specification's "Slices resource format"; +//! their options, slices outside the canvas, damaged or unknown slice data, placing scaled and +//! moved in one undo step, linked files, and `document.psdInfo`'s count. + +use serde_json::{Value, json}; +use vectorcraft_doc::{SliceKind, SliceOptions}; +use vectorcraft_geom::Rect; + +use crate::Session; + +/// A Unicode string: a count of UTF-16 units, then the units. +fn ustr(s: &str) -> Vec { + let units: Vec = s.encode_utf16().collect(); + let mut b = (units.len() as u32).to_be_bytes().to_vec(); + b.extend(units.iter().flat_map(|u| u.to_be_bytes())); + b +} + +/// One version 6 slice record. +#[derive(Clone)] +struct S { + /// 0: generated automatically, 1: follows a layer, 2: made by the user. + origin: u32, + name: &'static str, + /// 0: No Image, 1: Image. + kind: u32, + /// Left, top, right, bottom (px). + rect: [i32; 4], + url: &'static str, + target: &'static str, + message: &'static str, + alt: &'static str, + html: bool, + cell: &'static str, + /// Alpha, red, green, blue. + argb: [u8; 4], +} + +fn user(name: &'static str, rect: [i32; 4]) -> S { + S { origin: 2, name, kind: 1, rect, url: "", target: "", message: "", alt: "", html: false, cell: "", argb: [0; 4] } +} + +/// Resource 1050 in version 6, each record followed by `trailing` (a Photoshop 7 descriptor, or +/// nothing). +fn v6(slices: &[S], trailing: &[u8]) -> Vec { + let mut b = 6u32.to_be_bytes().to_vec(); + b.extend([0u8; 16]); + b.extend(ustr("group")); + b.extend((slices.len() as u32).to_be_bytes()); + for (i, s) in slices.iter().enumerate() { + b.extend((i as u32 + 1).to_be_bytes()); + b.extend(0u32.to_be_bytes()); + b.extend(s.origin.to_be_bytes()); + if s.origin == 1 { + b.extend(7u32.to_be_bytes()); + } + b.extend(ustr(s.name)); + b.extend(s.kind.to_be_bytes()); + for v in s.rect { + b.extend(v.to_be_bytes()); + } + for t in [s.url, s.target, s.message, s.alt] { + b.extend(ustr(t)); + } + b.push(u8::from(s.html)); + b.extend(ustr(s.cell)); + b.extend([0u8; 8]); + b.extend(s.argb); + b.extend(trailing); + } + b +} + +/// A descriptor value. +enum D { + Long(i32), + Doub(f64), + Bool(bool), + Text(&'static str), + Enum(&'static str, &'static str), + Obj(Vec<(&'static str, D)>), + List(Vec), +} + +/// A key or class ID: a four-character one with length 0, else its length and characters. +fn key(k: &str) -> Vec { + let mut b = if k.len() == 4 { 0u32 } else { k.len() as u32 }.to_be_bytes().to_vec(); + b.extend(k.as_bytes()); + b +} + +/// A descriptor: an empty class name, the class ID, the count, then each item. +fn descriptor(items: &[(&str, D)]) -> Vec { + let mut b = ustr(""); + b.extend(key("null")); + b.extend((items.len() as u32).to_be_bytes()); + for (k, v) in items { + b.extend(key(k)); + b.extend(value(v)); + } + b +} + +/// A value's type, then the value. +fn value(v: &D) -> Vec { + let mut b = vec![]; + match v { + D::Long(n) => { + b.extend(b"long"); + b.extend(n.to_be_bytes()); + } + D::Doub(d) => { + b.extend(b"doub"); + b.extend(d.to_be_bytes()); + } + D::Bool(on) => { + b.extend(b"bool"); + b.push(u8::from(*on)); + } + D::Text(t) => { + b.extend(b"TEXT"); + b.extend(ustr(t)); + } + D::Enum(t, e) => { + b.extend(b"enum"); + b.extend(key(t)); + b.extend(key(e)); + } + D::Obj(items) => { + b.extend(b"Objc"); + b.extend(descriptor(items)); + } + D::List(items) => { + b.extend(b"VlLs"); + b.extend((items.len() as u32).to_be_bytes()); + for i in items { + b.extend(value(i)); + } + } + } + b +} + +/// A bounds object: top, left, bottom and right. +fn bounds(l: i32, t: i32, r: i32, b: i32) -> D { + D::Obj(vec![("Top ", D::Long(t)), ("Left", D::Long(l)), ("Btom", D::Long(b)), ("Rght", D::Long(r))]) +} + +/// Resource 1050 in `version` 7 or 8 holding `slices`. +fn v7(version: u32, slices: Vec) -> Vec { + let mut b = version.to_be_bytes().to_vec(); + b.extend(16u32.to_be_bytes()); + b.extend(descriptor(&[("bounds", bounds(0, 0, 20, 20)), ("baseName", D::Text("poster")), ("slices", D::List(slices))])); + b +} + +/// A 20 × 20 px PSD file written by `document.export`, with its layers (two) or flat. +fn psd(layers: bool) -> Vec { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 20, "height": 20})).unwrap(); + s.execute("paint.setFill", &json!({ "color": "#ff0000" })).unwrap(); + s.execute("shape.rectangle", &json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap(); + s.execute("layer.new", &json!({ "name": "Top" })).unwrap(); + s.execute("shape.rectangle", &json!({"x": 8, "y": 8, "width": 10, "height": 10})).unwrap(); + let r = s.execute("document.export", &json!({"format": "psd", "layers": layers})).unwrap(); + vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap() +} + +/// `psd` with image resource `id` holding `data` added to its image resources. +fn with_resource(psd: &[u8], id: u16, data: &[u8]) -> Vec { + let u32_at = |at: usize| u32::from_be_bytes(psd[at..at + 4].try_into().unwrap()) as usize; + let colors = 26 + 4 + u32_at(26); + let len = u32_at(colors); + let mut block = b"8BIM".to_vec(); + block.extend(id.to_be_bytes()); + block.extend([0, 0]); + block.extend((data.len() as u32).to_be_bytes()); + block.extend(data); + block.resize(block.len().next_multiple_of(2), 0); + let mut out = psd[..colors].to_vec(); + out.extend(((len + block.len()) as u32).to_be_bytes()); + out.extend(&psd[colors + 4..colors + 4 + len]); + out.extend(block); + out.extend(&psd[colors + 4 + len..]); + out +} + +fn b64(f: &[u8]) -> String { + vectorcraft_format::base64_encode(f) +} + +fn open(f: &[u8], extra: Value) -> (Session, Value) { + let mut s = Session::new(); + let mut p = json!({"name": "poster.psd", "dataBase64": b64(f)}); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + let r = s.execute("document.open", &p).unwrap(); + (s, r) +} + +/// The document's user slices: rectangle and options. +fn slices(s: &Session) -> Vec<(Rect, SliceOptions)> { + s.doc().unwrap().doc.slices.iter().map(|x| (x.rect, x.options.clone())).collect() +} + +fn warnings(r: &Value) -> Vec { + r["warnings"].as_array().map(|a| a.iter().filter_map(|w| w.as_str().map(str::to_string)).collect()).unwrap_or_default() +} + +#[test] +fn version_6_slices_open_as_user_slices_with_their_options() { + let linked = S { origin: 1, url: "https://example.com/", target: "_blank", message: "Go", alt: "Logo", ..user("logo", [2, 4, 10, 8]) }; + let plain = S { kind: 0, cell: "a < b & c", argb: [0, 0, 0, 0], ..user("note", [10, 10, 20, 20]) }; + let html = S { kind: 0, html: true, cell: "Hi", argb: [255, 0x12, 0x34, 0x56], ..user("", [0, 12, 6, 18]) }; + let matte = S { argb: [0, 1, 2, 3], cell: "ignored", ..user("matte", [12, 0, 18, 6]) }; + let auto = S { origin: 0, ..user("auto", [0, 0, 20, 2]) }; + let data = v6(&[linked, plain, html, matte, auto], &[]); + for layers in [true, false] { + let f = with_resource(&psd(layers), 1050, &data); + // Either conversion brings the slices in; the automatic one stays out. + for p in [json!({}), json!({"layers": false})] { + let (s, r) = open(&f, p); + assert!(warnings(&r).is_empty(), "{r}"); + let got = slices(&s); + assert_eq!(got.len(), 4, "{got:?}"); + assert_eq!(got[0].0, Rect::new(2.0, 4.0, 10.0, 8.0)); + assert_eq!( + got[0].1, + SliceOptions { + kind: SliceKind::Image, + name: "logo".into(), + url: "https://example.com/".into(), + target: "_blank".into(), + message: "Go".into(), + alt: "Logo".into(), + ..Default::default() + } + ); + // Plain cell text is escaped as the HTML a No Image cell shows; HTML stays as it is. + assert_eq!((got[1].1.kind, got[1].1.text.as_str(), got[1].1.background.as_str()), (SliceKind::NoImage, "a < b & c", "")); + assert_eq!((got[2].1.text.as_str(), got[2].1.background.as_str(), got[2].1.name.as_str()), ("Hi", "#123456", "")); + // An Image slice's cell text isn't kept; a background with no alpha is the matte. + assert_eq!((got[3].1.text.as_str(), got[3].1.background.as_str()), ("", "matte")); + // Web output lays them out with auto slices around them. + let layout = s.doc().unwrap().doc.slice_layout(); + assert_eq!(layout.iter().filter(|a| a.source == vectorcraft_doc::SliceSource::User).count(), 4); + assert!(layout.iter().any(|a| a.source == vectorcraft_doc::SliceSource::Auto)); + } + } +} + +#[test] +fn photoshop_7_descriptors_after_version_6_records_are_read_past() { + let trailing = [16u32.to_be_bytes().to_vec(), descriptor(&[("topOutset", D::Long(0))])].concat(); + let f = with_resource(&psd(false), 1050, &v6(&[user("a", [0, 0, 5, 5]), user("b", [5, 5, 10, 10])], &trailing)); + let (s, r) = open(&f, json!({})); + assert!(warnings(&r).is_empty(), "{r}"); + let names: Vec = slices(&s).into_iter().map(|(_, o)| o.name).collect(); + assert_eq!(names, ["a", "b"]); +} + +#[test] +fn a_version_6_record_whose_id_is_16_is_a_slice_not_a_descriptor() { + // The 16th record has ID 16, group ID 0, origin 2, no name and the Image type: its first 18 + // bytes also read as a descriptor of version 16 with no items. + let records: Vec = (1..=17).map(|id| if id == 16 { user("", [1, 1, 4, 4]) } else { user("a", [0, 0, 5, 5]) }).collect(); + let descriptor_after = [16u32.to_be_bytes().to_vec(), descriptor(&[("topOutset", D::Long(0))])].concat(); + for trailing in [vec![], descriptor_after] { + let (s, r) = open(&with_resource(&psd(false), 1050, &v6(&records, &trailing)), json!({})); + assert!(warnings(&r).is_empty(), "{r}"); + let got = slices(&s); + assert_eq!(got.len(), 17, "{got:?}"); + assert_eq!((got[15].0, got[15].1.name.as_str()), (Rect::new(1.0, 1.0, 4.0, 4.0), "")); + assert_eq!(got[16].1.name, "a"); + } + // A descriptor after each record whose class ID is four zero bytes, with no items, followed by + // records with no strings: the records don't also read one after another. + let empty = [ustr(""), 0u32.to_be_bytes().to_vec(), vec![0; 4], 0u32.to_be_bytes().to_vec()].concat(); + let trailing = [16u32.to_be_bytes().to_vec(), empty].concat(); + for rect in [[0, 0, 0, 0], [0, 0, 5, 5]] { + let (s, r) = open(&with_resource(&psd(false), 1050, &v6(&[user("", rect), user("", rect), user("", rect)], &trailing)), json!({})); + let w = warnings(&r); + assert!(!w.iter().any(|w| w.starts_with("the slices can't be read")), "{w:?}"); + assert_eq!(slices(&s).len(), if rect[2] > 0 { 3 } else { 0 }, "{w:?}"); + } +} + +#[test] +fn version_6_descriptors_share_one_budget_of_values() { + // Each record's descriptor holds 2,501 values, well under the 200,000 one descriptor may hold; + // 100 of them hold 250,100 together. + let list = D::List((0..2_500).map(D::Long).collect()); + let trailing = [16u32.to_be_bytes().to_vec(), descriptor(&[("many", list)])].concat(); + let records: Vec = (0..100).map(|_| user("a", [0, 0, 5, 5])).collect(); + // Alone, one such descriptor is read past. + let (s, r) = open(&with_resource(&psd(false), 1050, &v6(&records[..1], &trailing)), json!({})); + assert!(warnings(&r).is_empty(), "{r}"); + assert_eq!(slices(&s).len(), 1); + // Together they are refused, and the file opens without slices. + let (s, r) = open(&with_resource(&psd(false), 1050, &v6(&records, &trailing)), json!({})); + let w = warnings(&r); + assert!(w.iter().any(|w| w.starts_with("the slices can't be read (") && w.contains("too many values")), "{w:?}"); + assert!(slices(&s).is_empty()); +} + +#[test] +fn version_7_and_8_descriptors_open_as_user_slices() { + let slice = |origin: &'static str, kind: &'static str, l: i32, t: i32, r: i32, b: i32| { + D::Obj(vec![ + ("sliceID", D::Long(1)), + ("groupID", D::Long(0)), + ("origin", D::Enum("ESliceOrigin", origin)), + ("Type", D::Enum("ESliceType", kind)), + ("bounds", bounds(l, t, r, b)), + ("Nm ", D::Text("cell")), + ("url", D::Text("https://example.com/")), + ("null", D::Text("_top")), + ("Msge", D::Text("msg")), + ("altTag", D::Text("alt")), + ("cellTextIsHTML", D::Bool(false)), + ("cellText", D::Text("x>y")), + ("bgColorType", D::Enum("ESliceBGColorType", "Clr ")), + ("bgColor", D::Obj(vec![("Rd ", D::Doub(255.0)), ("Grn ", D::Doub(128.0)), ("Bl ", D::Long(0))])), + ]) + }; + for version in [7, 8] { + let data = v7( + version, + vec![slice("userGenerated", "Img ", 1, 2, 9, 10), slice("autoGenerated", "Img ", 0, 0, 20, 1), slice("layer", "noImage", 10, 10, 15, 15)], + ); + let (s, r) = open(&with_resource(&psd(true), 1050, &data), json!({})); + assert!(warnings(&r).is_empty(), "{r}"); + let got = slices(&s); + assert_eq!(got.len(), 2, "{got:?}"); + assert_eq!(got[0].0, Rect::new(1.0, 2.0, 9.0, 10.0)); + assert_eq!( + got[0].1, + SliceOptions { + name: "cell".into(), + url: "https://example.com/".into(), + target: "_top".into(), + message: "msg".into(), + alt: "alt".into(), + background: "#ff8000".into(), + ..Default::default() + } + ); + assert_eq!((got[1].1.kind, got[1].1.text.as_str(), got[1].1.url.as_str()), (SliceKind::NoImage, "x>y", "")); + } +} + +#[test] +fn import_slices_false_leaves_them_out_and_must_be_a_switch() { + let f = with_resource(&psd(true), 1050, &v6(&[user("a", [0, 0, 5, 5])], &[])); + let (s, _) = open(&f, json!({"importSlices": false})); + assert!(slices(&s).is_empty()); + let mut s = Session::new(); + let e = s.execute("document.open", &json!({"name": "poster.psd", "dataBase64": b64(&f), "importSlices": "yes"})).unwrap_err(); + assert!(e.to_string().contains("importSlices must be true or false"), "{e}"); +} + +#[test] +fn slices_that_cant_be_read_warn_and_the_file_still_opens() { + let good = v6(&[user("a", [0, 0, 5, 5])], &[]); + let mut bad_descriptor = v7(7, vec![]); + bad_descriptor[4..8].copy_from_slice(&15u32.to_be_bytes()); + let cases: Vec<(Vec, &str)> = vec![ + (good[..good.len() - 3].to_vec(), "cut short"), + ([9u32.to_be_bytes().to_vec(), good[4..].to_vec()].concat(), "version 9"), + (bad_descriptor, "version other than 16"), + // The count follows the version, the bounds and the group's name. + ([&good[..34], &u32::MAX.to_be_bytes()[..], &good[38..]].concat(), "more than the 10000 read"), + (v7(8, vec![D::Long(3)]), "other than a slice"), + // A whole record whose name is longer than a slice's text may be. + (v6(&[user("a".repeat(65_537).leak(), [0, 0, 5, 5])], &[]), "more than the 65536 characters read"), + ]; + for (data, why) in cases { + for layers in [true, false] { + let (s, r) = open(&with_resource(&psd(layers), 1050, &data), json!({})); + let w = warnings(&r); + assert!(w.iter().any(|w| w.starts_with("the slices can't be read (") && w.contains(why)), "{why}: {w:?}"); + assert!(slices(&s).is_empty()); + // The art still came in. + assert!(s.doc().unwrap().doc.art_bounds().is_some(), "{why}"); + } + } + // A name of the longest length read comes in. + let longest = v6(&[user("a".repeat(65_536).leak(), [0, 0, 5, 5])], &[]); + let (s, r) = open(&with_resource(&psd(false), 1050, &longest), json!({})); + assert!(warnings(&r).is_empty(), "{r}"); + assert_eq!(slices(&s).first().map(|(_, o)| o.name.len()), Some(65_536)); + // A file without slices opens without a word about them. + let (s, r) = open(&psd(true), json!({})); + assert!(warnings(&r).is_empty() && slices(&s).is_empty(), "{r}"); +} + +#[test] +fn a_slices_resource_cut_short_warns_and_the_file_still_opens() { + let good = v6(&[user("a", [0, 0, 5, 5])], &[]); + // Image resource `id`, the last of the image resources, declares 10 bytes more than they hold. + let cut = |layers: bool, id: u16, data: &[u8]| { + let mut f = with_resource(&psd(layers), id, data); + let sig = [&b"8BIM"[..], &id.to_be_bytes()].concat(); + let at = f.windows(6).rposition(|w| w == sig.as_slice()).unwrap() + 8; + f[at..at + 4].copy_from_slice(&(data.len() as u32 + 10).to_be_bytes()); + f + }; + for layers in [true, false] { + let (s, r) = open(&cut(layers, 1050, &good), json!({})); + let w = warnings(&r); + assert!(w.iter().any(|w| w.starts_with("the slices can't be read (") && w.contains("cut short")), "{w:?}"); + assert!(slices(&s).is_empty()); + assert!(s.doc().unwrap().doc.art_bounds().is_some()); + // Another resource cut short says nothing about slices. + let (s, r) = open(&cut(layers, 1051, &[0, 1]), json!({})); + assert!(warnings(&r).is_empty() && slices(&s).is_empty(), "{r}"); + } +} + +#[test] +fn slices_are_clipped_to_the_canvas_and_those_outside_it_are_left_out() { + let data = v6(&[user("over", [-5, -5, 5, 30]), user("out", [25, 0, 30, 5]), user("empty", [4, 4, 4, 9]), user("in", [1, 1, 2, 2])], &[]); + let (s, r) = open(&with_resource(&psd(false), 1050, &data), json!({})); + assert_eq!(warnings(&r), ["2 slices lie outside the canvas or have no size and were left out"]); + let got: Vec<(Rect, String)> = slices(&s).into_iter().map(|(r, o)| (r, o.name)).collect(); + assert_eq!(got, [(Rect::new(0.0, 0.0, 5.0, 20.0), "over".to_string()), (Rect::new(1.0, 1.0, 2.0, 2.0), "in".to_string())]); +} + +#[test] +fn placed_embedded_files_bring_their_slices_with_the_art_in_one_undo_step() { + let data = v6(&[user("a", [0, 0, 10, 10]), user("b", [10, 10, 20, 20])], &[]); + for layers in [false, true] { + let f = with_resource(&psd(layers), 1050, &data); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + // Fitted into a 40 pt square at (100, 60): twice the size. + let r = s.execute("file.place", &json!({"name": "poster.psd", "dataBase64": b64(&f), "rect": [100, 60, 40, 40], "layers": layers})).unwrap(); + assert_eq!(r["slices"].as_array().map(Vec::len), Some(2), "{r}"); + let got: Vec = slices(&s).into_iter().map(|(r, _)| r).collect(); + assert_eq!(got, [Rect::new(100.0, 60.0, 120.0, 80.0), Rect::new(120.0, 80.0, 140.0, 100.0)]); + // The placed art stays selected, and one undo takes the art and the slices away. + assert_eq!(s.doc().unwrap().selection.objects.len(), 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(slices(&s).is_empty()); + assert!(s.doc().unwrap().doc.art_bounds().is_none()); + // Centered on `at` at 100%. + s.execute("file.place", &json!({"name": "poster.psd", "dataBase64": b64(&f), "at": [100, 100], "layers": layers})).unwrap(); + assert_eq!(slices(&s)[0].0, Rect::new(90.0, 90.0, 100.0, 100.0)); + // `importSlices: false` places the art alone. + let r = s.execute("file.place", &json!({"name": "poster.psd", "dataBase64": b64(&f), "importSlices": false, "layers": layers})).unwrap(); + assert!(r.get("slices").is_none()); + assert_eq!(slices(&s).len(), 2); + } +} + +#[test] +fn linked_files_are_placed_without_their_slices() { + let dir = std::env::temp_dir().join(format!("vc-psd-slices-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("poster.psd"); + std::fs::write(&path, with_resource(&psd(false), 1050, &v6(&[user("a", [0, 0, 5, 5])], &[]))).unwrap(); + let path = path.to_string_lossy().into_owned(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let r = s.execute("file.place", &json!({ "path": path })).unwrap(); + assert_eq!((&r["linked"], r.get("slices")), (&json!(true), None)); + assert!(slices(&s).is_empty()); + let e = s.execute("file.place", &json!({ "path": path, "importSlices": true })).unwrap_err(); + assert!(e.to_string().contains("importSlices: a linked PSD file is placed as its flat image"), "{e}"); + // Embedded from its path, they come in. + let r = s.execute("file.place", &json!({ "path": path, "link": false })).unwrap(); + assert_eq!((&r["linked"], r["slices"].as_array().map(Vec::len)), (&json!(false), Some(1))); + // file.place.info counts what a place would bring in. + let info = s.execute("file.place.info", &json!({ "path": path, "link": false })).unwrap(); + assert_eq!(info["slices"], json!(1)); + let info = s.execute("file.place.info", &json!({ "path": path })).unwrap(); + assert_eq!(info["slices"], json!(0)); + std::fs::remove_dir_all(&dir).ok(); +} + +#[test] +fn psd_info_counts_the_slices_that_come_in() { + let mut s = Session::new(); + let info = |s: &mut Session, f: &[u8]| s.execute("document.psdInfo", &json!({"dataBase64": b64(f)})).unwrap(); + let data = v6(&[user("a", [0, 0, 5, 5]), S { origin: 0, ..user("auto", [5, 5, 20, 20]) }, user("out", [30, 30, 40, 40])], &[]); + assert_eq!(info(&mut s, &with_resource(&psd(false), 1050, &data))["slices"], json!(1)); + assert_eq!(info(&mut s, &with_resource(&psd(true), 1050, &data[..data.len() - 4]))["slices"], json!(0)); + assert_eq!(info(&mut s, &psd(true))["slices"], json!(0)); +} + +#[test] +fn damaged_slices_never_panic() { + let data = v7(8, vec![D::Obj(vec![("origin", D::Enum("ESliceOrigin", "userGenerated")), ("bounds", bounds(0, 0, 5, 5))])]); + let base = with_resource(&psd(false), 1050, &data); + let start = base.windows(data.len()).position(|w| w == data).unwrap(); + for at in (start - 12..start + data.len()).step_by(3) { + for v in [0u8, 0x7f, 0xff] { + let mut f = base.clone(); + f[at] = v; + let mut s = Session::new(); + let _ = s.execute("document.open", &json!({"name": "poster.psd", "dataBase64": b64(&f)})); + let _ = s.execute("document.psdInfo", &json!({"dataBase64": b64(&f)})); + } + } +} diff --git a/crates/engine/src/cmd/flatten/analysis.rs b/crates/engine/src/cmd/flatten/analysis.rs index 4525a3aa5c..9771d18ef9 100644 --- a/crates/engine/src/cmd/flatten/analysis.rs +++ b/crates/engine/src/cmd/flatten/analysis.rs @@ -185,9 +185,12 @@ impl Sets { /// 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. 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`]). +/// a later box of its group overlaps and ends no further right than keeps only the part the later +/// box doesn't cover: its part above the later box's top when the later box starts lower and ends +/// no higher than it, and its part below the later box's bottom when the later box starts no lower +/// and ends higher than it. The open box's top then moves down in the tree, so boxes staggered right +/// and down, or right and up, 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()) } @@ -206,27 +209,25 @@ fn sweep(bounds: &[Option], see_through: Option<&[bool]>) -> Result = bounds.iter().enumerate().filter_map(|(i, b)| b.filter(finite).map(|b| (i, b))).collect(); let n = boxes.len(); - // Each box's place in the tree: by top (then index). - let mut by_top: Vec = (0..n).collect(); - by_top.sort_by(|&a, &b| boxes[a].1.y0.total_cmp(&boxes[b].1.y0).then(a.cmp(&b))); - let tops: Vec = by_top.iter().map(|&k| boxes[k].1.y0).collect(); - let mut leaf = vec![0usize; n]; - for (pos, &k) in by_top.iter().enumerate() { - leaf[k] = pos; - } - // The lowest bottom of the open boxes below each node (−∞: none open), in the tree of the - // boxes without transparency (every box without `see_through`) and the see-through boxes'. - let size = n.next_power_of_two().max(1); - let mut low = [vec![f64::NEG_INFINITY; 2 * size], if see_through.is_some() { vec![f64::NEG_INFINITY; 2 * size] } else { vec![] }]; - let tree = |k: usize| usize::from(see_through.is_some_and(|s| s[boxes[k].0])); - let set = |low: &mut [f64], pos: usize, v: f64| { - let mut i = pos + size; - low[i] = v; - while i > 1 { - i /= 2; - low[i] = low[2 * i].max(low[2 * i + 1]); - } + // The places an open box's top can be at in the tree: a box's top, or just below a box's + // bottom, where a later box cuts it short (`-0.0` as `0.0`). + let mut places: Vec = boxes.iter().flat_map(|(_, b)| [b.y0 + 0.0, b.y1.next_up() + 0.0]).collect(); + places.sort_by(f64::total_cmp); + places.dedup_by(|a, b| a.total_cmp(b).is_eq()); + let place = |y: f64| { + let y = y + 0.0; + let p = places.partition_point(|t| t.total_cmp(&y).is_lt()); + places.get(p).is_some_and(|t| t.total_cmp(&y).is_eq()).then_some(p) }; + // Each box's part still open, from its top to its bottom, and the place of its top while it + // is open. + let mut top: Vec = boxes.iter().map(|(_, b)| b.y0).collect(); + let mut bottom: Vec = boxes.iter().map(|(_, b)| b.y1).collect(); + let mut open: Vec> = vec![None; n]; + // The tree of the open boxes without transparency (every box without `see_through`) and the + // see-through boxes'. + let mut trees = [Open::new(places.len()), Open::new(if see_through.is_some() { places.len() } else { 0 })]; + let tree = |k: usize| usize::from(see_through.is_some_and(|s| s[boxes[k].0])); let mut by_left: Vec = (0..n).collect(); by_left.sort_by(|&a, &b| boxes[a].1.x0.total_cmp(&boxes[b].1.x0)); let mut by_right: Vec = (0..n).collect(); @@ -241,7 +242,9 @@ fn sweep(bounds: &[Option], see_through: Option<&[bool]>) -> Result], see_through: Option<&[bool]>) -> Result &[0, 1], Some(_) => &[1], }; - let below = tops.partition_point(|t| *t <= b.y1); + let below = places.partition_point(|t| *t <= b.y1); met.clear(); for &t in looks { + let tr = &trees[t]; stack.clear(); - stack.push((1, 0, size)); + stack.push((1, 0, tr.size)); while let Some((node, lo, hi)) = stack.pop() { work += 1; if work.is_multiple_of(4096) { vectorcraft_doc::cancel::check()?; } - if lo >= below || low[t][node] < b.y0 { + if lo >= below || tr.low[node] < b.y0 { continue; } if hi - lo == 1 { - met.push(by_top[lo]); + // The boxes with their top here, lowest bottom first. + for &(_, o) in tr.at[lo].iter().rev() { + if bottom[o] < b.y0 { + break; + } + work += 1; + if work.is_multiple_of(4096) { + vectorcraft_doc::cancel::check()?; + } + met.push(o); + } continue; } let mid = (lo + hi) / 2; @@ -286,30 +300,91 @@ fn sweep(bounds: &[Option], see_through: Option<&[bool]>) -> Result, + /// The open boxes at each place, by bottom ([`order`]) and then index. + at: Vec>, +} + +impl Open { + fn new(places: usize) -> Self { + let size = places.next_power_of_two().max(1); + Self { size, low: vec![f64::NEG_INFINITY; 2 * size], at: vec![BTreeSet::new(); places] } + } + + /// Opens box `k` at place `p`, with its bottom `bottom[k]`. + fn put(&mut self, p: usize, k: usize, bottom: &[f64]) { + self.at[p].insert((order(bottom[k]), k)); + self.fix(p, bottom); + } + + /// Closes box `k` at place `p`, while its bottom is still `bottom[k]`. + fn take(&mut self, p: usize, k: usize, bottom: &[f64]) { + self.at[p].remove(&(order(bottom[k]), k)); + self.fix(p, bottom); + } + + fn fix(&mut self, p: usize, bottom: &[f64]) { + let mut i = p + self.size; + self.low[i] = self.at[p].last().map_or(f64::NEG_INFINITY, |&(_, k)| bottom[k]); + while i > 1 { + i /= 2; + self.low[i] = self.low[2 * i].max(self.low[2 * i + 1]); + } + } +} + +/// `v` as an integer in the same order as [`f64::total_cmp`]. +fn order(v: f64) -> i64 { + let b = v.to_bits() as i64; + b ^ (((b >> 63) as u64) >> 1) as i64 +} + /// Boxes in blocks of nearby ones, each block with the box around it, to find the boxes a box /// touches. struct Blocks { @@ -775,6 +850,136 @@ mod tests { assert_eq!(sets.groups(), vec![(0..n).collect::>()]); } + /// `n` boxes of one size, each a little right of and above the one before, all overlapping and + /// none inside another. + fn staggered_up(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 up meets only the box before it, which keeps only its part + /// below the new box's bottom, not every box still open; so does each box of a stagger left and + /// down, which the sweep meets right and up. + #[test] + fn boxes_staggered_up_meet_only_the_box_before() { + let n = 512; + let bounds = staggered_up(n); + let all = vec![(0..n).collect::>()]; + let mut sets = sweep(&bounds, None).unwrap(); + assert_eq!(sets.meets, n - 1); + assert_eq!(sets.groups(), every_pair(&bounds)); + assert_eq!(sets.groups(), all); + let mut sets = sweep(&bounds, Some(&vec![true; n])).unwrap(); + assert_eq!(sets.meets, n - 1); + assert_eq!(sets.groups(), all); + let mut reversed = bounds.clone(); + reversed.reverse(); + let mut sets = sweep(&reversed, None).unwrap(); + assert_eq!(sets.meets, n - 1); + assert_eq!(sets.groups(), all); + let mut sets = sweep(&reversed, Some(&vec![true; n])).unwrap(); + assert_eq!(sets.meets, n - 1); + assert_eq!(sets.groups(), all); + } + + /// An open box cut short from above keeps the part a later box would meet without meeting the + /// box that cut it: a part below that box, a part further right, or any part when that box is + /// opaque or held; a box cut from above and from below keeps its middle. + #[test] + fn a_box_is_cut_short_from_above_only_where_the_later_box_covers_it() { + let k = Rect::new(5.0, -5.0, 15.0, 10.0); + let cases = [ + // Below `k`: the last box overlaps only the bottom of the first. + ("below", vec![Some(Rect::new(0.0, 0.0, 10.0, 20.0)), Some(k), Some(Rect::new(8.0, 15.0, 9.0, 25.0))], vec![true, true, false]), + // Further right than `k`: `k` cuts nothing and the last box overlaps the first. + ("right", vec![Some(Rect::new(0.0, 0.0, 20.0, 20.0)), Some(k), Some(Rect::new(17.0, 2.0, 25.0, 4.0))], vec![true, true, false]), + // Just below `k`'s bottom, and touching it. + ( + "edge", + vec![Some(Rect::new(0.0, 0.0, 10.0, 20.0)), Some(k), Some(Rect::new(8.0, 10.0, 9.0, 12.0)), Some(Rect::new(8.0, 10.5, 9.0, 12.0))], + vec![false, true, false, false], + ), + // An opaque `k` doesn't join the opaque last box, which joins the see-through first one. + ("opaque", vec![Some(Rect::new(0.0, 0.0, 10.0, 10.0)), Some(k), Some(Rect::new(6.0, -10.0, 7.0, 2.0))], vec![true, false, false]), + // A see-through `k` held by a see-through box around it isn't opened and cuts nothing short. + ( + "held", + vec![ + Some(Rect::new(0.0, -6.0, 30.0, 28.0)), + Some(Rect::new(1.0, 0.0, 10.0, 20.0)), + Some(k), + Some(Rect::new(6.0, 11.0, 7.0, 13.0)), + Some(Rect::new(6.0, 4.0, 7.0, 6.0)), + ], + vec![true, false, true, false, false], + ), + // Cut from above, then from below: a later box inside what is left joins the first. + ( + "middle", + vec![ + Some(Rect::new(0.0, 0.0, 10.0, 30.0)), + Some(Rect::new(2.0, -5.0, 12.0, 10.0)), + Some(Rect::new(3.0, 20.0, 13.0, 40.0)), + Some(Rect::new(5.0, 15.0, 6.0, 16.0)), + Some(Rect::new(5.0, 9.0, 6.0, 10.0)), + Some(Rect::new(5.0, 20.0, 6.0, 20.0)), + ], + vec![false, true, true, false, false, false], + ), + // Signed zeros, a point and a box that isn't finite. + ( + "zeros", + vec![ + Some(Rect::new(-0.0, -0.0, 4.0, 8.0)), + Some(Rect::new(0.0, -2.0, 6.0, -0.0)), + Some(Rect::new(1.0, 0.0, 1.0, 0.0)), + Some(Rect::new(2.0, f64::NEG_INFINITY, 3.0, 1.0)), + Some(Rect::new(3.0, f64::MAX, 3.0, f64::MAX)), + Some(Rect::new(3.5, 0.0, 3.5, 0.0)), + ], + vec![false, true, false, true, true, false], + ), + ]; + for (what, bounds, see) in cases { + assert_eq!(overlapping(&bounds).unwrap(), every_pair(&bounds), "{what}"); + let mut sets = sweep(&bounds, Some(&see)).unwrap(); + assert_eq!(sets.groups(), every_pair_joining(&bounds, |i, j| see[i] || see[j]), "{what}, with transparency"); + let mut sets = sweep(&bounds, Some(&vec![true; bounds.len()])).unwrap(); + assert_eq!(sets.groups(), every_pair(&bounds), "{what}, all see-through"); + } + } + + /// Boxes stepping right and alternately up and down, so that open boxes are cut short from + /// above and from below, of mixed sizes, some see-through, group as comparing every pair groups + /// them. + #[test] + fn boxes_stepping_up_and_down_group_as_comparing_every_pair() { + let mut seed = 0x6a09_e667_f3bc_c908u64; + 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..40 { + let n = 10 + round * 3; + let mut y = 0.0; + let bounds: Vec> = (0..n) + .map(|i| { + let up = if (i / (1 + round % 3)) % 2 == 0 { -1.0 } else { 1.0 }; + y += up * (next(4.0).floor() + 1.0); + let x = i as f64 + next(2.0).floor(); + let (w, h) = (next(12.0).floor() + 4.0, next(16.0).floor() + 2.0); + Some(Rect::new(x, y, x + w, y + h)) + }) + .collect(); + assert_eq!(overlapping(&bounds).unwrap(), every_pair(&bounds), "round {round}"); + let see: Vec = (0..n).map(|_| next(1.0) < if round % 2 == 0 { 0.5 } else { 0.9 }).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 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] diff --git a/crates/engine/src/cmd/fonts.rs b/crates/engine/src/cmd/fonts.rs index 7c8f664cf3..28662f013c 100644 --- a/crates/engine/src/cmd/fonts.rs +++ b/crates/engine/src/cmd/fonts.rs @@ -10,9 +10,10 @@ use vectorcraft_color::Paint; use vectorcraft_doc::{AppearanceItem, Document, Node, NodeId, NodeKind, TextKind, TextObject, TextRun}; use vectorcraft_geom::Rect; +use super::panelcmds::listed_artboards; use super::select::on_artboard; use super::typecmd::refresh_bounds; -use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, index, str_param}; +use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, str_param}; pub fn specs() -> Vec { vec![ @@ -39,7 +40,7 @@ pub fn specs() -> Vec { "Select Text by Font", [], None, - "{family, style?, scope?: \"document\" (default) | {artboards: [index, …] (0-based)} | {layers: [id, …] (layers or sublayers)}} select the text objects using the font, the instances of the symbols whose art uses it, the text whose inline graphics draw such a symbol, the objects painted with a pattern whose art uses it (by a visible fill or stroke whose opacity is above 0, a stroke wider than 0) and the objects whose opacity mask uses it (in type that is not hidden or locked in that art), that are not hidden or locked, in a hidden or locked group or layer, or on a locked artboard; a pattern swatch that nothing paints, or a layer's mask, selects nothing; with scope, only those on one of the artboards (as All on Active Artboard takes them: their bounds overlap it or their center is on it) or in one of the layers → {count}", + "{family, style?, scope?: \"document\" (default) | {artboards: [index, …] (0-based whole numbers)} | {layers: [id, …] (layers or sublayers)}} select the text objects using the font, the instances of the symbols whose art uses it, the text whose inline graphics draw such a symbol, the objects painted with a pattern whose art uses it (by a visible fill or stroke whose opacity is above 0, a stroke wider than 0) and the objects whose opacity mask uses it (in type that is not hidden or locked in that art), that are not hidden or locked, in a hidden or locked group or layer, or on a locked artboard; a pattern swatch that nothing paints, or a layer's mask, selects nothing; with scope, only those on one of the artboards (as All on Active Artboard takes them: their bounds overlap it or their center is on it) or in one of the layers → {count}", has_doc, select_font ), @@ -1080,9 +1081,9 @@ impl FontScope { Some(_) => Err(bad(C, format!("`scope.{key}` must be a non-empty array"))), } }; - if let Some(a) = list("artboards")? { - let rect = |v: &Value| v.as_u64().and_then(|i| d.artboards.get(index(i))).map(|b| b.rect); - return a.iter().map(|v| rect(v).ok_or_else(|| bad(C, format!("no such artboard {v}")))).collect::>().map(Self::Artboards); + if let (Some(v), Some(_)) = (scope.get("artboards"), list("artboards")?) { + let indices = listed_artboards(d, v, "scope.artboards", C)?; + return Ok(Self::Artboards(indices.into_iter().filter_map(|i| d.artboards.get(i)).map(|b| b.rect).collect())); } if let Some(a) = list("layers")? { let layer = |v: &Value| v.as_u64().map(NodeId).filter(|id| d.node(*id).is_some_and(Node::is_layer)); @@ -1292,6 +1293,40 @@ mod tests { } } + /// Select Text by Font refuses a `scope.artboards` entry that is not a whole number, naming the + /// parameter, before it looks at the artboards, and leaves the selection as it was; a whole + /// number past the last artboard is `no such artboard`. + #[test] + fn select_font_refuses_artboards_that_are_not_whole_numbers() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + s.execute("artboard.new", &json!({"x": 300, "y": 0, "width": 200, "height": 200})).unwrap(); + let text = |s: &mut Session, x: i32| { + NodeId(s.execute("text.create", &json!({"x": x, "y": 50, "text": "Serif", "font": "Source Serif 4"})).unwrap()["id"].as_u64().unwrap()) + }; + let first = text(&mut s, 10); + let second = text(&mut s, 350); + let run = + |s: &mut Session, artboards: Value| s.execute("select.font", &json!({"family": "Source Serif 4", "scope": {"artboards": artboards}})); + let malformed = "invalid parameters for `select.font`: `scope.artboards` must contain whole numbers"; + for (artboards, want) in [ + (json!(["1"]), malformed), + (json!([-1]), malformed), + (json!([1.5]), malformed), + (json!([true]), malformed), + (json!([null]), malformed), + (json!([9, "1"]), malformed), + (json!([9]), "no such artboard"), + (json!([1, 9]), "no such artboard"), + ] { + s.execute("select.set", &json!({"ids": [first.0]})).unwrap(); + assert_eq!(run(&mut s, artboards.clone()).unwrap_err().to_string(), want, "{artboards}"); + assert_eq!(s.doc().unwrap().selection.objects, [first], "{artboards}"); + } + run(&mut s, json!([1, 1])).unwrap(); + assert_eq!(s.doc().unwrap().selection.objects, [second]); + } + /// Select Text by Font with a layer scope takes the text in the layers, their sublayers /// included, and still leaves out hidden and locked text. #[test] diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs index 97917a2469..00575695d4 100644 --- a/crates/engine/src/cmd/gradient.rs +++ b/crates/engine/src/cmd/gradient.rs @@ -534,7 +534,7 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result { // Objects were given or selected, even when all of them are graph design art left out below: the stroke mode is then // not one for new art. let selected = !ids.is_empty(); - let ids = super::appearance::drop_design_art(&s.doc()?.doc, ids); + let ids = super::appearance::drop_design_art_rows(s, ids, item, !stroke, C)?; // How the gradient lies on a stroke (the panel's Stroke buttons). let mode = match str_param(p, "strokeMode") { None => None, @@ -558,7 +558,7 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result { _ => None, }); let for_default = match p.get("aspect").and_then(Value::as_f64) { - Some(a) if a < 0.0 && !ids.is_empty() && default_kind != Some(GradientKind::Conic) => { + Some(a) if a < 0.0 && selected && default_kind != Some(GradientKind::Conic) => { let mut q = p.clone(); q["aspect"] = json!(-a); std::borrow::Cow::Owned(q) @@ -568,7 +568,7 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result { // A spread for selected gradients leaves a freeform default (which has no ends) as it is. let spreads = matches!(spread_param(p), Ok(Some(sp)) if !sp.is_pad()); let for_default = match for_default { - q if spreads && !ids.is_empty() && default_kind == Some(GradientKind::Freeform) => { + q if spreads && selected && default_kind == Some(GradientKind::Freeform) => { let mut q = q.into_owned(); if let Some(o) = q.as_object_mut() { o.remove("spread"); @@ -579,8 +579,14 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result { }; let new_default = apply_gradient_edit_in_model(&default_paint, &with_stored_stops(&for_default, &default_paint, &stored), None, &|_| true, model) .map_err(|e| bad(C, e))?; - let freeform = str_param(p, "kind").and_then(GradientKind::parse) == Some(GradientKind::Freeform); let of = super::appearance::reference_of(s, p, item, C)?; + // Only design art was given or selected: nothing changes, the defaults and the remembered paint included. + if selected && ids.is_empty() { + // An aligned `item` of the art alone is still checked: a row the art lacks, or that no other object has, is an error. + edit_items(s, &ids, item, of, C, "Gradient", !stroke, |_, _| Ok(()))?; + return Ok(json!({"ids": []})); + } + let freeform = str_param(p, "kind").and_then(GradientKind::parse) == Some(GradientKind::Freeform); let shown_at = super::appearance::first_edited(s, item, of, &ids); // The objects returned: with a design's art, those with a row equal to the art's. let edited = edit_items(s, &ids, item, of, C, "Gradient", !stroke, |n, index| { @@ -770,7 +776,7 @@ fn set_gradient_geom(s: &mut Session, p: &Value) -> Result { if targets.is_empty() { return Err(EngineError::Other("nothing selected".into())); } - let targets = super::appearance::drop_design_art(&s.doc()?.doc, targets); + let targets = super::appearance::drop_design_art_rows(s, targets, item, !stroke, C)?; let model = super::paint::new_color_model(s, &Value::Null); let of = super::appearance::reference_of(s, p, item, C)?; // The objects returned: with a design's art, those with a row equal to the art's. diff --git a/crates/engine/src/cmd/graph.rs b/crates/engine/src/cmd/graph.rs index 7be0a122df..11a41174c1 100644 --- a/crates/engine/src/cmd/graph.rs +++ b/crates/engine/src/cmd/graph.rs @@ -49,9 +49,9 @@ use generate::generate; 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, plain_labels, series_group_marks, series_group_marks_where, series_groups_among, - series_marks_in, series_object_opacity_differs, shown_paint, + capture_label_styles, capture_label_text, capture_series_object_opacity, capture_series_opacity, capture_series_top_paints, follow_wedge_shades, + is_design_art, label_object_opacity_differs, labels_in, paint_targets, plain_labels, series_group_marks, series_group_marks_where, + series_groups_among, series_marks_in, series_object_opacity_differs, shown_paint, wedge_shades, }; #[cfg(test)] diff --git a/crates/engine/src/cmd/graph/series.rs b/crates/engine/src/cmd/graph/series.rs index ee33f23517..c3cf55ca60 100644 --- a/crates/engine/src/cmd/graph/series.rs +++ b/crates/engine/src/cmd/graph/series.rs @@ -1,4 +1,5 @@ use vectorcraft_color::BlendMode; +use vectorcraft_doc::swatches::walk_with_masks; use vectorcraft_geom::Shape; use super::axis::radar_axis; @@ -767,6 +768,68 @@ fn set_legend_fills(n: &mut Node, on_dark: &HashMap) { } } +/// Whether each wedge shows a dark fill, for each pie in `n` (`n` itself or one inside it, opacity-mask art included) +/// with Legends in Wedges whose legend labels' fill is not their own, so a redraw sets it by its wedge. Read before a +/// paste links the pie's colors to the document's swatches, for [`follow_wedge_shades`]. +pub(crate) fn wedge_shades(n: &Node) -> HashMap> { + let mut out = HashMap::new(); + walk_with_masks(n, &mut |m| { + if let Some(g) = m.extras().graph.as_deref() + && g.kind == GraphKind::Pie + && g.legend + && g.pie_legend_in_wedges + && !g.label_styles.legend_fill_is_own() + { + out.insert(m.id, pie_wedges(m).iter().map(|w| w.dark).collect()); + } + }); + out +} + +/// Give the legend labels of each pie in `n` that [`wedge_shades`] read as `was` the contrast a redraw sets, where a +/// wedge now shows a fill of the other darkness: white on a dark wedge, black on a light one. Pies whose wedges all kept +/// their darkness keep their labels as they are. +pub(crate) fn follow_wedge_shades(n: &mut Node, was: &HashMap>) { + let mut changed = vec![]; + walk_with_masks(n, &mut |m| { + if let Some(before) = was.get(&m.id) + && pie_wedges(m).iter().map(|w| w.dark).ne(before.iter().copied()) + { + changed.push(m.id); + } + }); + if !changed.is_empty() { + restore_contrast(n, &changed); + } +} + +/// Set the legend labels of the pies `ids` in `n` (`n` itself or ones inside it, opacity-mask art included) as a redraw +/// sets them on their wedges. +fn restore_contrast(n: &mut Node, ids: &[NodeId]) { + if ids.contains(&n.id) { + let on_dark = match n.extras().graph.as_deref() { + Some(g) => redrawn_on_dark(n, g).unwrap_or_else(|| legend_on_dark(n, g)), + None => HashMap::new(), + }; + set_legend_fills(n, &on_dark); + } + let holds = |c: &Node| { + let mut found = false; + walk_with_masks(c, &mut |m| found |= ids.contains(&m.id)); + found + }; + if n.extras().mask.as_ref().is_some_and(|m| holds(&m.art)) + && let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) + { + restore_contrast(Arc::make_mut(&mut m.art), ids); + } + for c in n.children_mut().into_iter().flatten() { + if holds(c) { + restore_contrast(Arc::make_mut(c), ids); + } + } +} + /// The legend labels of graph `n`: the type in its Legend group, as [`own_labels`] finds them. fn legend_labels(n: &Node) -> Vec<&Node> { legend_in(n.children().map_or(&[], |c| c.as_slice())) diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index ca1f1d2c45..d171224d14 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -454,7 +454,7 @@ fn an_edit_of_a_graph_designs_art_is_lost_when_the_graph_is_drawn_again() { /// it, and edit the other objects they are given. #[test] fn paint_commands_leave_a_graph_designs_art_out() { - let (mut s, _, copy, art, mark) = design_art(); + let (mut s, graph, copy, art, mark) = design_art(); let fill = top_row(&s, art, true); let commands = [ ("stroke.set", json!({"weight": 5})), @@ -466,6 +466,7 @@ fn paint_commands_leave_a_graph_designs_art_out() { ("paint.swap", json!({})), ("paint.default", json!({})), ("paint.invert", json!({"item": fill, "stroke": false})), + ("paint.invert", json!({})), ]; let (copy_was, art_was) = (look(&s, copy), look(&s, art)); for (cmd, p) in &commands { @@ -489,6 +490,11 @@ fn paint_commands_leave_a_graph_designs_art_out() { s.execute("select.set", &json!({"ids": [art.0]})).unwrap(); s.execute("stroke.set", &json!({"weight": 5})).unwrap(); assert_eq!(look(&s, art), art_was); + // Given the whole graph, Invert recolors the marks and leaves the art. + let mark_was = look(&s, mark); + s.execute("paint.invert", &json!({"ids": [graph.0]})).unwrap(); + assert_eq!(look(&s, art), art_was); + assert_ne!(look(&s, mark), mark_was); // A freeform gradient point is refused on the art alone. refused_on_design_art(&mut s, "paint.freeform.addPoint", json!({"ids": [art.0], "at": [0, 0]})); } @@ -517,6 +523,182 @@ fn stroke_edits_of_selected_design_art_leave_the_new_art_stroke() { assert_eq!(s.new_art_stroke().gradient_mode, mode, "paint.editGradient"); } +/// With only the art of a graph design given or selected, the gradient, swap, default and recolor commands leave the +/// paint for new art and the remembered colors as they are. +#[test] +fn paint_edits_of_design_art_alone_leave_the_defaults() { + let (mut s, _, _, art, _) = design_art(); + let fill = top_row(&s, art, true); + s.execute("select.set", &json!({"ids": []})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 3})).unwrap(); + let defaults = |s: &Session| format!("{:?}", (&s.paint, s.last_solid, &s.last_gradient, &s.recent_colors)); + let commands = [ + ("paint.editGradient", json!({"kind": "linear"})), + ("paint.editGradient", json!({"kind": "radial", "stroke": true})), + ("paint.swap", json!({})), + ("paint.default", json!({})), + ("paint.invert", json!({"item": fill, "stroke": false})), + ("paint.complement", json!({"item": fill, "stroke": false})), + ("paint.invert", json!({})), + ("paint.complement", json!({"stroke": true})), + ("stroke.set", json!({"weight": 7})), + ("stroke.weightUp", json!({})), + ]; + for (cmd, p) in &commands { + let was = defaults(&s); + let mut q = p.clone(); + q["ids"] = json!([art.0]); + s.execute(cmd, &q).unwrap(); + assert_eq!(defaults(&s), was, "{cmd}, given"); + // Selecting the art makes the defaults take its paint. + s.execute("select.set", &json!({"ids": [art.0]})).unwrap(); + let was = defaults(&s); + s.execute(cmd, p).unwrap(); + assert_eq!(defaults(&s), was, "{cmd}, selected"); + s.execute("select.set", &json!({"ids": []})).unwrap(); + } + // A bad `item`, `aligned` or `target` is still an error with only design art given. + for bad in [ + json!({"ids": [art.0], "item": "top"}), + json!({"ids": [art.0], "item": fill, "aligned": "yes"}), + json!({"ids": [art.0], "item": fill, "target": "nowhere"}), + json!({"ids": [art.0], "target": "nowhere"}), + ] { + assert!(s.execute("paint.invert", &bad).is_err(), "{bad}"); + assert!(s.execute("paint.complement", &bad).is_err(), "{bad}"); + } + // So is an `item` the art has no row for, in each command that leaves the art out. + let steps = s.doc().unwrap().history.undo.len(); + for (cmd, p) in [ + ("paint.invert", json!({})), + ("stroke.set", json!({"weight": 2})), + ("stroke.weightUp", json!({})), + ("stroke.setAdvanced", json!({"swapArrows": true})), + ("paint.editGradient", json!({"kind": "linear"})), + ("paint.setGradientGeom", json!({"start": [0, 0], "end": [50, 50]})), + ("object.setOverprint", json!({"fill": true})), + ] { + let mut q = p.clone(); + q["ids"] = json!([art.0]); + q["item"] = json!(99); + assert!(s.execute(cmd, &q).is_err(), "{cmd}"); + } + // The art's stroke row named without `stroke` is a stroke row: the gradient commands succeed and change nothing. + let stroke_row = top_row(&s, art, false); + for p in [json!({"kind": "linear"}), json!({"start": [0, 0], "end": [50, 50]})] { + let cmd = if p.get("kind").is_some() { "paint.editGradient" } else { "paint.setGradientGeom" }; + let mut q = p.clone(); + q["ids"] = json!([art.0]); + q["item"] = json!(stroke_row); + s.execute(cmd, &q).unwrap(); + } + assert_eq!(s.doc().unwrap().history.undo.len(), steps); + // With nothing selected, the swap still swaps the defaults. + let was = defaults(&s); + s.execute("paint.swap", &json!({})).unwrap(); + assert_ne!(defaults(&s), was); +} + +/// A spread or a negative aspect for the art of a graph design alone changes nothing, whatever kind of gradient the +/// default fill is; a bad value is still an error. +#[test] +fn gradient_edits_of_design_art_alone_skip_the_default_kind_checks() { + let (mut s, _, _, art, _) = design_art(); + for (default, p) in [("freeform", json!({"spread": "repeat"})), ("linear", json!({"aspect": -50}))] { + s.execute("select.set", &json!({"ids": []})).unwrap(); + s.execute("paint.editGradient", &json!({"kind": default})).unwrap(); + let (was, art_was, steps) = (format!("{:?}", s.paint), look(&s, art), s.doc().unwrap().history.undo.len()); + let mut q = p.clone(); + q["ids"] = json!([art.0]); + s.execute("paint.editGradient", &q).unwrap_or_else(|e| panic!("{q}: {e}")); + assert_eq!(format!("{:?}", s.paint), was, "{default}"); + assert_eq!(look(&s, art), art_was, "{default}"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{default}"); + } + assert!(s.execute("paint.editGradient", &json!({"ids": [art.0], "spread": "sideways"})).is_err()); +} + +/// Invert given a group around a graph recolors the group's own fill and the series marks, and leaves the art of a +/// graph design as it is. With `target: "contents"` the group's own fill stays as it is. +#[test] +fn invert_of_a_group_recolors_its_own_fill_and_leaves_design_art() { + let (mut s, graph, _, art, mark) = design_art(); + s.execute("select.set", &json!({"ids": [graph.0]})).unwrap(); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("appearance.addFill", &json!({"ids": [group.0]})).unwrap(); + let row = top_row(&s, group, true); + s.execute("paint.setFill", &json!({"ids": [group.0], "item": row, "color": "#ff0000"})).unwrap(); + let own = |s: &Session| format!("{:?}", s.doc().unwrap().doc.node(group).unwrap().appearance.items); + let (own_was, art_was, mark_was) = (own(&s), look(&s, art), look(&s, mark)); + s.execute("paint.invert", &json!({"ids": [group.0]})).unwrap(); + assert_ne!(own(&s), own_was, "the group's own fill"); + assert_ne!(look(&s, mark), mark_was); + assert_eq!(look(&s, art), art_was); + // The color remembered is the group's own new fill, which the Fill proxy shows. + let Some(Paint::Solid { color, .. }) = s.doc().unwrap().doc.node(group).unwrap().proxy_paint_only(false, None).cloned() else { + panic!("the group's fill is not a solid color") + }; + assert_eq!((s.last_solid, s.recent_colors.first().copied()), (color, Some(color))); + let (own_was, mark_was) = (own(&s), look(&s, mark)); + s.execute("paint.invert", &json!({"ids": [group.0], "target": "contents"})).unwrap(); + assert_eq!(own(&s), own_was, "target: contents"); + assert_ne!(look(&s, mark), mark_was); + assert_eq!(look(&s, art), art_was); +} + +/// Invert and Complement given a series group that holds only a graph design's art recolor the group's own fill and +/// remember that color, as the last color and the newest recent color. With several such groups the color remembered +/// is that of the first group whose fill changed. +#[test] +fn recoloring_a_group_of_design_art_alone_remembers_its_own_fill() { + // A fill of its own for `group`, painted `hex` (the color of a rectangle painted with it). + let paint_own = |s: &mut Session, group: NodeId, hex: &str| { + s.execute("appearance.addFill", &json!({"ids": [group.0]})).unwrap(); + let t = NodeId(s.execute("shape.rectangle", &json!({"x": 700, "y": 700, "width": 5, "height": 5})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"ids": [t.0], "color": hex})).unwrap(); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let paint = d.node(t).unwrap().proxy_paint_only(false, None).unwrap().clone(); + d.node_mut(group).unwrap().appearance.fill_at_mut(None).unwrap().paint = paint; + }; + // Series 0's group with its own fill painted `hex`. + let painted_series = |hex: &str| { + let (mut s, graph, _, art, _) = design_art(); + let group = series(s.doc().unwrap().doc.node(graph).unwrap(), 0).id; + paint_own(&mut s, group, hex); + (s, group, art) + }; + for cmd in ["paint.invert", "paint.complement"] { + let (mut s, group, art) = painted_series("#ff0000"); + let fill = |s: &Session| s.doc().unwrap().doc.node(group).unwrap().proxy_paint_only(false, None).unwrap().clone(); + let (art_was, fill_was) = (look(&s, art), fill(&s)); + s.execute(cmd, &json!({"ids": [group.0]})).unwrap(); + assert_eq!(look(&s, art), art_was, "{cmd}"); + assert_ne!(fill(&s), fill_was, "{cmd}: the group's fill is recolored"); + let Paint::Solid { color, .. } = fill(&s) else { panic!("{cmd}: the group's fill is not a solid color") }; + assert_eq!((s.last_solid, s.recent_colors.first().copied()), (color, Some(color)), "{cmd}"); + } + // A gray fill is its own complement: nothing changes, and the remembered colors stay as they were. + let (mut s, group, _) = painted_series("#808080"); + s.execute("select.set", &json!({"ids": []})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap(); + let remembered = |s: &Session| format!("{:?}", (s.last_solid, &s.recent_colors)); + let was = remembered(&s); + assert_eq!(s.execute("paint.complement", &json!({"ids": [group.0]})).unwrap()["changed"], json!(0)); + assert_eq!(remembered(&s), was); + // Both series groups hold only the design's art: a gray one first and a red one, given together. + let (mut s, graph, _, _, _) = design_art(); + s.execute("graph.column", &json!({"id": graph.0, "seriesIndexes": [1], "design": "Square"})).unwrap(); + let groups = [0, 1].map(|i| series(s.doc().unwrap().doc.node(graph).unwrap(), i).id); + paint_own(&mut s, groups[0], "#808080"); + paint_own(&mut s, groups[1], "#ff0000"); + s.execute("paint.complement", &json!({"ids": [groups[0].0, groups[1].0]})).unwrap(); + let Some(Paint::Solid { color, .. }) = s.doc().unwrap().doc.node(groups[1]).unwrap().proxy_paint_only(false, None).cloned() else { + panic!("the red group's fill is not a solid color") + }; + assert_eq!((s.last_solid, s.recent_colors.first().copied()), (color, Some(color))); +} + /// `transparency.set` without `item` refuses the art of a graph design in a series, and given it with other objects /// sets only theirs. #[test] @@ -596,6 +778,81 @@ fn expand_appearance_leaves_a_graph_designs_art() { assert!(s.doc().unwrap().doc.node(NodeId(other)).is_none_or(|m| m.appearance.effects.is_empty())); } +/// `effect` with `params`, as `effect.apply` gives it to an object. +fn an_effect(s: &mut Session, effect: &str, params: serde_json::Value) -> vectorcraft_doc::Effect { + let r = s.execute("shape.rectangle", &json!({"x": 700, "y": 20, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("effect.apply", &json!({"effect": effect, "ids": [r], "params": params})).unwrap(); + s.doc().unwrap().doc.node(NodeId(r)).unwrap().appearance.effects[0].clone() +} + +/// Expand Appearance of a graph neither lists the art of a design in a series whose own effect it leaves, nor adds an +/// image of that effect to the document. +#[test] +fn expand_appearance_lists_no_design_art_and_rasterizes_none() { + let (mut s, id, copy, _, mark) = design_art(); + let shadow = an_effect(&mut s, "stylize.dropShadow", json!({})); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(copy).unwrap().appearance.effects.push(shadow); + s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "ids": [mark.0]})).unwrap(); + let copy_was = look(&s, copy); + let images = |s: &Session| s.doc().unwrap().doc.images.len(); + let before = images(&s); + s.execute("select.set", &json!({"ids": [mark.0]})).unwrap(); + s.execute("effect.expandAppearance", &json!({})).unwrap(); + let per_mark = images(&s) - before; + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let expanded = s.execute("effect.expandAppearance", &json!({})).unwrap(); + assert_eq!(expanded["ids"], json!([mark.0])); + assert_eq!(look(&s, copy), copy_was); + assert_eq!(images(&s) - before, per_mark, "only the mark's shadow becomes an image"); +} + +/// A geometry effect of a series group that Expand Appearance bakes moves the art of a design in that series with the +/// marks. +#[test] +fn expand_appearance_moves_design_art_with_its_series_groups_effect() { + let (mut s, id, copy, _, _) = design_art(); + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + let group = series(&n, 0).id; + let shift = an_effect(&mut s, "distort.transform", json!({"moveH": 50})); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(group).unwrap().appearance.effects.push(shift); + let left = |s: &Session| { + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + series(&n, 0).children().unwrap()[0].geometric_bounds().unwrap().x0 + }; + let was = left(&s); + assert_eq!(series(&n, 0).children().unwrap()[0].id, copy); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("effect.expandAppearance", &json!({})).unwrap(); + assert!((left(&s) - was - 50.0).abs() < 1e-6, "{} then {}", was, left(&s)); +} + +/// The copies that a Transform effect of a series group makes of a design's art keep their own effects when Expand +/// Appearance bakes the series group's effect, as the art they copy does. +#[test] +fn expand_appearance_leaves_the_effects_of_design_art_copies() { + let (mut s, id, copy, _, _) = design_art(); + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + let group = series(&n, 0).id; + let shadow = an_effect(&mut s, "stylize.dropShadow", json!({})); + let copies = an_effect(&mut s, "distort.transform", json!({"moveH": 50, "copies": 2})); + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + doc.node_mut(copy).unwrap().appearance.effects.push(shadow); + doc.node_mut(group).unwrap().appearance.effects.push(copies); + let shadows = |s: &Session| { + let mut count = 0; + s.doc().unwrap().doc.node(id).unwrap().walk(&mut |m| count += m.appearance.effects.iter().filter(|e| e.id == "stylize.dropShadow").count()); + count + }; + let images = |s: &Session| s.doc().unwrap().doc.images.len(); + let before = images(&s); + assert_eq!(shadows(&s), 1); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("effect.expandAppearance", &json!({})).unwrap(); + assert_eq!(shadows(&s), 3, "the art and its two copies keep their shadows"); + assert_eq!(images(&s), before, "no shadow becomes an image"); +} + /// The commands that give rows, effects or graphic styles refuse the art of a graph design inside a series, given by /// id (the design's copy or a path inside it) or selected: the graph draws that art again from the design. #[test] @@ -1109,6 +1366,42 @@ fn aligned_effect_indices_past_the_end_of_a_graph_designs_art_are_refused() { assert!(rows(&s, mark).effects.is_empty()); } +/// With a graph design's art given first and `aligned: true`, `effect.remove` and `effect.duplicate` with `indices` are an +/// error and change nothing when one of the art's effects is one no other object has, as with that index given alone. +#[test] +fn aligned_effect_indices_of_a_graph_designs_art_that_no_object_has_are_refused() { + let rows = |s: &Session, id: NodeId| (*s.doc().unwrap().doc.node(id).unwrap().appearance).clone(); + let (mut s, _, art, mark) = aligned_design_art(); + // The art has a shadow and a roughen, the mark the shadow only. + s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "ids": [mark.0], "item": null})).unwrap(); + s.execute("effect.apply", &json!({"effect": "distort.roughen", "ids": [mark.0], "item": null})).unwrap(); + s.edit("Effects", |d, _| { + let effects = d.node(mark).unwrap().appearance.effects.clone(); + d.node_mut(art).unwrap().appearance.effects = effects; + d.node_mut(mark).unwrap().appearance.effects.pop(); + Ok(()) + }) + .unwrap(); + let (art_was, mark_was) = (rows(&s, art), rows(&s, mark)); + let steps = s.doc().unwrap().history.undo.len(); + for cmd in ["effect.remove", "effect.duplicate"] { + assert!(s.execute(cmd, &json!({"ids": [art.0, mark.0], "item": null, "index": 1, "aligned": true})).is_err(), "{cmd}"); + let e = s.execute(cmd, &json!({"ids": [art.0, mark.0], "item": null, "indices": [0, 1], "aligned": true})).unwrap_err(); + assert!(e.to_string().contains("no effects at indices 0, 1"), "{cmd}: {e}"); + assert_eq!((rows(&s, art), rows(&s, mark)), (art_was.clone(), mark_was.clone()), "{cmd}"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{cmd}"); + } + // With the roughen on the mark too, both of its effects are removed. + s.edit("Roughen", |d, _| { + let roughen = d.node(art).unwrap().appearance.effects[1].clone(); + d.node_mut(mark).unwrap().appearance.effects.push(roughen); + Ok(()) + }) + .unwrap(); + s.execute("effect.remove", &json!({"ids": [art.0, mark.0], "item": null, "indices": [0, 1], "aligned": true})).unwrap(); + assert!(rows(&s, mark).effects.is_empty()); +} + /// A blur on a series group makes the whole group an image, which draws the design's art with the series' other art: /// Expand Appearance does not put the art back beside the image. #[test] diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index b3fc65e8fc..522bd47817 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -1314,27 +1314,54 @@ pub(crate) fn file_hidden(path: &str, doc_path: Option<&str>) -> bool { /// gray or missing names none: the SVG writes gray pixels colorized and leaves out an image /// without pixels. The images of the art the SVG writes (opacity masks included) and of the /// symbols, patterns and brushes that art uses, as Copy follows them, are checked: the SVG writes -/// no other resource. Hidden layers and objects are written only with -/// SVG Options › hidden layers kept (`hidden`), and template layers never ([`svg_written`]). -/// Always `false` without read roots in force. -pub(crate) fn svg_names_hidden_image(d: &Document, base: LinkBase, link: bool, hidden: bool) -> bool { - if crate::file_access::current().is_none() || !names_hidden_image(d, base, link) { +/// no other resource. A placed document's images are those of the art the SVG draws for it. Hidden +/// layers and objects are written only with SVG Options › hidden layers kept (`hidden`), in the +/// layers and in the symbols, patterns and graph designs alike, and template layers never. SVG Tiny +/// 1.2 (`tiny`) writes no opacity masks ([`svg_written`]). Always `false` without read roots in +/// force. +pub(crate) fn svg_names_hidden_image(d: &Document, base: LinkBase, link: bool, hidden: bool, tiny: bool) -> bool { + if crate::file_access::current().is_none() { return false; } - let art = d.layers.iter().filter_map(|l| svg_written(l, hidden)).collect(); - names_hidden_image(&super::clipboard::Clipboard::gather(d, art).to_document(), base, link) + if !d.has_placed() && !names_hidden_image(d, base, link) { + return false; + } + // The writer draws placed documents' art with the pixels their files hold. + let placed = d.with_placed_art(); + let d = &*placed; + let art = d.layers.iter().filter_map(|l| svg_written(d, l, hidden, tiny)).collect(); + let mut out = super::clipboard::Clipboard::gather(d, art).to_document(); + let written = |n: &std::sync::Arc| { + let empty = || Node::new(n.id, NodeKind::Group { children: vec![], clip: false }); + std::sync::Arc::new(svg_written(d, n, hidden, tiny).unwrap_or_else(empty)) + }; + for s in &mut out.symbols { + s.art = written(&s.art); + } + for g in &mut out.graph_designs { + g.art = written(&g.art); + } + for p in &mut out.patterns { + p.art = p.art.iter().filter_map(|n| svg_written(d, n, hidden, tiny)).map(std::sync::Arc::new).collect(); + } + names_hidden_image(&out, base, link) } -/// `n` as the SVG writer writes it, or `None` when it writes none of it: a hidden layer or object -/// is left out unless `hidden`, a template layer's art always, and a disabled opacity mask's art. -/// Only layers and groups lose members; other objects keep theirs as they are. -fn svg_written(n: &Node, hidden: bool) -> Option { +/// `n` (an object of `d`) as the SVG writer writes it, or `None` when it writes none of it: a +/// hidden layer or object is left out unless `hidden`, a template layer's art always, a disabled +/// opacity mask's art, and with SVG Tiny 1.2 (`tiny`) every opacity mask's art. A placed document +/// is the art the writer draws for it. Only layers and groups lose members; other objects keep +/// theirs as they are. +fn svg_written(d: &Document, n: &Node, hidden: bool, tiny: bool) -> Option { if !(n.visible || hidden) { return None; } + if matches!(n.kind, NodeKind::PlacedDocument(_)) { + return svg_written(d, &vectorcraft_render::effects::expand_live_deep(Some(d), n), hidden, tiny); + } let mut n = n.clone(); - let mask = n.extras().mask.as_deref().filter(|m| !m.disabled).and_then(|m| { - let art = svg_written(&m.art, hidden)?; + let mask = n.extras().mask.as_deref().filter(|m| !m.disabled && !tiny).and_then(|m| { + let art = svg_written(d, &m.art, hidden, tiny)?; Some(Box::new(vectorcraft_doc::OpacityMask { art: std::sync::Arc::new(art), ..m.clone() })) }); if n.extras().mask.is_some() { @@ -1343,7 +1370,7 @@ fn svg_written(n: &Node, hidden: bool) -> Option { match &mut n.kind { NodeKind::Layer { template: true, children, .. } => children.clear(), NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => { - *children = children.iter().filter_map(|c| svg_written(c, hidden)).map(std::sync::Arc::new).collect(); + *children = children.iter().filter_map(|c| svg_written(d, c, hidden, tiny)).map(std::sync::Arc::new).collect(); } _ => {} } diff --git a/crates/engine/src/cmd/overprint.rs b/crates/engine/src/cmd/overprint.rs index 8149701334..e8957691ec 100644 --- a/crates/engine/src/cmd/overprint.rs +++ b/crates/engine/src/cmd/overprint.rs @@ -126,14 +126,18 @@ fn kinds(p: &Value, cmd: &str, keys: [&str; 2]) -> Result> { .collect() } -/// Each kind's item target and objects: (fill?, item, ids). -fn aims(s: &Session, p: &Value, cmd: &str, kinds: impl IntoIterator) -> Result)>> { +/// Each kind's item target and objects: (fill?, item, ids). With `edit`, the art of graph designs drawn in graph series +/// is left out, and an explicit item that the art left out has no row of that kind for is an error, as when the edit +/// resolves it on the other objects. Without it, the art is read with the other objects. +fn aims(s: &Session, p: &Value, cmd: &str, kinds: impl IntoIterator, edit: bool) -> Result)>> { let item = item_target(s, p, cmd)?; kinds .into_iter() .map(|fill| { let it = item.of_kind(s, fill); - Ok((fill, it, it.targets(s, p)?)) + let ids = it.targets(s, p)?; + let ids = if edit { super::appearance::drop_design_art_rows(s, ids, it, fill, cmd)? } else { ids }; + Ok((fill, it, ids)) }) .collect() } @@ -159,12 +163,7 @@ pub(super) type OverprintJob = ((bool, ItemTarget, Vec), bool); /// `object.setOverprint` aims, leaving out the art of graph designs drawn in graph series. pub(super) fn overprint_jobs(s: &Session, p: &Value, cmd: &str, keys: [&str; 2]) -> Result> { let kinds = kinds(p, cmd, keys)?; - let d = &s.doc()?.doc; - Ok(aims(s, p, cmd, kinds.iter().map(|k| k.0))? - .into_iter() - .map(|(fill, it, ids)| (fill, it, super::appearance::drop_design_art(d, ids))) - .zip(kinds.iter().map(|k| k.1)) - .collect()) + Ok(aims(s, p, cmd, kinds.iter().map(|k| k.0), true)?.into_iter().zip(kinds.iter().map(|k| k.1)).collect()) } /// Apply `jobs` to `d`, adding the objects changed to `changed`. @@ -203,7 +202,7 @@ fn attributes(s: &Session, p: &Value) -> Result { let d = &s.doc()?.doc; let mut info = AttributesInfo { ids: targets(s, p)?, recent_urls: s.recent_urls.clone(), ..Default::default() }; super::attributes::fill_info(d, &mut info); - for (fill, item, ids) in aims(s, p, C, [true, false])? { + for (fill, item, ids) in aims(s, p, C, [true, false], false)? { let mut all = ids.iter().filter_map(|id| d.node(*id)).filter_map(|n| Some(flags(n, fill, item.resolve(&n.appearance, fill, C).ok()?))).flatten(); let same = all.next().and_then(|first| all.all(|b| b == first).then_some(first)); diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 6370f8dbf9..967cf693a6 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -96,7 +96,7 @@ pub fn proxy_specs() -> Vec { "Invert", [], None, - "{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color of its characters and rows for every label of its kind (docs/mcp.md); no undo step when no color changes → {changed}", + "{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents and, except with target \"contents\", their own fills and strokes; a compound path's member stands for its compound path) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color of its characters and rows for every label of its kind (docs/mcp.md); no undo step when no color changes → {changed}", has_doc, |s, p| proxy_recolor(s, p, "paint.invert", "Invert", &super::colorcmds::invert) ), @@ -555,9 +555,15 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool) let ids = super::graph::paint_targets(&s.doc()?.doc, &selected); let of = super::appearance::reference_of(s, p, item, cmd)?; let paint = if span { - // With a design's art, the gradient spans only the objects with a row equal to the art's, which take it. - let spanned: Vec = ids.iter().zip(item.per_target_of(s, of, &ids)).filter_map(|(id, it)| it.map(|_| *id)).collect(); - placed_across(&s.doc()?.doc, &spanned, paint, p, fill) + // With a design's art, the gradient spans only the objects with a row equal to the art's, which take it. Each + // object's box is that of the row it edits. + let d = &s.doc()?.doc; + let mut spanned = Vec::with_capacity(ids.len()); + for (id, it) in ids.iter().zip(item.per_target_of(s, of, &ids)) { + let (Some(it), Some(n)) = (it, d.node(*id)) else { continue }; + spanned.push((*id, it.resolve(&n.appearance, fill, cmd)?)); + } + placed_across(d, &spanned, paint, p, fill) } else { paint }; @@ -730,14 +736,15 @@ fn spans_targets(p: &Value, paint: &Paint) -> std::result::Result Ok(true) } -/// `paint` placed once on the union of the bounds of `ids` (each one's fill box, or the box its -/// stroke paints), at the gradient's angle and aspect: every target gets the same vector in -/// document coordinates, so the ramp runs on across them (#2127). -fn placed_across(d: &Document, ids: &[NodeId], paint: Paint, p: &Value, fill: bool) -> Paint { +/// `paint` placed once on the union of the bounds of `ids` (each one's fill box, or the box the +/// stroke it edits paints: the row given with it, `None` for the topmost), at the gradient's angle +/// and aspect: every target gets the same vector in document coordinates, so the ramp runs on +/// across them (#2127). +fn placed_across(d: &Document, ids: &[(NodeId, Option)], paint: Paint, p: &Value, fill: bool) -> Paint { let union = ids .iter() - .filter_map(|id| d.node(*id)) - .filter_map(|n| item_paint_bounds(n, None, fill).or_else(|| n.geometric_bounds())) + .filter_map(|(id, index)| Some((d.node(*id)?, *index))) + .filter_map(|(n, index)| item_paint_bounds(n, index, fill).or_else(|| n.geometric_bounds())) .filter(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite())) .reduce(|a, b| a.union(b)); let (Some(union), Paint::Gradient(g)) = (union, &paint) else { return paint }; @@ -975,7 +982,13 @@ pub(super) fn restore_unpainted_stroke(ap: &mut Appearance, index: Option } fn swap(s: &mut Session, p: &Value) -> Result { - let ids = super::appearance::drop_design_art(&s.doc()?.doc, paint_targets(s, p)?); + let targets = paint_targets(s, p)?; + let given = !targets.is_empty(); + let ids = super::appearance::drop_design_art(&s.doc()?.doc, targets); + // Only design art was given or selected: nothing changes, the defaults included. + if given && ids.is_empty() { + return ok(); + } if !ids.is_empty() { // When every object comes out as it was, the document and its undo history stay as they are. let before = s.doc()?.doc.clone(); @@ -1010,7 +1023,13 @@ fn swap(s: &mut Session, p: &Value) -> Result { } fn default_paint(s: &mut Session, p: &Value) -> Result { - let ids = super::appearance::drop_design_art(&s.doc()?.doc, paint_targets(s, p)?); + let targets = paint_targets(s, p)?; + let given = !targets.is_empty(); + let ids = super::appearance::drop_design_art(&s.doc()?.doc, targets); + // Only design art was given or selected: nothing changes, the defaults included. + if given && ids.is_empty() { + return ok(); + } if !ids.is_empty() { // When every object comes out as it was, the document and its undo history stay as they are. let before = s.doc()?.doc.clone(); @@ -1079,10 +1098,26 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn( return Ok(json!({ "changed": changed as usize })); } let item = item_target(s, p, cmd)?.of_kind(s, !stroke); + // Read before the check below, so that a bad param (such as `target` or `aligned`, or an explicit `item` the art has + // no row for) is still an error. + let targets = super::appearance::drop_design_art_rows(s, item.targets(s, p)?, item, !stroke, cmd)?; + let of = match item { + ItemTarget::Item { .. } => super::appearance::reference_of(s, p, item, cmd)?, + ItemTarget::Top => None, + }; + // Read before the check below too: `targets` reads no `target` for the topmost fill or stroke. + let contents = super::appearance::targets_contents(p)?; + let ids = super::appearance::drop_design_art(&s.doc()?.doc, ids); + // Only design art was given or selected: nothing changes, the defaults and remembered colors included. + if ids.is_empty() { + return Ok(json!({ "changed": 0 })); + } let (r, shown_at) = match item { ItemTarget::Item { .. } => { - let targets = super::appearance::drop_design_art(&s.doc()?.doc, item.targets(s, p)?); - let of = super::appearance::reference_of(s, p, item, cmd)?; + // Only design art was given or selected: nothing changes, the remembered colors included. + if targets.is_empty() { + return Ok(json!({ "changed": 0 })); + } // The row shown is the one edited in the first object that has it: an aligned row maps to each object's equal row. let shown_at = super::appearance::first_edited(s, item, of, &targets).and_then(|(id, it)| match it { ItemTarget::Item { index, .. } => Some((id, Some(index))), @@ -1098,9 +1133,56 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn( (json!({ "changed": changed }), shown_at) } // The proxy recolors its paints, including a colorized image's fill, without changing image pixels or pattern tiles. + // A given group's own fills and strokes change with the objects inside it, except with `target: "contents"`; other + // objects change as their paint targets do (a compound path's member stands for the compound path). Design art + // inside a given graph or series group is left out. ItemTarget::Top => { - let q = json!({"fill": !stroke, "stroke": stroke, "includeImages": false, "includePatterns": false, "ids": ids.iter().map(|i| i.0).collect::>()}); - (super::colorcmds::recolor(s, &q, cmd, label, f)?, leaf_targets(s, &ids)?.first().map(|id| (*id, None))) + let mut roots = vec![]; + for id in &ids { + let n = s.doc()?.doc.node(*id); + let group = + !contents && n.is_some_and(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) && !n.is_compound_shape()); + if group { + roots.push(*id); + } else { + roots.extend(leaf_targets(s, &[*id])?); + } + } + let d = &s.doc()?.doc; + let mut seen = std::collections::HashSet::new(); + roots.retain(|id| seen.insert(*id)); + let roots = super::appearance::drop_design_art(d, roots); + if roots.is_empty() { + return Ok(json!({ "changed": 0 })); + } + let art = super::appearance::design_art_in(d, &roots).into_iter().collect(); + // The fill or stroke the proxy shows of each group among the roots, before the edit. + let own = |d: &Document, id: NodeId| { + d.node(id) + .filter(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. })) + .and_then(|n| n.proxy_paint_only(stroke, None)) + .cloned() + }; + let own_before: std::collections::HashMap = roots.iter().filter_map(|id| Some((*id, own(d, *id)?))).collect(); + let q = json!({"fill": !stroke, "stroke": stroke, "includeImages": false, "includePatterns": false, "ids": roots.iter().map(|i| i.0).collect::>()}); + let r = super::colorcmds::recolor_except(s, &q, cmd, label, f, art)?; + // As the proxy shows a group: its own fill or stroke when the edit changed it, else the first object inside it + // that is not design art (which keeps its paint). The first object given that has either shows it. + let d = &s.doc()?.doc; + let mut shown_at = None; + for id in &ids { + if let Some(was) = own_before.get(id) + && own(d, *id).as_ref() != Some(was) + { + shown_at = Some((*id, None)); + break; + } + if let Some(leaf) = super::appearance::drop_design_art(d, leaf_targets(s, &[*id])?).first() { + shown_at = Some((*leaf, None)); + break; + } + } + (r, shown_at) } }; // The paint remembered is one the edit recolored: a graph design's art that the item edit leaves out gives none. diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index 8f4e3c71f4..7062407c79 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -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), 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; a form other than \"default\" takes away their glyph choice), 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, down the column for an upright character in vertical type), diacriticHorizontal?, diacriticVertical?: 1/1000 em -1000..1000 (Character panel › Adjust Horizontal and Vertical Diacritic Position, with Show Indic Options, as text.setRangeStyle: the mark glyphs among the characters move right or up relative to their letters), 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; a form other than \"default\" takes away their glyph choice), 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\"|\"standardSingleLine\"|\"standardEveryLine\" (line breaking, Every-line by default; singleLine and everyLine are the Middle Eastern & South Asian composers, which shape Indic, Arabic and Hebrew type; the standard ones set it glyph by glyph as the font maps its characters, for legacy fonts that keep a script on Latin character codes), 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 ), @@ -255,7 +255,7 @@ pub(crate) fn artboard_indices(d: &vectorcraft_doc::Document, p: &Value, cmd: &s /// 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> { +pub(crate) 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"))); @@ -614,6 +614,8 @@ fn set_format(s: &mut Session, p: &Value) -> Result { "akiLeft", "akiRight", "tsume", + "diacriticHorizontal", + "diacriticVertical", "standardVerticalRoman", "noBreak", "digits", @@ -645,7 +647,9 @@ fn set_format(s: &mut Session, p: &Value) -> Result { Some(v) => Some(match v.as_str() { Some("singleLine") => Composer::SingleLine, Some("everyLine") => Composer::EveryLine, - _ => return Err(bad(C, "composer must be \"singleLine\" or \"everyLine\"")), + Some("standardSingleLine") => Composer::StandardSingleLine, + Some("standardEveryLine") => Composer::StandardEveryLine, + _ => return Err(bad(C, "composer must be \"singleLine\", \"everyLine\", \"standardSingleLine\" or \"standardEveryLine\"")), }), }; let (position, small_caps) = super::docsetup::script_params(p, &s.doc()?.doc.setup, C)?; @@ -661,6 +665,8 @@ fn set_format(s: &mut Session, p: &Value) -> Result { let aki_left = super::textedit::aki_param(p, "akiLeft", C)?; let aki_right = super::textedit::aki_param(p, "akiRight", C)?; let tsume = super::textedit::tsume_param(p, C)?; + let diacritic_horizontal = super::textedit::diacritic_param(p, "diacriticHorizontal", C)?; + let diacritic_vertical = super::textedit::diacritic_param(p, "diacriticVertical", C)?; let warichu_lines = super::textedit::warichu_lines_param(p, C)?; let warichu_gap = super::textedit::warichu_number_param(p, "warichuGap", C)?; let warichu_scale = super::textedit::warichu_number_param(p, "warichuScale", C)?; @@ -851,6 +857,8 @@ fn set_format(s: &mut Session, p: &Value) -> Result { if let Some(v) = tsume { st.tsume = v; } + st.diacritic_horizontal = diacritic_horizontal.unwrap_or(st.diacritic_horizontal); + st.diacritic_vertical = diacritic_vertical.unwrap_or(st.diacritic_vertical); if let Some(v) = flag("standardVerticalRoman") { st.standard_vertical_roman = v; } diff --git a/crates/engine/src/cmd/params.rs b/crates/engine/src/cmd/params.rs index fa9e9b2996..fdf7dd4b19 100644 --- a/crates/engine/src/cmd/params.rs +++ b/crates/engine/src/cmd/params.rs @@ -369,6 +369,12 @@ pub fn check_effect_params(id: &str, effect: &str, params: &Value) -> Result<()> { return Err(bad(id, "`origin` must be [x, y] in points")); } + if effect == vectorcraft_render::effects::SVG_FILTER + && let Some(axes) = given.get("axes") + && vectorcraft_render::effects::svg_filter::valid_axes(axes).is_none() + { + return Err(bad(id, "`axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0")); + } // Its name is the filter's id. if effect == vectorcraft_render::effects::SVG_FILTER && given.contains_key("name") && !given.contains_key("xml") { return Err(bad(id, "an SVG filter is named by its id: give `xml` with `name`")); diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index 0fb450fa43..4d160c7c49 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -5,7 +5,7 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_doc::{Document, Node, NodeId, NodeKind, Scaling, Selection}; -use vectorcraft_geom::{Anchor, AnchorKind, PathData, Point, SubPath, Vec2}; +use vectorcraft_geom::{Anchor, AnchorKind, Anchors, PathData, Point, SubPath, Vec2}; use super::create::anchor_from_json; use super::draw2::usize_opt; @@ -544,10 +544,12 @@ fn merge_coincident(sp: &mut SubPath, picked: impl Fn(usize) -> bool, join_kind: && before > 2 && picked(0) && picked(before - 1) - && let [first, .., last] = sp.anchors.as_mut_slice() - && same(first, last) + && let (Some(&first), Some(&last)) = (sp.anchors.first(), sp.anchors.last()) + && same(&first, &last) { - first.h_in = last.h_in; + if let Some(first) = sp.anchors.first_mut() { + first.h_in = last.h_in; + } sp.anchors.pop(); if let Some(smooth) = join_kind { join_point(sp, 0, smooth); @@ -565,10 +567,12 @@ fn merge_coincident(sp: &mut SubPath, picked: impl Fn(usize) -> bool, join_kind: for i in (1..len).rev() { if picked(i - 1) && picked(i) - && let Some([a, b]) = anchors.get_mut(i - 1..=i) - && same(a, b) + && let (Some(&a), Some(&b)) = (anchors.get(i - 1), anchors.get(i)) + && same(&a, &b) { - a.h_out = b.h_out; + if let Some(a) = anchors.get_mut(i - 1) { + a.h_out = b.h_out; + } if let Some(slot) = gone.get_mut(i) { *slot = true; } @@ -603,7 +607,7 @@ fn merge_coincident(sp: &mut SubPath, picked: impl Fn(usize) -> bool, join_kind: } /// [`join_point`] on anchor `ai` of `anchors` with its neighbors given by index. -fn join_point_between(anchors: &mut [Anchor], ai: usize, prev: Option, next: Option, smooth: bool) { +fn join_point_between(anchors: &mut Anchors, ai: usize, prev: Option, next: Option, smooth: bool) { let at = |j: Option| j.and_then(|j| anchors.get(j)).map(|a| a.p); let (prev, next) = (at(prev), at(next)); if let Some(a) = anchors.get_mut(ai) { @@ -1565,7 +1569,7 @@ enum Stretch { /// anchor, so the two handles of a smooth anchor stay in line with it. That share is below 0 or /// above 1 for a handle long enough beside the span. A closed subpath with no anchor that stays /// moves whole when it has a focal point. -fn stretch_weights(anchors: &[Anchor], closed: bool, roles: &[Stretch]) -> Vec<[f64; 3]> { +fn stretch_weights(anchors: &Anchors, closed: bool, roles: &[Stretch]) -> Vec<[f64; 3]> { let n = anchors.len(); let mut shares = vec![[0.0; 3]; n]; let role = |i: usize| match roles.get(i) { @@ -1891,10 +1895,10 @@ mod tests { && before > 2 && picked(0) && picked(before - 1) - && let [first, .., last] = sp.anchors.as_mut_slice() - && same(first, last) + && let (Some(&first), Some(&last)) = (sp.anchors.first(), sp.anchors.last()) + && same(&first, &last) { - first.h_in = last.h_in; + sp.anchors[0].h_in = last.h_in; sp.anchors.pop(); if let Some(smooth) = join_kind { join_point(sp, 0, smooth); @@ -1903,10 +1907,10 @@ mod tests { for i in (1..sp.anchors.len()).rev() { if picked(i - 1) && picked(i) - && let Some([a, b]) = sp.anchors.get_mut(i - 1..=i) - && same(a, b) + && let (Some(&a), Some(&b)) = (sp.anchors.get(i - 1), sp.anchors.get(i)) + && same(&a, &b) { - a.h_out = b.h_out; + sp.anchors[i - 1].h_out = b.h_out; sp.anchors.remove(i); if let Some(smooth) = join_kind { join_point(sp, i - 1, smooth); diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index 46231dcd0d..7a67773d0c 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -4,6 +4,10 @@ //! - A raster image becomes one image at 100% of its physical size: its pixels at the resolution //! the file declares ([`fileio::ppi`]; 72 ppi when it declares none), linked to its file with //! `link` ([`super::links`]). +//! - A PSD or PSB file placed with `layers` becomes one group of its layers as objects, embedded +//! ([`fileio::psd_layers`]); otherwise it is an image like any other, its merged image. An +//! embedded one brings its slices in as user slices, placed with its art (`importSlices`, +//! [`fileio::psd_slices`]). //! - An SVG becomes one group of its art; so does a DXF drawing, read with the DXF options //! (`dxf`, [`fileio::dxfimport`]), and an HP-GL plot file (`vectorcraft_cad::hpgl`). //! - An EMF, WMF or PICT picture becomes one group, clipped to its frame (`crop: "crop"`) or @@ -45,7 +49,7 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_color::Paint; -use vectorcraft_doc::{Appearance, Document, ImageObject, LinkInfo, Node, NodeId, NodeKind, PageBox, Scaling, SymbolBoxes}; +use vectorcraft_doc::{Appearance, Document, ImageObject, LinkInfo, Node, NodeId, NodeKind, PageBox, Scaling, SliceOptions, SymbolBoxes}; use vectorcraft_geom::{Affine, Point, Rect, shapes}; use vectorcraft_pdf::CropTo; @@ -67,6 +71,8 @@ const MAX_QUEUE: usize = 100; const MAX_THUMBNAIL: f64 = 512.0; /// A text file's natural box (`file.place.info`, the place cursor): a letter page less 1 in margins. const TEXT_FRAME: Rect = Rect::new(0.0, 0.0, 468.0, 648.0); +/// An encrypted PDF's box in the place cursor, which reads it without its password: a letter page. +const LOCKED_PAGE: Rect = Rect::new(0.0, 0.0, 612.0, 792.0); pub fn specs() -> Vec { vec![ @@ -75,7 +81,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, 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), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf and a PDF with several pages or a password and no page ask for those options first; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", + "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given; 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), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", has_doc, place ), @@ -84,7 +90,7 @@ pub fn specs() -> Vec { "Placed File Info", [], None, - "{path | name | dataBase64 (a file's path, or its name with its bytes), page?, crop?, password?, thumbnail?: px, link?: bool, dxf?: {…} (both as file.place)} what file.place would place, without placing it → {name, format, width, height (pt at 100%), pixelWidth?, pixelHeight?, ppi?: [x, y], colorMode?: RGB|Grayscale|CMYK (raster images), plates?: [ink names] (a DCS file), warnings, thumbnailBase64?: PNG of at most `thumbnail` (≤ 512) px on its longer side}", + "{path | name | dataBase64 (a file's path, or its name with its bytes), page?, crop?, password?, thumbnail?: px, link?: bool, dxf?: {…}, layers?, hiddenLayers?, importSlices? (all as file.place)} what file.place would place, without placing it → {name, format, width, height (pt at 100%), pixelWidth?, pixelHeight?, ppi?: [x, y], colorMode?: RGB|Grayscale|CMYK (raster images), plates?: [ink names] (a DCS file), slices?: the user slices a PSD or PSB file would bring in, warnings, thumbnailBase64?: PNG of at most `thumbnail` (≤ 512) px on its longer side}", always, info ), @@ -102,7 +108,7 @@ pub fn specs() -> Vec { "Load Place Cursor", [], None, - "{paths?: [path…], files?: [{name, dataBase64}…], link?, template?, page?, crop?, text?, dxf?, thumbnail?: px} load the place cursor (the `place` tool) with up to 100 files (as file.place reads them): a click places the current file at 100% with its top-left corner there, a drag places it at the dragged size (aspect kept), ←/→ and ↑/↓ cycle the files, Esc discards the current one; each placement is a file.place, and the previous tool returns after the last → {count, files: [{name, format, width, height, thumbnailBase64?}], skipped: [{name, error}]}", + "{paths?: [path…], files?: [{name, dataBase64}…], link?, template?, page?, crop?, text?, dxf?, layers?, hiddenLayers?, importSlices?, thumbnail?: px} load the place cursor (the `place` tool) with up to 100 files (as file.place reads them): a click places the current file at 100% with its top-left corner there, a drag places it at the dragged size (aspect kept), ←/→ and ↑/↓ cycle the files, Esc discards the current one; each placement is a file.place, and the previous tool returns after the last; an encrypted PDF, .ai or .ait file stays in the cursor at 612 × 792 pt (VectorCraft's own size) with needsPassword: true and no thumbnail, and a click on it in the app asks for its password (headless, its file.place fails for want of the password) → {count, files: [{name, format, width, height, thumbnailBase64?, needsPassword?}], skipped: [{name, error}]}", has_doc, queue ), @@ -148,16 +154,33 @@ struct Loaded { board: Option, } +/// A PSD or PSB file's slices, embedded with `importSlices`: their rectangles over the natural box +/// of its art, and their options. +type Slices = Vec<(Rect, SliceOptions)>; + /// Points per pixel of a raster image at the resolution it declares (72 ppi when none). pub(crate) fn pt_per_px(ppi: Option<(f64, f64)>) -> (f64, f64) { let (x, y) = ppi.unwrap_or((72.0, 72.0)); (72.0 / x, 72.0 / y) } +/// [`load_sliced`] without the slices. +fn load(p: &Value, cmd: &str, board: Option, link_pdf: bool) -> Result { + load_into(p, cmd, board, link_pdf, &mut vec![]) +} + +/// [`load_into`], with the slices of a PSD or PSB file that `importSlices` brings in. +fn load_sliced(p: &Value, cmd: &str, board: Option, link_pdf: bool) -> Result<(Loaded, Slices)> { + let mut slices = vec![]; + let l = load_into(p, cmd, board, link_pdf, &mut slices)?; + Ok((l, slices)) +} + /// The file `p` names, read into placeable art; a DXF drawing's Fit to Artboard fills `board` /// (unless the params name their own box). A PDF/.ai page read from a path is placed linked with -/// Link when `link_pdf` (false for the queries, which read it embedded). -fn load(p: &Value, cmd: &str, board: Option, link_pdf: bool) -> Result { +/// Link when `link_pdf` (false for the queries, which read it embedded). A PSD or PSB file's slices +/// go to `slices`. +fn load_into(p: &Value, cmd: &str, board: Option, link_pdf: bool, slices_out: &mut Slices) -> Result { let src = fileio::source(p, cmd)?; let name = fileio::file_name(src.name); // An Affinity file is recognised by its signature, whatever its name says. @@ -237,12 +260,52 @@ fn load(p: &Value, cmd: &str, board: Option, link_pdf: bool) -> Result match psd_groups(doc) { + Some((art, natural)) => { + *slices_out = psd_slices(slices_from, natural, &mut warnings); + return Ok(Loaded { name, format, art, natural, warnings, link: None, board: None }); + } + // No layer has art: the merged image, embedded. + None => unread = warnings, + }, + // No layers: the merged image, embedded. + Ok(None) => {} + Err(e) => unread.push(format!("the layers can't be read ({e}): the file was placed as its merged image")), + } + } + } if format.raster { let img = fileio::raster_image(&src.bytes)?; let (sx, sy) = pt_per_px(img.ppi); let natural = Rect::new(0.0, 0.0, img.width as f64 * sx, img.height as f64 * sy); - let link = src.path.map(|path| super::links::link_info(path, &src.bytes)); - let warnings = fileio::size_note(&img.blob.bytes).into_iter().collect(); + let link = src.path.filter(|_| !embed).map(|path| super::links::link_info(path, &src.bytes)); + let mut warnings: Vec = unread.into_iter().chain(fileio::size_note(&img.blob.bytes)).collect(); + *slices_out = psd_slices(slices_from, natural, &mut warnings); let clip = fileio::psdread::clipping_path(&src.bytes); return Ok(Loaded { name, format, art: Art::Image(img, clip), natural, warnings, link, board: None }); } @@ -303,6 +366,56 @@ fn load(p: &Value, cmd: &str, board: Option, link_pdf: bool) -> Result Option<(Art, Rect)> { + let canvas = doc.artboards.first()?.rect; + let nodes = psd_objects(&std::mem::take(&mut doc.layers)); + // Hidden layers count too: showing one later must not draw past the canvas. + let symbols = doc.symbol_boxes(); + let reached = nodes.iter().fold(None, |acc, n| vectorcraft_geom::union_opt(acc, reach(&symbols, n)))?; + let past = reached.union(canvas) != canvas; + Some((Art::Vector { src: Box::new(doc), nodes, clip: past.then_some(canvas) }, canvas)) +} + +/// The slices of the PSD or PSB file `bytes` (none without it) laid over `canvas`, the natural box +/// of its art; their warnings go to `warnings`. +fn psd_slices(bytes: Option<&[u8]>, canvas: Rect, warnings: &mut Vec) -> Slices { + let Some(bytes) = bytes else { return vec![] }; + let (slices, notes) = fileio::psd_slices(bytes, canvas); + warnings.extend(notes); + slices +} + +/// The bounds of `n` and every object inside it, hidden ones included. +fn reach(symbols: &SymbolBoxes, n: &Node) -> Option { + match n.children() { + Some(kids) => kids.iter().fold(None, |acc, k| vectorcraft_geom::union_opt(acc, reach(symbols, k))), + None => n.geometric_bounds_with(symbols), + } +} + +/// The layers a PSD import made as objects: a layer of sublayers as a group of them, and a layer +/// holding one image as that image, each with the layer's name, visibility, opacity, blend mode, +/// isolation and opacity mask. +fn psd_objects(layers: &[Arc]) -> Vec { + layers + .iter() + .map(|l| { + let mut n = (**l).clone(); + let NodeKind::Layer { children, .. } = &l.kind else { return n }; + n.kind = match &children[..] { + [c] if matches!(c.kind, NodeKind::Image(_)) => c.kind.clone(), + _ => NodeKind::Group { children: psd_objects(children).into_iter().map(Arc::new).collect(), clip: false }, + }; + n + }) + .collect() +} + /// Page `page` (1-based) of the PDF/.ai/.ait file `src` (`bytes`, read from `path` when there is /// one) as art to place: clipped to the box `opts.crop` names, or (`bounding`) the bounds of its /// art; read with `opts.password`. Only the page placed is read. A .ai saved without PDF @@ -548,6 +661,7 @@ pub struct PlaceJob { pub struct PlaceRead { job: PlaceJob, loaded: Loaded, + slices: Slices, } impl PlaceJob { @@ -562,7 +676,7 @@ impl PlaceJob { /// the renderers' image store for the first frame that draws them /// ([`super::links::readable_and_kept`]). pub fn read(self) -> Result { - let mut loaded = load(&self.params, PLACE, self.target, true)?; + let (mut loaded, slices) = load_sliced(&self.params, PLACE, self.target, true)?; let linked = loaded.link.is_some() && bool_or(&self.params, "link", true); match &mut loaded.art { Art::Image(img, _) => { @@ -572,7 +686,7 @@ impl PlaceJob { Art::Dcs(a) => a.img.blob = super::links::readable(a.img.blob.clone(), false, true)?, _ => {} } - Ok(PlaceRead { job: self, loaded }) + Ok(PlaceRead { job: self, loaded, slices }) } } @@ -653,7 +767,7 @@ fn prepare(s: &Session, p: &Value) -> Result { /// Place the file `read` holds in the active document. fn apply(s: &mut Session, read: PlaceRead) -> Result { - let PlaceRead { job: PlaceJob { params, old, target: read_for, .. }, mut loaded } = read; + let PlaceRead { job: PlaceJob { params, old, target: read_for, .. }, mut loaded, slices: read_slices } = read; let p = ¶ms; let template = bool_or(p, "template", false); let at = at_param(p)?; @@ -699,7 +813,22 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result { if let Art::Dcs(a) = &loaded.art { warnings.extend(dcs::swatch_notes(&st.doc, &a.spots)); } - let (id, size) = s.edit("Place", |d, sel| { + // A PSD file's slices move and scale with its art; one that would leave the canvas is left out. + let read_count = read_slices.len(); + let slices: Slices = read_slices + .into_iter() + .filter_map(|(r, o)| { + let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x0, r.y1), Point::new(r.x1, r.y1)].map(|c| m * c); + let placed = corners.iter().skip(1).fold(Rect::from_points(corners[0], corners[0]), |acc, c| acc.union_pt(*c)); + super::slices::slice_rect_ok(placed).then_some((placed, o)) + }) + .collect(); + match read_count - slices.len() { + 0 => {} + 1 => warnings.push("1 slice would lie outside the canvas and was left out".into()), + n => warnings.push(format!("{n} slices would lie outside the canvas and were left out")), + } + let (id, size, slice_ids) = s.edit("Place", |d, sel| { let node = transformed(build(d, loaded, link), m); let size = node.geometric_bounds_with(&d.symbol_boxes()).unwrap_or_default(); let (into, index) = match old { @@ -712,15 +841,19 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result { None => (parent, usize::MAX), }; let id = d.insert(into, index, node)?; + let slice_ids: Vec = slices.into_iter().map(|(r, o)| super::slices::add_slice(d, r, o).0).collect(); // Template art is locked: nothing to select. if template { sel.clear() } else { sel.set([id]) } - Ok((id, size)) + Ok((id, size, slice_ids)) })?; let mut out = json!({ "ids": [id.0], "name": name, "format": format, "linked": linked, "width": size.width(), "height": size.height(), "warnings": warnings }); + if !slice_ids.is_empty() { + out["slices"] = json!(slice_ids); + } // A DCS, PSD or PSB file clipped by its clipping path: its image, which the Links commands // take. if file_clipped { @@ -824,7 +957,7 @@ fn read_queue(doc: u64, p: Value, queued: Vec) -> Result { let thumbnail = p.get("thumbnail").and_then(Value::as_f64); let (mut entries, mut files, mut skipped) = (vec![], vec![], vec![]); for mut q in queued { - for k in ["link", "template", "page", "crop", "text", "dxf"] { + for k in ["link", "template", "page", "crop", "text", "dxf", "layers", "hiddenLayers", "importSlices"] { if let Some(v) = p.get(k) { q[k] = v.clone(); } @@ -857,6 +990,14 @@ fn read_queue(doc: u64, p: Value, queued: Vec) -> Result { } Err(e) => { let name = str_param(&q, "path").or(str_param(&q, "name")).map(fileio::file_name).unwrap_or_default(); + // An encrypted PDF stays, at a size of its own, so that a click in the app can ask + // for its password. + if let Some(format) = locked_pdf(&q, &e) { + let (w, h) = (LOCKED_PAGE.width(), LOCKED_PAGE.height()); + files.push(json!({ "name": name, "format": format, "width": w, "height": h, "needsPassword": true })); + entries.push(json!({ "params": q, "name": name, "width": w, "height": h })); + continue; + } skipped.push(json!({ "name": name, "error": e.to_string() })); } } @@ -864,13 +1005,29 @@ fn read_queue(doc: u64, p: Value, queued: Vec) -> Result { Ok(QueueRead { doc, params: p, entries, files, skipped }) } +/// The format id of the file `q` names when it is a PDF, `.ai` or `.ait` file (a path with one of +/// those extensions, as the app's password dialog reads it) that opens only with a password, and +/// reading it failed with `e` for want of that password (not for a bad option). +fn locked_pdf(q: &Value, e: &EngineError) -> Option<&'static str> { + if !e.to_string().contains(&vectorcraft_pdf::PdfError::NeedsPassword.to_string()) { + return None; + } + let src = fileio::source(q, QUEUE).ok()?; + if src.path.is_some() && !matches!(fileio::extension(src.name).as_str(), "pdf" | "ai" | "ait") { + return None; + } + let format = fileio::detect(src.name, &src.bytes)?; + let locked = matches!(vectorcraft_pdf::open_pdf(&src.bytes, None).map(|_| ()), Err(vectorcraft_pdf::PdfError::NeedsPassword)); + (matches!(format.id, "pdf" | "ai" | "ait") && locked).then_some(format.id) +} + impl Session { /// `file.place.queue`'s checks (with no document open, the error `file.place.queue` gives) of /// `params` → what reads the files ([`QueueJob::read`]; on the /// desktop the Place dialog's OK with several files does this off the UI thread). pub fn prepare_place_queue(&self, params: &Value) -> Result { has_doc(self).map_err(|why| EngineError::Disabled(QUEUE.into(), why))?; - check_switches(params, &["link", "template"], QUEUE)?; + check_switches(params, &["link", "template", "layers", "hiddenLayers", "importSlices"], QUEUE)?; check_numbers(params, &["thumbnail"], QUEUE)?; let files = queued_files(params)?; Ok(QueueJob { doc: self.doc()?.uid, params: params.clone(), files }) @@ -948,7 +1105,7 @@ pub fn read_info(p: &Value) -> Result { check_switches(p, &["link"], "file.place.info")?; check_numbers(p, &["thumbnail"], "file.place.info")?; // A PDF/.ai page linked or not has the same size and art. - let mut l = load(p, "file.place.info", None, false)?; + let (mut l, slices) = load_sliced(p, "file.place.info", None, false)?; let natural = l.natural; let mut out = json!({ "name": l.name, @@ -957,6 +1114,9 @@ pub fn read_info(p: &Value) -> Result { "height": natural.height(), "warnings": std::mem::take(&mut l.warnings), }); + if matches!(l.format.id, "psd" | "psb") { + out["slices"] = json!(slices.len()); + } if let Art::Image(img, _) = &l.art { let (x, y) = img.ppi.unwrap_or((72.0, 72.0)); out["pixelWidth"] = json!(img.width); diff --git a/crates/engine/src/cmd/place/docx.rs b/crates/engine/src/cmd/place/docx.rs index 063444442e..804e3fd6ae 100644 --- a/crates/engine/src/cmd/place/docx.rs +++ b/crates/engine/src/cmd/place/docx.rs @@ -38,7 +38,7 @@ use std::collections::HashMap; -use roxmltree::Node; +use craft_xml::{Canonical, Doctype, El, Limits, Names, Options}; use vectorcraft_doc::text::Kashida; use vectorcraft_doc::{CharPosition, CharStyle, Justify, ParaDirection, ParaStyle, ScriptMetrics, TextRun}; @@ -88,6 +88,7 @@ const MAX_RUNS: usize = 100_000; /// WordprocessingML's namespaces: Transitional, then Strict. const W: [&str; 2] = ["http://schemas.openxmlformats.org/wordprocessingml/2006/main", "http://purl.oclc.org/ooxml/wordprocessingml/main"]; +const DOCX_NS: Canonical<'static> = Canonical::new(&[("w", W[0]), ("w", W[1])]); /// Is the file `name` with `bytes` a Word document: a ZIP archive named `.docx`, or one that holds /// `word/document.xml`? @@ -104,7 +105,7 @@ pub(super) fn import(bytes: &[u8], cmd: &str) -> Result { let main = relationship(&zip, "", "officeDocument", cmd)?.unwrap_or_else(|| "word/document.xml".into()); let Some(xml) = part(&zip, &main, cmd)? else { return Err(bad(cmd, "not a Word document: its package has no main document part")) }; let doc = parse(&xml, &main, cmd)?; - if local(doc.root_element()) != Some("document") { + if local(&doc) != Some("document") { return Err(bad(cmd, "not a Word document: its main part is not a WordprocessingML document")); } let folder = main.rfind('/').and_then(|i| main.get(..=i)).unwrap_or_default(); @@ -117,7 +118,7 @@ pub(super) fn import(bytes: &[u8], cmd: &str) -> Result { if let Some(xml) = part(&zip, &styles, cmd)? { r.styles(&parse(&xml, &styles, cmd)?); } - if let Some(body) = doc.root_element().children().find(|n| local(*n) == Some("body")) { + if let Some(body) = child(&doc, "body") { r.block(body, 0); } r.finish(cmd) @@ -158,57 +159,21 @@ fn part(zip: &Archive, name: &str, cmd: &str) -> Result> { } /// The XML of the part `name`. -fn parse<'a>(xml: &'a str, name: &str, cmd: &str) -> Result> { - // roxmltree parses nested elements recursively. - if nesting(xml) > MAX_NESTING { - return Err(bad(cmd, format!("`{name}` in the Word document nests elements more than {MAX_NESTING} deep"))); +fn parse(xml: &str, name: &str, cmd: &str) -> Result { + let opts = Options { + names: Names::Canonical(&DOCX_NS), + doctype: Doctype::Reject, + limits: Limits { max_depth: MAX_NESTING, max_nodes: MAX_NODES as usize, ..Limits::DEFAULT }, + ..Options::default() } - let opts = roxmltree::ParsingOptions { nodes_limit: MAX_NODES, ..roxmltree::ParsingOptions::default() }; - roxmltree::Document::parse_with_options(xml, opts).map_err(|e| bad(cmd, format!("`{name}` in the Word document is not well-formed XML: {e}"))) -} - -/// How deep the elements of `xml` nest: start tags less end tags, at most, outside comments, -/// CDATA sections, processing instructions, declarations and quoted attribute values. -pub(crate) fn nesting(xml: &str) -> usize { - let b = xml.as_bytes(); - let (mut depth, mut most, mut i) = (0usize, 0usize, 0usize); - // The index just past the first `end` at or after `from` (the end of the text if none). - let past = |from: usize, end: &[u8]| { - b.get(from..).and_then(|rest| rest.windows(end.len()).position(|w| w == end)).map_or(b.len(), |at| from + at + end.len()) - }; - while let Some(at) = b.get(i..).and_then(|rest| rest.iter().position(|&c| c == b'<')) { - let start = i + at; - let rest = b.get(start..).unwrap_or_default(); - if rest.starts_with(b""); - } else if rest.starts_with(b""); - } else if rest.starts_with(b""); - } else if rest.starts_with(b""); - } else { - // A start tag: up to its `>` outside quotes; `/>` closes it at once. - let mut j = start + 1; - let mut quote = None; - while let Some(&c) = b.get(j) { - match (quote, c) { - (None, b'"' | b'\'') => quote = Some(c), - (Some(q), _) if c == q => quote = None, - (None, b'>') => break, - _ => {} - } - j += 1; - } - if b.get(j.saturating_sub(1)) != Some(&b'/') { - depth += 1; - most = most.max(depth); - } - i = j + 1; - } - } - most + .strict(); + let doc = opts.parse(xml.as_bytes()).map_err(|e| match e { + craft_xml::Error::TooDeep(_) => bad(cmd, format!("`{name}` in the Word document nests elements more than {MAX_NESTING} deep")), + _ => bad(cmd, format!("`{name}` in the Word document is not well-formed XML: {e}")), + })?; + crate::cmd::xmlattrs::validate(xml.as_bytes(), opts.limits) + .map_err(|e| bad(cmd, format!("`{name}` in the Word document is not well-formed XML: {e}")))?; + Ok(doc) } /// The part that the first relationship of part `source` (`""`: the package) whose type ends in @@ -220,11 +185,10 @@ fn relationship(zip: &Archive, source: &str, kind: &str, cmd: &str) -> Result String { } /// `n`'s local name when it is a WordprocessingML element. -fn local<'a>(n: Node<'a, '_>) -> Option<&'a str> { - (n.is_element() && n.tag_name().namespace().is_some_and(|ns| W.contains(&ns))).then(|| n.tag_name().name()) +fn local(n: &El) -> Option<&str> { + n.name.strip_prefix("w:") } /// `n`'s first WordprocessingML child element named `name`. -fn child<'a, 'i>(n: Node<'a, 'i>, name: &str) -> Option> { - n.children().find(|c| local(*c) == Some(name)) +fn child<'a>(n: &'a El, name: &str) -> Option<&'a El> { + n.elements().find(|c| local(c) == Some(name)) } /// `n`'s WordprocessingML attribute `name`. -fn attr<'a>(n: Node<'a, '_>, name: &str) -> Option<&'a str> { - n.attributes().find(|a| a.name() == name && a.namespace().is_some_and(|ns| W.contains(&ns))).map(|a| a.value()) +fn attr<'a>(n: &'a El, name: &str) -> Option<&'a str> { + n.attrs.iter().find_map(|(k, v)| k.strip_prefix("w:").filter(|&l| l == name).map(|_| v.as_str())) } /// An on/off property (ST_OnOff): on unless `w:val` is `false`, `0` or `off`. -fn on(n: Node) -> bool { +fn on(n: &El) -> bool { !matches!(attr(n, "val"), Some("false" | "0" | "off")) } @@ -280,12 +244,12 @@ fn measure(v: &str, per_pt: f64) -> Option { } /// Twentieths of a point. -fn twips(n: Node, name: &str) -> Option { +fn twips(n: &El, name: &str) -> Option { attr(n, name).and_then(|v| measure(v, 20.0)) } /// Half points. -fn half_points(n: Node) -> Option { +fn half_points(n: &El) -> Option { attr(n, "val").and_then(|v| measure(v, 2.0)) } @@ -462,21 +426,21 @@ struct Reader { impl Reader { /// The major and minor fonts of a theme part's font scheme. - fn theme_fonts(&mut self, doc: &roxmltree::Document) { + fn theme_fonts(&mut self, doc: &El) { for (slot, scheme) in self.theme.iter_mut().zip(["majorFont", "minorFont"]) { - *slot = doc - .descendants() - .find(|n| n.tag_name().name() == scheme) - .and_then(|n| n.children().find(|c| c.tag_name().name() == "latin")) - .and_then(|n| n.attribute("typeface")) + *slot = std::iter::once(doc) + .chain(doc.descendants()) + .find(|n| n.local() == scheme) + .and_then(|n| n.elements().find(|c| c.local() == "latin")) + .and_then(|n| n.attr("typeface")) .map(font_name) .filter(|f| !f.is_empty()); } } /// The document defaults and the styles of the styles part. - fn styles(&mut self, doc: &roxmltree::Document) { - for n in doc.root_element().children() { + fn styles(&mut self, doc: &El) { + for n in doc.elements() { match local(n) { Some("docDefaults") => { let props = |outer: &str, inner: &str| child(n, outer).and_then(|d| child(d, inner)); @@ -526,7 +490,7 @@ impl Reader { } /// The number of the font a `w:rFonts` element names. - fn font(&mut self, n: Node) -> Option { + fn font(&mut self, n: &El) -> Option { let theme = |v: &str| self.theme.get(usize::from(v.starts_with("minor"))).and_then(Option::as_deref); let name = attr(n, "asciiTheme") .and_then(theme) @@ -549,9 +513,9 @@ impl Reader { } /// The run properties of a `w:rPr` element. - fn run_props(&mut self, rpr: Node) -> RunProps { + fn run_props(&mut self, rpr: &El) -> RunProps { let mut p = RunProps::default(); - for n in rpr.children() { + for n in rpr.elements() { match local(n) { Some("rFonts") => p.font = self.font(n), Some("b") => p.bold = Some(on(n)), @@ -594,11 +558,11 @@ impl Reader { } /// The paragraphs, tables and containers of them that are `n`'s children. - fn block(&mut self, n: Node, depth: usize) { + fn block(&mut self, n: &El, depth: usize) { if depth > MAX_DEPTH { return; } - for c in n.children() { + for c in n.elements() { if self.full { return; } @@ -617,7 +581,7 @@ impl Reader { } /// A table: each row a paragraph, its cells separated by tabs. - fn table(&mut self, tbl: Node, depth: usize) { + fn table(&mut self, tbl: &El, depth: usize) { for row in items(tbl, "tr", depth) { for cell in items(row, "tc", depth) { self.flush(); @@ -638,7 +602,7 @@ impl Reader { } /// A paragraph. - fn paragraph(&mut self, p: Node, depth: usize) { + fn paragraph(&mut self, p: &El, depth: usize) { self.flush(); let ppr = child(p, "pPr"); let style = ppr @@ -675,11 +639,11 @@ impl Reader { } /// The runs of a paragraph, and the containers of runs in it. - fn inline(&mut self, n: Node, depth: usize) { + fn inline(&mut self, n: &El, depth: usize) { if depth > MAX_DEPTH { return; } - for c in n.children() { + for c in n.elements() { match local(c) { Some("r") => self.run(c), Some("hyperlink" | "ins" | "moveTo" | "smartTag" | "customXml" | "fldSimple" | "dir" | "bdo") => self.inline(c, depth + 1), @@ -694,7 +658,7 @@ impl Reader { } /// A run. - fn run(&mut self, r: Node) { + fn run(&mut self, r: &El) { let rpr = child(r, "rPr"); let mut chars = self.base; let style = rpr @@ -709,11 +673,10 @@ impl Reader { let props = self.run_props(n); chars.apply(&props, false); } - for c in r.children() { + for c in r.elements() { match local(c) { Some("t") => { - // Comments and processing instructions may split the text. - for ch in c.children().filter(|n| n.is_text()).filter_map(|n| n.text()).flat_map(str::chars) { + for ch in c.text().chars() { self.put(ch, chars); } } @@ -907,9 +870,9 @@ fn font_name(name: &str) -> String { } /// The paragraph properties of a `w:pPr` element. -fn para_props(ppr: Node) -> ParaProps { +fn para_props(ppr: &El) -> ParaProps { let mut p = ParaProps::default(); - for n in ppr.children() { + for n in ppr.elements() { match local(n) { Some("jc") => { p.align = match attr(n, "val") { @@ -945,12 +908,12 @@ fn para_props(ppr: Node) -> ParaProps { } /// `n`'s children named `name`, and those inside content controls and custom XML among them. -fn items<'a, 'i>(n: Node<'a, 'i>, name: &str, depth: usize) -> Vec> { +fn items<'a>(n: &'a El, name: &str, depth: usize) -> Vec<&'a El> { let mut out = vec![]; if depth > MAX_DEPTH { return out; } - for c in n.children() { + for c in n.elements() { match local(c) { Some(l) if l == name => out.push(c), Some("sdt") => { @@ -979,15 +942,6 @@ mod tests { assert_eq!(measure("wide", 20.0), None); } - #[test] - fn nesting_counts_elements_outside_markup_that_is_not_an_element() { - assert_eq!(nesting(r#"]]>"#), 2); - assert_eq!(nesting(""), 3, "unclosed elements count"); - assert_eq!(nesting(""), 1); - assert_eq!(nesting(" bool { let live = filters && pixels == 1 && effects::svg_filter::writes_live(&n.appearance.effects) - && fx.iter().any(|f| matches!(f, RasterFx::Pixel(effects::PixelFx::Svg(s)) if s.in_points() && (!s.measured() || fx.len() == 1) && s.writes_as_svg11())); + && fx + .iter() + .any(|f| matches!(f, RasterFx::Pixel(effects::PixelFx::Svg(s)) if (!s.measured() || fx.len() == 1) && s.writes_as_svg11() && s.opens_again())); (pixels > 0 && !live) || (fx.iter().any(|f| matches!(f, RasterFx::DropShadow { darkness: Some(_), .. })) && (cmyk || !simple_rgb_shadow_source(n, &fx))) } diff --git a/crates/engine/src/cmd/select.rs b/crates/engine/src/cmd/select.rs index 4e65de6660..e5fa5f75b3 100644 --- a/crates/engine/src/cmd/select.rs +++ b/crates/engine/src/cmd/select.rs @@ -8,9 +8,10 @@ use vectorcraft_doc::{Document, LockedArtboards, Node, NodeId, NodeKind}; use vectorcraft_tools::builder::is_live_paint; use super::object::can_align; +use super::panelcmds::artboard_at; use super::wand::{fill_of, stroke_of}; use super::{ - CommandSpec, Result, Session, bad, bool_or, checked_id, checked_ids_param, cmd, color_value, has_doc, has_selection, index, ok, str_param, + CommandSpec, Result, Session, bad, bool_or, checked_id, checked_ids_param, cmd, color_value, has_doc, has_selection, index_opt, ok, str_param, switch_or, text_param, }; use crate::DocState; @@ -31,7 +32,7 @@ pub fn specs() -> Vec { "All on Active Artboard", ["Select"], Some("Cmd+Alt+A"), - "{artboard?: index (0-based; the app passes the active one; default: the first)}", + "{artboard?: index (0-based whole number; the app passes the active one; default, or null: the first)}", has_doc, all_on_artboard ), @@ -229,7 +230,7 @@ pub fn specs() -> Vec { "Appearance Attribute", ["Select", "Same"], None, - "{item?: appearance item index} the objects sharing an appearance attribute of the first selected object: its fill or stroke `item` (default: the Appearance panel's active item), else its first effect, else its topmost fill (compound paths as select.same.fillColor)", + "{item?: appearance item index (0-based whole number; default, or null: the Appearance panel's active item)} the objects sharing an appearance attribute of the first selected object: its fill or stroke `item` (default: the Appearance panel's active item), else its first effect, else its topmost fill (compound paths as select.same.fillColor)", has_selection, same_attribute ), @@ -428,7 +429,7 @@ fn all(s: &mut Session, _: &Value) -> Result { fn all_on_artboard(s: &mut Session, p: &Value) -> Result { let st = s.doc()?; - let i = p.get("artboard").and_then(Value::as_u64).map_or(0, index); + let i = artboard_at(&st.doc, p, "artboard", "select.allOnArtboard")?.unwrap_or(0); let r = st.doc.artboards.get(i).map(|a| a.rect).ok_or_else(|| bad("select.allOnArtboard", "no such artboard"))?; let symbols = st.doc.symbol_boxes(); let ids: Vec = @@ -1217,10 +1218,10 @@ enum Attribute { fn same_attribute(s: &mut Session, p: &Value) -> Result { let cmd = "select.same.appearanceAttribute"; + let item = index_opt(p, "item", cmd)?.or(s.appearance_item()); let st = s.doc()?; let (refn, _) = same_reference(st, cmd)?; let ap = &refn.appearance; - let item = p.get("item").and_then(Value::as_u64).map(index).or(s.appearance_item()); let attr = match (item.and_then(|i| ap.items.get(i)), ap.effects.first()) { (Some(it), _) => Attribute::Item(it.clone()), (None, Some(e)) => Attribute::Effect(e.clone()), diff --git a/crates/engine/src/cmd/stroke.rs b/crates/engine/src/cmd/stroke.rs index 09ae0b8e41..7cfa020a12 100644 --- a/crates/engine/src/cmd/stroke.rs +++ b/crates/engine/src/cmd/stroke.rs @@ -234,8 +234,11 @@ fn stroke_set(s: &mut Session, p: &Value) -> Result { let item = item_target(s, p, C)?.of_kind(s, false); let mut ids = if item == ItemTarget::Top { own_stroke_or_leaves(s, p)? } else { item.targets(s, p)? }; let new_art = no_targets(&ids, p); + let given = !ids.is_empty(); // The art of a graph design in a series keeps the design's stroke. - ids = super::appearance::drop_design_art(&s.doc()?.doc, ids); + ids = super::appearance::drop_design_art_rows(s, ids, item, false, C)?; + // With only design art, the weight for new art stays as it is too. + let only_design_art = given && ids.is_empty(); if item == ItemTarget::Top { // Images and symbol instances take no stroke from the panel. let d = &s.doc()?.doc; @@ -329,7 +332,9 @@ fn stroke_set(s: &mut Session, p: &Value) -> Result { })?; // Commit the new-art template only after the complete request is validated // and the selected artwork edit has succeeded. - if let Some(w) = change.weight { + if let Some(w) = change.weight + && !only_design_art + { s.paint.stroke_width = w; } if new_art && let Some(st) = s.new_art_stroke_mut() { @@ -372,7 +377,7 @@ fn stroke_step(s: &mut Session, p: &Value, up: bool) -> Result { } return Ok(json!({"objects": 0})); } - let ids = super::appearance::drop_design_art(&s.doc()?.doc, ids); + let ids = super::appearance::drop_design_art_rows(s, ids, item, false, c)?; let label = if up { "Stroke Weight Up" } else { "Stroke Weight Down" }; edit_items(s, &ids, item, None, c, label, false, |n, index| { if index.is_none() @@ -517,7 +522,7 @@ fn stroke_advanced(s: &mut Session, p: &Value) -> Result { let ids = item.targets(s, p)?; let new_art = no_targets(&ids, p); // The art of a graph design in a series keeps the design's stroke. - let ids = super::appearance::drop_design_art(&s.doc()?.doc, ids); + let ids = super::appearance::drop_design_art_rows(s, ids, item, false, C)?; let arrows_and_profile = |st: &mut StrokeLayer| { if let Some(sc) = scale { st.arrow_scale = sc; diff --git a/crates/engine/src/cmd/swatch.rs b/crates/engine/src/cmd/swatch.rs index 3388b8344b..a42cc134ed 100644 --- a/crates/engine/src/cmd/swatch.rs +++ b/crates/engine/src/cmd/swatch.rs @@ -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} 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}", + "{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). A fold line role the swatch carries (addon.packaging.roles) stays with it under its new name, and moves to a new swatch name when Global is turned off. 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 ), @@ -93,7 +93,7 @@ pub fn specs() -> Vec { "Merge Swatches", ["Window", "Swatches"], None, - "{names: [two or more solid-colour swatches], name?: the merged swatch's name (one swatch kept)} keep the first (its name and colour) and delete the others; paints linked to them take its colour and link to it (or unlink when it isn't global), as one undo step → {name, merged: [deleted names], relinked}", + "{names: [two or more solid-colour swatches], name?: the merged swatch's name (one swatch kept)} keep the first (its name and colour) and delete the others; paints linked to them take its colour and link to it (or unlink when it isn't global), and gradient stops linked to them drop their process plates, as one undo step. When the kept swatch is global and carries no fold line role (addon.packaging.roles), it takes the role of the first merged swatch that carried one → {name, merged: [deleted names], relinked}", has_doc, swatch_merge ), @@ -688,6 +688,11 @@ impl Relink { /// batch, and a canceled batch preview, put back the paints the batch started with. A change is /// recorded with the step just made, so Undo and Redo put these paints back with the document. pub(super) fn map_default_paints(s: &mut Session, f: &mut LinkFn) -> Result<()> { + map_default_paints_by(s, &mut |p| p.map_links(f)) +} + +/// [`map_default_paints`] with `f` applied to each whole paint; `f` returns true when it changed it. +fn map_default_paints_by(s: &mut Session, f: &mut dyn FnMut(&mut Paint) -> bool) -> Result<()> { if s.in_interaction() && s.batch_stash.is_none() { return Ok(()); } @@ -699,7 +704,7 @@ pub(super) fn map_default_paints(s: &mut Session, f: &mut LinkFn) -> Result<()> }); let mut changed = false; for p in [&mut pd.fill, &mut pd.stroke].into_iter().chain(template) { - changed |= p.map_links(f); + changed |= f(p); } if changed { super::colormgmt::record_new_art_colors(s, start)?; @@ -932,6 +937,8 @@ fn swatch_edit(s: &mut Session, p: &Value) -> Result { } } let relinked = map_swatch_links(d, &mut |c, l, t| relink.apply(c, l, t)); + // A fold line role carried by the swatch follows its new name, as the strokes do. + super::addons::role_swatch_edited(d, &name, &to, global); super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(C, e))?; Ok(relinked) })?; @@ -1124,17 +1131,39 @@ fn swatch_merge(s: &mut Session, p: &Value) -> Result { *l = link.clone(); true }; + // A stop linked to a merged swatch loses its process plates, which printed with that ink. + let mut unplate = |p: &Paint| { + let mut q = p.clone(); + drop_stop_plates(&mut q, &merged_names).then_some(q) + }; let colorized_ok = super::paint::check_colorized(d).is_ok(); let relinked = s.edit("Merge Swatches", |d, _| { take_swatches(d, merged, |_| true); + map_all_paints(d, &mut unplate); let relinked = map_swatch_links(d, &mut relink); + // The lines of a merged role swatch link to the kept swatch, which takes that role. + super::addons::role_swatches_merged(d, merged, keep, link.is_some()); super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(C, e))?; Ok(relinked) })?; - map_default_paints(s, &mut relink)?; + map_default_paints_by(s, &mut |p| { + let unplated = drop_stop_plates(p, &merged_names); + p.map_links(&mut relink) | unplated + })?; Ok(json!({"name": keep, "merged": merged, "relinked": relinked})) } +/// Clear the process plates of `p`'s gradient stops linked to a swatch in `names`. True when any +/// stop had plates. +fn drop_stop_plates(p: &mut Paint, names: &HashSet<&str>) -> bool { + let Paint::Gradient(g) = p else { return false }; + g.gradient + .stops + .iter_mut() + .filter(|st| st.swatch.as_deref().is_some_and(|l| names.contains(l))) + .fold(false, |ch, st| st.plates.take().is_some() | ch) +} + fn swatch_ungroup(s: &mut Session, p: &Value) -> Result { const C: &str = "swatch.ungroup"; let name = str_param(p, "name").ok_or_else(|| bad(C, "missing `name`"))?.to_string(); diff --git a/crates/engine/src/cmd/symbollib.rs b/crates/engine/src/cmd/symbollib.rs index 7ddc6e4bb2..63096c9d98 100644 --- a/crates/engine/src/cmd/symbollib.rs +++ b/crates/engine/src/cmd/symbollib.rs @@ -384,7 +384,7 @@ fn weather_icons() -> SymbolLibrary { Anchor { p: Point::new(5.0, 16.0), h_in: Point::new(-6.0, 16.0), h_out: Point::new(0.0, 8.0), kind: AnchorKind::Corner }, Anchor { p: Point::new(-4.0, -1.0), h_in: Point::new(-4.0, 6.0), h_out: Point::new(-4.0, -8.0), kind: AnchorKind::Smooth }, ]; - let moon = PathData::single(SubPath { anchors: moon_anchors, closed: true }); + let moon = PathData::single(SubPath::new(moon_anchors, true)); // Helper for cloud contour let cloud_subpath = |offset_y: f64, scale: f64| -> SubPath { diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index 769ca7e6c5..4f3b814760 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; \"hkna\" is H or V Style, kana in the font's forms for the writing direction, shaped as `vkna` in vertical type, and \"ital\" is Roman Italics, half-width alphanumerics in the font's italic forms, both on or off only; 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; a form other than \"default\" takes away the characters' glyph choice (text.setGlyphAlternate); with fullWidth, halfWidth, thirdWidth or quarterWidth, proportionalMetrics is kept but `palt` is not applied, and the font's pair kerning is turned off; 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)}", + "{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; \"hkna\" is H or V Style, kana in the font's forms for the writing direction, shaped as `vkna` in vertical type, and \"ital\" is Roman Italics, half-width alphanumerics in the font's italic forms, both on or off only; 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, the glyph keeping its shape; 100 sets the ink edge to edge; a color glyph's ink is its color art or bitmap; 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; in vertical type an upright character is measured above and below its ink inside its cell down the column, a character lying on its side along its own width, and a tate-chu-yoko block's characters across the column, the block keeping its one em; 0 by default; a value that is not a number or is outside the range is refused), diacriticHorizontal?, diacriticVertical?: 1/1000 em -1000..1000 (Character panel › Adjust Horizontal and Vertical Diacritic Position, with Show Indic Options: the font's mark glyphs among the characters, those its GDEF table classes as marks such as Arabic harakat and Hebrew points, move right by a positive horizontal value and up by a positive vertical one, relative to their letters, in thousandths of the size; a harakat or Hebrew point styled apart from its letter takes its own values and stays attached to it, and another mark takes its letter's; letters and fonts without mark classes do not move; 0 by default; a value that is not a number or is outside the range is refused, naming the key), 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; a form other than \"default\" takes away the characters' glyph choice (text.setGlyphAlternate); with fullWidth, halfWidth, thirdWidth or quarterWidth, proportionalMetrics is kept but `palt` is not applied, and the font's pair kerning is turned off; 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 ), @@ -470,6 +470,9 @@ pub(crate) struct CharChange { aki_right: Option, /// Tsume, in percent. tsume: Option, + /// Adjust Horizontal and Vertical Diacritic Position, in 1/1000 em. + diacritic_horizontal: Option, + diacritic_vertical: Option, standard_vertical_roman: Option, no_break: Option, digits: Option, @@ -548,6 +551,16 @@ pub(crate) fn aki_param(p: &Value, key: &str, cmd: &str) -> Result> if (lo..=hi).contains(&v) { Ok(Some(v)) } else { Err(bad(cmd, format!("`{key}` must be from {lo} to {hi}"))) } } +/// `diacriticHorizontal` or `diacriticVertical` (Adjust Horizontal and Vertical Diacritic +/// Position): a number of thousandths of an em within +/// [`vectorcraft_doc::text::MAX_DIACRITIC_POSITION`] either way. Any other value is an error. +pub(crate) fn diacritic_param(p: &Value, key: &str, cmd: &str) -> Result> { + let Some(v) = p.get(key).filter(|v| !v.is_null()) else { return Ok(None) }; + let v = v.as_f64().filter(|v| v.is_finite()).ok_or_else(|| bad(cmd, format!("`{key}` must be a number")))?; + let (lo, hi) = (-vectorcraft_doc::text::MAX_DIACRITIC_POSITION, vectorcraft_doc::text::MAX_DIACRITIC_POSITION); + if (lo..=hi).contains(&v) { Ok(Some(v)) } else { Err(bad(cmd, format!("`{key}` must be from {lo} to {hi}"))) } +} + /// `tsume` (Tsume): a percentage from 0 to [`vectorcraft_doc::text::MAX_TSUME`]. Any other value is /// an error. pub(crate) fn tsume_param(p: &Value, cmd: &str) -> Result> { @@ -852,6 +865,8 @@ impl CharChange { aki_left: aki_param(p, "akiLeft", cmd)?, aki_right: aki_param(p, "akiRight", cmd)?, tsume: tsume_param(p, cmd)?, + diacritic_horizontal: diacritic_param(p, "diacriticHorizontal", cmd)?, + diacritic_vertical: diacritic_param(p, "diacriticVertical", cmd)?, standard_vertical_roman: flag("standardVerticalRoman"), no_break: flag("noBreak"), digits: digits_param(p, cmd)?, @@ -918,6 +933,8 @@ impl CharChange { && self.aki_left.is_none() && self.aki_right.is_none() && self.tsume.is_none() + && self.diacritic_horizontal.is_none() + && self.diacritic_vertical.is_none() && self.standard_vertical_roman.is_none() && self.no_break.is_none() && self.digits.is_none() @@ -963,7 +980,8 @@ impl CharChange { } } - /// The character alignment, direction and East Asian settings of [`Self::apply`]. + /// The character alignment, direction, diacritic positions and East Asian settings of + /// [`Self::apply`]. fn apply_cjk(&self, st: &mut CharStyle) { if let Some(v) = self.char_align { st.char_align = v; @@ -1010,6 +1028,12 @@ impl CharChange { if let Some(v) = self.tsume { st.tsume = v; } + if let Some(v) = self.diacritic_horizontal { + st.diacritic_horizontal = v; + } + if let Some(v) = self.diacritic_vertical { + st.diacritic_vertical = v; + } if let Some(v) = self.standard_vertical_roman { st.standard_vertical_roman = v; } diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index 18f87d44f7..efcc078e65 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -223,6 +223,8 @@ pub fn char_attrs(v: &CharStyle) -> Map { ("akiLeft", json!(v.aki_left)), ("akiRight", json!(v.aki_right)), ("tsume", json!(v.tsume)), + ("diacriticHorizontal", json!(v.diacritic_horizontal)), + ("diacriticVertical", json!(v.diacritic_vertical)), ("standardVerticalRoman", json!(v.standard_vertical_roman)), ("noBreak", json!(v.no_break)), ("digits", json!(v.digits)), @@ -584,6 +586,13 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma if changed(key) && !(lo..=hi).contains(&st.tsume) { return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}"))); } + let hi = vectorcraft_doc::text::MAX_DIACRITIC_POSITION; + let lo = -hi; + for (key, value) in [("diacriticHorizontal", st.diacritic_horizontal), ("diacriticVertical", st.diacritic_vertical)] { + if changed(key) && !(lo..=hi).contains(&value) { + return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}"))); + } + } let lines = vectorcraft_doc::text::WARICHU_LINES; if changed("warichuLines") && !lines.contains(&st.warichu_lines) { return Err(bad(&c, format!("`warichuLines` must be a whole number from {} to {}", lines.start(), lines.end()))); @@ -1081,12 +1090,12 @@ fn unused(s: &mut Session, kind: Kind) -> Result { /// The styles of `kind` in `src` that load, with their source names so that art in the file keeps /// referring to them: not the Normal style, and not one whose attributes don't read, whose sizes, -/// scales, leading, shifts, Insert Aki, Tsume, Warichu Settings or stroke width are out of the range `charStyle.new` takes, whose +/// scales, leading, shifts, Insert Aki, Tsume, diacritic positions, Warichu Settings or stroke width are out of the range `charStyle.new` takes, whose /// indents, spacing, Hyphenation or Justification options or tab stops are out of the range /// `paraStyle.new` takes, or whose name is empty, which are skipped. → (the styles, the names in /// `src` of those skipped) fn loadable(src: &Document, kind: Kind) -> (Vec, Vec) { - const RANGED: [&str; 22] = [ + const RANGED: [&str; 24] = [ "size", "h_scale", "v_scale", @@ -1095,6 +1104,8 @@ fn loadable(src: &Document, kind: Kind) -> (Vec, Vec) { "akiLeft", "akiRight", "tsume", + "diacriticHorizontal", + "diacriticVertical", "tcyUpDown", "tcyLeftRight", "warichuLines", diff --git a/crates/engine/src/cmd/textstyles/tests.rs b/crates/engine/src/cmd/textstyles/tests.rs index c8da4b578c..e8f57aa14f 100644 --- a/crates/engine/src/cmd/textstyles/tests.rs +++ b/crates/engine/src/cmd/textstyles/tests.rs @@ -399,6 +399,8 @@ fn character_style_dimensions_are_checked_before_a_definition_changes() { json!({"akiRight": 1000.1}), json!({"tsume": -0.1}), json!({"tsume": 100.1}), + json!({"diacriticHorizontal": -1000.1}), + json!({"diacriticVertical": 1000.1}), ] { let key = attrs.as_object().unwrap().keys().next().unwrap(); for cmd in ["charStyle.edit", "charStyle.setAttrs", "charStyle.new"] { @@ -422,7 +424,8 @@ fn character_style_dimensions_are_checked_before_a_definition_changes() { "baseline_shift": -1296.0, "tcyUpDown": 1296.0, "tcyLeftRight": -1296.0, "akiLeft": 0.0, "akiRight": 1000.0, - "tsume": 100.0 + "tsume": 100.0, + "diacriticHorizontal": -1000.0, "diacriticVertical": 1000.0 }}), ) .unwrap(); @@ -1652,6 +1655,30 @@ fn paragraph_style_options_edit_applies_to_users_and_is_one_saved_undo_step() { } } +/// A paragraph style can hold a Standard composer: it applies to its paragraphs, redefining and +/// resetting treat it like any attribute, and the style and the paragraphs keep it through a save. +#[test] +fn paragraph_styles_keep_a_standard_composer_through_a_save() { + use vectorcraft_doc::Composer; + let (mut s, id) = session_with_text("One\nTwo"); + s.execute("paraStyle.new", &json!({"name": "Legacy", "attrs": {"composer": "standardSingleLine"}})).unwrap(); + s.execute("paraStyle.apply", &json!({"name": "Legacy", "id": id, "start": 0, "end": 0})).unwrap(); + assert_eq!(paras(&s, id).iter().map(|p| p.composer).collect::>(), [Composer::StandardSingleLine, Composer::EveryLine]); + let doc = s.doc().unwrap().doc.clone(); + let saved = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap(); + let style = saved.para_styles.iter().find(|d| d.name == "Legacy").unwrap(); + assert_eq!(style.attrs["composer"], json!("standardSingleLine")); + let mut composers = vec![]; + saved.walk(|n| { + if let vectorcraft_doc::NodeKind::Text(t) = &n.kind { + composers.extend(t.paragraph_styles().iter().map(|p| p.composer)); + } + }); + assert_eq!(composers, [Composer::StandardSingleLine, Composer::EveryLine]); + s.execute("paraStyle.setAttrs", &json!({"name": "Legacy", "attrs": {"composer": "standardEveryLine"}})).unwrap(); + assert_eq!(paras(&s, id)[0].composer, Composer::StandardEveryLine, "an edited style reaches its paragraphs"); +} + /// A changed paragraph attribute outside the range `text.setFormat` keeps it to is an error for /// `paraStyle.edit`, `paraStyle.setAttrs` and `paraStyle.new`, with no change to the document; the /// ends of each range are accepted, and an out-of-range value the style already has can be kept. diff --git a/crates/engine/src/cmd/typecmd.rs b/crates/engine/src/cmd/typecmd.rs index b92f70e910..cb1366ed40 100644 --- a/crates/engine/src/cmd/typecmd.rs +++ b/crates/engine/src/cmd/typecmd.rs @@ -41,7 +41,7 @@ pub fn specs() -> Vec { "Create Outlines", ["Type"], Some("Cmd+Shift+O"), - "{} convert the selected text to groups of compound paths (one per glyph); the type object's own fills and strokes (not its characters') go on paths of its whole outline, below or above the glyphs as its Characters row places them; the group keeps the object's transparency, opacity mask and effects, once; a frame of threaded text leaves its thread with the text it shows; a dimension whose label is outlined becomes a plain group of its art → {ids}", + "{} convert the selected text to groups of compound paths (one per glyph); on type scaled unevenly, sheared or flattened, each glyph's stroke becomes a filled path over it, shaped as the canvas strokes it; the type object's own fills and strokes (not its characters') go on paths of its whole outline, below or above the glyphs as its Characters row places them; the group keeps the object's transparency, opacity mask and effects, once; a frame of threaded text leaves its thread with the text it shows; a dimension whose label is outlined becomes a plain group of its art → {ids}", has_selection, create_outlines ), @@ -619,16 +619,25 @@ fn scale_text_attributes(s: &mut Session, p: &Value) -> Result { /// 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 { +/// transform), followed by a path (or compound path) filled with the run's stroke when the type's +/// transform is not a similarity; empty when the piece has no path. +fn type_piece(d: &mut Document, t: &TextObject, bounds: kurbo::Rect, run: usize, outline: &kurbo::BezPath) -> Vec { let path = PathData::from_bezpath(outline); if path.is_empty() { - return None; + return vec![]; } 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) + let stroke = vectorcraft_render::effects::paint_type_piece(&mut node, &st, bounds, t.xf); + let mut out = vec![node]; + if let Some(s) = stroke + && let Some(path) = s.path_data() + { + let mut filled = shape_node(d, path.clone(), None); + filled.appearance = s.appearance.clone(); + out.push(filled); + } + out } fn create_outlines(s: &mut Session, _: &Value) -> Result { @@ -675,9 +684,7 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result { children.push(Arc::new(d.reid(&art))); break 'glyph; } - if let Some(node) = type_piece(d, t, lay.bounds, g.run, &g.outline) { - children.push(Arc::new(node)); - } + children.extend(type_piece(d, t, lay.bounds, g.run, &g.outline).into_iter().map(Arc::new)); } run_end.insert(g.run, children.len()); } @@ -686,10 +693,9 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result { // nothing there either). let mut ruby: Vec<(usize, Arc)> = vec![]; for g in &lay.ruby { - 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))); + ruby.extend(type_piece(d, t, lay.bounds, g.run, &g.outline).into_iter().map(|node| (at, Arc::new(node)))); } ruby.sort_by_key(|(at, _)| *at); let mut ruby = ruby.into_iter().peekable(); @@ -711,9 +717,7 @@ 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()); - if let Some(node) = type_piece(d, t, lay.bounds, run, &bar) { - children.push(Arc::new(node)); - } + children.extend(type_piece(d, t, lay.bounds, run, &bar).into_iter().map(Arc::new)); } // 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 diff --git a/crates/engine/src/cmd/typecmd/area_tests.rs b/crates/engine/src/cmd/typecmd/area_tests.rs index a63ebff9c4..9339e1d8c4 100644 --- a/crates/engine/src/cmd/typecmd/area_tests.rs +++ b/crates/engine/src/cmd/typecmd/area_tests.rs @@ -1921,6 +1921,66 @@ fn tsume_is_a_character_attribute() { assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step for a refused call"); } +/// Adjust Horizontal and Vertical Diacritic Position (Character panel, Middle Eastern options): +/// character attributes in thousandths of an em, 0 by default and saved only when not 0. Both +/// commands set them in one undo step, setting one leaves the other, a call that gives the values +/// the text already has records none, and a value that is not a number or lies outside -1000 to +/// 1000 is refused, naming the key, before anything changes; the native file and a character style +/// captured from the characters carry them. +#[test] +fn diacritic_positions_are_character_attributes() { + 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 moved = |s: &Session| runs(s).iter().map(|r| (r.text.clone(), r.style.diacritic_horizontal, r.style.diacritic_vertical)).collect::>(); + let saved = serde_json::to_value(&runs(&s)[0].style).unwrap(); + assert!(saved.get("diacriticHorizontal").is_none() && saved.get("diacriticVertical").is_none()); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + s.execute("text.setFormat", &json!({"diacriticHorizontal": -150})).unwrap(); + s.execute("text.setFormat", &json!({"diacriticVertical": 250})).unwrap(); + assert_eq!(moved(&s), [("بَب".to_string(), -150.0, 250.0)], "setting one leaves the other"); + let undo = s.doc().unwrap().history.undo.len(); + s.execute("text.setFormat", &json!({"diacriticHorizontal": -150, "diacriticVertical": 250})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step without a change"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(moved(&s), [("بَب".to_string(), -150.0, 0.0)], "one undo step"); + s.execute("edit.redo", &json!({})).unwrap(); + + let mark = "بَ".len(); + s.execute("text.setRangeStyle", &json!({"id": id, "start": "ب".len(), "end": mark, "diacriticVertical": -1000})).unwrap(); + assert_eq!(moved(&s), [("ب".to_string(), -150.0, 250.0), ("\u{064E}".to_string(), -150.0, -1000.0), ("ب".to_string(), -150.0, 250.0)]); + let saved = serde_json::to_value(&runs(&s)[1].style).unwrap(); + assert_eq!((saved["diacriticHorizontal"].clone(), saved["diacriticVertical"].clone()), (json!(-150.0), json!(-1000.0))); + 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") }; + let reopened: Vec<_> = t.runs.iter().map(|r| (r.text.clone(), r.style.diacritic_horizontal, r.style.diacritic_vertical)).collect(); + assert_eq!(reopened, moved(&s)); + let attrs = super::super::textstyles::char_attrs(&runs(&s)[1].style); + assert_eq!((attrs["diacriticHorizontal"].clone(), attrs["diacriticVertical"].clone()), (json!(-150.0), json!(-1000.0))); + + let before = moved(&s); + let undo = s.doc().unwrap().history.undo.len(); + for (cmd, p, want) in [ + ("text.setFormat", json!({"diacriticHorizontal": "50"}), "`diacriticHorizontal` must be a number"), + ("text.setFormat", json!({"diacriticVertical": 1000.5}), "`diacriticVertical` must be from -1000 to 1000"), + ("text.setRangeStyle", json!({"id": id, "diacriticVertical": true}), "`diacriticVertical` must be a number"), + ( + "text.setRangeStyle", + json!({"id": id, "start": 0, "end": mark, "diacriticHorizontal": -1001}), + "`diacriticHorizontal` must be from -1000 to 1000", + ), + ] { + let e = s.execute(cmd, &p).unwrap_err(); + assert!(matches!(&e, EngineError::BadParams { msg, .. } if msg == want), "{cmd} {p}: {e}"); + } + assert_eq!(moved(&s), before); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step for a refused call"); +} + /// Standard Vertical Roman Alignment (Character panel menu, East Asian options): a character /// attribute, off by default and saved only when on. Documents written before it read as off; a /// character style captured from the characters carries it. diff --git a/crates/engine/src/cmd/typemenu.rs b/crates/engine/src/cmd/typemenu.rs index 0701f6eeca..da930d7e59 100644 --- a/crates/engine/src/cmd/typemenu.rs +++ b/crates/engine/src/cmd/typemenu.rs @@ -1783,6 +1783,13 @@ fn strip_formatting(n: &mut vectorcraft_doc::Node) { fn paste_plain(s: &mut Session, p: &Value) -> Result { let saved = s.clipboard.nodes.clone(); + // Pasted colors linked to a swatch merged with the document's show its color, so a pasted pie's legend labels take + // the contrast of the wedges as pasted. A `swatchConflict` the paste refuses is left to its error. + if let (Ok(choices), Ok(st)) = (super::clipboard::SwatchChoices::parse("edit.pasteWithoutFormatting", p), s.doc()) { + let same_doc = s.clipboard.source_doc == Some(st.uid); + let d = std::sync::Arc::clone(&st.doc); + s.clipboard.show_merged_colors(&d, &choices, same_doc); + } for n in &mut s.clipboard.nodes { strip_formatting(n); } diff --git a/crates/engine/src/cmd/variablecmds.rs b/crates/engine/src/cmd/variablecmds.rs index 8e58132ce0..229aa1db3a 100644 --- a/crates/engine/src/cmd/variablecmds.rs +++ b/crates/engine/src/cmd/variablecmds.rs @@ -11,6 +11,7 @@ //! visibility, `@` for image, no prefix for text). `variable.loadLibrary` replaces the variables and data sets with the //! 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. +//! `variable.import` (the panel's Import…) runs one of the two readers by the file's extension. //! Agents reach every command through `run_command`, like all engine commands. use std::collections::{BTreeMap, BTreeSet}; @@ -865,6 +866,22 @@ fn dataset_step(s: &mut Session, cmd: &str, forward: bool) -> Result { apply_dataset(s, &name) } +/// The Variables panel's Import…: a data source file read by its extension, a CSV, TSV or TXT +/// file as `dataset.import` reads it and an XML file as `variable.loadLibrary` reads it. The +/// result is that command's, with `format` set to `csv` or `xml`. +fn variable_import(s: &mut Session, p: &Value) -> Result { + const C: &str = "variable.import"; + let path = str_param(p, "path").ok_or_else(|| bad(C, "missing `path`"))?; + let ext = std::path::Path::new(path).extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase); + let (format, mut out) = match ext.as_deref() { + Some("csv" | "tsv" | "txt") => ("csv", dataset_import(s, &json!({"path": path}))?), + Some("xml") => ("xml", load_library(s, &json!({"path": path}))?), + _ => return Err(bad(C, "Import reads a data source file ending in .csv, .tsv, .txt or .xml")), + }; + out["format"] = json!(format); + Ok(out) +} + pub fn specs() -> Vec { vec![ cmd!( @@ -1057,6 +1074,15 @@ pub fn specs() -> Vec { has_doc, dataset_import ), + cmd!( + "variable.import", + "Import…", + ["Window", "Variables"], + None, + "{path} import a data source file, chosen by its extension (any case): a .csv, .tsv or .txt file is read as dataset.import reads it, and an .xml file as variable.loadLibrary reads it, with their refusals and undo steps; any other extension, or none, is refused before the file is read → the result of that command with `format`: `csv` or `xml`", + has_doc, + variable_import + ), cmd!( query "dataset.export", "Export Data Sets…", diff --git a/crates/engine/src/cmd/variablecmds/library.rs b/crates/engine/src/cmd/variablecmds/library.rs index 2392a80ee4..ceab798373 100644 --- a/crates/engine/src/cmd/variablecmds/library.rs +++ b/crates/engine/src/cmd/variablecmds/library.rs @@ -60,8 +60,8 @@ fn library_bytes(p: &Value, cmd: &str) -> Result> { /// up to [`MAX_LIBRARY_ENTITIES`] entity declarations, each with a name of at most [`MAX_NAME`] /// bytes and a quoted value that holds no `<`, `&` or `%`. Anything else in it is refused, and so is /// a text that the replacements make longer than [`MAX_LIBRARY_BYTES`]. The XML parser then refuses -/// any other document type declaration, so [`nesting`](super::place::docx::nesting) counts the -/// elements the parser reads. +/// any other document type declaration, so its depth and node limits count the elements it +/// reads. fn without_doctype(xml: &str, cmd: &str) -> Result { let b = xml.as_bytes(); let past = |from: usize, end: &str| xml.get(from..).and_then(|rest| rest.find(end)).map(|at| from + at + end.len()); @@ -240,22 +240,25 @@ impl Library { /// 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 { - return Err(bad(cmd, format!("the variable library nests elements more than {MAX_LIBRARY_NESTING} deep"))); + let opts = craft_xml::Options { + names: craft_xml::Names::AsWritten, + limits: craft_xml::Limits { max_depth: MAX_LIBRARY_NESTING, max_nodes: MAX_LIBRARY_NODES as usize, ..craft_xml::Limits::DEFAULT }, + ..craft_xml::Options::default() } - let opts = roxmltree::ParsingOptions { nodes_limit: MAX_LIBRARY_NODES, ..roxmltree::ParsingOptions::default() }; - let doc = - roxmltree::Document::parse_with_options(&xml, opts).map_err(|e| bad(cmd, format!("the variable library is not well-formed XML: {e}")))?; - let is = |n: &roxmltree::Node, name: &str| n.is_element() && n.tag_name().name() == name; - let Some(root) = doc.descendants().find(|n| is(n, "variableSets")) else { + .strict(); + let doc = opts.parse(xml.as_bytes()).map_err(|e| match e { + craft_xml::Error::TooDeep(_) => bad(cmd, format!("the variable library nests elements more than {MAX_LIBRARY_NESTING} deep")), + _ => bad(cmd, format!("the variable library is not well-formed XML: {e}")), + })?; + crate::cmd::xmlattrs::validate(xml.as_bytes(), opts.limits).map_err(|e| bad(cmd, format!("the variable library is not well-formed XML: {e}")))?; + let Some(root) = std::iter::once(&doc).chain(doc.descendants()).find(|n| n.is(craft_xml::Local("variableSets"))) else { return Err(bad(cmd, "the file holds no `variableSets` element")); }; - let sets: Vec = root.children().filter(|n| is(n, "variableSet")).collect(); + let sets: Vec<&craft_xml::El> = root.children(craft_xml::Local("variableSet")).collect(); 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)?; - let trait_name = var.attribute("trait").map(|t| t.chars().take(MAX_NAME).collect::()); + for var in sets.iter().flat_map(|s| s.children(craft_xml::Local("variables"))).flat_map(|v| v.children(craft_xml::Local("variable"))) { + let name = named(var.attr("varName"), "varName", cmd)?; + let trait_name = var.attr("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"))); @@ -265,7 +268,7 @@ fn parse_library(xml: &str, cmd: &str, text_only: bool) -> Result { } 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()); + let element = var.attr("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())); } @@ -276,10 +279,8 @@ fn parse_library(xml: &str, cmd: &str, text_only: bool) -> Result { return Err(bad(cmd, "the variable library declares no variables")); } 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")) - { - let name = named(row.attribute("dataSetName"), "dataSetName", cmd)?; + for row in sets.iter().flat_map(|s| s.children(craft_xml::Local("sampleDataSets"))).flat_map(|d| d.children(craft_xml::Local("sampleDataSet"))) { + let name = named(row.attr("dataSetName"), "dataSetName", cmd)?; if !seen.insert(name.clone()) { return Err(bad(cmd, format!("data set `{name}` is declared twice"))); } @@ -287,8 +288,8 @@ fn parse_library(xml: &str, cmd: &str, text_only: bool) -> Result { return Err(bad(cmd, format!("the variable library declares more than {MAX_LIBRARY_DATASETS} data sets"))); } 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(); + for el in row.elements() { + let var = el.local(); 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"))); }; @@ -315,12 +316,12 @@ fn parse_library(xml: &str, cmd: &str, text_only: bool) -> Result { /// 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)) }; +fn library_value(el: &craft_xml::El, 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.local())); + let text = || if el.elements().next().is_some() { None } else { Some(el.deep_text()) }; match kind { VariableKind::Text => { - let paras: Vec = elements(el).filter(|n| n.tag_name().name() == "p").map(deep_text).collect(); + let paras: Vec = el.children(craft_xml::Local("p")).map(craft_xml::El::deep_text).collect(); Ok((!paras.is_empty()).then(|| DataValue::Text(paras.join("\n")))) } VariableKind::Visibility => { @@ -346,16 +347,6 @@ fn library_value(el: roxmltree::Node, kind: VariableKind, set: &str, cmd: &str) } } -/// 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 @@ -428,29 +419,28 @@ fn library_file(path: &str) -> String { /// 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(); +fn graph_value(el: &craft_xml::El, set: &str, cmd: &str) -> Result> { + let var = el.local(); 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 named = |name: &'static str| craft_xml::Local(name); + let mut children = el.elements(); 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, + (None, _) if el.deep_text().trim_matches(XML_SPACE).is_empty() => return Ok(None), + (Some(data), None) if data.local() == "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(); + data.child(named("propertyRow")).map(|r| r.children(named("value")).skip(1).map(craft_xml::El::deep_text).collect()).unwrap_or_default(); + let rows: Vec<&craft_xml::El> = data.children(named("values")).flat_map(|v| v.children(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")); + let wide = |row: &&craft_xml::El| { + let mut values = row.children(named("value")).peekable(); + let _name = values.next_if(|v| v.attr("key") == Some("name")); values.count() > MAX_GRAPH_SERIES }; if rows.len() > MAX_GRAPH_CATEGORIES || series.len() > MAX_GRAPH_SERIES || rows.iter().any(wide) { @@ -462,12 +452,12 @@ fn graph_value(el: roxmltree::Node, set: &str, cmd: &str) -> Result, 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) }); + let mut values = row.children(named("value")).peekable(); + let name = values.next_if(|v| v.attr("key") == Some("name")); + labelled |= name.is_some_and(|v| v.attr("type") == Some("string") || !v.deep_text().is_empty()); + let name = name.map(craft_xml::El::deep_text); + let number = |v: &craft_xml::El| v.deep_text().trim_matches(XML_SPACE).parse::().ok().filter(|n| n.is_finite()); + let numbers = values.map(|v| if v.attr("type") == Some("string") { None } else { number(v) }); (name, numbers.collect()) }) .collect(); diff --git a/crates/engine/src/cmd/xmlattrs.rs b/crates/engine/src/cmd/xmlattrs.rs new file mode 100644 index 0000000000..6dd2578fae --- /dev/null +++ b/crates/engine/src/cmd/xmlattrs.rs @@ -0,0 +1,55 @@ +//! Attribute uniqueness checks missing from the pinned shared XML reader's strict mode. +//! +//! Temporary consumer guard: parsing remains in craft-xml. Move this invariant into the +//! shared strict reader and remove this second event pass when that dependency is updated. + +/// Check names before canonical/local-name rewriting can collapse distinct attributes. +/// The event reader and namespace scope use the same caller-supplied resource caps. +pub(super) fn validate(xml: &[u8], limits: craft_xml::Limits) -> Result<(), String> { + use std::collections::BTreeSet; + + let opts = craft_xml::Options { limits, doctype: craft_xml::Doctype::Reject, ..Default::default() }.strict(); + let mut events = opts.events(xml); + let mut bindings: Vec<(String, String)> = Vec::new(); + let mut scopes = Vec::new(); + while let Some(event) = events.next().map_err(|e| e.to_string())? { + match event { + craft_xml::Event::Start { attrs, .. } => { + scopes.push(bindings.len()); + let mut raw = BTreeSet::new(); + for (key, value) in &attrs { + if !raw.insert(key.as_str()) { + return Err(format!("duplicate attribute `{key}`")); + } + if let Some(prefix) = key.strip_prefix("xmlns:") { + if bindings.len() >= limits.max_attrs { + return Err("too many in-scope namespace declarations".into()); + } + bindings.push((prefix.to_string(), value.clone())); + } + } + let mut expanded = BTreeSet::new(); + for (key, _) in &attrs { + if key == "xmlns" || key.starts_with("xmlns:") { + continue; + } + // Default namespaces do not apply to attributes. Preserve undeclared + // prefixes for standalone SVG library fragments, as the importer did. + let name = match key.split_once(':') { + Some(("xml", local)) => ("http://www.w3.org/XML/1998/namespace", local), + Some((prefix, local)) => { + bindings.iter().rev().find(|(p, _)| p == prefix).map_or(("", key.as_str()), |(_, uri)| (uri.as_str(), local)) + } + None => ("", key.as_str()), + }; + if !expanded.insert(name) { + return Err(format!("duplicate expanded attribute `{key}`")); + } + } + } + craft_xml::Event::End { .. } => bindings.truncate(scopes.pop().unwrap_or(0)), + _ => {} + } + } + Ok(()) +} diff --git a/crates/engine/src/sanity.rs b/crates/engine/src/sanity.rs index f1b6fd55bb..4737246c9d 100644 --- a/crates/engine/src/sanity.rs +++ b/crates/engine/src/sanity.rs @@ -59,8 +59,23 @@ fn rect_in_range(r: vectorcraft_geom::Rect) -> bool { /// margin passes without being measured: its curves stay inside their control points. Any other /// object, and a path with a point outside that margin, is measured. pub(crate) fn objects_in_range(d: &Document, ids: &[NodeId]) -> bool { - let paths = d.index_paths(ids.iter().copied()); - ids.iter().all(|id| paths.get(id).and_then(|p| d.node_at(p)).is_none_or(|n| points_in_range(n) || n.geometric_bounds().is_none_or(rect_in_range))) + if ids.is_empty() { + return true; + } + let node_ok = |n: &vectorcraft_doc::Node| points_in_range(n) || n.geometric_bounds().is_none_or(rect_in_range); + // A cached document or a few ids: look each one up. Otherwise one walk of the tree, with no + // path vectors allocated. + if d.has_lookup_cache() || ids.len() <= 16 { + return ids.iter().all(|id| d.node(*id).is_none_or(node_ok)); + } + let want: std::collections::HashSet = ids.iter().copied().collect(); + let mut ok = true; + d.walk(|n| { + if ok && want.contains(&n.id) && !node_ok(n) { + ok = false; + } + }); + ok } /// Coordinates at most this far from 0 keep a curve's measured bounds within [`MAX_COORD`] diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index f150dfd465..1b420d7805 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2133,7 +2133,7 @@ mod pen_interactions { gesture(&mut s, &[(400.0, 500.0)], Mods::default(), v); let extended = path(&s, id); assert_eq!(extended.anchor_count(), 3); - assert_eq!(extended.subpaths[0].anchors[..2], reversed.subpaths[0].anchors); + assert_eq!(extended.subpaths[0].anchors.to_vec()[..2], reversed.subpaths[0].anchors); assert!(!s.in_interaction() && !s.tool_busy()); assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 1); } @@ -2168,7 +2168,7 @@ mod pen_interactions { gesture(&mut s, &[(300.0, 400.0)], Mods::default(), v); let extended = path(&s, id); assert_eq!(extended.anchor_count(), 3); - assert_eq!(extended.subpaths[0].anchors[..2], converted.subpaths[0].anchors); + assert_eq!(extended.subpaths[0].anchors.to_vec()[..2], converted.subpaths[0].anchors); assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 1); } @@ -2227,7 +2227,7 @@ mod pen_interactions { } let extended = path(&s, id); assert_eq!(extended.anchor_count(), 3); - assert_eq!(extended.subpaths[0].anchors[..2], before.subpaths[0].anchors); + assert_eq!(extended.subpaths[0].anchors.to_vec()[..2], before.subpaths[0].anchors); let a = extended.subpaths[0].anchors[2]; assert_eq!(a.p, Point::new(320.0, 450.0)); assert_eq!(a.h_in, Point::new(290.0, 430.0), "Alt freezes the incoming handle and Space translates it"); @@ -3381,7 +3381,7 @@ fn reshape_open_path(s: &mut Session, anchors: Value) -> NodeId { /// The anchors of the path's first subpath. fn reshape_anchors(s: &Session, id: NodeId) -> Vec { - s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[0].anchors.clone() + s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[0].anchors.to_vec() } /// The share of the drag an anchor takes at `u` of the way from an end to the grabbed point. diff --git a/crates/engine/src/tests/actionset.rs b/crates/engine/src/tests/actionset.rs index d80e649ec7..49e5685bdc 100644 --- a/crates/engine/src/tests/actionset.rs +++ b/crates/engine/src/tests/actionset.rs @@ -3,7 +3,7 @@ use serde_json::json; -use crate::cmd::actionset::{AiaStep, read_aia}; +use crate::cmd::actionset::{AiaData, AiaStep, AiaValue, read_aia}; use crate::*; /// `text` as a bracketed hexadecimal value. @@ -37,7 +37,12 @@ fn a_set_reads_its_actions_and_steps() { let names: Vec<&str> = set.actions.iter().map(|a| a.name.as_str()).collect(); assert_eq!(names, ["First", "二番目"]); let step = |a: usize, s: usize| set.actions[a].steps[s].clone(); - let join = AiaStep { name: "sample_join".into(), label: Some("Join".into()), on: Some(1), params: 3, declared: Some(3), line: 9 }; + let values = vec![ + AiaValue { key: Some(1), kind: Some("unit real".into()), value: None }, + AiaValue { key: None, kind: Some("ustring".into()), value: Some(AiaData::Text(b"a } brace".to_vec())) }, + AiaValue { key: None, kind: Some("raw".into()), value: None }, + ]; + let join = AiaStep { name: "sample_join".into(), label: Some("Join".into()), on: Some(1), params: 3, values, declared: Some(3), line: 9 }; assert_eq!(step(0, 0), join); assert_eq!((step(1, 0).name.as_str(), step(1, 0).label.clone(), step(1, 0).on), ("sample)one", None, Some(0))); assert_eq!((step(1, 1).label.as_deref(), step(1, 1).on, step(1, 1).line), (Some("Second Step"), None, 39)); @@ -60,6 +65,55 @@ fn recorded_values_are_counted_and_checked() { assert!(set(&[value("one"), "/value [ 1 zz ]".to_string()]).truncated, "a second value that isn't hexadecimal"); } +/// `actionSet.read` answers with each recorded value's key, type and value: a number, text in +/// parentheses or hexadecimal text that is UTF-8 with its length in bytes, and null for text that +/// isn't UTF-8 and for other values. Fields may come in any order, and a value with the wrong byte +/// count still marks the set truncated. +#[test] +fn recorded_values_come_back_with_their_keys_and_types() { + let mut s = Session::new(); + let text = format!( + "/version 3 /action-1 {{ /event-1 {{ /internalName (sample_values) /parameterCount 6 \ + /parameter-1 {{ /key 1952807028 /type (ustring) /value {note} }} \ + /parameter-2 {{ /value 1 /type (boolean) /key 2003792484 }} \ + /parameter-3 {{ /type (ustring) /value [ 2 c328 ] /key 7 }} \ + /parameter-4 {{ /key 99999999999999999999 /type (real) /value 4.5 }} \ + /parameter-5 {{ /key 3 /type (text) /value (plain) }} \ + /parameter-6 {{ }} }} }}", + note = hex("Größe ✓") + ); + let r = s.execute("actionSet.read", &json!({ "data": text })).unwrap(); + assert_eq!(r["truncated"], false); + assert_eq!( + r["actions"][0]["steps"][0]["values"], + json!([ + {"key": 1952807028, "type": "ustring", "value": "Größe ✓", "bytes": 11}, + {"key": 2003792484, "type": "boolean", "value": 1}, + {"key": 7, "type": "ustring", "value": null, "bytes": 2}, + {"key": null, "type": "real", "value": null}, + {"key": 3, "type": "text", "value": "plain", "bytes": 5}, + {"key": null, "type": null, "value": null}, + ]) + ); + let bad = "/version 3 /action-1 { /event-1 { /parameter-1 { /key 1 /type (ustring) /value [ 3 4142 ] } } }"; + assert_eq!(s.execute("actionSet.read", &json!({ "data": bad })).unwrap()["truncated"], true); +} + +/// At most 100,000 recorded values are kept in a set: the others are still counted, so a step's +/// `values` can be shorter than its `params`. +#[test] +fn recorded_values_past_the_cap_are_counted_but_not_kept() { + let step = format!("/event-1 {{ {} }} ", "/parameter-1 { /key 1 /value 0 } ".repeat(1000)); + let action = format!("/action-1 {{ {} }} ", step.repeat(50)); + let set = read_aia(format!("/version 3 {}", action.repeat(3)).as_bytes()).unwrap(); + assert!(!set.truncated); + let steps = || set.actions.iter().flat_map(|a| &a.steps); + assert_eq!(steps().map(|s| s.params).sum::(), 150_000); + assert_eq!(steps().map(|s| s.values.len()).sum::(), 100_000); + assert_eq!(set.actions[2].steps[0].values.len(), 0); + assert_eq!(set.actions[1].steps[49].values[999], AiaValue { key: Some(1), kind: None, value: Some(AiaData::Int(0)) }); +} + /// `actionSet.read` takes exactly one of `path`, `data` and `dataBase64`, and text for the text /// params; any other value is an error. #[test] @@ -97,7 +151,7 @@ fn read_command_answers_with_the_set() { let text = sample().replacen(&format!("/name {}", hex("Prep Sätze")), "", 1); let r = s.execute("actionSet.read", &json!({ "data": text, "name": "/sets/Mine.aia" })).unwrap(); assert_eq!(r["set"], "Mine"); - assert_eq!(r["actions"][1]["steps"][0], json!({"name": "sample)one", "label": null, "on": false, "params": 0, "line": 34})); + assert_eq!(r["actions"][1]["steps"][0], json!({"name": "sample)one", "label": null, "on": false, "params": 0, "values": [], "line": 34})); assert_eq!(r["actions"][0]["steps"][0]["on"], true); assert_eq!(r["actions"][0]["steps"][0]["label"], "Join"); let blank = format!("/version 3 /action-1 {{ /event-1 {{ /internalName (x) /localizedName {} }} }}", hex(" ")); diff --git a/crates/engine/src/tests/anchor_edit_work.rs b/crates/engine/src/tests/anchor_edit_work.rs index 1055156167..5401bc0bf8 100644 --- a/crates/engine/src/tests/anchor_edit_work.rs +++ b/crates/engine/src/tests/anchor_edit_work.rs @@ -1,6 +1,7 @@ //! An edit of one anchor of a long selected path does not measure the path's segments -//! ([`vectorcraft_geom::path::measured_segments`]) to check that it stays within the canvas, and -//! an edit that leaves the anchor as it was records no undo step. +//! ([`vectorcraft_geom::path::measured_segments`]) to check that it stays within the canvas, its +//! undo step keeps the chunk of anchors it changed rather than a copy of every anchor, and an edit +//! that leaves the anchor as it was records no undo step. use std::collections::BTreeSet; use std::sync::Arc; @@ -74,6 +75,46 @@ fn one_anchor_edit_of_a_long_path_measures_few_segments() { } } +/// Most bytes the undo step of one anchor edit may keep, however many anchors the path has: about +/// one chunk of anchors and the node, with room for the chunk tables of 200,000 anchors. +const MOST_STEP_BYTES: usize = 48 * 1024; + +#[test] +fn one_anchor_edit_of_a_long_path_keeps_one_chunk_in_its_undo_step() { + for n in [10_000, 200_000] { + let (mut s, id) = long_path(n); + let original = s.doc().unwrap().doc.clone(); + let edits = [ + ("path.moveAnchor", json!({"id": id.0, "anchor": 5, "x": 3, "y": 50})), + ("path.setHandle", json!({"id": id.0, "anchor": 5, "which": "out", "x": 4, "y": 40})), + ("path.moveAnchors", json!({"dx": 1, "dy": 0})), + ("object.nudge", json!({"dx": 1, "dy": 0})), + ]; + let mut docs = vec![]; + for (cmd, p) in &edits { + s.execute(cmd, p).unwrap(); + let step = s.doc().unwrap().history.undo.last().unwrap().bytes; + assert!(step <= MOST_STEP_BYTES, "{cmd} on {n} anchors kept {step} bytes in its undo step"); + docs.push(s.doc().unwrap().doc.clone()); + } + assert_eq!(anchor(&s, id, 5).p, Point::new(5.0, 50.0)); + assert_eq!(anchor(&s, id, 5).h_out, Point::new(6.0, 40.0)); + assert_eq!(anchor(&s, id, n - 1), original.node(id).unwrap().path_data().unwrap().subpaths[0].anchors[n - 1]); + // Undo gives back each version exactly, and redo the edits, each step as small. + for k in (0..edits.len()).rev() { + s.execute("edit.undo", &json!({})).unwrap(); + let expected = if k == 0 { &original } else { &docs[k - 1] }; + assert!(s.doc().unwrap().doc == *expected, "undo of {} on {n} anchors", edits[k].0); + let redo = s.doc().unwrap().history.redo.last().unwrap().bytes; + assert!(redo <= MOST_STEP_BYTES, "redo of {} on {n} anchors keeps {redo} bytes", edits[k].0); + } + for (k, doc) in docs.iter().enumerate() { + s.execute("edit.redo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc == *doc, "redo of {} on {n} anchors", edits[k].0); + } + } +} + /// A handle past the canvas is measured: the edit stands while the curve stays within the canvas, /// and is refused once the curve leaves it. #[test] diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index a2e9eb3012..706bf2a508 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -1037,6 +1037,40 @@ fn brush_freehand_direct_call_has_one_undo_step() { assert_eq!(s.doc().unwrap().history.undo.last().map(|e| e.label.as_str()), Some("Paintbrush"), "a stroke with a brush is a Paintbrush step"); } +/// A `brush.freehand` call that continues a path by one point changes only the path's brush, and +/// applies `keepSelected` as a longer continuation does: off, the path is deselected while the +/// rest of the selection stays; on, the path is selected. A call that leaves the brush as it is +/// changes neither the selection nor the undo history. +#[test] +fn brush_freehand_continued_by_one_point_follows_keep_selected() { + let mut s = session(); + let r = s.execute("brush.freehand", &json!({"points": [[10, 10], [60, 40], [120, 10]], "style": "brush", "brush": "Charcoal"})).unwrap(); + let p = NodeId(r["id"].as_u64().unwrap()); + let a = rect(&mut s, 200.0, 200.0, 10.0, 10.0); + let extend = json!({"id": p.0, "end": "end"}); + + select(&mut s, &[p, a]); + let off = json!({"points": [[120, 10]], "extend": extend, "brush": "Dots", "keepSelected": false}); + assert_eq!(s.execute("brush.freehand", &off).unwrap()["id"], json!(p.0)); + assert_eq!(brush_of(&s, p).as_deref(), Some("Dots")); + assert_eq!(selected(&s), [a], "Keep selected off: the path is deselected and the rest stays"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(brush_of(&s, p).as_deref(), Some("Charcoal"), "one Undo takes back the brush"); + assert_eq!(selected(&s), [p, a], "Undo gives back the earlier selection"); + + select(&mut s, &[a]); + let on = json!({"points": [[120, 10]], "extend": extend, "brush": "Dots"}); + s.execute("brush.freehand", &on).unwrap(); + assert_eq!(brush_of(&s, p).as_deref(), Some("Dots")); + assert_eq!(selected(&s), [p], "Keep selected on: the continued path is selected"); + + select(&mut s, &[a]); + let undo = s.doc().unwrap().history.undo.len(); + s.execute("brush.freehand", &on).unwrap(); + assert_eq!(selected(&s), [a], "the same brush again: the selection stays"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "the same brush again: no undo step"); +} + /// `brush.freehand` refuses a brush for a path with no stroke (a continued path, a redrawn one /// and a new filled pencil path while the stroke is None) instead of reporting it painted: the /// document, the selection and the undo history stay as they were. Without a brush the path is diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index 722cee04fe..91c1ad7814 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -3908,6 +3908,266 @@ fn live_paint_bucket_triple_click_fills_every_face_of_the_same_fill() { assert_eq!([a, b, c, d].map(|f| fill_of(&s, f)), [green.clone(), green, red.clone(), red]); } +/// A triple-click whose first click is released across an edge, in the face it then clicks twice, +/// matches that face's fill from before the first click: the release painted it too. +#[test] +fn live_paint_bucket_triple_click_after_a_release_across_an_edge_matches_the_fill_before() { + 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::solid(Color::rgb(0.0, 0.0, 0.0)), &[(a, red.clone()), (b, red.clone()), (c, blue.clone()), (d, red.clone())]); + let v = ViewInfo::default(); + s.select_tool("livePaintBucket", v).unwrap(); + s.paint.fill = green.clone(); + s.pointer(&PointerEvent::new(PointerKind::Down, 45.0, 25.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 55.0, 25.0), v).unwrap(); + assert_eq!([a, b].map(|f| fill_of(&s, f)), [green.clone(), green.clone()], "the release across x = 50 fills both faces"); + for kind in [PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick, PointerKind::Down, PointerKind::Up, PointerKind::TripleClick] { + s.pointer(&PointerEvent::new(kind, 55.0, 25.0), v).unwrap(); + } + assert_eq!([a, b, c, d].map(|f| fill_of(&s, f)), [green.clone(), green.clone(), blue, green]); +} + +/// A triple-click whose third press lands in another face and is released in the face its first +/// two clicks painted still matches that face's fill from before the first click. +#[test] +fn live_paint_bucket_triple_click_released_from_another_face_matches_the_fill_before() { + 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::solid(Color::rgb(0.0, 0.0, 0.0)), &[(a, red.clone()), (b, red.clone()), (c, blue.clone()), (d, red.clone())]); + 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, 55.0, 25.0), v).unwrap(); + } + s.pointer(&PointerEvent::new(PointerKind::Down, 45.0, 25.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 55.0, 25.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::TripleClick, 55.0, 25.0), v).unwrap(); + assert_eq!([a, b, c, d].map(|f| fill_of(&s, f)), [green.clone(), green.clone(), blue, green]); +} + +/// A triple-click whose first click makes the Live Paint group and is released across an edge, in +/// the face it then clicks twice, matches the fill that face was made with. +#[test] +fn live_paint_bucket_triple_click_after_making_the_group_across_an_edge_matches_the_made_fill() { + let mut s = session(); + let ids: Vec = [0.0, 50.0, 200.0, 300.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, red]) { + 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(); + s.pointer(&PointerEvent::new(PointerKind::Down, 45.0, 25.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 55.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 click made a group"); + let faces = faces_at(&s, g, &[(25.0, 25.0), (75.0, 25.0), (225.0, 25.0), (325.0, 25.0)]); + assert_eq!(faces[..2].iter().map(|f| fill_of(&s, *f)).collect::>(), [green.clone(), green.clone()], "the release fills both faces"); + for kind in [PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick, PointerKind::Down, PointerKind::Up, PointerKind::TripleClick] { + s.pointer(&PointerEvent::new(kind, 55.0, 25.0), v).unwrap(); + } + assert_eq!(faces.iter().map(|f| fill_of(&s, *f)).collect::>(), [green.clone(), green.clone(), Paint::solid(blue), green]); +} + +/// When the first click makes the Live Paint group and is released in a face covered by a source +/// path with no fill in front of a filled one, the face was made with the filled source's fill, as +/// Make gives it, so the triple-click there matches that fill and not none. +#[test] +fn live_paint_bucket_triple_click_after_making_the_group_under_an_unfilled_path_matches_the_made_fill() { + let mut s = session(); + let red = Color::rgb(1.0, 0.0, 0.0); + let (a, b, d) = (rect(&mut s, 0.0, 0.0, 50.0, 50.0), rect(&mut s, 50.0, 0.0, 50.0, 50.0), rect(&mut s, 200.0, 0.0, 50.0, 50.0)); + for id in [a, b, d] { + set_fill(&mut s, id, red); + } + let (c, e) = (rect(&mut s, 60.0, 10.0, 30.0, 30.0), rect(&mut s, 300.0, 0.0, 50.0, 50.0)); + s.edit("t", |doc, _| { + for id in [c, e] { + doc.node_mut(id).unwrap().appearance.set_fill(Paint::None); + } + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [a.0, b.0, d.0, c.0, e.0]})).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(); + s.pointer(&PointerEvent::new(PointerKind::Down, 45.0, 25.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 75.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 click made a group"); + let faces = faces_at(&s, g, &[(75.0, 25.0), (225.0, 25.0), (325.0, 25.0)]); + assert_eq!(fill_of(&s, faces[0]), green, "the release fills the face under the unfilled path"); + assert_eq!([faces[1], faces[2]].map(|f| fill_of(&s, f)), [Paint::solid(red), Paint::None], "Make gave the far faces red and none"); + for kind in [PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick, PointerKind::Down, PointerKind::Up, PointerKind::TripleClick] { + s.pointer(&PointerEvent::new(kind, 75.0, 25.0), v).unwrap(); + } + assert_eq!([faces[1], faces[2]].map(|f| fill_of(&s, f)), [green, Paint::None], "the triple-click matches the red the face was made with"); +} + +/// A triple-click whose first click adds paths to a selected Live Paint group and is released in a +/// face of that group matches the face's fill, not the edge around it. +#[test] +fn live_paint_bucket_triple_click_after_merging_across_an_edge_matches_the_face_fill() { + let mut s = session(); + let g = live_squares(&mut s, &[0.0]); + let [a] = faces_at(&s, g, &[(25.0, 25.0)])[..] else { panic!("one face") }; + let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 51.0, 51.0)); + paint_parts(&mut s, &all, &Paint::solid(Color::rgb(0.0, 0.0, 0.0)), &[(a, red.clone())]); + let (next, far) = (rect(&mut s, 50.0, 0.0, 50.0, 50.0), rect(&mut s, 200.0, 0.0, 50.0, 50.0)); + set_fill(&mut s, next, Color::rgb(0.0, 0.0, 1.0)); + set_fill(&mut s, far, Color::rgb(1.0, 0.0, 0.0)); + s.execute("select.set", &json!({"ids": [g.0, next.0, far.0]})).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(); + s.pointer(&PointerEvent::new(PointerKind::Down, 55.0, 25.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 45.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 click merged the paths"); + let faces = faces_at(&s, g, &[(25.0, 25.0), (225.0, 25.0)]); + assert_eq!(fill_of(&s, faces[0]), green, "the release fills the group's face"); + for kind in [PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick, PointerKind::Down, PointerKind::Up, PointerKind::TripleClick] { + s.pointer(&PointerEvent::new(kind, 45.0, 25.0), v).unwrap(); + } + assert_eq!(fill_of(&s, faces[1]), green, "the far face had the red the face had"); +} + +/// When the first click merges two selected Live Paint groups, a face of the group in front takes +/// its source path's fill, so a triple-click there after a release across an edge matches that fill +/// and not the paint the face had before the merge. +#[test] +fn live_paint_bucket_triple_click_after_merging_two_groups_matches_the_merged_fill() { + let mut s = session(); + let back = live_squares(&mut s, &[0.0]); + let source = rect(&mut s, 100.0, 0.0, 50.0, 50.0); + set_fill(&mut s, source, Color::rgb(1.0, 0.0, 0.0)); + s.execute("select.set", &json!({"ids": [source.0]})).unwrap(); + let front = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let [f] = faces_at(&s, front, &[(125.0, 25.0)])[..] else { panic!("one face") }; + let blue = Paint::solid(Color::rgb(0.0, 0.0, 1.0)); + paint_parts(&mut s, &[], &Paint::None, &[(f, blue.clone())]); + let (next, far) = (rect(&mut s, 150.0, 0.0, 50.0, 50.0), rect(&mut s, 300.0, 0.0, 50.0, 50.0)); + set_fill(&mut s, next, Color::rgb(1.0, 1.0, 0.0)); + set_fill(&mut s, far, Color::rgb(1.0, 0.0, 0.0)); + s.execute("select.set", &json!({"ids": [back.0, front.0, next.0, far.0]})).unwrap(); + let merged = NodeId(s.execute("livePaint.merge", &json!({})).unwrap()["id"].as_u64().unwrap()); + let [m] = faces_at(&s, merged, &[(125.0, 25.0)])[..] else { panic!("one face") }; + assert_eq!(fill_of(&s, m), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), "Merge gives the front group's face its source's fill"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [back.0, front.0, next.0, far.0]})).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(); + s.pointer(&PointerEvent::new(PointerKind::Down, 155.0, 25.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 145.0, 25.0), v).unwrap(); + let g = vectorcraft_tools::builder::live_paint_at(&s.doc().unwrap().doc, Point::new(125.0, 25.0)).expect("the click merged the groups"); + let faces = faces_at(&s, g, &[(125.0, 25.0), (325.0, 25.0)]); + assert_eq!(fill_of(&s, faces[0]), green, "the release fills the front group's face"); + for kind in [PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick, PointerKind::Down, PointerKind::Up, PointerKind::TripleClick] { + s.pointer(&PointerEvent::new(kind, 145.0, 25.0), v).unwrap(); + } + assert_eq!(fill_of(&s, faces[1]), green, "the far face had the red the merge gave the face"); +} + +/// When the first click merges paths into a selected Live Paint group whose face has an unplaced +/// gradient, Merge fixes the gradient to the face's fit, so a triple-click there after a release +/// across an edge matches the fixed gradient: a far face whose source has that same fixed gradient +/// takes the bucket's paint. +#[test] +fn live_paint_bucket_triple_click_after_merging_matches_the_fixed_gradient() { + use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)]; + let gradient = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops)))); + let mut s = session(); + let g = live_squares(&mut s, &[0.0]); + let [f] = faces_at(&s, g, &[(25.0, 25.0)])[..] else { panic!("one face") }; + paint_parts(&mut s, &[], &Paint::None, &[(f, gradient.clone())]); + let (next, far) = (rect(&mut s, 50.0, 0.0, 50.0, 50.0), rect(&mut s, 200.0, 0.0, 50.0, 50.0)); + set_fill(&mut s, next, Color::rgb(1.0, 1.0, 0.0)); + s.execute("select.set", &json!({"ids": [g.0, next.0]})).unwrap(); + let merged = NodeId(s.execute("livePaint.merge", &json!({})).unwrap()["id"].as_u64().unwrap()); + let [m] = faces_at(&s, merged, &[(25.0, 25.0)])[..] else { panic!("one face") }; + let fixed = fill_of(&s, m); + assert_ne!(fixed, gradient, "Merge fixes the face's gradient to its fit"); + s.execute("edit.undo", &json!({})).unwrap(); + s.edit("t", |d, _| { + d.node_mut(far).unwrap().appearance.set_fill(fixed.clone()); + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [g.0, next.0, far.0]})).unwrap(); + let v = ViewInfo::default(); + s.select_tool("livePaintBucket", v).unwrap(); + let green = Paint::solid(Color::from_hex("#00ff00").unwrap()); + s.paint.fill = green.clone(); + s.pointer(&PointerEvent::new(PointerKind::Down, 55.0, 25.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 45.0, 25.0), v).unwrap(); + let g = vectorcraft_tools::builder::live_paint_at(&s.doc().unwrap().doc, Point::new(45.0, 25.0)).expect("the click merged the paths"); + let [far_face] = faces_at(&s, g, &[(225.0, 25.0)])[..] else { panic!("the far face") }; + assert_eq!(fill_of(&s, far_face), fixed, "the far face keeps its source's fixed gradient"); + for kind in [PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick, PointerKind::Down, PointerKind::Up, PointerKind::TripleClick] { + s.pointer(&PointerEvent::new(kind, 45.0, 25.0), v).unwrap(); + } + assert_eq!(fill_of(&s, far_face), green, "the far face had the fixed gradient the merge gave the face"); +} + +/// When the first click merges a line that splits a painted face of the selected Live Paint group, +/// Merge keeps the face's paint in one part only and the other part takes its source path's fill; +/// a triple-click in that other part after a release across an edge matches the source's fill. +#[test] +fn live_paint_bucket_triple_click_after_a_merge_splits_a_face_matches_the_part_fill() { + let mut s = session(); + let source = rect(&mut s, 0.0, 0.0, 50.0, 50.0); + set_fill(&mut s, source, Color::rgb(1.0, 0.0, 0.0)); + s.execute("select.set", &json!({"ids": [source.0]})).unwrap(); + let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let [f] = faces_at(&s, g, &[(25.0, 25.0)])[..] else { panic!("one face") }; + paint_parts(&mut s, &[], &Paint::None, &[(f, Paint::solid(Color::rgb(0.0, 0.0, 1.0)))]); + let line = NodeId(s.execute("shape.line", &json!({"x1": 40, "y1": -10, "x2": 40, "y2": 60})).unwrap()["id"].as_u64().unwrap()); + let next = rect(&mut s, 50.0, 0.0, 50.0, 50.0); + set_fill(&mut s, next, Color::rgb(1.0, 1.0, 0.0)); + let (red_far, blue_far) = (rect(&mut s, 200.0, 0.0, 50.0, 50.0), rect(&mut s, 300.0, 0.0, 50.0, 50.0)); + set_fill(&mut s, red_far, Color::rgb(1.0, 0.0, 0.0)); + set_fill(&mut s, blue_far, Color::rgb(0.0, 0.0, 1.0)); + let ids = json!({"ids": [g.0, line.0, next.0, red_far.0, blue_far.0]}); + s.execute("select.set", &ids).unwrap(); + let merged = NodeId(s.execute("livePaint.merge", &json!({})).unwrap()["id"].as_u64().unwrap()); + let parts = faces_at(&s, merged, &[(20.0, 25.0), (45.0, 25.0)]); + assert_eq!( + parts.iter().map(|p| fill_of(&s, *p)).collect::>(), + [Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0))], + "Merge keeps the paint in the part that holds the face's inside point" + ); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("select.set", &ids).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(); + s.pointer(&PointerEvent::new(PointerKind::Down, 55.0, 25.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 45.0, 25.0), v).unwrap(); + for kind in [PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick, PointerKind::Down, PointerKind::Up, PointerKind::TripleClick] { + s.pointer(&PointerEvent::new(kind, 45.0, 25.0), v).unwrap(); + } + let g = vectorcraft_tools::builder::live_paint_at(&s.doc().unwrap().doc, Point::new(45.0, 25.0)).expect("the click merged the paths"); + let far = faces_at(&s, g, &[(225.0, 25.0), (325.0, 25.0)]); + assert_eq!(far.iter().map(|p| fill_of(&s, *p)).collect::>(), [green, Paint::solid(Color::rgb(0.0, 0.0, 1.0))]); +} + /// A triple-click whose first click makes the Live Paint group from the selected paths matches the /// fill the face was made with. #[test] @@ -3978,6 +4238,116 @@ fn live_paint_bucket_double_and_triple_click_paint_joined_and_same_stroke_edges( assert_eq!(node(&s, apart[0]).appearance.stroke_paint(), black); } +/// A double-click whose two clicks land on two joined edges paints every edge joined to them that +/// had their stroke: the edge the first click painted still joins the others. +#[test] +fn live_paint_bucket_double_click_across_a_junction_paints_the_joined_edges() { + // A square with a line across its middle, cut at x = 30 and x = 70 by two lines from the top: the + // middle line's three edges join end to end. + 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}]), + json!([{"x": 70, "y": 0}, {"x": 70, "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 (black, red) = (Paint::solid(Color::rgb(0.0, 0.0, 0.0)), 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, 101.0)); + paint_parts(&mut s, &all, &red, &[]); + let middle = edges_in(&s, g, Rect::new(-1.0, 49.0, 101.0, 51.0)); + assert_eq!(middle.len(), 3, "the middle line's three edges"); + paint_parts(&mut s, &middle, &black, &[]); + let v = ViewInfo::default(); + s.select_tool("livePaintBucket", v).unwrap(); + s.paint.stroke = green.clone(); + let shift = Mods { shift: true, ..Default::default() }; + for (kind, x) in + [(PointerKind::Down, 50.0), (PointerKind::Up, 50.0), (PointerKind::Down, 85.0), (PointerKind::Up, 85.0), (PointerKind::DoubleClick, 85.0)] + { + s.pointer(&PointerEvent::new(kind, x, 50.0).with_mods(shift), v).unwrap(); + } + assert_eq!(middle.iter().map(|e| node(&s, *e).appearance.stroke_paint()).collect::>(), [green.clone(), green.clone(), green]); + // `through` takes edge ids, with scope "connected" only. + for p in [ + json!({"group": g.0, "point": [15, 50], "scope": "connected", "through": "x"}), + json!({"group": g.0, "point": [15, 50], "scope": "connected", "through": [-1]}), + json!({"group": g.0, "point": [15, 50], "scope": "samePaint", "through": []}), + json!({"group": g.0, "point": [15, 50], "through": []}), + ] { + assert!(s.execute("livePaint.strokeEdge", &p).is_err(), "{p}"); + } +} + +/// A double-click whose second press lands on the next joined edge and is released back on the +/// edge the first click painted (at the end of the line) matches that edge's stroke paint from +/// before the first click, and the edge the second press painted still joins the edge past it. +#[test] +fn live_paint_bucket_double_click_released_back_on_the_first_edge_paints_the_joined_edges() { + 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}]), + json!([{"x": 70, "y": 0}, {"x": 70, "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 (black, red) = (Paint::solid(Color::rgb(0.0, 0.0, 0.0)), 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, 101.0)); + paint_parts(&mut s, &all, &red, &[]); + let middle = edges_in(&s, g, Rect::new(-1.0, 49.0, 101.0, 51.0)); + assert_eq!(middle.len(), 3, "the middle line's three edges"); + paint_parts(&mut s, &middle, &black, &[]); + let v = ViewInfo::default(); + s.select_tool("livePaintBucket", v).unwrap(); + s.paint.stroke = green.clone(); + let shift = Mods { shift: true, ..Default::default() }; + for (kind, x) in + [(PointerKind::Down, 15.0), (PointerKind::Up, 15.0), (PointerKind::Down, 50.0), (PointerKind::Up, 15.0), (PointerKind::DoubleClick, 15.0)] + { + s.pointer(&PointerEvent::new(kind, x, 50.0).with_mods(shift), v).unwrap(); + } + assert_eq!(middle.iter().map(|e| node(&s, *e).appearance.stroke_paint()).collect::>(), [green.clone(), green.clone(), green]); +} + +/// A triple-click whose second press holds Cmd (it goes to the selection tool Cmd lends) matches +/// the fill the face had before the first click: the lent press counts as one that paints nothing. +#[test] +fn live_paint_bucket_triple_click_with_a_cmd_press_between_matches_the_fill_before() { + 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::solid(Color::rgb(0.0, 0.0, 0.0)), &[(a, red.clone()), (b, red.clone()), (c, blue.clone()), (d, red.clone())]); + let v = ViewInfo::default(); + s.select_tool("livePaintBucket", v).unwrap(); + s.paint.fill = green.clone(); + let cmd = Mods { cmd: true, ..Default::default() }; + for (kind, m) in [ + (PointerKind::Down, Mods::default()), + (PointerKind::Up, Mods::default()), + (PointerKind::Down, cmd), + (PointerKind::Up, cmd), + (PointerKind::Down, Mods::default()), + (PointerKind::Up, Mods::default()), + (PointerKind::TripleClick, Mods::default()), + ] { + s.pointer(&PointerEvent::new(kind, 25.0, 25.0).with_mods(m), v).unwrap(); + } + assert_eq!(s.tool_id(), "livePaintBucket"); + assert_eq!([a, b, c, d].map(|f| fill_of(&s, f)), [green.clone(), green.clone(), blue, green]); +} + /// 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] @@ -5689,6 +6059,57 @@ fn a_trace_run_applies_only_in_its_own_document() { } } +/// A trace prepared before File › Revert doesn't apply after it, even when the document keeps its +/// uid and the restored image, object and settings are the same: both trace commands drop the +/// trace handed in and trace the restored image again, as one undo step. Reverting another +/// document, or a revert that fails, leaves the run current, and a trace prepared after the revert +/// applies as usual. +#[test] +fn a_trace_run_prepared_before_a_revert_does_not_apply_after_it() { + 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.clone(), None); + assert!(s.replace_document(b, copy.clone())); + assert!(s.set_active(a)); + assert!(run.current(&s) && !run.reverted(&s), "{command}: another document reverted"); + assert!(!s.replace_document(s.documents().len(), copy.clone())); + assert!(run.current(&s) && !run.reverted(&s), "{command}: a revert that failed"); + let (uid, reverts) = (s.doc().unwrap().uid, s.doc().unwrap().reverts); + assert!(s.replace_document(a, copy)); + assert_eq!(s.doc().unwrap().uid, uid, "{command}: the tab keeps its uid"); + assert_eq!(s.doc().unwrap().reverts, reverts + 1, "{command}"); + assert!(!run.current(&s), "{command}: reverted"); + assert!(run.reverted(&s), "{command}"); + traced.hand_in(&mut s); + let traces = cmd::TraceRun::traces_on_this_thread(); + let got = s.execute(run.command(), run.params()).unwrap(); + assert_eq!(cmd::TraceRun::traces_on_this_thread(), traces + 1, "{command}: traced again"); + 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"); + // A trace prepared after the revert is handed in and applied without tracing again. + let after = cmd::TraceRun::prepare(&s, command, run.params()).unwrap(); + let traced = after.run(&|_, _| true).unwrap(); + assert!(after.current(&s) && !after.reverted(&s), "{command}: prepared after the revert"); + traced.hand_in(&mut s); + let traces = cmd::TraceRun::traces_on_this_thread(); + s.execute(after.command(), after.params()).unwrap(); + assert_eq!(cmd::TraceRun::traces_on_this_thread(), traces, "{command}: the trace handed in applied"); + } +} + /// 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/charstroke.rs b/crates/engine/src/tests/charstroke.rs index 2c34e697ea..d692becbce 100644 --- a/crates/engine/src/tests/charstroke.rs +++ b/crates/engine/src/tests/charstroke.rs @@ -188,6 +188,77 @@ fn align_stroke_reaches_the_characters_stroke() { assert!(aligns.contains(&StrokeAlign::Inside) && aligns.contains(&StrokeAlign::Outside), "{aligns:?}"); } +/// The bounds of type `t`'s glyph outlines in text space. +fn glyph_bounds(t: &TextObject) -> kurbo::Rect { + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + let mut all = kurbo::BezPath::new(); + for g in &lay.glyphs { + all.extend(g.outline.iter()); + } + kurbo::Shape::bounding_box(&all) +} + +/// Create Outlines on type scaled 300% across and 100% down: the canvas strokes the characters in +/// text space and then scales them, so the outlined stroke is filled art three times as thick +/// across upright stems as across level bars, not a live stroke of one mean weight. +#[test] +fn create_outlines_keeps_the_character_strokes_thickness_under_an_uneven_scale() { + let mut s = session(); + let id = stroked_text(&mut s); + run(&mut s, "stroke.set", json!({"weight": 4, "join": "round", "cap": "round"})); + run(&mut s, "object.scale", json!({"ids": [id.0], "sx": 300, "sy": 100})); + let t = text(&s, id); + let [a, b, c, d, ..] = t.xf.as_coeffs(); + assert!((a - 3.0).abs() < 1e-9 && b.abs() < 1e-9 && c.abs() < 1e-9 && (d - 1.0).abs() < 1e-9, "{:?}", t.xf); + let w = t.runs[0].style.stroke_width; + let gb = glyph_bounds(&t); + run(&mut s, "select.set", json!({ "ids": [id.0] })); + let g = run(&mut s, "type.createOutlines", json!({}))["ids"][0].as_u64().unwrap(); + let doc = &s.doc().unwrap().doc; + let group = doc.node(NodeId(g)).unwrap(); + let mut strokes: Option = None; + for c in group.children().unwrap() { + assert!(c.appearance.stroke().is_none(), "no live stroke of one weight is left"); + if c.appearance.fill_paint() == Paint::solid(Color::rgb8(255, 0, 0)) { + let cb = c.geometric_bounds().unwrap(); + strokes = Some(strokes.map_or(cb, |s| s.union(cb))); + } + } + // Round joins and caps reach half the weight past the glyphs in text space, then scale. + let want = t.xf.transform_rect_bbox(gb.inflate(w / 2.0, w / 2.0)); + let got = strokes.expect("filled character strokes"); + assert!((got.width() - want.width()).abs() < 0.1 && (got.height() - want.height()).abs() < 0.1, "{got:?} for {want:?}"); + assert!((got.height() - (gb.height() + w)).abs() < 0.1, "level bars keep the weight: {got:?}"); +} + +/// Under a uniform scale and a rotation the outlined characters keep a live stroke, its weight +/// and dashes scaled with them. +#[test] +fn create_outlines_keeps_a_live_character_stroke_under_a_uniform_scale_and_rotation() { + let mut s = session(); + let id = stroked_text(&mut s); + run(&mut s, "stroke.set", json!({"weight": 4, "dash": [6, 2]})); + run(&mut s, "object.scale", json!({"ids": [id.0], "sx": 200, "sy": 200})); + run(&mut s, "object.rotate", json!({"angle": 30})); + let t = text(&s, id); + let k = t.xf.determinant().abs().sqrt(); + assert!((k - 2.0).abs() < 1e-9, "{:?}", t.xf); + let st = t.runs[0].style.clone(); + let dash = st.stroke_dash.as_ref().unwrap().pattern.clone(); + let glyphs = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).glyphs.len(); + run(&mut s, "select.set", json!({ "ids": [id.0] })); + let g = run(&mut s, "type.createOutlines", json!({}))["ids"][0].as_u64().unwrap(); + let doc = &s.doc().unwrap().doc; + let pieces = doc.node(NodeId(g)).unwrap().children().unwrap().to_vec(); + assert_eq!(pieces.len(), glyphs, "one path for each glyph, no filled strokes"); + for p in &pieces { + let ps = p.appearance.stroke().expect("a live stroke"); + assert!((ps.width - st.stroke_width * k).abs() < 1e-6, "{} for {}", ps.width, st.stroke_width * k); + let got = &ps.dash.as_ref().unwrap().pattern; + assert!(got.iter().zip(&dash).all(|(g, d)| (g - d * k).abs() < 1e-6), "{got:?} for {dash:?}"); + } +} + /// Copying type's appearance onto a path keeps its characters' stroke alignment (the Eyedropper's /// own stroke attributes have none, on paths as on type). #[test] diff --git a/crates/engine/src/tests/clipboard.rs b/crates/engine/src/tests/clipboard.rs index 368bc6de10..d049698222 100644 --- a/crates/engine/src/tests/clipboard.rs +++ b/crates/engine/src/tests/clipboard.rs @@ -768,6 +768,84 @@ fn a_legend_fill_of_its_own_stays_behind_when_pasted_without_formatting() { assert_eq!(label(&s, p, "North").1, Paint::solid(Color::WHITE), "still white when the pie is drawn again"); } +/// A pie pasted into a document whose swatch of the same name is another color takes that color on its linked wedges +/// (Merge), and its legend labels in those wedges take the contrast a redraw gives them there: white on a wedge that +/// turned dark. Pasting with Add, which keeps the copied color, keeps the labels as they were. +#[test] +fn pie_legend_labels_follow_wedges_that_take_the_documents_swatch() { + let mut s = session(); + let csv = ",North,South\nP,1,1"; + s.execute("swatch.new", &json!({"name": "Brand", "color": "#ffff66", "global": true})).unwrap(); + let g = id_of(&s.execute("graph.create", &json!({"type": "pie", "x": 50, "y": 50, "width": 200, "height": 200, "csv": csv})).unwrap()); + s.execute("graph.setType", &json!({"id": g.0, "pieLegend": "wedges"})).unwrap(); + /// The fill of the legend label of graph `id` that says `name`. + fn label(s: &Session, id: NodeId, name: &str) -> Paint { + let mut out = None; + node(s, id).walk(&mut |n| { + if let NodeKind::Text(t) = &n.kind + && t.plain_text() == name + { + out = Some(t.first_style().fill.clone()); + } + }); + out.unwrap() + } + // The North wedge, black when drawn, takes the light Brand swatch, and a redraw sets its label black. + let mut wedges = vec![]; + for c in node(&s, g).children().unwrap().iter().filter(|c| c.extras().series_index == Some(0)) { + c.walk(&mut |m| { + if matches!(m.kind, NodeKind::Path { .. }) { + wedges.push(m.id.0); + } + }); + } + assert!(!wedges.is_empty()); + s.execute("paint.setFill", &json!({"ids": wedges, "swatch": "Brand"})).unwrap(); + s.execute("graph.setData", &json!({"id": g.0, "csv": csv})).unwrap(); + assert_eq!(label(&s, g, "North"), Paint::solid(Color::BLACK), "black on the light wedge"); + assert_eq!(label(&s, g, "South"), Paint::solid(Color::BLACK)); + copy(&mut s, &[g]); + + for (cmd, choice, north) in [ + ("edit.pasteWithoutFormatting", "merge", Color::WHITE), + ("edit.paste", "merge", Color::WHITE), + ("edit.pasteWithoutFormatting", "add", Color::BLACK), + ("edit.paste", "add", Color::BLACK), + ] { + new_doc(&mut s); + s.execute("swatch.new", &json!({"name": "Brand", "color": "#202020", "global": true})).unwrap(); + let p = ids_of(&s.execute(cmd, &json!({"swatchConflict": choice})).unwrap())[0]; + assert_eq!(label(&s, p, "North"), Paint::solid(north), "{cmd} {choice}"); + assert_eq!(label(&s, p, "South"), Paint::solid(Color::BLACK), "{cmd} {choice}"); + s.execute("graph.setData", &json!({"id": p.0, "csv": csv})).unwrap(); + assert_eq!(label(&s, p, "North"), Paint::solid(north), "{cmd} {choice}: as a redraw sets it"); + } + + // A copy of the pie in the opacity mask of a rectangle follows the same way. + s.execute("document.activate", &json!({"index": 0})).unwrap(); + let r = rect(&mut s, 10.0, 10.0, 300.0, 300.0); + let art = { + let d = doc_mut(&mut s); + let pie = d.node(g).unwrap().clone(); + d.reid(&pie) + }; + doc_mut(&mut s).node_mut(r).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(art, true))); + copy(&mut s, &[r]); + new_doc(&mut s); + s.execute("swatch.new", &json!({"name": "Brand", "color": "#202020", "global": true})).unwrap(); + let p = ids_of(&s.execute("edit.paste", &json!({"swatchConflict": "merge"})).unwrap())[0]; + let mask = node(&s, p).extras().mask.as_deref().unwrap().art.clone(); + let mut north = None; + mask.walk(&mut |n| { + if let NodeKind::Text(t) = &n.kind + && t.plain_text() == "North" + { + north = Some(t.first_style().fill.clone()); + } + }); + assert_eq!(north, Some(Paint::solid(Color::WHITE)), "in an opacity mask"); +} + /// A two-line legend label in a narrow dark wedge, whose text sits off the wedge's middle line, stays white when its graph /// is pasted without formatting. #[test] @@ -1034,6 +1112,68 @@ fn a_repainted_wedge_sets_its_label_color_when_pasted_without_formatting() { assert_eq!(pasted, labels(&s, p), "copied as {before:?}"); } +/// Wedges linked to a global swatch that the destination document gives a dark color, merged on Paste without +/// Formatting, give their legend labels white characters, as a redraw does; added under a new name, they keep the +/// copied light color and black labels. +#[test] +fn wedges_merged_into_a_dark_swatch_give_white_labels_when_pasted_without_formatting() { + let csv = ",North,South\nP,1,1"; + fn labels(s: &Session, id: NodeId) -> Vec<(String, Paint)> { + let mut out = vec![]; + node(s, id).walk(&mut |n| { + if let NodeKind::Text(t) = &n.kind + && ["North", "South"].contains(&t.plain_text().as_str()) + { + out.push((t.plain_text(), t.first_style().fill.clone())); + } + }); + out + } + let both = |c: Color| vec![("North".to_string(), Paint::solid(c)), ("South".to_string(), Paint::solid(c))]; + for (conflict, expected) in [("merge", Color::WHITE), ("add", Color::BLACK)] { + let mut s = session(); + let g = id_of(&s.execute("graph.create", &json!({"type": "pie", "x": 50, "y": 50, "width": 200, "height": 200, "csv": csv})).unwrap()); + s.execute("graph.setType", &json!({"id": g.0, "pieLegend": "wedges"})).unwrap(); + s.execute("swatch.new", &json!({"name": "Ink", "color": "#ffffff", "global": true})).unwrap(); + let mut wedges = vec![]; + node(&s, g).walk(&mut |m| { + if let NodeKind::Path { .. } = m.kind { + wedges.push(m.id.0); + } + }); + s.execute("paint.setFill", &json!({"ids": wedges, "swatch": "Ink"})).unwrap(); + s.execute("graph.setData", &json!({"id": g.0, "csv": csv})).unwrap(); + assert_eq!(labels(&s, g), both(Color::BLACK), "light wedges have black labels"); + copy(&mut s, &[g]); + new_doc(&mut s); + s.execute("swatch.new", &json!({"name": "Ink", "color": "#000000", "global": true})).unwrap(); + let p = ids_of(&s.execute("edit.pasteWithoutFormatting", &json!({"swatchConflict": conflict})).unwrap())[0]; + let pasted = labels(&s, p); + assert_eq!(pasted, both(expected), "{conflict}"); + s.execute("graph.setData", &json!({"id": p.0, "csv": csv})).unwrap(); + assert_eq!(pasted, labels(&s, p), "{conflict}: as a redraw sets them"); + } +} + +/// An object linked to a graphic style and to a swatch merged with the document's keeps its graphic style link when +/// pasted without formatting, and its color shows the document's swatch. +#[test] +fn a_merged_swatch_keeps_graphic_style_links_when_pasted_without_formatting() { + let mut s = session(); + let r = swatched_rect(&mut s, "Ink", "#ffffff"); + sel(&mut s, &[r]); + s.execute("graphicStyle.new", &json!({"name": "Sun"})).unwrap(); + copy(&mut s, &[r]); + new_doc(&mut s); + s.execute("swatch.new", &json!({"name": "Ink", "color": "#000000", "global": true})).unwrap(); + let v = s.execute("edit.pasteWithoutFormatting", &json!({})).unwrap(); + assert_eq!(v["merged"], 1); + let p = ids_of(&v)[0]; + let style = node(&s, p).extras().graphic_style.and_then(|id| doc(&s).graphic_style_by_id(id)).map(|g| g.name.clone()); + assert_eq!(style.as_deref(), Some("Sun")); + assert_eq!(fill(&s, p), linked(hex("#000000"), "Ink", 1.0)); +} + /// When one pie's wedge of a series is repainted and another pie's wedge of that series is not, each pasted legend label /// takes the contrast of the wedge it is in. #[test] diff --git a/crates/engine/src/tests/constrain_new.rs b/crates/engine/src/tests/constrain_new.rs index 382e3af31c..49fd29e94b 100644 --- a/crates/engine/src/tests/constrain_new.rs +++ b/crates/engine/src/tests/constrain_new.rs @@ -40,7 +40,7 @@ fn close(a: f64, b: f64) -> bool { fn segment_angles(p: &PathData) -> Vec { p.subpaths .iter() - .flat_map(|sp| sp.anchors.windows(2).map(|w| w[1].p - w[0].p)) + .flat_map(|sp| sp.anchors.iter().zip(sp.anchors.iter().skip(1)).map(|(a, b)| b.p - a.p)) .filter(|v| v.hypot() > 1e-9) .map(|v| (-v.y).atan2(v.x).to_degrees().rem_euclid(90.0)) .collect() diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index a0129c1cd1..0a3f188fbc 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -890,7 +890,7 @@ fn curvature_rubber_band_is_the_path_the_click_makes() { s.pointer(&PointerEvent::new(PointerKind::Up, 450.0, 400.0), v).unwrap(); let made = path(&s, id).subpaths[0].clone(); assert_eq!(made.anchors.len(), 4); - let tail = vectorcraft_geom::SubPath::new(made.anchors[1..].to_vec(), false); + let tail = vectorcraft_geom::SubPath::new(made.anchors.to_vec()[1..].to_vec(), false); assert_eq!(preview, bez(&tail)); } @@ -1218,7 +1218,7 @@ fn scissors_cut_ellipse_end_drags_alone() { s.pointer(&PointerEvent::new(PointerKind::Up, cut.x + 8.0, cut.y + 8.0).with_mods(m), v).unwrap(); assert_eq!(undo_steps(&s), undo + 1); let after = path(&s, id); - let (old, new) = (&sp.anchors, &after.subpaths[0].anchors); + let (old, new) = (&sp.anchors.to_vec(), &after.subpaths[0].anchors.to_vec()); assert_eq!(new.len(), old.len()); assert_eq!(new[1..], old[1..], "only the dragged end moves (at anchor: {at_anchor}, {m:?})"); let d = Point::new(cut.x + 8.0, cut.y + 8.0) - cut; @@ -1572,7 +1572,7 @@ fn a_short_smooth_drag_leaves_the_rest_of_long_segments_alone() { drag(&mut s, "smooth", &[(195.0, 194.0), (205.0, 194.0)], Mods::default()); let p = path(&s, id); assert_ne!(p, before, "the bump is smoothed"); - let a = &p.subpaths[0].anchors; + let a = &p.subpaths[0].anchors.to_vec(); let (first, second, last) = (a[0], a[1], a[a.len() - 1]); assert!(first.p == Point::new(50.0, 200.0) && !first.has_out() && !second.has_in(), "the left side is a line still: {first:?} {second:?}"); assert!(last.p == Point::new(350.0, 200.0) && !last.has_in() && !a[a.len() - 2].has_out(), "and the right one: {last:?}"); @@ -1783,7 +1783,7 @@ fn smoothing_over_a_closed_paths_first_anchor_keeps_its_start() { 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] { + for a in &before.subpaths[0].anchors.to_vec()[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(); @@ -2326,6 +2326,39 @@ fn smoothing_keeps_a_corner_between_curves() { } } +/// A Smooth drag over a corner of a path cut into very many short segments keeps it, however many +/// segments twice the reach spans: an open path's 90° corner with legs of 2,000 segments 0.05 pt +/// long at the default reach, and a corner of a 200 pt square cut into 0.25 pt segments with a 40 pt +/// reach. +#[test] +fn smoothing_keeps_corners_on_a_path_of_many_short_segments() { + let mut s = session(); + let (id, v, drag) = smooth_corner_path(&mut s, 90.0, 2000); + smooth_pass(&mut s, &drag); + let at = smooth_turn_at(&path(&s, id).subpaths[0], v); + assert!(at.is_some_and(|t| (t - 90.0).abs() < 0.01), "the open path's corner is kept: {at:?}"); + + let mut s = session(); + let ends = [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 mut anchors = vec![]; + for k in 0..4 { + let (a, b) = (ends[k], ends[(k + 1) % 4]); + anchors.extend((0..800).map(|j| { + let p = a.lerp(b, f64::from(j) / 800.0); + json!({"x": p.x, "y": p.y}) + })); + } + let id = smooth_test_path(&mut s, &anchors, true); + let v = ends[1]; + 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 + kurbo::Vec2::new(0.0, 5.0 * f64::from(k)))); + let pts: Vec<_> = drag.iter().map(|p| json!([p.x, p.y])).collect(); + s.execute("path.smoothRegion", &json!({"points": pts, "radius": 40, "fidelity": 2.5})).unwrap(); + let sp = &path(&s, id).subpaths[0]; + let at = smooth_turn_at(sp, v); + assert!(sp.closed && at.is_some_and(|t| (t - 90.0).abs() < 0.01), "the square's corner 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] @@ -3885,7 +3918,7 @@ fn pen_cmd_selected_anchors_are_what_copy_and_cut_take() { assert!(left.is_empty()); assert!(s.doc().unwrap().selection.objects.is_empty()); assert_eq!(s.clipboard.nodes.len(), 1); - assert_eq!(s.clipboard.nodes[0].path_data().unwrap().subpaths[0].anchors, original.subpaths[0].anchors[1..3]); + assert_eq!(s.clipboard.nodes[0].path_data().unwrap().subpaths[0].anchors, original.subpaths[0].anchors.to_vec()[1..3]); s.execute("edit.undo", &json!({})).unwrap(); assert_eq!(paths(&s), vec![(id, original.clone())]); assert_eq!(s.doc().unwrap().selection, picked); diff --git a/crates/engine/src/tests/gradient.rs b/crates/engine/src/tests/gradient.rs index 9f404b050d..14cdb653b5 100644 --- a/crates/engine/src/tests/gradient.rs +++ b/crates/engine/src/tests/gradient.rs @@ -377,14 +377,15 @@ fn annotator_gestures_edit_the_gradient_as_single_undo_steps() { assert_eq!(stops.len(), 3); assert!((stops[1].offset - 0.3).abs() < 1e-6); assert_eq!(s.selected_stop(), Some(1)); - // Dragging the end handle changes only the end, as one undo step. + // Dragging the end handle changes only the length (the end stays on the bar's line), as one + // undo step. let undo = s.doc().unwrap().history.undo.len(); gesture( &mut s, &[(PointerKind::Down, 200.0, 150.0), (PointerKind::Drag, 210.0, 160.0), (PointerKind::Drag, 220.0, 170.0), (PointerKind::Up, 220.0, 170.0)], ); let g = fill_geom(&s, id); - assert_eq!((g.start, g.end), (Point::new(100.0, 150.0), Point::new(220.0, 170.0))); + assert_eq!((g.start, g.end), (Point::new(100.0, 150.0), Point::new(220.0, 150.0))); assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); s.execute("edit.undo", &json!({})).unwrap(); // The selected stop takes Delete ahead of edit.clear; the object stays. diff --git a/crates/engine/src/tests/gradspan.rs b/crates/engine/src/tests/gradspan.rs index 9674204642..664afdbdb6 100644 --- a/crates/engine/src/tests/gradspan.rs +++ b/crates/engine/src/tests/gradspan.rs @@ -119,6 +119,28 @@ fn strokes_span_the_targets_too() { assert!(ga.start.x < 0.0 && ga.end.x > 400.0, "the stroke's box, half its weight out: {ga:?}"); } +#[test] +fn a_lower_stroke_row_spans_the_box_that_row_paints() { + let mut s = session(); + let a = rect(&mut s, 0.0, 50.0, 100.0, 100.0); + let b = rect(&mut s, 300.0, 50.0, 100.0, 100.0); + // [Fill, Stroke 40 pt, Stroke 1 pt] on both. + s.execute("appearance.addStroke", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("stroke.set", &json!({"ids": [a.0, b.0], "item": 1, "weight": 40})).unwrap(); + for aligned in [false, true] { + s.execute("paint.setStroke", &json!({"ids": [a.0, b.0], "item": 1, "aligned": aligned, "gradient": black_to_white(), "span": "selection"})) + .unwrap(); + for id in [a, b] { + let Paint::Gradient(g) = &s.doc().unwrap().doc.node(id).unwrap().appearance.stroke_at(Some(1)).unwrap().paint else { + panic!("expected a gradient on stroke row 1") + }; + // The 40 pt row reaches 20 pt past the union 0..400, not the 1 pt topmost stroke's 0.5 pt. + let geom = g.geom.expect("placed in document coordinates"); + assert!(near(geom.start, Point::new(-20.0, 100.0)) && near(geom.end, Point::new(420.0, 100.0)), "aligned {aligned}, {id:?}: {geom:?}"); + } + } +} + #[test] fn the_new_art_default_stays_unplaced() { let mut s = session(); diff --git a/crates/engine/src/tests/linked_stops.rs b/crates/engine/src/tests/linked_stops.rs index 62955e6065..a0f001afe6 100644 --- a/crates/engine/src/tests/linked_stops.rs +++ b/crates/engine/src/tests/linked_stops.rs @@ -231,6 +231,75 @@ fn deleting_a_spot_swatch_takes_the_process_plates_of_the_stops_it_unlinks() { assert_eq!(gradient(&s, id).gradient.stops[1], linked, "undo brings back the link and the plates"); } +/// The stops of the gradients the merge test puts in place: the art's fill, gradient swatch "Glow", +/// graphic style "Style", the art of brush "Brush" and the fill new art takes. +fn merge_test_stops(s: &Session, id: NodeId) -> Vec<(&'static str, Vec)> { + let d = doc(s); + let stops = |p: Paint| match p { + Paint::Gradient(g) => g.gradient.stops, + p => panic!("not a gradient: {p:?}"), + }; + let style = d.graphic_style("Style").unwrap().appearance.items.iter().find_map(|it| match it { + vectorcraft_doc::AppearanceItem::Fill(f) => Some(f.paint.clone()), + vectorcraft_doc::AppearanceItem::Stroke(_) => None, + }); + let mut brush = None; + for n in vectorcraft_brush::find(d, "Brush").unwrap().art() { + n.walk(&mut |m| { + if brush.is_none() && matches!(m.appearance.fill_paint(), Paint::Gradient(_)) { + brush = Some(m.appearance.fill_paint()); + } + }); + } + vec![ + ("art", stops(d.node(id).unwrap().appearance.fill_paint())), + ("gradient swatch", stops(d.swatch("Glow").unwrap().paint.clone())), + ("graphic style", stops(style.unwrap())), + ("brush art", stops(brush.unwrap())), + ("new art", stops(s.paint.fill.clone())), + ] +} + +#[test] +fn merging_swatches_takes_the_process_plates_of_the_stops_it_relinks() { + // Kept swatch "Keep": spot, global process, and process that isn't global. + for (spot, global) in [(true, true), (false, true), (false, false)] { + let (mut s, id) = setup(); + run(&mut s, "swatch.new", json!({"name": "Keep", "color": "#00ff00", "spot": spot, "global": global})); + run(&mut s, "swatch.new", json!({"name": "Other", "color": {"c": 1, "m": 0, "y": 0, "k": 0}, "spot": true})); + // Ink at 50 % over a 30 % cyan plate, and Other over its own 20 % magenta plate, which the + // merge leaves alone. + let plated = json!({"stops": [ + {"offset": 0, "swatch": "Ink", "tint": 50, "plates": [0.3, 0, 0, 0]}, + {"offset": 1, "swatch": "Other", "plates": [0, 0.2, 0, 0]}, + ]}); + run(&mut s, "paint.editGradient", plated.clone()); + run(&mut s, "swatch.new", json!({"name": "Glow", "gradient": plated})); + run(&mut s, "graphicStyle.new", json!({"name": "Style"})); + run(&mut s, "brush.new", json!({"type": "art", "name": "Brush"})); + s.paint.fill = doc(&s).node(id).unwrap().appearance.fill_paint(); + let before = merge_test_stops(&s, id); + let kept = doc(&s).linked_color(doc(&s).swatch("Keep").unwrap().paint.color().unwrap(), spot); + assert!(before.iter().all(|(_, st)| st[0].plates == Some([0.3, 0.0, 0.0, 0.0])), "{before:?}"); + + run(&mut s, "swatch.merge", json!({"names": ["Keep", "Ink"]})); + let after = merge_test_stops(&s, id); + // The stop shows its tint of the kept color, unlinked when the kept swatch isn't global. + let (link, tint, color) = if global { (Some("Keep"), 0.5, kept.tinted(0.5)) } else { (None, 1.0, kept.tinted(0.5)) }; + for (place, st) in &after { + let what = format!("spot {spot}, global {global}, {place}: {st:?}"); + assert_eq!((st[0].swatch.as_deref(), st[0].tint, st[0].plates), (link, tint, None), "{what}"); + assert_eq!(st[0].color, color, "{what}"); + assert_eq!((st[1].swatch.as_deref(), st[1].plates), (Some("Other"), Some([0.0, 0.2, 0.0, 0.0])), "{what}"); + } + + run(&mut s, "edit.undo", json!({})); + assert_eq!(merge_test_stops(&s, id), before, "undo brings back the links and the plates"); + run(&mut s, "edit.redo", json!({})); + assert_eq!(merge_test_stops(&s, id), after, "redo merges again"); + } +} + #[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 57bb9e278e..931c011d40 100644 --- a/crates/engine/src/tests/links.rs +++ b/crates/engine/src/tests/links.rs @@ -2138,3 +2138,141 @@ fn confined_preserve_editing_svg_refuses_a_brush_library_entry_it_cannot_read() confine(roots.as_ref(), || s.execute("document.serialize", &json!({"format": "svg"}))).unwrap(); } } + +/// A confined caller's SVG of a placed document whose art links an image: the file draws that art +/// and names the image's file, so a file outside the read roots refuses it and one inside them is +/// written. Any output that names no file is written. +#[test] +fn confined_svg_output_checks_the_images_of_placed_documents() { + use crate::file_access::{AutomationRoots, confine}; + + let away = Folder::new("svg-placed-away"); + let home = Folder::new("svg-placed-home"); + let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap(); + for (photo, outside) in [(away.file("photo.png"), true), (home.file("photo.png"), false)] { + write(&photo, &png(60, 30, RED)); + let src = home.file("src.vectorcraft"); + let mut inner = session(); + place(&mut inner, &photo); + save(&mut inner, &src); + let mut s = session(); + place(&mut s, &src); + let link = json!({"format": "svg", "images": "link"}); + assert!(svg_text(&s.execute("document.serialize", &link).unwrap()).contains(&photo), "the file names the placed art's image"); + for format in ["svg", "svgz"] { + for images in ["link", "embed"] { + let p = json!({"format": format, "images": images}); + // Embed writes the pixels the placed file holds. + let names = svg_text(&s.execute("document.serialize", &p).unwrap()).contains(&photo); + assert_eq!(names, images == "link", "{p}"); + match confine(roots.as_ref(), || s.execute("document.serialize", &p)) { + Ok(r) => assert!(!outside || !svg_text(&r).contains(&photo), "{p}: {}", svg_text(&r)), + Err(e) => { + assert!(outside && names, "{p}: {e}"); + assert!(e.to_string().contains("a linked image file is outside the read roots"), "{p}: {e}"); + } + } + } + } + if outside { + let e = confine(roots.as_ref(), || s.execute("document.serialize", &link)).unwrap_err().to_string(); + assert!(e.contains("a linked image file is outside the read roots") && !e.contains("photo.png"), "{e}"); + } + } +} + +/// A confined caller's SVG of a symbol holding a visible rectangle and a hidden linked image outside +/// the read roots: the file leaves the hidden image out of the symbol and is written, unless hidden +/// layers are kept, which writes the image and refuses the file. +#[test] +fn confined_svg_output_leaves_hidden_symbol_art_unchecked() { + use crate::file_access::{AutomationRoots, confine}; + + let away = Folder::new("svg-symbol-hidden-away"); + let home = Folder::new("svg-symbol-hidden-home"); + let photo = away.file("photo.png"); + write(&photo, &png(60, 30, RED)); + let mut s = session(); + let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap()["id"].clone(); + let a = place(&mut s, &photo); + s.execute("object.hide", &json!({"ids": [a.0]})).unwrap(); + s.execute("select.set", &json!({"ids": [r, a.0]})).unwrap(); + s.execute("symbol.new", &json!({"name": "Mixed"})).unwrap(); + let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap(); + for format in ["svg", "svgz"] { + let p = json!({"format": format, "images": "link"}); + assert!(!svg_text(&s.execute("document.serialize", &p).unwrap()).contains(&photo), "{p}"); + let text = svg_text(&confine(roots.as_ref(), || s.execute("document.serialize", &p)).unwrap()); + assert!(!text.contains(&photo), "{p}: {text}"); + let kept = json!({"format": format, "images": "link", "hiddenLayers": true}); + assert!(svg_text(&s.execute("document.serialize", &kept).unwrap()).contains(&photo), "{kept}"); + let e = confine(roots.as_ref(), || s.execute("document.serialize", &kept)).unwrap_err().to_string(); + assert!(e.contains("a linked image file is outside the read roots"), "{kept}: {e}"); + } +} + +/// A confined caller's SVG Tiny 1.2 of an object whose opacity mask is a linked image outside the +/// read roots: the Tiny file leaves the mask out and is written; SVG 1.1 writes the mask and is +/// refused. +#[test] +fn confined_svg_tiny_output_leaves_opacity_mask_images_unchecked() { + use crate::file_access::{AutomationRoots, confine}; + + let away = Folder::new("svg-tiny-mask-away"); + let home = Folder::new("svg-tiny-mask-home"); + let photo = away.file("photo.png"); + write(&photo, &png(60, 30, RED)); + let mut s = session(); + let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap()["id"].clone(); + let a = place(&mut s, &photo); + s.execute("select.set", &json!({"ids": [r, a.0]})).unwrap(); + s.execute("transparency.makeOpacityMask", &json!({})).unwrap(); + let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap(); + for format in ["svg", "svgz"] { + let tiny = json!({"format": format, "images": "link", "profile": "tiny12"}); + assert!(!svg_text(&s.execute("document.serialize", &tiny).unwrap()).contains(&photo), "{tiny}"); + let text = svg_text(&confine(roots.as_ref(), || s.execute("document.serialize", &tiny)).unwrap()); + assert!(!text.contains(&photo), "{tiny}: {text}"); + let full = json!({"format": format, "images": "link"}); + assert!(svg_text(&s.execute("document.serialize", &full).unwrap()).contains(&photo), "{full}"); + let e = confine(roots.as_ref(), || s.execute("document.serialize", &full)).unwrap_err().to_string(); + assert!(e.contains("a linked image file is outside the read roots"), "{full}: {e}"); + } +} + +/// A confined caller's SVG of a linked image outside the read roots, without pixels in the +/// document, under Radial Blur: the file and the clipboard draw the rendered image in its place, +/// name no file, and are written. +#[test] +fn confined_svg_output_checks_the_images_drawn_for_pixel_effects() { + use crate::file_access::{AutomationRoots, confine}; + + let away = Folder::new("svg-flat-away"); + let home = Folder::new("svg-flat-home"); + let photo = away.file("photo.png"); + write(&photo, &png(60, 30, RED)); + let mut s = session(); + let a = place(&mut s, &photo); + s.execute("effect.apply", &json!({"effect": "blur.radial", "ids": [a.0], "params": {"amount": 30, "quality": "draft"}})).unwrap(); + without_pixels(&mut s, a); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap(); + let clip = + |s: &mut Session| confine(roots.as_ref(), || s.execute("clipboard.exportSvg", &json!({}))).unwrap()["svg"].as_str().unwrap().to_string(); + assert!(!clip(&mut s).contains(&photo)); + assert!(confine(roots.as_ref(), || s.clipboard_svg()).is_some_and(|svg| !svg.contains(&photo))); + for format in ["svg", "svgz"] { + for images in ["link", "embed"] { + let p = json!({"format": format, "images": images}); + let text = svg_text(&confine(roots.as_ref(), || s.execute("document.serialize", &p)).unwrap()); + assert!(!text.contains(&photo), "{p}: {text}"); + } + } + // Without the effect, the image names its file. + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("effect.remove", &json!({"index": 0})).unwrap(); + assert!(s.doc().unwrap().doc.node(a).unwrap().appearance.effects.is_empty()); + let e = confine(roots.as_ref(), || s.execute("document.serialize", &json!({"format": "svg"}))).unwrap_err().to_string(); + assert!(e.contains("a linked image file is outside the read roots"), "{e}"); +} diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index 4afab29a91..1db3ffa34e 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -3299,6 +3299,32 @@ fn select_all_on_artboard_refuses_an_artboard_past_u32() { assert!(selected(&s).is_empty()); } +/// All on Active Artboard refuses an `artboard` that is not a whole number, naming the parameter, +/// and leaves the selection as it was; a whole number past the last artboard is `no such +/// artboard`. Left out or null, it takes the first artboard. +#[test] +fn select_all_on_artboard_refuses_an_artboard_that_is_not_a_whole_number() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 2, "artboardLayout": {"layout": "row", "spacing": 0}})).unwrap(); + let (first, second) = (rect(&mut s, 10.0, 10.0, 20.0, 20.0), rect(&mut s, 110.0, 10.0, 20.0, 20.0)); + for bad in [json!("1"), json!(-1), json!(1.5), json!(true), json!([1]), json!({})] { + s.execute("select.none", &json!({})).unwrap(); + let err = s.execute("select.allOnArtboard", &json!({"artboard": bad})).unwrap_err().to_string(); + assert_eq!(err, "invalid parameters for `select.allOnArtboard`: `artboard` must be a whole number", "{bad}"); + assert!(selected(&s).is_empty(), "{bad}"); + } + s.execute("select.none", &json!({})).unwrap(); + assert_eq!(s.execute("select.allOnArtboard", &json!({"artboard": 9})).unwrap_err().to_string(), "no such artboard"); + assert!(selected(&s).is_empty()); + for p in [json!({}), json!({"artboard": null}), json!({"artboard": 0})] { + s.execute("select.none", &json!({})).unwrap(); + s.execute("select.allOnArtboard", &p).unwrap(); + assert_eq!(selected(&s), vec![first], "{p}"); + } + s.execute("select.allOnArtboard", &json!({"artboard": 1})).unwrap(); + assert_eq!(selected(&s), vec![second]); +} + #[test] fn save_and_recall_selection() { let mut s = session(); @@ -4605,6 +4631,27 @@ fn artboard_guides_go_with_their_artboard() { assert_eq!((guides(&s).len(), selected_guides(&s)), (3, vec![0, 1])); } +/// `guide.add` refuses an `artboard` that is not a whole number, naming the parameter, and adds no +/// guide; a whole number past the last artboard is `no such artboard`. Null makes a canvas guide, +/// and a whole number an artboard guide. +#[test] +fn guide_add_refuses_an_artboard_that_is_not_a_whole_number() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 900, "y": 0, "width": 400, "height": 300})).unwrap(); + let add = |s: &mut Session, artboard: Value| s.execute("guide.add", &json!({"vertical": true, "pos": 10, "artboard": artboard})); + for bad in [json!("1"), json!(-1), json!(1.5), json!(true), json!([1]), json!({})] { + let err = add(&mut s, bad.clone()).unwrap_err().to_string(); + assert_eq!(err, "invalid parameters for `guide.add`: `artboard` must be a whole number", "{bad}"); + } + assert_eq!(add(&mut s, json!(9)).unwrap_err().to_string(), "no such artboard"); + assert!(s.doc().unwrap().doc.ruler_guides().is_empty()); + add(&mut s, Value::Null).unwrap(); + add(&mut s, json!(1)).unwrap(); + let d = &s.doc().unwrap().doc; + let boards: Vec<_> = d.ruler_guides().iter().map(|g| g.artboard).collect(); + assert_eq!(boards, [None, Some(d.artboards[1].id)]); +} + /// #451: a guide dragged out of a ruler snaps (to the art's corners, side midpoints and anchors, /// the artboards' edges and centres) and is made in one undo step where it is released over the /// canvas; with the Artboard tool it is an artboard guide of the active artboard. diff --git a/crates/engine/src/tests/objexpand.rs b/crates/engine/src/tests/objexpand.rs index 494c070a66..1bac01d48d 100644 --- a/crates/engine/src/tests/objexpand.rs +++ b/crates/engine/src/tests/objexpand.rs @@ -717,6 +717,29 @@ fn type_reports_a_gradient_when_any_glyph_expands() { assert_eq!(gradients_and_type(&s), (1, 0), "the large glyph keeps its gradient"); } +/// Type scaled unevenly outlines its characters' stroke as a filled path, so a gradient on that +/// stroke becomes a gradient fill: the query reports it, and Expand turns it into art. +#[test] +fn type_reports_a_stroke_gradient_its_uneven_scale_turns_into_a_fill() { + let mut s = session(); + let t = run(&mut s, "text.create", json!({"x": 50, "y": 100, "text": "Hi", "size": 48}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids": [t]})); + run( + &mut s, + "paint.setStroke", + json!({"gradient": {"kind": "linear", "spread": "repeat", "repeats": 100, "start": [50, 100], "end": [70, 100], + "stops": [{"offset": 0, "color": "#ffff00"}, {"offset": 1, "color": "#004080"}]}}), + ); + run(&mut s, "stroke.set", json!({"weight": 4})); + let info = run(&mut s, "object.expand.info", json!({})); + assert_eq!(info["gradient"], json!(false), "a live stroke's gradient is not a fill"); + run(&mut s, "object.scale", json!({"ids": [t], "sx": 300, "sy": 100})); + let info = run(&mut s, "object.expand.info", json!({})); + assert_eq!((info["gradient"].clone(), info["fill"].clone()), (json!(true), json!(true))); + run(&mut s, "object.expand", json!({})); + assert_eq!(gradients_and_type(&s), (0, 0), "the filled strokes' gradients became art"); +} + /// The same rule for type in the art of a symbol instance that Object expands. The symbol's art /// is the type scaled down (its "i" about 2.5 pt wide), so its glyphs need more runs than are /// written with 0.002 pt runs (over a 0.2 pt vector). diff --git a/crates/engine/src/tests/paintproxy.rs b/crates/engine/src/tests/paintproxy.rs index b270826e7a..e10f2df6d8 100644 --- a/crates/engine/src/tests/paintproxy.rs +++ b/crates/engine/src/tests/paintproxy.rs @@ -706,3 +706,16 @@ fn a_marker_designs_art_in_a_series_keeps_its_paint() { s.execute("addon.color.fillToStroke", &json!({"ids": [series.id.0]})).unwrap(); assert_eq!(design_strokes(&s), before, "the design's art keeps its paint"); } + +/// Invert given a member of a compound path inverts the compound path's fill, which the member stands for. +#[test] +fn invert_of_a_compound_member_inverts_the_compound_path() { + let mut s = session(); + let (a, b) = (rect(&mut s), rect(&mut s)); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let comp = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"ids": [comp.0], "color": "#ff0000"})).unwrap(); + let member = node(&s, comp).children().into_iter().flatten().next().unwrap().id; + s.execute("paint.invert", &json!({"ids": [member.0]})).unwrap(); + assert_eq!(node(&s, comp).appearance.fill_paint().color().unwrap().to_hex(), "#00ffff"); +} diff --git a/crates/engine/src/tests/panelcmds.rs b/crates/engine/src/tests/panelcmds.rs index 715bf2b8ce..7d2675e938 100644 --- a/crates/engine/src/tests/panelcmds.rs +++ b/crates/engine/src/tests/panelcmds.rs @@ -1722,6 +1722,35 @@ fn text_set_format() { assert_eq!(t.para.composer, vectorcraft_doc::Composer::EveryLine); } +/// `text.setFormat {composer}` takes the two Middle Eastern & South Asian and the two Standard +/// composers, each per paragraph and one undo step; any other value is refused and names them all. +#[test] +fn text_set_format_takes_the_four_composers() { + use vectorcraft_doc::Composer; + let mut s = session(); + let r = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "One\nTwo"})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + let composers = |s: &Session| { + let NodeKind::Text(t) = node(s, id).kind else { panic!() }; + [t.para_at(0).composer, t.para_at(1).composer] + }; + assert_eq!(composers(&s), [Composer::EveryLine; 2], "new type is ME&SA Every-line"); + for (value, want) in [ + ("singleLine", Composer::SingleLine), + ("standardSingleLine", Composer::StandardSingleLine), + ("standardEveryLine", Composer::StandardEveryLine), + ("everyLine", Composer::EveryLine), + ] { + s.execute("text.setFormat", &json!({"ids": [id.0], "composer": value, "start": 4, "end": 4})).unwrap(); + assert_eq!(composers(&s), [Composer::EveryLine, want], "{value}: only the second paragraph"); + } + s.execute("text.setFormat", &json!({"ids": [id.0], "composer": "standardEveryLine"})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(composers(&s), [Composer::EveryLine; 2], "one undo step"); + let e = s.execute("text.setFormat", &json!({"ids": [id.0], "composer": "standard"})).unwrap_err().to_string(); + assert!(e.contains("standardSingleLine") && e.contains("standardEveryLine"), "{e}"); +} + #[test] fn stroke_advanced_scale_swap_flip() { let mut s = session(); diff --git a/crates/engine/src/tests/params.rs b/crates/engine/src/tests/params.rs index 52cb314de0..708b602d1f 100644 --- a/crates/engine/src/tests/params.rs +++ b/crates/engine/src/tests/params.rs @@ -704,10 +704,11 @@ fn effect_params_are_the_effects_own() { fn an_effect_parameter_without_a_default_is_held_to_its_type() { use crate::cmd::params::undefaulted_type; use vectorcraft_render::effects::effect_catalog; - // Read by checks of their own: a stored texture or a texture to load, an SVG filter, a Warp's + // Read by checks of their own: a stored texture or a texture to load, an SVG filter and its axes, a Warp's // map and the style of Crop Marks. let own_check = |effect: &str, key: &str| match key { "textureImage" | "name" | "xml" => true, + "axes" => effect == "svg.filter", "version" => effect.starts_with("warp."), "style" => effect == "cropMarks", _ => false, diff --git a/crates/engine/src/tests/place.rs b/crates/engine/src/tests/place.rs index 8dbe06f349..cade51bca6 100644 --- a/crates/engine/src/tests/place.rs +++ b/crates/engine/src/tests/place.rs @@ -1101,6 +1101,35 @@ fn the_place_queue_skips_an_image_whose_pixels_cant_be_read() { assert_eq!(b.place_queue_read(read).unwrap(), r); } +/// An encrypted PDF stays in the place cursor's queue, read with the session or apart from it, at +/// a letter page's size with `needsPassword`, so that a click in the app can ask for its password; +/// headless, a click on it places nothing. +#[test] +fn the_place_queue_keeps_an_encrypted_pdf() { + use vectorcraft_testkit::pdf::{PdfPage, pdf}; + let locked = pdf(&[PdfPage::new(100.0, 50.0, "0 g 0 0 10 10 re f")], Some("pw")); + let p = json!({"files": [file("locked.pdf", &locked), file("a.png", &png(40, 20, [9, 9, 9, 255], None))], "thumbnail": 8}); + let (mut a, mut b) = (session(), session()); + let r = a.execute("file.place.queue", &p).unwrap(); + assert_eq!((&r["count"], &r["skipped"]), (&json!(2), &json!([])), "{r}"); + assert_eq!(r["files"][0], json!({"name": "locked.pdf", "format": "pdf", "width": 612.0, "height": 792.0, "needsPassword": true})); + assert!(r["files"][1].get("needsPassword").is_none()); + let read = b.prepare_place_queue(&p).unwrap().read().unwrap(); + assert_eq!(b.place_queue_read(read).unwrap(), r); + let view = ViewInfo::default(); + assert_eq!(a.tool_options()["name"], "locked.pdf"); + let _ = a.pointer(&PointerEvent::new(PointerKind::Down, 10.0, 10.0), view); + let _ = a.pointer(&PointerEvent::new(PointerKind::Up, 10.0, 10.0), view); + assert_eq!((top_children(&a).len(), a.doc().unwrap().history.undo.len()), (0, 0), "nothing placed without the password"); + // An encrypted PDF with a bad option is refused for the option, not kept. + let e = a.execute("file.place.queue", &json!({"files": [file("locked.pdf", &locked)], "page": 0})).unwrap_err().to_string(); + assert!(e.contains("page must be a whole number from 1"), "{e}"); + // A PDF that can't be read for another reason is still skipped. + let broken = file("broken.pdf", b"%PDF-1.7\nnot a PDF body\n"); + let r = a.execute("file.place.queue", &json!({"files": [broken, file("b.png", &png(4, 4, [0; 4], None))]})).unwrap(); + assert_eq!((&r["count"], &r["skipped"][0]["name"]), (&json!(1), &json!("broken.pdf")), "{r}"); +} + /// The place queue's thumbnail of an image is drawn from the pixels its check decoded, so each /// image is decoded once. #[test] diff --git a/crates/engine/src/tests/simplify_part.rs b/crates/engine/src/tests/simplify_part.rs index 12f3330595..f3ab93f274 100644 --- a/crates/engine/src/tests/simplify_part.rs +++ b/crates/engine/src/tests/simplify_part.rs @@ -73,8 +73,8 @@ fn simplify_refits_only_the_run_between_direct_selected_anchors() { assert_eq!(out["after"].as_u64(), Some(len as u64)); assert!(len < 101 - 30, "{len}"); let end = len - 41; - assert_eq!(sp.anchors[..20], original.anchors[..20], "the anchors before the run"); - assert_eq!(sp.anchors[end + 1..], original.anchors[61..], "the anchors after the run"); + assert_eq!(sp.anchors.to_vec()[..20], original.anchors.to_vec()[..20], "the anchors before the run"); + assert_eq!(sp.anchors.to_vec()[end + 1..], original.anchors.to_vec()[61..], "the anchors after the run"); assert_eq!((sp.anchors[20].p, sp.anchors[20].h_in), (original.anchors[20].p, original.anchors[20].h_in)); assert_eq!((sp.anchors[end].p, sp.anchors[end].h_out), (original.anchors[60].p, original.anchors[60].h_out)); for i in 0..20 { @@ -100,7 +100,7 @@ fn separate_runs_on_one_path_simplify_independently_in_one_step() { let id = wave(&mut s); select_anchors(&mut s, id, ranges); s.execute("object.path.simplify", &json!({"tolerance": 1})).unwrap(); - path_of(&s, id).subpaths[0].anchors.clone() + path_of(&s, id).subpaths[0].anchors.to_vec() }; let (first, second) = (alone(&[(10, 30)]), alone(&[(60, 80)])); let mut s = session(); @@ -110,13 +110,13 @@ fn separate_runs_on_one_path_simplify_independently_in_one_step() { let undo = undo_len(&s); s.execute("object.path.simplify", &json!({"tolerance": 1})).unwrap(); assert_eq!(undo_len(&s), undo + 1, "one undo step"); - let both = path_of(&s, id).subpaths[0].anchors.clone(); + let both = path_of(&s, id).subpaths[0].anchors.to_vec(); // Where old anchor 30 is in the first result, and old anchor 80 in the second. let (a30, a80) = (first.len() - 71, second.len() - 21); assert!(a30 < 30 && a80 < 80, "both runs lose anchors"); let mid = a30 + 30; assert_eq!(both[..=a30], first[..=a30]); - assert_eq!(both[a30 + 1..mid], original.anchors[31..60], "the anchors between the runs"); + assert_eq!(both[a30 + 1..mid], original.anchors.to_vec()[31..60], "the anchors between the runs"); assert_eq!(both[mid..], second[60..]); let sel: BTreeSet<_> = (10..=a30).chain(mid..=mid + a80 - 60).map(|i| (0, i)).collect(); assert_eq!(s.doc().unwrap().selection.anchors.get(&id), Some(&sel)); @@ -138,7 +138,7 @@ fn a_run_across_the_start_of_a_closed_path_simplifies_as_one() { assert!(sp.closed); assert!(sp.anchors.len() < 80 - 10, "{}", sp.anchors.len()); assert!(!sp.anchors.iter().any(|a| a.p == original.anchors[0].p), "anchor 0 was inside the run"); - assert_eq!(sp.anchors[1..60], original.anchors[11..70]); + assert_eq!(sp.anchors.to_vec()[1..60], original.anchors.to_vec()[11..70]); assert_eq!((sp.anchors[0].p, sp.anchors[0].h_out), (original.anchors[10].p, original.anchors[10].h_out)); assert_eq!((sp.anchors[60].p, sp.anchors[60].h_in), (original.anchors[70].p, original.anchors[70].h_in)); for i in 0..60 { @@ -162,8 +162,8 @@ fn picked_segments_simplify_and_stay_picked() { s.execute("object.path.simplify", &json!({"tolerance": 1})).unwrap(); let sp = path_of(&s, id).subpaths[0].clone(); let end = sp.anchors.len() - 41; - assert_eq!(sp.anchors[..20], original.anchors[..20]); - assert_eq!(sp.anchors[end + 1..], original.anchors[61..]); + assert_eq!(sp.anchors.to_vec()[..20], original.anchors.to_vec()[..20]); + assert_eq!(sp.anchors.to_vec()[end + 1..], original.anchors.to_vec()[61..]); let sel = &s.doc().unwrap().selection; assert_eq!(sel.segments.get(&id), Some(&(20..end).map(|i| (0, i)).collect())); assert_eq!(sel.anchors.get(&id), Some(&(20..=end).map(|i| (0, i)).collect())); @@ -200,8 +200,8 @@ fn slider_preview_and_auto_simplify_only_the_run() { let previewed = path_of(&s, id); let sp = &previewed.subpaths[0]; assert!(sp.anchors.len() < 101, "{p}"); - assert_eq!(sp.anchors[..20], original.anchors[..20], "{p}"); - assert_eq!(sp.anchors[sp.anchors.len() - 40..], original.anchors[61..], "{p}"); + assert_eq!(sp.anchors.to_vec()[..20], original.anchors.to_vec()[..20], "{p}"); + assert_eq!(sp.anchors.to_vec()[sp.anchors.len() - 40..], original.anchors.to_vec()[61..], "{p}"); s.execute("edit.undo", &json!({})).unwrap(); s.execute("object.path.simplify", &p).unwrap(); assert_eq!(path_of(&s, id), previewed, "{p}"); diff --git a/crates/engine/src/tests/smooth_path.rs b/crates/engine/src/tests/smooth_path.rs index 9ce6a21044..1ca7a6d5e0 100644 --- a/crates/engine/src/tests/smooth_path.rs +++ b/crates/engine/src/tests/smooth_path.rs @@ -93,7 +93,7 @@ fn more_smoothing_removes_the_jags_and_keeps_the_shape() { // Within the tolerance (2.5 % of 300 pt at most) plus the jag the refit smooths away. assert!(farthest(&before, &after) <= 7.5 + 1.5, "level {level}: {}", farthest(&before, &after)); // The end points of an open path stay put. - let (a, b) = (&before.subpaths[0].anchors, &after.subpaths[0].anchors); + let (a, b) = (&before.subpaths[0].anchors.to_vec(), &after.subpaths[0].anchors.to_vec()); assert_eq!((a[0].p, a[a.len() - 1].p), (b[0].p, b[b.len() - 1].p)); assert!(!after.subpaths[0].closed); s.execute("edit.undo", &json!({})).unwrap(); @@ -206,7 +206,7 @@ fn direct_selected_anchors_smooth_only_their_section() { s.execute("select.anchors", &json!({"id": id.0, "anchors": anchors})).unwrap(); s.execute("object.path.smooth", &json!({"level": 100})).unwrap(); let after = path_of(&s, id); - let (a, b) = (&before.subpaths[0].anchors, &after.subpaths[0].anchors); + let (a, b) = (&before.subpaths[0].anchors.to_vec(), &after.subpaths[0].anchors.to_vec()); assert!(b.len() < a.len(), "{} → {}", a.len(), b.len()); // Anchors 0..=10 and 30..=40 are untouched, the section between them refitted. assert_eq!(a[..=10].iter().map(|x| x.p).collect::>(), b[..=10].iter().map(|x| x.p).collect::>()); diff --git a/crates/engine/src/tests/styles.rs b/crates/engine/src/tests/styles.rs index 6f77b58971..e460aeb890 100644 --- a/crates/engine/src/tests/styles.rs +++ b/crates/engine/src/tests/styles.rs @@ -325,6 +325,26 @@ fn select_same_appearance_attribute() { run(&mut s, "select.set", json!({"ids": [a.0]})); run(&mut s, "select.same.appearanceAttribute", json!({"item": (1u64 << 32) + 1})); assert_eq!(s.doc().unwrap().selection.objects, vec![a, b]); + // Null is the default: the shared effect. + run(&mut s, "select.set", json!({"ids": [a.0]})); + run(&mut s, "select.same.appearanceAttribute", json!({"item": null})); + assert_eq!(s.doc().unwrap().selection.objects, vec![a, b]); +} + +/// Select > Same > Appearance Attribute refuses an `item` that is not a whole number and leaves +/// the selection as it was. +#[test] +fn select_same_appearance_attribute_refuses_an_item_that_is_not_a_whole_number() { + let mut s = session(); + let a = rect(&mut s, 10.0); + run(&mut s, "effect.apply", json!({"effect": "distort.roughen"})); + rect(&mut s, 100.0); + run(&mut s, "select.set", json!({"ids": [a.0]})); + for item in [json!("1"), json!(-1), json!(1.5), json!(true), json!([1])] { + let e = s.execute("select.same.appearanceAttribute", &json!({"item": item})).unwrap_err().to_string(); + assert_eq!(e, "invalid parameters for `select.same.appearanceAttribute`: `item` must be a whole number", "{item}"); + assert_eq!(s.doc().unwrap().selection.objects, vec![a], "{item}"); + } } /// With a member path of a compound path selected first, Select > Same > Graphic Style and diff --git a/crates/engine/src/tests/svgfilter.rs b/crates/engine/src/tests/svgfilter.rs index e42d7f9736..611c9bfd1f 100644 --- a/crates/engine/src/tests/svgfilter.rs +++ b/crates/engine/src/tests/svgfilter.rs @@ -551,6 +551,26 @@ fn svg_export_keeps_a_measured_region_only_on_the_object_alone() { assert!(after.contains(""#; + for (scale, axes, live) in [(2.0, json!([2, 0, 0, 2]), true), (1000.0, json!([2, 0, 0, 2]), false)] { + let mut s = session(); + let a = rect(&mut s, 10.0); + run(&mut s, "effect.apply", json!({"effect": "svg.filter", "ids": [a.0], "params": {"xml": hue, "scale": scale, "axes": axes}})); + let out = svg(&mut s); + assert_eq!((out.contains("")])).unwrap_err(); assert!(e.contains("not well-formed XML"), "{e}"); + for xml in [ + format!(r#"partial text"#), + document("A&missing;B"), + document("text"), + document("text"), + ] { + let e = place(&mut s, "a.docx", &store(&[("word/document.xml", xml.as_bytes())])).unwrap_err(); + assert!(e.contains("not well-formed XML"), "{e}"); + } let e = place(&mut s, "a.docx", &store(&[("word/document.xml", document("").as_bytes())])).unwrap_err(); assert!(e.contains("no text to place"), "{e}"); // A file whose headers understate what it unpacks to, and one whose headers say it is too large. diff --git a/crates/engine/src/tests/toolsettings.rs b/crates/engine/src/tests/toolsettings.rs index 2ec7667bde..a9d9e3f5bd 100644 --- a/crates/engine/src/tests/toolsettings.rs +++ b/crates/engine/src/tests/toolsettings.rs @@ -286,7 +286,7 @@ fn legacy_spiral_decay_preferences_report_the_ratio_drawn_after_reopening() { 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; + let anchors = &path.subpaths[0].anchors.to_vec(); assert_eq!(anchors.len(), 5); assert!(!path.is_closed()); let center = Point::new(200.0, 200.0); diff --git a/crates/engine/src/tests/variables.rs b/crates/engine/src/tests/variables.rs index 9119c3e151..a50485f3f8 100644 --- a/crates/engine/src/tests/variables.rs +++ b/crates/engine/src/tests/variables.rs @@ -2420,6 +2420,69 @@ fn a_variable_library_defines_text_variables_and_data_sets() { assert_eq!(s.doc().unwrap().doc.variables.datasets.len(), 2); } +/// The Variables panel's Import… reads a data source by its extension, in any case: a .csv, .tsv +/// or .txt file as Import Data Sets… reads it, and an .xml file as Load Variable Library… reads it. +/// Any other extension, or none, is refused before the file is read. +#[test] +fn variable_import_reads_a_data_source_by_its_extension() { + let dir = Folder::new("vars-import"); + let mut s = session(); + let t = text(&mut s, "Alice"); + s.execute("variable.define", &json!({"name": "Name", "kind": "text"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "Name", "ids": [t.0]})).unwrap(); + + for name in ["rows.csv", "rows.TSV", "rows.txt"] { + let path = dir.file(name); + write(&path, b"Name\nAnn\nBob\n"); + let r = s.execute("variable.import", &json!({"path": path})).unwrap(); + assert_eq!((r["format"].clone(), r["names"].clone()), (json!("csv"), json!(["Data Set 1", "Data Set 2"])), "{name}"); + } + s.execute("dataset.select", &json!({"name": "Data Set 2"})).unwrap(); + assert_eq!(plain(&s, t), "Bob"); + + let xml = r#"

Charlie

"#; + let path = dir.file("library.Xml"); + write(&path, xml.as_bytes()); + let r = s.execute("variable.import", &json!({"path": path})).unwrap(); + assert_eq!((r["format"].clone(), r["names"].clone(), r["deleted"].clone()), (json!("xml"), json!(["Row 1"]), json!([]))); + // The library declares the bound text variable, so its binding stays. + s.execute("dataset.select", &json!({"name": "Row 1"})).unwrap(); + assert_eq!(plain(&s, t), "Charlie"); + + // The extension picks the reader: CSV text in an .xml file goes to the library reader, which + // refuses it, and a library in a .csv file goes to the CSV reader. + let csv_in_xml = dir.file("rows.xml"); + write(&csv_in_xml, b"Name\nAnn\n"); + let e = s.execute("variable.import", &json!({"path": csv_in_xml})).unwrap_err().to_string(); + assert!(e.contains("variable.loadLibrary"), "{e}"); + let xml_in_csv = dir.file("library.csv"); + write(&xml_in_csv, xml.as_bytes()); + let e = s.execute("variable.import", &json!({"path": xml_in_csv})).unwrap_err().to_string(); + assert!(e.contains("dataset.import"), "{e}"); + + // Other extensions, or none, are refused before the file is read, so a missing file gives the + // same error; the data sets stay as they were. + let refused = "Import reads a data source file ending in .csv, .tsv, .txt or .xml"; + for (name, exists) in [("rows.json", true), ("rows", true), ("rows.csv.bak", true), ("missing.ai", false)] { + let path = dir.file(name); + if exists { + write(&path, b"Name\nAnn\n"); + } + let e = s.execute("variable.import", &json!({"path": path})).unwrap_err().to_string(); + assert!(e.contains(refused), "{name}: {e}"); + } + let names: Vec = s.doc().unwrap().doc.variables.datasets.iter().map(|d| d.name.clone()).collect(); + assert_eq!(names, ["Row 1"]); + + // `path` is required, and the command takes no other parameter. + for bad in [json!({}), json!({"path": 3})] { + let e = s.execute("variable.import", &bad).unwrap_err().to_string(); + assert!(e.contains("missing `path`"), "{bad}: {e}"); + } + let e = s.execute("variable.import", &json!({"path": dir.file("rows.csv"), "csv": "Name\nX\n"})).unwrap_err().to_string(); + assert!(e.contains("unknown parameter `csv`"), "{e}"); +} + /// Load Variable Library replaces the document's variables and data sets: every variable goes with /// its bindings and values, a variable of another kind with a library variable's name included, /// and every data set goes, the active one included. A text variable the library also declares @@ -2665,6 +2728,11 @@ fn malformed_variable_libraries_are_refused() { let long_graph = format!("{}", row.repeat(2_000)); let cases = [ ("not well-formed XML", "".to_string()), + ("not well-formed XML", ok.replace("

x

", "

A&missing;B

")), + ("not well-formed XML", ok.replace("
", "")), + ("not well-formed XML", ok.replace("varName=\"Name\"", "varName=\"Name\" varName=\"Other\"")), + ("not well-formed XML", ok.replace("".to_string()), ("declares no variables", "".to_string()), ("is declared twice", library(&[("Name", "textcontent"), ("Name", "textcontent")], &[])), @@ -3545,6 +3613,17 @@ fn variable_sort_orders_the_list_by_each_column() { } } +#[test] +fn variable_library_attributes_keep_their_namespace() { + let mut s = session(); + let xml = library(&[("Name", "textcontent")], &[("A", &[("Name", &["x"])])]) + .replace("varName=\"Name\"", "xmlns:m=\"urn:metadata\" m:varName=\"Other\" varName=\"Name\""); + let loaded = s.execute("variable.loadLibrary", &json!({"xml": xml})).unwrap(); + assert_eq!(loaded["variables"], json!(["Name"])); + let sets = s.execute("dataset.list", &json!({})).unwrap(); + assert_eq!(sets["datasets"][0]["values"], json!({"Name": {"text": "x"}})); +} + /// The sort is panel state: it is not an undo step and does not count as a change to save, and /// setting the order the list already has does not redraw anything. A bad `by` or `descending` /// is an error that leaves the order as it was. diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 66ed0a41e3..59eb78a51b 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -255,6 +255,9 @@ impl Session { } // The Selection and Group Selection tools act on the instance whole. self.select_whole_instance(id); + // The tool lent to does not see the press: it counts as a press elsewhere for the clicks a + // double-click or triple-click compares. + self.tool.press_elsewhere(); let lent = self.make_tool(id); self.selection_at_lend = self.active().map(|d| (d.uid, d.selection.clone())); self.lender = Some(std::mem::replace(&mut self.tool, lent)); @@ -1086,6 +1089,12 @@ impl Session { self.with_tool_cx(view, |t, cx| t.hover_ended(cx)); } + /// A press on the canvas went to the view tools and not to the active tool + /// ([`vectorcraft_tools::Tool::press_elsewhere`]). + pub fn tool_press_elsewhere(&mut self) { + self.tool.press_elsewhere(); + } + /// Whether the active tool's hover depends on what lies under a still pointer /// ([`vectorcraft_tools::Tool::wants_rehover`]). pub fn tool_wants_rehover(&self) -> bool { diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index fce3742d11..30d0dc96cf 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -993,6 +993,13 @@ fn structured_junk() { ("addon.document.symbolsFromLayers", json!({"layers": "x", "replace": 3})), ("addon.document.symbolsFromLayers", json!({"layers": [1e308, -1, null, u64::MAX], "replace": true})), ("addon.document.symbolsFromLayers", json!({"layers": [], "replace": true})), + // Packaging Tools add-on. + ("addon.packaging.setRole", json!({"role": "cut", "ids": [u64::MAX], "overprint": "no"})), + ("addon.packaging.setRole", json!({"role": ["crease"], "ids": "all"})), + ("addon.packaging.setRole", json!({"role": "none", "overprint": null})), + ("addon.packaging.roles", json!({"ids": [-1, 1e300]})), + ("addon.packaging.setRoleSwatch", json!({"role": "perforation", "swatch": "[Registration]"})), + ("addon.packaging.setRoleSwatch", json!({"role": "cut", "swatch": 5})), // Smart Pen add-on. ("addon.pen.append", json!({"id": 2, "x": 1e308, "y": 0, "in": [1e308, -1e308]})), ("addon.pen.append", json!({"id": 2, "subpath": u64::MAX, "x": 0, "y": 0, "segment": "curved"})), diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 46e8561f4c..8de519fa4e 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -1672,6 +1672,9 @@ fn action_set(bytes: &[u8]) -> Result<(), TestCaseError> { prop_assert!(actions.iter().all(|a| a["steps"].as_array().map_or(0, Vec::len) <= 10_000)); prop_assert!(actions.iter().map(|a| a["steps"].as_array().map_or(0, Vec::len)).sum::() <= 100_000); prop_assert!(r["unread"].as_array().map_or(0, Vec::len) <= 1000); + let steps = || actions.iter().flat_map(|a| a["steps"].as_array().cloned().unwrap_or_default()); + prop_assert!(steps().all(|s| s["values"].as_array().map_or(0, Vec::len) as u64 <= s["params"].as_u64().unwrap_or(0))); + prop_assert!(steps().map(|s| s["values"].as_array().map_or(0, Vec::len)).sum::() <= 100_000); } Ok(()) } @@ -1690,6 +1693,8 @@ fn arb_aia_token() -> impl Strategy> { "/localizedName", "/isOn", "/value", + "/key", + "/type", "/x", "/version", ]) @@ -1699,6 +1704,7 @@ fn arb_aia_token() -> impl Strategy> { "[a-z ()\\\\]{0,12}".prop_map(|t| format!("({t})").into_bytes()), prop::sample::select(vec!["(", ")", "\\", "[ 2 4142 ]", "[ 3 41 4", "[ 1 zz ]", "[", "]", "< 2 0a0b >", "<", ">", "2.5"]) .prop_map(|t| t.as_bytes().to_vec()), + prop::sample::select(vec!["[ 2 c328 ]", "(ustring)", "(boolean)"]).prop_map(|t| t.as_bytes().to_vec()), prop::sample::select(vec!["{", "}", "\r\n", "\r", "\n"]).prop_map(|t| t.as_bytes().to_vec()), prop::sample::select(vec![vec![0u8], vec![0xFF, 0xFE], vec![0xC3]]), ] @@ -1835,6 +1841,7 @@ proptest! { /// Mutated copies of the PSD and PSB samples never crash opening them with their layers, hidden /// ones too: the PSD's layer records, channel lengths and data, and the PSB's layer count. /// (Masks, clipping and groups are covered by `tests_psdlayers::damaged_layers_never_panic`.) + /// Neither does `document.psdInfo`, nor placing them with their layers as objects. #[test] fn mutated_layered_psds_open_without_panics(which in 6usize..8, cut in 0usize..1_000_000, edits in prop::collection::vec((0usize..1_000_000, any::()), 0..12)) { let (name, mut bytes) = raster_samples().swap_remove(which); @@ -1849,6 +1856,10 @@ proptest! { let mut s = vectorcraft_engine::Session::new(); let p = json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(&bytes), "hiddenLayers": true}); let _ = no_panic(s.execute("document.open", &p)); + let _ = no_panic(s.execute("document.psdInfo", &p)); + let _ = no_panic(s.execute("file.new", &json!({}))); + let p = json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(&bytes), "layers": true, "hiddenLayers": true}); + let _ = no_panic(s.execute("file.place", &p)); }); prop_assert!(r.is_ok(), "{name}: panicked: {:?}", r.err()); } diff --git a/crates/engine/tests/plugin_safe_mode.rs b/crates/engine/tests/plugin_safe_mode.rs index 2c5fc1c307..9ff0d0668a 100644 --- a/crates/engine/tests/plugin_safe_mode.rs +++ b/crates/engine/tests/plugin_safe_mode.rs @@ -463,6 +463,69 @@ fn expand_appearance_keeps_a_plug_in_effect_safe_mode_skips() { s.execute("effect.expandAppearance", &json!({})).unwrap(); } +/// In Safe Mode, a plug-in effect in the art of a graph design in a series stops Expand Appearance of the graph only +/// when an effect of the series group draws that art with the group. +#[test] +fn expand_appearance_in_safe_mode_checks_design_art_its_series_group_draws() { + let _f = fresh(); + let mut s = Session::new(); + let fx = wat::parse_str(tpl::returning(&tpl::manifest("test.sm.graph", "effect", "{}"), r#"{"objects":[]}"#)).unwrap(); + s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&fx)})).unwrap(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let csv = ",2024,2025\nQ1,3,2\nQ2,5,4"; + let graph = s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap()["id"] + .as_u64() + .unwrap(); + let r = s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].clone(); + s.execute("effect.apply", &json!({"effect": "plugin.test.sm.graph", "ids": [r]})).unwrap(); + s.execute("select.set", &json!({"ids": [r]})).unwrap(); + s.execute("graph.design", &json!({"new": "Plug"})).unwrap(); + s.execute("graph.column", &json!({"id": graph, "seriesIndexes": [0], "design": "Plug"})).unwrap(); + let series = |s: &Session, index: u32| { + let d = &s.doc().unwrap().doc; + let n = d.node(vectorcraft_engine::doc::NodeId(graph)).unwrap(); + n.children().unwrap().iter().find(|c| c.extras().series_index == Some(index)).unwrap().id + }; + let (art_series, other_series) = (series(&s, 0), series(&s, 1)); + // A mark in the other series has an effect to expand. + let mark = s.doc().unwrap().doc.node(other_series).unwrap().children().unwrap()[0].id; + s.execute("effect.apply", &json!({"effect": "distort.puckerBloat", "ids": [mark.0]})).unwrap(); + s.execute("select.set", &json!({"ids": [graph]})).unwrap(); + safe_mode::set_active(Some(safe_mode::Source::Flag)); + s.execute("effect.expandAppearance", &json!({})).unwrap(); + safe_mode::set_active(None); + s.execute("edit.undo", &json!({})).unwrap(); + // With a Transform effect on the art's series group, expanding the group draws the art's plug-in effect. + let shift = { + let t = s.execute("shape.rectangle", &json!({"x": 700, "y": 20, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("effect.apply", &json!({"effect": "distort.transform", "ids": [t], "params": {"moveH": 5}})).unwrap(); + s.doc().unwrap().doc.node(vectorcraft_engine::doc::NodeId(t)).unwrap().appearance.effects[0].clone() + }; + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(art_series).unwrap().appearance.effects.push(shift); + s.execute("select.set", &json!({"ids": [graph]})).unwrap(); + safe_mode::set_active(Some(safe_mode::Source::Flag)); + let err = s.execute("effect.expandAppearance", &json!({})).unwrap_err().to_string(); + safe_mode::set_active(None); + assert!(err.contains("a plug-in effect in the selection can't be expanded in Safe Mode"), "{err}"); + // With a Gaussian Blur on a fill of the art's series group instead, expanding the group makes an image of it, art included. + let blurred_fill = { + let t = s.execute("shape.rectangle", &json!({"x": 700, "y": 40, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("effect.apply", &json!({"effect": "blur.gaussian", "ids": [t], "item": 0, "params": {"radius": 2}})).unwrap(); + s.doc().unwrap().doc.node(vectorcraft_engine::doc::NodeId(t)).unwrap().appearance.items[0].clone() + }; + { + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let g = d.node_mut(art_series).unwrap(); + g.appearance.effects.clear(); + g.appearance.items.push(blurred_fill); + } + s.execute("select.set", &json!({"ids": [graph]})).unwrap(); + safe_mode::set_active(Some(safe_mode::Source::Flag)); + let err = s.execute("effect.expandAppearance", &json!({})).unwrap_err().to_string(); + safe_mode::set_active(None); + assert!(err.contains("a plug-in effect in the selection can't be expanded in Safe Mode"), "{err}"); +} + /// In Safe Mode, a plug-in effect on a dimension selected with the art it measures does not stop /// Expand Appearance: the dimension is left as it is, its effect included, and the art expands. #[test] diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index 18b67e6c6f..88a640ea40 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -1038,7 +1038,8 @@ fn nested_symbol_instances_stop_at_the_symbol_art_limit() { /// The documents [`the_writer_counts_objects_as_the_reader_reads_them`] writes: groups, compound /// paths, guides, sublayers, clipping groups and layers, painted clipping paths, opacity masks, /// gradients, pattern definitions and tiles, images, type, symbol definitions and instances, -/// objects with art styles, objects bound to variables and live envelopes. +/// objects with art styles, objects bound to variables, live envelopes, and the rectangles of the +/// bounds of wrapped objects written as their art. fn counted() -> Vec<(&'static str, Document)> { vec![ ("sample", sample()), @@ -1054,9 +1055,28 @@ fn counted() -> Vec<(&'static str, Document)> { ("blend", blend_doc()), ("brushes", brushes_document()), ("envelopes", envelopes_document()), + ("wrap bounds", wrap_bounds_doc()), ] } +/// Area type below a wrapped symbol instance written as its art and wrapped type written as its +/// outlines, each with the rectangle of its bounds. +fn wrap_bounds_doc() -> Document { + let mut doc = over_area_type(|doc| { + two_leaves(doc); + let mut n = instance(doc, "Leaf", Affine::new([3.0, 0.0, 0.0, 3.0, 150.0, 100.0])); + n.isolate = true; + wrapped(n, 4.5, false) + }); + let mut label = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::ZERO, "Ill", 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 label = wrapped(text_node(&mut doc, label), -2.0, true); + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, label).unwrap(); + doc +} + /// A blend of two squares 20 pt apart with a step every 10 pt, written as its steps. fn blend_doc() -> Document { let mut doc = Document::new(200.0, 100.0); @@ -4088,20 +4108,21 @@ fn predefined_mojikumi_sets_are_reported_as_left_out() { } } -/// The text document has no Bunri-Kinshi: a paragraph with it on and an inseparable pair in it is -/// reported as left out, and comes back off; with it off, or with no pair, nothing is reported. +/// Bunri-Kinshi comes back on or off, with or without an inseparable pair in the paragraph, and +/// nothing is reported. #[test] -fn bunri_kinshi_is_reported_only_for_paragraphs_with_a_pair() { +fn bunri_kinshi_comes_back_with_or_without_a_pair() { use vectorcraft_doc::TextObject; - for (text, on, reported) in [ - ("Wait——now", true, true), - ("Wait——now", false, false), - ("Wait—now", true, false), - ("Wait……now", true, true), - ("Wait‥‥now", true, true), - ("あ〳〵い", true, true), - ("あ〴〵い", true, true), - ("あ〵〳い", true, false), + for (text, on) in [ + ("Wait——now", true), + ("Wait——now", false), + ("Wait—now", true), + ("Wait……now", true), + ("Wait‥‥now", true), + ("あ〳〵い", true), + ("あ〴〵い", true), + ("あ〵〳い", true), + ("あ〵〳い", false), ] { let mut t = TextObject::point(vectorcraft_geom::Point::new(20.0, 40.0), text, style(14.0, Color::BLACK)); t.para.bunri_kinshi = on; @@ -4110,7 +4131,7 @@ fn bunri_kinshi_is_reported_only_for_paragraphs_with_a_pair() { let n = text_node(&mut doc, t); doc.insert(Some(layer), usize::MAX, n).unwrap(); let out = export_ai_editing(&doc, &opts()).unwrap(); - assert_eq!(!out.warnings.is_empty(), reported, "{text} {on}: {:?}", out.warnings); + assert!(out.warnings.is_empty(), "{text} {on}: {:?}", out.warnings); let mut all = vec![]; paths(&read_back(&doc).layers, &mut all); let paras: Vec = all @@ -4120,10 +4141,87 @@ fn bunri_kinshi_is_reported_only_for_paragraphs_with_a_pair() { _ => None, }) .collect(); - assert_eq!(paras, [false], "{text} {on}"); + assert_eq!(paras, [on], "{text} {on}"); } } +/// Each paragraph's Kinsoku set, Kinsoku Shori Type, Burasagari and Bunri-Kinshi come back, and +/// nothing is reported: every value of each, mixed across the paragraphs of one object, Burasagari +/// and Bunri-Kinshi kept under Kinsoku None. The text document lists the Hard and Soft sets, and +/// every paragraph, the normal paragraph style and the document's defaults write all four keys. +/// Another attribute the text document leaves out is still reported. +#[test] +fn kinsoku_settings_come_back_on_each_paragraph() { + use vectorcraft_doc::{Burasagari, Kinsoku, KinsokuShoriType, ParaStyle, TextObject}; + let cases = [ + (Kinsoku::None, KinsokuShoriType::PushInFirst, Burasagari::Forced, true), + (Kinsoku::Soft, KinsokuShoriType::PushOutFirst, Burasagari::Standard, false), + (Kinsoku::Hard, KinsokuShoriType::PushOutOnly, Burasagari::None, true), + (Kinsoku::Hard, KinsokuShoriType::PushInFirst, Burasagari::Standard, false), + (Kinsoku::Soft, KinsokuShoriType::PushOutOnly, Burasagari::Forced, true), + ]; + let mut t = TextObject::point(vectorcraft_geom::Point::new(20.0, 40.0), "かな。\n「かな」、\nあ——い\nかな\nかな。", style(14.0, Color::BLACK)); + t.set_paragraph_styles( + cases + .iter() + .map(|&(kinsoku, kinsoku_type, burasagari, bunri_kinshi)| ParaStyle { + kinsoku, + kinsoku_type, + burasagari, + bunri_kinshi, + ..ParaStyle::default() + }) + .collect(), + ); + let mut doc = Document::new(200.0, 200.0); + let layer = doc.layers[0].id; + 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 mut all = vec![]; + paths(&back.layers, &mut all); + let read: Vec<_> = all + .iter() + .filter_map(|n| match &n.kind { + NodeKind::Text(t) => { + Some(t.paragraph_styles().iter().map(|p| (p.kinsoku, p.kinsoku_type, p.burasagari, p.bunri_kinshi)).collect::>()) + } + _ => None, + }) + .collect(); + assert_eq!(read, [cases.to_vec()]); + let decoded = text_document(&program(&doc)); + let hard = decoded.find("PhotoshopKinsokuHard").unwrap_or_else(|| panic!("{decoded}")); + let soft = decoded.find("PhotoshopKinsokuSoft").unwrap_or_else(|| panic!("{decoded}")); + assert!(hard < soft, "{decoded}"); + // Five paragraphs, then the normal paragraph style and the document's defaults (Hard, Push Out + // Only, no Burasagari, Bunri-Kinshi off). + for (key, count) in [ + ("/27 /nil", 1), + ("/27 0", 4), + ("/27 1", 2), + ("/25 0", 2), + ("/25 1", 1), + ("/25 2", 4), + ("/24 0", 3), + ("/24 1", 2), + ("/24 2", 2), + ("/23 true", 3), + ("/23 false", 4), + ] { + assert_eq!(decoded.matches(key).count(), count, "{key}: {decoded}"); + } + 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]); +} + #[test] fn type_is_written_again_as_the_same_bytes() { let doc = typed(); @@ -10712,6 +10810,129 @@ fn unreachable_envelope() -> ! { panic!("not an envelope") } +/// `doc` with its first artboard 20,000.5 points wide: it is written on a large canvas, at 1/10. +fn on_large_canvas(mut doc: Document) -> Document { + doc.artboards[0].rect = Rect::new(0.0, 0.0, 20_000.5, 100.0); + doc +} + +/// A route an envelope was read back by: its name, the envelope and the reader's notes. +type EnvelopeRoute = (&'static str, Node, Vec); + +/// The envelope `doc` holds alone on its first layer, read back from the editing data alone and +/// beside a page that draws as `doc` does ([`read_with_page`]); and the writer's warnings. +fn envelope_both_routes(doc: &Document) -> (Vec, Vec) { + let (alone, warnings, notes) = envelope_back(doc); + let (paged, _, page_notes) = read_with_page(doc); + assert_eq!(paged.len(), 1, "{paged:#?} {page_notes:?}"); + (vec![("alone", alone, notes), ("beside its page", (*paged[0]).clone(), page_notes)], warnings) +} + +/// On a large canvas, a warp, a mesh and a top object envelope, with Edit Contents off and on, are +/// written live at 1/10 and open as the same envelope at their size, from the editing data alone +/// and beside the page: contents, Fidelity, Edit Contents, Envelope Options, shape and name as +/// saved. Saved again as they opened, they open as the same envelope again. +#[test] +fn large_canvas_envelope_kinds_round_trip_on_both_ai_routes() { + // GUARDS: an envelope on a large canvas was written as its drawn art, with a warning. + use vectorcraft_doc::live::EnvelopeOptions; + for (name, kind) in live_envelope_kinds() { + for editing in [false, true] { + let what = format!("{name}, editing {editing}"); + let doc = on_large_canvas(envelope_doc(kind.clone(), 50.0, editing, EnvelopeOptions::NEW)); + let text = program(&doc); + assert!(text.contains("%AI24_LargeCanvasScale: 10\n") && text.contains("AIDeformOptionsKey"), "{what}"); + let (routes, warnings) = envelope_both_routes(&doc); + assert!(!warnings.iter().any(|w| w == writer::ENVELOPES), "{what}: {warnings:?}"); + for (route, back, notes) in routes { + let what = format!("{what}, {route}"); + assert!(!notes.iter().any(|w| w == crate::import::ENVELOPE_DRAWN), "{what}: {notes:?}"); + let NodeKind::Envelope { content, kind: got, fidelity, editing: e, options, frame } = &back.kind else { + panic!("{what}: {back:#?} {notes:?}") + }; + assert_eq!((*fidelity, *e, *options, **frame), (50.0, editing, EnvelopeOptions::NEW, Affine::IDENTITY), "{what}"); + assert!(same_envelope_kind(&kind, got), "{what}: {got:?}"); + assert_eq!(back.name.as_deref(), Some("Bent"), "{what}"); + let colors: Vec> = content.iter().map(|c| c.appearance.fill_paint().color()).collect(); + assert_eq!(colors, [Some(Color::rgb(1.0, 0.0, 0.0)), Some(Color::rgb(0.0, 0.0, 1.0))], "{what}"); + let b = content.iter().filter_map(|c| c.visual_bounds()).reduce(|a, b| a.union(b)).unwrap(); + let want = Rect::new(40.0, 20.0, 160.0, 80.0); + assert!([b.x0 - want.x0, b.y0 - want.y0, b.x1 - want.x1, b.y1 - want.y1].iter().all(|d| d.abs() < 1e-2), "{what}: {b:?}"); + } + let (back, _, _) = envelope_back(&doc); + let mut again = on_large_canvas(Document::new(200.0, 100.0)); + let layer = again.layers[0].id; + again.insert(Some(layer), usize::MAX, back).unwrap(); + let (twice, warnings, notes) = envelope_back(&again); + assert!(!warnings.iter().any(|w| w == writer::ENVELOPES), "{what}, saved again: {warnings:?}"); + let NodeKind::Envelope { kind: twice, .. } = &twice.kind else { panic!("{what}, saved again: {twice:#?} {notes:?}") }; + assert!(same_envelope_kind(&kind, twice), "{what}, saved again: {twice:?}"); + } + } +} + +/// On a large canvas, envelopes with Distort Appearance whose stroked contents (at fractional places) +/// map from their bounds with their strokes keep that margin, the contents' 8-point strokes and the +/// Distort Linear Gradients and Distort Pattern Fills switches, from the editing data alone and +/// beside the page. +#[test] +fn large_canvas_envelope_stroke_margin_round_trips_on_both_ai_routes() { + // GUARDS: read from the editing data alone, the saved size was compared at 1/10 with contents at + // their size, and the contents' strokes came back at 1/10: the margin was lost. + use vectorcraft_doc::live::{EnvelopeOptions, envelope_content_boxes, envelope_stroke_margin}; + for (name, kind) in live_envelope_kinds() { + for editing in [false, true] { + let what = format!("{name}, editing {editing}"); + let mut doc = Document::new(200.0, 100.0); + let switches = EnvelopeOptions { distort_linear_gradients: editing, distort_pattern_fills: !editing, ..EnvelopeOptions::NEW }; + let mut envelope = envelope_node(&mut doc, kind.clone(), 50.0, editing, switches); + let NodeKind::Envelope { content, options, .. } = &mut envelope.kind else { unreachable_envelope() }; + for c in content.iter_mut() { + let c = Arc::make_mut(c); + c.transform(Affine::translate((0.25, 0.375)), true); + let fill = c.appearance.fill_paint(); + c.appearance = Appearance::basic(fill, solid(Color::BLACK), 8.0).into(); + } + let (stroked, plain) = envelope_content_boxes(content, Affine::IDENTITY).unwrap(); + options.bounds_margin = envelope_stroke_margin(stroked, plain).unwrap(); + let want = *options; + assert!(want.bounds_margin.iter().all(|m| *m > 0.0), "{what}: {want:?}"); + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, envelope).unwrap(); + let (routes, warnings) = envelope_both_routes(&on_large_canvas(doc)); + assert!(!warnings.iter().any(|w| w == writer::ENVELOPES), "{what}: {warnings:?}"); + for (route, back, notes) in routes { + let what = format!("{what}, {route}"); + let NodeKind::Envelope { content, options, .. } = &back.kind else { panic!("{what}: {back:#?} {notes:?}") }; + let margin = options.bounds_margin; + assert!(margin.iter().zip(want.bounds_margin).all(|(a, b)| (a - b).abs() < 1e-4), "{what}: {margin:?} {want:?}"); + assert_eq!(EnvelopeOptions { bounds_margin: want.bounds_margin, ..*options }, want, "{what}"); + let widths: Vec = content.iter().filter_map(|c| c.appearance.stroke().map(|s| s.width)).collect(); + assert!(widths.len() == 2 && widths.iter().all(|w| (w - 8.0).abs() < 1e-4), "{what}: {widths:?}"); + } + } + } +} + +/// On a large canvas a path's stroke weight and dashes, written at 1/10, come back at their size +/// from the editing data alone. +#[test] +fn a_large_canvas_path_keeps_its_stroke_weight_and_dashes_read_alone() { + // GUARDS: read from the editing data alone, the stroke's weight, dashes and dash offset came + // back at 1/10 while the path came back at its size. + let mut doc = on_large_canvas(Document::new(200.0, 100.0)); + let mut n = + Node::path(doc.alloc_id(), shapes::line((20.0, 50.0).into(), (180.0, 50.0).into()), Appearance::basic(Paint::None, solid(Color::BLACK), 6.0)); + n.appearance.stroke_mut().unwrap().dash = Some(Dash { pattern: vec![12.0, 4.5], offset: 3.0, align_corners: false }); + put(&mut doc, n); + let back = read_back(&doc); + let st = back.layers[0].children().unwrap()[0].appearance.stroke().cloned().unwrap(); + assert!((st.width - 6.0).abs() < 1e-6, "{st:?}"); + let dash = st.dash.unwrap(); + assert!(dash.pattern.len() == 2 && (dash.pattern[0] - 12.0).abs() < 1e-6 && (dash.pattern[1] - 4.5).abs() < 1e-6, "{dash:?}"); + assert!((dash.offset - 3.0).abs() < 1e-6, "{dash:?}"); +} + /// The record is written in the order the reader reads it: on `%_` lines the group holding the /// grid, its dictionary with the options, the contents' block and the kind, then the distorted art /// on plain lines and the plugin's `XP`. While the contents are edited, the group holds them and @@ -10825,7 +11046,10 @@ fn envelopes_the_reader_cannot_open_live_are_written_as_their_art() { ("fractional fidelity", fractional), ("margin kept", margin_kept), ]; - for (what, doc) in cases { + // On a large canvas too. + let large: Vec<(String, Document)> = + cases.iter().map(|(what, doc)| (format!("{what}, on a large canvas"), on_large_canvas(doc.clone()))).collect(); + for (what, doc) in cases.into_iter().map(|(what, doc)| (what.to_string(), doc)).chain(large) { let text = program(&doc); assert!(!text.contains("AIDeformOptionsKey"), "{what}: {text}"); let (back, warnings, _) = envelope_back(&doc); @@ -11374,6 +11598,42 @@ fn text_wrap_options_of_type_and_envelopes_are_read_back() { same_wraps(&wraps(top), &[(Some("Bent".into()), 2.5, true)]); } +/// The wrap shapes that `doc`'s first area type on its first layer takes from the objects above it, +/// in the type's own space: the bounds of each one's subpaths, and its options. +fn area_wrap_region(doc: &Document) -> Vec<(Vec<[f64; 4]>, f64, bool)> { + use vectorcraft_doc::TextKind; + 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 parts = s + .path + .subpaths + .iter() + .map(|sp| { + let b = PathData::new(vec![sp.clone()]).bounds().unwrap_or_default(); + [b.x0, b.y0, b.x1, b.y1] + }) + .collect(); + (parts, s.wrap.offset, s.wrap.invert) + }) + .collect() +} + +/// `before` and `after` hold as many wrap shapes, each with as many subpaths, with bounds within +/// `1e-3`, and the same options. +fn same_region(before: &[(Vec<[f64; 4]>, f64, bool)], after: &[(Vec<[f64; 4]>, f64, bool)]) -> bool { + let close = + |b: &[[f64; 4]], a: &[[f64; 4]]| b.len() == a.len() && b.iter().zip(a).all(|(b, a)| b.iter().zip(a).all(|(x, y)| (x - y).abs() < 1e-3)); + before.len() == after.len() && before.iter().zip(after).all(|(b, a)| close(&b.0, &a.0) && (b.1 - a.1).abs() < 1e-6 && b.2 == a.2) +} + /// 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. @@ -11464,6 +11724,276 @@ fn type_written_as_outlines_keeps_wrapping_by_its_bounds() { assert_eq!(top[1].name.as_deref(), Some("Label"), "{text_out}"); } +/// A 300 × 200 document of area type "Body" filling the page, with `top` above it. +fn over_area_type(make: impl FnOnce(&mut Document) -> Node) -> Document { + use vectorcraft_doc::{TextKind, TextObject, TextRun}; + 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 top = make(&mut doc); + for n in [body, top] { + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + doc +} + +/// Symbol "Leaf": two squares in opposite corners of the 20 × 20 square around the origin, apart. +fn two_leaves(doc: &mut Document) { + let a = square(doc, Rect::new(-10.0, -10.0, -6.0, -6.0), LEAF); + let b = square(doc, Rect::new(6.0, 6.0, 10.0, 10.0), LEAF); + let art = group(doc, vec![a, b], false); + doc.symbols.push(Symbol { dynamic: false, name: "Leaf".into(), art: Arc::new(art) }); +} + +/// A symbol instance written as its art (its isolation is a group's), a blend and an intertwine, +/// each written as a group of its art, wrap area type below them by their bounds after reopening, +/// as they did before saving, not by the members of that art: the text wrap options go on an +/// unpainted rectangle of the bounds, the group's first member, and the group, which keeps the +/// object's name, isolation, lock and visibility, has none. A positive offset, a negative offset +/// with Invert Wrap, and hidden and locked. +#[test] +fn live_art_written_as_a_group_keeps_wrapping_by_its_bounds() { + let instance_of = |offset: f64, invert: bool, visible: bool, locked: bool| { + move |doc: &mut Document| { + two_leaves(doc); + let mut n = instance(doc, "Leaf", Affine::new([3.0, 0.0, 0.0, 3.0, 150.0, 100.0])); + n.isolate = true; + (n.visible, n.locked) = (visible, locked); + wrapped(named(n, "Thing"), offset, invert) + } + }; + let blend = |doc: &mut Document| { + let keys = vec![ + Arc::new(square(doc, Rect::new(60.0, 80.0, 70.0, 90.0), Color::gray(0.5))), + Arc::new(square(doc, Rect::new(220.0, 110.0, 230.0, 120.0), Color::gray(0.5))), + ]; + let spec = vectorcraft_doc::BlendSpec { spacing: vectorcraft_doc::BlendSpacing::Distance(60.0), ..Default::default() }; + wrapped(named(Node::new(doc.alloc_id(), NodeKind::Blend { children: keys, spec: Box::new(spec) }), "Thing"), 4.5, false) + }; + let intertwine = |doc: &mut Document| { + let a = Arc::new(square(doc, Rect::new(60.0, 60.0, 80.0, 80.0), Color::gray(0.5))); + let b = Arc::new(square(doc, Rect::new(200.0, 120.0, 220.0, 140.0), Color::gray(0.5))); + wrapped(named(Node::new(doc.alloc_id(), NodeKind::Intertwine { children: vec![a, b] }), "Thing"), 2.0, true) + }; + let repeat = |doc: &mut Document| { + let a = Arc::new(square(doc, Rect::new(100.0, 80.0, 110.0, 90.0), Color::gray(0.5))); + let spec = vectorcraft_doc::RepeatSpec::grid(vec![a], 8.0, 12.0); + wrapped(named(Node::new(doc.alloc_id(), NodeKind::Repeat(spec)), "Thing"), 1.5, false) + }; + // A Fidelity that isn't a whole number: written as its distorted art. + let envelope = |doc: &mut Document| { + use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions}; + let kind = EnvelopeKind::Mesh { rows: 2, cols: 3, points: envelope_points(2, 3), handles: vec![] }; + wrapped(named(envelope_node(doc, kind, 50.5, false, EnvelopeOptions::NEW), "Thing"), -3.0, true) + }; + let docs = [ + ("instance", over_area_type(instance_of(4.5, false, true, false)), 4.5, false, true, false), + ("instance, inverted", over_area_type(instance_of(-2.0, true, true, false)), -2.0, true, true, false), + ("instance, hidden and locked", over_area_type(instance_of(3.0, false, false, true)), 3.0, false, false, true), + ("blend", over_area_type(blend), 4.5, false, true, false), + ("intertwine", over_area_type(intertwine), 2.0, true, true, false), + ("repeat", over_area_type(repeat), 1.5, false, true, false), + ("envelope", over_area_type(envelope), -3.0, true, true, false), + ]; + for (name, doc, offset, invert, visible, locked) in docs { + let thing = &doc.layers[0].children().unwrap()[1]; + let want = thing.geometric_bounds().unwrap(); + let text_out = program(&doc); + let back = read_back(&doc); + let (before, after) = (area_wrap_region(&doc), area_wrap_region(&back)); + assert_eq!(before.len(), usize::from(visible), "{name}"); + assert!(same_region(&before, &after), "{name}\n{before:?}\n{after:?}\n{text_out}"); + assert_eq!(text_out.matches("(AI11TextWrapOffset)").count(), 1, "{name}: {text_out}"); + let top = back.layers[0].children().unwrap(); + same_wraps(&wraps(top), &[(None, offset, invert)]); + let g = &top[1]; + assert!(matches!(g.kind, NodeKind::Group { clip: false, .. }), "{name}: {text_out}"); + assert_eq!( + (g.name.as_deref(), g.extras().wrap, g.visible, g.locked, g.isolate), + (Some("Thing"), None, visible, locked, thing.isolate), + "{name}" + ); + let first = &g.children().unwrap()[0]; + assert!(matches!(first.kind, NodeKind::Path { guide: false, .. }) && first.appearance.items.is_empty(), "{name}: {text_out}"); + assert_eq!((first.visible, first.locked), (visible, locked), "{name}"); + let b = first.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), "{name}: {b:?} {want:?}"); + } + + // An envelope written live opens live and wraps by its bounds, its options its own. + let live = |doc: &mut Document| { + use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions}; + let kind = EnvelopeKind::Mesh { rows: 2, cols: 3, points: envelope_points(2, 3), handles: vec![] }; + wrapped(named(envelope_node(doc, kind, 50.0, false, EnvelopeOptions::NEW), "Thing"), -3.0, true) + }; + let doc = over_area_type(live); + let text_out = program(&doc); + let back = read_back(&doc); + let (before, after) = (area_wrap_region(&doc), area_wrap_region(&back)); + assert_eq!(before.len(), 1); + assert!(same_region(&before, &after), "{before:?}\n{after:?}\n{text_out}"); + let top = back.layers[0].children().unwrap(); + assert!(matches!(top[1].kind, NodeKind::Envelope { .. }), "{text_out}"); + same_wraps(&wraps(top), &[(Some("Thing".into()), -3.0, true)]); +} + +/// The rectangle that keeps a blend written as its art wrapping by its bounds counts toward the +/// object limit, ahead of the art: one object short, the last step is left out with the limit's +/// warning; without room for the rectangle, the options are left out with the warning, and the +/// group does not take them. In an instance whose art holds area type, shown, hidden, in a hidden +/// group or written as its outlines, the rectangle is the group's first member, below that type: +/// area type below the instance wraps by its bounds after reopening, and the type in its art is not +/// wrapped by them. +#[test] +fn wrap_bounds_of_live_art_fit_the_object_limit_and_leave_area_type_in_the_art_unwrapped() { + use vectorcraft_doc::{TextKind, TextObject, TextRun}; + // A blend alone, without a symbol definition, so the objects are the group, the rectangle and + // the steps. + let mut doc = Document::new(300.0, 200.0); + let keys = vec![ + Arc::new(square(&mut doc, Rect::new(60.0, 80.0, 70.0, 90.0), Color::gray(0.5))), + Arc::new(square(&mut doc, Rect::new(220.0, 110.0, 230.0, 120.0), Color::gray(0.5))), + ]; + let spec = vectorcraft_doc::BlendSpec { spacing: vectorcraft_doc::BlendSpacing::Distance(60.0), ..Default::default() }; + let thing = wrapped(named(Node::new(doc.alloc_id(), NodeKind::Blend { children: keys, spec: Box::new(spec) }), "Thing"), 4.5, false); + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, thing).unwrap(); + let steps = export_ai_editing(&doc, &opts()).unwrap(); + let steps = crate::ai_alone(&steps.program).unwrap().0.layers[0].children().unwrap()[0].children().unwrap().len() - 1; + 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_eq!(text_out.matches("(AI11TextWrapOffset)").count(), 1, "{text_out}"); + let (back, _) = crate::ai_alone(&out.program).unwrap(); + let top = back.layers[0].children().unwrap(); + same_wraps(&wraps(top), &[(None, 4.5, false)]); + assert_eq!((top[0].name.as_deref(), top[0].extras().wrap), (Some("Thing"), None), "{text_out}"); + let members = top[0].children().unwrap(); + assert_eq!(members.len(), steps, "the rectangle and all but the last step: {text_out}"); + assert!(matches!(members[0].kind, NodeKind::Path { guide: false, .. }) && members[0].appearance.items.is_empty(), "{text_out}"); + let out = export_within(&doc, &opts(), read - steps - 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(); + assert!(wraps(back.layers[0].children().unwrap()).is_empty(), "{text_out}"); + + // Area type in the symbol's art, shown or hidden, of `words`, in a hidden group with `in_hidden`. + let make = |shown: bool, words: &'static str, in_hidden: bool| { + move |doc: &mut Document| { + let mut t = TextObject::point(vectorcraft_geom::Point::ZERO, "", style(2.0, Color::BLACK)); + t.runs = vec![TextRun::new(words, style(2.0, Color::BLACK))]; + t.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(-10.0, -10.0, -6.0, -6.0)) }; + t.xf = Affine::IDENTITY; + let mut t = text_node(doc, t); + t.visible = shown; + if in_hidden { + t = group(doc, vec![t], false); + t.visible = false; + } + let s = square(doc, Rect::new(6.0, 6.0, 10.0, 10.0), LEAF); + let art = group(doc, vec![t, s], false); + doc.symbols.push(Symbol { dynamic: false, name: "Leaf".into(), art: Arc::new(art) }); + let mut n = instance(doc, "Leaf", Affine::new([3.0, 0.0, 0.0, 3.0, 150.0, 100.0])); + n.isolate = true; + wrapped(named(n, "Thing"), 4.5, false) + } + }; + // Type of spaces alone is written as its outlines, which are not type. + for (what, shown, words, in_hidden) in + [("shown", true, "leaf", false), ("hidden", false, "leaf", false), ("in a hidden group", true, "leaf", true), ("spaces", true, " ", false)] + { + let doc = over_area_type(make(shown, words, in_hidden)); + let text_out = program(&doc); + assert_eq!(text_out.matches("(AI11TextWrapOffset)").count(), 1, "{what}: {text_out}"); + let back = read_back(&doc); + let (before, after) = (area_wrap_region(&doc), area_wrap_region(&back)); + assert_eq!(before.len(), 1, "{what}"); + assert!(same_region(&before, &after), "{what}\n{before:?}\n{after:?}\n{text_out}"); + let g = &back.layers[0].children().unwrap()[1]; + assert!(matches!(g.kind, NodeKind::Group { clip: false, .. }), "{what}: {text_out}"); + assert_eq!(g.extras().wrap, None, "{what}: {text_out}"); + let first = &g.children().unwrap()[0]; + assert!(matches!(first.kind, NodeKind::Path { guide: false, .. }) && first.appearance.items.is_empty(), "{what}: {text_out}"); + let mut resolved = back.clone(); + vectorcraft_doc::text::resolve_wrap(None, &mut resolved); + let mut inner = vec![]; + resolved.layers[0].children().unwrap()[1].walk(&mut |m| { + if let NodeKind::Text(t) = &m.kind { + inner.push((matches!(t.kind, TextKind::Area { .. }), m.visible, t.wrap.len())); + } + }); + let want: &[(bool, bool, usize)] = match what { + "shown" | "in a hidden group" => &[(true, true, 0)], + "hidden" => &[(true, false, 0)], + _ => &[], + }; + assert_eq!(inner, want, "{what}: {text_out}"); + } +} + +/// A blend with no keys, written as an empty group, has no bounds for a rectangle: its group keeps +/// the text wrap options, and they read back. +#[test] +fn live_art_without_bounds_keeps_its_text_wrap_on_the_group() { + let mut doc = Document::new(300.0, 200.0); + let spec = vectorcraft_doc::BlendSpec::default(); + let thing = wrapped(named(Node::new(doc.alloc_id(), NodeKind::Blend { children: vec![], spec: Box::new(spec) }), "Thing"), 4.5, true); + assert_eq!(thing.geometric_bounds(), None); + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, thing).unwrap(); + let text_out = program(&doc); + assert_eq!(text_out.matches("(AI11TextWrapOffset)").count(), 1, "{text_out}"); + let back = read_back(&doc); + same_wraps(&wraps(back.layers[0].children().unwrap()), &[(Some("Thing".into()), 4.5, true)]); +} + +/// A symbol instance written as its art, whose art holds an envelope of area type beside a square, +/// wraps area type below it by its bounds after reopening. The envelope there is written as its art, +/// after the type written for it as a live envelope is taken back: the group has no text wrap +/// options, and its first member is the rectangle of the bounds. +#[test] +fn an_envelope_of_area_type_in_written_art_leaves_the_wrap_on_the_bounds() { + use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions}; + use vectorcraft_doc::{TextKind, TextObject, TextRun}; + let doc = over_area_type(|doc| { + let kind = EnvelopeKind::Mesh { rows: 2, cols: 3, points: envelope_points(2, 3), handles: vec![] }; + let mut envelope = envelope_node(doc, kind, 50.0, false, EnvelopeOptions::NEW); + let mut t = TextObject::point(vectorcraft_geom::Point::ZERO, "", style(10.0, Color::BLACK)); + t.runs = vec![TextRun::new("bent", style(10.0, Color::BLACK))]; + t.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(60.0, 30.0, 140.0, 70.0)) }; + t.xf = Affine::IDENTITY; + let t = text_node(doc, t); + let NodeKind::Envelope { content, .. } = &mut envelope.kind else { unreachable_envelope() }; + content.push(Arc::new(t)); + let s = square(doc, Rect::new(250.0, 150.0, 260.0, 160.0), LEAF); + let art = group(doc, vec![envelope, s], false); + doc.symbols.push(Symbol { dynamic: false, name: "Bent".into(), art: Arc::new(art) }); + let mut n = instance(doc, "Bent", Affine::IDENTITY); + n.isolate = true; + wrapped(named(n, "Thing"), 4.5, false) + }); + let text_out = program(&doc); + let back = read_back(&doc); + let (before, after) = (area_wrap_region(&doc), area_wrap_region(&back)); + assert_eq!(before.len(), 1); + assert!(same_region(&before, &after), "{before:?}\n{after:?}\n{text_out}"); + let g = &back.layers[0].children().unwrap()[1]; + assert_eq!(g.extras().wrap, None, "{text_out}"); + let mut live = 0; + g.walk(&mut |m| live += usize::from(matches!(m.kind, NodeKind::Envelope { .. }))); + assert_eq!(live, 0, "{text_out}"); + let first = &g.children().unwrap()[0]; + assert!(matches!(first.kind, NodeKind::Path { guide: false, .. }) && first.appearance.items.is_empty(), "{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, and /// with its strokes when the region outside leaves nothing of its fills. diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index fcbf1e1b82..1b48697e32 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -289,7 +289,8 @@ 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 + /// The type just written as outlines, or the symbol instance or live object just written as a + /// group of its art, 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`]). @@ -773,6 +774,8 @@ impl<'a> Writer<'a> { if !self.open_group("u") { return; } + let state = self.state; + let moved = self.wrap_on_bounds(n, state); // The canvas places an instance inside a symbol's art where the outer instance puts // it (9-slice guides, stains and patterns included), and this art doesn't move with it. self.wrote_fixed |= self.in_symbol; @@ -817,12 +820,13 @@ impl<'a> Writer<'a> { self.warn(SYMBOL_LIMIT); } } + self.wrap_moved = moved; self.end_group("U", xy); } NodeKind::Envelope { .. } if self.envelope(n, xy) => {} - NodeKind::Envelope { .. } => self.drawn_art(n, xy, Some(envelopes::ENVELOPES)), + NodeKind::Envelope { .. } => self.drawn_art(n, xy, Some(envelopes::ENVELOPES), true), NodeKind::Blend { .. } | NodeKind::Mesh(_) | NodeKind::Repeat(_) | NodeKind::PlacedDocument(_) | NodeKind::Intertwine { .. } => { - self.drawn_art(n, xy, Some(LIVE)); + self.drawn_art(n, xy, Some(LIVE), true); } // Ruler guides are kept in the document's native copy only. NodeKind::RulerGuide { .. } => {} @@ -889,13 +893,17 @@ impl<'a> Writer<'a> { } /// Live object `n`, of transparency `xy`, as a group of its art, with `warning` when it is given. - fn drawn_art(&mut self, n: &Node, xy: Xy, warning: Option<&str>) { + /// With `bounds`, `n`'s text wrap options go on the rectangle of its bounds, the group's first + /// member ([`Self::wrap_on_bounds`]); without it, in the group's dictionary. + fn drawn_art(&mut self, n: &Node, xy: Xy, warning: Option<&str>, bounds: bool) { if !self.open_group("u") { return; } + let state = self.state; if let Some(w) = warning { self.warn(w); } + let moved = bounds && self.wrap_on_bounds(n, state); if self.nest < MAX_NEST { let g = vectorcraft_effects::expand_live_deep(Some(self.doc), n); self.nest += 1; @@ -906,9 +914,29 @@ impl<'a> Writer<'a> { self.drawn -= 1; self.nest -= 1; } + self.wrap_moved = moved; self.end_group("U", xy); } + /// In the group that object `n` is written as, when the group's dictionary would hold `n`'s text + /// wrap options: the rectangle of `n`'s bounds with them ([`Self::wrap_bounds`]), then lock and + /// hidden state `state` again. True when the group's dictionary is to leave the options out + /// ([`Self::wrap_moved`]), so the group wraps type by `n`'s bounds, as `n` does + /// ([`vectorcraft_doc::text::resolve_wrap`]), not by its members. Written before the group's + /// members, the rectangle is below any area type among them and does not wrap it. False, + /// writing nothing, when `n` has no finite bounds, and the group's dictionary keeps the options. + fn wrap_on_bounds(&mut self, n: &Node, state: Option<(bool, bool)>) -> bool { + let Some(w) = n.extras().wrap.filter(|_| self.drawn == 0 && !self.in_look) else { return false }; + if finite_bounds(n).is_none() { + return false; + } + self.wrap_bounds(n, w); + if let Some((locked, hidden)) = state { + self.state(locked, hidden); + } + true + } + /// `n`'s `/ArtDictionary`, after it, when it has a name (`AI10_ArtUID`, see [`Self::take_id`]), /// is bound to variables ([`Self::bound_variables`]; without a name, it gets an XML id and an /// empty `AIArtName`), has text wrap options ([`Self::text_wrap`]), has an opacity mask @@ -1555,23 +1583,20 @@ 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; - } + // Type wraps by its bounds. + self.wrap_moved = self.wrap_on_bounds(n, state); 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 + /// An unpainted closed rectangle at the geometric bounds of type, a symbol instance or a live + /// object `n`, the region its text wraps around ([`vectorcraft_doc::text::resolve_wrap`]), 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 }; + let Some(b) = finite_bounds(n) else { return }; self.state(n.locked, !n.visible); let objects = self.objects; self.plain_object(&shapes::rectangle(b), FillRule::NonZero, None, None, Xy::PLAIN); @@ -1760,6 +1785,11 @@ impl<'a> Writer<'a> { } } +/// `n`'s geometric bounds, when they are finite. +fn finite_bounds(n: &Node) -> Option { + n.geometric_bounds().filter(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite())) +} + /// The gradient of paint `p`, when it has one. fn gradient(p: Option<&Paint>) -> Option<&vectorcraft_color::GradientPaint> { match p { diff --git a/crates/eps/src/ai_editing/writer/envelopes.rs b/crates/eps/src/ai_editing/writer/envelopes.rs index dbd906e7cd..8b4ebc880d 100644 --- a/crates/eps/src/ai_editing/writer/envelopes.rs +++ b/crates/eps/src/ai_editing/writer/envelopes.rs @@ -27,7 +27,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 whose type is threaded, has text wrap options or is written as its outlines, 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"; +pub(in crate::ai_editing) const ENVELOPES: &str = "envelopes whose type is threaded, has text wrap options or is written as its outlines, envelopes without contents, envelopes in opacity masks, pattern tiles, art cut to a clipping object or other envelopes' contents, envelopes 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). @@ -356,15 +356,17 @@ fn top_object_grid(path: &PathData, corners: Option<[u32; 4]>) -> Option<(usize, impl Writer<'_> { /// Envelope `n`, of transparency `xy`, as a live envelope (see the module's form), outside opacity - /// masks' art, pattern tiles, art cut to a clipping object and the layers of a large canvas. Type - /// in its contents is written as type, which the reader makes the envelope's contents again. + /// masks' art, pattern tiles and art cut to a clipping object. On a large canvas it is written at + /// the document's reduced size, its saved box size included, which the reader reads at the + /// declared scale. Type in its contents is written as type, which the reader makes the + /// envelope's contents again. /// False, writing nothing, where it is written as its art instead: where the reader would open it /// in another shape, or with its type as drawn art (threaded type, type with text wrap options, /// type written as its outlines), 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.checks_left == 0 { + if self.hidden > 0 || self.clip.is_some() || self.nest >= MAX_NEST || self.checks_left == 0 { return false; } if content.iter().any(|c| holds_type(c)) && !content.iter().all(|c| type_reads_back(c, self.doc)) { @@ -411,9 +413,10 @@ impl Writer<'_> { self.hidden -= 1; self.nest -= 1; // The distorted art, which takes the envelope's lock, visibility, transparency, name and - // opacity mask. + // opacity mask. The reader opens the envelope live, wrapping type by its bounds, so its text + // wrap options stay in the art's dictionary. self.state(n.locked, !n.visible); - self.drawn_art(n, xy, None); + self.drawn_art(n, xy, None, false); if !opened || outlines || self.left_out_since(charges) { let lines = self.body.split_off(start); self.give_back(charges, &lines); diff --git a/crates/eps/src/ai_editing/writer/texts.rs b/crates/eps/src/ai_editing/writer/texts.rs index f1fb10af78..9bc831e537 100644 --- a/crates/eps/src/ai_editing/writer/texts.rs +++ b/crates/eps/src/ai_editing/writer/texts.rs @@ -22,15 +22,15 @@ 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, + AreaOptions, Burasagari, CharStyle, Document, FirstBaseline, Justify, Kinsoku, KinsokuShoriType, LineCap, LineJoin, Mojikumi, Node, NodeId, + NodeKind, ParaDirection, ParaStyle, PathAlign, PathEffect, TextKind, TextObject, VerticalAlign, }; 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, 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"; +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, right-to-left direction, Kinsoku set, Kinsoku Shori Type, Burasagari and Bunri-Kinshi (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; @@ -161,6 +161,10 @@ fn dict(pairs: Vec<(u32, V)>) -> V { V::Dict(pairs) } +/// The document's Kinsoku sets, in order, each by its name: a paragraph's key 27 is its set's index +/// here (0 Hard, 1 Soft), as the reader's `kinsoku_sets` reads them. +const KINSOKU_SETS: [&str; 2] = ["PhotoshopKinsokuHard", "PhotoshopKinsokuSoft"]; + /// A resource set: its resources, each `<< /0 resource >>`, and its display list. fn set(resources: Vec, display: bool) -> V { let mut d = vec![(0, V::List(resources.into_iter().map(|r| dict(vec![(0, r)])).collect()))]; @@ -401,7 +405,6 @@ pub(in crate::ai_editing) fn loses(t: &TextObject) -> bool { } let hangul = text.chars().any(|c| matches!(c, '\u{1100}'..='\u{11FF}' | '\u{3130}'..='\u{318F}' | '\u{A960}'..='\u{A97F}' | '\u{AC00}'..='\u{D7FF}' | '\u{FFA0}'..='\u{FFDC}')); - let pairs = text.chars().zip(text.chars().skip(1)).any(|(a, b)| vectorcraft_text::inseparable(a, b)); let held = ParaStyle { justify: p.justify, left_indent: p.left_indent, @@ -411,16 +414,16 @@ pub(in crate::ai_editing) fn loses(t: &TextObject) -> bool { space_after: p.space_after, hyphenate: p.hyphenate, direction: p.direction.filter(|d| *d == ParaDirection::RightToLeft), - // The composition of Japanese punctuation new type gets (Line-end Punctuation Half - // Width, Standard burasagari) isn't reported: it changes no other script's lines. + // The Mojikumi set new type gets (Line-end Punctuation Half Width) isn't reported: it + // changes no other script's lines. mojikumi: if p.mojikumi == Mojikumi::LineEndHalf { p.mojikumi } else { ParaStyle::default().mojikumi }, - burasagari: if p.burasagari == Burasagari::Standard { p.burasagari } else { ParaStyle::default().burasagari }, + kinsoku: p.kinsoku, + kinsoku_type: p.kinsoku_type, + burasagari: p.burasagari, + bunri_kinshi: p.bunri_kinshi, // The text document has no Korean Line Break Anywhere: it reads back off, which // changes only the lines of a paragraph with Hangul in it. korean_line_break_anywhere: p.korean_line_break_anywhere && !hangul, - // Nor Bunri-Kinshi: it reads back off, which changes only the lines of a paragraph - // with an inseparable pair in it. - bunri_kinshi: p.bunri_kinshi && !pairs, ..ParaStyle::default() }; *p != held @@ -756,6 +759,32 @@ impl TextDoc { (4, len(p.space_before)), (5, len(p.space_after)), (9, V::Bool(p.hyphenate)), + (23, V::Bool(p.bunri_kinshi)), + ( + 24, + V::Int(match p.burasagari { + Burasagari::None => 0, + Burasagari::Standard => 1, + Burasagari::Forced => 2, + }), + ), + ( + 25, + V::Int(match p.kinsoku_type { + KinsokuShoriType::PushInFirst => 0, + KinsokuShoriType::PushOutFirst => 1, + KinsokuShoriType::PushOutOnly => 2, + }), + ), + // The Kinsoku set: `/nil` for None, else its index in the document's sets ([`KINSOKU_SETS`]). + ( + 27, + match p.kinsoku { + Kinsoku::None => V::Name("nil"), + Kinsoku::Hard => V::Int(0), + Kinsoku::Soft => V::Int(1), + }, + ), ]; if rtl { d.push((33, V::Int(1))); @@ -1110,7 +1139,7 @@ impl TextDoc { (1, set(fonts, true)), (2, empty()), (3, empty()), - (4, empty()), + (4, set(KINSOKU_SETS.iter().map(|name| dict(vec![(0, V::Str((*name).into()))])).collect(), false)), (5, set(vec![normal_char], true)), (6, set(vec![normal_para], true)), (8, set(self.frames.iter().map(clone_v).collect(), false)), diff --git a/crates/eps/src/ai_ops.rs b/crates/eps/src/ai_ops.rs index 6b1374cd83..aa819a77ad 100644 --- a/crates/eps/src/ai_ops.rs +++ b/crates/eps/src/ai_ops.rs @@ -36,10 +36,8 @@ pub(crate) fn subpath(s: &mut String, xf: Affine, sp: &SubPath) { s.push_str(if smooth { "c\n" } else { "C\n" }); } }; - for pair in sp.anchors.windows(2) { - if let [a, b] = pair { - segment(s, a, b); - } + for (a, b) in sp.anchors.iter().zip(sp.anchors.iter().skip(1)) { + segment(s, a, b); } if sp.closed && sp.anchors.len() > 1 diff --git a/crates/eps/src/import/ai/envelope.rs b/crates/eps/src/import/ai/envelope.rs index 3ae753b7d5..501b9f4b00 100644 --- a/crates/eps/src/import/ai/envelope.rs +++ b/crates/eps/src/import/ai/envelope.rs @@ -121,11 +121,12 @@ pub(super) fn options(o: &Obj) -> Option<(EnvelopeOptions, f64)> { /// The margins of `content` when the size the file saves for it (`AIDeformArtWidthKey`, /// `AIDeformArtHeightKey`) matches its bounds with its strokes within [`SAVED_SIZE_SLACK`] and lies -/// nearer them than its geometric bounds. None without that size, or for contents with no width or -/// no height. -fn saved_margin(o: &Obj, content: &[Arc]) -> Option<[f32; 4]> { +/// nearer them than its geometric bounds. The saved size is in art space, and `scale` takes it to the +/// contents' space (a Large Canvas copy read at its declared scale). None without that size, or for +/// contents with no width or no height. +fn saved_margin(o: &Obj, content: &[Arc], scale: f64) -> Option<[f32; 4]> { let saved = |key: &str| match o.nums(key).as_slice() { - [v] if v.is_finite() => Some(*v), + [v] if v.is_finite() => Some(*v * scale).filter(|v| v.is_finite()), _ => None, }; let (w, h) = (saved("AIDeformArtWidthKey")?, saved("AIDeformArtHeightKey")?); @@ -508,9 +509,10 @@ fn unwrapped(mut nodes: Vec) -> Vec> { } /// The live envelope of dictionary `o`, the group on `%_` lines before it (`before`) and the art -/// in its `AIDeformArtKey` block (`inner`); `None` where they don't make one. -pub(super) fn live(o: &Obj, before: Option, inner: Vec) -> Option { - envelope_as(o, before, inner, false) +/// in its `AIDeformArtKey` block (`inner`); `None` where they don't make one. `scale` takes sizes in +/// art space to the space the art was read into ([`saved_margin`]). +pub(super) fn live(o: &Obj, before: Option, inner: Vec, scale: f64) -> Option { + envelope_as(o, before, inner, false, scale) } /// Is the envelope of dictionary `o` a warp? @@ -521,12 +523,12 @@ fn is_warp(o: &Obj) -> bool { /// [`live`] for a warp, as a mesh envelope on the grid its editing data saves (the mesh that shapes /// it), its points and handles as saved: it draws as that grid does, without the warp's style, bend /// and distortions. `None` for an envelope that isn't a warp, or whose grid doesn't read. -fn live_on_saved_grid(o: &Obj, before: Option, inner: Vec) -> Option { - envelope_as(o, before, inner, true) +fn live_on_saved_grid(o: &Obj, before: Option, inner: Vec, scale: f64) -> Option { + envelope_as(o, before, inner, true, scale) } /// [`live`], or with `on_grid` [`live_on_saved_grid`]. -fn envelope_as(o: &Obj, before: Option, inner: Vec, on_grid: bool) -> Option { +fn envelope_as(o: &Obj, before: Option, inner: Vec, on_grid: bool, scale: f64) -> Option { let editing = switch(o, "AIDeformEditModeKey")?; let (mut options, fidelity) = options(o)?; let before = before?; @@ -546,7 +548,7 @@ fn envelope_as(o: &Obj, before: Option, inner: Vec, on_grid: bool) - return None; } if options.distort_appearance { - options.bounds_margin = saved_margin(o, &content).unwrap_or_default(); + options.bounds_margin = saved_margin(o, &content, scale).unwrap_or_default(); } let kind = match (whole(o, "AIDeformStyle")??, on_grid) { (1, false) => warp(o)?, @@ -637,14 +639,15 @@ pub(super) struct WarpedLook { /// An envelope of type read with its drawn art: its dictionary, the group on `%_` lines before it /// and the art in its `AIDeformArtKey` block, as [`live`] takes them (their text slots still -/// empty), and the id of its drawn art in the document. Type is laid out after the layers are read, -/// so it waits for that ([`WarpedType::settle_envelopes`]). +/// empty), the id of its drawn art in the document, and the scale [`live`] takes. Type is laid out +/// after the layers are read, so it waits for that ([`WarpedType::settle_envelopes`]). #[derive(Debug)] pub(crate) struct TypedEnvelope { pub(super) obj: Obj, pub(super) before: Option, pub(super) inner: Vec, pub(super) drawn: NodeId, + pub(super) scale: f64, } /// Why an envelope of type kept its drawn art. @@ -788,7 +791,7 @@ impl WarpedType { shown: &BTreeSet, waiting: usize, ) -> Result<(NodeId, Vec), TypeKept> { - let TypedEnvelope { obj, mut before, mut inner, drawn } = envelope; + let TypedEnvelope { obj, mut before, mut inner, drawn, scale } = envelope; let art = doc.node(drawn).cloned().ok_or(TypeKept::Read)?; // The text slots in the contents, in the order the reader put their hidden copies in. let mut slots = vec![]; @@ -813,13 +816,13 @@ impl WarpedType { } // A warp that VectorCraft's own warp doesn't draw as its drawn art may still draw as the // grid the file saves for it: then it opens as a mesh envelope on that grid. - let on_grid = if is_warp(&obj) { live_on_saved_grid(&obj, before.clone(), inner.clone()) } else { None }; + let on_grid = if is_warp(&obj) { live_on_saved_grid(&obj, before.clone(), inner.clone(), scale) } else { None }; // With Distort Appearance, a file's envelope may map its type from its glyphs grown by half // their strokes' weight or from the glyphs alone, and for type the size the file saves for // that box is often out of date (not the size of the type there now): each is checked. // After all of those, each is checked mapping from what its type paints, where that box is // another: it is measured only when such a check comes and one is left. - let kinds: Vec = live(&obj, before, inner).into_iter().chain(on_grid).collect(); + let kinds: Vec = live(&obj, before, inner, scale).into_iter().chain(on_grid).collect(); if kinds.is_empty() { return Err(TypeKept::Read); } diff --git a/crates/eps/src/import/ai/read.rs b/crates/eps/src/import/ai/read.rs index d32ae4c177..67928785ad 100644 --- a/crates/eps/src/import/ai/read.rs +++ b/crates/eps/src/import/ai/read.rs @@ -581,6 +581,10 @@ struct Reader<'a> { blend_budget: usize, /// The group on `%_` lines an envelope's dictionary just took (see [`Reader::drop_envelope_art`]). envelope_art: Option, + /// The envelope dictionaries whose `AIDeformArtKey` block (`X=` … `X+`) is being read, as how + /// many frames were open with each one innermost, innermost last. The block's art is art: a + /// dictionary in it is read as it is in a container ([`Reader::end_obj`]). + envelope_blocks: Vec, /// Envelopes waiting for their drawn art, innermost last. envelopes: Vec, /// How many more envelopes and warped text objects this import may draw to check @@ -813,6 +817,7 @@ impl<'a> Reader<'a> { blend_record: None, blend_budget: BLEND_BUDGET, envelope_art: None, + envelope_blocks: Vec::new(), envelopes: Vec::new(), envelope_checks: super::envelope::MAX_CHECKED, envelope_spent: super::envelope::Spent::default(), diff --git a/crates/eps/src/import/ai/read/art.rs b/crates/eps/src/import/ai/read/art.rs index 3338968895..c181fcb9d5 100644 --- a/crates/eps/src/import/ai/read/art.rs +++ b/crates/eps/src/import/ai/read/art.rs @@ -2,8 +2,8 @@ use super::containers::close; use super::document::TEXT_SLOT; use super::raster::{self, Limits, Shape}; use super::types::{ - FLIP, Frame, IMAGE_TOO_LARGE, Kind, LARGE_IMAGES, LINKED_PLACEHOLDERS, LINKED_PREVIEWS, MAX_PIXELS, MAX_PLACED_ELSEWHERE, MAX_POINTS, MAX_SIDE, - NON_NATIVE_ART, NON_NATIVE_ART_UNREAD, PLACED_CROP, PLACED_PAGE, Place, PlacedPage, PlacedTail, + FLIP, Frame, GState, IMAGE_TOO_LARGE, Kind, LARGE_IMAGES, LINKED_PLACEHOLDERS, LINKED_PREVIEWS, MAX_PIXELS, MAX_PLACED_ELSEWHERE, MAX_POINTS, + MAX_SIDE, NON_NATIVE_ART, NON_NATIVE_ART_UNREAD, PLACED_CROP, PLACED_PAGE, Place, PlacedPage, PlacedTail, }; use super::{ Affine, AnchorKind, Appearance, AppearanceItem, Arc, BezPath, CANVAS_CENTRE, FillLayer, ImageBlob, ImageObject, Inks, Instance, LinkInfo, Node, @@ -224,12 +224,7 @@ impl<'a> Reader<'a> { items.push(AppearanceItem::Fill(FillLayer { overprint: gs.overprint_fill, ..FillLayer::new(fill_paint.unwrap_or(gs.fill.clone())) })); } if stroke { - let mut st = StrokeLayer::new(stroke_paint.unwrap_or(gs.stroke.clone()), gs.line_width()); - st.cap = gs.cap; - st.join = gs.join; - st.miter_limit = gs.miter; - st.dash = gs.dash.clone(); - st.overprint = gs.overprint_stroke; + let st = self.stroke_layer(stroke_paint.unwrap_or(gs.stroke.clone()), &gs); items.push(AppearanceItem::Stroke(st)); } let kind = NodeKind::Path { path, rule: gs.rule, live: None, clipping: clip, guide }; @@ -330,17 +325,29 @@ impl<'a> Reader<'a> { if !matches!(n.kind, NodeKind::Path { .. }) || n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(_))) { return; } - let mut st = StrokeLayer::new(gs.stroke.clone(), gs.line_width()); - st.cap = gs.cap; - st.join = gs.join; - st.miter_limit = gs.miter; - st.dash = gs.dash.clone(); - st.overprint = gs.overprint_stroke; + let st = self.stroke_layer(gs.stroke.clone(), &gs); + let Some(n) = self.frames.last_mut().and_then(|f| f.children.last_mut()) else { return }; let mut a = (*n.appearance).clone(); a.items.push(AppearanceItem::Stroke(st)); n.appearance = a.into(); } + /// A stroke of `paint` with graphics state `gs`'s weight, caps, joins, miter limit, dashes and + /// overprint, its weight and dashes at the scale the art is read at ([`Self::space_scale`]). + fn stroke_layer(&mut self, paint: Paint, gs: &GState) -> StrokeLayer { + let k = self.space_scale(); + let mut st = StrokeLayer::new(paint, gs.line_width() * k); + st.cap = gs.cap; + st.join = gs.join; + st.miter_limit = gs.miter; + st.dash = gs.dash.clone().map(|mut d| { + d.scale(k); + d + }); + st.overprint = gs.overprint_stroke; + st + } + pub(super) fn set_instance(&mut self, i: &Instance) { let mut to_doc = self.space(); // In a pattern's definition a gradient's `Xm` and `Bm` are written y down about the canvas point of art space's diff --git a/crates/eps/src/import/ai/read/containers.rs b/crates/eps/src/import/ai/read/containers.rs index 8e670b3f72..9db1470093 100644 --- a/crates/eps/src/import/ai/read/containers.rs +++ b/crates/eps/src/import/ai/read/containers.rs @@ -482,6 +482,13 @@ impl<'a> Reader<'a> { return Ok(()); } let Some(f) = self.frames.pop() else { return Ok(()) }; + let depth = self.frames.len(); + // A block left open ends with its dictionary, and envelopes still waiting in it keep their + // drawn art: nothing after the dictionary is theirs. + self.envelope_blocks.retain(|d| *d <= depth); + while let Some(p) = self.envelopes.pop_if(|p| p.depth > depth) { + self.warn(crate::import::ai::envelope::drawn_note(p.typed)); + } let Frame { kind, children, base, hidden, gs, pending_unread_fill, pending_unread_stroke, after, mesh_ended, state, .. } = f; let Kind::Obj(mut o) = kind else { return Ok(()) }; obj::close(&mut o, &mut self.stack, base); @@ -496,7 +503,10 @@ impl<'a> Reader<'a> { } self.after_object = after; self.mesh_ended = mesh_ended; - if matches!(self.frames.last(), Some(Frame { kind: Kind::Obj(_), .. })) { + // An object's dictionary in an envelope's `AIDeformArtKey` block is about the art before it + // there, as it is in a container: an envelope there is one of the outer envelope's contents. + let in_block = o.ty == "ArtDictionary" && self.envelope_blocks.last() == Some(&depth); + if !in_block && matches!(self.frames.last(), Some(Frame { kind: Kind::Obj(_), .. })) { return self.push(V::Obj(Rc::new(*o))); } match o.ty.as_str() { @@ -875,6 +885,7 @@ impl<'a> Reader<'a> { return; } let Some(p) = self.envelopes.pop() else { return }; + let scale = self.space_scale(); let drawn = self.frames.last().filter(|f| f.children.len() == p.siblings + 1).and_then(|f| f.children.last()); let Some(drawn) = drawn else { self.warn(crate::import::ai::envelope::drawn_note(p.typed)); @@ -884,7 +895,7 @@ impl<'a> Reader<'a> { self.wait_for_type(p); return; } - let live = (self.envelope_checks > 0).then(|| crate::import::ai::envelope::live(&p.obj, p.before, p.inner)).flatten(); + let live = (self.envelope_checks > 0).then(|| crate::import::ai::envelope::live(&p.obj, p.before, p.inner, scale)).flatten(); let Some(kind) = live else { self.warn(crate::import::ai::envelope::DRAWN); return; @@ -972,8 +983,8 @@ impl Reader<'_> { self.warn(crate::import::ai::envelope::TYPE_DRAWN); return; } - let drawn = drawn.id; - self.typed_envelopes.push(crate::import::ai::envelope::TypedEnvelope { obj: p.obj, before: p.before, inner: p.inner, drawn }); + let (drawn, scale) = (drawn.id, self.space_scale()); + self.typed_envelopes.push(crate::import::ai::envelope::TypedEnvelope { obj: p.obj, before: p.before, inner: p.inner, drawn, scale }); } } diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs index 312b7cc275..258d7d584b 100644 --- a/crates/eps/src/import/ai/read/document.rs +++ b/crates/eps/src/import/ai/read/document.rs @@ -934,6 +934,13 @@ impl<'a> Reader<'a> { } } + /// How many times as long [`Self::space`] makes a length in art space: a Large Canvas copy's + /// declared scale in the document, and 1 in a pattern's or a symbol's definition. + pub(super) fn space_scale(&mut self) -> f64 { + let k = self.space().determinant().abs().sqrt(); + if k.is_finite() && k > 0.0 { k } else { 1.0 } + } + /// The space an image's matrix is in → where the art being read goes: [`Self::space`], and in a /// symbol's art (outside a pattern's definition) the canvas's space turned y up about art space's /// origin there, as an instance's matrix in it is; `None` there without a template box. diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index 8c032d5d83..721a6988ba 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -41,8 +41,19 @@ impl<'a> Reader<'a> { } /// `X=` in a `/Mask` dictionary: the opacity mask's art starts, read until its `X+` - /// ([`Self::end_mask`]). + /// ([`Self::end_mask`]). In an envelope's dictionary, its `AIDeformArtKey` block starts + /// ([`Reader::envelope_blocks`]). fn open_mask_object(&mut self, hidden: bool) -> Result<(), String> { + if let Some(Frame { kind: Kind::Obj(o), .. }) = self.frames.last() + && o.ty == "ArtDictionary" + && o.get("AIDeformOptionsKey").is_some() + { + // One entry for each open dictionary, however many `X=` it has. + if self.envelope_blocks.last() != Some(&self.frames.len()) { + self.envelope_blocks.push(self.frames.len()); + } + return Ok(()); + } if !matches!(self.frames.last(), Some(Frame { kind: Kind::Obj(o), .. }) if o.ty == "Mask") { // `X=` also introduces legacy text frame art, read by `text_frames`. return Ok(()); @@ -63,6 +74,22 @@ impl<'a> Reader<'a> { self.open(Kind::Mask, hidden) } + /// `X+`: a dictionary's art block ends. The block of a dictionary whose `X=` opened no frame (an + /// envelope's, in an opacity mask's art too) ends with the dictionary still innermost; an opacity + /// mask's ends its art ([`Self::end_mask`]). + fn end_block(&mut self) -> Result<(), String> { + if matches!(self.frames.last(), Some(Frame { kind: Kind::Obj(_), .. })) { + if self.envelope_blocks.last() == Some(&self.frames.len()) { + self.envelope_blocks.pop(); + } + return Ok(()); + } + if self.frames.iter().any(|f| matches!(f.kind, Kind::Mask)) { + return self.end_mask(); + } + Ok(()) + } + /// `LB`: a graph started in this layer that hasn't ended doesn't go on past it; the layer ends. fn layer_end(&mut self) -> Result<(), String> { if self.graph.as_ref().is_some_and(|g| g.frames >= self.frames.len()) { @@ -159,8 +186,7 @@ impl<'a> Reader<'a> { } ";" => return self.end_obj(), "X=" => return self.open_mask_object(hidden), - "X+" if self.frames.iter().any(|f| matches!(f.kind, Kind::Mask)) => return self.end_mask(), - "X+" => return Ok(()), + "X+" => return self.end_block(), _ => {} } self.state_block_continues(w); diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 7013468d25..f133a9ee03 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -8620,6 +8620,224 @@ fn an_envelope_off_the_page_opens_live_when_it_draws_close_to_its_drawn_art() { assert!(r.warnings.is_empty(), "{:?}", r.warnings); } +/// `art` on `%_` lines, as the editing data writer hides it: a line already on one stays as it is. +fn hidden_once(art: &str) -> String { + art.lines().map(|l| if l.starts_with("%_") { format!("{l}\n") } else { format!("%_{l}\n") }).collect() +} + +/// A mesh envelope of `content` shaped by the grid `shape`, with Edit Contents on (`editing`: the +/// contents in the group before the dictionary, the grid in its `AIDeformArtKey` block) or off (the +/// other way round, the contents in a plain group), then `drawn` and the plugin's `XP`. An envelope +/// record in `content` keeps its own `%_` lines. +fn mesh_envelope(shape: &str, editing: bool, content: &str, drawn: &str) -> String { + let keys = ENVELOPE_KEYS.replace("0 /Bool (AIDeformEditModeKey)", &format!("{} /Bool (AIDeformEditModeKey)", u8::from(editing))); + let (before, block) = if editing { (content.to_string(), shape.to_string()) } else { (shape.to_string(), format!("u\n{content}U\n9 () XW\n")) }; + format!( + "{}%_/ArtDictionary :\n{}%_X=\n{}%_X+\n%_ (AIDeformArtKey) ,\n%_2 /Int (AIDeformStyle) ,\n%_;\n%_\n%_9 () XW\nu\n{drawn}U\n9 () XW\n(Adobe Deform Plugin) 1 0 0 XP\n", + hidden_once(&format!("u\n{before}U\n")), + commented(&keys), + hidden_once(&block), + ) +} + +/// The mesh envelope that maps the box 40 20 160 80 onto itself, and what it draws of +/// [`envelope_content`]. +fn flat_mesh() -> (String, vectorcraft_doc::live::EnvelopeKind, String) { + let flat = vectorcraft_doc::live::EnvelopeKind::Mesh { + rows: 1, + cols: 1, + points: vec![Point::new(40.0, 20.0), Point::new(160.0, 20.0), Point::new(40.0, 80.0), Point::new(160.0, 80.0)], + handles: vec![], + }; + let drawn = drawn_content(&flat); + (straight_mesh(1, 1, (120.0, 60.0)), flat, drawn) +} + +/// An envelope inside another envelope's contents opens as a live envelope inside the live outer +/// one, with Edit Contents on or off at either level: each keeps its own kind, contents and Edit +/// Contents, and neither leaves a copy of its contents drawn beside it. +#[test] +fn an_envelope_in_an_envelope_s_contents_opens_live_inside_it() { + use vectorcraft_doc::live::EnvelopeKind; + let (shape, flat, drawn) = flat_mesh(); + let EnvelopeKind::Mesh { points, .. } = &flat else { panic!("{flat:?}") }; + for (outer_editing, inner_editing) in [(false, false), (false, true), (true, false), (true, true)] { + let why = format!("outer editing {outer_editing}, inner editing {inner_editing}"); + let inner = mesh_envelope(&shape, inner_editing, &envelope_content(), &drawn); + let r = read_ok(&layer(&mesh_envelope(&shape, outer_editing, &hidden_once(&inner), &format!("u\n{drawn}U\n")))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{why}: {a:#?}"); + let flat_points = |kind: &EnvelopeKind| match kind { + EnvelopeKind::Mesh { rows: 1, cols: 1, points, .. } => Some(points.clone()), + _ => None, + }; + let (content, kind, _, editing, _) = live_envelope(&a[0]); + assert_eq!((flat_points(kind), editing), (Some(points.clone()), outer_editing), "{why}: {kind:?}"); + assert_eq!(content.len(), 1, "{why}: {content:#?}"); + let (inner, kind, _, editing, _) = live_envelope(&content[0]); + assert_eq!((flat_points(kind), editing), (Some(points.clone()), inner_editing), "{why}: {kind:?}"); + assert_eq!(inner.len(), 1, "{why}: {inner:#?}"); + assert!(matches!(inner[0].kind, NodeKind::Path { .. }), "{why}: {inner:#?}"); + assert_eq!(fill(&inner[0]).color(), Some(Color::rgb(1.0, 0.0, 0.0)), "{why}"); + assert!(r.warnings.is_empty(), "{why}: {:?}", r.warnings); + } +} + +/// An outer envelope, Edit Contents off, whose `AIDeformArtKey` block holds `block` as it is, with no +/// plain group around it, shaped by the grid `shape` and drawn as `drawn`. +fn bare_block_envelope(shape: &str, block: &str, drawn: &str) -> String { + format!( + "{}%_/ArtDictionary :\n{}%_X=\n{}%_X+\n%_ (AIDeformArtKey) ,\n%_2 /Int (AIDeformStyle) ,\n%_;\n%_\n%_9 () XW\nu\n{drawn}U\n9 () XW\n(Adobe Deform Plugin) 1 0 0 XP\n", + hidden_once(&format!("u\n{shape}U\n")), + commented(ENVELOPE_KEYS), + hidden_once(block), + ) +} + +/// An envelope record straight in another envelope's `AIDeformArtKey` block, with no group around +/// it, opens live inside the live outer envelope too. Two of them there are both its contents. +#[test] +fn an_envelope_straight_in_an_envelope_s_block_opens_live_inside_it() { + let (shape, _, drawn) = flat_mesh(); + let inner = hidden_once(&mesh_envelope(&shape, false, &envelope_content(), &drawn)); + let r = read_ok(&layer(&bare_block_envelope(&shape, &inner, &format!("u\n{drawn}U\n")))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + let (content, ..) = live_envelope(&a[0]); + assert_eq!(content.len(), 1, "{content:#?}"); + let (inner_content, ..) = live_envelope(&content[0]); + assert!(matches!(inner_content[0].kind, NodeKind::Path { .. }), "{inner_content:#?}"); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + // Two envelopes side by side in the block: both are the outer envelope's contents, each live. + let two = format!("{inner}{inner}"); + let r = read_ok(&layer(&bare_block_envelope(&shape, &two, &format!("u\n{drawn}U\nu\n{drawn}U\n")))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + let (content, ..) = live_envelope(&a[0]); + assert_eq!(content.len(), 2, "{content:#?}"); + content.iter().for_each(|c| _ = live_envelope(c)); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); +} + +/// An object's own dictionary straight in an envelope's block, with no group around them, names it +/// there. +#[test] +fn an_object_s_dictionary_straight_in_an_envelope_s_block_names_it() { + let (shape, _, drawn) = flat_mesh(); + let block = format!("{}/ArtDictionary :\n(Box) /String (AIArtName) ,\n;\n", envelope_content()); + let r = read_ok(&layer(&bare_block_envelope(&shape, &block, &format!("u\n{drawn}U\n")))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + let (content, ..) = live_envelope(&a[0]); + assert_eq!(content.len(), 1, "{content:#?}"); + assert_eq!(content[0].name.as_deref(), Some("Box"), "{content:#?}"); +} + +/// An inner envelope that doesn't open live keeps its drawn art inside the live outer envelope, +/// drawn once, without its own source art: one whose drawn art differs from what it draws, and one +/// whose record doesn't read (a style number past the list). The outer envelope maps that drawn +/// art's box onto its grid. An outer envelope that doesn't match its drawn art keeps that drawn +/// art, and nothing of its record is drawn. +#[test] +fn a_nested_envelope_that_doesn_t_open_live_keeps_its_drawn_art() { + let (shape, _, drawn) = flat_mesh(); + let shifted = format!("{RED}{}f\n", rect_path(42.0, 20.0, 162.0, 80.0)); + let unread = mesh_envelope(&shape, false, &envelope_content(), &drawn).replace("%_2 /Int (AIDeformStyle)", "%_9 /Int (AIDeformStyle)"); + for (why, inner) in [("drawn elsewhere", mesh_envelope(&shape, false, &envelope_content(), &shifted)), ("unread", unread)] { + for bare in [false, true] { + let inner = hidden_once(&inner); + let outer_drawn = format!("u\n{drawn}U\n"); + let body = if bare { bare_block_envelope(&shape, &inner, &outer_drawn) } else { mesh_envelope(&shape, false, &inner, &outer_drawn) }; + let r = read_ok(&layer(&body)); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{why}, bare {bare}: {a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Envelope { .. }), "{why}, bare {bare}: {:?}", r.warnings); + let (content, ..) = live_envelope(&a[0]); + assert_eq!(content.len(), 1, "{why}, bare {bare}: {content:#?}"); + // The inner envelope's drawn art: its group of one path, or, straight in the block, the + // path, as the plain group around a block's only object is the block's own. + let drawn_path = if bare { + &content[0] + } else { + let kids = content[0].children().unwrap_or_else(|| panic!("{why}: {content:#?}")); + assert_eq!(kids.len(), 1, "{why}: {content:#?}"); + &kids[0] + }; + assert!(matches!(drawn_path.kind, NodeKind::Path { .. }), "{why}, bare {bare}: {content:#?}"); + assert_eq!(r.warnings, [super::envelope::DRAWN], "{why}, bare {bare}"); + } + } + // The outer envelope's drawn art lies elsewhere: it stays, as one group, the inner record with it. + let inner = hidden_once(&mesh_envelope(&shape, false, &envelope_content(), &drawn)); + for bare in [false, true] { + let outer_drawn = format!("u\n{shifted}U\n"); + let body = if bare { bare_block_envelope(&shape, &inner, &outer_drawn) } else { mesh_envelope(&shape, false, &inner, &outer_drawn) }; + let r = read_ok(&layer(&body)); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "bare {bare}: {a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Group { .. }), "bare {bare}: {a:#?}"); + assert_eq!(a[0].geometric_bounds(), Some(Rect::new(42.0, 20.0, 162.0, 80.0)), "bare {bare}"); + assert_eq!(r.warnings, [super::envelope::DRAWN], "bare {bare}"); + } +} + +/// Broken nested records read without taking another record's place: an inner `X=` with no `X+` +/// (the inner envelope still opens live), an inner dictionary with no group before it (its drawn art +/// stays), and an `XP` repeated after the inner one. The outer envelope, whose own record is whole, +/// still opens live around what the inner one left. +#[test] +fn broken_nested_envelope_records_keep_the_outer_envelope() { + let (shape, _, drawn) = flat_mesh(); + let inner = hidden_once(&mesh_envelope(&shape, false, &envelope_content(), &drawn)); + let no_end = inner.replacen("%_X+\n", "", 1); + let no_group = inner.replacen(&hidden_once(&format!("u\n{shape}U\n")), "", 1); + let twice = inner.replace("%_(Adobe Deform Plugin) 1 0 0 XP\n", "%_(Adobe Deform Plugin) 1 0 0 XP\n%_(Adobe Deform Plugin) 1 0 0 XP\n"); + for (why, inner, live) in [("no X+", no_end, true), ("no group", no_group, false), ("XP twice", twice, true)] { + for bare in [false, true] { + let outer_drawn = format!("u\n{drawn}U\n"); + let body = if bare { bare_block_envelope(&shape, &inner, &outer_drawn) } else { mesh_envelope(&shape, false, &inner, &outer_drawn) }; + let r = read_ok(&layer(&body)); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{why}, bare {bare}: {a:#?}"); + let (content, ..) = live_envelope(&a[0]); + assert_eq!(content.len(), 1, "{why}, bare {bare}: {content:#?}"); + assert_eq!(matches!(content[0].kind, NodeKind::Envelope { .. }), live, "{why}, bare {bare}: {content:#?}"); + } + } +} + +/// An inner envelope whose `XP` is missing stops waiting when the outer envelope's dictionary ends: +/// a stray `XP` in a later group leaves that group's art as it is. +#[test] +fn an_inner_envelope_without_its_xp_does_not_take_later_art() { + let (shape, _, drawn) = flat_mesh(); + let inner = hidden_once(&mesh_envelope(&shape, false, &envelope_content(), &drawn)).replace("%_(Adobe Deform Plugin) 1 0 0 XP\n", ""); + let later = format!("u\nu\n{drawn}U\n(Adobe Deform Plugin) 1 0 0 XP\nU\n"); + let r = read_ok(&layer(&format!("{}{later}", bare_block_envelope(&shape, &inner, &format!("u\n{drawn}U\n"))))); + let a = art(&r.doc); + assert_eq!(a.len(), 2, "{a:#?}"); + live_envelope(&a[0]); + let kids = a[1].children().unwrap_or_else(|| panic!("{a:#?}")); + assert!(matches!(kids[0].kind, NodeKind::Group { .. }), "{a:#?}"); + assert_eq!(r.warnings, [super::envelope::DRAWN], "{:?}", r.warnings); +} + +/// An envelope in an opacity mask's art reads: its block's `X+` ends the block, not the mask's art. +#[test] +fn an_envelope_in_an_opacity_mask_s_art_reads() { + let (shape, _, drawn) = flat_mesh(); + let owner = format!("{RED}{}f\n", rect_path(10.0, 20.0, 170.0, 90.0)); + let envelope = hidden_once(&mesh_envelope(&shape, false, &envelope_content(), &drawn)); + let mask = format!( + "%_/ArtDictionary :\n%_/Mask :\n%_1 /Bool (Linked) ,\n%_X=\n%_u\n{envelope}%_U\n%_X+\n%_(Art) ,\n%_1 /Bool (Clipping) ,\n%_0 /Bool (Inverted) ,\n%_0 /Bool (Disabled) ,\n%_; (AI9_Mask) ,\n%_;\n" + ); + let r = read_ok(&layer(&format!("{owner}{mask}"))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + let m = a[0].extras().mask.as_ref().unwrap_or_else(|| panic!("{a:#?}")); + assert_eq!(m.art.geometric_bounds(), Some(Rect::new(40.0, 20.0, 160.0, 80.0)), "{:#?}", m.art); +} + #[test] fn a_gradient_mesh_reads_as_a_patch() { let corner = |rgb: &str, x: i32, y: i32, next: (i32, i32), prev: (i32, i32)| { diff --git a/crates/format/tests/it/native_v3.rs b/crates/format/tests/it/native_v3.rs index 512025375e..afc3bea9d2 100644 --- a/crates/format/tests/it/native_v3.rs +++ b/crates/format/tests/it/native_v3.rs @@ -212,6 +212,44 @@ fn text_composer_round_trips() { assert!(!String::from_utf8_lossy(&save(&d2, false)).contains("composer")); } +/// Every composer reads back as it was saved (the two Standard ones as their own values), and the +/// ME&SA names are the ones files have always used: `everyLine` stays the unwritten default and +/// `singleLine` keeps its spelling, so a document that never picks a Standard composer is unchanged. +#[test] +fn all_four_composers_round_trip() { + use vectorcraft_doc::{TextKind, TextObject}; + let one = |c: Composer| { + let mut d = Document::new(200.0, 200.0); + let mut t = TextObject::point(vectorcraft_geom::Point::ZERO, "ક\u{ACD}ક", Default::default()); + t.para.composer = c; + t.kind = TextKind::Point; + let id = d.alloc_id(); + d.insert(None, usize::MAX, Node::new(id, NodeKind::Text(Box::new(t)))).unwrap(); + d + }; + for (c, written) in [ + (Composer::SingleLine, Some("singleLine")), + (Composer::EveryLine, None), + (Composer::StandardSingleLine, Some("standardSingleLine")), + (Composer::StandardEveryLine, Some("standardEveryLine")), + ] { + let bytes = save(&one(c), false); + let text = String::from_utf8_lossy(&bytes); + match written { + Some(w) => assert!(text.contains(&format!("\"composer\":\"{w}\"")), "{c:?}"), + None => assert!(!text.contains("\"composer\""), "{c:?}"), + } + let back = load(&bytes).unwrap(); + let mut got = None; + back.walk(|n| { + if let NodeKind::Text(t) = &n.kind { + got = Some(t.para.composer); + } + }); + assert_eq!(got, Some(c)); + } +} + /// A document as the first version wrote it (format name `drawcraft`, anchors as maps). const V1_FILE: &str = r#"{"format":"drawcraft","version":1,"generator":"DrawCraft 0.1.0","document":{"version":1,"title":"Old","artboards":[{"id":1,"name":"Artboard 1","rect":{"x0":0.0,"y0":0.0,"x1":100.0,"y1":80.0}}], "layers":[{"id":1,"name":"Layer 1","visible":true,"locked":false,"opacity":1.0,"kind":{"type":"layer","children":[ diff --git a/crates/geom/src/anchors.rs b/crates/geom/src/anchors.rs new file mode 100644 index 0000000000..57b8081686 --- /dev/null +++ b/crates/geom/src/anchors.rs @@ -0,0 +1,790 @@ +//! The anchors of a subpath, held in shared chunks. +//! +//! [`Anchors`] keeps its anchors in chunks of at most [`CHUNK`] anchors, each behind an `Arc`. +//! Copying the list copies the table of chunks and shares the chunks themselves; changing an +//! anchor copies only the chunk that holds it when another copy still shares that chunk. An undo +//! step that keeps the version of a path before a one-anchor edit then keeps one chunk of its +//! own, however many anchors the path has. Inserting or removing an anchor copies the chunk it is +//! in and rebuilds the table, which has one entry per chunk. +//! +//! The list reads and writes as one flat sequence of anchors, as a `Vec` does. + +use std::borrow::Cow; +use std::fmt; +use std::ops::{Index, IndexMut, RangeBounds}; +use std::sync::Arc; + +use serde::{Deserialize, Serialize}; + +use crate::path::Anchor; + +/// An [`Anchors`] list of the anchors given, as `vec!` makes a `Vec`. +#[macro_export] +macro_rules! anchors { + ($($t:tt)*) => { + $crate::Anchors::from(vec![$($t)*]) + }; +} + +/// Most anchors one chunk holds. +pub const CHUNK: usize = 256; + +/// The anchors of a subpath: a sequence with the reads of a slice and the edits of a `Vec`, whose +/// copies share the chunks they have not changed. +#[derive(Clone, Default)] +pub struct Anchors { + /// The chunks in order, none of them empty. + chunks: Vec>>, + /// Empty while every chunk but the last holds [`CHUNK`] anchors (anchor `i` is then in chunk + /// `i / CHUNK`). Otherwise `ends[c]` is the number of anchors in chunks `0..=c`. + ends: Vec, + /// The number of anchors. + len: usize, +} + +impl Anchors { + /// An empty list. + pub const fn new() -> Self { + Self { chunks: Vec::new(), ends: Vec::new(), len: 0 } + } + + /// The number of anchors. + pub fn len(&self) -> usize { + self.len + } + + /// Whether the list has no anchors. + pub fn is_empty(&self) -> bool { + self.len == 0 + } + + /// The chunk that holds anchor `i` and its place in that chunk. For `i` at or past the end the + /// chunk or the place is out of range. + fn locate(&self, i: usize) -> (usize, usize) { + if self.ends.is_empty() { + (i / CHUNK, i % CHUNK) + } else { + let c = self.ends.partition_point(|&e| e <= i); + let start = c.checked_sub(1).and_then(|p| self.ends.get(p)).copied().unwrap_or(0); + (c, i.saturating_sub(start)) + } + } + + /// Anchor `i`, or `None` past the end. + pub fn get(&self, i: usize) -> Option<&Anchor> { + if i >= self.len { + return None; + } + let (c, o) = self.locate(i); + self.chunks.get(c)?.get(o) + } + + /// Anchor `i` to change, or `None` past the end. Copies the chunk that holds it when another + /// list shares that chunk. + pub fn get_mut(&mut self, i: usize) -> Option<&mut Anchor> { + if i >= self.len { + return None; + } + let (c, o) = self.locate(i); + Arc::make_mut(self.chunks.get_mut(c)?).get_mut(o) + } + + /// The first anchor. + pub fn first(&self) -> Option<&Anchor> { + self.chunks.first()?.first() + } + + /// The last anchor. + pub fn last(&self) -> Option<&Anchor> { + self.chunks.last()?.last() + } + + /// The first anchor to change. + pub fn first_mut(&mut self) -> Option<&mut Anchor> { + Arc::make_mut(self.chunks.first_mut()?).first_mut() + } + + /// The last anchor to change. + pub fn last_mut(&mut self) -> Option<&mut Anchor> { + Arc::make_mut(self.chunks.last_mut()?).last_mut() + } + + /// The anchors in order. + pub fn iter(&self) -> Iter<'_> { + let (front, back): (&[Anchor], &[Anchor]) = (&[], &[]); + Iter { chunks: self.chunks.iter(), front: front.iter(), back: back.iter(), left: self.len } + } + + /// The anchors in order, to change. Each chunk is copied, when another list shares it, as the + /// iterator reaches it. + pub fn iter_mut(&mut self) -> IterMut<'_> { + let chunk: fn(&mut Arc>) -> std::slice::IterMut<'_, Anchor> = |c| Arc::make_mut(c).iter_mut(); + self.chunks.iter_mut().flat_map(chunk) + } + + /// The anchors as one slice: borrowed when they are in one chunk, copied otherwise. + pub fn contiguous(&self) -> Cow<'_, [Anchor]> { + match self.chunks.as_slice() { + [] => Cow::Borrowed(&[]), + [one] => Cow::Borrowed(one.as_slice()), + _ => Cow::Owned(self.to_vec()), + } + } + + /// The anchors in `range` copied into a `Vec`, or `None` when the range is out of bounds or + /// starts after it ends (as `slice::get` with a range). + pub fn get_range(&self, range: impl RangeBounds) -> Option> { + use std::ops::Bound; + let start = match range.start_bound() { + Bound::Included(&s) => s, + Bound::Excluded(&s) => s.checked_add(1)?, + Bound::Unbounded => 0, + }; + let end = match range.end_bound() { + Bound::Included(&e) => e.checked_add(1)?, + Bound::Excluded(&e) => e, + Bound::Unbounded => self.len, + }; + (start <= end && end <= self.len).then(|| self.iter().skip(start).take(end - start).copied().collect()) + } + + /// The anchors copied into a `Vec`. + pub fn to_vec(&self) -> Vec { + let mut v = Vec::with_capacity(self.len); + for c in &self.chunks { + v.extend_from_slice(c); + } + v + } + + /// The anchors as a `Vec`, without a copy when they are in one chunk no other list shares. + pub fn into_vec(mut self) -> Vec { + if self.chunks.len() == 1 + && let Some(one) = self.chunks.pop() + { + return Arc::try_unwrap(one).unwrap_or_else(|shared| (*shared).clone()); + } + self.to_vec() + } + + /// Change the anchors as a `Vec` (for edits that move many of them, such as reversing). + pub fn with_vec(&mut self, f: impl FnOnce(&mut Vec) -> R) -> R { + let mut v = std::mem::take(self).into_vec(); + let r = f(&mut v); + *self = Self::from(v); + r + } + + /// Rebuild `ends` and `len` after the chunks changed, dropping empty chunks. + fn reindex(&mut self) { + self.chunks.retain(|c| !c.is_empty()); + self.len = self.chunks.iter().map(|c| c.len()).sum(); + let n = self.chunks.len(); + let uniform = self.chunks.iter().enumerate().all(|(k, c)| if k + 1 == n { c.len() <= CHUNK } else { c.len() == CHUNK }); + self.ends.clear(); + if !uniform { + let mut total = 0; + self.ends.extend(self.chunks.iter().map(|c| { + total += c.len(); + total + })); + } + } + + /// Add `a` at the end. + pub fn push(&mut self, a: Anchor) { + match self.chunks.last_mut() { + Some(last) if last.len() < CHUNK => Arc::make_mut(last).push(a), + _ => { + self.chunks.push(Arc::new(vec![a])); + if !self.ends.is_empty() { + self.ends.push(self.len); + } + } + } + self.len += 1; + if let Some(end) = self.ends.last_mut() { + *end = self.len; + } + } + + /// Remove the last anchor. + pub fn pop(&mut self) -> Option { + let last = self.chunks.last_mut()?; + let a = Arc::make_mut(last).pop(); + if last.is_empty() { + self.chunks.pop(); + self.ends.pop(); + } + self.len = self.len.saturating_sub(1); + if let Some(end) = self.ends.last_mut() { + *end = self.len; + } + a + } + + /// Insert `a` before anchor `i`, or at the end when `i` is the length or more. + pub fn insert(&mut self, i: usize, a: Anchor) { + if i >= self.len { + self.push(a); + return; + } + let (c, o) = self.locate(i); + let Some(chunk) = self.chunks.get_mut(c) else { return }; + let chunk = Arc::make_mut(chunk); + chunk.insert(o.min(chunk.len()), a); + if chunk.len() > CHUNK { + let tail = chunk.split_off(chunk.len() / 2); + self.chunks.insert(c + 1, Arc::new(tail)); + } + self.reindex(); + } + + /// Remove anchor `i`, or `None` past the end. + pub fn try_remove(&mut self, i: usize) -> Option { + if i >= self.len { + return None; + } + let (c, o) = self.locate(i); + let chunk = Arc::make_mut(self.chunks.get_mut(c)?); + let a = (o < chunk.len()).then(|| chunk.remove(o)); + // A chunk left small joins the next one when the two fit in one chunk. + if chunk.len() < CHUNK / 4 + && let Some(next) = self.chunks.get(c + 1) + && self.chunks.get(c).map_or(0, |c| c.len()) + next.len() <= CHUNK + { + let next = self.chunks.remove(c + 1); + if let Some(chunk) = self.chunks.get_mut(c) { + Arc::make_mut(chunk).extend_from_slice(&next); + } + } + self.reindex(); + a + } + + /// Remove anchor `i`. Panics past the end, as `Vec::remove` does. + pub fn remove(&mut self, i: usize) -> Anchor { + match self.try_remove(i) { + Some(a) => a, + None => { + let none: &[Anchor] = &[]; + none[i] + } + } + } + + /// Keep the first `n` anchors. + pub fn truncate(&mut self, n: usize) { + if n >= self.len { + return; + } + let (c, o) = self.locate(n); + self.chunks.truncate(c + 1); + if let Some(last) = self.chunks.last_mut() { + Arc::make_mut(last).truncate(o); + } + self.reindex(); + } + + /// Remove every anchor. + pub fn clear(&mut self) { + *self = Self::new(); + } + + /// Add the anchors of `s` at the end. + pub fn extend_from_slice(&mut self, s: &[Anchor]) { + self.extend(s.iter().copied()); + } + + /// Keep the anchors for which `f` is true. + pub fn retain(&mut self, f: impl FnMut(&Anchor) -> bool) { + self.with_vec(|v| v.retain(f)); + } + + /// Keep the anchors for which `f` is true, letting `f` change them. + pub fn retain_mut(&mut self, f: impl FnMut(&mut Anchor) -> bool) { + self.with_vec(|v| v.retain_mut(f)); + } + + /// Reverse the order of the anchors. + pub fn reverse(&mut self) { + self.with_vec(|v| v.reverse()); + } + + /// Rotate the anchors `k` places towards the start. + pub fn rotate_left(&mut self, k: usize) { + self.with_vec(|v| v.rotate_left(k)); + } + + /// Rotate the anchors `k` places towards the end. + pub fn rotate_right(&mut self, k: usize) { + self.with_vec(|v| v.rotate_right(k)); + } + + /// Remove the anchors in `range` and return them. + pub fn drain(&mut self, range: impl RangeBounds) -> std::vec::IntoIter { + self.with_vec(|v| v.drain(range).collect::>()).into_iter() + } + + /// Replace the anchors in `range` with those of `with`, and return the anchors replaced. + pub fn splice(&mut self, range: impl RangeBounds, with: impl IntoIterator) -> std::vec::IntoIter { + self.with_vec(|v| v.splice(range, with).collect::>()).into_iter() + } + + /// The pairs of anchors in the same place in `self` and `other`, with that place, in order. + /// When the two are chunked alike, the chunks they share in the same place are skipped (their + /// anchors are the same); otherwise every pair is visited. Stops at the end of the shorter list. + pub fn pairs_not_shared<'a>(&'a self, other: &'a Self) -> impl Iterator + 'a { + let alike = self.len == other.len && self.chunks.len() == other.chunks.len() && self.ends == other.ends; + let chunked = alike.then(|| { + let starts = self.chunks.iter().scan(0, |start, c| { + let at = *start; + *start += c.len(); + Some(at) + }); + starts + .zip(self.chunks.iter().zip(&other.chunks)) + .filter(|(_, (a, b))| !Arc::ptr_eq(a, b)) + .flat_map(|(at, (a, b))| a.iter().zip(b.iter()).enumerate().map(move |(o, (x, y))| (at + o, x, y))) + }); + let flat = (!alike).then(|| self.iter().zip(other.iter()).enumerate().map(|(i, (a, b))| (i, a, b))); + chunked.into_iter().flatten().chain(flat.into_iter().flatten()) + } + + /// Each chunk's address and capacity (in anchors): two lists hold a chunk in common when they + /// give the same address. For memory estimates. + pub fn chunk_allocations(&self) -> impl Iterator + '_ { + self.chunks.iter().map(|c| (Arc::as_ptr(c) as usize, c.capacity())) + } + + /// The bytes the list's own tables hold on the heap (the chunk table and the running totals), + /// without the chunks. + pub fn table_bytes(&self) -> usize { + self.chunks.capacity() * size_of::>>() + self.ends.capacity() * size_of::() + } +} + +/// [`Anchors::iter_mut`]'s iterator. +pub type IterMut<'a> = std::iter::FlatMap< + std::slice::IterMut<'a, Arc>>, + std::slice::IterMut<'a, Anchor>, + fn(&mut Arc>) -> std::slice::IterMut<'_, Anchor>, +>; + +/// [`Anchors::iter`]'s iterator. +#[derive(Clone)] +pub struct Iter<'a> { + /// The chunks neither end has reached. + chunks: std::slice::Iter<'a, Arc>>, + /// What is left of the chunk the front is in. + front: std::slice::Iter<'a, Anchor>, + /// What is left of the chunk the back is in. + back: std::slice::Iter<'a, Anchor>, + /// The anchors left. + left: usize, +} + +impl<'a> Iterator for Iter<'a> { + type Item = &'a Anchor; + + fn next(&mut self) -> Option<&'a Anchor> { + loop { + if let Some(a) = self.front.next() { + self.left -= 1; + return Some(a); + } + match self.chunks.next() { + Some(c) => self.front = c.iter(), + None => { + let a = self.back.next()?; + self.left -= 1; + return Some(a); + } + } + } + } + + fn size_hint(&self) -> (usize, Option) { + (self.left, Some(self.left)) + } + + fn nth(&mut self, mut n: usize) -> Option<&'a Anchor> { + // Whole chunks are skipped without visiting their anchors. + loop { + let f = self.front.len(); + if n < f { + self.left -= n + 1; + return self.front.nth(n); + } + n -= f; + self.left -= f; + self.front = Default::default(); + match self.chunks.as_slice().first() { + Some(c) if c.len() <= n => { + n -= c.len(); + self.left -= c.len(); + self.chunks.next(); + } + Some(_) => { + if let Some(c) = self.chunks.next() { + self.front = c.iter(); + } + } + None => { + let b = self.back.len(); + if n < b { + self.left -= n + 1; + return self.back.nth(n); + } + self.left -= b; + self.back = Default::default(); + return None; + } + } + } + } + + fn count(self) -> usize { + self.left + } + + fn last(mut self) -> Option<&'a Anchor> { + self.next_back() + } +} + +impl<'a> DoubleEndedIterator for Iter<'a> { + fn next_back(&mut self) -> Option<&'a Anchor> { + loop { + if let Some(a) = self.back.next_back() { + self.left -= 1; + return Some(a); + } + match self.chunks.next_back() { + Some(c) => self.back = c.iter(), + None => { + let a = self.front.next_back()?; + self.left -= 1; + return Some(a); + } + } + } + } +} + +impl ExactSizeIterator for Iter<'_> {} + +impl std::iter::FusedIterator for Iter<'_> {} + +impl Index for Anchors { + type Output = Anchor; + + /// Anchor `i`. Panics past the end, as indexing a slice does. + fn index(&self, i: usize) -> &Anchor { + let (c, o) = self.locate(i); + &self.chunks[c][o] + } +} + +impl IndexMut for Anchors { + /// Anchor `i` to change ([`Anchors::get_mut`]). Panics past the end, as indexing a slice does. + fn index_mut(&mut self, i: usize) -> &mut Anchor { + let (c, o) = self.locate(i); + &mut Arc::make_mut(&mut self.chunks[c])[o] + } +} + +impl From> for Anchors { + fn from(v: Vec) -> Self { + if v.is_empty() { + return Self::new(); + } + let len = v.len(); + let chunks = if len <= CHUNK { vec![Arc::new(v)] } else { v.chunks(CHUNK).map(|c| Arc::new(c.to_vec())).collect() }; + Self { chunks, ends: Vec::new(), len } + } +} + +impl From<&[Anchor]> for Anchors { + fn from(s: &[Anchor]) -> Self { + Self::from(s.to_vec()) + } +} + +impl From<[Anchor; N]> for Anchors { + fn from(s: [Anchor; N]) -> Self { + Self::from(Vec::from(s)) + } +} + +impl From for Vec { + fn from(a: Anchors) -> Self { + a.into_vec() + } +} + +impl FromIterator for Anchors { + fn from_iter>(it: I) -> Self { + Self::from(it.into_iter().collect::>()) + } +} + +impl Extend for Anchors { + fn extend>(&mut self, it: I) { + for a in it { + self.push(a); + } + } +} + +impl<'a> Extend<&'a Anchor> for Anchors { + fn extend>(&mut self, it: I) { + self.extend(it.into_iter().copied()); + } +} + +impl<'a> IntoIterator for &'a Anchors { + type Item = &'a Anchor; + type IntoIter = Iter<'a>; + + fn into_iter(self) -> Iter<'a> { + self.iter() + } +} + +impl<'a> IntoIterator for &'a mut Anchors { + type Item = &'a mut Anchor; + type IntoIter = IterMut<'a>; + + fn into_iter(self) -> IterMut<'a> { + self.iter_mut() + } +} + +impl IntoIterator for Anchors { + type Item = Anchor; + type IntoIter = std::vec::IntoIter; + + fn into_iter(self) -> std::vec::IntoIter { + self.into_vec().into_iter() + } +} + +impl PartialEq for Anchors { + fn eq(&self, other: &Self) -> bool { + self.len == other.len && self.iter().eq(other.iter()) + } +} + +impl PartialEq<[Anchor]> for Anchors { + fn eq(&self, other: &[Anchor]) -> bool { + self.len == other.len() && self.iter().eq(other.iter()) + } +} + +impl PartialEq<&[Anchor]> for Anchors { + fn eq(&self, other: &&[Anchor]) -> bool { + *self == **other + } +} + +impl PartialEq> for Anchors { + fn eq(&self, other: &Vec) -> bool { + *self == **other + } +} + +impl PartialEq<[Anchor; N]> for Anchors { + fn eq(&self, other: &[Anchor; N]) -> bool { + *self == other[..] + } +} + +impl PartialEq for [Anchor] { + fn eq(&self, other: &Anchors) -> bool { + *other == *self + } +} + +impl PartialEq for Vec { + fn eq(&self, other: &Anchors) -> bool { + *other == **self + } +} + +impl fmt::Debug for Anchors { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list().entries(self.iter()).finish() + } +} + +impl Serialize for Anchors { + fn serialize(&self, s: S) -> Result { + s.collect_seq(self.iter()) + } +} + +impl<'de> Deserialize<'de> for Anchors { + fn deserialize>(d: D) -> Result { + Vec::::deserialize(d).map(Self::from) + } +} + +#[cfg(test)] +mod tests { + use kurbo::Point; + + use super::*; + + fn line(n: usize) -> Vec { + (0..n).map(|i| Anchor::corner(Point::new(i as f64, (i % 7) as f64))).collect() + } + + /// Chunks of `a` that `b` does not hold, with their capacity in anchors. + fn own_chunks(a: &Anchors, b: &Anchors) -> Vec { + let theirs: Vec = b.chunk_allocations().map(|(id, _)| id).collect(); + a.chunk_allocations().filter(|(id, _)| !theirs.contains(id)).map(|(_, cap)| cap).collect() + } + + #[test] + fn editing_one_anchor_copies_one_chunk_whatever_the_length() { + for n in [10_000, 200_000] { + let before = Anchors::from(line(n)); + let mut after = before.clone(); + after[n / 2].p = Point::new(-1.0, -1.0); + if let Some(a) = after.get_mut(n / 2 + 1) { + a.h_out = Point::new(-2.0, -2.0); + } + let copied = own_chunks(&after, &before); + assert_eq!(copied.len(), 1, "{n} anchors: one chunk copied"); + assert!(copied.iter().all(|&cap| cap <= CHUNK), "{n} anchors: {copied:?}"); + assert_eq!(own_chunks(&before, &after).len(), 1, "{n} anchors: the old version keeps one chunk of its own"); + // The old version is as it was; the new one differs only at the two anchors. + assert_eq!(before, line(n)); + let mut expected = line(n); + expected[n / 2].p = Point::new(-1.0, -1.0); + expected[n / 2 + 1].h_out = Point::new(-2.0, -2.0); + assert_eq!(after, expected); + } + } + + #[test] + fn inserting_and_removing_copy_only_the_chunk_touched() { + let n = 200_000; + let before = Anchors::from(line(n)); + let mut after = before.clone(); + let extra = Anchor::corner(Point::new(0.5, 0.5)); + after.insert(n / 2, extra); + assert!(own_chunks(&after, &before).len() <= 2, "the chunk split in two"); + assert_eq!(after.len(), n + 1); + assert_eq!(after[n / 2], extra); + assert_eq!(after[n / 2 + 1], line(n)[n / 2]); + assert_eq!(after.remove(n / 2), extra); + assert_eq!(after, line(n)); + assert!(own_chunks(&after, &before).len() <= 2); + assert_eq!(before, line(n)); + } + + #[test] + fn acts_as_a_vec_through_edits() { + // A run of edits applied to an `Anchors` and to a `Vec` leaves the two the same, across + // chunk splits, joins and the uniform and non-uniform layouts. + let mut v = line(700); + let mut a = Anchors::from(v.clone()); + let mut seed = 7u64; + let mut next = |m: usize| { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (seed >> 33) as usize % m.max(1) + }; + for step in 0..3000 { + let x = Anchor::corner(Point::new(step as f64, 0.25)); + match next(8) { + 0 | 1 => { + let i = next(v.len() + 1); + v.insert(i, x); + a.insert(i, x); + } + 2 | 3 if !v.is_empty() => { + let i = next(v.len()); + assert_eq!(v.remove(i), a.remove(i)); + } + 4 => { + v.push(x); + a.push(x); + } + 5 => assert_eq!(v.pop(), a.pop()), + 6 if !v.is_empty() => { + let i = next(v.len()); + v[i].h_in = x.p; + a[i].h_in = x.p; + } + _ => { + let keep = v.len().saturating_sub(next(3)); + v.truncate(keep); + a.truncate(keep); + } + } + assert_eq!(a.len(), v.len(), "step {step}"); + if step % 50 == 0 { + assert_eq!(a, v, "step {step}"); + for i in 0..v.len() { + assert_eq!(a.get(i), v.get(i), "step {step}, anchor {i}"); + } + } + } + assert_eq!(a, v); + assert_eq!(a.iter().rev().copied().collect::>(), v.iter().rev().copied().collect::>()); + assert_eq!(a.get(v.len()), None); + } + + #[test] + fn iterators_skip_and_count_as_a_slice_does() { + let v = line(1000); + let a = Anchors::from(v.clone()); + for skip in [0, 1, 255, 256, 257, 999, 1000, 1001] { + assert_eq!(a.iter().nth(skip), v.get(skip), "nth {skip}"); + assert_eq!(a.iter().skip(skip).count(), v.iter().skip(skip).count(), "skip {skip}"); + assert_eq!(a.iter().skip(skip).len(), v.iter().skip(skip).len(), "len after {skip}"); + } + let mut both = a.iter(); + let mut vs = v.iter(); + for k in 0..1000 { + let (x, y) = if k % 3 == 0 { (both.next_back(), vs.next_back()) } else { (both.next(), vs.next()) }; + assert_eq!(x, y, "step {k}"); + assert_eq!(both.len(), vs.len()); + } + assert_eq!(both.next(), None); + assert_eq!(a.iter().last(), v.last()); + let mut m = a.clone(); + m.iter_mut().for_each(|x| x.p.x += 1.0); + assert!(m.iter().zip(&v).all(|(x, y)| x.p.x == y.p.x + 1.0)); + assert_eq!(a, v, "changing a copy left the original alone"); + } + + #[test] + fn reads_and_writes_as_a_flat_list() { + let v = line(600); + let a = Anchors::from(v.clone()); + assert_eq!(serde_json::to_string(&a).ok(), serde_json::to_string(&v).ok()); + let back: Anchors = serde_json::from_str(&serde_json::to_string(&v).unwrap_or_default()).unwrap_or_default(); + assert_eq!(back, v); + assert_eq!(format!("{a:?}"), format!("{v:?}")); + } + + #[test] + fn pairs_not_shared_skip_the_chunks_both_hold() { + let before = Anchors::from(line(10_000)); + let mut after = before.clone(); + after[5000].p = Point::new(-3.0, 0.0); + let pairs: Vec<_> = before.pairs_not_shared(&after).collect(); + assert!(pairs.len() <= CHUNK); + let changed: Vec = pairs.iter().filter(|(_, a, b)| a != b).map(|(i, _, _)| *i).collect(); + assert_eq!(changed, [5000]); + assert!(pairs.iter().all(|&(i, a, b)| *a == before[i] && *b == after[i])); + // Chunked differently: every pair. + let mut moved = before.clone(); + moved.insert(0, Anchor::corner(Point::ZERO)); + moved.remove(0); + assert_eq!(before.pairs_not_shared(&moved).count(), 10_000); + } +} diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index 12a7492e7f..7d3e3f0f4b 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -7,6 +7,7 @@ //! Coordinates are document points (1/72 in), y pointing down. #![forbid(unsafe_code)] +pub mod anchors; pub mod arc; pub mod bez; pub mod corners; @@ -17,6 +18,7 @@ pub mod recognize; pub mod shapes; pub mod snap; +pub use anchors::Anchors; pub use arc::ArcPath; pub use kurbo; pub use kurbo::{Affine, BezPath, CubicBez, Line, ParamCurve, PathEl, PathSeg, Point, Rect, Shape, Size, Vec2}; diff --git a/crates/geom/src/path.rs b/crates/geom/src/path.rs index bef18334ae..c5343171ef 100644 --- a/crates/geom/src/path.rs +++ b/crates/geom/src/path.rs @@ -6,6 +6,7 @@ use kurbo::{Affine, BezPath, CubicBez, ParamCurve, ParamCurveExtrema, ParamCurve use serde::{Deserialize, Serialize}; use crate::EPS; +use crate::anchors::Anchors; /// Fill rule for paths and compound paths. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] @@ -224,15 +225,15 @@ pub fn with_anchor_budget(max: usize, f: impl FnOnce() -> T) -> T { } /// A subpath's anchors read within [`with_anchor_budget`]. -fn anchors_within<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { +fn anchors_within<'de, D: serde::Deserializer<'de>>(d: D) -> Result { struct V; impl<'de> serde::de::Visitor<'de> for V { - type Value = Vec; + type Value = Anchors; fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { f.write_str("a list of anchors") } - fn visit_seq>(self, mut a: A) -> Result, A::Error> { - let mut out = Vec::new(); + fn visit_seq>(self, mut a: A) -> Result { + let mut out = Anchors::new(); while let Some(anchor) = a.next_element::()? { if let Some(left) = ANCHORS_LEFT.get() { let left = left @@ -262,13 +263,17 @@ pub fn measured_segments() -> u64 { #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct SubPath { #[serde(deserialize_with = "anchors_within")] - pub anchors: Vec, + pub anchors: Anchors, #[serde(default)] pub closed: bool, } impl SubPath { pub fn new(anchors: Vec, closed: bool) -> Self { + Self { anchors: anchors.into(), closed } + } + /// A subpath of `anchors`, sharing their chunks. + pub fn of(anchors: Anchors, closed: bool) -> Self { Self { anchors, closed } } /// Polyline from points. @@ -442,7 +447,7 @@ impl SubPath { let (run, cuts): (Vec, BTreeSet) = if self.closed { (self.anchors.iter().cycle().skip(first).take(n + 1).copied().collect(), cuts.map(|c| (c + n - first) % n).chain([n]).collect()) } else { - (self.anchors.clone(), cuts.collect()) + (self.anchors.to_vec(), cuts.collect()) }; let mut pieces = vec![]; let mut cur: Vec = vec![]; @@ -511,11 +516,11 @@ impl PathData { { subpaths.push(sp); } - cur = Some(SubPath { anchors: vec![Anchor::corner(p)], closed: false }); + cur = Some(SubPath::new(vec![Anchor::corner(p)], false)); last = p; } PathEl::LineTo(p) => { - let sp = cur.get_or_insert_with(|| SubPath { anchors: vec![Anchor::corner(last)], closed: false }); + let sp = cur.get_or_insert_with(|| SubPath::new(vec![Anchor::corner(last)], false)); sp.anchors.push(Anchor::corner(p)); last = p; } @@ -752,7 +757,7 @@ pub fn segment_bounds(seg: PathSeg) -> Rect { } fn push_curve(cur: &mut Option, last: Point, c1: Point, c2: Point, p: Point) { - let sp = cur.get_or_insert_with(|| SubPath { anchors: vec![Anchor::corner(last)], closed: false }); + let sp = cur.get_or_insert_with(|| SubPath::new(vec![Anchor::corner(last)], false)); if let Some(a) = sp.anchors.last_mut() { a.h_out = c1; } diff --git a/crates/geom/src/shapes.rs b/crates/geom/src/shapes.rs index 3baf55f147..0ae8a75190 100644 --- a/crates/geom/src/shapes.rs +++ b/crates/geom/src/shapes.rs @@ -814,7 +814,7 @@ mod tests { for decay in [20.0, 30.0, 50.0, 80.0, 95.0] { for clockwise in [true, false] { let p = spiral(center, 100.0, decay, 8, clockwise); - let anchors = &p.subpaths[0].anchors; + let anchors = &p.subpaths[0].anchors.to_vec(); let k = (decay / 100.0_f64).ln() / TAU; let mut worst = 0.0_f64; for pair in anchors.windows(2) { diff --git a/crates/mcp/src/tests/gradient.rs b/crates/mcp/src/tests/gradient.rs index 302926ed1c..e5d8925006 100644 --- a/crates/mcp/src/tests/gradient.rs +++ b/crates/mcp/src/tests/gradient.rs @@ -44,10 +44,15 @@ fn gradient_annotator_end_to_end() { let r = ok(&mut h, "press_key", json!({"key": "Delete"})); assert_eq!(r["handledBy"], "tool", "{r}"); assert_eq!(offsets(&gradient(&h)), vec![0.0, 100.0]); - // The end handle changes only the end. + // The end handle changes only the length: the end stays on the bar's line. let end = json!({"events": [{"kind": "down", "x": 200, "y": 150}, {"kind": "drag", "x": 230, "y": 120}, {"kind": "up", "x": 230, "y": 120}]}); ok(&mut h, "pointer_gesture", end); let g = gradient(&h).geom.unwrap(); + assert_eq!((g.start, g.end), (Point::new(100.0, 150.0), Point::new(230.0, 150.0))); + // Alt-dragged, it changes the length and the angle together. + let end = json!({"mods": {"alt": true}, "events": [{"kind": "down", "x": 230, "y": 150}, {"kind": "drag", "x": 230, "y": 120}, {"kind": "up", "x": 230, "y": 120}]}); + ok(&mut h, "pointer_gesture", end); + let g = gradient(&h).geom.unwrap(); assert_eq!((g.start, g.end), (Point::new(100.0, 150.0), Point::new(230.0, 120.0))); // Double-clicking a stop asks for its popover. let dbl = ok(&mut h, "pointer_gesture", json!({"events": [{"kind": "doubleclick", "x": 100, "y": 160}]})); diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index a797cfba04..6e8626666a 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -167,6 +167,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} toggle a red underline under the words of the document's type its dictionaries don't know (text.spelling.check lists them), kept up to date as the type changes; type with effects isn't underlined → whether Auto Spell Check is on", ), + ( + "ui.checkSpelling", + "Check Spelling…", + "Cmd+I", + "{} open the Check Spelling dialog to walk through unrecognized words with suggestions, ignore, change and dictionary options", + ), ("shortcuts.set", "Set Keyboard Shortcut", "", "{id: command id or tool:, shortcut: \"Cmd+Shift+K\" | \"\" (none) | null (default), force?}"), ("shortcuts.list", "List Keyboard Shortcuts", "", "{query?} → [{id, label, group, shortcut, default, overridden}]"), ("shortcuts.conflicts", "Keyboard Shortcut Conflicts", "", "{} → [{shortcut, ids}]"), @@ -392,7 +398,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "type.lineComposer", "Toggle Line Composer", "Cmd+Alt+Shift+C", - "{} the selected type's paragraphs (or those the Type tool's selection touches) use the Single-line Composer when they all use the Every-line Composer, else the Every-line Composer (text.setFormat {composer}) → \"singleLine\" | \"everyLine\"", + "{} the selected type's paragraphs (or those the Type tool's selection touches) use the Single-line Composer when they all use the Every-line Composer, else the Every-line Composer; paragraphs that all use a Standard composer keep it, any other mix takes the Middle Eastern & South Asian one (text.setFormat {composer}) → \"singleLine\" | \"everyLine\" | \"standardSingleLine\" | \"standardEveryLine\"", ), ( "type.hyphenate", @@ -432,6 +438,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ ), ("view.nextArtboard", "Next Artboard", "", "{} the navigator's Next Artboard button: view.goToArtboard {index: \"next\"} → {index}"), ("view.lastArtboard", "Last Artboard", "", "{} the navigator's Last Artboard button: view.goToArtboard {index: \"last\"} → {index}"), + ( + "view.statusBarShow", + "Status Bar Show", + "", + "{show: \"artboardName\" | \"currentTool\" | \"dateTime\" | \"undos\" | \"colorProfile\"} the status bar's Show menu (a click on its info field): the field shows the name of the artboard the navigator shows, the tool in use (the default), the date and time (local on the desktop, UTC on the web), the active document's undo and redo step counts, or the profile its colors use (the one assigned for its color mode, else, or when that one is not available, that mode's working space); kept with the UI state; any other value is an error → show", + ), ("view.edges", "Hide Edges", "Cmd+H", "{}"), ("view.artboards", "Hide Artboards", "Cmd+Shift+H", "{}"), ( @@ -644,6 +656,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{panel, collapsed?: bool} minimize the group holding a panel to its tabs (in a floating window, the window to its title bar), or restore it, as a double-click on a tab or the drag bar does; the same as window.panel.minimize {panel, minimized}. Without `collapsed` it toggles. Returns {panel, collapsed, layout}", ), + ( + "window.panel.cycleOptions", + "Cycle Display Sizes", + "", + "{panel} show a panel at its next display size, as the double triangle at the right end of its tab strip does: the sizes are the states of its panel menu's Show/Hide Options (Transparency: options and thumbnails, thumbnails alone, neither), largest first, and the smallest goes back to the largest; Align, Attributes, Character, Color, Flattener Preview, Gradient, Info, Paragraph, Stroke, Transform and Transparency have them. An unknown panel or one without display sizes is an error and changes nothing. Returns {panel, size: 0 for the largest, sizes: how many it has}", + ), ( "window.panel.float", "Float Panel", @@ -1615,7 +1633,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.actionSet.load", "Load Actions…", "", - "{path? | data?: the file's text} read an action set file (.vcactions) at path, else a picked one, and add its set after the Actions panel's sets; a set named like one in the panel gets the next free number (Print 2), and the other sets stay. Files of another version, over 8 MiB, with more than 1,000 actions or with an action of more than 10,000 steps are refused, and so is any set, .aia ones too, that Save Actions… would write larger than 8 MiB (a file with less white space, or a name that gets a number); the panel menu's Load Actions… (disabled where there is no open dialog, the web) → {set: index, name, actions: n}. An action set another app saved as text (.aia, starting /version; read with actionSet.read) comes in with its actions. A step with a label and no recorded values comes in when exactly one menu command has that label (in English or the interface language, any case, no final …), and that command is directly in a top menu, can be recorded in actions, is what its menu bar item runs with no values and opens no dialog (never a submenu's item, a file or document command, Paste, Undo, Redo or an add-on's command), with no params and excluded from playback when it is off in the file; the other steps, every step with no label and every step recorded with values (a recorded menu item too) among them, are left out → {set, name, actions, skipped: [{action, step: its label, else its name}] (the first 1,000), leftOut: n}, and the status bar says how many were left out; a set with no name takes the file's name, else Actions; a file actionSet.read marks truncated is refused, and text that starts /version and isn't an action set gives \"not an action set file\"", + "{path? | data?: the file's text} read an action set file (.vcactions) at path, else a picked one, and add its set after the Actions panel's sets; a set named like one in the panel gets the next free number (Print 2), and the other sets stay. Files of another version, over 8 MiB, with more than 1,000 actions or with an action of more than 10,000 steps are refused, and so is any set, .aia ones too, that Save Actions… would write larger than 8 MiB (a file with less white space, or a name that gets a number); the panel menu's Load Actions… (disabled where there is no open dialog, the web) → {set: index, name, actions: n}. An action set another app saved as text (.aia, starting /version; read with actionSet.read) comes in with its actions. A step with a label and no recorded values comes in when exactly one menu command has that label (in English or the interface language, any case, no final …), and that command is directly in a top menu, can be recorded in actions, is what its menu bar item runs with no values and opens no dialog (never a submenu's item, a file or document command, Paste, Undo, Redo or an add-on's command), with no params and excluded from playback when it is off in the file. A Set Selection step (found by its internal name, whatever its label) comes in as select.byNote {note, caseSensitive, wholeWord} when it has exactly three recorded values: text (ustring, UTF-8; 1 to 1,024 bytes once trimmed), word and case (boolean, 0 or 1); with any other values it is left out. The other steps, every other step with no label and every other step recorded with values (a recorded menu item too) among them, are left out → {set, name, actions, skipped: [{action, step: its label, else its name}] (the first 1,000), leftOut: n}, and the status bar says how many were left out; a set with no name takes the file's name, else Actions; a file actionSet.read marks truncated is refused, and text that starts /version and isn't an action set gives \"not an action set file\"", ), ( "ui.actionSet.delete", diff --git a/crates/pathops/src/addons/cleanup.rs b/crates/pathops/src/addons/cleanup.rs index 75cf45b583..b0c000be9a 100644 --- a/crates/pathops/src/addons/cleanup.rs +++ b/crates/pathops/src/addons/cleanup.rs @@ -104,7 +104,7 @@ pub fn merge_duplicate_anchors(sp: &mut SubPath, distance: f64) -> usize { { *f = Anchor::with_handles(f.p, moved(f.p, last.p, last.h_in), f.h_out); } - sp.anchors = out; + sp.anchors = out.into(); before - sp.anchors.len() } diff --git a/crates/pathops/src/addons/keep_shape.rs b/crates/pathops/src/addons/keep_shape.rs index a3721f8f22..12ba4b21df 100644 --- a/crates/pathops/src/addons/keep_shape.rs +++ b/crates/pathops/src/addons/keep_shape.rs @@ -27,7 +27,7 @@ const ACCURACY: f64 = 1e-6; fn merged(prev: &Anchor, cur: &Anchor, next: &Anchor) -> CubicBez { let mut run = SubPath::new(vec![*prev, *cur, *next], false); remove_anchor(&mut run, 1); - match run.anchors.as_slice() { + match &*run.anchors.contiguous() { [a, b] => CubicBez::new(prev.p, a.h_out, b.h_in, next.p), _ => CubicBez::new(prev.p, prev.h_out, next.h_in, next.p), } diff --git a/crates/pathops/src/addons/pathtools/shared_edge.rs b/crates/pathops/src/addons/pathtools/shared_edge.rs index 6b4e8bfb1e..5acee01def 100644 --- a/crates/pathops/src/addons/pathtools/shared_edge.rs +++ b/crates/pathops/src/addons/pathtools/shared_edge.rs @@ -377,7 +377,7 @@ fn splice(sp: &SubPath, st: Stretch, chain: &[CubicBez]) -> Option { let own = backward(chain); let chain = if st.reversed { own.as_slice() } else { chain }; let (first, last) = (chain.first()?, chain.last()?); - let mut out = sp.anchors.clone(); + let mut out = sp.anchors.to_vec(); let start = st.start.min(out.len()); out.rotate_left(start); let settle = |a: &mut Anchor| { diff --git a/crates/pathops/src/edit.rs b/crates/pathops/src/edit.rs index 87b4cb000d..3ad1281eb2 100644 --- a/crates/pathops/src/edit.rs +++ b/crates/pathops/src/edit.rs @@ -5,7 +5,7 @@ use std::collections::{BTreeMap, BTreeSet}; use kurbo::{CubicBez, Line, ParamCurve, ParamCurveNearest, PathSeg, Point, Rect, Vec2}; use vectorcraft_geom::path::measured_arclen; -use vectorcraft_geom::{Anchor, AnchorKind, PathData, SubPath}; +use vectorcraft_geom::{Anchor, AnchorKind, Anchors, PathData, SubPath}; use crate::boolean::{Seg, segs_to_subpath}; use crate::fit::{end_tangent, fit_cubics, fit_single, fit_single_from, is_straight, largest_second_difference, sample, start_tangent, unit}; @@ -1091,7 +1091,7 @@ pub fn remove_anchor(sp: &mut SubPath, index: usize) -> bool { /// Refit the facing handles of anchors `pi` and `ni` so one cubic follows the two segments that /// meet at anchor `index` between them ([`remove_anchor`]). Two straight segments are left as /// they are, and so are the handles when the fit is not finite. -fn refit_across(anchors: &mut [Anchor], pi: usize, index: usize, ni: usize) { +fn refit_across(anchors: &mut Anchors, pi: usize, index: usize, ni: usize) { let (Some(&a), Some(&b), Some(&c)) = (anchors.get(pi), anchors.get(index), anchors.get(ni)) else { return }; let line = |a: &Anchor, b: &Anchor| !a.has_out() && !b.has_in(); if line(&a, &b) && line(&b, &c) { @@ -1233,7 +1233,7 @@ pub fn add_anchor_points(path: &PathData) -> PathData { v[2 * seg + 1] = Anchor { p: l.p3, h_in: l.p2, h_out: r.p1, kind: AnchorKind::Smooth }; } } - sp.anchors = v; + sp.anchors = v.into(); } out } diff --git a/crates/pathops/tests/it/ops.rs b/crates/pathops/tests/it/ops.rs index 0b5b0bbf25..a31c9af2e4 100644 --- a/crates/pathops/tests/it/ops.rs +++ b/crates/pathops/tests/it/ops.rs @@ -769,7 +769,7 @@ fn add_anchor_points_doubles() { /// The one-pass build gives what inserting a midpoint into each segment (last first) gives, open or closed. #[test] fn add_anchor_points_matches_inserting() { - let open = PathData::single(SubPath::new(circle(0.0, 0.0, 10.0).subpaths[0].anchors.clone(), false)); + let open = PathData::single(SubPath::new(circle(0.0, 0.0, 10.0).subpaths[0].anchors.to_vec(), false)); for src in [circle(0.0, 0.0, 10.0), rect(0.0, 0.0, 10.0, 10.0), open] { let mut want = src.clone(); for sp in &mut want.subpaths { diff --git a/crates/pdf/Cargo.toml b/crates/pdf/Cargo.toml index d4394dfefa..d59243eb75 100644 --- a/crates/pdf/Cargo.toml +++ b/crates/pdf/Cargo.toml @@ -33,8 +33,8 @@ smallvec = "1" siphasher = "1" weezl = "0.2" serde = { workspace = true } -# The XMP packet that File Info is read from (file_info.rs); the version usvg already uses. -roxmltree = "0.21" +# The XMP packet that File Info is read from (file_info.rs). +craft-xml = { workspace = true } # PDF security (encrypt.rs): pure Rust, MIT OR Apache-2.0, builds for wasm. aes = "0.8" md-5 = { version = "0.10", default-features = false } diff --git a/crates/pdf/src/export/exporter.rs b/crates/pdf/src/export/exporter.rs index f102e0a0ab..a116f8bc2a 100644 --- a/crates/pdf/src/export/exporter.rs +++ b/crates/pdf/src/export/exporter.rs @@ -18,6 +18,10 @@ pub(super) const MAX_PATTERN_DEPTH: u32 = 4; /// (`vectorcraft-engine`'s `rasterfx::undecoded_warning`). pub(super) const UNDECODED: &str = "an image couldn't be decoded and is missing from the picture"; +/// The warning for an image left out because its colors can't be converted as the Output +/// settings ask, although it could be written in its own colors. +pub(super) const UNCONVERTED: &str = "an image couldn't be converted to the Output destination and is missing from the picture"; + /// The warning for an image whose placement cannot be written. pub(super) const UNWRITABLE_IMAGE: &str = "an image couldn't be written and is missing from the picture"; diff --git a/crates/pdf/src/export/images.rs b/crates/pdf/src/export/images.rs index 04a3a811f3..f280f02ee5 100644 --- a/crates/pdf/src/export/images.rs +++ b/crates/pdf/src/export/images.rs @@ -1,8 +1,10 @@ -use super::exporter::{UNDECODED, UNWRITABLE_IMAGE, q, writable, xf}; +use super::exporter::{UNCONVERTED, UNDECODED, UNWRITABLE_IMAGE, q, writable, xf}; use super::{Arc, BlendMode, Color, Exporter, Image, Node, NodeKind, Paint, Rect, Size, Surface, cmyk, krilla}; use krilla::color::device_n::{Colorant, DeviceNSpace, Process}; use krilla::image::{BitsPerComponent, CustomImage, ImageColorspace}; +use crate::images::SourceProfiles; + /// The byte count of a repeated color channel, within [`vectorcraft_doc::MAX_RASTER_ALLOC`]. fn tinted_color_len(samples: usize, pixels: usize) -> Option { let bytes = samples.checked_mul(pixels)?; @@ -124,7 +126,9 @@ impl Exporter<'_> { /// settings say ([`crate::images::recode`], [`crate::images::recode_cmyk`] for CMYK images); /// cached by key (and size when images are resampled). With `interpolate` (and the export's /// own setting), viewers may smooth it. `None`, with [`UNDECODED`] among the warnings, for an - /// image that is missing, can't be decoded or is in [`Self::left_out`]. + /// image that is missing, can't be decoded or is in [`Self::left_out`]; `None`, with + /// [`UNCONVERTED`], for one whose colors the Output settings convert but that can only be + /// written in its own ([`crate::images::Recoded::unconverted`]). fn load_image(&mut self, im: &vectorcraft_doc::ImageObject, size: (f64, f64), interpolate: bool) -> Option { let key = im.key.as_str(); let c = self.compression; @@ -138,8 +142,9 @@ impl Exporter<'_> { } let doc = self.doc; let out = self.out.clone(); - let profiles = !out.standard.cmyk_only(); + let profiles = out.source_profiles(); let to_srgb = out.image_srgb_intent().map(|intent| crate::images::ToSrgb { intent, sixteen_bit: self.sixteen_bit }); + let mut unconverted = false; 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 { @@ -147,10 +152,16 @@ impl Exporter<'_> { } let r = if cmyk_image { let icc = out.cmyk_image_icc(blob); - crate::images::recode_cmyk(blob, size, c, interpolate, out.cmyk_pixels(), None, icc.as_deref()) + crate::images::recode_cmyk(blob, size, c, interpolate, out.cmyk_pixels(), None, out.cmyk_tag(icc.as_deref())) } else { crate::images::recode(&blob.bytes, size, c, interpolate, out.pixels(), profiles, to_srgb) }; + if r.unconverted { + // The source image would be written in its own colors: it is left out, with a + // warning that names the conversion when it could have been written. + unconverted = embed(blob, interpolate, self.sixteen_bit, profiles).is_some(); + return None; + } let img = r.image.or_else(|| embed(blob, interpolate, self.sixteen_bit, profiles)); // An image left out gets the warning below instead. for w in [r.warning, r.note].into_iter().flatten().filter(|_| img.is_some()) { @@ -158,7 +169,9 @@ impl Exporter<'_> { } img }); - if img.is_none() { + if unconverted { + self.warn(UNCONVERTED); + } else if img.is_none() { self.warn(UNDECODED); } self.images.insert(cache, img.clone()); @@ -197,7 +210,8 @@ impl Exporter<'_> { 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 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()); + let tag = self.out.cmyk_tag(icc.as_deref()); + let r = crate::images::recode_cmyk(blob, size, self.compression, interpolate, self.out.cmyk_pixels(), Some(alpha), tag); if let (Some(w), Some(_)) = (r.warning, &r.image) { self.warn(w); } @@ -320,13 +334,15 @@ pub(super) fn png_8_bit(bytes: &[u8]) -> Option> { } /// Image `blob` as it is: PNG, JPEG, GIF and WebP through the PDF writer (JPEG data unchanged), -/// 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 { +/// other formats (a TIFF) decoded with their 16-bit samples and, when `profiles` keeps it (not in +/// PDF/X-1a), the ICC profile they carry ([`crate::images::decoded_image`]). When `profiles` +/// doesn't keep it, 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. With [`SourceProfiles::Remove`], an image that +/// carries any profile is written without it, a JPEG without its `ICC_PROFILE` segments (decoded +/// when those can't be taken out). 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: SourceProfiles) -> 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(); @@ -334,16 +350,25 @@ pub(super) fn embed(blob: &vectorcraft_doc::ImageBlob, interpolate: bool, sixtee 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 + // The PDF writer keeps a gray or RGB image's ICC profile: unless `profiles` keeps it, 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)), + // 16..20 even in a profile cut short, as the PDF writer reads it. With `Remove`, a JPEG's + // `ICC_PROFILE` segments are taken out also when they don't make up a profile the decoder reads. + let remove = profiles == SourceProfiles::Remove; + let jpeg = matches!(blob.mime.as_str(), "image/jpeg" | "image/jpg"); + let unkept = crate::images::source_icc(&bytes).is_some_and(|icc| match icc.get(16..20) { + _ if remove => true, + Some(space @ (b"GRAY" | b"RGB ")) => { + profiles != SourceProfiles::Keep || <[u8; 4]>::try_from(space).is_ok_and(|s| !crate::images::valid_icc(&icc, s)) + } _ => false, }); + let strip = (remove && jpeg) || unkept; let direct = match blob.mime.as_str() { - "image/jpeg" | "image/jpg" if strip => Image::from_jpeg_with_icc(bytes.clone().into(), None, interpolate).ok(), + "image/jpeg" | "image/jpg" if strip => { + crate::images::jpeg_data(&bytes, remove).and_then(|data| Image::from_jpeg_with_icc(data.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(), @@ -371,7 +396,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, true).is_none()); + assert!(super::embed(&ImageBlob::png(png), false, true, super::SourceProfiles::Keep).is_none()); } #[test] diff --git a/crates/pdf/src/export/nodes.rs b/crates/pdf/src/export/nodes.rs index 403cbc5431..71b65e65d0 100644 --- a/crates/pdf/src/export/nodes.rs +++ b/crates/pdf/src/export/nodes.rs @@ -859,7 +859,9 @@ impl Exporter<'_> { /// Opens the blend mode and the transparency group `n` is drawn with (`container` when it is a /// group or layer whose children `knockout` each other). Returns how many were opened, and /// whether the children are to be drawn in an isolated group of their own: the knockout group of -/// an unclipped group's elements is its isolated group too. +/// an unclipped group's elements is its isolated group too. An opaque knockout group in Normal +/// mode that does not isolate opens no group: its elements are drawn on the art below it, in a +/// knockout group without `/I` when there are several. fn transparency(s: &mut Surface, n: &Node, page: Rect, container: bool, knockout: bool) -> (usize, bool) { let mut pushes = 0; if n.blend != BlendMode::Normal { @@ -876,6 +878,8 @@ fn transparency(s: &mut Surface, n: &Node, page: Rect, container: bool, knockout } else if n.opacity < 1.0 { s.push_opacity(norm(n.opacity)); pushes += 1; + } else if knockout && !n.isolate && n.blend == BlendMode::Normal { + // A knockout group that does not isolate: its elements start from the art below it. } else if knockout && matches!(n.kind, NodeKind::Layer { clip: false, .. } | NodeKind::Group { clip: false, .. }) { isolated_children = true; } else { diff --git a/crates/pdf/src/export/text.rs b/crates/pdf/src/export/text.rs index c6946f5416..ea29167f1b 100644 --- a/crates/pdf/src/export/text.rs +++ b/crates/pdf/src/export/text.rs @@ -326,7 +326,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, !self.out.standard.cmyk_only()); + let img = embed(&image.blob, self.interpolate, self.sixteen_bit, self.out.source_profiles()); self.images.insert(cache, img.clone()); img } diff --git a/crates/pdf/src/file_info.rs b/crates/pdf/src/file_info.rs index 1cb0a45273..930f7e4013 100644 --- a/crates/pdf/src/file_info.rs +++ b/crates/pdf/src/file_info.rs @@ -5,7 +5,7 @@ use craft_pdf::syntax::Pdf; use craft_pdf::syntax::object::{DateTime, Dict, Stream}; -use roxmltree::Node; +use craft_xml::{Canonical, Doctype, El, Limits, Names, Options}; use crate::import_scan::text_string; @@ -15,12 +15,13 @@ const MAX_XMP: usize = 8 << 20; const MAX_NESTING: usize = 256; const RDF: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; -const XML: &str = "http://www.w3.org/XML/1998/namespace"; pub(crate) const DC: &str = "http://purl.org/dc/elements/1.1/"; const XMP: &str = "http://ns.adobe.com/xap/1.0/"; // brand-ok: the XMP namespace the files use pub(crate) const XMP_RIGHTS: &str = "http://ns.adobe.com/xap/1.0/rights/"; // brand-ok: the XMP namespace the files use const PDF: &str = "http://ns.adobe.com/pdf/1.3/"; // brand-ok: the XMP namespace the files use +const XMP_NAMESPACES: Canonical<'static> = Canonical::new(&[("rdf", RDF), ("dc", DC), ("xmp", XMP), ("xmpRights", XMP_RIGHTS), ("pdf", PDF)]); + /// The File Info fields a PDF gives, each `None` when the file gives none (or only blank text). #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct FileInfo { @@ -73,39 +74,39 @@ fn packet(pdf: &Pdf) -> Option> { } /// The File Info fields of an XMP packet; `None` when it isn't XML in UTF-8 or UTF-16, or when its -/// elements nest more than [`MAX_NESTING`] deep. +/// [`xmp`] of `packet`; `None` when it isn't XML in UTF-8 or UTF-16, or when its elements nest +/// more than [`MAX_NESTING`] deep. fn xmp(packet: &[u8]) -> Option { let text = xml_text(packet)?; - // roxmltree parses nested elements recursively. - if nesting(&text) > MAX_NESTING { - return None; + let opts = Options { + names: Names::Canonical(&XMP_NAMESPACES), + doctype: Doctype::Reject, + limits: Limits { max_depth: MAX_NESTING, ..Limits::DEFAULT }, + ..Options::default() } - let xml = roxmltree::Document::parse(&text).ok()?; + .strict(); + let root = opts.parse(text.as_bytes()).ok()?; // The resource's own descriptions: those right under `rdf:RDF`, not the ones inside a value. - let descriptions: Vec> = xml - .descendants() - .filter(|n| n.has_tag_name((RDF, "RDF"))) - .flat_map(|rdf| rdf.children()) - .filter(|n| n.has_tag_name((RDF, "Description"))) - .collect(); - let get = |ns: &str, name: &str| property(&descriptions, ns, name); - let first = |ns: &str, name: &str| get(ns, name).into_iter().next(); - let creators = get(DC, "creator"); - let subjects = get(DC, "subject"); + let descriptions: Vec<&El> = + std::iter::once(&root).chain(root.descendants()).filter(|n| n.is("rdf:RDF")).flat_map(|rdf| rdf.children("rdf:Description")).collect(); + let get = |name: &str| property(&descriptions, name); + let first = |name: &str| get(name).into_iter().next(); + let creators = get("dc:creator"); + let subjects = get("dc:subject"); Some(FileInfo { - title: first(DC, "title"), + title: first("dc:title"), author: (!creators.is_empty()).then(|| creators.join(", ")), - description: first(DC, "description"), - keywords: if subjects.is_empty() { first(PDF, "Keywords").map(|k| split(&k)).filter(|k| !k.is_empty()) } else { Some(subjects) }, - copyright_notice: first(DC, "rights"), - copyright_url: first(XMP_RIGHTS, "WebStatement"), - copyrighted: first(XMP_RIGHTS, "Marked").and_then(|m| match m.to_ascii_lowercase().as_str() { + description: first("dc:description"), + keywords: if subjects.is_empty() { first("pdf:Keywords").map(|k| split(&k)).filter(|k| !k.is_empty()) } else { Some(subjects) }, + copyright_notice: first("dc:rights"), + copyright_url: first("xmpRights:WebStatement"), + copyrighted: first("xmpRights:Marked").and_then(|m| match m.to_ascii_lowercase().as_str() { "true" => Some(true), "false" => Some(false), _ => None, }), - created: first(XMP, "CreateDate").and_then(|d| xmp_date(&d)), - modified: first(XMP, "ModifyDate").and_then(|d| xmp_date(&d)), + created: first("xmp:CreateDate").and_then(|d| xmp_date(&d)), + modified: first("xmp:ModifyDate").and_then(|d| xmp_date(&d)), }) } @@ -123,58 +124,14 @@ fn xml_text(b: &[u8]) -> Option { } } -/// How deep the elements of `xml` nest: start tags less end tags, at most, outside comments, -/// CDATA sections, processing instructions, declarations and quoted attribute values. -fn nesting(xml: &str) -> usize { - let b = xml.as_bytes(); - let (mut depth, mut most, mut i) = (0usize, 0usize, 0usize); - // The index just past the first `end` at or after `from` (the end of the text if none). - let past = |from: usize, end: &[u8]| { - b.get(from..).and_then(|rest| rest.windows(end.len()).position(|w| w == end)).map_or(b.len(), |at| from + at + end.len()) - }; - while let Some(at) = b.get(i..).and_then(|rest| rest.iter().position(|&c| c == b'<')) { - let start = i + at; - let rest = b.get(start..).unwrap_or_default(); - if rest.starts_with(b""); - } else if rest.starts_with(b""); - } else if rest.starts_with(b""); - } else if rest.starts_with(b""); - } else { - // A start tag: up to its `>` outside quotes; `/>` closes it at once. - let mut j = start + 1; - let mut quote = None; - while let Some(&c) = b.get(j) { - match (quote, c) { - (None, b'"' | b'\'') => quote = Some(c), - (Some(q), _) if c == q => quote = None, - (None, b'>') => break, - _ => {} - } - j += 1; - } - if b.get(j.saturating_sub(1)) != Some(&b'/') { - depth += 1; - most = most.max(depth); - } - i = j + 1; - } - } - most -} - -/// The values of property `ns` `name` on the first of `descriptions` that gives it: an attribute +/// The values of property `name` on the first of `descriptions` that gives it: an attribute /// of the `rdf:Description`, or a property element's items ([`items`]), blank ones left out. -fn property(descriptions: &[Node<'_, '_>], ns: &str, name: &str) -> Vec { +fn property(descriptions: &[&El], name: &str) -> Vec { for d in descriptions { - if let Some(v) = d.attribute((ns, name)).map(str::trim).filter(|v| !v.is_empty()) { + if let Some(v) = d.attr(name).map(str::trim).filter(|v| !v.is_empty()) { return vec![v.to_string()]; } - let found = d.children().filter(|c| c.has_tag_name((ns, name))).map(items).find(|v| !v.is_empty()); + let found = d.children(name).map(items).find(|v| !v.is_empty()); if let Some(v) = found { return v; } @@ -185,14 +142,10 @@ fn property(descriptions: &[Node<'_, '_>], ns: &str, name: &str) -> Vec /// The items of property element `p`: the `rdf:li` of its `rdf:Seq`, `rdf:Bag` or `rdf:Alt` (the /// `x-default` language item first), else its own value ([`value_of`]); trimmed, blank ones left /// out. -fn items(p: Node<'_, '_>) -> Vec { - let array = p.children().find(|c| ["Seq", "Bag", "Alt"].into_iter().any(|t| c.has_tag_name((RDF, t)))); +fn items(p: &El) -> Vec { + let array = p.elements().find(|c| matches!(c.name.as_str(), "rdf:Seq" | "rdf:Bag" | "rdf:Alt")); let mut values: Vec<(bool, String)> = match array { - Some(a) => a - .children() - .filter(|c| c.has_tag_name((RDF, "li"))) - .map(|li| (li.attribute((XML, "lang")).is_some_and(|l| l.eq_ignore_ascii_case("x-default")), value_of(li))) - .collect(), + Some(a) => a.children("rdf:li").map(|li| (li.attr("xml:lang").is_some_and(|l| l.eq_ignore_ascii_case("x-default")), value_of(li))).collect(), None => vec![(false, value_of(p))], }; // A stable sort: the `x-default` item first, the others in their order. @@ -203,19 +156,19 @@ fn items(p: Node<'_, '_>) -> Vec { /// The value of element `n`: the URI of its `rdf:resource` attribute (how RDF writes a URI value); /// for a qualified value, its `rdf:value` (an attribute or an element, on `n` or on an /// `rdf:Description` inside it), without the qualifiers; else the text inside it. -fn value_of(mut n: Node<'_, '_>) -> String { +fn value_of(mut n: &El) -> String { // Each step goes to an element inside `n`, so the loop ends. loop { - if let Some(uri) = n.attribute((RDF, "resource")) { + if let Some(uri) = n.attr("rdf:resource") { return uri.to_string(); } - let holder = n.children().find(|c| c.has_tag_name((RDF, "Description"))).unwrap_or(n); - if let Some(v) = holder.attribute((RDF, "value")) { + let holder = n.child("rdf:Description").unwrap_or(n); + if let Some(v) = holder.attr("rdf:value") { return v.to_string(); } - match holder.children().find(|c| c.has_tag_name((RDF, "value"))) { + match holder.child("rdf:value") { Some(v) => n = v, - None => return n.descendants().filter(|d| d.is_text()).filter_map(|d| d.text()).collect(), + None => return n.deep_text(), } } } diff --git a/crates/pdf/src/images.rs b/crates/pdf/src/images.rs index ac1d77f372..872080bfb5 100644 --- a/crates/pdf/src/images.rs +++ b/crates/pdf/src/images.rs @@ -20,6 +20,9 @@ //! 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. +//! With Don't Include Profiles set ([`SourceProfiles::Remove`], [`CmykTag::Removed`]), a JPEG +//! embedded as it is loses its `ICC_PROFILE` segments, its other segments and compressed samples +//! unchanged. use std::io::Cursor; use std::sync::Arc; @@ -152,10 +155,10 @@ pub(crate) fn from_decoded(img: DynamicImage, icc: Option>, interpolate: } /// 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) +/// `profiles` keeps it ([`SourceProfiles::Keep`]), 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: SourceProfiles) -> Option { + from_decoded(decoded(bytes)?, (profiles == SourceProfiles::Keep).then(|| source_icc(bytes)).flatten(), interpolate, sixteen_bit) } /// Are all of the RGBA pixels `rgba` grey? @@ -317,6 +320,9 @@ pub(crate) struct Recoded { /// Set when the image's colors are converted to the destination without its ICC profile, /// which can't be read. pub note: Option<&'static str>, + /// Set when the colors were to be converted but the image couldn't be decoded within the + /// allowance or written with them: the source image, kept as it is, would be in its own colors. + pub unconverted: bool, } /// How [`recode`] converts a gray or RGB image that carries an ICC profile to sRGB (Convert to @@ -330,6 +336,47 @@ pub(crate) struct ToSrgb { pub sixteen_bit: bool, } +/// What happens to the ICC profile a gray or RGB image carries +/// ([`crate::output::ColorOut::source_profiles`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum SourceProfiles { + /// The image keeps a well-formed gray or RGB profile ([`valid_icc`]). + Keep, + /// The image is untagged; a JPEG embedded as it is keeps its data unchanged (PDF/X-1a). + Untag, + /// The image is untagged and a JPEG embedded as it is loses its `ICC_PROFILE` segments, its + /// other segments and compressed samples unchanged (Don't Include Profiles). + Remove, +} + +/// The CMYK profile [`recode_cmyk`] tags a CMYK image that keeps its numbers with. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum CmykTag<'a> { + /// This profile ([`cmyk_icc`]). + Profile(&'a [u8]), + /// None; a JPEG embedded as it is keeps its data unchanged. + Untagged, + /// None, and a JPEG embedded as it is loses its `ICC_PROFILE` segments, its other segments + /// and compressed samples unchanged (Don't Include Profiles). + Removed, +} + +impl<'a> CmykTag<'a> { + /// The profile the image is tagged with. + fn icc(self) -> Option<&'a [u8]> { + match self { + Self::Profile(icc) => Some(icc), + Self::Untagged | Self::Removed => None, + } + } +} + +/// JPEG `bytes` as they are embedded: without their `ICC_PROFILE` segments with `remove` +/// ([`vectorcraft_doc::cmyk::jpeg_without_icc`]). `None` when those can't be taken out. +pub(crate) fn jpeg_data(bytes: &[u8], remove: bool) -> Option> { + if remove { vectorcraft_doc::cmyk::jpeg_without_icc(bytes) } else { Some(bytes.to_vec()) } +} + /// The ICC profile image `bytes` carries ([`source_icc`]), when it is a well-formed profile of /// colour space `space` (`GRAY` or `RGB `, [`valid_icc`]): `None` without one, `Some(None)` when /// the CMS can't read it. @@ -474,21 +521,23 @@ fn resample_channels(img: DynamicImage, r: &Rule, (w, h): (u32, u32)) -> Dynamic /// 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). 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); -/// with `to_srgb`, pixels in a gray or RGB profile other than sRGB are converted from it to sRGB +/// they carry when `profiles` keeps it ([`SourceProfiles::Keep`]); with `to_srgb`, pixels in a gray or RGB profile other than sRGB are converted from it to sRGB /// instead ([`ToSrgb`]), and colour ones then by `convert`; grey ones that `convert` leaves as /// they are keep their profile. `interpolate` lets viewers smooth it. An image that can't be -/// decoded is kept as it is, with a warning when its pixels were to be converted to sRGB. +/// decoded is kept as it is, with a warning when its pixels were to be converted to sRGB. When +/// `convert` was to convert its colors, it is [`Recoded::unconverted`] if its header can't be read +/// (it may be in color) or its pixels are beyond the decode allowance; a color image whose pixel +/// data can't be read is not. pub(crate) fn recode( bytes: &[u8], size: (f64, f64), c: &CompressionSettings, interpolate: bool, convert: Option<&Pixels>, - profiles: bool, + profiles: SourceProfiles, to_srgb: Option, ) -> Recoded { - let keep = Recoded { image: None, warning: None, note: None }; + let keep = Recoded { image: None, warning: None, note: None, unconverted: convert.is_some() }; let Ok(reader) = ImageReader::new(Cursor::new(bytes)).with_guessed_format() else { return keep }; let jpeg = reader.format() == Some(ImageFormat::Jpeg); let Ok(mut decoder) = reader.into_decoder() else { return keep }; @@ -506,23 +555,25 @@ pub(crate) fn recode( note = Some(CONVERTED_AS_SRGB); None } - Some((None, _)) => return Recoded { image: None, warning: Some(UNCONVERTED), note: None }, + Some((None, _)) => return Recoded { image: None, warning: Some(UNCONVERTED), note: None, unconverted: false }, None => None, }; // Pixels that can't be decoded are kept as they are, with a warning when they were to be // converted. - let keep = if source.is_some() { Recoded { image: None, warning: Some(UNDECODED), note: None } } else { keep }; + let keep = if source.is_some() { Recoded { warning: Some(UNDECODED), ..keep } } else { keep }; // What the header declares is decoded within the image allowance, not whatever it asks for. + // Grey pixels aren't converted. if decoder.set_limits(limits()).is_err() { - return keep; + return Recoded { unconverted: convert.is_some() && !grey, ..keep }; } let (mut kind, pixels) = if grey { // Only the pixels tell monochrome images from greyscale ones: decoded unless both keep it. let (g, m) = (rule(c, Kind::Gray), rule(c, Kind::Mono)); if source.is_none() && kept(&g, dims, size, jpeg) && kept(&m, dims, size, jpeg) && g.instead == m.instead { - return Recoded { image: None, warning: g.instead, note: None }; + return Recoded { image: None, warning: g.instead, note: None, unconverted: false }; } - let Ok(img) = DynamicImage::from_decoder(decoder) else { return keep }; + // Grey pixels aren't converted. + let Ok(img) = DynamicImage::from_decoder(decoder) else { return Recoded { unconverted: false, ..keep } }; (if bilevel(&img) { Kind::Mono } else { Kind::Gray }, Some(img)) } else { (Kind::Color, None) @@ -530,9 +581,14 @@ pub(crate) fn recode( let mut rule = rule(c, kind); let convert = convert.filter(|_| kind == Kind::Color); if kept(&rule, dims, size, jpeg) && convert.is_none() && source.is_none() { - return Recoded { image: None, warning: rule.instead, note: None }; + return Recoded { image: None, warning: rule.instead, note: None, unconverted: false }; } - let Some(mut img) = pixels.or_else(|| decoded(bytes)) else { return keep }; + // Pixels that can't be read can't be written in their own colors either; ones beyond the + // allowance can. + let mut img = match pixels.map_or_else(|| decoded_within(bytes), Ok) { + Ok(img) => img, + Err(limited) => return Recoded { unconverted: limited && convert.is_some(), ..keep }, + }; if let Some((p, t)) = &source { let srgb = match into_srgb(img, p, t.intent) { Some(s) => Some(s), @@ -542,7 +598,7 @@ pub(crate) fn recode( note = Some(CONVERTED_AS_SRGB); None } - None => return Recoded { image: None, warning: Some(UNCONVERTED), note: None }, + None => return Recoded { image: None, warning: Some(UNCONVERTED), note: None, unconverted: false }, }; img = match srgb { Some((srgb, changed)) => { @@ -553,27 +609,34 @@ pub(crate) fn recode( // Written as it is only when nothing converts it further. let as_is = kept(&rule, dims, size, jpeg) && convert.is_none(); // A JPEG kept as JPEG whose samples the conversion leaves unchanged (an sRGB - // profile): its JPEG data, without the profile. - if !changed && as_is && jpeg { - let image = Image::from_jpeg_with_icc(bytes.to_vec().into(), None, interpolate).ok(); - return Recoded { image, warning: rule.instead, note: None }; + // profile): its JPEG data, without the profile (and, with `Remove`, without its + // segments: encoded again when those can't be taken out). + if !changed + && as_is + && jpeg + && let Some(data) = jpeg_data(bytes, profiles == SourceProfiles::Remove) + { + let image = Image::from_jpeg_with_icc(data.into(), None, interpolate).ok(); + return Recoded { image, warning: rule.instead, note: None, unconverted: false }; } // Not resampled and lossless: written at its own depth. if as_is && jpeg_quality(&rule, jpeg).is_none() { - return Recoded { image: from_decoded(srgb, None, interpolate, t.sixteen_bit), warning: rule.instead, note: None }; + let image = from_decoded(srgb, None, interpolate, t.sixteen_bit); + return Recoded { image, warning: rule.instead, note: None, unconverted: false }; } srgb } - None => { - let Some(img) = decoded(bytes) else { return keep }; - img - } + None => match decoded_within(bytes) { + Ok(img) => img, + Err(limited) => return Recoded { unconverted: limited && convert.is_some(), ..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() && source.is_none()).then(|| source_icc(bytes)).flatten().filter(|icc| valid_icc(icc, want)); + let keeps = profiles == SourceProfiles::Keep && convert.is_none() && source.is_none(); + let icc = keeps.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 { @@ -601,7 +664,8 @@ pub(crate) fn recode( 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, icc)); - Recoded { image, warning: rule.instead, note } + let unconverted = image.is_none() && convert.is_some(); + Recoded { image, warning: rule.instead, note, unconverted } } /// A colorized image's coverage (one sample a pixel, `w` × `h`, see @@ -630,8 +694,9 @@ 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. 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. +/// inks can't be read. When its numbers are kept, the image is tagged as `tag` says, and is +/// untagged without a profile; converted pixels are never tagged with it. +/// With `convert`, an image whose inks can't be read or written is [`Recoded::unconverted`]. pub(crate) fn recode_cmyk( blob: &ImageBlob, size: (f64, f64), @@ -639,29 +704,38 @@ pub(crate) fn recode_cmyk( interpolate: bool, convert: Option<&CmykPixels>, alpha: Option>, - icc: Option<&[u8]>, + tag: CmykTag<'_>, ) -> Recoded { let rule = rule(c, Kind::Color); let jpeg = jpeg_components(&blob.bytes).is_some(); - let icc = icc.filter(|_| convert.is_none()); + let icc = tag.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 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. + // The JPEG data as it is (without its `ICC_PROFILE` segments with `CmykTag::Removed`: its + // inks are encoded again when those can't be taken out), tagged with `icc` rather than + // with its own segments; one larger than [`MAX_EMBED_PIXELS`] is not written. + if let Some((w, h)) = dims.filter(|d| kept(&rule, *d, size, true)) + && let Some(data) = jpeg_data(&blob.bytes, tag == CmykTag::Removed) + { 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()) + .then(|| Image::from_jpeg_with_icc(data.into(), icc.map(|i| i.to_vec().into()), interpolate).ok()) .flatten(); - return Recoded { image, warning: rule.instead, note: None }; + return Recoded { image, warning: rule.instead, note: None, unconverted: false }; } } + // Inks that can't be read can't be converted: the image is not to be kept as it is. + let unconverted = Recoded { image: None, warning: None, note: None, unconverted: true }; let Some(inks) = blob.cmyk() else { - return Recoded { image: None, warning: Some(if jpeg { CMYK_KEPT } else { CMYK_RGB }), note: None }; + if convert.is_some() { + return unconverted; + } + return Recoded { image: None, warning: Some(if jpeg { CMYK_KEPT } else { CMYK_RGB }), note: None, unconverted: false }; }; 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, note: None }, + Err(_) if convert.is_some() => return unconverted, + Err(warning) => return Recoded { image: None, warning, note: None, unconverted: false }, }; let (samples, space) = match convert { Some(p) => p.convert(&inks), @@ -670,7 +744,8 @@ pub(crate) fn recode_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, icc)); let image = image.or_else(|| lossless(samples, alpha, space, width, height, interpolate, icc)); - Recoded { image, warning: rule.instead, note: None } + let unconverted = image.is_none() && convert.is_some(); + Recoded { image, warning: rule.instead, note: None, unconverted } } /// Ink amounts (four bytes a pixel) and their alpha (one byte a pixel), if any. @@ -715,9 +790,15 @@ fn limits() -> image::Limits { /// `bytes` decoded within [`limits`]: an image whose header asks for more is not decoded. fn decoded(bytes: &[u8]) -> Option { - let mut r = ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?; + decoded_within(bytes).ok() +} + +/// `bytes` decoded like [`decoded`]; on failure, whether the decoder stopped at [`limits`] +/// (`true`) rather than at data it can't read (`false`). +fn decoded_within(bytes: &[u8]) -> Result { + let mut r = ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(|_| false)?; r.limits(limits()); - r.decode().ok() + r.decode().map_err(|e| matches!(e, image::ImageError::Limits(_))) } /// The alpha an opacity mask whose art is greyscale image `blob` alone gives the image of diff --git a/crates/pdf/src/import/builder.rs b/crates/pdf/src/import/builder.rs index 0d50c58f31..c2650138b9 100644 --- a/crates/pdf/src/import/builder.rs +++ b/crates/pdf/src/import/builder.rs @@ -361,8 +361,9 @@ impl<'p> Builder<'p> { Some(MaskSpec::Mask(m)) => (opacity, Some(m.clone())), None => (opacity, None), }; - // Isolation only shows with blending inside; knockout with several objects. - let isolate = isolate && Node::children_blend(&children, &mut |c| c.blends_through()); + // Isolation only shows with blending or overprinting inside; knockout with several + // objects. + let isolate = isolate && (Node::children_blend(&children, &mut |c| c.blends_through()) || children_overprint(&children)); let knockout = knockout && children.len() > 1; let plain = opacity >= 0.999 && blend == BlendMode::Normal && mask.is_none() && !isolate && !knockout; if children.is_empty() { @@ -1183,3 +1184,16 @@ fn visual_glyph_text(text: String) -> String { let chars: Vec = text.chars().collect(); order.iter().filter_map(|&i| chars.get(i)).collect() } + +/// Whether a visible fill or stroke among `children` overprints, characters' too, directly or +/// through children that don't isolate. In an isolated group an overprinting object is drawn on +/// the group's empty backdrop, so it covers the inks of the art below the group that it does not +/// paint; without isolation it leaves them. +fn children_overprint(children: &[Arc]) -> bool { + children.iter().any(|c| { + c.visible + && (c.appearance.items.iter().any(|i| i.visible() && i.overprint()) + || matches!(&c.kind, NodeKind::Text(t) if t.runs.iter().any(|r| r.style.overprint_fill || r.style.overprint_stroke)) + || (!c.isolate && c.children().is_some_and(|ch| children_overprint(ch)))) + }) +} diff --git a/crates/pdf/src/import/entry.rs b/crates/pdf/src/import/entry.rs index 8503b4fb20..8f84b9a332 100644 --- a/crates/pdf/src/import/entry.rs +++ b/crates/pdf/src/import/entry.rs @@ -239,6 +239,14 @@ pub fn imports_of(bytes: &[u8]) -> usize { IMPORTS.lock().ok().and_then(|i| i.get(&(bytes.as_ptr() as usize)).copied()).unwrap_or(0) } +/// The widest bleed of `pages` on each side (`[top, bottom, left, right]`, see [`crate::pages::bleed`]). +fn widest_bleed<'p, 'd: 'p>(pages: impl Iterator>) -> [f64; 4] { + pages.fold([0.0; 4], |widest, page| { + let bleed = crate::pages::bleed(page); + std::array::from_fn(|i| widest[i].max(bleed[i])) + }) +} + /// [`read_with_reader_options`] of `original`, the PDF `bytes` read with `reader`. fn read_opened( bytes: &[u8], @@ -286,15 +294,17 @@ fn read_opened( let mut nesting = Nesting::new(); // The top-level groups in the order the pages mark them, bottom first. let (mut order, mut known) = (vec![], HashSet::new()); + // Artboards on the trim boxes have the bleed boxes round them as the document's bleed, so the + // art there shows and prints as bleed. + if opts.crop == CropTo::Trim { + doc.setup.bleed = widest_bleed(picked.iter().filter_map(|&n| pages.get(n))); + } + // The artboards are the gap apart plus the document's bleed on both sides, which export adds + // round every artboard, so no page's bleed reaches into the next artboard. + let [_, _, bleed_left, bleed_right] = doc.setup.bleed; + let spacing = opts.artboard_gap + bleed_left + bleed_right; for (i, &number) in picked.iter().enumerate() { let Some(page) = pages.get(number) else { continue }; - // Artboards on the trim boxes have the bleed boxes round them as the document's bleed - // (the widest of the pages' on each side), so the art there shows and prints as bleed. - if opts.crop == CropTo::Trim { - for (side, b) in doc.setup.bleed.iter_mut().zip(crate::pages::bleed(page)) { - *side = side.max(b); - } - } // The chosen box sits at (x, 0); the page draws round it. let (init, frame) = crate::pages::frame(page, opts.crop); let mut ab = Rect::new(x, 0.0, x + frame.width(), frame.height()); @@ -371,7 +381,7 @@ fn read_opened( right = right.max(art.x1); ab = art; } - x = right + opts.artboard_gap; + x = right + spacing; clear = right.max(art_right) + opts.artboard_gap; doc.artboards.push(Artboard { id: i as u32 + 1, diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index 8f9959c77f..0658624452 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -134,7 +134,8 @@ impl PdfOptions { pub struct ImportOptions { /// Import at most this many pages (of those picked); `None` = all of them. pub max_pages: Option, - /// Horizontal gap in points between the artboards created for consecutive pages. + /// Horizontal gap in points between the artboards created for consecutive pages (on trim + /// boxes, plus the document's bleed on both sides). pub artboard_gap: f64, /// 0-based pages to import, in this order; `None` = every page. pub pages: Option>, diff --git a/crates/pdf/src/output.rs b/crates/pdf/src/output.rs index 92381e1628..454e41c5ac 100644 --- a/crates/pdf/src/output.rs +++ b/crates/pdf/src/output.rs @@ -24,7 +24,11 @@ //! always tag them, whatever `profiles` says; PDF/X-1a never does, and always converts to a //! 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`]). +//! and PDF/X-4 unless `profiles` is `destination` ([`ColorOut::cmyk_image_icc`]). When +//! `profiles` isn't set, colors are written as with `none` and gray and RGB images keep the +//! profiles they carry (but in PDF/X-1a); when it is set to `none`, no image keeps its own +//! profile, a JPEG's `ICC_PROFILE` segments included, except in PDF/A, PDF/X-3 and PDF/X-4 +//! ([`ColorOut::source_profiles`]). //! - 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 @@ -70,6 +74,9 @@ pub(crate) struct ColorOut { /// CMYK images that keep their numbers are tagged with the CMYK profile they carry /// ([`Self::cmyk_image_icc`]). image_icc: bool, + /// Don't Include Profiles was set, in a file that doesn't tag every color: no image keeps its + /// own ICC profile, a JPEG's `ICC_PROFILE` segments included ([`Self::source_profiles`]). + no_profiles: 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 @@ -117,6 +124,7 @@ impl Default for ColorOut { dest: None, tagged: false, image_icc: false, + no_profiles: false, cmyk_profile, srgb_note: None, pixels: OnceLock::new(), @@ -246,9 +254,11 @@ impl ColorOut { } out.dest = Some(Dest { srgb: name == cms::SRGB, cms, model, keep, destination }); } - out.tagged = matches!(set.standard, Standard::PdfA2b | Standard::PdfX3 | Standard::PdfX4) + let profiles = set.output.profiles.unwrap_or_default(); + let tags_all = matches!(set.standard, Standard::PdfA2b | Standard::PdfX3 | Standard::PdfX4); + out.tagged = tags_all || (!set.standard.cmyk_only() - && match set.output.profiles { + && match profiles { ProfileInclusion::None => false, ProfileInclusion::All | ProfileInclusion::Destination => true, ProfileInclusion::TaggedSource => !doc.color_profiles.is_empty(), @@ -256,11 +266,14 @@ impl ColorOut { // 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 { + && match profiles { ProfileInclusion::All | ProfileInclusion::TaggedSource => true, - ProfileInclusion::None => matches!(set.standard, Standard::PdfA2b | Standard::PdfX3 | Standard::PdfX4), + ProfileInclusion::None => tags_all, ProfileInclusion::Destination => false, }; + // A set Don't Include Profiles leaves out every image's own profile, outside the files + // that tag every color. + out.no_profiles = set.output.profiles == Some(ProfileInclusion::None) && !tags_all; 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()), @@ -367,6 +380,33 @@ impl ColorOut { crate::images::cmyk_icc(blob) } + /// How CMYK image `blob` is tagged ([`crate::images::recode_cmyk`]): with the profile + /// [`Self::cmyk_image_icc`] gives (`icc`), else untagged, without a JPEG's own `ICC_PROFILE` + /// segments when Don't Include Profiles was set. + pub(crate) fn cmyk_tag<'a>(&self, icc: Option<&'a [u8]>) -> crate::images::CmykTag<'a> { + use crate::images::CmykTag; + match icc { + Some(icc) => CmykTag::Profile(icc), + None if self.no_profiles => CmykTag::Removed, + None => CmykTag::Untagged, + } + } + + /// What happens to the ICC profile a gray or RGB image carries ([`crate::images::recode`]): + /// left out with its JPEG segments when Don't Include Profiles was set (not in PDF/A, PDF/X-3 + /// and PDF/X-4), left out of the color space in PDF/X-1a, which allows no ICC-based color + /// spaces, and kept otherwise, also when the Profiles setting isn't set. + pub(crate) fn source_profiles(&self) -> crate::images::SourceProfiles { + use crate::images::SourceProfiles; + if self.no_profiles { + SourceProfiles::Remove + } else if self.standard.cmyk_only() { + SourceProfiles::Untag + } else { + SourceProfiles::Keep + } + } + /// 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> { diff --git a/crates/pdf/src/settings.rs b/crates/pdf/src/settings.rs index adaaa30c9c..c2f5487cbb 100644 --- a/crates/pdf/src/settings.rs +++ b/crates/pdf/src/settings.rs @@ -387,7 +387,12 @@ pub struct OutputSettings { /// Destination profile name (empty: the document's profile; [`DOCUMENT_CMYK`]: the CMYK /// profile in effect, whatever the document's colour mode). pub destination: String, - pub profiles: ProfileInclusion, + /// The Profile Inclusion setting; `None` (left out, `null` or `"default"`) when it isn't set: + /// colors are then written as with [`ProfileInclusion::None`], while gray and RGB images keep + /// the ICC profiles they carry. A set [`ProfileInclusion::None`] also leaves those out (see + /// [`crate::output`]). + #[serde(deserialize_with = "unset_or_choice")] + pub profiles: Option, /// PDF/X output intent profile name. pub output_intent: String, pub output_condition: String, @@ -397,6 +402,19 @@ pub struct OutputSettings { pub trapped: bool, } +/// The JSON id of a setting that isn't set ([`OutputSettings::profiles`]), as `null` is. +pub const UNSET_CHOICE: &str = "default"; + +/// A choice that may be left unset: `null` and [`UNSET_CHOICE`] are `None`, a choice's id is that +/// choice. +fn unset_or_choice<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(d: D) -> Result, D::Error> { + match Option::::deserialize(d)? { + None => Ok(None), + Some(id) if id == UNSET_CHOICE => Ok(None), + Some(id) => T::deserialize(serde::de::value::StringDeserializer::::new(id)).map(Some), + } +} + /// The Advanced section. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] diff --git a/crates/pdf/src/tests/blend.rs b/crates/pdf/src/tests/blend.rs index c55a0b7504..25948763d8 100644 --- a/crates/pdf/src/tests/blend.rs +++ b/crates/pdf/src/tests/blend.rs @@ -151,6 +151,114 @@ fn a_knockout_group_is_written_as_one_pdf_knockout_group() { } } +/// A knockout group with nothing blending inside is drawn in an isolated group (`/I true`) only +/// when the group isolates, clipped or not, with opaque or translucent elements, and reads back +/// knocking out. +#[test] +fn a_knockout_group_without_blending_inside_is_isolated_only_when_it_isolates() { + for clip in [false, true] { + for opacity in [0.5, 1.0] { + for isolate in [false, true] { + let mut d = knockout_squares(3, false, isolate); + let g = d.layers[0].children().unwrap()[1].id; + let mut squares: Vec<_> = d.node(g).unwrap().children().unwrap().to_vec(); + for s in &mut squares { + std::sync::Arc::make_mut(s).opacity = opacity; + } + if clip { + let c = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(10.0, 10.0, 190.0, 190.0)), + Appearance::basic(Paint::None, Paint::None, 0.0), + ); + squares.insert(0, std::sync::Arc::new(c)); + } + d.node_mut(g).unwrap().kind = vectorcraft_doc::NodeKind::Group { children: squares, clip }; + let case = format!("clip {clip}, opacity {opacity}, isolate {isolate}"); + let t = text(&d); + assert_eq!(t.matches("/Ktrue").count(), 1, "{case}"); + // Each translucent element is an isolated form with its opacity. + let elements = if opacity < 1.0 { 3 } else { 0 }; + assert_eq!(t.matches("/Itrue").count(), elements + usize::from(isolate), "{case}"); + let back = import(&export(&d, &PdfOptions::default()).unwrap()).unwrap_or_else(|e| panic!("{case}: {e}")); + let mut found = vec![]; + back.walk(|n| { + if n.knockout == vectorcraft_doc::Knockout::On { + found.push(n.isolate); + } + }); + assert_eq!(found, [false], "{case}"); + } + } + } +} + +/// An overprinting element of a knockout group that does not isolate is drawn in a `/K` group +/// without `/I true`, so it overprints the art below the group, and its graphics state still +/// overprints (`/OP`, `/op`, `/OPM 1`). An isolated group keeps `/I true`, reads back isolated +/// and is written with `/I true` again. +#[test] +fn an_overprinting_element_of_a_knockout_group_that_does_not_isolate_overprints_the_art_below() { + for isolate in [false, true] { + let mut d = knockout_squares(3, false, isolate); + let g = d.layers[0].children().unwrap()[1].id; + let squares: Vec<_> = d.node(g).unwrap().children().unwrap().iter().map(|s| s.id).collect(); + for s in &squares { + d.node_mut(*s).unwrap().opacity = 1.0; + } + d.node_mut(squares[2]).unwrap().appearance.fill_mut().unwrap().overprint = true; + let t = text(&d); + assert_eq!(t.matches("/Ktrue").count(), 1, "isolate {isolate}"); + assert_eq!(t.matches("/Itrue").count(), usize::from(isolate), "isolate {isolate}"); + assert!(t.contains("/OPtrue/optrue/OPM1"), "isolate {isolate}"); + let back = import(&export(&d, &PdfOptions::default()).unwrap()).unwrap_or_else(|e| panic!("isolate {isolate}: {e}")); + let mut overprints = vec![]; + back.walk(|n| { + if let Some(f) = n.appearance.fill() { + overprints.push(f.overprint); + } + }); + assert_eq!(overprints, [false, false, false, true], "isolate {isolate}"); + assert_eq!(knockout_groups(&back), [3], "isolate {isolate}"); + let mut found = vec![]; + back.walk(|n| { + if n.knockout == vectorcraft_doc::Knockout::On { + found.push(n.isolate); + } + }); + assert_eq!(found, [isolate], "isolate {isolate}"); + assert_eq!(text(&back).matches("/Itrue").count(), usize::from(isolate), "isolate {isolate}"); + } +} + +/// An isolated group with nothing blending inside but an overprinting fill reads back as an +/// isolated group and is written with `/I true` again; a group that does not isolate reads back +/// as its objects. +#[test] +fn an_isolated_group_with_an_overprinting_object_reads_back_isolated() { + for isolate in [false, true] { + let mut d = Document::new(200.0, 200.0); + add(&mut d, rect(Rect::new(0.0, 0.0, 200.0, 200.0), (0.9, 0.8, 0.2))); + let mut top = rect(Rect::new(60.0, 60.0, 160.0, 160.0), (0.0, 0.0, 1.0)); + top.appearance.fill_mut().unwrap().overprint = true; + let mut below = rect(Rect::new(20.0, 20.0, 120.0, 120.0), (1.0, 0.0, 0.0)); + (below.id, top.id) = (d.alloc_id(), d.alloc_id()); + let mut g = Node::group(NodeId(0), vec![std::sync::Arc::new(below), std::sync::Arc::new(top)]); + g.isolate = isolate; + add(&mut d, g); + assert_eq!(text(&d).matches("/Itrue").count(), usize::from(isolate), "isolate {isolate}"); + let back = import(&export(&d, &PdfOptions::default()).unwrap()).unwrap_or_else(|e| panic!("isolate {isolate}: {e}")); + let mut groups = vec![]; + back.walk(|n| { + if matches!(n.kind, vectorcraft_doc::NodeKind::Group { .. }) { + groups.push(n.isolate); + } + }); + assert_eq!(groups, if isolate { vec![true] } else { vec![] }, "isolate {isolate}"); + assert_eq!(text(&back).matches("/Itrue").count(), usize::from(isolate), "isolate {isolate}"); + } +} + /// The knockout group of an isolated group is isolated too (`/I true` beside `/K true`), and the /// group reads back as isolated and knocking out. (Each translucent element is a group of its own.) #[test] diff --git a/crates/pdf/src/tests/cmykimages.rs b/crates/pdf/src/tests/cmykimages.rs index 590afa3df9..57ccef1c6d 100644 --- a/crates/pdf/src/tests/cmykimages.rs +++ b/crates/pdf/src/tests/cmykimages.rs @@ -573,6 +573,35 @@ fn a_cmyk_image_that_keeps_its_numbers_carries_its_cmyk_profile() { assert!(!String::from_utf8_lossy(&bytes).contains("/S/Luminosity"), "no luminosity soft mask"); } +/// With Don't Include Profiles set, a CMYK JPEG kept as it is is DeviceCMYK without its own +/// `ICC_PROFILE` segments, its compressed inks unchanged; one resampled and compressed again is +/// written without a profile too. Left unset, the JPEG data stays as it is. +#[test] +fn a_set_dont_include_profiles_takes_a_cmyk_jpegs_profile_out() { + let ink = [0u8, 102, 255, 0]; + let icc = cmyk_profile(|_| {}); + 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 export = |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 segment = |data: &[u8]| data.windows(12).any(|w| w == b"ICC_PROFILE\0"); + let (w, _) = export(json!({})); + assert!(w.data == jpg && segment(&w.data), "unset: the JPEG data unchanged"); + let s = json!({"output": {"profiles": "none"}}); + let (w, bytes) = export(s.clone()); + assert_eq!((w.space.as_str(), w.filter.as_deref()), ("DeviceCMYK", Some("DCTDecode")), "{s}"); + assert!(!segment(&w.data) && w.data.len() < jpg.len(), "{s}: no ICC_PROFILE segment is left"); + assert!(w.data == vectorcraft_doc::cmyk::jpeg_without_icc(&jpg).unwrap(), "{s}: the other segments and the scan unchanged"); + assert_eq!(blobs(&import(&bytes).unwrap())[0].cmyk().unwrap().data, ImageBlob::new("image/jpeg", jpg.clone()).cmyk().unwrap().data); + let s = json!({"output": {"profiles": "none"}, "compression": {"color": {"downsample": "bicubic", "ppi": 72.0, "abovePpi": 100.0}}}); + let (w, _) = export(s.clone()); + assert!(w.icc.is_none() && !segment(&w.data), "{s}: {w:?}"); +} + /// 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] @@ -593,6 +622,38 @@ fn a_kept_cmyk_jpeg_declaring_too_many_pixels_is_left_out() { } } +/// A CMYK JPEG whose inks can't be read (it declares more pixels than CMYK images are decoded +/// with, though fewer than the writer embeds) is written with its own numbers only when they are +/// kept: when the Output settings convert its colors it is left out with a warning, in every +/// standard. +#[test] +fn a_cmyk_jpeg_whose_inks_cant_be_read_is_left_out_when_its_colors_are_converted() { + let mut jpg = cmyk_jpeg(&flat([0, 102, 255, 0], 4), 2, 2); + // Height and width of the SOF0 segment (after its marker, length and precision): 8200 × 8200. + let sof = jpg.windows(2).position(|w| w == [0xFF, 0xC0]).unwrap(); + jpg[sof + 5..sof + 9].copy_from_slice(&[0x20, 0x08, 0x20, 0x08]); + let blob = ImageBlob::new("image/jpeg", jpg); + assert!(blob.is_cmyk() && blob.cmyk().is_none()); + let d = image_doc(blob, 2, 2); + let out = export_with_report(&d, &opts(json!({}))).unwrap(); + let kept = written(&out.bytes); + assert!(kept.len() == 1 && kept[0].space == "DeviceCMYK", "kept as it is: {kept:?}"); + let unconverted = "an image couldn't be converted to the Output destination and is missing from the picture"; + for s in [ + json!({"output": {"conversion": "destination", "destination": DEVICE_CMYK}}), + json!({"output": {"conversion": "destination", "destination": SRGB}}), + json!({"standard": "pdfX1a", "output": {"conversion": "destination", "destination": DEVICE_CMYK}}), + json!({"standard": "pdfX4", "output": {"conversion": "destination", "destination": DEVICE_CMYK}}), + json!({"standard": "pdfA2b", "output": {"conversion": "destination", "destination": DEVICE_CMYK}}), + ] { + let out = export_with_report(&d, &opts(s.clone())).unwrap_or_else(|e| panic!("{s}: {e}")); + assert!(written(&out.bytes).is_empty(), "{s}"); + assert!(out.warnings.iter().any(|w| w == unconverted), "{s}: {:?}", out.warnings); + let other = out.warnings.iter().any(|w| w.contains("couldn't be decoded") || w.contains("written as it is")); + assert!(!other, "{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>> { diff --git a/crates/pdf/src/tests/compression.rs b/crates/pdf/src/tests/compression.rs index f36cb88e4b..90cc66bc5f 100644 --- a/crates/pdf/src/tests/compression.rs +++ b/crates/pdf/src/tests/compression.rs @@ -266,10 +266,58 @@ 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, true, None); + let r = crate::images::recode(&png, (10.0, 10.0), &c, false, None, crate::images::SourceProfiles::Keep, None); assert!(r.image.is_none(), "kept as it is"); } +/// When the Output settings convert colors, a color image beyond the decode allowance can't be +/// kept as it is: it is unconverted, and so is one whose header can't be read. A color image +/// whose pixel data can't be read (tagged with an ICC profile it is converted from or not) can't +/// be written in its own colors either, and is kept as it is, as is a grey one, whose pixels +/// aren't converted, and any image without a conversion. +#[test] +fn a_color_image_beyond_the_allowance_for_a_conversion_is_unconverted() { + use vectorcraft_color::cms::{DISPLAY_P3, GENERIC_CMYK, icc_bytes}; + let d = doc(encoded(colour(), ImageFormat::Png), "image/png"); + let settings: PdfSettings = serde_json::from_value(json!({"output": {"conversion": "destination", "destination": GENERIC_CMYK}})).unwrap(); + let out = crate::output::ColorOut::new(&d, &settings).unwrap(); + assert!(out.pixels().is_some()); + let to_srgb = out.image_srgb_intent().map(|intent| crate::images::ToSrgb { intent, sixteen_bit: false }); + assert!(to_srgb.is_some()); + let c: CompressionSettings = serde_json::from_value(json!({})).unwrap(); + let half = |mut bytes: Vec| { + bytes.truncate(bytes.len() / 2); + bytes + }; + let cut = |img: DynamicImage| half(encoded(img, ImageFormat::Png)); + let mut p3 = icc_bytes(DISPLAY_P3).unwrap().to_vec(); + p3[8..12].copy_from_slice(&[4, 0x20, 0, 0]); + // `declared_png`'s header declaring RGB pixels (color type 2), with the IHDR chunk's CRC + // written again. + let mut rgb_declared = declared_png(60_000, 60_000); + rgb_declared[25] = 2; + let mut crc = flate2::Crc::new(); + crc.update(&rgb_declared[12..29]); + rgb_declared[29..33].copy_from_slice(&crc.sum().to_be_bytes()); + let cases = [ + ("RGB declaring more than the allowance", rgb_declared, true), + ("RGB", cut(colour()), false), + ("tagged RGB", half(tagged(&colour(), &p3, ImageFormat::Png)), false), + ("unreadable", vec![1, 2, 3], true), + ("grey", cut(colour().grayscale()), false), + ("grey declaring more than the allowance", declared_png(60_000, 60_000), false), + ]; + for (what, bytes, unconverted) in cases { + let r = crate::images::recode(&bytes, (72.0, 72.0), &c, false, out.pixels(), crate::images::SourceProfiles::Keep, to_srgb); + assert!(r.image.is_none(), "{what}"); + assert_eq!(r.unconverted, unconverted, "{what}"); + assert!( + !crate::images::recode(&bytes, (72.0, 72.0), &c, false, None, crate::images::SourceProfiles::Keep, None).unconverted, + "{what}, no conversion" + ); + } +} + /// 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 { @@ -425,6 +473,80 @@ fn pdf_x1a_keeps_a_tagged_gray_jpeg_as_jpeg() { } } +/// With Don't Include Profiles set, a gray or RGB image is written without the ICC profile it +/// carries: a PNG, JPEG or TIFF embedded as it is, resampled or compressed with JPEG, with alpha and +/// at 16 bits. A JPEG kept as it is loses its `ICC_PROFILE` segments, its compressed samples +/// unchanged. Left unset, or `null`, the setting keeps the profiles. PDF/X-4 files keep them +/// whatever the setting says. +#[test] +fn a_set_dont_include_profiles_removes_image_profiles() { + 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 deep = DynamicImage::ImageRgb16(colour().to_rgb16()); + let export = |d: &Document, settings: Value| { + let mut settings: PdfSettings = serde_json::from_value(settings).unwrap(); + settings.compression.compress_text = false; + export_with_report(d, &PdfOptions { settings, ..Default::default() }).unwrap() + }; + let resampled = + json!({"color": {"downsample": "bicubic", "ppi": 150, "abovePpi": 225}, "gray": {"downsample": "bicubic", "ppi": 150, "abovePpi": 225}}); + let jpeg = json!({"color": {"compression": "jpeg"}, "gray": {"compression": "jpeg"}}); + let cases = [ + ("RGB PNG", tagged(&colour(), &rgb, ImageFormat::Png), "image/png", json!({}), "DeviceRGB"), + ("gray PNG", tagged(&colour().grayscale(), &gray, ImageFormat::Png), "image/png", json!({}), "DeviceGray"), + ("RGB JPEG", tagged(&colour(), &rgb, ImageFormat::Jpeg), "image/jpeg", json!({}), "DeviceRGB"), + ("gray JPEG", tagged(&colour().grayscale(), &gray, ImageFormat::Jpeg), "image/jpeg", json!({}), "DeviceGray"), + ("RGB TIFF", tagged(&colour(), &rgb, ImageFormat::Tiff), "image/tiff", json!({}), "DeviceRGB"), + ("gray TIFF", tagged(&colour().grayscale(), &gray, ImageFormat::Tiff), "image/tiff", json!({}), "DeviceGray"), + ("RGBA TIFF", tagged(&clear.into(), &rgb, ImageFormat::Tiff), "image/tiff", json!({}), "DeviceRGB"), + ("16-bit TIFF", tagged(&deep, &rgb, ImageFormat::Tiff), "image/tiff", json!({}), "DeviceRGB"), + ("RGB PNG, resampled", tagged(&colour(), &rgb, ImageFormat::Png), "image/png", resampled.clone(), "DeviceRGB"), + ("gray JPEG, resampled", tagged(&colour().grayscale(), &gray, ImageFormat::Jpeg), "image/jpeg", resampled, "DeviceGray"), + ("RGB TIFF as JPEG", tagged(&colour(), &rgb, ImageFormat::Tiff), "image/tiff", jpeg.clone(), "DeviceRGB"), + ("gray TIFF as JPEG", tagged(&colour().grayscale(), &gray, ImageFormat::Tiff), "image/tiff", jpeg, "DeviceGray"), + ]; + for (what, bytes, mime, compression, device) in cases { + let d = doc(bytes.clone(), mime); + // Left unset, or null, the image keeps its profile. + for profiles in [json!({}), json!({"profiles": null})] { + let r = export(&d, json!({"compression": compression.clone(), "output": profiles})); + let spaces = image_spaces(&r.bytes); + assert!(spaces.len() == 1 && spaces[0].space == "ICCBased" && spaces[0].icc.is_some(), "{what}, {profiles}: {spaces:?}"); + } + let none = export(&d, json!({"compression": compression.clone(), "output": {"profiles": "none"}})); + assert!(none.warnings.is_empty(), "{what}: {:?}", none.warnings); + let spaces = image_spaces(&none.bytes); + assert!(spaces.len() == 1 && spaces[0].space == device && spaces[0].icc.is_none(), "{what}: {spaces:?}"); + let data = image_data(&none.bytes); + assert!(data.iter().all(|d| !d.windows(12).any(|w| w == b"ICC_PROFILE\0")), "{what}: no ICC_PROFILE segment is left"); + if mime == "image/jpeg" && compression == json!({}) { + // The JPEG data without its profile segments: the image decoder reads the same pixels + // from it, and no profile. + assert!(data.len() == 1 && data[0].len() < bytes.len(), "{what}: the JPEG data kept"); + let decode = |b: &[u8]| image::load_from_memory_with_format(b, ImageFormat::Jpeg).unwrap(); + assert!(decode(&data[0]) == decode(&bytes), "{what}: the same pixels"); + assert!(crate::images::source_icc(&data[0]).is_none() && crate::images::source_icc(&bytes).is_some(), "{what}"); + } + // PDF/X-4 tags every colour: the image keeps its profile. + let x4 = export(&d, json!({"standard": "pdfX4", "compatibility": "1.6", "compression": compression, "output": {"profiles": "none"}})); + let spaces = image_spaces(&x4.bytes); + assert!(spaces.len() == 1 && spaces[0].space == "ICCBased", "{what}, PDF/X-4: {spaces:?}"); + } + // A JPEG whose `ICC_PROFILE` segments don't make up a profile (the first of two, the second + // missing) loses them too. + let plain = encoded(colour(), ImageFormat::Jpeg); + let mut part = vec![0xFF, 0xD8, 0xFF, 0xE2, 0, 30]; + part.extend_from_slice(b"ICC_PROFILE\0"); + part.extend_from_slice(&[1, 2]); + part.extend_from_slice(&rgb[..14]); + part.extend_from_slice(&plain[2..]); + assert!(crate::images::source_icc(&part).is_none(), "the decoder reads no profile"); + let none = export(&doc(part, "image/jpeg"), json!({"output": {"profiles": "none"}})); + let data = image_data(&none.bytes); + assert!(data == [plain], "an unreadable profile: the JPEG data without its segments"); +} + /// 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 @@ -778,9 +900,10 @@ fn convert_to_srgb_converts_tagged_images_from_their_profile() { let c: CompressionSettings = serde_json::from_value(json!({})).unwrap(); let srgb_out = Some(crate::images::ToSrgb { intent: Intent::RelativeColorimetric, sixteen_bit: true }); for (what, png) in [("RGB", declared(&colour(), &p3)), ("gray", declared(&colour().grayscale(), &gray))] { - let r = crate::images::recode(&png, (100.0, 100.0), &c, false, None, true, srgb_out); + let keep = crate::images::SourceProfiles::Keep; + let r = crate::images::recode(&png, (100.0, 100.0), &c, false, None, keep, srgb_out); assert!(r.image.is_none() && r.warning.is_some_and(|w| w.contains("not converted to sRGB")), "{what}: {:?}", r.warning); - let r = crate::images::recode(&png, (100.0, 100.0), &c, false, None, true, None); + let r = crate::images::recode(&png, (100.0, 100.0), &c, false, None, keep, None); assert!(r.image.is_none() && r.warning.is_none(), "{what}, no conversion: {:?}", r.warning); // Too large to embed as it is too: the export leaves it out, and says only that. let mut settings: PdfSettings = serde_json::from_value(to_srgb(json!({}))).unwrap(); diff --git a/crates/pdf/src/tests/import_options.rs b/crates/pdf/src/tests/import_options.rs index 2ed84d5dc0..a419d64137 100644 --- a/crates/pdf/src/tests/import_options.rs +++ b/crates/pdf/src/tests/import_options.rs @@ -91,6 +91,27 @@ fn trim_box_artboards_take_the_bleed_box_round_them_as_the_document_bleed() { assert_eq!((d.artboards[0].rect.width(), d.setup.bleed), (300.0, [0.0; 4])); } +#[test] +fn trim_box_artboards_keep_the_bleed_between_them() { + // The second page's bleed box is its trim box: the document's bleed (10 mm, over half the + // 36 pt gap) still goes round its artboard. + let edge = Some([50.0, 50.0, 250.0, 150.0]); + let plain = PdfPage { bleed: edge, trim: edge, ..PdfPage::new(300.0, 200.0, "0 g 50 50 200 100 re f") }; + let bytes = pdf(&[bled_page(), plain, bled_page()], None); + let d = open(&bytes, ImportOptions { crop: CropTo::Trim, ..Default::default() }); + let starts: Vec = d.artboards.iter().map(|a| a.rect.x0).collect(); + let step = 200.0 + 36.0 + 2.0 * BLEED; + assert!(near([starts[0], starts[1], starts[2], 0.0], [0.0, step, 2.0 * step, 0.0]), "{starts:?}"); + // Each artboard's bleed ends 36 pt before the next one's begins. + for pair in d.artboards.windows(2) { + let (a, b) = (d.setup.bleed_rect(pair[0].rect), d.setup.bleed_rect(pair[1].rect)); + assert!((b.x0 - a.x1 - 36.0).abs() < 1e-3, "{a:?} {b:?}"); + } + // On the crop boxes there is no bleed, and the artboards are 36 pt apart. + let d = open(&bytes, ImportOptions::default()); + assert_eq!(d.artboards.iter().map(|a| a.rect.x0).collect::>(), [0.0, 336.0, 672.0]); +} + #[test] fn missing_boxes_fall_back_to_the_crop_box_and_boxes_are_clipped_to_the_media_box() { let page = PdfPage { crop: Some([10.0, 10.0, 290.0, 390.0]), art: Some([-50.0, 0.0, 100.0, 100.0]), ..PdfPage::new(300.0, 400.0, "") }; diff --git a/crates/pdf/src/tests/settings.rs b/crates/pdf/src/tests/settings.rs index e159b7b162..d4dd5a63ce 100644 --- a/crates/pdf/src/tests/settings.rs +++ b/crates/pdf/src/tests/settings.rs @@ -41,6 +41,24 @@ fn json_is_camel_case_and_partial_objects_keep_defaults() { } } +/// The Profiles setting is unset when left out, `null` or `"default"` (written as `null`), and set +/// by a choice's id; another value is refused. +#[test] +fn the_profiles_setting_can_be_left_unset() { + assert_eq!(serde_json::to_value(PdfSettings::default()).unwrap()["output"]["profiles"], serde_json::Value::Null); + for unset in [json!({}), json!({"profiles": null}), json!({"profiles": "default"})] { + assert_eq!(settings(json!({"output": unset.clone()})).output.profiles, None, "{unset}"); + } + for (id, want) in [("none", ProfileInclusion::None), ("all", ProfileInclusion::All), ("taggedSource", ProfileInclusion::TaggedSource)] { + let s = settings(json!({"output": {"profiles": id}})); + assert_eq!(s.output.profiles, Some(want), "{id}"); + assert_eq!(serde_json::from_value::(serde_json::to_value(&s).unwrap()).unwrap(), s, "{id} round-trips"); + } + for bad in [json!("Default"), json!("never"), json!(1)] { + assert!(serde_json::from_value::(json!({"output": {"profiles": bad.clone()}})).is_err(), "{bad}"); + } +} + #[test] fn passwords_are_never_serialized() { let s = settings(json!({"security": {"openPassword": "secret", "permissionsPassword": "owner"}})); diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml index 4bd499b9d4..ecdaa60273 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -19,13 +19,12 @@ vello_cpu = { workspace = true } # Filter types (Gaussian blur, drop shadow) are not re-exported by vello_cpu 0.2. vello_common = { version = "0.2", default-features = false } image = { workspace = true } +craft-image-codecs = { workspace = true } flate2 = { workspace = true } jpeg-encoder = { workspace = true } gif = { workspace = true } # TIFF LZW compression (MIT OR Apache-2.0; already used by the image crate's TIFF reader). weezl = "0.2" -# PNG rows read one at a time (MIT OR Apache-2.0; already used by the image crate's PNG reader). -png = "0.18" log = { workspace = true } # Combining marks inside a lam-alef cluster (MIT OR Apache-2.0; already used by vectorcraft-text). unicode-general-category = "1" @@ -47,8 +46,7 @@ vectorcraft-plugins = { workspace = true } wat = { workspace = true } # Decoders the export tests read their files back with. image = { workspace = true, features = ["tga"] } -tiff = "0.11" -# Reads the PSD exports back (MIT OR Apache-2.0). -psd = "0.3" +craft-tiff = { workspace = true } +craft-psd = { workspace = true } proptest = { workspace = true } serde_json = { workspace = true } diff --git a/crates/render/src/encode/tests.rs b/crates/render/src/encode/tests.rs index a910480641..0a8227b75f 100644 --- a/crates/render/src/encode/tests.rs +++ b/crates/render/src/encode/tests.rs @@ -86,8 +86,10 @@ fn gray_and_bilevel_images_store_gray() { assert_eq!(gray(&file), levels); let (mime, file) = img.to_bilevel(150.0).unwrap(); assert_eq!(mime, "image/tiff"); - let mut d = ::tiff::decoder::Decoder::new(std::io::Cursor::new(&file)).unwrap(); - assert_eq!(d.colortype().unwrap(), ::tiff::ColorType::Gray(1)); + let tiff = craft_tiff::Tiff::parse(&file).unwrap(); + let ifd = &tiff.ifds[0]; + assert_eq!(ifd.u16(craft_tiff::tags::SAMPLES_PER_PIXEL), Some(1)); + assert_eq!(ifd.value(craft_tiff::tags::BITS_PER_SAMPLE).unwrap().to_u64_vec(), vec![1]); let bw: Vec = [0u8, 0, 255, 255, 255, 0].iter().flat_map(|&g| [g, 255]).collect(); assert_eq!(gray(&file), bw, "from 128 up is white"); // Half-covered white over the light grey; a clear pixel is white. diff --git a/crates/render/src/encode/tests_psd.rs b/crates/render/src/encode/tests_psd.rs index a488cceff2..e2df72e01c 100644 --- a/crates/render/src/encode/tests_psd.rs +++ b/crates/render/src/encode/tests_psd.rs @@ -144,9 +144,18 @@ fn unpack(mut src: &[u8], out: &mut Vec) { } } -/// The composite as a reader sees it. +/// The stored composite: RGB stays white-matted, with its original alpha. fn merged(f: &[u8]) -> Vec { - ::psd::Psd::from_bytes(f).expect("a PSD a reader takes").rgba() + let psd = craft_psd::PsdFile::from_bytes(f).expect("a PSD a reader takes"); + if psd.header.color_mode != craft_psd::ColorMode::Rgb { + return psd.composite_rgba8().expect("composite").data; + } + assert_eq!(psd.header.depth, 8); + let samples = psd.decode_merged().expect("stored composite planes"); + let count = psd.header.width as usize * psd.header.height as usize; + (0..count) + .flat_map(|i| [samples[i], samples[count + i], samples[2 * count + i], if psd.merged_has_alpha() { samples[3 * count + i] } else { 255 }]) + .collect() } fn pixel(px: &[u8], width: usize, x: usize, y: usize) -> [u8; 4] { @@ -168,11 +177,12 @@ fn layers_are_the_top_level_layers_and_the_merged_image_is_the_render() { assert_eq!(p.records[1].rect, [0, 0, 50, 60], "the blue square and the corner"); // A reader decodes it: the layers, in place, and the merged image. - let psd = ::psd::Psd::from_bytes(&file).unwrap(); - assert_eq!((psd.width(), psd.height(), psd.layers().len()), (100, 60, 2)); - let red = psd.layer_by_name("Layer 1").unwrap().rgba(); - assert_eq!(pixel(&red, 100, 20, 20), [255, 0, 0, 255]); - assert_eq!(pixel(&red, 100, 50, 45)[3], 0, "the blue square isn't on Layer 1"); + let psd = craft_psd::PsdFile::from_bytes(&file).unwrap(); + assert_eq!((psd.header.width, psd.header.height, psd.layers().len()), (100, 60, 2)); + let layer = psd.iter_layers().find(|l| l.name() == "Layer 1").unwrap(); + assert_eq!(layer.record.rect, craft_psd::layer::Rect { top: 10, left: 10, bottom: 40, right: 40 }); + let red = layer.rgba8().unwrap().data; + assert_eq!(pixel(&red, 30, 10, 10), [255, 0, 0, 255]); // The merged image is the flat render: colours on white where transparent, alpha apart. let img = Renderer::new().render_region_with(&doc, doc.artboards[0].rect, 1.0, &opts(PsdOptions::default()).render_options(RasterFormat::Psd)); @@ -200,7 +210,7 @@ fn flat_writes_the_merged_image_alone_on_white() { assert_eq!(o.encode(&img, RasterFormat::Psd).unwrap(), file); let file = export(&doc, &RasterExportOptions { ppi: 150.0, ..o }); assert_eq!(u32_at(parse(&file).resources, 12), 150 << 16); - assert_eq!(::psd::Psd::from_bytes(&file).unwrap().width(), 208); + assert_eq!(craft_psd::PsdFile::from_bytes(&file).unwrap().header.width, 208); } #[test] @@ -230,8 +240,11 @@ fn maximum_editability_writes_groups_and_an_object_per_layer() { assert_eq!((p.records[4].opacity, p.records[4].blend, p.records[4].rect), (128, *b"mul ", [20, 30, 50, 60])); assert_eq!((p.records[8].blend, p.records[8].opacity), (*b"pass", 255)); assert_eq!(p.records[6].rect, [0, 0, 6, 6]); - let psd = ::psd::Psd::from_bytes(&file).unwrap(); - assert_eq!((psd.layers().len(), psd.groups().len()), (3, 3)); + let psd = craft_psd::PsdFile::from_bytes(&file).unwrap(); + let content_layers = psd.layers().iter().filter(|l| matches!(l.section_type(), craft_psd::SectionType::Other)).count(); + let groups = + psd.layers().iter().filter(|l| matches!(l.section_type(), craft_psd::SectionType::OpenFolder | craft_psd::SectionType::ClosedFolder)).count(); + assert_eq!((content_layers, groups), (3, 3)); assert_eq!(merged(&file), merged(&export(&doc, &opts(PsdOptions::default()))), "the same merged image"); // Hidden layers: written hidden, drawn as if visible, instead of left out. @@ -300,8 +313,8 @@ fn a_background_colour_is_the_bottom_layer() { let p = parse(&file); assert_eq!((p.channels, p.count), (3, 3), "opaque: no merged alpha"); assert_eq!((p.records[0].name.as_str(), p.records[0].rect), ("Background", [0, 0, 60, 100])); - let psd = ::psd::Psd::from_bytes(&file).unwrap(); - assert!(psd.layer_by_name("Background").unwrap().rgba().chunks(4).all(|p| p == [0, 0, 255, 255])); + let psd = craft_psd::PsdFile::from_bytes(&file).unwrap(); + assert!(psd.iter_layers().find(|l| l.name() == "Background").unwrap().rgba8().unwrap().data.chunks(4).all(|p| p == [0, 0, 255, 255])); assert_eq!(pixel(&merged(&file), 100, 5, 50), [0, 0, 255, 255]); } diff --git a/crates/render/src/encode/tests_tiff.rs b/crates/render/src/encode/tests_tiff.rs index c70eacd2fc..e10739e67a 100644 --- a/crates/render/src/encode/tests_tiff.rs +++ b/crates/render/src/encode/tests_tiff.rs @@ -1,22 +1,25 @@ //! TIFF export: byte order, LZW, colour models and samples, resolution, profile, strips. -use std::io::Cursor; - -use tiff::decoder::{Decoder, DecodingResult}; -use tiff::tags::Tag; +use craft_tiff::Tiff; +use craft_tiff::tags; use super::jpeg::ColorModel; use super::tiff::{self as t, ByteOrder, Compression, Image, Layout, Photometric, TiffOptions}; -fn decoder(file: &[u8]) -> Decoder> { - Decoder::new(Cursor::new(file)).expect("a TIFF") +fn ifd0(file: &[u8]) -> craft_tiff::Ifd { + Tiff::parse(file).expect("a TIFF").ifds.into_iter().next().expect("IFD0") +} + +fn tag_u16_vec(ifd: &craft_tiff::Ifd, tag: u16) -> Option> { + ifd.value(tag).map(|v| v.to_u64_vec().into_iter().map(|x| x as u16).collect()) +} + +fn tag_u32_vec(ifd: &craft_tiff::Ifd, tag: u16) -> Option> { + ifd.value(tag).map(|v| v.to_u64_vec().into_iter().map(|x| x as u32).collect()) } fn pixels(file: &[u8]) -> Vec { - match decoder(file).read_image().expect("decodes") { - DecodingResult::U8(v) => v, - _ => panic!("8-bit samples"), - } + craft_image_codecs::decode_as(craft_image_codecs::Format::Tiff, file).expect("decodes").into_data() } /// Straight RGBA: flat areas (as art is) with a transparent corner when `clear`. @@ -46,7 +49,7 @@ fn byte_order_writes_an_ii_or_mm_header() { assert_eq!(&file[..4], magic); let rgb: Vec = px.chunks(4).flat_map(|p| &p[..3]).copied().collect(); assert_eq!(pixels(&file), rgb, "{order:?}"); - assert_eq!(decoder(&file).get_tag_ascii_string(Tag::Software).unwrap(), "VectorCraft"); + assert_eq!(ifd0(&file).string(tags::SOFTWARE).as_deref(), Some("VectorCraft")); } for (s, o) in [("little", ByteOrder::Little), ("MM", ByteOrder::Big), ("mac", ByteOrder::Big), ("ii", ByteOrder::Little), ("big", ByteOrder::Big)] { @@ -61,44 +64,51 @@ fn lzw_is_smaller_and_decodes_the_same() { let plain = t::encode_samples(&px, 120, 90, 72.0, &TiffOptions { lzw: false, ..opts(ColorModel::Rgb) }).unwrap(); let lzw = t::encode_samples(&px, 120, 90, 72.0, &opts(ColorModel::Rgb)).unwrap(); assert!(lzw.len() * 4 < plain.len(), "{} vs {}", lzw.len(), plain.len()); - assert_eq!(decoder(&lzw).get_tag_unsigned::(Tag::Compression).unwrap(), 5); - assert_eq!(decoder(&plain).get_tag_unsigned::(Tag::Compression).unwrap(), 1); + assert_eq!(ifd0(&lzw).u16(tags::COMPRESSION), Some(5)); + assert_eq!(ifd0(&plain).u16(tags::COMPRESSION), Some(1)); assert_eq!(pixels(&lzw), px, "transparency kept as an alpha channel"); assert_eq!(pixels(&plain), px); - // The image crate reads it too. - let img = image::load_from_memory_with_format(&lzw, image::ImageFormat::Tiff).unwrap().to_rgba8(); - assert_eq!(img.into_raw(), px); + let img = craft_image_codecs::decode_as(craft_image_codecs::Format::Tiff, &lzw).unwrap(); + assert_eq!(img.data(), px); } #[test] fn colour_models_write_their_samples() { let px = art(9, 6, true); let rgba = t::encode_samples(&px, 9, 6, 72.0, &opts(ColorModel::Rgb)).unwrap(); - assert_eq!(decoder(&rgba).colortype().unwrap(), tiff::ColorType::RGBA(8)); - assert_eq!(decoder(&rgba).get_tag_u16_vec(Tag::ExtraSamples).unwrap(), [2], "unassociated alpha"); + let rgba_ifd = ifd0(&rgba); + assert_eq!(rgba_ifd.u16(tags::PHOTOMETRIC), Some(2)); + assert_eq!(rgba_ifd.u16(tags::SAMPLES_PER_PIXEL), Some(4)); + assert_eq!(tag_u16_vec(&rgba_ifd, tags::BITS_PER_SAMPLE).as_deref(), Some([8, 8, 8, 8].as_slice())); + assert_eq!(tag_u16_vec(&rgba_ifd, tags::EXTRA_SAMPLES).as_deref(), Some([2].as_slice()), "unassociated alpha"); let opaque = art(9, 6, false); let rgb = t::encode_samples(&opaque, 9, 6, 72.0, &opts(ColorModel::Rgb)).unwrap(); - assert_eq!(decoder(&rgb).colortype().unwrap(), tiff::ColorType::RGB(8)); - assert!(decoder(&rgb).find_tag(Tag::ExtraSamples).unwrap().is_none()); + let rgb_ifd = ifd0(&rgb); + assert_eq!(rgb_ifd.u16(tags::PHOTOMETRIC), Some(2)); + assert_eq!(rgb_ifd.u16(tags::SAMPLES_PER_PIXEL), Some(3)); + assert!(rgb_ifd.value(tags::EXTRA_SAMPLES).is_none()); let gray = t::encode_samples(&opaque, 9, 6, 72.0, &opts(ColorModel::Gray)).unwrap(); - assert_eq!(decoder(&gray).colortype().unwrap(), tiff::ColorType::Gray(8)); - assert_eq!(decoder(&gray).get_tag_unsigned::(Tag::PhotometricInterpretation).unwrap(), 1, "black is zero"); + let gray_ifd = ifd0(&gray); + assert_eq!(gray_ifd.u16(tags::SAMPLES_PER_PIXEL), Some(1)); + assert_eq!(tag_u16_vec(&gray_ifd, tags::BITS_PER_SAMPLE).as_deref(), Some([8].as_slice())); + assert_eq!(gray_ifd.u16(tags::PHOTOMETRIC), Some(1), "black is zero"); let g = pixels(&gray); assert_eq!((g[0], g[8]), (super::jpeg::to_gray()([200, 30, 40]), 255), "lightness; white stays white"); let on_white = t::encode_samples(&px, 9, 6, 72.0, &opts(ColorModel::Gray)).unwrap(); - assert_eq!(decoder(&on_white).colortype().unwrap(), tiff::ColorType::Gray(8), "grey has no alpha: few readers take it"); + let on_white_ifd = ifd0(&on_white); + assert_eq!(on_white_ifd.u16(tags::SAMPLES_PER_PIXEL), Some(1), "grey has no alpha: few readers take it"); assert_eq!(pixels(&on_white)[0], 255, "the transparent corner is white"); // CMYK: four samples a pixel, ink amounts as given. let inks: Vec = (0..9 * 6 * 4).map(|i| (i * 7 % 256) as u8).collect(); let cmyk = t::encode_samples(&inks, 9, 6, 72.0, &opts(ColorModel::Cmyk)).unwrap(); - let mut d = decoder(&cmyk); - assert_eq!(d.colortype().unwrap(), tiff::ColorType::CMYK(8)); - assert_eq!(d.get_tag_unsigned::(Tag::SamplesPerPixel).unwrap(), 4); - assert_eq!(d.get_tag_unsigned::(Tag::PhotometricInterpretation).unwrap(), 5, "separated"); - assert_eq!(d.get_tag_unsigned::(Tag::Unknown(332)).unwrap(), 1, "CMYK inks"); - assert_eq!(pixels(&cmyk), inks); + let d = ifd0(&cmyk); + assert_eq!(d.u16(tags::SAMPLES_PER_PIXEL), Some(4)); + assert_eq!(d.u16(tags::PHOTOMETRIC), Some(5), "separated"); + assert_eq!(d.u16(332), Some(1), "CMYK inks"); + let cmyk_img = craft_image_codecs::decode_as(craft_image_codecs::Format::Tiff, &cmyk).unwrap(); + assert_eq!(cmyk_img.data(), inks); } #[test] @@ -106,16 +116,18 @@ fn resolution_tags_and_the_profile() { let px = art(4, 4, false); for (ppi, rational) in [(300.0, (300, 1)), (72.5, (7250, 100))] { let file = t::encode_samples(&px, 4, 4, ppi, &opts(ColorModel::Rgb)).unwrap(); - let mut d = decoder(&file); - for tag in [Tag::XResolution, Tag::YResolution] { - assert_eq!(d.get_tag(tag).unwrap(), tiff::decoder::ifd::Value::Rational(rational.0, rational.1)); + let d = ifd0(&file); + for tag in [tags::X_RESOLUTION, tags::Y_RESOLUTION] { + let Some(craft_tiff::Value::Rational(v)) = d.value(tag) else { panic!("rational") }; + assert_eq!(v.as_slice(), &[rational]); } - assert_eq!(d.get_tag_unsigned::(Tag::ResolutionUnit).unwrap(), 2, "inches"); + assert_eq!(d.u16(tags::RESOLUTION_UNIT), Some(2), "inches"); } for model in ColorModel::ALL { let src = if model == ColorModel::Cmyk { vec![0; 64] } else { px.clone() }; let file = t::encode_samples(&src, 4, 4, 72.0, &TiffOptions { embed_icc: true, ..opts(model) }).unwrap(); - let icc = decoder(&file).get_tag_u8_vec(Tag::IccProfile).unwrap(); + let ifd = ifd0(&file); + let icc = ifd.bytes(tags::ICC_PROFILE).unwrap(); assert_eq!(&icc[36..40], b"acsp", "{model:?}: an ICC profile"); let space: &[u8; 4] = match model { ColorModel::Rgb => b"RGB ", @@ -125,7 +137,7 @@ fn resolution_tags_and_the_profile() { assert_eq!(&icc[16..20], space, "{model:?}"); } let file = t::encode_samples(&px, 4, 4, 72.0, &opts(ColorModel::Rgb)).unwrap(); - assert!(decoder(&file).find_tag(Tag::IccProfile).unwrap().is_none()); + assert!(ifd0(&file).value(tags::ICC_PROFILE).is_none()); } #[test] @@ -135,10 +147,10 @@ fn big_images_take_several_strips_in_either_order() { for order in ByteOrder::ALL { for lzw in [false, true] { let file = t::encode_samples(&px, w, h, 72.0, &TiffOptions { lzw, byte_order: order, ..opts(ColorModel::Gray) }).unwrap(); - let mut d = decoder(&file); - let offsets = d.get_tag_u32_vec(Tag::StripOffsets).unwrap(); + let d = ifd0(&file); + let offsets = tag_u32_vec(&d, tags::STRIP_OFFSETS).unwrap(); // 300 bytes a row: 27 rows a strip. - assert_eq!(d.get_tag_u32(Tag::RowsPerStrip).unwrap(), 27); + assert_eq!(d.u32(tags::ROWS_PER_STRIP), Some(27)); assert_eq!(offsets.len(), 4); assert!(offsets.iter().all(|o| o % 2 == 0), "strips start on a word"); assert_eq!(pixels(&file).len(), (w * h) as usize, "{order:?} lzw {lzw}"); @@ -152,11 +164,19 @@ fn packbits_and_bilevel_images_decode() { let rows = [0b1010_1010u8, 0b1100_0000, 0xFF, 0xC0, 0, 0]; let image = Image { width: 10, height: 3, data: &rows, photometric: Photometric::WhiteIsZero, samples: 1, bits: 1, alpha: false }; let file = t::write(&image, &Layout { byte_order: ByteOrder::Big, compression: Compression::PackBits, ppi: 72.0, icc: None }).unwrap(); - let mut d = decoder(&file); - assert_eq!(d.colortype().unwrap(), tiff::ColorType::Gray(1)); - assert_eq!(d.get_tag_unsigned::(Tag::Compression).unwrap(), 32773); + let d = ifd0(&file); + assert_eq!(d.u16(tags::SAMPLES_PER_PIXEL), Some(1)); + assert_eq!(tag_u16_vec(&d, tags::BITS_PER_SAMPLE).as_deref(), Some([1].as_slice())); + assert_eq!(d.u16(tags::COMPRESSION), Some(32773)); // The decoder turns WhiteIsZero into black-is-zero. - assert_eq!(pixels(&file), rows.map(|b| !b)); + let dec = craft_image_codecs::decode_as(craft_image_codecs::Format::Tiff, &file).unwrap(); + assert_eq!(dec.width(), 10); + assert_eq!(dec.height(), 3); + assert_eq!( + dec.data(), + [0, 255, 0, 255, 0, 255, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + "WhiteIsZero samples are inverted and row padding is ignored" + ); // A buffer that doesn't match the size is refused, not written. let short = Image { data: &rows[..5], ..image }; assert!(t::write(&short, &Layout { byte_order: ByteOrder::Little, compression: Compression::None, ppi: 72.0, icc: None }).is_err()); diff --git a/crates/render/src/fx/tests.rs b/crates/render/src/fx/tests.rs index 50d0245c12..3bbd803cc2 100644 --- a/crates/render/src/fx/tests.rs +++ b/crates/render/src/fx/tests.rs @@ -337,6 +337,38 @@ fn a_transform_after_a_drop_shadow_scales_the_shadow_with_the_art() { } } +/// A Transform effect listed after a Bas Relief turns its light with the art: a group of a black +/// square centered on a white one, lit from the top and turned 90° counterclockwise about its +/// center, draws as the group lit from the left. +#[test] +fn a_transform_after_bas_relief_turns_its_light_with_the_art() { + let relieved = |effects: Vec<(&str, serde_json::Value)>| { + let mut d = Document::new(100.0, 100.0); + let mut square = + |r: Rect, c: Color| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(r), Appearance::basic(Paint::solid(c), Paint::None, 0.0))); + let members = vec![square(Rect::new(20.0, 20.0, 80.0, 80.0), Color::WHITE), square(Rect::new(40.0, 40.0, 60.0, 60.0), Color::BLACK)]; + let mut g = Node::group(d.alloc_id(), members); + g.appearance.effects = effects.into_iter().map(|(id, p)| Effect { id: id.into(), params: p, visible: true }).collect(); + let l = d.layers[0].id; + d.insert(Some(l), 0, g).unwrap(); + render(&d) + }; + let relief = |light: &str| ("sketch.basRelief", json!({"lightDirection": light})); + let turned = relieved(vec![relief("top"), ("distort.transform", json!({"rotate": 90}))]); + let left = relieved(vec![relief("left")]); + let top = relieved(vec![relief("top")]); + // The largest difference of a channel between two images. + let diff = |a: &Rendered, b: &Rendered| { + (0..100u32) + .flat_map(|y| (0..100u32).map(move |x| (x, y))) + .map(|(x, y)| a.pixel(x, y).iter().zip(b.pixel(x, y)).map(|(p, q)| p.abs_diff(q)).max().unwrap_or(0)) + .max() + .unwrap_or(0) + }; + assert!(diff(&left, &top) > 50, "the light's direction shows: {}", diff(&left, &top)); + assert!(diff(&turned, &left) <= 2, "turned top light draws as a left light: {}", diff(&turned, &left)); +} + /// An object's or a group's Transform effect transforms the raster effects of what it holds with /// the art: halving a 40 pt square about its center halves the 10 pt offset of its fill's shadow, /// and of a group member's own shadow, with Scale Strokes & Effects off or on. diff --git a/crates/render/src/kept_paths.rs b/crates/render/src/kept_paths.rs index a6deb8e334..c609590d16 100644 --- a/crates/render/src/kept_paths.rs +++ b/crates/render/src/kept_paths.rs @@ -290,7 +290,7 @@ impl Sub { /// them. fn moved(&mut self, was: &SubPath, now: &SubPath, els: &mut [PathEl], st: Option<&StrokeLayer>) { let (mut first, mut segs) = (false, vec![]); - for (k, (a, b)) in was.anchors.iter().zip(&now.anchors).enumerate() { + for (k, a, b) in was.anchors.pairs_not_shared(&now.anchors) { if same(a, b) { continue; } @@ -489,7 +489,7 @@ fn differs(was: &PathData, now: &PathData) -> bool { !std::ptr::eq(was, now) && (was.subpaths.len() != now.subpaths.len() || was.subpaths.iter().zip(&now.subpaths).any(|(w, p)| { - w.closed != p.closed || w.anchors.len() != p.anchors.len() || w.anchors.iter().zip(&p.anchors).any(|(a, b)| !same(a, b)) + w.closed != p.closed || w.anchors.len() != p.anchors.len() || w.anchors.pairs_not_shared(&p.anchors).any(|(_, a, b)| !same(a, b)) })) } diff --git a/crates/render/src/paint.rs b/crates/render/src/paint.rs index c130fbe346..8650ae7886 100644 --- a/crates/render/src/paint.rs +++ b/crates/render/src/paint.rs @@ -258,9 +258,13 @@ fn reduction(bytes: &[u8], allowance: u64) -> Option { return None; } let to = fitted_dims(w, h, allowance)?; - // A PNG that isn't interlaced is read a row at a time when the reader's buffers fit the allowance. + // A PNG that isn't interlaced or animated (and upright in pre-pixel EXIF) is read a row at a time when the reader's buffers fit the allowance. let row_scratch = if format == image::ImageFormat::Png { - png_reader(bytes).filter(|r| !r.info().interlaced).and_then(|r| png_row_scratch(&r)).filter(|&s| s <= allowance) + let streamed = craft_image_codecs::PngDecodeRows::new_streaming(bytes, &png_streaming_limits(allowance)) + .ok() + .filter(|dec| dec.streamable()) + .and_then(|dec| png_row_scratch(&dec.header())); + streamed.or_else(|| png_row_scratch_from_header(bytes, w, h, d.total_bytes())).filter(|&s| s <= allowance) } else { None }; @@ -272,6 +276,13 @@ fn reduction(bytes: &[u8], allowance: u64) -> Option { (rows || d.total_bytes() <= allowance).then_some(Reduction { size: (w, h), to, rows, scratch }) } +/// Streaming retains rows, not the declared full image. Preserve the renderer's source-pixel +/// allowance even when RGBA16's declared samples exceed the shared whole-image default budget. +/// Row scratch and the reduced pixmap are admitted separately before decoding starts. +fn png_streaming_limits(source_pixels: u64) -> craft_image_codecs::Limits { + craft_image_codecs::Limits { max_width: u32::MAX, max_height: u32::MAX, max_pixels: source_pixels, max_alloc: source_pixels.saturating_mul(8) } +} + /// How many rows of an image decoded whole [`reduced_pixmap`] converts to RGBA at a time. const BAND: u32 = 16; @@ -283,17 +294,58 @@ const PNG_KEPT_ROWS: u64 = 128 << 10; /// stream buffer grows by. const PNG_WINDOW_AND_STEP: u64 = (32 << 10) + (8 << 10); -/// The most memory `r` takes in its buffers to read its image a row at a time: the stream buffer -/// holds the rows already read up to [`PNG_KEPT_ROWS`] or four rows, whichever is more, the previous -/// and current rows, and [`PNG_WINDOW_AND_STEP`]. The buffer grows by doubling its reservation, -/// and while it grows its old reservation and the new one, up to twice the size it holds, are both -/// allocated: three times that size at most. A copy of a stored row and the row given out come on -/// top. `None` when a row given out doesn't fit memory. -fn png_row_scratch(r: &png::Reader>) -> Option { - let info = r.info(); - // A filter byte and the row's samples, in whole bytes. - let stored = 1 + (u64::from(info.width) * info.color_type.samples() as u64 * info.bit_depth as u64).div_ceil(8); - let out = u64::try_from(r.output_line_size(info.width)?).ok()?; +/// The most memory `craft-image-codecs`'s PNG row decoder takes in its buffers to read its image +/// a row at a time: the stream buffer holds the rows already read up to [`PNG_KEPT_ROWS`] or four +/// rows, whichever is more, the previous and current rows, and [`PNG_WINDOW_AND_STEP`]. The buffer +/// grows by doubling its reservation, and while it grows its old reservation and the new one, up +/// to twice the size it holds, are both allocated: three times that size at most. A copy of a +/// stored row and the row given out come on top. `None` when a row given out doesn't fit memory. +fn png_row_scratch(hdr: &craft_image_codecs::PngHeader) -> Option { + let out = u64::from(hdr.width).checked_mul(hdr.layout.channels() as u64)?.checked_mul(hdr.sample.bytes() as u64)?; + png_row_scratch_for_row(out) +} + +/// The row decoder rejects a truncated PNG's tiny IDAT before it can report its header. For a +/// size estimate, the image decoder still gives us the declared output bytes; use those only when +/// the PNG header says it is a static, non-interlaced image, the format the renderer can stream. +fn png_row_scratch_from_header(bytes: &[u8], width: u32, height: u32, total_bytes: u64) -> Option { + const SIG: &[u8; 8] = b"\x89PNG\r\n\x1a\n"; + if bytes.get(..8)? != SIG || height == 0 || !total_bytes.is_multiple_of(u64::from(height)) { + return None; + } + let mut at = 8usize; + let mut header = false; + loop { + let len = u32::from_be_bytes(bytes.get(at..at + 4)?.try_into().ok()?) as usize; + let kind = bytes.get(at + 4..at + 8)?; + let data_at = at.checked_add(8)?; + let end = data_at.checked_add(len)?; + let data = bytes.get(data_at..end)?; + match kind { + b"IHDR" if len == 13 && !header => { + header = true; + if at != 8 + || u32::from_be_bytes(data[..4].try_into().ok()?) != width + || u32::from_be_bytes(data[4..8].try_into().ok()?) != height + || data[12] != 0 + { + return None; + } + } + b"acTL" | b"eXIf" => return None, + b"IDAT" if header => { + let row = total_bytes / u64::from(height); + return row.checked_add(1).and_then(png_row_scratch_for_row); + } + _ => {} + } + at = end.checked_add(4)?; // CRC + } +} + +fn png_row_scratch_for_row(out: u64) -> Option { + // A filter byte and the row's samples. + let stored = 1u64.checked_add(out)?; let kept = (stored * 4).next_multiple_of(64).max(PNG_KEPT_ROWS); let stream = kept + stored * 2 + PNG_WINDOW_AND_STEP; Some(stream * 3 + stored + out) @@ -313,14 +365,6 @@ fn fitted_dims(w: u32, h: u32, allowance: u64) -> Option<(u32, u32)> { (u64::from(nw) * u64::from(nh) * 4 <= allowance).then_some((nw, nh)) } -/// A PNG reader of `bytes` that gives 8-bit gray, gray with alpha, RGB or RGBA rows, with its -/// header and the chunks before the pixels read. -fn png_reader(bytes: &[u8]) -> Option>> { - let mut d = png::Decoder::new(std::io::Cursor::new(bytes)); - d.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16); - d.read_info().ok() -} - /// `bytes` decoded at the size [`reduction`] gives. Each pixel of the result is the mean of the /// image's pixels it covers. [`Undecoded::Unreadable`] when they can't be read, and /// [`Undecoded::NoRoom`] when the result and what reading takes ([`Reduction::scratch`]) don't fit @@ -335,19 +379,64 @@ fn reduced_pixmap(bytes: &[u8], r: &Reduction) -> Result Option { + shrunk_with_png_limits(bytes, r, &png_streaming_limits(allowance())) +} + +fn shrunk_with_png_limits(bytes: &[u8], r: &Reduction, png_limits: &craft_image_codecs::Limits) -> Option { let mut shrink = Shrink::new(r.size, r.to); if r.rows { - let mut reader = png_reader(bytes)?; - let (color, _) = reader.output_color_type(); - while let Some(row) = reader.next_row().ok()? { - let data = row.data(); - match color { - png::ColorType::Grayscale => shrink.row(data.iter().map(|&g| [g, g, g, 255])), - png::ColorType::GrayscaleAlpha => shrink.row(data.as_chunks::<2>().0.iter().map(|&[g, a]| [g, g, g, a])), - png::ColorType::Rgb => shrink.row(data.as_chunks::<3>().0.iter().map(|&[r, g, b]| [r, g, b, 255])), - png::ColorType::Rgba => shrink.row(data.as_chunks::<4>().0.iter().copied()), - png::ColorType::Indexed => return None, - } + use craft_image_codecs::{ChannelLayout, CodecError, Format, PngDecodeRows, SampleType}; + let mut dec = PngDecodeRows::new_streaming(bytes, png_limits).ok()?; + if !dec.streamable() { + return None; + } + let hdr = dec.header(); + // Yield after each row and stop once all pixels have arrived. The pinned decoder's + // first tail batch only locates a text chunk; later batches inflate/retain its value. + // Never run those batches: the renderer needs pixels, not ancillary text. Its underlying + // PNG reader also ignores text chunks before IDAT, so neither location retains text. + for _ in 0..hdr.height { + let _extras = dec + .step_stream::(1, &mut || false, &mut |_y, row| { + match (hdr.layout, hdr.sample) { + (ChannelLayout::Gray, SampleType::U8) => shrink.row(row.iter().map(|&g| [g, g, g, 255])), + (ChannelLayout::GrayA, SampleType::U8) => shrink.row(row.as_chunks::<2>().0.iter().map(|&[g, a]| [g, g, g, a])), + (ChannelLayout::Rgb, SampleType::U8) => shrink.row(row.as_chunks::<3>().0.iter().map(|&[r, g, b]| [r, g, b, 255])), + (ChannelLayout::Rgba, SampleType::U8) => shrink.row(row.as_chunks::<4>().0.iter().copied()), + (ChannelLayout::Gray, SampleType::U16) => shrink.row(row.as_chunks::<2>().0.iter().map(|&g| { + let v = (u16::from_ne_bytes(g) >> 8) as u8; + [v, v, v, 255] + })), + (ChannelLayout::GrayA, SampleType::U16) => shrink.row(row.as_chunks::<4>().0.iter().map(|&[g0, g1, a0, a1]| { + let g = (u16::from_ne_bytes([g0, g1]) >> 8) as u8; + let a = (u16::from_ne_bytes([a0, a1]) >> 8) as u8; + [g, g, g, a] + })), + (ChannelLayout::Rgb, SampleType::U16) => shrink.row(row.as_chunks::<6>().0.iter().map(|&[r0, r1, g0, g1, b0, b1]| { + [ + (u16::from_ne_bytes([r0, r1]) >> 8) as u8, + (u16::from_ne_bytes([g0, g1]) >> 8) as u8, + (u16::from_ne_bytes([b0, b1]) >> 8) as u8, + 255, + ] + })), + (ChannelLayout::Rgba, SampleType::U16) => { + shrink.row(row.as_chunks::<8>().0.iter().map(|&[r0, r1, g0, g1, b0, b1, a0, a1]| { + [ + (u16::from_ne_bytes([r0, r1]) >> 8) as u8, + (u16::from_ne_bytes([g0, g1]) >> 8) as u8, + (u16::from_ne_bytes([b0, b1]) >> 8) as u8, + (u16::from_ne_bytes([a0, a1]) >> 8) as u8, + ] + })) + } + _ => { + return Err(CodecError::Unsupported { format: Format::Png, reason: "unsupported PNG channel layout".into() }); + } + } + Ok(()) + }) + .ok()?; } } else { let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok()?; @@ -589,6 +678,58 @@ mod tests { assert_eq!(room_for(MAX_DECODE_ALLOC, MAX_DECODE_ALLOC), Ok(())); } + #[test] + fn streaming_header_accepts_rgba16_above_whole_image_default() { + // Header-only fixture: opening the stream checks declared size without allocating or + // decoding the 1.2 GB canvas. Padding meets the decoder's compressed-size plausibility + // bound; no rows are requested from this deliberately incomplete image. + let (w, h) = (10_000u32, 15_000u32); + let mut bytes = b"\x89PNG\r\n\x1a\n".to_vec(); + let ihdr = [&b"IHDR"[..], &w.to_be_bytes(), &h.to_be_bytes(), &[16, 6, 0, 0, 0]].concat(); + let mut idat = b"IDAT\x78\x9c".to_vec(); + idat.resize(1_200_000, 0); + for chunk in [&ihdr[..], &idat, b"IEND"] { + bytes.extend((chunk.len() as u32 - 4).to_be_bytes()); + bytes.extend(chunk); + let mut crc = flate2::Crc::new(); + crc.update(chunk); + bytes.extend(crc.sum().to_be_bytes()); + } + let default = craft_image_codecs::Limits { max_alloc: 1 << 30, max_pixels: 150_000_000, ..Default::default() }; + assert!(craft_image_codecs::PngDecodeRows::new_streaming(&bytes, &default).is_err()); + let rows = craft_image_codecs::PngDecodeRows::new_streaming(&bytes, &png_streaming_limits(150_000_000)).unwrap(); + assert_eq!((rows.header().width, rows.header().height), (w, h)); + assert!(rows.streamable()); + assert!(craft_image_codecs::PngDecodeRows::new_streaming(&bytes, &png_streaming_limits(149_999_999)).is_err()); + } + + #[test] + fn streaming_reduction_does_not_retain_text_after_pixels() { + let mut bytes = Vec::new(); + striped(8).write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + let mut chunk = b"tEXtComment\0".to_vec(); + chunk.extend(std::iter::repeat_n(b'x', 1 << 20)); + // PNG's IEEE CRC over type and payload, kept local to this fixture. + let mut crc = u32::MAX; + for &byte in &chunk { + crc ^= u32::from(byte); + for _ in 0..8 { + crc = (crc >> 1) ^ (0xedb88320 & 0u32.wrapping_sub(crc & 1)); + } + } + let mut tail = ((chunk.len() - 4) as u32).to_be_bytes().to_vec(); + tail.extend(chunk); + tail.extend((!crc).to_be_bytes()); + bytes.splice(bytes.len() - 12..bytes.len() - 12, tail); + let limits = craft_image_codecs::Limits { max_alloc: 1 << 19, ..Default::default() }; + let mut full = craft_image_codecs::PngDecodeRows::new_streaming(&bytes, &limits).unwrap(); + assert!(full.step_stream::(1, &mut || true, &mut |_, _| Ok(())).is_err()); + // The renderer stops after the pixels instead of retaining ancillary text. + let reduced = shrunk_with_png_limits(&bytes, &Reduction { size: (8, 1), to: (4, 1), rows: true, scratch: 0 }, &limits).unwrap(); + assert_eq!((reduced.width(), reduced.height()), (4, 1)); + assert!(red_at_its_coverage(&reduced)); + } + /// 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]) }) diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 99fa434ca3..b562e85865 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -1883,14 +1883,14 @@ fn a_png_past_the_allowance_draws_at_reduced_size() { assert_eq!((pm.width(), pm.height(), [c.r, c.g, c.b, c.a]), (300, 300, [200, 40, 40, 255])); // A row is read only while the reader's buffers fit the allowance, counting the stream buffer // three times for the moment it grows. Below 4,096 columns of 16-bit RGBA they take 516,103 - // bytes and 60 a column: 1,398 columns take 599,983 bytes, within 600,000, and 1,399 columns - // take 600,043 and are not decoded (their samples, 8 bytes a pixel, are past it too). + // bytes plus 64 bytes a column: 1,310 columns take 599,943 bytes, within 600,000, and 1,311 + // columns take 600,007 and are not decoded (their samples, 8 bytes a pixel, are past it too). let wide = |w: u32| { let img = image::ImageBuffer::, _>::from_pixel(w, 60, image::Rgba([51400, 10280, 10280, 65535])); encoded(image::DynamicImage::ImageRgba16(img), image::ImageFormat::Png) }; - assert_eq!(with_allowance(600_000, || paint::reduced_size(&wide(1398))), Some((1398, 60))); - assert_eq!(with_allowance(600_000, || paint::reduced_size(&wide(1399))), None); + assert_eq!(with_allowance(600_000, || paint::reduced_size(&wide(1310))), Some((1310, 60))); + assert_eq!(with_allowance(600_000, || paint::reduced_size(&wide(1311))), None); // An image of more pixels than the allowance has bytes is not read: 1,000 × 400 8-bit gray // pixels are drawn at 500 × 200 within 400,000 bytes, and 1,000 × 401 are not. let gray = |h: u32| encoded(image::DynamicImage::ImageLuma8(image::GrayImage::from_pixel(1000, h, image::Luma([90]))), image::ImageFormat::Png); @@ -1938,13 +1938,13 @@ fn a_reduced_decode_counts_what_reading_takes_beside_the_images_paints_hold() { // Decoded whole: 14,400 bytes of RGB and a 16-row band of 8,960 bytes, beside a 73 × 54 result // of 15,768 bytes. let jpeg = encoded(image::DynamicImage::ImageRgb8(image::RgbImage::from_pixel(80, 60, image::Rgb([30, 120, 200]))), image::ImageFormat::Jpeg); - // Read a row at a time: 540,103 bytes in the reader's buffers for 400 columns of 16-bit RGBA, + // Read a row at a time: 541,703 bytes in the reader's buffers for 400 columns of 16-bit RGBA, // beside a 387 × 387 result of 599,076 bytes. let png = encoded( image::DynamicImage::ImageRgba16(image::ImageBuffer::from_pixel(400, 400, image::Rgba([51400, 10280, 10280, 65535]))), image::ImageFormat::Png, ); - for (bytes, allowance, room, size) in [(&jpeg, 16_000, 15_768 + 14_400 + 8_960, (73, 54)), (&png, 600_000, 599_076 + 540_103, (387, 387))] { + for (bytes, allowance, room, size) in [(&jpeg, 16_000, 15_768 + 14_400 + 8_960, (73, 54)), (&png, 600_000, 599_076 + 541_703, (387, 387))] { let failed = decode_failures(); let none = with_allowance(allowance, || with_room(room - 1, || paint::decode_pixmap_or_why(bytes))); assert_eq!(none.err(), Some(paint::Undecoded::NoRoom), "not decoded with a byte too few, and tried again later"); diff --git a/crates/render/src/tests/keptpath.rs b/crates/render/src/tests/keptpath.rs index e7097c4850..12e87f272b 100644 --- a/crates/render/src/tests/keptpath.rs +++ b/crates/render/src/tests/keptpath.rs @@ -140,7 +140,7 @@ fn a_long_path_draws_and_culls_after_each_edit_as_when_its_path_is_made_again() }), ("that anchor moved off it", |p| moved(&mut p.subpaths[0].anchors[1535], Vec2::new(5.0, 5.0))), ("a doubled anchor moved off its twin", |p| moved(&mut p.subpaths[0].anchors[1536], Vec2::new(0.0, -12.0))), - ("1,200 anchors moved", |p| p.subpaths[0].anchors[..1200].iter_mut().for_each(|a| moved(a, Vec2::new(2.0, 1.0)))), + ("1,200 anchors moved", |p| p.subpaths[0].anchors.iter_mut().take(1200).for_each(|a| moved(a, Vec2::new(2.0, 1.0)))), ("an anchor added", |p| _ = p.subpaths[0].insert_anchor(1520, 0.5)), ("an anchor deleted", |p| _ = p.subpaths[0].anchors.remove(1521)), ("the subpath closed", |p| p.subpaths[0].closed = true), @@ -454,7 +454,7 @@ fn random_edit(g: &mut Seeded, p: &mut PathData) -> String { match g.below(3) { 0 => moved(&mut sp.anchors[at], Vec2::new(g.offset(30), g.offset(30))), 1 => sp.anchors[at].h_out = sp.anchors[at].p + Vec2::new(g.offset(10), g.offset(10)), - _ => sp.anchors[at..].iter_mut().take(n / 10).for_each(|a| moved(a, Vec2::new(1.0, -1.0))), + _ => sp.anchors.iter_mut().skip(at).take(n / 10).for_each(|a| moved(a, Vec2::new(1.0, -1.0))), } format!("anchors moved at {at} of subpath {s} of {n}") } @@ -486,7 +486,7 @@ fn same_as_made_again(k: &mut crate::kept_paths::KeptPath, n: &Arc, st: &S fn random_edits_of_a_long_path_keep_what_making_its_path_again_makes() { let st = stroke(6.0, LineJoin::Miter, LineCap::Butt); let mut g = Seeded(5744); - let closed = |sp: SubPath| SubPath::new(sp.anchors, true); + let closed = |sp: SubPath| SubPath::of(sp.anchors, true); let path = PathData::new(vec![ zigzag(2, 11_990.0), closed(zigzag(3, 12_000.0)), @@ -517,7 +517,7 @@ fn random_edits_of_a_long_compound_path_keep_what_making_its_path_again_makes() Arc::new(Node::path(NodeId(ids.get()), p, Appearance::default())) }; let children = vec![ - member(PathData::new(vec![SubPath::new(zigzag(3, 11_990.0).anchors, true), zigzag(5, 12_010.0)])), + member(PathData::new(vec![SubPath::of(zigzag(3, 11_990.0).anchors, true), zigzag(5, 12_010.0)])), member(PathData::single(zigzag(3000, 0.0))), member(PathData::single(ring(40, Point::new(12_000.0, 15.0), 30.0))), member(PathData::single(zigzag(2, 12_020.0))), diff --git a/crates/svg/src/export/output.rs b/crates/svg/src/export/output.rs index 36f215d032..818a64e293 100644 --- a/crates/svg/src/export/output.rs +++ b/crates/svg/src/export/output.rs @@ -500,8 +500,8 @@ impl Writer<'_> { /// `` when its radii are written the same, else ``. fn ellipse_shape(&self, sp: &SubPath, m: Affine) -> Option<(&'static str, String)> { let tol = 10f64.powi(-i32::from(self.opts.decimals)); - let (anchors, closed) = (sp.anchors.as_slice(), sp.closed); - let [a0, a1, a2, a3] = anchors else { return None }; + let (anchors, closed) = (sp.anchors.contiguous(), sp.closed); + let [a0, a1, a2, a3] = &*anchors else { return None }; let [p0, p1, p2, p3] = [a0.p, a1.p, a2.p, a3.p].map(|p| m * p); let c = p0.midpoint(p2); let near = |a: f64, b: f64| (a - b).abs() <= tol; diff --git a/crates/svg/src/export/paint.rs b/crates/svg/src/export/paint.rs index bedf456f11..f52a701867 100644 --- a/crates/svg/src/export/paint.rs +++ b/crates/svg/src/export/paint.rs @@ -37,9 +37,25 @@ pub(super) enum StrokePlan { Written(Written), } +/// Visit `n` and the descendants the writer draws ([`Writer::node_body`]): a hidden layer or object +/// and what it holds only with `hidden` (SVG Options › hidden layers kept), and a template layer's +/// art never. +fn walk_drawn<'a>(n: &'a Node, hidden: bool, f: &mut impl FnMut(&'a Node)) { + if !(n.visible || hidden) { + return; + } + f(n); + if matches!(n.kind, NodeKind::Layer { template: true, .. }) { + return; + } + for c in n.children().into_iter().flatten() { + walk_drawn(c, hidden, f); + } +} + impl Writer<'_> { pub(super) fn count_colorized_images(&mut self, art: &Node) { - art.walk(&mut |n| { + walk_drawn(art, self.opts.hidden_layers, &mut |n| { let NodeKind::Image(im) = &n.kind else { return }; let Some(Paint::Solid { color, .. }) = n.extras().colorize.as_deref() else { return }; let shown = self.doc.shown_image(n, im); @@ -176,7 +192,7 @@ impl Writer<'_> { self.count_colorized_images(art); // Each image's count and its first piece, which shows what they all show. let mut seen: HashMap<(String, u32, u32), (usize, vectorcraft_doc::ImageObject)> = HashMap::new(); - art.walk(&mut |c| { + walk_drawn(art, self.opts.hidden_layers, &mut |c| { if let NodeKind::Image(im) = &c.kind { let shown = self.doc.shown_image(c, im); let im = &*shown; @@ -604,25 +620,41 @@ impl Writer<'_> { let mut inner = n.clone(); inner.appearance.effects.retain(|e| !vectorcraft_effects::is_raster(&e.id)); // An SVG filter's user-space coordinates are the document's from the effect's origin: the - // object is written in them, in a group that moves it where the rest of the art goes. + // object is written in them, in a group that moves it where the rest of the art goes. A + // user space that is scaled or turned ([`turned_filter_space`]) is the group's own: the + // object is written as it is in a group inside the filter that maps it back + // ([`Self::open_filters`]), so its strokes keep their widths. let xf = self.xf; - let origin = live_svg_filter(&n.appearance.effects).map(|f| Affine::translate(f.origin())); + let live = live_svg_filter(&n.appearance.effects); + let turned = self.turned_filter_space(live.as_ref()); + let origin = live.filter(|_| turned.is_none()).map(|f| Affine::translate(f.origin())); let moved = origin.is_some_and(|o| xf * o != Affine::IDENTITY); if let Some(o) = origin.filter(|_| moved) { self.line(&format!("", self.matrix(xf * o))); self.depth += 1; self.xf = o.inverse(); } + if let Some(space) = turned { + self.line(&format!("", exact_matrix(space))); + self.depth += 1; + } let opened = self.open_filters(n, &n.appearance.effects); self.node_body(&inner); self.close_filters(opened); - if moved { + if moved || turned.is_some() { self.xf = xf; self.depth -= 1; self.line(""); } } + /// The group transform that holds a live SVG filter `live` ([`live_svg_filter`]) whose user + /// space is scaled or turned (not only moved, [`vectorcraft_effects::svg_filter::SvgFilterFx::moves_only`]): the filter's user + /// space in the output's. `None` for other filters and in SVG Tiny, which writes no filters. + fn turned_filter_space(&self, live: Option<&vectorcraft_effects::svg_filter::SvgFilterFx>) -> Option { + live.filter(|f| !f.moves_only() && !self.tiny()).map(|f| self.xf * f.to_doc()) + } + /// Open one `` per visible raster effect of `effects` (an object's, or one fill or /// stroke's) on `n`, outermost last effect; returns how many to close. pub(super) fn open_filters(&mut self, n: &Node, effects: &[vectorcraft_doc::Effect]) -> usize { @@ -644,6 +676,7 @@ impl Writer<'_> { let mut opened = 0; // An SVG filter that is the object's last effect is written as it is ([`Self::filtered`]). let live = if std::ptr::eq(effects, n.appearance.effects.as_slice()) { live_svg_filter(effects) } else { None }; + let turned = self.turned_filter_space(live.as_ref()); for (k, f) in fx.iter().enumerate().rev() { if let RasterFx::Pixel(vectorcraft_effects::PixelFx::Svg(sf)) = f && live.is_some() @@ -654,12 +687,40 @@ impl Writer<'_> { // against the object alone, which is all it runs on ([`live_svg_filter`]). let mut input = n.clone(); input.appearance.effects.clear(); - let input_bounds = input.visual_bounds_with(&self.doc.symbol_boxes()).unwrap_or_default(); - if let Some(def) = sf.written_xml(input_bounds).and_then(|xml| vectorcraft_effects::svg_filter::with_id(&xml, &fid)) { - self.def(1, &def); + // Its box in the filter's user space: in a turned or skewed one, the box of the + // object's geometry turned into it, grown by what its strokes and other paint add + // around it in the document: a square that far to each side, as it measures in + // user space along each axis (a miter corner reaches that far along both). + let symbols = self.doc.symbol_boxes(); + let visual = input.visual_bounds_with(&symbols).unwrap_or_default(); + let user_box = if sf.moves_only() { + visual - sf.origin() + } else { + let geometric = input.geometric_bounds_with(&symbols).unwrap_or(visual); + let margin = [geometric.x0 - visual.x0, geometric.y0 - visual.y0, visual.x1 - geometric.x1, visual.y1 - geometric.y1] + .into_iter() + .fold(0.0, f64::max); + let to_user = sf.to_doc().inverse(); + input.transform(to_user, false); + let [a, b, c, d, _, _] = to_user.as_coeffs(); + let turned = input.geometric_bounds_with(&symbols).unwrap_or_default(); + turned.inflate(margin * (a.abs() + c.abs()), margin * (b.abs() + d.abs())) + }; + let def = sf.written_xml(user_box).and_then(|xml| vectorcraft_effects::svg_filter::with_id(&xml, &fid)); + if let Some(def) = &def { + self.def(1, def); self.line(&format!("")); self.depth += 1; opened += 1; + } + // Inside the group of a turned user space ([`Self::filtered`]), the object and its + // other effects are written as they are, in a group that maps them back to it. + if let Some(space) = turned { + self.line(&format!("", exact_matrix(space.inverse()))); + self.depth += 1; + opened += 1; + } + if def.is_some() { continue; } } @@ -786,8 +847,18 @@ pub(super) fn pixel_gradient(p: &Paint, fill: bool) -> Option<&GradientPaint> { } } +/// `a` as an SVG `matrix(…)` with every digit its numbers need to read back the same, whatever +/// the export's decimals: the transforms around a turned SVG filter ([`Writer::turned_filter_space`]) +/// and their inverses still undo each other when one holds very small numbers. +fn exact_matrix(a: Affine) -> String { + // (Without negative zeros.) + let [a, b, c, d, e, f] = a.as_coeffs().map(|v| v + 0.0); + format!("matrix({a} {b} {c} {d} {e} {f})") +} + /// The SVG filter (Effect › SVG Filters) of an object's `effects` that SVG keeps as a ``: -/// its last visible effect, measured in points. +/// its last visible effect, in any user space the effect gives it ([`Writer::turned_filter_space`]) +/// that SVG import can store again. fn live_svg_filter(effects: &[vectorcraft_doc::Effect]) -> Option { if !vectorcraft_effects::svg_filter::writes_live(effects) { return None; @@ -797,7 +868,7 @@ fn live_svg_filter(effects: &[vectorcraft_doc::Effect]) -> Option + if (alone || !f.measured()) && f.writes_as_svg11() && f.opens_again() => { Some(f) } diff --git a/crates/svg/src/export/text.rs b/crates/svg/src/export/text.rs index 2f8e8b8a1b..f325387033 100644 --- a/crates/svg/src/export/text.rs +++ b/crates/svg/src/export/text.rs @@ -86,11 +86,15 @@ impl Writer<'_> { // type with warichu, whose stacked lines a reader's can't place either. So are // small capitals, superscript and subscript and tab leaders, which SVG text doesn't draw (#3869), // and a glyph chosen for a character, which a reader's draws with the default glyph. So - // is type in one of the document's composite fonts, which a reader can't find by its name. + // is type in one of the document's composite fonts, which a reader can't find by its name, + // and type with an Adjust Diacritic Position, whose marks a reader's draws where the + // font puts them. let unwritable = t.runs.iter().any(|r| { r.style.small_caps.is_some() || r.style.position != vectorcraft_doc::CharPosition::Normal || r.style.glyph_alternate.is_some() + || r.style.diacritic_horizontal != 0.0 + || r.style.diacritic_vertical != 0.0 || vectorcraft_doc::CompositeFont::named(&doc.composite_fonts, &r.style.font_family).is_some() }) || std::iter::once(&t.para).chain(&t.paras).any(|p| p.tabs.iter().any(|tab| !tab.leader.is_empty())); let outlined = self.opts.outline_text diff --git a/crates/svg/src/import/files.rs b/crates/svg/src/import/files.rs index c60d22f983..8b612f78c1 100644 --- a/crates/svg/src/import/files.rs +++ b/crates/svg/src/import/files.rs @@ -875,7 +875,8 @@ fn raster(format: image::ImageFormat) -> Option { /// 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, with the resolution the file declares -/// ([`vectorcraft_doc::ppi::resolution`]), its axes swapped by a quarter turn. A CMYK TIFF also +/// ([`vectorcraft_doc::ppi::resolution`]), its axes swapped by a quarter turn, and the ICC profile +/// the file carries when its color space is the written samples' (gray or RGB). 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 @@ -893,7 +894,7 @@ fn shown(bytes: Arc>, format: image::ImageFormat) -> Option { return Some(Shown { kind, bytes, cmyk: None }); } let tiff = image::guess_format(&bytes).ok() == Some(F::Tiff); - let mut img = if tiff { tiff_pixels(&bytes)? } else { decoded(&bytes, format)? }; + let (mut img, icc) = 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); @@ -906,18 +907,38 @@ fn shown(bytes: Arc>, format: image::ImageFormat) -> Option { if let Some(orientation) = orientation { img.apply_orientation(orientation); } + use image::DynamicImage as D; + let img = match img { + D::ImageLuma8(_) | D::ImageLumaA8(_) | D::ImageRgb8(_) | D::ImageRgba8(_) => img, + D::ImageLuma16(_) | D::ImageLumaA16(_) | D::ImageRgb16(_) | D::ImageRgba16(_) => img, + other => D::ImageRgba8(other.into_rgba8()), + }; let mut png = Vec::new(); - img.write_to(&mut std::io::Cursor::new(&mut png), F::Png).ok()?; + let mut encoder = image::codecs::png::PngEncoder::new(&mut png); + if let Some(icc) = icc.filter(|icc| png_takes_icc(&img, icc)) { + // A profile the encoder doesn't take leaves the image without one. + let _ = image::ImageEncoder::set_icc_profile(&mut encoder, icc); + } + img.write_with_encoder(encoder).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 }) } +/// Can a PNG of `img`'s samples carry ICC profile `icc`? Its color space must be the samples': +/// `GRAY` for gray samples, `RGB ` for RGB ones. +fn png_takes_icc(img: &image::DynamicImage, icc: &[u8]) -> bool { + let want = if img.color().has_color() { *b"RGB " } else { *b"GRAY" }; + vectorcraft_doc::cmyk::icc_color_space(icc) == Some(want) +} + /// The pixels of encoded image `bytes` (`format` when their bytes don't say), as stored, decoded /// within [`vectorcraft_doc::MAX_RASTER_ALLOC`], counted as decoded and as RGBA, as Open and Place -/// decode them; `None` when they can't be. -fn decoded(bytes: &[u8], format: image::ImageFormat) -> Option { +/// decode them, with the ICC profile their samples are in when the file carries one the decoder +/// can read (a TIFF's read by [`vectorcraft_doc::cmyk::tiff_icc_profile`]); `None` when they +/// can't be. +fn decoded(bytes: &[u8], format: image::ImageFormat) -> Option<(image::DynamicImage, Option>)> { use image::ImageDecoder as _; let max = vectorcraft_doc::MAX_RASTER_ALLOC; let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok()?; @@ -927,12 +948,16 @@ fn decoded(bytes: &[u8], format: image::ImageFormat) -> Option max || u64::from(w) * u64::from(h) * 4 > max { return None; } - image::DynamicImage::from_decoder(decoder).ok() + // The image decoder reads a TIFF's tags within the size of its pixels, so a small TIFF's + // profile is read by the TIFF decoder itself. + let icc = if tiff { vectorcraft_doc::cmyk::tiff_icc_profile(bytes) } else { decoder.icc_profile().ok().flatten() }; + Some((image::DynamicImage::from_decoder(decoder).ok()?, icc)) } /// The pixels of TIFF `bytes`, as stored, read as Open and Place read them: a TIFF with extra @@ -940,15 +965,17 @@ fn decoded(bytes: &[u8], format: image::ImageFormat) -> Option Option { +/// ([`vectorcraft_doc::cmyk::stored_cmyk_tiff`]). Pixels the image decoder reads come with the +/// TIFF's ICC profile; the other readers give sRGB pixels, without one. `None` when they can't be +/// read. +fn tiff_pixels(bytes: &[u8]) -> Option<(image::DynamicImage, Option>)> { use image::DynamicImage::ImageRgba8; let cms = vectorcraft_color::cms::active(); if let Some(img) = vectorcraft_doc::cmyk::extra_samples_tiff_rgba(bytes, |c| cms.cmyk_to_srgb(c, false)) { - return Some(ImageRgba8(img)); + return Some((ImageRgba8(img), None)); } if let Some(read) = vectorcraft_doc::cmyk::group3_tiff_rgba(bytes) { - return read.ok().map(ImageRgba8); + return read.ok().map(|img| (ImageRgba8(img), None)); } decoded(bytes, image::ImageFormat::Tiff).or_else(|| decoded(&vectorcraft_doc::cmyk::stored_cmyk_tiff(bytes, None)?, image::ImageFormat::Tiff)) } diff --git a/crates/svg/src/import/fx.rs b/crates/svg/src/import/fx.rs index 4a549552d4..08e2dfeb9a 100644 --- a/crates/svg/src/import/fx.rs +++ b/crates/svg/src/import/fx.rs @@ -142,19 +142,22 @@ fn source_of<'a>(filter: &Filter, sources: &'a HashMap) -> Optio /// XML from `sources` ([`sources`]), in user space mapped to the document by `ts`. `None` when one /// isn't there, looks different outside the document, or isn't a filter the effect draws /// ([`vectorcraft_effects::svg_filter::check`]), or -/// when `ts` turns or skews the user space or scales it past what the effect measures (0.001 to -/// 1000 points to a unit). Where `ts` moves the user space is the effect's `origin`. +/// when `ts` scales the user space past what the effect measures (0.001 to 1000 points to a unit, +/// as the square root of its area scale) or stretches its axes past what the effect's `axes` hold. +/// Where `ts` moves the user space is the effect's `origin`; a user space that `ts` turns, skews +/// or scales unevenly keeps those directions in the effect's `axes`, so the filter runs in the +/// element's own user space as SVG 1.1 defines it (). pub(super) fn kept(filters: &[Arc], ts: Affine, sources: &HashMap) -> Option> { - let [a, b, c, d, e, f] = ts.as_coeffs(); - if b != 0.0 || c != 0.0 || !(0.001..=1000.0).contains(&a) || (a - d).abs() > 1e-9 * a.abs().max(1.0) || !e.is_finite() || !f.is_finite() { - return None; - } + let space = vectorcraft_effects::svg_filter::user_space(ts)?; filters .iter() .map(|filter| { // A filter styled by the document is left out rather than drawn differently. let source = source_of(filter, sources).filter(|s| !s.styled)?; - let params = json!({ "name": source.name()?, "xml": source.xml, "scale": a, "origin": [e, f] }); + let mut params = json!({ "name": source.name()?, "xml": source.xml, "scale": space.scale, "origin": space.origin }); + if let Some(axes) = space.axes { + params["axes"] = json!(axes); + } Some(Effect { id: vectorcraft_effects::SVG_FILTER.into(), params, visible: true }) }) .collect() @@ -312,9 +315,51 @@ impl V { } } -/// σ of a blur with standard deviations `x`, `y` (their mean: the effects blur evenly). -fn sd(x: f32, y: f32) -> f64 { - (x as f64 + y as f64) / 2.0 +/// σ of a blur with standard deviations `x`, `y` in a user space the document scales by the same +/// amount in every direction when `even` (turned, flipped or scaled alike along both axes). The +/// effects blur evenly: `None` when the blur differs by direction in the document, unless `blurs` +/// is [`Blurs::Nearest`], which takes the mean. +fn sd(x: f32, y: f32, even: bool, blurs: Blurs) -> Option { + let uneven = (x > 0.0 || y > 0.0) && (x != y || !even); + (blurs == Blurs::Nearest || !uneven).then_some((x as f64 + y as f64) / 2.0) +} + +/// How [`effects`] reads a blur that differs by direction in the document, which the effects +/// draw the same in every direction. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Blurs { + /// Not as an effect: the filter is left for an SVG Filters effect ([`kept`]), which draws it. + Exact, + /// As the even blur of the mean standard deviation. + Nearest, +} + +/// Whether the linear part of `ts` scales every direction by the same amount (a turn, a flip and +/// an even scale), so an even blur stays even in the document. +fn even_space(ts: Affine) -> bool { + let [a, b, c, d, _, _] = ts.as_coeffs(); + let tol = 1e-9 * ts.determinant().abs().sqrt().max(1.0); + let near = |p: f64, q: f64| (p - q).abs() <= tol; + (near(a, d) && near(b, -c)) || (near(a, -d) && near(b, c)) +} + +/// `filters` (in the order they apply) imported in user space mapped to the document by `ts`: as +/// the live effects they draw as ([`effects`]), else as SVG Filters effects that keep their XML +/// ([`kept`]), else as the live effects nearest them (a blur that differs by direction drawn as +/// an even one). With whether they are live effects. `None` when none of these takes them. +pub(super) fn imported( + filters: &[Arc], + ts: Affine, + blends: &HashMap, + sources: &HashMap, +) -> Option<(Vec, bool)> { + if let Some(fx) = effects(filters, ts, blends, Blurs::Exact) { + return Some((fx, true)); + } + if let Some(fx) = kept(filters, ts, sources) { + return Some((fx, false)); + } + effects(filters, ts, blends, Blurs::Nearest).map(|fx| (fx, true)) } fn color(c: usvg::Color) -> Color { @@ -361,9 +406,10 @@ fn transferred(v: V, [r, g, b, a]: [&TransferFunction; 4], srgb: bool) -> Option } } -/// Evaluate one filter's primitives, `k` the scale from its user space to the document. +/// Evaluate one filter's primitives, `k` the scale from its user space to the document, `even` +/// when that scale is the same in every direction ([`even_space`]), blurs read as `blurs` says. /// `None` when one does something the effects cannot represent. -fn eval(f: &Filter, k: f64) -> Option { +fn eval(f: &Filter, k: f64, even: bool, blurs: Blurs) -> Option { let mut results: HashMap<&str, V> = HashMap::new(); let mut last = V::Graphic; for p in f.primitives() { @@ -377,7 +423,7 @@ fn eval(f: &Filter, k: f64) -> Option { let v = match p.kind() { Kind::GaussianBlur(b) => { let linear = p.color_interpolation() == ColorInterpolation::LinearRGB; - input(b.input())?.blur(sd(b.std_dev_x().get(), b.std_dev_y().get()), linear)? + input(b.input())?.blur(sd(b.std_dev_x().get(), b.std_dev_y().get(), even, blurs)?, linear)? } Kind::Offset(o) => input(o.input())?.offset(o.dx() as f64, o.dy() as f64)?, Kind::Flood(fl) => V::Flood(color(fl.color()), fl.opacity().get()), @@ -447,8 +493,8 @@ fn eval(f: &Filter, k: f64) -> Option { } } Kind::DropShadow(d) if matches!(input(d.input())?, V::Graphic) => { - let shape = - Shape { sd: sd(d.std_dev_x().get(), d.std_dev_y().get()), dx: d.dx() as f64, dy: d.dy() as f64, moved: true, inverted: false }; + let sd = sd(d.std_dev_x().get(), d.std_dev_y().get(), even, blurs)?; + let shape = Shape { sd, dx: d.dx() as f64, dy: d.dy() as f64, moved: true, inverted: false }; V::Stack(vec![V::Paint { shape, color: color(d.color()), opacity: d.opacity().get(), clipped: false }, V::Graphic]) } _ => return None, @@ -460,10 +506,12 @@ fn eval(f: &Filter, k: f64) -> Option { } /// The live effects `filters` (in the order they apply) stand for, in user space mapped to the -/// document by `ts`; `blends`: the modes our export recorded ([`blends`]). `None` when one of -/// them isn't an effect the canvas draws. -pub(super) fn effects(filters: &[Arc], ts: Affine, blends: &HashMap) -> Option> { +/// document by `ts`; `blends`: the modes our export recorded ([`blends`]); `blurs`: how a blur +/// that differs by direction reads ([`Blurs`]). `None` when one of them isn't an effect the +/// canvas draws. +fn effects(filters: &[Arc], ts: Affine, blends: &HashMap, blurs: Blurs) -> Option> { let k = ts.determinant().abs().sqrt(); + let even = even_space(ts); let [a, b, c, d, _, _] = ts.as_coeffs(); let along = |dx: f64, dy: f64| Vec2::new(a * dx + c * dy, b * dx + d * dy); let num = |v: f64| (v * 1000.0).round() / 1000.0; @@ -472,7 +520,7 @@ pub(super) fn effects(filters: &[Arc], ts: Affine, blends: &HashMap continue, // SVG blurs in linear light unless the filter asks for sRGB (`color-interpolation-filters`). V::Blurred(sd, true) => ("blur.gaussian", json!({ "radius": blur(sd), "linear": true })), diff --git a/crates/svg/src/import/importer.rs b/crates/svg/src/import/importer.rs index 2eede1f7be..ebafbb1346 100644 --- a/crates/svg/src/import/importer.rs +++ b/crates/svg/src/import/importer.rs @@ -243,48 +243,59 @@ impl Importer { if !matches!(kids.get(main), Some(usvg::Node::Path(p)) if p.is_visible()) { return Some(vec![]); } - let text::PendingText { name, mut obj, servers, paints, non_scaling, under, .. } = self.slots.texts.get(i)?.clone(); - // The scale the type draws at becomes its size (last, below): text space grows by `grow`. - let xf = ts * obj.xf; - let grow = text::size_scale(&obj, xf); - // usvg resolved the `url(#…)` paints (the paths after the main one) in the element's user - // space; runs paint in text space. - let to_text = Affine::scale(grow) * obj.xf.inverse(); + let text::PendingText { name, obj, servers, rest, paints, non_scaling, under, .. } = self.slots.texts.get(i)?.clone(); let slot_paint = |im: &mut Self, k: usize, m: Affine| match kids.get(main + 1 + k) { Some(usvg::Node::Path(p)) => p.fill().map_or(Paint::None, |f| im.paint(f.paint(), m)), _ => Paint::None, }; - let resolved: Vec = (0..paints).map(|k| slot_paint(self, k, to_text)).collect(); - let server = |k: usize| resolved.get(k).cloned().unwrap_or(Paint::None); - for (run, (fill, stroke)) in obj.runs.iter_mut().zip(servers) { - if let Some(k) = fill { - run.style.fill = server(k); + // A text split into several objects becomes a group of them, named after the element. + let whole = rest.is_empty(); + let mut skewed = false; + let mut nodes = Vec::with_capacity(rest.len() + 1); + for (mut obj, servers) in std::iter::once((obj, servers)).chain(rest) { + // The scale the type draws at becomes its size (last, below): text space grows by `grow`. + let xf = ts * obj.xf; + let grow = text::size_scale(&obj, xf); + // usvg resolved the `url(#…)` paints (the paths after the main one) in the element's user + // space; runs paint in text space. + let to_text = Affine::scale(grow) * obj.xf.inverse(); + let resolved: Vec = (0..paints).map(|k| slot_paint(self, k, to_text)).collect(); + let server = |k: usize| resolved.get(k).cloned().unwrap_or(Paint::None); + for (run, (fill, stroke)) in obj.runs.iter_mut().zip(servers) { + if let Some(k) = fill { + run.style.fill = server(k); + } + if let Some(k) = stroke { + run.style.stroke = server(k); + } } - if let Some(k) = stroke { - run.style.stroke = server(k); + obj.xf = xf; + skewed |= non_scaling && !vector_effect::unscale_text(&mut obj, self.screen); + // A stroke under the characters is the object's own: it paints in the document. + let under = under.clone().map(|(mut sl, k)| { + if let Some(k) = k { + sl.paint = slot_paint(self, k, ts); + } + let mut ap = Appearance { items: vec![AppearanceItem::Stroke(sl)], ..Default::default() }; + ap.scale_strokes(if non_scaling { self.screen } else { obj.xf.determinant().abs().sqrt() }); + ap.set_contents_at(1); + ap + }); + text::fold_scale(&mut obj, grow); + let mut n = self.named(if whole { &name } else { "" }, NodeKind::Text(Box::new(obj)))?; + if let Some(ap) = under { + n.appearance = ap.into(); } + nodes.push(Arc::new(n)); } - obj.xf = xf; - if non_scaling && !vector_effect::unscale_text(&mut obj, self.screen) { + if skewed { let label = if name.is_empty() || made_up(&name) { "a text".to_string() } else { format!("text '{name}'") }; self.warn(format!("non-scaling stroke on {label} approximated: the text is stretched or skewed")); } - // A stroke under the characters is the object's own: it paints in the document. - let under = under.map(|(mut sl, k)| { - if let Some(k) = k { - sl.paint = slot_paint(self, k, ts); - } - let mut ap = Appearance { items: vec![AppearanceItem::Stroke(sl)], ..Default::default() }; - ap.scale_strokes(if non_scaling { self.screen } else { obj.xf.determinant().abs().sqrt() }); - ap.set_contents_at(1); - ap - }); - text::fold_scale(&mut obj, grow); - let mut n = self.named(&name, NodeKind::Text(Box::new(obj)))?; - if let Some(ap) = under { - n.appearance = ap.into(); + if whole { + return Some(nodes); } - Some(vec![Arc::new(n)]) + Some(vec![Arc::new(self.named(&name, NodeKind::Group { children: nodes, clip: false })?)]) } fn group_node(&mut self, g: &usvg::Group, acc: Affine) -> Option { @@ -303,11 +314,11 @@ impl Importer { (None, id) => format!("'{id}'"), }; let mask = g.mask().and_then(|m| self.opacity_mask(m, ts, &label)); - // Blurs, shadows and glows become live effects (see [`fx`]); other filters become Effect › - // SVG Filters effects that keep their XML. + // Blurs, shadows and glows become live effects (see [`fx`]); other filters, and blurs that + // differ by direction in the document, become Effect › SVG Filters effects that keep their XML. let effects = match g.filters() { [] => vec![], - filters => fx::effects(filters, ts, &self.blends).or_else(|| fx::kept(filters, ts, &self.filter_sources)).unwrap_or_else(|| { + filters => fx::imported(filters, ts, &self.blends, &self.filter_sources).map(|(fx, _)| fx).unwrap_or_else(|| { // usvg wraps a filtered element in a group of its own: name the element then. let on = match g.children() { [usvg::Node::Group(_)] | [] => label.clone(), @@ -383,7 +394,7 @@ impl Importer { /// () cuts a filter's result at /// its region. A filter that didn't import (drawn without it) clips nothing. fn filter_regions(&mut self, g: &usvg::Group, ts: Affine, mut n: Node) -> Option { - if g.filters().is_empty() || fx::effects(g.filters(), ts, &self.blends).is_none() { + if g.filters().is_empty() || !fx::imported(g.filters(), ts, &self.blends, &self.filter_sources).is_some_and(|(_, live)| live) { return Some(n); } for f in g.filters() { @@ -584,7 +595,8 @@ impl Importer { if p.id().is_empty() || !p.is_visible() || p.fill().is_some_and(|f| f.rule() == usvg::FillRule::EvenOdd) { return None; } - let mut obj = self.slots.texts.get(self.slots.find(p)?)?.obj.clone(); + // A text split into several objects clips by its outlines. + let mut obj = self.slots.texts.get(self.slots.find(p)?).filter(|t| t.rest.is_empty())?.obj.clone(); obj.xf = m * self.slots.inner(p) * obj.xf; let grow = text::size_scale(&obj, obj.xf); for run in &mut obj.runs { diff --git a/crates/svg/src/import/text.rs b/crates/svg/src/import/text.rs index ef3934c2d6..d783c04319 100644 --- a/crates/svg/src/import/text.rs +++ b/crates/svg/src/import/text.rs @@ -130,6 +130,7 @@ const BIDI_NESTED: &str = "a unicode-bidi embedding inside another imported one const BIDI_TEXT_OVERRIDE: &str = "unicode-bidi override on the text imported as its paragraph direction; directional override is not supported"; /// One character of a text and the adjustments its position needs. +#[derive(Clone)] struct Cell { ch: char, style: CharStyle, @@ -178,6 +179,9 @@ pub(super) struct PendingText { pub obj: TextObject, /// For each run, the index of its fill's and stroke's `url(#…)` paint, if any. pub servers: Vec<(Option, Option)>, + /// The other point type objects of a text whose absolutely placed characters one object cannot + /// put on their x ([`split`]), after `obj` in text order, each with its runs' paint indices. + pub rest: Vec<(TextObject, Vec)>, /// Number of `url(#…)` paints (the placeholder paths after the main one, in order). pub paints: usize, /// `vector-effect="non-scaling-stroke"`: the character strokes keep their width on screen. @@ -233,7 +237,14 @@ impl TextSlots { return Some(bp.clone()); } let t = self.texts.get(i)?; - let bp = Rc::new(vectorcraft_text::layout(FontDb::global(), &t.obj).to_bezpath()); + let mut bp = vectorcraft_text::layout(FontDb::global(), &t.obj).to_bezpath(); + // The other objects of a split text, in the first one's text space. + for (o, _) in &t.rest { + let mut more = vectorcraft_text::layout(FontDb::global(), o).to_bezpath(); + more.apply_affine(t.obj.xf.inverse() * o.xf); + bp.extend(more.elements().iter().copied()); + } + let bp = Rc::new(bp); self.outlines.borrow_mut().insert(i, bp.clone()); Some(bp) } @@ -534,7 +545,10 @@ fn use_slot( shown.build(style_xml, style_t, &label, &mut found) }; let differs = |(text, paints): &(PendingText, Vec)| { - slots.texts.get(shared).is_none_or(|old| old.obj != text.obj || old.servers != text.servers || old.under != text.under) + slots + .texts + .get(shared) + .is_none_or(|old| old.obj != text.obj || old.servers != text.servers || old.rest != text.rest || old.under != text.under) || inst.paints.get(shared) != Some(paints) }; let slot = built.filter(differs).map(|(text, paints)| { @@ -1337,7 +1351,7 @@ impl Ctx { } let marker = Rect::new(b.x0, b.y0, b.x1.max(b.x0 + 1.0), b.y1.max(b.y0 + 1.0)); let name = t.attribute("id").unwrap_or("").to_string(); - Some((PendingText { name, obj, servers, paints: 0, non_scaling: false, under: None, marker }, Vec::new())) + Some((PendingText { name, obj, servers, rest: vec![], paints: 0, non_scaling: false, under: None, marker }, Vec::new())) } /// Read one ``: the pending text and its `url(#…)` paints. @@ -1469,6 +1483,7 @@ impl Ctx { let mut obj = TextObject::point(Point::ZERO, "", CharStyle::default()); let mut breaks: Vec = vec![]; let mut para_styles: Vec = vec![]; + let mut rest = vec![]; if let Some((tp, followed)) = path { let bp = &followed.path; // Along the path: dx is extra advance, dy shifts off the path. @@ -1549,46 +1564,37 @@ impl Ctx { obj.kind = TextKind::OnPath { path: PathData::from_bezpath(&bp), start: 0.0, end: None }; 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, unplaced) = lines(&mut cells, &x, &y, &dx, &dy, &anchor_of, &pin, origin.x, &mut breaks); - if unplaced > 0 { + let whole = cells.clone(); + let mut ys = vec![]; + let (b, p, unplaced) = place(&mut cells, &x, &y, &dx, &dy, &anchor_of, &pin, &mut obj, &mut ys); + (breaks, para_styles) = (b, p); + if !unplaced.is_empty() { + // One object cannot put every absolutely placed character on its x: the text becomes + // several, the first of them `obj`. + let mut pieces = split(&whole, &x, &y, &dx, &dy, &ys, &anchor_of, &pin, unplaced).into_iter(); + if let Some(first) = pieces.next() { + (obj, cells, breaks, para_styles) = (first.obj, first.cells, first.breaks, first.paras); + } + rest = pieces + .map(|mut p| { + let servers = finish(&mut p.obj, &p.cells, &p.breaks, p.paras, &pin); + (p.obj, servers) + }) + .collect(); warnings.push(format!( - "{label}: {unplaced} absolutely placed character(s) between characters of the other direction keep their place in the line" + "{label}: imported as {} point type objects in a group, since one object cannot put every character on its own x", + rest.len() + 1 )); } - obj.para.justify = justify; - obj.xf = Affine::translate((finite(left), finite(origin.y))); - // Lines anchored differently or at different x (paragraphs aligned or indented - // differently): each line's paragraph takes its alignment, and indents that put it - // where it was. - if starts.iter().any(|&(_, a, ax)| a != starts[0].1 || ax != starts[0].2) { - for (k, &(_, a, ax)) in starts.iter().enumerate() { - let d = finite(ax - left); - let mut pa = ParaStyle { justify: justify_of(a), ..ParaStyle::default() }; - match pa.justify { - Justify::Center if d >= 0.0 => pa.left_indent = 2.0 * d, - Justify::Center => pa.right_indent = -2.0 * d, - Justify::Right => pa.right_indent = -d, - _ => pa.left_indent = d, - } - let count = if k == 0 { 1 } else { breaks.get(k - 1).map_or(1, |b| b.count) }; - para_styles.extend(std::iter::repeat_n(pa, count)); - } - } } - let (runs, servers) = assemble(&cells, &breaks).0; - obj.runs = runs; - if !para_styles.is_empty() { - obj.set_paragraph_styles(para_styles); - } - pin(&mut obj); - keep_reader_anchors(&mut obj); + let servers = finish(&mut obj, &cells, &breaks, para_styles, &pin); // The placeholder covers the text (laid out when a paint server needs its bounding box). - let b = if paints.is_empty() { obj.bounds() } else { Some(obj.xf.transform_rect_bbox(measure(&obj).bounds)) }.unwrap_or_default(); + let bounds = |o: &TextObject| if paints.is_empty() { o.bounds() } else { Some(o.xf.transform_rect_bbox(measure(o).bounds)) }; + let b = rest.iter().filter_map(|(o, _)| bounds(o)).fold(bounds(&obj), |all, b| Some(all.map_or(b, |a| a.union(b)))).unwrap_or_default(); let marker = Rect::new(b.x0, b.y0, b.x1.max(b.x0 + 1.0), b.y1.max(b.y0 + 1.0)); let name = t.attribute("id").unwrap_or("").to_string(); let non_scaling = vector_effect::is_non_scaling(&self.css, t); - Some((PendingText { name, obj, servers, paints: paints.len(), non_scaling, under, marker }, paints)) + Some((PendingText { name, obj, servers, rest, paints: paints.len(), non_scaling, under, marker }, paints)) } } @@ -1683,13 +1689,145 @@ fn leading_tolerance(spacing: f64) -> f64 { 0.01_f64.min(spacing.abs() * 1e-3) } +/// Point type `obj` of `cells` placed by the positioning lists ([`lines`]): sets its justification +/// and transform, and returns its line breaks, its paragraph styles and the absolutely placed +/// characters kerning cannot put on their x. `ys` takes each character's line baseline and y. +#[allow(clippy::too_many_arguments)] +fn place( + cells: &mut [Cell], + x: &[Option], + y: &[Option], + dx: &[f64], + dy: &[f64], + anchor_of: &dyn Fn(usize) -> f64, + pin: &dyn Fn(&mut TextObject), + obj: &mut TextObject, + ys: &mut Vec<(f64, f64)>, +) -> (Vec, Vec, Vec) { + let mut breaks = vec![]; + let mut para_styles = vec![]; + let origin = Point::new(x[0].unwrap_or(0.0) + dx[0], y[0].unwrap_or(0.0) + dy[0]); + let (justify, left, starts, unplaced) = lines(cells, x, y, dx, dy, anchor_of, pin, origin.x, &mut breaks, ys); + obj.para.justify = justify; + obj.xf = Affine::translate((finite(left), finite(origin.y))); + // Lines anchored differently or at different x (paragraphs aligned or indented + // differently): each line's paragraph takes its alignment, and indents that put it + // where it was. + if starts.iter().any(|&(_, a, ax)| a != starts[0].1 || ax != starts[0].2) { + for (k, &(_, a, ax)) in starts.iter().enumerate() { + let d = finite(ax - left); + let mut pa = ParaStyle { justify: justify_of(a), ..ParaStyle::default() }; + match pa.justify { + Justify::Center if d >= 0.0 => pa.left_indent = 2.0 * d, + Justify::Center => pa.right_indent = -2.0 * d, + Justify::Right => pa.right_indent = -d, + _ => pa.left_indent = d, + } + let count = if k == 0 { 1 } else { breaks.get(k - 1).map_or(1, |b| b.count) }; + para_styles.extend(std::iter::repeat_n(pa, count)); + } + } + (breaks, para_styles, unplaced) +} + +/// Gives `obj` the runs of `cells` with `breaks`, its paragraph styles and its paragraph +/// directions; returns the paint indices of its runs. +fn finish(obj: &mut TextObject, cells: &[Cell], breaks: &[Break], para_styles: Vec, pin: &dyn Fn(&mut TextObject)) -> Vec { + let (runs, servers) = assemble(cells, breaks).0; + obj.runs = runs; + if !para_styles.is_empty() { + obj.set_paragraph_styles(para_styles); + } + pin(obj); + keep_reader_anchors(obj); + servers +} + +/// One point type object of a text [`split`] into several, before [`finish`]. +struct Piece { + obj: TextObject, + cells: Vec, + breaks: Vec, + paras: Vec, +} + +/// How many times [`split`] cuts a piece before the characters kerning cannot place; a piece that +/// still has such characters is then cut before each of its chunks. +const MAX_SPLITS: usize = 3; + +/// Point type objects, in text order, that together put every absolutely placed character of +/// `cells` (before [`place`] kerned them) on its x. SVG anchors each chunk on its own and reorders +/// right-to-left characters only within a chunk (SVG 2 › Text, https://www.w3.org/TR/SVG2/text.html), +/// while one object reorders the whole +/// line: a left-to-right character drawn right before a right-to-left one has no kerning between +/// them. The text is cut before each character `unplaced` lists, and each piece placed again. `ys` +/// holds each character's line baseline and y, so that a piece keeps its characters' baselines. +#[allow(clippy::too_many_arguments)] +fn split( + cells: &[Cell], + x: &[Option], + y: &[Option], + dx: &[f64], + dy: &[f64], + ys: &[(f64, f64)], + anchor_of: &dyn Fn(usize) -> f64, + pin: &dyn Fn(&mut TextObject), + unplaced: Vec, +) -> Vec { + let piece = |r: Range| { + let s = r.start; + let mut cells = cells[r.clone()].to_vec(); + let (base, cur) = ys.get(s).copied().unwrap_or((0.0, 0.0)); + // The piece starts on its line's baseline, and its first character keeps its own y. + cells[0].style.baseline_shift += base - cur; + let py: Vec> = r + .clone() + .map(|i| match i - s { + 0 => Some(base), + 1 => y[i].or(Some(cur)), + _ => y[i], + }) + .collect(); + let mut pdy = dy[r.clone()].to_vec(); + pdy[0] = 0.0; + let mut obj = TextObject::point(Point::ZERO, "", CharStyle::default()); + let (breaks, paras, unplaced) = place(&mut cells, &x[r.clone()], &py, &dx[r], &pdy, &|j| anchor_of(s + j), pin, &mut obj, &mut vec![]); + (Piece { obj, cells, breaks, paras }, unplaced.into_iter().map(|j| s + j).collect::>()) + }; + let mut done = vec![]; + let mut todo = vec![(0..cells.len(), unplaced, 0)]; + while let Some((range, failed, round)) = todo.pop() { + // Past the last round every chunk of the piece is a piece of its own, and so has no + // characters to place. + let mut cuts: Vec = if round < MAX_SPLITS { failed } else { (range.start + 1..range.end).filter(|&i| x[i].is_some()).collect() }; + cuts.sort_unstable(); + cuts.dedup(); + let mut from = range.start; + for to in cuts.into_iter().chain([range.end]) { + if to <= from || to > range.end { + continue; + } + match piece(from..to) { + (p, failed) if failed.is_empty() => done.push((from, p)), + (_, failed) => todo.push((from..to, failed, round + 1)), + } + from = to; + } + } + done.sort_by_key(|p| p.0); + done.into_iter().map(|p| p.1).collect() +} + +/// A line's first character, alignment (as for [`justify_of`]) and anchor x. +type LineStart = (usize, f64, f64); + /// Point type: line breaks, baseline shifts and kerning from the positioning lists. Returns the /// justification, the x of the first line's left (or anchor) edge and each line's first /// 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. Also returns how many absolutely placed characters kerning -/// cannot put on their x. +/// and its anchor x is its left edge. Also returns the absolutely placed characters kerning cannot +/// put on their x. `ys` takes each character's line baseline and y. #[allow(clippy::too_many_arguments)] fn lines( cells: &mut [Cell], @@ -1701,10 +1839,13 @@ fn lines( pin: &dyn Fn(&mut TextObject), x0: f64, breaks: &mut Vec, -) -> (Justify, f64, Vec<(usize, f64, f64)>, usize) { + ys: &mut Vec<(f64, f64)>, +) -> (Justify, f64, Vec, Vec) { let n = cells.len(); let y0 = y[0].unwrap_or(0.0) + dy[0]; let (mut base, mut cur) = (y0, y0); + ys.clear(); + ys.push((y0, y0)); // Line starts (first character, anchor x) and absolutely placed characters (index, x). let mut lines = vec![(0, x0)]; let mut targets: Vec<(usize, f64)> = vec![]; @@ -1723,9 +1864,11 @@ fn lines( breaks.push(Break { at: i, count: count as usize, leading: gap / count }); lines.push((i, ax + dx[i])); (base, cur) = (ny, ny); + ys.push((base, cur)); continue; } cur = ny; + ys.push((base, cur)); match x[i] { Some(ax) => targets.push((i, ax + dx[i])), None => cells[i - 1].kern += dx[i], @@ -1744,7 +1887,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, 0); + return (justify_of(anchor_of(0)), x0, starts, vec![]); } // 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 @@ -1774,7 +1917,7 @@ fn lines( 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; + let mut unplaced = vec![]; // Kerning changes shaping (pair kerning is off for manually kerned characters): repeat until // every character sits on its x. for round in 0..4 { @@ -1811,7 +1954,7 @@ fn lines( // character's horizontal scale, so each correction is divided by it. let mut worst = 0.0f64; let mut from = 0; - unplaced = 0; + unplaced.clear(); while from < wants.len() { let l = line_of(wants[from].0); let to = from + wants[from..].partition_point(|&(i, _)| line_of(i) == l); @@ -1831,35 +1974,35 @@ fn lines( .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(); + let mut points: Vec<(usize, f64, f64, usize)> = + on_line.iter().filter_map(|&(i, want)| pens[i].map(|p| (2 * p.rank + 2, p.start, want, i))).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..] { + for &(place, start, want, i) 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; + unplaced.push(i); } 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() { + for &(place, start, want, i) 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; + unplaced.push(i); } prev = place; } @@ -2064,7 +2207,8 @@ fn pens(lay: &TextLayout, bytes: &[usize], cells: &[Cell]) -> Vec> { .collect() } -type Key = (Option, Option); +/// The indices of a run's fill and stroke `url(#…)` paints. +pub(super) type Key = (Option, Option); type Runs = (Vec, Vec); /// Runs (and their paint indices) from the characters, with `breaks` inserted; also the byte offset diff --git a/crates/svg/tests/it/clip_text.rs b/crates/svg/tests/it/clip_text.rs index bb92802e60..4cbcc9a812 100644 --- a/crates/svg/tests/it/clip_text.rs +++ b/crates/svg/tests/it/clip_text.rs @@ -125,6 +125,20 @@ fn a_text_clip_path_with_a_clip_rule_or_a_clip_of_its_own_clips_by_its_outlines( assert_eq!(shapes[0].1, vectorcraft_geom::FillRule::EvenOdd); } +#[test] +fn a_text_imported_as_several_objects_clips_by_all_their_outlines() { + // One object cannot put ג on its x, so the text is several objects; the clip outlines all of them. + let d = open( + r##"אbג + "##, + ); + let (clip, _) = clip_group(&top(&d)[0]); + assert!(!matches!(clip.kind, NodeKind::Text(_)), "{:?}", clip.kind); + let b = clip_bounds(clip); + // ג ends at 220, the first object at 160. + assert!(b.x1 > 200.0 && b.x1 <= 220.0 + 1e-6 && b.x0 < 100.0, "{b:?}"); +} + #[test] fn tspans_and_type_on_a_path_clip_too() { let d = open( diff --git a/crates/svg/tests/it/image_orientation.rs b/crates/svg/tests/it/image_orientation.rs index d9de61290b..e824337857 100644 --- a/crates/svg/tests/it/image_orientation.rs +++ b/crates/svg/tests/it/image_orientation.rs @@ -362,6 +362,133 @@ fn a_cmyk_tiff_keeps_its_resolution_turned_or_not() { } } +/// A made-up ICC profile of `len` bytes (at least a header's 128) whose header names the color +/// space `space`; the bytes after the header differ from place to place. +fn icc_profile(space: &[u8; 4], len: usize) -> Vec { + let mut icc: Vec = (0..len).map(|i| (i % 251) as u8).collect(); + icc[..4].copy_from_slice(&u32::try_from(len).unwrap().to_be_bytes()); + icc[12..16].copy_from_slice(b"mntr"); + icc[16..20].copy_from_slice(space); + icc[36..40].copy_from_slice(b"acsp"); + icc +} + +/// `tiff` (little-endian) with an ICCProfile tag (34675, of type UNDEFINED) holding `icc`: its first +/// directory copied to the end of the file with the tag added in order. +fn tiff_with_icc(tiff: &[u8], icc: &[u8]) -> Vec { + let at = usize::try_from(u32::from_le_bytes(tiff[4..8].try_into().unwrap())).unwrap(); + let n = usize::from(u16::from_le_bytes([tiff[at], tiff[at + 1]])); + let mut entries: Vec> = tiff[at + 2..at + 2 + 12 * n].chunks(12).map(<[u8]>::to_vec).collect(); + let mut out = tiff.to_vec(); + if out.len() % 2 == 1 { + out.push(0); + } + let data = u32::try_from(out.len()).unwrap(); + out.extend(icc); + if out.len() % 2 == 1 { + out.push(0); + } + let i = entries.iter().position(|e| u16::from_le_bytes([e[0], e[1]]) > 34675).unwrap_or(n); + let count = u32::try_from(icc.len()).unwrap(); + entries.insert(i, [&34675u16.to_le_bytes()[..], &7u16.to_le_bytes(), &count.to_le_bytes(), &data.to_le_bytes()].concat()); + let ifd = u32::try_from(out.len()).unwrap(); + out[4..8].copy_from_slice(&ifd.to_le_bytes()); + out.extend(u16::try_from(n + 1).unwrap().to_le_bytes()); + out.extend(entries.concat()); + out.extend([0; 4]); + out +} + +/// A little-endian EXIF block (a TIFF header and one directory) giving Orientation `orientation`. +fn exif_block(orientation: u16) -> Vec { + let o = orientation.to_le_bytes(); + [b"II".as_slice(), &[0x2a, 0, 8, 0, 0, 0], &[1, 0], &[0x12, 0x01, 3, 0, 1, 0, 0, 0, o[0], o[1], 0, 0], &[0, 0, 0, 0]].concat() +} + +/// The ICC profile and the bits per sample of the PNG `im` is stored as. +fn stored_icc(d: &Document, im: &ImageObject) -> (Option>, u16) { + use image::ImageDecoder as _; + let blob = &d.images[&im.key]; + assert_eq!(blob.mime, "image/png"); + let mut dec = image::codecs::png::PngDecoder::new(std::io::Cursor::new(blob.bytes.as_slice())).unwrap(); + let color = dec.original_color_type(); + (dec.icc_profile().unwrap(), color.bits_per_pixel() / u16::from(color.channel_count())) +} + +/// A raster that import writes again as PNG keeps the gray or RGB ICC profile its file carries, +/// byte for byte, linked and as a data URL: a TIFF, turned or not, and a turned PNG and JPEG, with +/// 16-bit samples kept at 16 bits and the resolution kept beside the profile. A profile of another +/// color space than the written samples', one too short to be a profile, and one on a TIFF whose +/// pixels are read as RGBA by its own reader are left out, and the image still imports. +#[test] +fn a_raster_written_again_as_png_keeps_its_icc_profile() { + use image::{DynamicImage, ImageEncoder as _}; + let (rgb_icc, gray_icc, cmyk_icc) = (icc_profile(b"RGB ", 600), icc_profile(b"GRAY", 300), icc_profile(b"CMYK", 400)); + let rgb8 = DynamicImage::ImageRgb8(image::RgbImage::from_fn(3, 2, |x, y| image::Rgb([u8::try_from(x * 70 + y * 9).unwrap(), 200, 13]))); + let gray8 = DynamicImage::ImageLuma8(image::GrayImage::from_fn(3, 2, |x, y| image::Luma([u8::try_from(x * 80 + y * 7).unwrap()]))); + let rgb16 = DynamicImage::ImageRgb16(image::ImageBuffer::from_fn(3, 2, |x, y| { + let v = u16::try_from(x * 0x1111 + y * 0x2345).unwrap(); + image::Rgb([0x1000 + v, 0x8001 + v, 0xF0F3 - v]) + })); + let tiff_of = |img: &DynamicImage, icc: &[u8]| { + let mut out = Vec::new(); + let mut enc = image::codecs::tiff::TiffEncoder::new(std::io::Cursor::new(&mut out)); + enc.set_icc_profile(icc.to_vec()).unwrap(); + img.write_with_encoder(enc).unwrap(); + out + }; + let png = { + let mut out = Vec::new(); + let mut enc = image::codecs::png::PngEncoder::new(&mut out); + enc.set_icc_profile(rgb_icc.clone()).unwrap(); + enc.set_exif_metadata(exif_block(6)).unwrap(); + rgb16.write_with_encoder(enc).unwrap(); + out + }; + let jpg = { + let mut out = Vec::new(); + let mut enc = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, 95); + enc.set_icc_profile(rgb_icc.clone()).unwrap(); + rgb8.write_with_encoder(enc).unwrap(); + let exif = [b"Exif\0\0".as_slice(), &exif_block(6)].concat(); + let mut turned = out[..2].to_vec(); + turned.extend([0xff, 0xe1]); + turned.extend(u16::try_from(exif.len() + 2).unwrap().to_be_bytes()); + turned.extend(&exif); + turned.extend(&out[2..]); + turned + }; + let gray = [0, 0, 255, 255, 0, 0, 255, 255]; + let turned_gray = tiff_with_icc(&tiff_at(4, 2, 1, &gray, 6, Some((300, 150))), &gray_icc); + let gray_alpha = [0, 255, 0, 255, 255, 255, 255, 255, 0, 255, 0, 255, 255, 255, 255, 255]; + // (what, file, the ICC profile to keep, bits per sample, resolution) + type Case<'a> = (&'a str, Vec, Option<&'a [u8]>, u16, Option<(f64, f64)>); + let cases: Vec = vec![ + ("RGB TIFF", tiff_of(&rgb8, &rgb_icc), Some(&rgb_icc), 8, None), + ("gray TIFF", tiff_of(&gray8, &gray_icc), Some(&gray_icc), 8, None), + ("16-bit RGB TIFF", tiff_of(&rgb16, &rgb_icc), Some(&rgb_icc), 16, None), + ("gray TIFF, orientation 6, with a resolution", turned_gray, Some(&gray_icc), 8, Some((150.0, 300.0))), + ("16-bit RGB PNG, orientation 6", png, Some(&rgb_icc), 16, None), + ("JPEG, orientation 6", jpg, Some(&rgb_icc), 8, None), + ("RGB TIFF with a gray profile", tiff_of(&rgb8, &gray_icc), None, 8, None), + ("gray TIFF with an RGB profile", tiff_of(&gray8, &rgb_icc), None, 8, None), + ("RGB TIFF with a CMYK profile", tiff_of(&rgb8, &cmyk_icc), None, 8, None), + ("RGB TIFF with a profile too short to be one", tiff_of(&rgb8, &rgb_icc[..40]), None, 8, None), + ("gray TIFF with alpha, read as RGBA", tiff_with_icc(&tiff(4, 2, 2, &gray_alpha, 1), &rgb_icc), None, 8, None), + ]; + let dir = folder("icc"); + for (what, file, icc, bits, ppi) in cases { + std::fs::write(dir.join("photo.img"), &file).unwrap(); + let data = format!("data:;base64,{}", base64_encode(&file)); + for href in ["photo.img", data.as_str()] { + let what = format!("{what}, {}", &href[..href.len().min(12)]); + let (d, im) = import_one(&format!(r#""#), Some(&dir)); + assert_eq!(stored_icc(&d, &im), (icc.map(<[u8]>::to_vec), bits), "{what}"); + assert_eq!(stored_ppi(&d, &im), ppi, "{what}"); + } + } +} + /// 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() { diff --git a/crates/svg/tests/it/import_details.rs b/crates/svg/tests/it/import_details.rs index 3a598f5ca1..239ce7e07a 100644 --- a/crates/svg/tests/it/import_details.rs +++ b/crates/svg/tests/it/import_details.rs @@ -763,14 +763,15 @@ fn percentages_in_a_symbol_are_of_its_view_box() { } /// #1598: the warning for a filter that neither the live effects nor an SVG filter effect can hold -/// (here, on turned objects) names the filter, its primitives and the object, and says it is drawn -/// without it (not "a group": usvg wraps the element in one). Such a filter on an object that -/// isn't turned comes in as an SVG filter effect holding the filter's XML. +/// (here, on objects skewed past what the effect measures) names the filter, its primitives and the +/// object, and says it is drawn without it (not "a group": usvg wraps the element in one). Such a +/// filter on an object that isn't skewed that far comes in as an SVG filter effect holding the +/// filter's XML. #[test] fn unsupported_filters_are_named_in_the_warning() { let body = r#" - - + + "#; let (d, w) = import_with_report(&svg(body)).unwrap(); assert!(w.iter().any(|w| w == "filter 'f' (feColorMatrix) on an object isn't supported; drawn without it"), "{w:?}"); diff --git a/crates/svg/tests/it/import_live.rs b/crates/svg/tests/it/import_live.rs index 1d10c5d9fe..5e1757ae8b 100644 --- a/crates/svg/tests/it/import_live.rs +++ b/crates/svg/tests/it/import_live.rs @@ -284,6 +284,63 @@ fn a_gaussian_blur_becomes_the_effect_with_its_radius() { assert_eq!(effects(&d)[0].params["radius"], json!(12.0)); } +/// A blur that differs by direction in the document (standard deviations that differ, or an even +/// one in a user space scaled unevenly or skewed) is kept as an SVG filter, which draws it as it +/// is, not as an even Gaussian Blur. In a turned, flipped or evenly scaled user space an even blur +/// stays the effect. +#[test] +fn a_blur_that_differs_by_direction_is_kept_as_its_filter() { + let ids = |body: &str| { + let (d, w) = open(body); + assert!(w.is_empty(), "{w:?}"); + effects(&d).iter().map(|e| e.id.clone()).collect::>() + }; + let blur = |sd: &str, transform: &str| { + format!( + r##""## + ) + }; + assert_eq!(ids(&blur("4 1", "translate(0)")), ["svg.filter"]); + assert_eq!(ids(&blur("3", "scale(1 4)")), ["svg.filter"]); + assert_eq!(ids(&blur("3", "skewX(30)")), ["svg.filter"]); + assert_eq!(ids(&blur("3", "rotate(30) scale(2)")), ["blur.gaussian"]); + assert_eq!(ids(&blur("3", "scale(-2 2)")), ["blur.gaussian"]); + let shadow = |sd: &str| { + format!( + r##""## + ) + }; + assert_eq!(ids(&shadow("3 1")), ["svg.filter"]); + assert_eq!(ids(&shadow("3")), ["stylize.dropShadow"]); +} + +/// An SVG filter's blur in a user space scaled unevenly is written live and opens again as the +/// same effect, which blurs more along the stretched axis, not as an even Gaussian Blur. +#[test] +fn an_exported_blur_in_a_stretched_user_space_opens_as_the_same_effect() { + let xml = r#""#; + let mut d = Document::new(200.0, 120.0); + let mut n = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(60.0, 40.0, 140.0, 80.0)), + Appearance::basic(Paint::solid(Color::rgb(0.9, 0.1, 0.1)), Paint::None, 0.0), + ); + let params = json!({ "xml": xml, "scale": 2.0, "origin": [0.0, 0.0], "axes": [0.5, 0.0, 0.0, 2.0] }); + n.appearance.effects = vec![Effect { id: "svg.filter".into(), params, visible: true }]; + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + let out = export(&d, &ExportOptions::default()); + assert!(out.contains(">(), ["svg.filter"], "{out}"); + let num = |v: &serde_json::Value| v.as_f64().unwrap(); + let axes: Vec = fx[0].params["axes"].as_array().unwrap().iter().map(num).collect(); + assert!(axes.iter().zip([0.5, 0.0, 0.0, 2.0]).all(|(a, b)| (a - b).abs() < 1e-6), "{axes:?}"); + assert_similar(&render_artboard(&d), &render_artboard(&back), 40.0, 0.02); +} + /// `color-interpolation-filters` (SVG 1.1 §15.7.6, initially linearRGB: /// https://www.w3.org/TR/SVG11/painting.html#ColorInterpolationFiltersProperty) picks whether the /// blur mixes colours in linear light; sRGB, on the primitive or the filter, keeps them as they @@ -522,7 +579,8 @@ fn a_filter_used_twice_among_many_is_kept_twice() { assert_eq!(filters, vec![vec![json!("g")], vec![json!("g")]], "{:?}", art(&d)); } -/// Other filters come in as SVG filters; one on a turned object is reported and left out. +/// Other filters come in as SVG filters, on a turned or skewed object too, with the object's user +/// space in `scale`, `origin` and `axes`; one past what the effect measures is reported and left out. #[test] fn other_filters_are_kept_or_reported() { let (d, w) = @@ -530,8 +588,32 @@ fn other_filters_are_kept_or_reported() { assert!(w.is_empty(), "{w:?}"); let fx = effects(&d); assert_eq!((fx.len(), fx[0].id.as_str(), &fx[0].params["name"]), (1, "svg.filter", &json!("t"))); + assert!(fx[0].params.get("axes").is_none(), "the document's axes: {:?}", fx[0].params); let (d, w) = open( - r##""##, + r##""##, + ); + assert!(w.is_empty(), "{w:?}"); + let fx = effects(&d); + assert_eq!(fx.len(), 1); + let p = &fx[0].params; + let (c, s) = (30f64.to_radians().cos(), 30f64.to_radians().sin()); + let num = |v: &serde_json::Value| v.as_f64().unwrap(); + assert!((num(&p["scale"]) - 2.0).abs() < 1e-6 && p["origin"] == json!([10.0, 20.0]), "{p}"); + let axes: Vec = p["axes"].as_array().unwrap().iter().map(num).collect(); + assert!(axes.iter().zip([c, s, -s, c]).all(|(a, b)| (a - b).abs() < 1e-6), "{axes:?}"); + // Skewed, and scaled unevenly: the axes keep both. + let (d, w) = open( + r##""##, + ); + assert!(w.is_empty(), "{w:?}"); + let all: Vec> = + art(&d).iter().flat_map(|n| &n.appearance.effects).map(|e| e.params["axes"].as_array().unwrap().iter().map(num).collect()).collect(); + assert_eq!(all.len(), 2); + assert!(all.iter().any(|a| a.iter().zip([1.0, 0.0, 1.0, 1.0]).all(|(a, b)| (a - b).abs() < 1e-6)), "{all:?}"); + assert!(all.iter().any(|a| a.iter().zip([0.5, 0.0, 0.0, 2.0]).all(|(a, b)| (a - b).abs() < 1e-6)), "{all:?}"); + // Skewed so far that an axis would stretch past 1000 times: reported and left out. + let (d, w) = open( + r##""##, ); assert!(w.iter().any(|w| w.contains("filter")), "{w:?}"); assert!(effects(&d).is_empty()); @@ -543,6 +625,40 @@ fn other_filters_are_kept_or_reported() { assert!(effects(&d).is_empty()); } +/// A filter on a turned object runs in the object's user space (SVG 1.1 measures its lengths +/// there): opened, it draws as the same filter does on the same art drawn unturned with its offset +/// turned by hand. +#[test] +fn a_filter_on_a_turned_object_draws_in_its_user_space() { + let filter = |dx: f64, dy: f64| { + format!( + r#""# + ) + }; + let turned = format!( + r##"{}"##, + filter(24.0, 0.0) + ); + let (d, w) = open(&turned); + assert!(w.is_empty(), "{w:?}"); + assert_eq!(effects(&d).iter().map(|e| e.id.as_str()).collect::>(), ["svg.filter"]); + // The same square, its corners turned by hand, with the offset 24 along the turned x axis. + let (c, s) = (30f64.to_radians().cos(), 30f64.to_radians().sin()); + let corner = |x: f64, y: f64| format!("{},{}", 80.0 + c * (x - 80.0) - s * (y - 50.0), 50.0 + s * (x - 80.0) + c * (y - 50.0)); + let reference = format!( + r##"{}"##, + filter(24.0 * c, 24.0 * s), + corner(60.0, 30.0), + corner(100.0, 30.0), + corner(100.0, 70.0), + corner(60.0, 70.0) + ); + let canvas = render_artboard(&d); + // The moved square lies beyond where it was: its center, turned and moved, is near (100.8, 62). + assert!(canvas.over_white(101, 62) != [255, 255, 255], "drawn where the offset puts it"); + assert_similar(&canvas, &resvg_render(&svg(&reference), 200, 120), 40.0, 0.02); +} + #[test] fn a_filter_and_a_clip_on_one_object_filter_first() { let body = r##" @@ -638,6 +754,69 @@ fn filtered_rect(xml: &str) -> Document { d } +/// An SVG filter in a scaled, turned or skewed user space is written live: the filter's user space +/// is a group's transform, and the art is written in document coordinates in a group inside the +/// filter that maps it back, so its stroke keeps its width. Opened again, it is the same effect +/// and draws as the canvas drew it. +#[test] +fn an_exported_turned_filter_opens_as_the_same_effect() { + let xml = r#""#; + for (scale, axes) in [(2.0, json!([0.8, 0.6, -0.6, 0.8])), (1.0, json!([1.0, 0.0, 0.5, 1.0])), (0.5, serde_json::Value::Null)] { + let mut d = Document::new(200.0, 120.0); + let mut n = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(40.0, 20.0, 100.0, 70.0)), + Appearance::basic(Paint::solid(Color::rgb(0.9, 0.1, 0.1)), Paint::solid(Color::BLACK), 4.0), + ); + let mut params = json!({ "xml": xml, "scale": scale, "origin": [30.0, 10.0] }); + if !axes.is_null() { + params["axes"] = axes.clone(); + } + n.appearance.effects = vec![Effect { id: "svg.filter".into(), params, visible: true }]; + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + let out = export(&d, &ExportOptions::default()); + assert!(out.contains(" = fx[0].params["origin"].as_array().unwrap().iter().map(num).collect(); + assert!((origin[0] - 30.0).abs() < 1e-6 && (origin[1] - 10.0).abs() < 1e-6, "{origin:?}"); + match fx[0].params.get("axes") { + Some(got) => { + let got: Vec = got.as_array().unwrap().iter().map(num).collect(); + let want: Vec = axes.as_array().unwrap().iter().map(num).collect(); + assert!(got.iter().zip(&want).all(|(a, b)| (a - b).abs() < 1e-6), "{got:?}"); + } + None => assert!(axes.is_null(), "{:?}", fx[0].params), + } + assert_similar(&render_artboard(&d), &render_artboard(&back), 40.0, 0.02); + } + // A user space stretched 10,000 times along x: the inverse transform holds 0.0001, which the + // export's three decimals would round to 0, and the art still opens at its place. + let mut d = Document::new(200.0, 120.0); + let mut n = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(40.0, 20.0, 100.0, 70.0)), + Appearance::basic(Paint::solid(Color::rgb(0.9, 0.1, 0.1)), Paint::None, 0.0), + ); + let xml = r#""#; + let params = json!({ "xml": xml, "scale": 10.0, "axes": [1000.0, 0.0, 0.0, 1.0] }); + n.appearance.effects = vec![Effect { id: "svg.filter".into(), params, visible: true }]; + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + let out = export(&d, &ExportOptions::default()); + let (back, w) = import_with_report(&out).unwrap(); + assert!(w.is_empty(), "{w:?}"); + let bounds = |d: &Document| art(d).iter().find_map(|n| n.path_data().and_then(|p| p.bounds())).unwrap(); + let (a, b) = (bounds(&d), bounds(&back)); + assert!((a.x0 - b.x0).abs() < 1e-3 && (a.x1 - b.x1).abs() < 1e-3 && (a.y1 - b.y1).abs() < 1e-3, "{a:?} {b:?}: {out}"); +} + /// SVG 1.1 export writes an SVG filter's image reference as `xlink:href`, and it imports back. #[test] fn an_exported_filter_image_has_an_xlink_reference() { diff --git a/crates/svg/tests/it/import_text.rs b/crates/svg/tests/it/import_text.rs index fa91f8d162..c8a1cfd4ed 100644 --- a/crates/svg/tests/it/import_text.rs +++ b/crates/svg/tests/it/import_text.rs @@ -974,7 +974,7 @@ fn absolutely_placed_right_to_left_characters_sit_on_their_own_x() { 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")); + let unplaced = |w: &[String]| w.iter().any(|w| w.contains("point type objects")); for (body, share, chunks) in cases { let (d, w) = import_with_report(&svg(&body)).unwrap(); assert!(!unplaced(&w), "{body}: {w:?}"); @@ -988,12 +988,82 @@ fn absolutely_placed_right_to_left_characters_sit_on_their_own_x() { 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}"); +} + +/// The document-space edges of character `ch`, in whichever text of `d` holds it (as +/// [`chunk_edges`] measures them), and the y it is drawn at (its baseline moved by its baseline +/// shift). +fn char_edges(d: &Document, ch: char) -> (f64, f64, f64) { + let t = texts(d).into_iter().find(|t| t.plain_text().contains(ch)).unwrap_or_else(|| panic!("no text holds {ch}")); + let at = t.plain_text().find(ch).unwrap(); + let (left, right) = chunk_edges(t, at..at + ch.len_utf8()); + let shift = t.runs.iter().find(|r| r.text.contains(ch)).unwrap().style.baseline_shift; + let y = layout(FontDb::global(), t).glyphs.iter().find(|g| g.byte == at).map(|g| (t.xf * g.origin).y).unwrap() - shift; + (left, right, y) +} + +/// SVG 2 › Text (https://www.w3.org/TR/SVG2/text.html): each absolute position starts a chunk, +/// and bidi reordering happens only within a chunk. A left-to-right character drawn right before a +/// right-to-left one has no kerning between them in one text object, so such a text imports as a +/// group of point type objects, each character on its own x. +#[test] +fn absolutely_placed_characters_one_object_cannot_place_import_as_a_group() { + // (markup, the characters of its objects in order, each character with the x its right edge + // sits on and its baseline) + type Case = (&'static str, &'static str, Vec<(char, f64, f64)>); + let cases: Vec = vec![ + ( + r#"אbג"#, + "אbג", + vec![('א', 100.0, 80.0), ('b', 160.0, 80.0), ('ג', 220.0, 80.0)], + ), + ( + r#"אbגd"#, + "אbגd", + vec![('א', 100.0, 80.0), ('b', 160.0, 80.0), ('ג', 220.0, 80.0), ('d', 280.0, 80.0)], + ), + // x values that decrease. + ( + r#"אbג"#, + "אbג", + vec![('א', 220.0, 80.0), ('b', 160.0, 80.0), ('ג', 100.0, 80.0)], + ), + // On a second line, and with a baseline of its own. + ( + r#"אבגbד"#, + "אבגbד", + vec![('א', 40.0, 40.0), ('ג', 100.0, 80.0), ('b', 160.0, 80.0), ('ד', 220.0, 90.0)], + ), + ]; + for (body, text, chars) in cases { + let (d, w) = import_with_report(&svg(body)).unwrap(); + assert!(w.iter().any(|w| w.contains("point type objects in a group")), "{body}: {w:?}"); + let top = d.layers[0].children().unwrap(); + assert_eq!(top.len(), 1, "{body}: {top:?}"); + assert_eq!(top[0].name.as_deref(), Some("t"), "{body}: the group takes the element's id"); + let NodeKind::Group { children, clip: false } = &top[0].kind else { panic!("{body}: {:?}", top[0].kind) }; + assert!(children.len() > 1 && children.iter().all(|c| matches!(c.kind, NodeKind::Text(_))), "{body}: {children:?}"); + let all: String = texts(&d).iter().map(|t| t.plain_text().replace('\n', "")).collect(); + assert_eq!(all, text, "{body}: every character once, in order"); + for (ch, x, y) in chars { + let (left, right, base) = char_edges(&d, ch); + assert!(close(right, x, 0.05), "{body}: {ch} spans {left}..{right}, not ending at {x}"); + assert!(close(base, y, 1e-6), "{body}: {ch} sits on {base}, not {y}"); + } + } + // Placed characters one object can place stay one object, also when their x values decrease. + for (body, chars) in [ + (r#"אbc"#, [('א', 100.0), ('b', 160.0), ('c', 220.0)]), + (r#"אבג"#, [('א', 220.0), ('ב', 160.0), ('ג', 100.0)]), + ] { + let (d, w) = import_with_report(&svg(body)).unwrap(); + assert!(!w.iter().any(|w| w.contains("point type objects")), "{body}: {w:?}"); + only_text(&d); + for (ch, x) in chars { + let (left, right, _) = char_edges(&d, ch); + assert!(close(right, x, 0.05), "{body}: {ch} spans {left}..{right}, not ending at {x}"); + } + } } #[test] diff --git a/crates/svg/tests/it/text_layout.rs b/crates/svg/tests/it/text_layout.rs index c53318c358..8c61087e3e 100644 --- a/crates/svg/tests/it/text_layout.rs +++ b/crates/svg/tests/it/text_layout.rs @@ -357,6 +357,19 @@ fn a_chosen_glyph_is_written_as_outlines() { assert!(!svg.contains("` would draw +/// the marks where the font puts them. +#[test] +fn moved_diacritics_are_written_as_outlines() { + let svg = export(&area_doc(vec![run("re\u{301}sume\u{301}", style(12.0))], 280.0, Justify::Left), &ExportOptions::default()); + assert!(svg.contains("` element's 12. diff --git a/crates/svg/tests/it/warp_pieces.rs b/crates/svg/tests/it/warp_pieces.rs index 9c8b3e1760..4d61baee14 100644 --- a/crates/svg/tests/it/warp_pieces.rs +++ b/crates/svg/tests/it/warp_pieces.rs @@ -118,6 +118,49 @@ fn opaque_pixels_stay_opaque_where_warp_pieces_overlap() { } } +/// Pieces the file leaves out share no image: with Images set to Link, the warp pieces of a linked +/// image that are hidden, or sit in hidden clip groups, put no `` naming its file in the +/// defs unless hidden layers are kept. Visible pieces share one. +#[test] +fn hidden_warp_pieces_share_no_image() { + let path = "/away/photo.png"; + let svg = |d: &Document, hidden_layers: bool| { + let opts = ExportOptions { images: vectorcraft_svg::ImageMode::Link, hidden_layers, ..ExportOptions::default() }; + export_full(d, &opts, None).svg + }; + // Every image in `n` linked to `path`. + fn link(n: &mut Node, path: &str) { + if let NodeKind::Image(im) = &mut n.kind { + im.link = Some(vectorcraft_doc::LinkInfo::new(path)); + } + for c in n.children_mut().into_iter().flatten() { + link(std::sync::Arc::make_mut(c), path); + } + } + for masked in [false, true] { + // Hide every image (`ancestor` false), or every clip group holding one (`ancestor` true). + for ancestor in [false, true] { + let mut d = warped_pixels(&|p| p, masked, [255, 0, 0, 255], |_| {}); + let layer = std::sync::Arc::make_mut(&mut d.layers[0]); + let g = std::sync::Arc::make_mut(&mut layer.children_mut().unwrap()[0]); + link(g, path); + let visible = d.clone(); + assert_eq!(svg(&visible, false).matches(path).count(), 1, "masked {masked}: the pieces share one image"); + let layer = std::sync::Arc::make_mut(&mut d.layers[0]); + let g = std::sync::Arc::make_mut(&mut layer.children_mut().unwrap()[0]); + for piece in g.children_mut().unwrap() { + let piece = std::sync::Arc::make_mut(piece); + match piece.children_mut() { + Some(kids) if !ancestor => std::sync::Arc::make_mut(&mut kids[1]).visible = false, + _ => piece.visible = false, + } + } + assert!(!svg(&d, false).contains(path), "masked {masked}, ancestor {ancestor}: {}", svg(&d, false)); + assert_eq!(svg(&d, true).matches(path).count(), 1, "masked {masked}, ancestor {ancestor}"); + } + } +} + /// Pieces of an opaque image are drawn one over another without knockout masks; a colorize paint /// draws a gray image's light pixels partly transparent, so its pieces take them. #[test] diff --git a/crates/text/src/features.rs b/crates/text/src/features.rs index 11f174e1a4..4891e679c3 100644 --- a/crates/text/src/features.rs +++ b/crates/text/src/features.rs @@ -52,6 +52,10 @@ pub struct OtFeatures { pub extra_values: [u16; EXTRA_FEATURES.len()], /// The value `swsh=N` gives swashes ([`Self::swash`]), as [`Self::extra_values`] for `salt`. pub swash_value: u16, + /// Set a complex script (Indic, Arabic, Hebrew) glyph by glyph as the font maps its + /// characters, with none of its layout tables: the Standard composers. Set per paragraph by + /// layout from the paragraph's composer, not by a style. + pub unshaped_complex: bool, } /// The largest value a `tag=N` feature takes: a font's glyph ids are 16 bits, so is an alternate's @@ -94,6 +98,7 @@ impl Default for OtFeatures { extra: 0, extra_values: [0; EXTRA_FEATURES.len()], swash_value: 0, + unshaped_complex: false, } } } @@ -167,6 +172,7 @@ impl OtFeatures { extra: u32::MAX >> (32 - EXTRA_FEATURES.len()), extra_values: [0; EXTRA_FEATURES.len()], swash_value: 0, + unshaped_complex: false, }; change(&mut off); change(&mut on); diff --git a/crates/text/src/harakat.rs b/crates/text/src/harakat.rs index ab5aa593bd..9ea14d0f08 100644 --- a/crates/text/src/harakat.rs +++ b/crates/text/src/harakat.rs @@ -13,6 +13,12 @@ //! a mark on a ligature (for example Geeza Pro's Allah ligature) painted as its letter. Renderers //! and exporters read the glyph's run as they always did, so they need no change. The text itself //! is never changed. +//! +//! The Adjust Horizontal and Vertical Diacritic Positions ([`CharStyle::diacritic_horizontal`]) +//! move the face's mark glyphs (GDEF class 3) by the values of the glyph's run. Runs that differ +//! only in paint and those positions stay one shaping cluster at an Arabic harakat or a Hebrew +//! point ([`diacritic_mark_boundary`]), so a mark set apart from its letter takes its own values +//! the same way it takes its own paint. use skrifa::raw::TableProvider; use skrifa::raw::tables::layout::ClassDef; @@ -36,11 +42,24 @@ pub(crate) fn is_harakat(c: char) -> bool { ) } +/// Is `c` a Hebrew point or cantillation mark (U+0591–U+05BD, U+05BF, U+05C1–U+05C2, +/// U+05C4–U+05C5, U+05C7)? +fn is_hebrew_mark(c: char) -> bool { + matches!(c as u32, 0x0591..=0x05BD | 0x05BF | 0x05C1..=0x05C2 | 0x05C4..=0x05C5 | 0x05C7) +} + +/// Is `c` a diacritical mark the Adjust Diacritic Position fields set apart from its letter: an +/// Arabic harakat ([`is_harakat`]) or a Hebrew point? +pub(crate) fn is_diacritic(c: char) -> bool { + is_harakat(c) || is_hebrew_mark(c) +} + /// Do character styles `a` and `b` differ, if at all, only in paint: fill, stroke and how the /// stroke is drawn, overprint, and the character style name? OpenType feature differences are /// ignored here: they already apply to their own character ranges during shaping. Nor is the /// space before a line's first character read inside a cluster, which takes it from its first -/// character (#5111). Stricter than [`crate::shape`]'s `shapes_alike` (which also ignores baseline +/// character (#5111), nor the Adjust Diacritic Positions, which move a mark glyph by its own run's +/// values. Stricter than [`crate::shape`]'s `shapes_alike` (which also ignores baseline /// shift, tracking, underline, …). pub(crate) fn paint_only(a: &CharStyle, b: &CharStyle) -> bool { // Exhaustive: a new attribute must explicitly keep or relax this boundary rule. @@ -82,6 +101,8 @@ pub(crate) fn paint_only(a: &CharStyle, b: &CharStyle) -> bool { warichu_scale, warichu_align, digits, + diacritic_horizontal: _, + diacritic_vertical: _, font_height_reference, no_break, language, @@ -150,6 +171,16 @@ pub(crate) fn paint_only_mark_boundary(text: &str, at: usize, before: &CharStyle (next.is_some_and(is_harakat) || previous.is_some_and(is_harakat)) && paint_only(before, after) } +/// Is the run boundary at byte `at` of `text`, between styles `before` and `after`, one where the +/// Adjust Diacritic Positions differ, nothing but paint differs besides, and an Arabic harakat or a +/// Hebrew point is on either side? It stays inside a shaping cluster as a paint-only one does. +pub(crate) fn diacritic_mark_boundary(text: &str, at: usize, before: &CharStyle, after: &CharStyle) -> bool { + let next = text.get(at..).and_then(|s| s.chars().next()); + let previous = text.get(..at).and_then(|s| s.chars().next_back()); + let moved = before.diacritic_horizontal != after.diacritic_horizontal || before.diacritic_vertical != after.diacritic_vertical; + moved && (next.is_some_and(is_diacritic) || previous.is_some_and(is_diacritic)) && paint_only(before, after) +} + /// The byte ranges of the harakat in `text[range]`, each run of consecutive harakat as one range. /// The range is normalised as [`crate::edit::style_range`] takes one: its ends clamped to the /// text, each moved back to the start of the character it falls in, and put in order. @@ -194,7 +225,8 @@ pub(crate) fn mark_classes(face: &FontFace) -> Option> { /// by glyph): repeated glyph ids alone could hide a changed correspondence. A glyph whose character /// lies outside its own shaping cluster of `raw` (from its cluster value up to the next larger one, /// else `end`) gets its cluster's first character instead. A later in-cluster character is kept -/// only when the glyph is a GDEF mark and that character is a harakat; otherwise the cluster start +/// only when the glyph is a GDEF mark and that character is a harakat or a Hebrew point +/// ([`is_diacritic`]); otherwise the cluster start /// is kept (conservative: a mark may miss its colour; a base must never take a mark's). `raw`'s /// clusters are never changed. These are HarfBuzz shaping clusters, which can span more than one /// grapheme (a ligature). @@ -224,8 +256,9 @@ pub(crate) fn own_chars( if c.1 == r.1 { return c.1; } - // Later in-cluster character: only a positively identified mark glyph on a harakat. - let mark_char = text.get(c.1 as usize..).and_then(|s| s.chars().next()).is_some_and(is_harakat); + // Later in-cluster character: only a positively identified mark glyph on a harakat or + // a Hebrew point. + let mark_char = text.get(c.1 as usize..).and_then(|s| s.chars().next()).is_some_and(is_diacritic); if is_gdef_mark(r.0) && mark_char { c.1 } else { r.1 } }) .collect() diff --git a/crates/text/src/kashida.rs b/crates/text/src/kashida.rs index c36eacbf2d..8db784a2bc 100644 --- a/crates/text/src/kashida.rs +++ b/crates/text/src/kashida.rs @@ -78,10 +78,11 @@ fn joining(c: char) -> Joining { } /// Is the cluster of glyph `a` joined to the cluster of glyph `b` that follows it in `text`: both -/// right to left in one face, `a`'s last character other than a mark joining the letter after it, -/// and `b` starting with a letter that joins the one before it? +/// right to left in one face and set as joining letters (not by a Standard composer), `a`'s last +/// character other than a mark joining the letter after it, and `b` starting with a letter that +/// joins the one before it? fn joined(text: &str, a: &SGlyph, b: &SGlyph) -> bool { - if a.face.id() != b.face.id() || a.level != b.level || !a.level.is_rtl() || a.byte + a.len != b.byte { + if a.face.id() != b.face.id() || a.level != b.level || !a.level.is_rtl() || a.byte + a.len != b.byte || !(a.cursive && b.cursive) { return false; } let last = text.get(a.byte..a.byte + a.len).and_then(|s| s.chars().rev().find(|&c| joining(c) != Joining::Transparent)); diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs index 6f558d86dd..7a7c904591 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -22,7 +22,7 @@ use crate::shape::{ Punct, SGlyph, Tcy, cap_x_heights, hyphen_glyph, is_cjk, mark_word_ends, no_line_end, no_line_start, punct, run_face, shape_range, shape_runs, soft_line_start, style_metrics, }; -use crate::{Composer, FirstBaseline, InlineGlyph, LayoutOptions, LineInfo, ListMarker, OtFeatures, PositionedGlyph, TextLayout, VerticalAlign}; +use crate::{FirstBaseline, InlineGlyph, LayoutOptions, LineInfo, ListMarker, OtFeatures, PositionedGlyph, TextLayout, VerticalAlign}; mod bidi; mod breaking; @@ -229,11 +229,14 @@ impl Ctx<'_> { out } - /// Shape paragraph `r` (its bidi resolution `bidi`). - fn shape_para(&self, r: Range, bidi: Option<&BidiInfo<'_>>) -> Vec { + /// Shape paragraph `r` (its bidi resolution `bidi`, its attributes `para`). A Standard composer + /// sets a complex script glyph by glyph ([`OtFeatures::unshaped_complex`]). + fn shape_para(&self, r: Range, bidi: Option<&BidiInfo<'_>>, para: &ParaStyle) -> Vec { let mut v = Vec::with_capacity(r.len()); let levels = bidi.map_or(&[][..], |b| &b.levels); - shape_runs(self.db, self.text, r, &self.runs, &self.inlines, &self.faces, &self.opts.features, levels, &mut v); + let standard = !self.opts.composer.unwrap_or(para.composer).shapes_complex_scripts(); + let feats = OtFeatures { unshaped_complex: standard, ..self.opts.features }; + shape_runs(self.db, self.text, r, &self.runs, &self.inlines, &self.faces, &feats, levels, &mut v); self.finish_shaping(&mut v, |g| self.style_at(g.byte)); v } @@ -255,18 +258,43 @@ impl Ctx<'_> { // of the glyph before it takes no cell of its own: it turns with that glyph (`emit`). for i in 0..v.len() { let continues = continues_cluster(i.checked_sub(1).and_then(|p| v.get(p)), v.get(i)); - let Some(g) = v.get_mut(i).filter(|g| g.adv > 0.0 && !continues && stands_upright(g)) else { continue }; - let extra = upright_cell(g) - g.face.advance(g.gid) * g.sx; + if continues || !v.get(i).is_some_and(stands_upright) { + continue; + } + // Tsume measured the cluster across its glyphs' widths when it was shaped: an + // upright glyph's blank space runs down its cell, so that is taken back first. + let measured_down = v.get(i).is_some_and(|g| g.tcy.is_none()); + if measured_down { + let end = (i + 1..v.len()).find(|&j| !continues_cluster(v.get(j - 1), v.get(j))).unwrap_or(v.len()); + let tsume = v.get(end - 1).map_or(0.0, |g| g.tsume); + for g in v.get_mut(i..end).unwrap_or_default() { + g.dx += g.tsume_shift; + g.tsume_shift = 0.0; + } + if let Some(g) = v.get_mut(end - 1) { + g.adv += tsume; + g.tsume = 0.0; + } + } + let Some(g) = v.get_mut(i).filter(|g| g.adv > 0.0) else { continue }; + let cell = upright_cell(g); + let extra = cell - g.face.advance(g.gid) * g.sx; g.dx += extra * 0.5; g.adv += extra; // Proportional Metrics: `vpal` (and the vertical kerning with it) moves it and // changes its length down the column, in fonts with vertical metrics (else the cell // stays as it is, #966). + let mut length = cell; if let Some(a) = g.vpal.filter(|_| g.tcy.is_none() && g.face.vertical_glyph(g.gid).is_some()) { g.dx += a.dx; g.dy += a.dy; g.adv += a.advance; g.proportional = a.proportional; + length += a.advance; + } + let st = style(g); + if measured_down && st.tsume > 0.0 { + self.tighten_upright(g, cell, length, st.size, st.tsume); } } } @@ -283,6 +311,25 @@ impl Ctx<'_> { } } + /// Tsume `tsume` on upright glyph `g` in vertical type, in type of size `em`, its cell `cell` + /// long down the column and `length` long with the Proportional Metrics change to it: its share + /// of the blank space above and below what it paints, inside that length, comes out of its + /// advance, and it is drawn the share above it earlier, keeping its shape. A combining mark in + /// its cluster moves with it. A glyph that paints nothing keeps its place and length. + fn tighten_upright(&self, g: &mut SGlyph, cell: f64, length: f64, em: f64, tsume: f64) { + let Some(b) = crate::shape::painted_box(self.db, g) else { return }; + // The glyph turns about the center of its cell, which is `upright_centre` above the + // baseline: a point of it in font units (y down) lands that far below the center, down the + // column from the top of the cell. + let centre = cell * 0.5 + upright_centre(g, cell, em) + g.dy; + let (a, z) = (centre + b.y0 * g.sy, centre + b.y1 * g.sy); + let Some((above, below)) = crate::shape::tsume_shares((a.min(z), a.max(z)), length, tsume) else { return }; + g.kern_shift -= above; + g.tsume_shift = above; + g.adv -= above + below; + g.tsume = above + below; + } + /// Bullets and numbered lists: put marker `text` (the bullet, or the number and its period; /// [`list_markers`]) of list paragraph `pr` (attributes `para`, right to left when `rtl`) /// before its glyphs `sg` and return how many glyphs went in (none for a paragraph without a @@ -373,7 +420,8 @@ impl Ctx<'_> { // Only the glyph right after an upright glyph can continue its cluster. let cluster = self.upright_cluster.take(); // Control characters (tabs) and soft hyphens draw nothing (fonts map them to .notdef). - let blank = g.is_soft_hyphen() || g.ch.is_control() || g.ch == '\u{2028}'; + // Joiners and direction marks are format controls: no ink either, whatever glyph the font maps. + let blank = g.is_soft_hyphen() || g.ch.is_control() || g.ch == '\u{2028}' || crate::justify::is_format_control(g.ch); // A colour glyph draws its art (COLR layers, an SVG document) or its image (a bitmap, or // COLR paints documents have no form for), not its outline; COLR, then SVG, then bitmaps. // Art in the text's colours takes the run's fill (black when it isn't a colour) and diff --git a/crates/text/src/layout/breaking.rs b/crates/text/src/layout/breaking.rs index fadb0165d5..ef62fa2bcc 100644 --- a/crates/text/src/layout/breaking.rs +++ b/crates/text/src/layout/breaking.rs @@ -395,8 +395,29 @@ pub(super) fn word_width(g: &[SGlyph], i: usize, line_end: &[f64], kinsoku: Kins if end >= g.len() { set(w, trailing, ink) } else { w } } +/// Whether the cluster `j..end` is drawn last, at the right end, of the left-to-right line of +/// glyphs `i..end`: the line's glyphs are reordered by their levels (UAX #9 L2), with each tab and +/// the spaces before it at the paragraph's level (L1). +fn drawn_last(g: &[SGlyph], i: usize, j: usize, end: usize) -> bool { + let line = g.get(i..end).unwrap_or_default(); + let mut levels: Vec = line.iter().map(|h| h.level).collect(); + let mut before_tab = false; + for (level, h) in levels.iter_mut().zip(line).rev() { + if h.ch == '\t' && h.len > 0 { + before_tab = true; + } else if !h.is_space() { + before_tab = false; + } + if before_tab { + *level = unicode_bidi::Level::ltr(); + } + } + unicode_bidi::BidiInfo::reorder_visual(&levels).last().is_some_and(|&k| i + k >= j) +} + /// Greedy break: returns (end glyph index, hyphenated) for a line starting at `i` of `width`. -/// With burasagari, a comma or full stop that doesn't fit ends the line, hanging outside it. +/// With burasagari, a comma or full stop that doesn't fit ends the line, hanging outside it, +/// unless No Break or Bunri-Kinshi keeps characters after it on its line. /// `hyphenate` holds the paragraph's Hyphenation options and the Hyphenation Zone in force when /// the line may hyphenate a word; a line whose text before the overflowing word already ends /// within the zone breaks before that word. A tab is as wide as it is set: up to its next stop @@ -416,7 +437,9 @@ pub(super) fn word_width(g: &[SGlyph], i: usize, line_end: &[f64], kinsoku: Kins /// 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. +/// drawn. Such a line with a tab hangs a burasagari mark only when the mark is drawn at its right +/// end in the visual order of the line's levels ([`drawn_last`]) and the line before the mark fits +/// as drawn. #[allow(clippy::too_many_arguments)] pub(super) fn break_line( text: &str, @@ -543,8 +566,24 @@ pub(super) fn break_line( 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) { + // It ends the line with the spaces after it, when the mark is all the characters kept + // together (the line's last character is the mark, which is what hangs). Once the line + // holds a tab and is measured as drawn, the mark hangs only where it is drawn at the + // line's right end (its cluster is last in the line's visual order, [`drawn_last`]) and + // the line before it fits as drawn with no line-end trim on its last glyph; otherwise the + // line ends at a legal break that fits as drawn. + let alone = g[j..cluster_end].iter().all(|h| h.byte == gl.byte); + let hangs_as_drawn = || match fits.filter(|_| tabbed) { + None => true, + Some(fits) => { + let mut body = j; + while body > i && g[body - 1].is_space() { + body -= 1; + } + drawn_last(g, i, j, cluster_end) && line_end_credit(g, line_end, body) == 0.0 && fits(j, false) + } + }; + if burasagari != Burasagari::None && hangs(gl) && alone && kinsoku_allows(g, cluster_end - 1, kinsoku) && hangs_as_drawn() { let mut end = cluster_end; while g.get(end).is_some_and(SGlyph::is_space) { end += 1; diff --git a/crates/text/src/layout/flow.rs b/crates/text/src/layout/flow.rs index 30b615c5fc..0c4e1ae615 100644 --- a/crates/text/src/layout/flow.rs +++ b/crates/text/src/layout/flow.rs @@ -8,9 +8,9 @@ use super::vertical::{ EM_CENTER, MojikumiRules, align_shift, compress_punctuation, dot_quarter, glyph_em, halve_punctuation, punct_half, space_japanese_and_latin, }; use super::{ - Affine, BidiInfo, Burasagari, CharStyle, Composer, Ctx, EPS, Flex, Justify, Kinsoku, KinsokuShoriType, LeadingModel, LineFit, LineInfo, - ListMarker, ParaStyle, Params, Point, Punct, Range, SGlyph, SingleWordJustify, TextObject, apply_desired, cap_x_heights, compose, fit_line, - hyphen_glyph, is_cjk, is_word_space, kashida, mark_word_ends, no_line_end, no_line_start, style_metrics, + Affine, BidiInfo, Burasagari, CharStyle, Ctx, EPS, Flex, Justify, Kinsoku, KinsokuShoriType, LeadingModel, LineFit, LineInfo, ListMarker, + ParaStyle, Params, Point, Punct, Range, SGlyph, SingleWordJustify, TextObject, apply_desired, cap_x_heights, compose, fit_line, hyphen_glyph, + is_cjk, is_word_space, kashida, mark_word_ends, no_line_end, no_line_start, style_metrics, }; use crate::justify::is_format_control; use crate::shape::{keep_inseparable_pairs, keep_korean_words}; @@ -62,7 +62,7 @@ fn compose_para( // The tab of a list marker is on the first line, with the marker, and has a fixed width. let has_tab = sg.iter().any(|g| g.ch == '\t' && g.len > 0); let has_soft_break = sg.iter().any(|g| g.ch == '\u{2028}'); - if composer != Composer::EveryLine + if composer.is_single_line() || pen.regions.is_none() || sg.len() < 2 || sg.len() > MAX_COMPOSE_GLYPHS @@ -247,7 +247,7 @@ fn prepare_paragraph<'a, 'text>( let text = cx.text; let bidi = para_bidi_with(text.get(pr.clone()).unwrap_or_default(), para.direction, &cx.char_directions(&pr)); let rtl = is_rtl(bidi.as_ref()); - let mut sg = cx.shape_para(pr.clone(), bidi.as_ref()); + let mut sg = cx.shape_para(pr.clone(), bidi.as_ref(), para); // Thai, Lao, Khmer and Myanmar break lines between words, not at spaces. mark_word_ends(text.get(pr.clone()).unwrap_or_default(), pr.start, &mut sg); // Korean breaks between words, unless Korean Line Break Anywhere lets it break between syllables. @@ -321,7 +321,7 @@ fn prepare_paragraph<'a, 'text>( let composed = compose_para(cx, &sg, &flex, &line_end, para, pen, rtl, continued); // Hyphenation options: the Hyphenation Zone applies with the Single-line Composer, and the // Hyphen Limit counts the lines in a row that end with a hyphen. - let zone = if cx.opts.composer.unwrap_or(para.composer) == Composer::SingleLine { para.hyphenation.zone } else { 0.0 }; + let zone = if cx.opts.composer.unwrap_or(para.composer).is_single_line() { para.hyphenation.zone } else { 0.0 }; let hyphen_limit = usize::try_from(para.hyphenation.hyphen_limit).unwrap_or(usize::MAX); let mirror = mirrors_indents(para, rtl, cx.vertical); ParagraphData { @@ -474,7 +474,9 @@ fn place_flow_line(cx: &mut Ctx<'_>, pen: &mut Pen<'_>, context: &mut PlacementC ¶.tabs, ind_l, hyphenate, - para.burasagari, + // A right-to-left paragraph draws a burasagari mark inside its line + // ([`prepare_line_geometry`]): the line ends where it fits with the mark. + if *rtl { Burasagari::None } else { para.burasagari }, para.kinsoku, ty, *hanging, diff --git a/crates/text/src/layout/on_path.rs b/crates/text/src/layout/on_path.rs index d1072d3781..ecb1377d10 100644 --- a/crates/text/src/layout/on_path.rs +++ b/crates/text/src/layout/on_path.rs @@ -422,7 +422,7 @@ pub(super) fn on_path(cx: &mut Ctx<'_>, paras: &[Range], t: &TextObject, let text = cx.text; let bidi = para_bidi_with(text.get(pr.clone()).unwrap_or_default(), para.direction, &cx.char_directions(pr)); rtl.get_or_insert(is_rtl(bidi.as_ref()) && !cx.vertical); - let mut glyphs = cx.shape_para(pr.clone(), bidi.as_ref()); + let mut glyphs = cx.shape_para(pr.clone(), bidi.as_ref(), t.para_at(pi)); // Bullets and numbers: a list paragraph's text starts after its marker here too, unless // the paragraph continues from the frame before in its thread. if pi > 0 || !t.first_para_continues { diff --git a/crates/text/src/layout/wrapping_tests.rs b/crates/text/src/layout/wrapping_tests.rs index a0a09956bc..c7d8ff8a4b 100644 --- a/crates/text/src/layout/wrapping_tests.rs +++ b/crates/text/src/layout/wrapping_tests.rs @@ -477,6 +477,95 @@ fn a_tabbed_line_ends_at_the_latest_break_that_fits_as_drawn() { assert_eq!(ended, (8, false)); } +/// A tabbed line measured as drawn hangs a burasagari full stop that overflows only when the stop +/// is drawn at the line's right end (last in the visual order of the line's levels, whatever its +/// own level) and the line before it fits as drawn with no line-end trim on its last glyph; +/// otherwise it ends at the latest legal break that fits as drawn. +#[test] +fn a_tabbed_burasagari_mark_hangs_only_at_the_drawn_end_of_a_fitting_line() { + let text = "a \t\u{05D0} 漢。"; + let specs: Vec<_> = text.char_indices().map(|(byte, ch)| (byte, ch.len_utf8(), 10.0, ch)).collect(); + let mut glyphs = synthetic_glyphs(&specs); + glyphs[3].level = unicode_bidi::Level::rtl(); + // The text without its tab is 60 pt wide at 。 (glyph 6), past 55 pt; kinsoku keeps 。 off a line + // start, so the latest legal break before it ends the line before 漢 (glyph 5). + let end = |glyphs: &[SGlyph], line_end: &[f64], fits: Option<&dyn Fn(usize, bool) -> bool>| { + break_line( + text, + glyphs, + 0, + 55.0, + &[], + 0.0, + None, + Burasagari::Standard, + Kinsoku::Hard, + KinsokuShoriType::PushOutOnly, + false, + false, + line_end, + fits, + ) + }; + let all_fit = |_end: usize, _hyphenated: bool| true; + assert_eq!(end(&glyphs, &[], Some(&all_fit)), (7, false), "drawn at the right end of a line that fits: 。 hangs"); + let body_too_wide = |end: usize, _hyphenated: bool| end <= 5; + assert_eq!(end(&glyphs, &[], Some(&body_too_wide)), (5, false), "the line before 。 is too wide as drawn"); + let mut trimmed = vec![0.0; glyphs.len()]; + trimmed[5] = 2.0; + assert_eq!(end(&glyphs, &trimmed, Some(&all_fit)), (5, false), "the line before 。 fits only with 漢 trimmed"); + let level = |n: u8| unicode_bidi::Level::new(n).unwrap_or_else(|_| panic!("level {n}")); + glyphs[6].level = level(2); + assert_eq!(end(&glyphs, &[], Some(&all_fit)), (7, false), "。 set left to right in right-to-left text is drawn at the right end"); + glyphs[6].level = level(1); + assert_eq!(end(&glyphs, &[], Some(&all_fit)), (7, false), "。 alone right to left after 漢 is drawn at the right end"); + glyphs[5].level = level(1); + assert_eq!(end(&glyphs, &[], Some(&all_fit)), (5, false), "。 right to left after 漢 in the same run is drawn inside the line"); + glyphs[6].level = level(2); + assert_eq!(end(&glyphs, &[], Some(&all_fit)), (5, false), "。 left to right inside the right-to-left run of 漢 is drawn inside the line"); +} + +/// A burasagari full stop that No Break keeps with the character after it does not hang: the line +/// would end with that character, which is drawn inside the line, so it ends at an earlier break. +#[test] +fn a_burasagari_mark_kept_with_the_next_character_does_not_hang() { + let text = "漢漢。漢"; + let specs: Vec<_> = text.char_indices().map(|(byte, ch)| (byte, ch.len_utf8(), 10.0, ch)).collect(); + let mut glyphs = synthetic_glyphs(&specs); + let end = |glyphs: &[SGlyph]| { + break_line(text, glyphs, 0, 25.0, &[], 0.0, None, Burasagari::Standard, Kinsoku::Hard, KinsokuShoriType::PushOutOnly, false, false, &[], None) + }; + assert_eq!(end(&glyphs), (3, false), "alone, 。 overflows by 5 pt and hangs"); + glyphs[2].no_break = true; + glyphs[3].no_break = true; + assert_eq!(end(&glyphs), (1, false), "kept with the 漢 after it, 。 does not end the line"); +} + +/// A line with a tab and right-to-left text pushes a closing bracket out with every Kinsoku Shori +/// Type, where the same widths without them push it in. +#[test] +fn push_in_leaves_a_tabbed_right_to_left_line_to_push_out() { + use vectorcraft_doc::{TabAlign, TabStop}; + let tabbed = "\u{05D0}\t一二三四五」六"; + let mut glyphs = full_width(tabbed); + glyphs[0].level = unicode_bidi::Level::rtl(); + glyphs[1].adv = 2.0; + let tabs = [TabStop { position: 12.0, align: TabAlign::Left, leader: String::new(), align_on: '.' }]; + let all_fit = |_end: usize, _hyphenated: bool| true; + let fits: Option<&dyn Fn(usize, bool) -> bool> = Some(&all_fit); + // 」 (glyph 7) ends 72 pt along, 5 pt past the measure: five gaps close by 1 pt each. + let end = |ty| break_line(tabbed, &glyphs, 0, 67.0, &tabs, 0.0, None, Burasagari::None, Kinsoku::Hard, ty, false, false, &[], fits); + for ty in [KinsokuShoriType::PushInFirst, KinsokuShoriType::PushOutFirst, KinsokuShoriType::PushOutOnly] { + assert_eq!(end(ty), (6, false), "{ty:?}: 五 is pushed out with 」"); + } + let plain = "ax一二三四五」六"; + let mut glyphs = full_width(plain); + glyphs[1].adv = 2.0; + let pushed = + break_line(plain, &glyphs, 0, 67.0, &[], 0.0, None, Burasagari::None, Kinsoku::Hard, KinsokuShoriType::PushInFirst, false, false, &[], None); + assert_eq!(pushed, (8, false), "without the tab and right-to-left text, 」 is pushed in"); +} + /// Past the breaks a tabbed line measures one by one, it ends at the latest break without a hyphen /// that fits as drawn, whatever the breaks with a hyphen between them measure. #[test] diff --git a/crates/text/src/shape.rs b/crates/text/src/shape.rs index 4c320a2bb4..8ba1746a4d 100644 --- a/crates/text/src/shape.rs +++ b/crates/text/src/shape.rs @@ -128,6 +128,27 @@ pub(crate) fn joins(script: Script) -> bool { ) } +/// Is `script` one a Standard composer leaves unshaped: Indic (conjuncts, half forms, marks placed +/// by the font's layout tables), the joining scripts ([`joins`]: Arabic, Syriac, N'Ko, Mongolian…) +/// and Hebrew? +fn is_complex_script(script: Script) -> bool { + joins(script) + || matches!( + script, + Script::Hebrew + | Script::Devanagari + | Script::Bengali + | Script::Gurmukhi + | Script::Gujarati + | Script::Oriya + | Script::Tamil + | Script::Telugu + | Script::Kannada + | Script::Malayalam + | Script::Sinhala + ) +} + /// How `vpal` and the vertical kerning with it move an upright glyph in vertical type and change /// its length down the column, in points: `advance` down the column, `dx` and `dy` in glyph space /// (y down; `dy` is down the column once the glyph stands upright). `proportional`: `vpal` itself @@ -577,7 +598,7 @@ pub(crate) fn shape_runs( // Synthesized Small Caps shape lowercase letters separately (as smaller capitals). let small_caps = st.small_caps.is_some() && !st.all_caps; // Split into segments by font coverage (and case, for Small Caps). - let mut seg = Segment { range: a..a, runs, source_runs, st, face: primary.clone(), small: false, level: level_at(a) }; + let mut seg = Segment { db, range: a..a, runs, source_runs, st, face: primary.clone(), small: false, level: level_at(a) }; let mut cache: std::collections::HashMap<&str, Arc> = std::collections::HashMap::new(); let mut script = Script::Common; // A grapheme cluster (a letter and its marks, an emoji sequence) is set in one face. @@ -1032,6 +1053,10 @@ fn drawn_alike(a: &CharStyle, b: &CharStyle, vertical: bool) -> bool { warichu_scale: _, warichu_align: _, digits, + // A mark glyph moves by its own run's values ([`shape_segment`]), so a mark keeps its + // letter whatever they are. + diacritic_horizontal: _, + diacritic_vertical: _, font_height_reference, no_break, language, @@ -1106,7 +1131,8 @@ 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 and the East Asian glyph form (each run's apply to its own characters, as features +/// Insert Aki ([`aki`]), Tsume ([`tighten`]), the Adjust Diacritic Positions (each mark glyph takes +/// its run's), 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 { @@ -1165,6 +1191,8 @@ fn shapes_alike(a: &CharStyle, b: &CharStyle) -> bool { warichu_scale: _, warichu_align: _, digits, + diacritic_horizontal: _, + diacritic_vertical: _, font_height_reference, no_break, language, @@ -1326,6 +1354,7 @@ fn inline_glyph( /// alike ([`shapes_alike`]). #[derive(Clone)] struct Segment<'a> { + db: &'a FontDb, range: Range, /// All the runs, and the indices of those the piece's shaping span takes in. runs: &'a [(Range, &'a CharStyle)], @@ -1385,7 +1414,7 @@ fn is_mark(c: char) -> bool { /// SS). A cluster that would take in characters of runs with different drawing attributes (a /// ligature, a base with its marks) is not formed, except for paint-only harakat differences. fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFeatures, out: &mut Vec) { - let Segment { range, runs, source_runs, st, face, small, level } = seg; + let Segment { db, range, runs, source_runs, st, face, small, level } = seg; let (range, small) = (range.clone(), *small); // The source runs the segment's bytes lie in (a span can hold many segments). let span = runs.get(source_runs.clone()).unwrap_or_default(); @@ -1394,7 +1423,13 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe let source_runs = &(source_runs.start + first..source_runs.start + last); let text_seg = &text[range.clone()]; // The segment's script: that of its first character of a script of its own. - let cursive = text_seg.chars().map(|c| c.script()).find(|s| !matches!(s, Script::Common | Script::Inherited)).is_some_and(joins); + let first_script = text_seg.chars().map(|c| c.script()).find(|s| !matches!(s, Script::Common | Script::Inherited)); + // A Standard composer sets a complex script glyph by glyph (no layout tables, nominal glyphs). + // shortcut: decided for the whole segment by its first strong script, as `cursive` is; segments + // already split where the script changes. + let unshaped = feats.unshaped_complex && first_script.is_some_and(is_complex_script); + // Unshaped letters don't join, so they are not bent along a path as joined ones are. + let cursive = first_script.is_some_and(joins) && !unshaped; let full = st.size.max(0.0); // Superscript/subscript and small capitals shrink the glyphs; line metrics keep the full size. let (_, pos_shift) = st.position.scale_shift(full); @@ -1437,11 +1472,21 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe if !manual_ends.is_empty() { return shape_apart(manual_ends, out); } - // Harakat styled apart from their letters (paint only): shaped with them, each glyph then - // takes its own character's run ([`crate::harakat`]). + // Harakat styled apart from their letters (paint only), and harakat and Hebrew points with + // diacritic positions of their own: shaped with them, each glyph then takes its own + // character's run ([`crate::harakat`]). let mark_boundaries: Vec = boundaries() - .filter(|&b| run_at(b - 1).1 != run_at(b).1 && crate::harakat::paint_only_mark_boundary(text, b, run_at(b - 1).1, run_at(b).1)) + .filter(|&b| { + let (before, after) = (run_at(b - 1).1, run_at(b).1); + before != after + && (crate::harakat::paint_only_mark_boundary(text, b, before, after) + || crate::harakat::diacritic_mark_boundary(text, b, before, after)) + }) .collect(); + // The face's mark classes, read once when any of the segment's runs moves its marks. + let moves_marks = + runs.get(source_runs.clone()).unwrap_or_default().iter().any(|(_, s)| s.diacritic_horizontal != 0.0 || s.diacritic_vertical != 0.0); + let diacritic_classes = if moves_marks { crate::harakat::mark_classes(face) } else { None }; // Source run starts are sorted. Reuse their classification when checking cluster splits. let styled_marks = !mark_boundaries.is_empty(); let char_level = std::cell::Cell::new(false); @@ -1463,8 +1508,8 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe } ranged }; - // Horizontal type with Tsume on any of the segment's characters. - let tsume_here = !feats.vertical && runs.get(source_runs.clone()).unwrap_or_default().iter().any(|(_, s)| s.tsume > 0.0); + // Tsume on any of the segment's characters. + let tsume_here = runs.get(source_runs.clone()).unwrap_or_default().iter().any(|(_, s)| s.tsume > 0.0); // Shape the segment as if all of it were in `st`, with the features `more` on top. let shape_in = |st: &CharStyle, more: &[Feature]| { // A BCP 47 tag is short ASCII; anything else (a file may hold anything) is shaped without one. @@ -1475,7 +1520,7 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe .and_then(|l| l.parse::().ok()); let mut shaped = Shaped::default(); let Shaped { raw, proportional, vpal, chars, unkerned } = &mut shaped; - let hb_shaped = face.hb().map(|hb| { + let hb_shaped = face.hb().filter(|_| !unshaped).map(|hb| { let shaper = face.shaper.shaper(&hb).instance(face.instance.as_ref()).build(); // The baseline and character-level pass use exactly the same resolved features. // Alternate positioning passes still resolve their own features, with `more` last. @@ -1591,7 +1636,8 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe } }); if hb_shaped.is_none() { - // Fallback: nominal glyphs and hmtx advances, no shaping. + // Fallback: nominal glyphs and hmtx advances, no shaping (also a complex script under a + // Standard composer). if let Some(f) = face.skrifa() { let cmap = f.charmap(); let gm = f.glyph_metrics(Size::unscaled(), face.location()); @@ -1600,8 +1646,14 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe let c = st.digits.map(c); let chars: Vec = if upper { c.to_uppercase().collect() } else { vec![c] }; for u in chars { - let g = cmap.map(u).unwrap_or_default(); - let adv = gm.advance_width(g).unwrap_or(face.upem as f32 * 0.5); + // Format characters (joiners, direction marks) have no glyph of their own in most + // fonts, and the shaper hides them: draw the space's glyph with no advance. + let (g, adv) = if crate::justify::is_format_control(u) { + (cmap.map(' ').unwrap_or_default(), 0.0) + } else { + let g = cmap.map(u).unwrap_or_default(); + (g, gm.advance_width(g).unwrap_or(face.upem as f32 * 0.5)) + }; raw.push((g.to_u32(), cl, adv.round() as i32, 0, 0)); } } @@ -1735,11 +1787,21 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe for (gi, &(gid, cl, xa, xo, yo)) in raw.iter().enumerate() { let cl = cl as usize; let (run, gst) = run_at(cl); - // A glyph of a harakat styled apart takes its own character's run (paint only). - let run = match chars.get(gi).map(|&c| run_at(c as usize)) { - Some((own, own_st)) if crate::harakat::paint_only(gst, own_st) => own, - _ => run, + // A glyph of a harakat styled apart takes its own character's run (paint and diacritic + // positions only). + let (run, run_st) = match chars.get(gi).map(|&c| run_at(c as usize)) { + Some((own, own_st)) if crate::harakat::paint_only(gst, own_st) => (own, own_st), + _ => (run, gst), }; + // A mark glyph (GDEF class 3) moves by its run's Adjust Diacritic Positions, thousandths + // of the em it is set in: right and up for positive values. + let (mut dx, mut dy) = (xo as f64 * k * hs, -(yo as f64) * k * vs); + if let Some(classes) = &diacritic_classes + && classes.get(skrifa::GlyphId::new(gid)) == 3 + { + dx += run_st.diacritic_horizontal / 1000.0 * size * hs; + dy -= run_st.diacritic_vertical / 1000.0 * size * vs; + } let end = cluster_end(cl); let last_in_cluster = gi + 1 == n || raw[gi + 1].1 as usize != cl; let ch = first_char(cl); @@ -1794,8 +1856,8 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe run, adv, tracking: tracked, - dx: xo as f64 * k * hs, - dy: -(yo as f64) * k * vs, + dx, + dy, kern_shift, aki_shift, aki: aki_in_adv, @@ -1827,10 +1889,11 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe hyphen_language: crate::hyphen::Language::from_tag(gst.language.as_deref()), }); // Tsume takes its share of the blank space beside the cluster's ink once the cluster is - // complete, in horizontal type. - if last_in_cluster && !invisible && !feats.vertical && gst.tsume > 0.0 { + // complete, along the line. In vertical type a glyph that stands upright is measured down + // the column instead, once its cell is known ([`crate::layout`]). + if last_in_cluster && !invisible && gst.tsume > 0.0 { let first = out.iter().rposition(|g| g.byte != cl).map_or(0, |i| i + 1); - tighten(out.get_mut(first..).unwrap_or_default(), own, gst.tsume); + tighten(db, out.get_mut(first..).unwrap_or_default(), own, gst.tsume); } } } @@ -1841,25 +1904,20 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe /// and its ink, on each side, comes out of the cluster's advance, and its glyphs are drawn the /// 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) { +/// width that is not positive, keeps its place and width. The ink is what the glyph paints +/// ([`painted_box`]): its color art or bitmap when it has one, else its outline. +fn tighten(db: &FontDb, 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 }; let (mut pen, mut ink): (f64, Option<(f64, f64)>) = (0.0, None); for (i, g) in glyphs.iter().enumerate() { - if let Some((a, b)) = ink_across(&g.face, g.gid) { - let (a, b) = (pen + g.dx + a * g.sx, pen + g.dx + b * g.sx); + if let Some(b) = painted_box(db, g) { + let (a, b) = (pen + g.dx + b.x0 * g.sx, pen + g.dx + b.x1 * g.sx); let (lo, hi) = (a.min(b), a.max(b)); ink = Some(ink.map_or((lo, hi), |(l, h)| (l.min(lo), h.max(hi)))); } pen += if i == last { own } else { g.adv }; } - let Some((lo, hi)) = ink.filter(|(lo, hi)| lo.is_finite() && hi.is_finite()) else { return }; - if !(pen.is_finite() && pen > 0.0) { - return; - } - let left = lo.clamp(0.0, pen) * share; - let right = (pen - hi).clamp(0.0, pen) * share; + let Some((left, right)) = ink.and_then(|ink| tsume_shares(ink, pen, tsume)) else { return }; for g in glyphs.iter_mut() { g.dx -= left; g.tsume_shift = left; @@ -1870,18 +1928,38 @@ fn tighten(glyphs: &mut [SGlyph], own: f64, tsume: f64) { } } -/// The left and right edges of glyph `gid`'s outline in `face`, in font units; `None` for a glyph -/// without an outline (a space, or a bitmap or color glyph without one). -fn ink_across(face: &FontFace, gid: u32) -> Option<(f64, f64)> { - let font = face.skrifa()?; - let glyph = font.outline_glyphs().get(skrifa::GlyphId::new(gid))?; - let mut pen = crate::fontdb::FlipPen(kurbo::BezPath::new()); - glyph.draw(skrifa::outline::DrawSettings::unhinted(Size::unscaled(), face.location()), &mut pen).ok()?; - if pen.0.elements().is_empty() { +/// What Tsume `tsume` (percent) takes off before and after ink running from `lo` to `hi` along a +/// cell running from 0 to `length`: its share of the blank space on each side, inside the cell. +/// `None` when the ink or the cell is not finite, or the cell's length is not positive. +pub(crate) fn tsume_shares((lo, hi): (f64, f64), length: f64, tsume: f64) -> Option<(f64, f64)> { + let share = if tsume.is_nan() { 0.0 } else { tsume.clamp(0.0, MAX_TSUME) / 100.0 }; + if !(lo.is_finite() && hi.is_finite() && length.is_finite() && length > 0.0) { return None; } - let b = pen.0.bounding_box(); - Some((b.x0, b.x1)) + Some((lo.clamp(0.0, length) * share, (length - hi).clamp(0.0, length) * share)) +} + +/// The box of what glyph `g` paints, in font units (y down, as outlines are), as the layout draws +/// it: its COLR or SVG art, else its color bitmap, else its outline. `None` for a glyph that paints +/// nothing: a space, a control or format character, or art, an image or an outline that is empty +/// or not finite. +pub(crate) fn painted_box(db: &FontDb, g: &SGlyph) -> Option { + if g.inline.is_some() || g.is_soft_hyphen() || g.ch.is_control() || g.ch == '\u{2028}' || crate::justify::is_format_control(g.ch) { + return None; + } + let image_box = |image: &crate::GlyphImage| image.xf.transform_rect_bbox(image.rect()); + let b = match db.glyph_colour(&g.face, g.gid, vectorcraft_doc::color::Color::BLACK, None) { + Some(crate::colr::ColourContent::Art(art)) => art.geometric_bounds(), + Some(crate::colr::ColourContent::Image(image)) => Some(image_box(&image)), + None => match db.glyph_image(&g.face, g.gid) { + Some(image) => Some(image_box(&image)), + None => { + let outline = db.outline(&g.face, g.gid); + (!outline.elements().is_empty()).then(|| outline.bounding_box()) + } + }, + }; + b.filter(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()) && (b.width() > 0.0 || b.height() > 0.0)) } #[cfg(test)] diff --git a/crates/text/src/test_fonts.rs b/crates/text/src/test_fonts.rs index 7abae3f0eb..d17ce78603 100644 --- a/crates/text/src/test_fonts.rs +++ b/crates/text/src/test_fonts.rs @@ -534,7 +534,8 @@ pub fn half_form_font(half: bool) -> Option> { pub const CONJUNCT_FAMILY: &str = "Conjuncttest Sans"; /// A test-only cmap over bundled Source Sans 3: Devanagari Ka uses K, the halant uses a period and -/// the vowel sign I (drawn before its syllable) uses i. The `GSUB` table's `dev2` script has an +/// the vowel sign I (drawn before its syllable) uses i; Gujarati Ka, virama and vowel sign I use the +/// same glyphs. The `GSUB` table's `dev2` and `gjr2` scripts have an /// `aalt` single substitution of K by k and a `salt` one of K by i, which list k and the vowel /// sign's glyph as alternates of Ka, and a `half` ligature of K and the period into k (Ka's half /// form). Family [`CONJUNCT_FAMILY`]. `None` when it can't be built. @@ -549,7 +550,7 @@ pub fn conjunct_font() -> Option> { const BASE: &[u8] = include_bytes!("../../../assets/fonts/SourceSans3-Regular.ttf"); let font = skrifa::FontRef::new(BASE).ok()?; let charmap = font.charmap(); - let mapping = [('क', 'K'), ('\u{094D}', '.'), ('\u{093F}', 'i')]; + let mapping = [('क', 'K'), ('\u{094D}', '.'), ('\u{093F}', 'i'), ('ક', 'K'), ('\u{0ACD}', '.'), ('\u{0ABF}', 'i')]; let mappings = mapping.into_iter().map(|(c, source)| Some((c, write_fonts::types::GlyphId::new(charmap.map(source)?.to_u32())))); let cmap = Cmap::from_mappings(mappings.collect::>>()?).ok()?; let family = CONJUNCT_FAMILY; @@ -574,7 +575,8 @@ pub fn conjunct_font() -> Option> { SubstitutionLookup::Ligature(Lookup::new(Default::default(), vec![half])), SubstitutionLookup::Single(Lookup::new(Default::default(), vec![salt.into()])), ]); - let scripts = ScriptList::new(vec![ScriptRecord::new(Tag::new(b"dev2"), Script::new(Some(LangSys::new(vec![0, 1, 2])), vec![]))]); + let langsys = || Script::new(Some(LangSys::new(vec![0, 1, 2])), vec![]); + let scripts = ScriptList::new(vec![ScriptRecord::new(Tag::new(b"dev2"), langsys()), ScriptRecord::new(Tag::new(b"gjr2"), langsys())]); builder.add_table(&Gsub::new(scripts, features, lookups)).ok()?; for r in font.table_directory.table_records() { let tag = Tag::new(&r.tag().to_be_bytes()); diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index 3837a1adf4..4bab8aa561 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -10,6 +10,7 @@ mod bidi; mod bitmaps; mod colr; mod combos; +mod composers; mod composite; mod devanagari; mod embed; diff --git a/crates/text/src/tests/composers.rs b/crates/text/src/tests/composers.rs new file mode 100644 index 0000000000..45e760b9d2 --- /dev/null +++ b/crates/text/src/tests/composers.rs @@ -0,0 +1,113 @@ +//! The four composers: the Middle Eastern & South Asian ones shape complex scripts with the font's +//! layout tables, the Standard ones set them glyph by glyph as the font maps their characters. +//! Uses a font built in code ([`conjunct_font`]): Ka K, halant a period and vowel sign I i, in +//! Devanagari and Gujarati, with a `half` ligature of K and the period into k. +use crate::test_fonts::{CONJUNCT_FAMILY, conjunct_font, source_sans_gid}; +use crate::*; +use kurbo::Point; +use vectorcraft_doc::{CharStyle, Composer, TextObject}; + +/// Ka, halant, Ka, vowel sign I in Devanagari, then in Gujarati. +const DEVANAGARI: &str = "क\u{94D}क\u{93F}"; +const GUJARATI: &str = "ક\u{ACD}ક\u{ABF}"; + +fn db() -> FontDb { + let db = FontDb::with_font_dirs(vec![]); + db.add_font(conjunct_font().expect("the test font builds")); + db +} + +fn object(text: &str, composer: Composer) -> TextObject { + let st = CharStyle { font_family: CONJUNCT_FAMILY.into(), font_style: "Regular".into(), size: 20.0, ..CharStyle::default() }; + let mut t = TextObject::point(Point::ZERO, text, st); + t.para.composer = composer; + t +} + +/// The glyph ids drawn for `text` with `composer`, and each glyph's source cluster length. +fn drawn(db: &FontDb, text: &str, composer: Composer) -> Vec<(u32, usize)> { + layout(db, &object(text, composer)).glyphs.iter().map(|g| (g.gid, g.len)).collect() +} + +fn g(c: char) -> u32 { + u32::from(source_sans_gid(c).expect("a Source Sans glyph")) +} + +/// Under the ME&SA composers the conjunct forms (the vowel sign I drawn before its syllable and Ka's +/// half form, in Devanagari and in Gujarati); under the Standard ones each character +/// has its own glyph, in text order, as the font maps it. +#[test] +fn standard_composers_set_indic_text_glyph_by_glyph() { + let db = db(); + let ids = |v: Vec<(u32, usize)>| v.into_iter().map(|(gid, _)| gid).collect::>(); + for composer in [Composer::SingleLine, Composer::EveryLine] { + assert_eq!(ids(drawn(&db, DEVANAGARI, composer)), [g('i'), g('k'), g('K')], "{composer:?} Devanagari"); + assert_eq!(ids(drawn(&db, GUJARATI, composer)), [g('i'), g('k'), g('K')], "{composer:?} Gujarati"); + } + for composer in [Composer::StandardSingleLine, Composer::StandardEveryLine] { + let plain = [g('K'), g('.'), g('K'), g('i')]; + let devanagari = drawn(&db, DEVANAGARI, composer); + assert_eq!(ids(devanagari.clone()), plain, "{composer:?} Devanagari"); + assert_eq!(ids(drawn(&db, GUJARATI, composer)), plain, "{composer:?} Gujarati"); + assert!(devanagari.iter().all(|&(_, len)| len == 3), "each glyph is one character's own cluster: {devanagari:?}"); + } +} + +/// The composer is per paragraph: of two paragraphs of the same text, each is shaped by its own. +#[test] +fn each_paragraph_follows_its_own_composer() { + let db = db(); + let mut t = object(&format!("{DEVANAGARI}\n{DEVANAGARI}"), Composer::EveryLine); + let standard = vectorcraft_doc::ParaStyle { composer: Composer::StandardEveryLine, ..t.para.clone() }; + t.set_paragraph_styles(vec![t.para.clone(), standard]); + let l = layout(&db, &t); + let second = DEVANAGARI.len() + 1; + let of = |from: usize, to: usize| l.glyphs.iter().filter(|g| (from..to).contains(&g.byte) && g.len > 0).map(|g| g.gid).collect::>(); + assert_eq!(of(0, second), [g('i'), g('k'), g('K')], "ME&SA paragraph"); + assert_eq!(of(second, second + DEVANAGARI.len()), [g('K'), g('.'), g('K'), g('i')], "Standard paragraph"); +} + +/// Layout's composer override ([`LayoutOptions::composer`]) decides the shaping too. +#[test] +fn the_layout_composer_override_decides_the_shaping() { + let db = db(); + let t = object(DEVANAGARI, Composer::EveryLine); + let with = |c| layout_with(&db, &t, &LayoutOptions { composer: Some(c), ..Default::default() }).glyphs.len(); + assert_eq!((with(Composer::SingleLine), with(Composer::StandardSingleLine)), (3, 4)); +} + +/// Standard composers break lines as the ME&SA ones do (`is_single_line`), and old files' composers +/// keep their meaning. +#[test] +fn composers_split_into_breaking_and_shaping() { + use Composer::*; + for (c, single, shapes) in + [(SingleLine, true, true), (EveryLine, false, true), (StandardSingleLine, true, false), (StandardEveryLine, false, false)] + { + assert_eq!((c.is_single_line(), c.shapes_complex_scripts()), (single, shapes), "{c:?}"); + assert_eq!(c.with_breaking(single), c, "{c:?}"); + assert_eq!( + (c.with_breaking(!single).is_single_line(), c.with_breaking(!single).shapes_complex_scripts()), + (!single, shapes), + "{c:?} toggled" + ); + } + assert_eq!(Composer::default(), EveryLine, "new type and old documents are ME&SA Every-line"); +} + +/// A joiner or non-joiner has no glyph in most fonts and the shaper hides it; a Standard composer +/// draws it as no width at all, not as a missing-glyph box. +#[test] +fn standard_composers_give_format_characters_no_width() { + let db = db(); + let text = "क\u{200C}क"; + for composer in [Composer::StandardSingleLine, Composer::StandardEveryLine] { + let l = layout(&db, &object(text, composer)); + let widths: Vec = l.glyphs.iter().map(|g| g.advance).collect(); + assert_eq!(widths.len(), 3, "{composer:?}: {widths:?}"); + assert_eq!(widths[1], 0.0, "{composer:?}: the non-joiner takes no room: {widths:?}"); + assert!(widths[0] > 0.0 && widths[2] > 0.0, "{composer:?}: {widths:?}"); + // The test font maps no space: the control must still draw nothing (not glyph 0's outline). + assert!(l.glyphs[1].outline.elements().is_empty(), "{composer:?}: the non-joiner has no ink"); + } +} diff --git a/crates/text/src/tests/hang.rs b/crates/text/src/tests/hang.rs index 5ccb79a5ca..ba978147bf 100644 --- a/crates/text/src/tests/hang.rs +++ b/crates/text/src/tests/hang.rs @@ -293,3 +293,38 @@ fn burasagari_counts_the_hung_start() { assert!((quote.origin.x + quote.advance).abs() < EPS, "the quote hangs: {:?}", quote.origin); assert!((comma.origin.x + comma.advance - 100.0).abs() < EPS, "、 inside, on the edge: {:?} {}", comma.origin, comma.advance); } + +/// A right-to-left paragraph draws a burasagari full stop inside its line, so the line breaks where +/// it fits with the stop: in a frame too narrow for the whole line by half the stop, the line ends +/// after the first word and nothing is drawn past the frame. +#[test] +fn right_to_left_burasagari_keeps_the_line_inside_the_frame() { + use vectorcraft_doc::{Burasagari, Kinsoku, ParaDirection}; + const EPS: f64 = 1e-6; + let text = "\u{05D0}\u{05D1} \u{05D2}\u{05D3}\u{3002}"; + let lay = |width: f64| { + let mut t = area(text, 20.0, Rect::new(0.0, 0.0, width, 400.0), Justify::Auto); + t.para.direction = Some(ParaDirection::RightToLeft); + t.para.burasagari = Burasagari::Standard; + t.para.kinsoku = Kinsoku::Hard; + let l = layout(db(), &t); + (t, l) + }; + let (_, wide) = lay(1000.0); + assert_eq!(wide.lines.len(), 1); + let full: f64 = wide.glyphs.iter().map(|g| g.advance).sum(); + let Some(stop) = wide.glyphs.iter().find(|g| g.byte == text.len() - '\u{3002}'.len_utf8()) else { + panic!("。 is set as a glyph of its own"); + }; + let (t, l) = lay(full - stop.advance / 2.0); + assert!(!l.overflow); + assert_eq!(l.lines.len(), 2, "the line ends after the first word"); + for (li, gs) in inked(&t, &l) { + // A right-to-left line's trailing space is set at its left, outside the aligned text. + for g in gs.into_iter().filter(|g| !is_space(ch(&t, g))) { + let c = ch(&t, g); + assert!(g.origin.x >= li.avail.0 - EPS, "{c:?} starts at {} before {}", g.origin.x, li.avail.0); + assert!(g.origin.x + g.advance <= li.avail.1 + EPS, "{c:?} ends at {} past {}", g.origin.x + g.advance, li.avail.1); + } + } +} diff --git a/crates/text/src/tests/harakat.rs b/crates/text/src/tests/harakat.rs index 0b401a5cd3..4e11921a6f 100644 --- a/crates/text/src/tests/harakat.rs +++ b/crates/text/src/tests/harakat.rs @@ -173,6 +173,8 @@ fn paint_only_keeps_every_drawing_attribute_and_partial_equality() { b.style_name = a.style_name.clone(); b.kerning_before = a.kerning_before; b.features = a.features.clone(); + b.diacritic_horizontal = a.diacritic_horizontal; + b.diacritic_vertical = a.diacritic_vertical; *a == b } @@ -226,6 +228,8 @@ fn paint_only_keeps_every_drawing_attribute_and_partial_equality() { field!(tcy_left_right, 1.0, false); field!(standard_vertical_roman, true, false); field!(digits, Digits::Hindi, false); + field!(diacritic_horizontal, 100.0, true); + field!(diacritic_vertical, -100.0, true); field!(font_height_reference, FontHeightReference::CapHeight, false); field!(no_break, true, false); field!(language, Some("ar".into()), false); @@ -331,6 +335,74 @@ fn feature_only_harakat_boundaries_keep_attachment_and_ownership() { } } +/// Adjust Horizontal and Vertical Diacritic Position move the mark glyphs (GDEF class 3) by +/// thousandths of an em of the glyph size, right and up for positive values, and leave the letters +/// where they were. A mark styled apart from its letter takes its own values. +#[test] +fn diacritic_positions_move_marks_and_keep_letters() { + let db = FontDb::with_font_dirs(vec![]); + assert_eq!(db.add_font(crate::test_fonts::lam_alef_font(b"rlig").expect("the test font builds")), 1); + let family = crate::test_fonts::lam_alef_family(b"rlig"); + let face = db.face(family, "Regular").expect("the test face"); + const WORD: &str = "بَبَبَ"; + let plain = TextObject::point(Point::ZERO, WORD, style(family)); + let before = layout(&db, &plain); + assert_eq!(before.glyphs.len(), 6, "three bases with their attached marks"); + let (h, v) = (200.0, 100.0); + let moved = (h / 1000.0 * 48.0, -v / 1000.0 * 48.0); + // (letters set, marks set): which glyphs move. + for (letters, marks) in [(true, true), (false, true), (true, false), (false, false)] { + let mut text = plain.clone(); + for (byte, ch) in WORD.char_indices() { + if (is_harakat(ch) && marks) || (!is_harakat(ch) && letters) { + crate::edit::style_range(&mut text.runs, byte, byte + ch.len_utf8(), |st| { + st.diacritic_horizontal = h; + st.diacritic_vertical = v; + }); + } + } + let after = layout(&db, &text); + assert_eq!(after.glyphs.len(), before.glyphs.len(), "letters {letters}, marks {marks}"); + let mut marks_seen = 0; + for (a, b) in before.glyphs.iter().zip(&after.glyphs) { + assert_eq!((a.gid, a.byte, a.origin, a.advance), (b.gid, b.byte, b.origin, b.advance), "letters {letters}, marks {marks}"); + let (ta, tb) = (a.xf.translation(), b.xf.translation()); + let delta = (tb.x - ta.x, tb.y - ta.y); + let mark = is_gdef_mark(&face, a.gid); + marks_seen += usize::from(mark); + let want = if mark && marks { moved } else { (0.0, 0.0) }; + assert!( + (delta.0 - want.0).abs() < 1e-9 && (delta.1 - want.1).abs() < 1e-9, + "letters {letters}, marks {marks}: glyph {} moved {delta:?}, want {want:?}", + a.gid + ); + } + assert_eq!(marks_seen, 3, "the three fathas are marks"); + } +} + +/// Hebrew points count as diacritics as well as Arabic harakat; Latin accents and letters do not. +/// A boundary where only the diacritic positions differ asks for the character-level pass only +/// at such a mark. +#[test] +fn hebrew_points_and_harakat_are_diacritics() { + use crate::harakat::{diacritic_mark_boundary, is_diacritic}; + for c in ['\u{05B8}', '\u{05C1}', '\u{05BC}', '\u{064E}', '\u{0651}'] { + assert!(is_diacritic(c), "{c:?}"); + } + for c in ['\u{05D0}', '\u{0628}', '\u{0301}', 'a', '\u{05BE}'] { + assert!(!is_diacritic(c), "{c:?}"); + } + let a = style(FAMILY); + let b = CharStyle { diacritic_vertical: 150.0, ..a.clone() }; + assert!(diacritic_mark_boundary("שָׁ", 2, &a, &b), "a Hebrew point styled apart"); + assert!(diacritic_mark_boundary("بَ", 2, &a, &b), "a fatha styled apart"); + assert!(!diacritic_mark_boundary("e\u{301}", 1, &a, &b), "a Latin accent keeps its cluster's values"); + assert!(!diacritic_mark_boundary("بَ", 2, &a, &a), "the same values"); + let c = CharStyle { size: 20.0, ..b.clone() }; + assert!(!diacritic_mark_boundary("بَ", 2, &a, &c), "a size change splits the run anyway"); +} + /// A range is normalised as `edit::style_range` takes one: clamped, each end moved back to the /// start of its character, put in order. Never a silent empty result for a usable range. #[test] diff --git a/crates/text/src/tests/tsume.rs b/crates/text/src/tests/tsume.rs index bd2d7d9ccc..73f541bf0d 100644 --- a/crates/text/src/tests/tsume.rs +++ b/crates/text/src/tests/tsume.rs @@ -1,5 +1,6 @@ //! Tsume (`CharStyle::tsume`): the share of the blank space on each side of a character's ink, -//! inside its own width, that horizontal type takes away, the glyph keeping its shape. +//! inside its own width (in vertical type, down an upright character's cell), that is taken away, +//! the glyph keeping its shape. use super::{area, db, point, style}; use crate::*; use kurbo::Shape; @@ -150,13 +151,134 @@ fn justification_keeps_the_tsume() { assert!(gap(<) < gap(&lp) - 1.0, "{} {}", gap(&lp), gap(<)); } +fn vertical(text: &str, st: CharStyle) -> TextObject { + let mut t = point(text, st); + t.xf = Affine::IDENTITY; + t.vertical = true; + t +} + +/// The box of what glyph `byte` paints: its outline, its bitmap or its color art. +fn painted(l: &TextLayout, byte: usize) -> Rect { + let g = l.glyphs.iter().find(|g| g.byte == byte).unwrap(); + let image = g.placed_image().map(|(image, xf)| xf.transform_rect_bbox(image.rect())); + let colour = g.colour.as_ref().and_then(|c| c.geometric_bounds()).map(|b| g.xf.transform_rect_bbox(b)); + image.or(colour).unwrap_or_else(|| g.outline.bounding_box()) +} + +/// Where glyph `byte`'s cell starts down a vertical column. +fn cell_top(l: &TextLayout, byte: usize) -> f64 { + l.glyphs.iter().find(|g| g.byte == byte).map(|g| g.origin.y).unwrap() +} + #[test] -fn vertical_type_keeps_its_spacing() { - for text in ["§§", "ab"] { - let mut plain = point(text, style(20.0)); - plain.xf = Affine::IDENTITY; - plain.vertical = true; - let centers = |t: &TextObject| layout(db(), t).glyphs.iter().map(|g| g.outline.bounding_box().center()).collect::>(); - assert_eq!(centers(&with(&plain, 0, |s| s.tsume = 100.0)), centers(&plain), "{text}"); +fn upright_glyphs_take_their_share_of_the_space_above_and_below_their_ink() { + use crate::test_fonts::{VERTICAL_FAMILY, vertical_font}; + // The bundled font without vertical metrics (a cell of one em), and with them: § 1.4 em down + // the column from its vertical origin, given by VORG or by its top side bearing. + for vorg in [None, Some(false), Some(true)] { + let fonts = FontDb::with_font_dirs(vec![]); + let mut st = style(20.0); + if let Some(vorg) = vorg { + fonts.add_font(vertical_font(vorg).unwrap()); + st.font_family = VERTICAL_FAMILY.into(); + } + let plain = vertical("§§§", st.clone()); + let lp = layout(&fonts, &plain); + let (before, after) = (painted(&lp, 2).y0 - cell_top(&lp, 2), cell_top(&lp, 4) - painted(&lp, 2).y1); + assert!(before > 1.0 && after > 1.0, "{vorg:?}: {before} {after}"); + for tsume in [25.0, 100.0] { + let share = tsume / 100.0; + let lt = layout(&fonts, &with(&plain, 2, |s| s.tsume = tsume)); + // The middle § moves up by its share of the space above its ink, and the § after it by + // the share of the space above and below it; the first stays, and the glyph keeps its + // shape. + let moved = (painted(<, 2).y0 - painted(&lp, 2).y0, painted(<, 4).y0 - painted(&lp, 4).y0); + assert!((moved.0 + before * share).abs() < 1e-6, "{vorg:?} {tsume}: {moved:?}"); + assert!((moved.1 + (before + after) * share).abs() < 1e-6, "{vorg:?} {tsume}: {moved:?}"); + assert!((painted(<, 2).height() - painted(&lp, 2).height()).abs() < 1e-6); + assert!((painted(<, 2).center().x - painted(&lp, 2).center().x).abs() < 1e-6, "it stays on the column's center line"); + assert!((painted(<, 0).y0 - painted(&lp, 0).y0).abs() < 1e-9); + } + // At 100% the ink runs edge to edge down the column. + let lt = layout(&fonts, &with(&plain, 2, |s| s.tsume = 100.0)); + assert!((painted(<, 2).y0 - cell_top(&lp, 2)).abs() < 1e-6 && (cell_top(<, 4) - painted(<, 2).y1).abs() < 1e-6, "{vorg:?}"); + // A space keeps its length down the column. + let spaced = vertical("§ §", st); + let tops = |t: &TextObject| layout(&fonts, t).glyphs.iter().map(|g| g.origin.y).collect::>(); + assert_eq!(tops(&with(&spaced, 2, |s| s.tsume = 100.0)), tops(&spaced), "{vorg:?}"); + } +} + +#[test] +fn letters_on_their_side_take_the_tsume_of_horizontal_type() { + // In vertical type a letter lies on its side: its space before and after its ink runs down + // the column, as far as it runs along a horizontal line. + let (across, down) = (point("HOH", style(20.0)), vertical("HOH", style(20.0))); + let moves_along = |t: &TextObject, vertical: bool| { + let (lp, lt) = (layout(db(), t), layout(db(), &with(t, 1, |s| s.tsume = 100.0))); + [1, 2].map(|i| if vertical { painted(<, i).y0 - painted(&lp, i).y0 } else { painted(<, i).x0 - painted(&lp, i).x0 }) + }; + let (h, v) = (moves_along(&across, false), moves_along(&down, true)); + assert!(h[1] < -1.0 && near(&v, &h), "{h:?} {v:?}"); +} + +#[test] +fn tsume_inside_a_tate_chu_yoko_block_keeps_its_cell() { + // Two digits are set across the column as one block one em long; Tsume closes them up across + // it, and the letter after the block keeps its place. + let plain = vertical("H12H", style(20.0)); + let tight = with(&with(&plain, 1, |s| s.tsume = 100.0), 2, |s| s.tsume = 100.0); + let (lp, lt) = (layout(db(), &plain), layout(db(), &tight)); + let side_by_side = (painted(&lp, 1).center().y - painted(&lp, 2).center().y).abs(); + assert!(side_by_side < 1.0, "the digits stand side by side across the column: {side_by_side}"); + let apart = |l: &TextLayout| (painted(l, 2).center().x - painted(l, 1).center().x).abs(); + assert!(apart(<) < apart(&lp) - 1.0, "{} {}", apart(&lp), apart(<)); + assert!((painted(<, 3).y0 - painted(&lp, 3).y0).abs() < 1e-9); + assert!((painted(<, 1).width() - painted(&lp, 1).width()).abs() < 1e-6, "the digits keep their size"); +} + +#[test] +fn upright_glyphs_on_a_vertical_path_take_the_tsume_of_point_type() { + use vectorcraft_doc::TextKind; + use vectorcraft_geom::PathData; + let point_type = vertical("§§§", style(20.0)); + let mut on_path = point_type.clone(); + on_path.kind = + TextKind::OnPath { path: PathData::from_bezpath(&kurbo::Line::new((0.0, 0.0), (0.0, 3000.0)).to_path(0.1)), start: 0.0, end: None }; + let moved = |t: &TextObject| { + let (lp, lt) = (layout(db(), t), layout(db(), &with(t, 2, |s| s.tsume = 100.0))); + [2, 4].map(|i| painted(<, i).y0 - painted(&lp, i).y0) + }; + let (p, path) = (moved(&point_type), moved(&on_path)); + assert!(p[1] < -1.0 && near(&path, &p), "{p:?} {path:?}"); +} + +#[test] +fn bitmap_and_color_glyphs_measure_what_they_paint() { + use crate::test_fonts::{COLOUR_CHAR, colour_bitmap_family, colour_bitmap_font, colr_family, colr_font}; + // Each font keeps the base outline of its color glyph; the image or art drawn in its place is + // what Tsume measures. + let fonts = [ + (colour_bitmap_font(true), colour_bitmap_family(true)), + (colour_bitmap_font(false), colour_bitmap_family(false)), + (colr_font(false), colr_family(false)), + (colr_font(true), colr_family(true)), + ]; + for (font, family) in fonts { + let fonts = FontDb::with_font_dirs(vec![]); + fonts.add_font(font.expect("the test font builds")); + let plain = point(&format!("{COLOUR_CHAR}H"), CharStyle { font_family: family.into(), ..style(100.0) }); + let lp = layout(&fonts, &plain); + let g = &lp.glyphs[0]; + assert!(g.image.is_some() || g.colour.is_some(), "{family}"); + let (start, end) = (g.origin.x, lp.glyphs[1].origin.x); + let p = painted(&lp, 0); + let width = end - start; + let (left, right) = ((p.x0 - start).clamp(0.0, width), (end - p.x1).clamp(0.0, width)); + let lt = layout(&fonts, &with(&plain, 0, |s| s.tsume = 100.0)); + let moved = (painted(<, 0).x0 - p.x0, lt.glyphs[1].origin.x - end); + assert!((moved.0 + left).abs() < 1e-6 && (moved.1 + left + right).abs() < 1e-6, "{family}: {moved:?} {left} {right}"); + assert!((painted(<, 0).width() - p.width()).abs() < 1e-6, "{family}"); } } diff --git a/crates/three-d/src/solid/tests.rs b/crates/three-d/src/solid/tests.rs index a75821e696..0d9566e5e5 100644 --- a/crates/three-d/src/solid/tests.rs +++ b/crates/three-d/src/solid/tests.rs @@ -1457,7 +1457,7 @@ fn touching_contours_keep_their_parts_and_holes() { #[test] fn an_open_subpath_closes_straight_whether_or_not_contours_meet() { let open = vectorcraft_geom::SubPath { - anchors: vec![ + anchors: vectorcraft_geom::anchors![ vectorcraft_geom::Anchor { p: Point::new(0.0, 0.0), h_in: Point::new(0.0, -50.0), @@ -1505,7 +1505,7 @@ fn flat_far_and_too_large_merges() { assert!(close(area(&cap), 200.0, 1e-3), "joined, not lost"); // Handles count too: a lobe whose handles reach 1.3e8 widens the boolean's snapping to 1.85e-6. let lobe = vectorcraft_geom::SubPath { - anchors: vec![ + anchors: vectorcraft_geom::anchors![ vectorcraft_geom::Anchor { p: Point::new(0.0, 1000.0), h_in: Point::new(0.0, 1000.0), @@ -1604,7 +1604,7 @@ fn meets_within_twice_the_boolean_tolerance() { // What the boolean is given decides the tolerance: an open subpath's end handles (closed // straight) and a one-anchor subpath (skipped) don't widen it. let ends = vectorcraft_geom::SubPath { - anchors: vec![ + anchors: vectorcraft_geom::anchors![ vectorcraft_geom::Anchor { p: Point::new(0.0, 0.0), h_in: Point::new(1e9, 0.0), @@ -1620,7 +1620,8 @@ fn meets_within_twice_the_boolean_tolerance() { ], closed: false, }; - let speck = vectorcraft_geom::SubPath { anchors: vec![vectorcraft_geom::Anchor::corner(Point::new(1e9, 1e9))], closed: true }; + let speck = + vectorcraft_geom::SubPath { anchors: vectorcraft_geom::anchors![vectorcraft_geom::Anchor::corner(Point::new(1e9, 1e9))], closed: true }; let quiet = PathData::new(vec![ends, speck]); assert_eq!(rings::touch(&rings::closed_straight(&quiet)), 1e-6); // A closing-side handle at either end alone is enough to close the subpath straight. @@ -1653,7 +1654,7 @@ fn the_merged_rings_are_turned_as_a_whole() { #[test] fn a_one_anchor_subpath_builds_nothing() { let loop_ = vectorcraft_geom::SubPath { - anchors: vec![vectorcraft_geom::Anchor { + anchors: vectorcraft_geom::anchors![vectorcraft_geom::Anchor { p: Point::new(0.0, 0.0), h_in: Point::new(-20.0, 30.0), h_out: Point::new(20.0, 30.0), diff --git a/crates/tools/src/addons/extend_path.rs b/crates/tools/src/addons/extend_path.rs index 2269396f90..816000ac9f 100644 --- a/crates/tools/src/addons/extend_path.rs +++ b/crates/tools/src/addons/extend_path.rs @@ -178,10 +178,10 @@ impl Tool for ExtendPathTool { let (k, n) = (end.sp.anchors.len(), ext.anchors.len()); // From the old end on; a stretched last curve (no anchor added) shows whole. let from = if n > k { k - 1 } else { n.saturating_sub(2) }; - let tail = if end.start { ext.anchors.get(..n - from) } else { ext.anchors.get(from..) }; + let tail = if end.start { ext.anchors.get_range(..n - from) } else { ext.anchors.get_range(from..) }; if let Some(tail) = tail { let mut bp = vectorcraft_geom::BezPath::new(); - SubPath::new(tail.to_vec(), false).to_bezpath_into(&mut bp); + SubPath::new(tail, false).to_bezpath_into(&mut bp); out.push(Overlay::Path { path: bp, color: GREY, width: 1.0, dashed: true }); } } diff --git a/crates/tools/src/addons/smart_pen.rs b/crates/tools/src/addons/smart_pen.rs index c25ab8f670..43269ed580 100644 --- a/crates/tools/src/addons/smart_pen.rs +++ b/crates/tools/src/addons/smart_pen.rs @@ -478,9 +478,9 @@ impl SmartPenTool { } else { straighten_segment(&mut sp, prev); } - let tail = sp.anchors.get(prev..)?; + let tail = sp.anchors.get_range(prev..)?; let mut bp = BezPath::new(); - SubPath::new(tail.to_vec(), false).to_bezpath_into(&mut bp); + SubPath::new(tail, false).to_bezpath_into(&mut bp); Some(bp) } } diff --git a/crates/tools/src/builder.rs b/crates/tools/src/builder.rs index 00005e3c21..51617935f5 100644 --- a/crates/tools/src/builder.rs +++ b/crates/tools/src/builder.rs @@ -41,9 +41,10 @@ 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, 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, + EDGE_NAME, FACE_NAME, Face, LIVE_PAINT_NAME, LIVE_PAINT_PREFIX, LP_JOIN_TOL, SOURCES_NAME, builder_members, connected_edges, + connected_edges_through, 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 bdb1ca2e7b..b32535d83e 100644 --- a/crates/tools/src/builder/live_paint.rs +++ b/crates/tools/src/builder/live_paint.rs @@ -1,14 +1,15 @@ use super::cache::RegionCache; use super::lookup::{ - connected_edges, edges, faces, 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, + connected_edges, connected_edges_through, edges, face_at, faces, 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::map::{BuilderMap, 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; +use vectorcraft_pathops as po; // ---------- Live Paint Bucket ---------- @@ -178,10 +179,12 @@ enum LpPaint { /// /// 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 +/// A triple-click on a face fills every face of the group that has the face's fill, and on an edge +/// it paints every edge of the group that draws with the edge's stroke paint (`scope: +/// "samePaint"`); each of them takes the bucket's paint. Each click of a double-click or +/// triple-click paints as it arrives, as its own undo step when it changes a paint, and the paint +/// compared is the one the face or edge had before the first of its clicks that painted it, +/// including a click whose drag or release crossed 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 @@ -201,6 +204,8 @@ pub struct LivePaintBucketTool { at: Option<(Point, Mods)>, /// The fill command and polyline previewed from the press's snapshot. fill_drag: Option<(Value, Vec>)>, + /// What a fill drag paints, as it was at its press. + drag_from: LpDragFrom, /// 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>, @@ -229,22 +234,128 @@ struct LpPress { /// 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 other faces the press's drag crossed, its release included, each with its fill before + /// the press. + dragged: Vec<(NodeId, Paint)>, + /// For a press that makes the Live Paint group: what the group is made from, with the path + /// chunks of the press's drag, its release included. + dragged_made: Option>)>>, } -/// 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); +/// What a Live Paint Bucket fill drag paints, as it was at the press. +#[derive(Default)] +enum LpDragFrom { + #[default] + None, + /// The faces of an existing Live Paint group. + Faces(Vec>), + /// What the group is made from, for a drag that makes the group. + Made(LpMade), +} + +/// The faces among `faces` (a Live Paint group's faces, back to front) that a drag along the path +/// chunks `chunks` crosses, as `livePaint.fill` finds them, each with its fill. +fn crossed_faces(faces: &[Arc], chunks: &[Vec]) -> Vec<(NodeId, Paint)> { + let mut hit = vec![]; + let mut regions = vec![]; + // Front first, as visible_face_at looks. + for f in faces.iter().rev().filter(|f| f.visible) { + if let Some(path) = f.path_data() + && let Some(bounds) = path.bounds() + { + hit.push(f); + regions.push((po::Region { path: path.clone(), sources: vec![] }, path.to_bezpath(), bounds)); + } } + let map = BuilderMap { regions, ..Default::default() }; + let mut crossed: Vec<(NodeId, Paint)> = vec![]; + for chunk in chunks { + for f in map.hits_along(chunk, None).regions.iter().filter_map(|i| hit.get(*i)) { + if !crossed.iter().any(|(id, _)| *id == f.id) { + crossed.push((f.id, f.appearance.fill_paint())); + } + } + } + crossed +} + +/// What the Live Paint group a fill press makes from the selection is made from, as it was at the +/// press, following Live Paint Make and Merge. +#[derive(Debug, PartialEq)] +struct LpMade { + /// The paint Merge keeps from the faces of the first selected Live Paint group that draw: a + /// point inside each face with its fill, given to the made face that holds the point. + kept: Vec<(Point, Paint)>, + /// The paths the faces are made from, back to front: Merge's group's source paths first, then + /// the other objects', a Live Paint group giving its source paths. + sources: Vec, +} + +/// What the Live Paint group the selected `roots` make is made from ([`LpMade`]). +fn made_leaves(doc: &Document, roots: &[NodeId]) -> LpMade { + let nodes: Vec<&Node> = roots.iter().filter_map(|id| doc.node(*id)).collect(); + let target = nodes.iter().position(|n| is_live_paint(n)); + let mut kept = vec![]; + let mut sources = vec![]; + for i in target.into_iter().chain((0..nodes.len()).filter(|i| Some(*i) != target)) { + let Some(n) = nodes.get(i) else { continue }; + if !is_live_paint(n) { + leaf_shapes(n, &mut sources); + continue; + } + for s in super::lookup::sources(n).and_then(|g| g.children()).into_iter().flatten() { + leaf_shapes(s, &mut sources); + } + if Some(i) == target { + let draws = |f: &&Arc| f.visible && f.opacity > 0.0 && (f.appearance.has_drawn_fill() || f.appearance.has_drawn_stroke()); + // Merge fixes a kept unplaced gradient to its fit on the face it comes from. + let kept_fill = |f: &Arc| { + let mut n = (**f).clone(); + n.pin_gradients(); + n.appearance.fill_paint() + }; + kept.extend(faces(n).into_iter().filter(draws).filter_map(|f| Some((po::interior_point(f.path_data()?)?, kept_fill(f))))); + } + } + LpMade { kept, sources: sources.into_iter().cloned().collect() } +} + +/// The fill a face made at `p` from the source paths of `made` gets: the topmost fill that draws +/// of the front-most source path whose closed subpaths hold `p` and that has such a fill, else +/// none. Open subpaths bound no face. +fn made_face_fill(made: &LpMade, p: Point) -> Paint { 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()) + // As Make: the front-most covering source with a fill that draws (shown, with paint and an + // opacity above 0, on a source with an opacity above 0) gives the face its topmost such fill, + // an unplaced gradient fixed to its fit on the source. + made.sources + .iter() + .rev() + .filter(|l| l.opacity > 0.0 && l.appearance.has_drawn_fill() && holds(l)) + .find_map(|l| { + let mut n = l.clone(); + n.pin_gradients(); + n.appearance.items.iter().rev().find_map(|i| match i { + vectorcraft_doc::AppearanceItem::Fill(f) if f.visible && !f.paint.is_none() && f.opacity > 0.0 => Some(f.paint.clone()), + _ => None, + }) + }) + .unwrap_or(Paint::None) +} + +/// The fill face `face` of Live Paint group `group` was made with from `made`: the kept paint +/// whose point the face holds (the last one, as Merge applies them in order), else the fill of the +/// source path at a point inside the face. +fn made_part_fill(made: &LpMade, group: &Node, face: &Node) -> Paint { + if let Some((_, paint)) = made.kept.iter().rev().find(|(p, _)| face_at(group, *p).is_some_and(|f| f.id == face.id)) { + return paint.clone(); + } + face.path_data().and_then(po::interior_point).map_or(Paint::None, |p| made_face_fill(made, p)) } /// How many presses the Live Paint Bucket keeps: the three of a triple-click. @@ -260,6 +371,7 @@ impl Default for LivePaintBucketTool { hover: LpHover::None, at: None, fill_drag: None, + drag_from: LpDragFrom::None, presses: Vec::new(), fills: true, strokes: false, @@ -336,7 +448,26 @@ impl LivePaintBucketTool { /// 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![] })); + self.note_press(Some(LpPress { part: Some(n.id), at, before, also: vec![], dragged: vec![], dragged_made: None })); + } + + /// End the fill drag, noting on the last press the other faces its drag crossed, with their + /// fills before the press (for a press that makes the group, what the group is made from and + /// the drag, for [`Self::before`] to look the faces up in the group made). → whether a fill + /// drag was on. + fn end_fill(&mut self) -> bool { + let from = std::mem::take(&mut self.drag_from); + let Some((_, chunks)) = self.fill_drag.take() else { return false }; + let Some(Some(last)) = self.presses.last_mut() else { return true }; + match from { + LpDragFrom::None => {} + LpDragFrom::Faces(faces) => { + let part = last.part; + last.dragged = crossed_faces(&faces, &chunks).into_iter().filter(|(id, _)| part != Some(*id)).collect(); + } + LpDragFrom::Made(made) => last.dragged_made = Some(Arc::new((made, chunks))), + } + true } /// Note that the double-click after the last press also reaches `parts` of group `group`, with @@ -356,12 +487,17 @@ impl LivePaintBucketTool { /// 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. + /// filled there is `part`), a press's drag or release crossing `part` included; `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)) { + let made_part = |at: Point| live_paint_at(cx.doc, at).and_then(|g| visible_face_at(cx.doc.node(g)?, 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.at)); + let dragged = |q: &LpPress| q.dragged.iter().any(|(id, _)| *id == part); + // An earlier press of the sequence that painted `part` counts too: a press on the next edge + // released back on `part` paints that edge, and the double-click targets `part`. + let painted = run.iter().enumerate().any(|(i, q)| q.as_ref().is_some_and(|q| on_part(i, q))); + if !painted && !run.last().and_then(Option::as_ref).is_some_and(dragged) { return now; } for (i, q) in run.iter().enumerate() { @@ -369,7 +505,17 @@ impl LivePaintBucketTool { if on_part(i, q) { return q.before.clone(); } - if let Some((_, paint)) = q.also.iter().find(|(id, _)| *id == part) { + // A face of the group the press made (the one under the press) that its drag crossed has + // the fill it was made with. + if i == 0 + && let Some(drag) = &q.dragged_made + && let Some(group) = live_paint_at(cx.doc, q.at).and_then(|g| cx.doc.node(g)) + && let Some(face) = faces(group).into_iter().find(|f| f.id == part) + && !crossed_faces(std::slice::from_ref(face), &drag.1).is_empty() + { + return made_part_fill(&drag.0, group, face); + } + if let Some((_, paint)) = q.dragged.iter().chain(&q.also).find(|(id, _)| *id == part) { return paint.clone(); } } @@ -395,7 +541,23 @@ impl LivePaintBucketTool { if clicks == 2 && let Some(group) = cx.doc.node(g) { - self.note_reached(group, connected_edges(group, e.id, &like), true); + // The other edge either click painted joins as the stroke paint it had before. + let through: Vec = self + .presses + .len() + .checked_sub(2) + .and_then(|i| self.presses.get(i..)) + .into_iter() + .flatten() + .flatten() + .filter(|q| q.before == like) + .filter_map(|q| q.part) + .filter(|id| *id != e.id) + .collect(); + self.note_reached(group, connected_edges_through(group, e.id, &like, &through), true); + if !through.is_empty() { + v["through"] = json_ids(&through); + } } if let Ok(like) = serde_json::to_value(like) { v["match"] = like; @@ -495,7 +657,7 @@ impl Tool for LivePaintBucketTool { fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { let p = ev.pos; // A second press finishes the preceding click, including callers without a release. - if ev.kind == PointerKind::Down && self.fill_drag.take().is_some() { + if ev.kind == PointerKind::Down && self.end_fill() { let mut acts = vec![Action::Commit]; acts.extend(self.pointer(cx, ev)); return acts; @@ -553,11 +715,15 @@ impl Tool for LivePaintBucketTool { Some(f) => self.note_part(f, false, p), None => self.note_press(None), } + self.drag_from = LpDragFrom::Faces(cx.doc.node(g).map(|n| faces(n).into_iter().cloned().collect()).unwrap_or_default()); 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![] })); + let made = made_leaves(cx.doc, &roots); + let before = made_face_fill(&made, p); + self.note_press(Some(LpPress { part: None, at: p, before, also: vec![], dragged: vec![], dragged_made: None })); + self.drag_from = LpDragFrom::Made(made); return self.begin_fill(json!({ "ids": json_ids(&roots), "point": point }), p); } self.note_press(None); @@ -568,7 +734,7 @@ impl Tool for LivePaintBucketTool { // The swatch preview shows again at the release point. self.at = Some((p, ev.mods)); let mut acts = self.drag_fill(p); - if self.fill_drag.take().is_some() { + if self.end_fill() { acts.push(Action::Commit); } acts @@ -586,6 +752,7 @@ impl Tool for LivePaintBucketTool { /// the active paint, while no drag is on. fn key(&mut self, cx: &ToolContext, key: ToolKey, mods: Mods) -> Vec { if key == ToolKey::Escape { + self.drag_from = LpDragFrom::None; return if self.fill_drag.take().is_some() { vec![Action::Cancel] } else { vec![] }; } if !self.claims_key_with(cx, key, mods) { @@ -621,7 +788,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![] } + if self.end_fill() { vec![Action::Commit] } else { vec![] } } /// The pointer hovers nothing for the tool: its highlight and its swatch preview go. @@ -630,6 +797,12 @@ impl Tool for LivePaintBucketTool { self.at = None; } + /// A press the view tools took counts as a press that paints no face or edge, for the clicks + /// a double-click or triple-click compares. + fn press_elsewhere(&mut self) { + self.note_press(None); + } + fn overlays(&self, cx: &ToolContext) -> Vec { let mut out = lp_overlays(&self.hover, &self.cache, self.color, self.width as f32, (self.width * LP_BUCKET_EDGE_FRACTION) as f32); // No chips during a fill drag, or while Alt makes the tool sample with the eyedropper. diff --git a/crates/tools/src/builder/lookup.rs b/crates/tools/src/builder/lookup.rs index daa9a34f82..7a08deaed3 100644 --- a/crates/tools/src/builder/lookup.rs +++ b/crates/tools/src/builder/lookup.rs @@ -405,8 +405,15 @@ impl LpEdgeGrid { /// 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 { + connected_edges_through(group, start, paint, &[]) +} + +/// [`connected_edges`], with the edges in `through` counted as drawing with stroke paint `paint` +/// whatever paint they draw with now. +pub fn connected_edges_through(group: &Node, start: NodeId, paint: &Paint, through: &[NodeId]) -> 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(); + let es: Vec<&Arc> = + edges(group).into_iter().filter(|e| e.visible && (e.id == start || through.contains(&e.id) || lp_stroke_paint(e) == *paint)).collect(); // The first and last points of each subpath of each edge. let ends: Vec> = es .iter() diff --git a/crates/tools/src/builder/tests.rs b/crates/tools/src/builder/tests.rs index 75e15da82d..8d6788bbbc 100644 --- a/crates/tools/src/builder/tests.rs +++ b/crates/tools/src/builder/tests.rs @@ -1386,6 +1386,39 @@ fn bucket_triple_click_with_a_click_on_another_face_between_matches_the_first_fi ); } +/// A triple-click whose second press the view tools take (held Space) matches the fill the face had +/// before the first click: that press counts as one that paints nothing. The pointer leaving the +/// canvas between three clicks adds no press. +#[test] +fn bucket_triple_click_with_a_view_tool_press_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 own = serde_json::to_value(d.node(f2).unwrap().appearance.fill_paint()).unwrap(); + assert_ne!(own, serde_json::to_value(&red).unwrap()); + let want = vec![Action::Exec("livePaint.fill".into(), json!({ "group": gid.0, "point": [75.0, 25.0], "scope": "samePaint", "match": own }))]; + fn click(t: &mut LivePaintBucketTool, ctx: &ToolContext) { + t.pointer(ctx, &ev(PointerKind::Down, 75.0, 25.0)); + t.pointer(ctx, &ev(PointerKind::Up, 75.0, 25.0)); + } + let mut t = LivePaintBucketTool::default(); + click(&mut t, &cx); + t.press_elsewhere(); + click(&mut t, &later); + assert_eq!(t.pointer(&later, &ev(PointerKind::TripleClick, 75.0, 25.0)), want, "a view tool's press between"); + let mut t = LivePaintBucketTool::default(); + click(&mut t, &cx); + click(&mut t, &later); + t.hover_ended(&later); + click(&mut t, &later); + assert_eq!(t.pointer(&later, &ev(PointerKind::TripleClick, 75.0, 25.0)), want, "the pointer leaving between"); +} + /// With Space held for the view tools, the pointer outlines no face or edge, as a press there /// paints nothing. #[test] @@ -2736,6 +2769,58 @@ fn live_paint_selection_triple_click_series_ends_with_the_same_paint_parts() { assert_eq!(sel, vec![c.0]); } +/// A Shift-triple-click on a face whose double-click already reaches a joined face of the same +/// fill selects every face with that fill: the joined face the double-click toggled on is not +/// toggled off again. +#[test] +fn live_paint_selection_shift_triple_click_keeps_joined_faces_of_the_same_fill() { + let mut d = Document::new(500.0, 500.0); + let (_, [a, b, c], _) = live_strip(&mut d); + let red = Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)); + // A and B are joined across the unstroked edge AB; C is parted from them by the stroked edge BC. + for id in [a, b, c] { + d.node_mut(id).unwrap().appearance.set_fill(red.clone()); + } + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let shift = Mods { shift: true, ..Default::default() }; + let mut t = LivePaintSelectionTool::default(); + let mut sel: Vec = vec![]; + for kind in [ + PointerKind::Down, + PointerKind::Up, + PointerKind::Down, + PointerKind::Up, + PointerKind::DoubleClick, + PointerKind::Down, + PointerKind::Up, + PointerKind::TripleClick, + ] { + for act in t.pointer(&cx, &ev(kind, 25.0, 25.0).with_mods(shift)) { + let Action::Exec(cmd, args) = act else { panic!("{act:?}") }; + assert_eq!(cmd, "select.toggle"); + let ids: Vec = match (args.get("ids"), args.get("id")) { + (Some(v), _) => v.as_array().unwrap().iter().map(|i| i.as_u64().unwrap()).collect(), + (None, Some(i)) => vec![i.as_u64().unwrap()], + (None, None) => vec![], + }; + for i in ids { + match sel.iter().position(|x| *x == i) { + Some(k) => { + sel.remove(k); + } + None => sel.push(i), + } + } + } + } + sel.sort_unstable(); + let mut want = vec![a.0, b.0, c.0]; + want.sort_unstable(); + assert_eq!(sel, want); +} + #[test] fn live_paint_selection_double_click_skips_locked_groups_and_art_outside_isolation() { let mut d = Document::new(500.0, 500.0); diff --git a/crates/tools/src/distort/liquify.rs b/crates/tools/src/distort/liquify.rs index efc68132a1..0dc599444f 100644 --- a/crates/tools/src/distort/liquify.rs +++ b/crates/tools/src/distort/liquify.rs @@ -547,7 +547,7 @@ fn simplify(sp: &mut SubPath, tol: f64, region: Rect) { None => out[0].h_in = h_in, } } - sp.anchors = out; + sp.anchors = out.into(); } /// Apply a liquify stroke (its dabs, at the brush's intensity) to `path`. `salt` decorrelates diff --git a/crates/tools/src/draw2.rs b/crates/tools/src/draw2.rs index 46e77314b6..9401dcd4c2 100644 --- a/crates/tools/src/draw2.rs +++ b/crates/tools/src/draw2.rs @@ -21,7 +21,7 @@ pub use curvature::{ CurvatureTool, EndCurve, curvature_close, curvature_extend, curvature_insert, curvature_move, curvature_remove, curvature_smooth, }; pub use family::FamilyTool; -pub use gesture::GestureTool; +pub use gesture::{GestureTool, can_smooth}; /// Colour of tool feedback (Illustrator's selection blue). pub const FEEDBACK: [u8; 3] = [0x4f, 0x9d, 0xff]; diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index 75b71ec8df..7d6f997cf9 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -190,6 +190,10 @@ pub struct GestureTool { /// Which way the pen leaned at the last point of the stroke where it leaned 1° or more from /// upright ([`super::pen_bearing`]), for the Eraser's tip outline. bearing: Option, + /// `bearing` as it was at each of `poses`, for the outline of the area the Eraser's drag covers. + bearings: Vec>, + /// The first of `bearings` that the pen gave: the release gives it to the points before it. + first_bearing: Option, /// The length of the stroke, in points. length: f64, /// The outline of the area a Blob Brush or Eraser drag covers, as far as it is built @@ -791,9 +795,16 @@ fn redraw_targets(cx: &ToolContext, id: NodeId) -> Vec { /// Whether the selection contains a path the Smooth command can act on: one with a subpath of three /// or more anchors, or of two anchors joined by a curve. fn has_selected_smooth_path(cx: &ToolContext) -> bool { - let editable = cx.doc.editable(); + can_smooth(cx.doc, cx.selection) +} + +/// Whether `selection` in `doc` holds an editable path, selected or inside a selected object, that +/// the Smooth tool can smooth: one with a subpath of three or more anchors, or of two anchors +/// joined by a curve. +pub fn can_smooth(doc: &vectorcraft_doc::Document, selection: &vectorcraft_doc::Selection) -> bool { + let editable = doc.editable(); let smoothable = |sp: &vectorcraft_geom::SubPath| sp.anchors.len() >= 3 || (0..sp.segment_count()).any(|i| !super::segment_is_straight(sp, i)); - cx.selection.objects.iter().filter_map(|id| cx.doc.node(*id)).any(|n| { + selection.objects.iter().filter_map(|id| doc.node(*id)).any(|n| { let mut found = false; n.walk(&mut |child| { if !found @@ -871,6 +882,8 @@ impl GestureTool { tip_at: None, light: false, bearing: None, + bearings: vec![], + first_bearing: None, length: 0.0, area: Cell::new(None), area_pending: Cell::new(false), @@ -938,6 +951,8 @@ impl GestureTool { let pose = ev.pen.map(PenPose::sanitized); self.bearing = pose.and_then(super::pen_bearing).or(self.bearing); self.poses.push(pose); + self.bearings.push(self.bearing); + self.first_bearing = self.first_bearing.or(self.bearing); } } @@ -959,6 +974,14 @@ impl GestureTool { None if had_bearing => self.poses.iter().rev().find_map(|q| q.and_then(super::pen_bearing)), None => self.bearing, }; + if let Some(b) = self.bearings.last_mut() { + *b = self.bearing; + } + // The bearings carry forward, so the last sample gives the first bearing only when the one + // before it has none. + if self.bearings.len().checked_sub(2).and_then(|i| self.bearings.get(i)).copied().flatten().is_none() { + self.first_bearing = self.bearing; + } } /// Would a press with `m` held draw a straight Pencil line? Shift or Alt held, unless Alt lends @@ -1046,6 +1069,8 @@ impl GestureTool { self.shift_line = None; self.light = false; self.bearing = None; + self.bearings.clear(); + self.first_bearing = None; self.length = 0.0; self.area.set(None); self.area_pending.set(false); @@ -1106,12 +1131,74 @@ impl GestureTool { matches!(self.id, "blobBrush" | "eraser") } - /// The pen pressure of each point of a Blob Brush or Eraser stroke whose Size varies with - /// Pressure, when a pen pressed less than fully anywhere along it (a stroke without pressure - /// keeps its Size). - fn size_pressures(&self) -> Option<&[f32]> { - let pressed = self.pressures.len() == self.points.len() && self.light; - (self.tip_modes()[2] == Variation::Pressure && !self.smoothing && pressed).then_some(self.pressures.as_slice()) + /// Which of the tip's angle, roundness and size vary along a Blob Brush or Eraser stroke: those + /// on a mode the pen gave a reading for anywhere along it (a pressure less than full, a tilt, a + /// bearing or a rotation). Random draws one value from the whole drag at the release, and the + /// outline shows the value itself. + fn tip_varies(&self) -> [bool; 3] { + let (pressed, posed) = (self.reads_pressures(), self.reads_poses()); + let reads = |mode: Variation| match mode { + Variation::Pressure => pressed, + Variation::Tilt => posed && self.poses.iter().flatten().any(|q| q.tilt.is_some()), + Variation::Bearing => posed && self.bearings.iter().any(Option::is_some), + Variation::Rotation => posed && self.poses.iter().flatten().any(|q| q.rotation.is_some()), + Variation::Fixed | Variation::Random => false, + }; + if self.smoothing { + return [false; 3]; + } + self.tip_modes().map(reads) + } + + /// Does the release read the stroke's pressures ([`Self::stroke_json`]): one for every point, + /// with the pen pressed less than fully somewhere? A mode set to Pressure during the drag + /// leaves the points before it without one. + fn reads_pressures(&self) -> bool { + self.light && self.pressures.len() == self.points.len() + } + + /// Does the release read the stroke's tilts and rotations ([`Self::stroke_json`]): a pose for + /// every point? A mode set to Tilt, Bearing or Rotation during the drag leaves the points + /// before it without one. + fn reads_poses(&self) -> bool { + self.poses.len() == self.points.len() + } + + /// The tip at point `i` of the stroke, as `path.eraseRegion` reads the pen there + /// ([`Self::controls_of_point`]). + fn tip_of_point(&self, i: usize) -> [f64; 3] { + self.tip_of_controls(self.controls_of_point(i)) + } + + /// The tip halfway along the step from point `j` to point `j + 1`, as `path.eraseRegion` reads + /// the pen there: the pressure and tilt halfway between those at the two points, and the + /// bearing and rotation halfway between them the shorter way round. A tip whose angle follows + /// the pressure from 0 at one point to 1 at the next lies level there, not turned as at + /// either end. + fn tip_between(&self, j: usize) -> [f64; 3] { + let (a, b) = (self.controls_of_point(j), self.controls_of_point(j + 1)); + // Bearing and rotation read ½ plus the angle over 360° ([`super::pen_controls`]). + let turn = |a: f64, b: f64| { + let (a, b) = ((a - 0.5) * 360.0, (b - 0.5) * 360.0); + 0.5 + vectorcraft_geom::normalize_deg(a + vectorcraft_geom::normalize_deg(b - a) / 2.0) / 360.0 + }; + self.tip_of_controls([(a[0] + b[0]) / 2.0, (a[1] + b[1]) / 2.0, turn(a[2], b[2]), turn(a[3], b[3])]) + } + + /// What each of the variation modes Pressure, Tilt, Bearing and Rotation reads at point `i` of + /// the stroke, as `path.eraseRegion` reads the pen there ([`super::pen_controls`]): the + /// pressure once the pen has pressed less than fully, the tilt and rotation of the point, and + /// the bearing of the last point up to it that the pen leaned 1° or more at, or before the + /// first such point the bearing of that first one. What the release does not read + /// ([`Self::reads_pressures`], [`Self::reads_poses`]) reads ½, the values themselves. + fn controls_of_point(&self, i: usize) -> [f64; 4] { + let pressure = if self.reads_pressures() { self.pressures.get(i).map_or(0.5, |p| f64::from(*p)) } else { 0.5 }; + let (pose, bearing) = if self.reads_poses() { + (self.poses.get(i).copied().flatten(), self.bearings.get(i).copied().flatten().or(self.first_bearing)) + } else { + (None, None) + }; + super::pen_controls(pressure, pose, bearing) } /// How the tip's angle, roundness and size vary: the Eraser's three modes, the Blob Brush's @@ -1137,12 +1224,25 @@ impl GestureTool { /// more at), as `path.eraseRegion` reads the stroke; before a press, and for Random, Fixed and a /// pen that gives no reading, the values themselves. The Blob Brush's are its own values. fn tip_now(&self) -> [f64; 3] { - let base = [self.angle, self.roundness, self.size]; if self.id != "eraser" || !self.active { - return base; + return [self.angle, self.roundness, self.size]; } let pressure = if self.light { self.pressures.last().map_or(0.5, |p| f64::from(*p)) } else { 0.5 }; - let controls = super::pen_controls(pressure, self.poses.last().copied().flatten(), self.bearing); + self.tip_for(pressure, self.poses.last().copied().flatten(), self.bearing) + } + + /// The tip's angle, roundness and size for a pen at `pressure` held as `pose`, leaning toward + /// `bearing`: each value on a mode that follows the pen goes from the value less its Variation + /// to the value plus it ([`super::pen_controls`]); for Random, Fixed and what the pen does not + /// give, the values themselves. + fn tip_for(&self, pressure: f64, pose: Option, bearing: Option) -> [f64; 3] { + self.tip_of_controls(super::pen_controls(pressure, pose, bearing)) + } + + /// The tip's angle, roundness and size where the modes Pressure, Tilt, Bearing and Rotation + /// read `controls` (0..1 each, [`super::pen_controls`]). + fn tip_of_controls(&self, controls: [f64; 4]) -> [f64; 3] { + let base = [self.angle, self.roundness, self.size]; let variations = [self.angle_variation, self.roundness_variation, self.size_variation]; let mut out = base; for (i, (v, mode)) in out.iter_mut().zip(self.tip_modes()).enumerate() { @@ -1653,31 +1753,39 @@ impl Tool for GestureTool { }; let color = if self.id == "eraser" { [0x80, 0x80, 0x80] } else { FEEDBACK }; // A tip that is not round shows the outline of the area it covers, each step of the drag - // as wide as the pen pressed there with Size set to Pressure. So does a round Blob Brush - // tip: a line as wide as the brush would end square, where the stroke it adds is round at - // both ends (#4343). The outline is built a bounded amount per call ([`AreaPreview`]). - if matches!(self.id, "eraser" | "blobBrush") && (self.roundness < 100.0 || self.id == "blobBrush") && !self.smoothing { - let pressures = self.size_pressures(); + // with the tip the pen gives there on the modes that follow the pen. So does a round Blob + // Brush tip: a line as wide as the brush would end square, where the stroke it adds is + // round at both ends (#4343). The outline is built a bounded amount per call ([`AreaPreview`]). + let [angle_varies, roundness_varies, size_varies] = self.tip_varies(); + // An angle varies the tip only when it is not round. + let shaped = roundness_varies || (angle_varies && self.roundness < 100.0); + if matches!(self.id, "eraser" | "blobBrush") && (self.roundness < 100.0 || shaped || self.id == "blobBrush") && !self.smoothing { let key = AreaKey { blob: self.id == "blobBrush", size: self.size, - variation: self.size_variation, + variation: if size_varies { self.size_variation } else { 0.0 }, angle: self.angle, roundness: self.roundness, - pressure: pressures.is_some(), + varies: shaped || size_varies, + shaped, + pressed: self.reads_pressures() && self.tip_modes().contains(&Variation::Pressure), + first_bearing: self.first_bearing.filter(|_| self.reads_poses() && self.tip_modes().contains(&Variation::Bearing)), + modes: self.tip_modes(), + variations: [self.angle_variation, self.roundness_variation, self.size_variation], }; let mut area = self.area.take().filter(|a| a.fits(key, &self.points)).unwrap_or_else(|| AreaPreview::new(key, self.points[0])); - area.step(&self.points, pressures); + let sized = |[angle, roundness, size]: [f64; 3]| [angle, roundness, if size_varies { size } else { self.size }]; + area.step(&self.points, &|i| sized(self.tip_of_point(i)), &|j| sized(self.tip_between(j))); let paths = area.paths(&self.points); o.extend(paths.settled.into_iter().map(|path| Overlay::SharedPath { path, color, width: 1.0 })); o.extend(paths.live.into_iter().map(|path| Overlay::Path { path, color, width: 1.0, dashed: false })); self.area_pending.set(area.pending(&self.points)); self.area.set(Some(area)); - } else if let Some(pressures) = self.size_pressures() { - // With Size set to Pressure, each step of the drag shows as wide as the pen pressed there. - for (seg, p) in self.points.windows(2).zip(pressures.windows(2)) { - let pressure = f64::from(p[0] + p[1]) / 2.0; - let width = super::pressure_size(self.size, self.size_variation, pressure) * cx.zoom; + } else if size_varies { + // With Size on a mode that follows the pen, each step of the drag shows as wide as the + // tip the pen gives at its ends. + for (j, seg) in self.points.windows(2).enumerate() { + let width = (self.tip_of_point(j)[2] + self.tip_of_point(j + 1)[2]) / 2.0 * cx.zoom; o.push(Overlay::Path { path: polyline(seg), color, width: width as f32, dashed: false }); } } else { diff --git a/crates/tools/src/draw2/gesture/area.rs b/crates/tools/src/draw2/gesture/area.rs index a56322db40..5a33e6e77f 100644 --- a/crates/tools/src/draw2/gesture/area.rs +++ b/crates/tools/src/draw2/gesture/area.rs @@ -2,10 +2,11 @@ //! tip covers, built a bounded amount at a time. //! //! The drag is cut into pieces of up to [`PIECE_SEGMENTS`] segments (one segment each when the -//! Size varies with pressure). A call outlines again, in the space where the tip is round, only the +//! tip varies along the drag). A call outlines again, in the space where the tip is round, only the //! pieces it added segments to. A piece's outline then loses the parts that lie inside the area //! of another piece, found through a grid of squares that lists the segments near each square, so -//! the pieces show as one outline. One call takes at most [`POINTS_PER_CALL`] new points and does at most +//! the pieces show as one outline. When the tip's angle or roundness varies, each segment has its +//! own space where its tip is round, and the grid is on the page. One call takes at most [`POINTS_PER_CALL`] new points and does at most //! [`WORK_PER_CALL`] units of work, plus the one step it was in; what is left waits for the next //! call ([`AreaPreview::pending`]). Until then a piece shows the outline it last finished, and the //! points not yet taken show as a thin line. The settled pieces show as paths of up to @@ -15,14 +16,15 @@ use std::collections::{BTreeSet, HashMap}; use std::sync::Arc; +use vectorcraft_brush::Variation; use vectorcraft_geom::{Affine, BezPath, Line, ParamCurve, PathData, PathEl, PathSeg, Point, SubPath}; use vectorcraft_pathops as po; use vectorcraft_pathops::{Cap, Join}; use super::super::{MIN_BRUSH_SIZE, blob_tip, eraser_tip, pressure_size}; -/// The most segments of a drag that one piece of its outline holds, when the Size does not vary -/// with pressure (a piece then holds one segment). +/// The most segments of a drag that one piece of its outline holds, when the tip does not vary +/// along the drag (a piece then holds one segment). pub(super) const PIECE_SEGMENTS: usize = 32; /// The most points of a drag one call takes. pub(super) const POINTS_PER_CALL: usize = 256; @@ -68,10 +70,26 @@ pub(super) struct AreaKey { pub variation: f64, pub angle: f64, pub roundness: f64, - /// Each segment is as wide as the pen pressed there. - pub pressure: bool, + /// Each segment takes its own tip from the pen's readings at its ends ([`AreaPreview::step`]): + /// its own size, and with `shaped` its own angle and roundness. + pub varies: bool, + /// Each segment's tip has its own angle and roundness. + pub shaped: bool, + /// The tips at the points take the pen's pressure there: once the pen presses less than fully, + /// a point pressed fully takes the tip of full pressure instead of that of a stroke without + /// pressure. + pub pressed: bool, + /// The bearing the tips take at the points before the pen first leaned, when a tip follows the + /// bearing: the first lean gives it to the points already outlined. + pub first_bearing: Option, + /// The modes and Variations of the angle, roundness and size that the tips at the points follow. + pub modes: [Variation; 3], + pub variations: [f64; 3], } +/// A tip's angle in degrees, roundness in percent and size in points. +pub(super) type Tip = [f64; 3]; + /// The work of the last call. #[derive(Clone, Copy, Default, Debug)] pub(super) struct AreaWork { @@ -129,16 +147,24 @@ struct Check { pub(super) struct AreaPreview { key: AreaKey, first: Point, + /// The map from the page to the grid's space: where the tip is round, or the page itself when + /// each segment's tip has its own angle and roundness. squash: Affine, stretch: Affine, - /// The side of the grid's squares, where the tip is round. + /// The side of the grid's squares, in the grid's space. side: f64, - /// The points taken, where the tip is round. + /// The points taken, in the grid's space. sq: Vec, /// The last point taken, on the page. last: Point, - /// The tip's radius along each segment, where the tip is round. + /// The tip at the last point taken, when the tip varies along the drag. + last_tip: Option, + /// The tip's radius along each segment, where its tip is round. It is also as far as the + /// segment's area reaches from the segment in the grid's space. radius: Vec, + /// The map from the grid's space to the space where each segment's tip is round, when each + /// segment's tip has its own angle and roundness (empty otherwise: the grid's space). + to_round: Vec, pieces: Vec, squares: HashMap<(i64, i64), Vec>, /// How many listings the squares hold ([`LISTINGS`]). @@ -156,8 +182,12 @@ pub(super) struct AreaPreview { impl AreaPreview { /// The outline of a drag that starts at `first`. pub(super) fn new(key: AreaKey, first: Point) -> Self { - let stretch = if key.blob { blob_tip(key.angle, key.roundness) } else { eraser_tip(key.angle, key.roundness) }; - let widest = if key.pressure { pressure_size(key.size, key.variation, 1.0) } else { key.size }; + let stretch = match key { + AreaKey { shaped: true, .. } => Affine::IDENTITY, + AreaKey { blob: true, .. } => blob_tip(key.angle, key.roundness), + _ => eraser_tip(key.angle, key.roundness), + }; + let widest = if key.varies { pressure_size(key.size, key.variation, 1.0) } else { key.size }; Self { key, first, @@ -166,7 +196,9 @@ impl AreaPreview { side: widest.max(MIN_BRUSH_SIZE), sq: vec![], last: first, + last_tip: None, radius: vec![], + to_round: vec![], pieces: vec![], squares: HashMap::new(), listed: 0, @@ -208,28 +240,49 @@ impl AreaPreview { } /// Take the points of the drag `pts` added since the last call and check outlines, within this - /// call's limits. `pressures` holds the pen pressure at each point when the Size varies with it. - pub(super) fn step(&mut self, pts: &[Point], pressures: Option<&[f32]>) { + /// call's limits. When the tip varies along the drag, `tip(i)` gives the tip at point `i`, and + /// segment `j` takes `middle(j)`, the tip halfway along it. A last point whose tip changed since + /// it was taken (a pen turned or tilted in place) gives its segment the new tip. + pub(super) fn step(&mut self, pts: &[Point], tip: &dyn Fn(usize) -> Tip, middle: &dyn Fn(usize) -> Tip) { self.work = AreaWork::default(); let mut changed = BTreeSet::new(); + if self.key.varies + && let Some(j) = self.sq.len().checked_sub(2) + && self.last_tip.is_some_and(|t| t != tip(j + 1)) + { + let k = self.piece_of(j); + let old = self.radius[j]; + self.set_tip(j, middle(j)); + self.last_tip = Some(tip(j + 1)); + changed.insert(k); + // The pieces near the old tip or the new one are checked again. + let new = self.radius[j]; + self.radius[j] = old.max(new); + self.near(j, k, false); + self.radius[j] = new; + } while self.sq.len() < pts.len() && self.work.points < POINTS_PER_CALL && self.work.work < WORK_PER_CALL { let i = self.sq.len(); self.sq.push(self.squash * pts[i]); self.last = pts[i]; self.work.points += 1; + if self.key.varies { + self.last_tip = Some(tip(i)); + } let Some(j) = i.checked_sub(1) else { continue }; - let size = match pressures.filter(|_| self.key.pressure).and_then(|f| f.get(j..=i)) { - Some(f) => pressure_size(self.key.size, self.key.variation, f64::from(f[0] + f[1]) / 2.0), - None => self.key.size, - }; - self.radius.push(size / 2.0); - if self.key.pressure || self.pieces.last().is_none_or(|p| p.to - p.from >= PIECE_SEGMENTS) { + if self.key.varies { + self.radius.push(0.0); + self.set_tip(j, middle(j)); + } else { + self.radius.push(self.key.size / 2.0); + } + if self.key.varies || self.pieces.last().is_none_or(|p| p.to - p.from >= PIECE_SEGMENTS) { self.pieces.push(Piece { from: j, to: j, outline: vec![], shown: BezPath::new() }); } let k = self.pieces.len() - 1; self.pieces[k].to = j + 1; changed.insert(k); - self.list(j, k); + self.near(j, k, true); } for k in changed { self.outline_piece(k); @@ -237,6 +290,24 @@ impl AreaPreview { self.check_some(); } + /// Give segment `j` the tip `[angle, roundness, size]`, the tip halfway along it: its radius, + /// and with `shaped` the map to the space where that tip is round. + fn set_tip(&mut self, j: usize, [angle, roundness, size]: Tip) { + self.radius[j] = size.max(MIN_BRUSH_SIZE) / 2.0; + if self.key.shaped { + let round = eraser_tip(angle, roundness).inverse(); + match self.to_round.get_mut(j) { + Some(m) => *m = round, + None => self.to_round.push(round), + } + } + } + + /// The map from the grid's space to the space where segment `m`'s tip is round. + fn round_of(&self, m: usize) -> Affine { + self.to_round.get(m).copied().unwrap_or(Affine::IDENTITY) + } + /// The paths to show: the settled pieces' outlines, joined [`BLOCK_PIECES`] at a time, the /// growing last piece's and a thin line over the points of `pts` not taken yet. The joined /// paths with a changed piece are joined again, newest first, at most @@ -281,13 +352,13 @@ impl AreaPreview { /// How many pieces no longer grow: all of them but a last one with room for more segments. fn settled_count(&self) -> usize { - let growing = !self.key.pressure && self.pieces.last().is_some_and(|p| p.to - p.from < PIECE_SEGMENTS); + let growing = !self.key.varies && self.pieces.last().is_some_and(|p| p.to - p.from < PIECE_SEGMENTS); self.pieces.len() - usize::from(growing) } /// The piece that holds segment `j`. fn piece_of(&self, j: usize) -> usize { - if self.key.pressure { j } else { j / PIECE_SEGMENTS } + if self.key.varies { j } else { j / PIECE_SEGMENTS } } /// The square of the grid that holds `p`; `None` far outside any document. @@ -317,16 +388,16 @@ impl AreaPreview { Some(keys) } - /// List segment `j` of piece `k` in the squares its area reaches, and mark the other pieces - /// whose outline its area can reach to be checked again. - fn list(&mut self, j: usize, k: usize) { + /// With `add`, list segment `j` of piece `k` in the squares its area reaches; either way, mark + /// the other pieces whose outline its area can reach to be checked again. + fn near(&mut self, j: usize, k: usize, add: bool) { let (a, b, r) = (self.sq[j], self.sq[j + 1], self.radius[j]); let mut near = vec![]; match self.squares_along(a, b, SEGMENT_SAMPLES) { Some(keys) => { for key in keys { self.work.work += 1; - if self.listed >= LISTINGS { + if self.listed >= LISTINGS || !add { near.extend(self.squares.get(&key).into_iter().flatten().map(|m| *m as usize)); continue; } @@ -350,7 +421,7 @@ impl AreaPreview { } } } - if self.wide.len() < WIDE_SEGMENTS { + if add && self.wide.len() < WIDE_SEGMENTS { self.wide.push(j); } } @@ -374,10 +445,21 @@ impl AreaPreview { fn outline_piece(&mut self, k: usize) { let settled = self.settled_count(); let Some(p) = self.pieces.get(k) else { return }; - let pts = &self.sq[p.from..=p.to]; let width = 2.0 * self.radius[p.from]; - self.work.outlined += pts.len(); - let area = po::outline_stroke(&PathData::single(SubPath::polyline(pts, false)), width, Cap::Round, Join::Round, 4.0).to_bezpath(); + self.work.outlined += p.to + 1 - p.from; + // A piece whose tip has its own angle and roundness (one segment) is outlined where that + // tip is round and taken back to the grid's space. + let area = match self.to_round.get(p.from) { + Some(&round) => { + let pts = [round * self.sq[p.from], round * self.sq[p.to]]; + round.inverse() + * po::outline_stroke(&PathData::single(SubPath::polyline(&pts, false)), width, Cap::Round, Join::Round, 4.0).to_bezpath() + } + None => { + let pts = &self.sq[p.from..=p.to]; + po::outline_stroke(&PathData::single(SubPath::polyline(pts, false)), width, Cap::Round, Join::Round, 4.0).to_bezpath() + } + }; let outline = segments(&area); let shown = self.stretch * area; if let Some(p) = self.pieces.get_mut(k) { @@ -454,7 +536,11 @@ impl AreaPreview { /// The stretches of `seg` (from and to, 0 at its start, 1 at its end) that lie inside no area /// of a segment of the drag but `own`. fn visible(&mut self, seg: PathSeg, own: std::ops::Range) -> Vec<(f64, f64)> { - let inside = |s: &Self, q: Point, m: usize| distance_to_segment(q, s.sq[m], s.sq[m + 1]) < s.radius[m] * (1.0 - INSIDE); + // Each segment's area is tested where its tip is round. + let inside = |s: &Self, q: Point, m: usize| { + let round = s.round_of(m); + distance_to_segment(round * q, round * s.sq[m], round * s.sq[m + 1]) < s.radius[m] * (1.0 - INSIDE) + }; match seg { PathSeg::Line(line) => { let len = line.p0.distance(line.p1); @@ -482,7 +568,14 @@ impl AreaPreview { keys }; let near = self.candidates(keys, &own); - let spans = near.iter().filter_map(|&m| capsule_span(line, self.sq[m], self.sq[m + 1], self.radius[m] * (1.0 - INSIDE))).collect(); + // A map keeps a line's points where they are along it. + let spans = near + .iter() + .filter_map(|&m| { + let round = self.round_of(m); + capsule_span(round * line, round * self.sq[m], round * self.sq[m + 1], self.radius[m] * (1.0 - INSIDE)) + }) + .collect(); gaps(&merge_spans(spans)) } _ => { diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index 9dfbdba2de..7aba70d4b6 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -2933,6 +2933,317 @@ fn the_eraser_tip_turns_in_place_and_passes_a_nib_size() { near(tip(&t), (-800.0, -950.0, 1200.0, 1050.0)); } +/// The outline of the area an Eraser drag covers takes, at each step, the tip the pen gives there +/// on the modes that follow it, as the release erases: turned, made rounder or larger, turned +/// again when the pen turns in place, and turned anew when a Variation changes. A round tip whose Size follows the pen shows each step as +/// wide as that tip, and a mouse, which reads no tilt or rotation, keeps the set tip. +#[test] +fn the_eraser_drag_area_follows_its_variation_modes() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + // Precise cursors: no tip outline, only the outline of the area. + let cx = ToolContext { precise_cursors: true, ..cx(&d, &s, &p) }; + let bounds = |t: &GestureTool| { + let o = t.overlays(&cx); + o.iter() + .filter_map(|o| match o { + Overlay::Path { path, .. } => Some(vectorcraft_geom::Shape::bounding_box(path)), + Overlay::SharedPath { path, .. } => Some(vectorcraft_geom::Shape::bounding_box(&**path)), + _ => None, + }) + .reduce(|a, b| a.union(b)) + .unwrap_or_else(|| panic!("{o:?}")) + }; + let near = |b: vectorcraft_geom::Rect, want: (f64, f64, f64, f64)| { + assert!([b.x0 - want.0, b.y0 - want.1, b.x1 - want.2, b.y1 - want.3].iter().all(|e| e.abs() < 0.01), "{b:?} vs {want:?}"); + }; + let set = |t: &mut GestureTool, options: &[(&str, Value)]| { + for (k, v) in options { + t.set_option(k, v); + } + }; + let upright = Some(PenPose { tilt: Some([0.0, 0.0]), rotation: None }); + let turned = Some(PenPose { tilt: None, rotation: Some(180.0) }); + let level = Some(PenPose { tilt: None, rotation: Some(0.0) }); + let press = |t: &mut GestureTool, pen: Option, kind: PointerKind, x: f64| { + t.pointer(&cx, &PointerEvent { pen, pressure: 0.5, ..PointerEvent::new(kind, x, 150.0) }); + }; + + // A tip 20 by 5 pt lying level, its angle on the barrel's rotation by up to 90°. + let mut t = GestureTool::new("eraser"); + set(&mut t, &[("size", json!(20)), ("roundness", json!(25)), ("angleMode", json!("rotation")), ("angleVariation", json!(90))]); + // With the barrel turned half way round all along, the tip stands upright: along the + // horizontal drag from x 50 to x 150 the area reaches 2.5 pt either side and 10 pt above and + // below. + press(&mut t, turned, PointerKind::Down, 50.0); + press(&mut t, turned, PointerKind::Drag, 150.0); + near(bounds(&t), (47.5, 140.0, 152.5, 160.0)); + // The barrel turns back with the pointer still: the step takes the tip halfway between the + // two, turned 45°, which reaches √(10² + 2.5²) / √2 pt from the drag every way. + press(&mut t, level, PointerKind::Drag, 150.0); + let r = (100.0f64 + 6.25).sqrt() / 2f64.sqrt(); + near(bounds(&t), (50.0 - r, 150.0 - r, 150.0 + r, 150.0 + r)); + press(&mut t, level, PointerKind::Up, 150.0); + // A Variation changed during the drag gives the outline the new tip: with 45° the turned + // barrel turns the tip 45°. + press(&mut t, turned, PointerKind::Down, 50.0); + press(&mut t, turned, PointerKind::Drag, 150.0); + near(bounds(&t), (47.5, 140.0, 152.5, 160.0)); + t.set_option("angleVariation", &json!(45)); + near(bounds(&t), (50.0 - r, 150.0 - r, 150.0 + r, 150.0 + r)); + press(&mut t, turned, PointerKind::Up, 150.0); + t.set_option("angleVariation", &json!(90)); + // A mouse drag keeps the set tip, lying level. + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 50.0, 150.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 150.0, 150.0)); + near(bounds(&t), (40.0, 147.5, 160.0, 152.5)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 150.0, 150.0)); + + // A round tip whose Roundness follows the tilt by up to 75%, the angle 90°: with the pen + // lying flat the tip is 25% round and stands upright. + let mut t = GestureTool::new("eraser"); + set(&mut t, &[("size", json!(20)), ("angle", json!(90)), ("roundnessMode", json!("tilt")), ("roundnessVariation", json!(75))]); + let flat = Some(PenPose { tilt: Some([90.0, 0.0]), rotation: None }); + press(&mut t, flat, PointerKind::Down, 50.0); + press(&mut t, flat, PointerKind::Drag, 150.0); + near(bounds(&t), (47.5, 140.0, 152.5, 160.0)); + press(&mut t, flat, PointerKind::Up, 150.0); + + // Size on Tilt by up to 8 pt, the pen upright: a tip 28 pt long, 7 pt wide standing upright, + // and a round one 28 pt across. + for (roundness, want) in [(25.0, (46.5, 136.0, 153.5, 164.0)), (100.0, (36.0, 136.0, 164.0, 164.0))] { + let mut t = GestureTool::new("eraser"); + set( + &mut t, + &[("size", json!(20)), ("angle", json!(90)), ("roundness", json!(roundness)), ("sizeMode", json!("tilt")), ("sizeVariation", json!(8))], + ); + press(&mut t, upright, PointerKind::Down, 50.0); + press(&mut t, upright, PointerKind::Drag, 150.0); + if roundness < 100.0 { + near(bounds(&t), want); + } else { + let o = t.overlays(&cx); + assert!(matches!(&o[..], [Overlay::Path { width, .. }] if *width == 28.0), "{o:?}"); + } + press(&mut t, upright, PointerKind::Up, 150.0); + } +} + +/// The outline of an Eraser drag shows the tips the release erases with: once the pen presses less +/// than fully, the steps already outlined take the tip of the pressure at their points, and a mode +/// set to Tilt during the drag, whose tilts the release does not read, leaves the tip as set. +#[test] +fn the_eraser_drag_area_matches_the_release_when_pressure_or_a_mode_starts_during_the_drag() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = ToolContext { precise_cursors: true, ..cx(&d, &s, &p) }; + let bounds = |t: &GestureTool| { + drain_area(t, &cx); + let o = t.overlays(&cx); + o.iter() + .filter_map(|o| match o { + Overlay::Path { path, .. } => Some(vectorcraft_geom::Shape::bounding_box(path)), + Overlay::SharedPath { path, .. } => Some(vectorcraft_geom::Shape::bounding_box(&**path)), + _ => None, + }) + .reduce(|a, b| a.union(b)) + .unwrap_or_else(|| panic!("{o:?}")) + }; + let near = |b: vectorcraft_geom::Rect, want: (f64, f64, f64, f64)| { + assert!([b.x0 - want.0, b.y0 - want.1, b.x1 - want.2, b.y1 - want.3].iter().all(|e| e.abs() < 0.01), "{b:?} vs {want:?}"); + }; + let upright = Some(PenPose { tilt: Some([0.0, 0.0]), rotation: None }); + let leaning = Some(PenPose { tilt: Some([45.0, 0.0]), rotation: None }); + let press = |t: &mut GestureTool, pen: Option, pressure: f32, kind: PointerKind, x: f64| { + t.pointer(&cx, &PointerEvent { pen, pressure, ..PointerEvent::new(kind, x, 150.0) }); + }; + + // A tip 20 by 5 pt lying level, its angle on Pressure by up to 90° and its Roundness on Tilt + // by up to 75%, so that each step has its own tip from the press on. The pen leans 45°, which + // keeps the Roundness at 25%. + let mut t = GestureTool::new("eraser"); + for (k, v) in [ + ("size", json!(20)), + ("roundness", json!(25)), + ("angleMode", json!("pressure")), + ("angleVariation", json!(90)), + ("roundnessMode", json!("tilt")), + ("roundnessVariation", json!(75)), + ] { + t.set_option(k, &v); + } + // Pressed fully, the drag reads as a stroke without pressure: the tip lies level. + press(&mut t, leaning, 1.0, PointerKind::Down, 50.0); + press(&mut t, leaning, 1.0, PointerKind::Drag, 100.0); + press(&mut t, leaning, 1.0, PointerKind::Drag, 150.0); + near(bounds(&t), (40.0, 147.5, 160.0, 152.5)); + // The pen lifts to no pressure: the release reads full pressure at the first three points, the + // tip turned 90°, and none at the last, turned -90°. The first two steps stand upright, and + // the last, halfway between full pressure and none, lies level. + press(&mut t, leaning, 0.0, PointerKind::Drag, 200.0); + near(bounds(&t), (47.5, 140.0, 210.0, 160.0)); + press(&mut t, leaning, 0.0, PointerKind::Up, 200.0); + + // The same tip with its angle on Pressure by up to 90°, pressed halfway all along, and + // Roundness on Tilt by up to 75% set after the first two points: the release reads no tilt, + // so the tip stays 20 by 5 pt lying level, though the pen stands upright, which would make it + // round. + let mut t = GestureTool::new("eraser"); + for (k, v) in [("size", json!(20)), ("roundness", json!(25)), ("angleMode", json!("pressure")), ("angleVariation", json!(90))] { + t.set_option(k, &v); + } + press(&mut t, None, 0.5, PointerKind::Down, 50.0); + press(&mut t, None, 0.5, PointerKind::Drag, 100.0); + t.set_option("roundnessMode", &json!("tilt")); + t.set_option("roundnessVariation", &json!(75)); + press(&mut t, upright, 0.5, PointerKind::Drag, 150.0); + near(bounds(&t), (40.0, 147.5, 160.0, 152.5)); + let released = t.stroke_json(); + assert!(released.as_array().is_some_and(|a| a.iter().all(|p| p.as_array().is_some_and(|p| p.len() == 3))), "{released}"); + press(&mut t, upright, 0.5, PointerKind::Up, 150.0); +} + +/// The release gives the points of an Eraser drag before the pen first leans the bearing of that +/// first lean, so the outline of a drag that starts upright and then leans is the outline of the +/// same drag leaning that way from the press, the steps already outlined included. +#[test] +fn the_eraser_drag_area_gives_the_first_lean_to_the_points_before_it() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = ToolContext { precise_cursors: true, ..cx(&d, &s, &p) }; + let bounds = |t: &GestureTool| { + drain_area(t, &cx); + let o = t.overlays(&cx); + o.iter() + .filter_map(|o| match o { + Overlay::Path { path, .. } => Some(vectorcraft_geom::Shape::bounding_box(path)), + Overlay::SharedPath { path, .. } => Some(vectorcraft_geom::Shape::bounding_box(&**path)), + _ => None, + }) + .reduce(|a, b| a.union(b)) + .unwrap_or_else(|| panic!("{o:?}")) + }; + // A tip 20 by 5 pt lying level, its angle on Bearing by up to 90° and its Roundness on + // Rotation by up to 50%, so that each step has its own tip from the press on. The barrel stays + // turned 30° all along. `in_place` is a tilt given last, by a drag within a pixel of the last + // point. + let drag = |poses: [[f32; 2]; 5], in_place: Option<[f32; 2]>| { + let mut t = GestureTool::new("eraser"); + for (k, v) in [ + ("size", json!(20)), + ("roundness", json!(25)), + ("angleMode", json!("bearing")), + ("angleVariation", json!(90)), + ("roundnessMode", json!("rotation")), + ("roundnessVariation", json!(50)), + ] { + t.set_option(k, &v); + } + let mut shown = vec![]; + for (i, (tilt, x)) in poses.into_iter().zip([50.0, 100.0, 150.0, 200.0, 250.0]).enumerate() { + let kind = if i == 0 { PointerKind::Down } else { PointerKind::Drag }; + let pen = Some(PenPose { tilt: Some(tilt), rotation: Some(30.0) }); + t.pointer(&cx, &PointerEvent { pen, pressure: 1.0, ..PointerEvent::new(kind, x, 150.0) }); + if i > 0 { + shown.push(bounds(&t)); + } + } + if let Some(tilt) = in_place { + let pen = Some(PenPose { tilt: Some(tilt), rotation: Some(30.0) }); + t.pointer(&cx, &PointerEvent { pen, pressure: 1.0, ..PointerEvent::new(PointerKind::Drag, 250.2, 150.0) }); + shown.push(bounds(&t)); + } + shown.last().copied().unwrap_or_else(|| panic!("no outline")) + }; + let same = |b: (vectorcraft_geom::Rect, vectorcraft_geom::Rect)| { + assert!([b.0.x0 - b.1.x0, b.0.y0 - b.1.y0, b.0.x1 - b.1.x1, b.0.y1 - b.1.y1].iter().all(|e| e.abs() < 0.01), "{b:?}"); + }; + let leaning = drag([[0.0, 45.0]; 5], None); + // Upright for four points, outlined as they come, then leaning toward the bottom of the page. + same((drag([[0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 45.0]], None), leaning)); + // Upright for all five, then leaning that way in place at the last. + same((drag([[0.0, 0.0]; 5], Some([0.0, 45.0])), drag([[0.0, 45.0]; 5], Some([0.0, 45.0])))); +} + +/// Each step of an Eraser drag's outline takes the tip the release erases with halfway along it: +/// with the angle on Pressure by up to 90°, a step from no pressure (the tip turned -90°) to full +/// pressure (turned 90°) shows the tip lying level, as the release turns it through level there, +/// though the tips at its ends are the same upright tip. +#[test] +fn the_eraser_drag_area_takes_the_tip_halfway_along_each_step() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = ToolContext { precise_cursors: true, ..cx(&d, &s, &p) }; + let mut t = GestureTool::new("eraser"); + for (k, v) in [("size", json!(20)), ("roundness", json!(25)), ("angleMode", json!("pressure")), ("angleVariation", json!(90))] { + t.set_option(k, &v); + } + t.pointer(&cx, &PointerEvent { pressure: 0.0, ..PointerEvent::new(PointerKind::Down, 50.0, 150.0) }); + t.pointer(&cx, &PointerEvent { pressure: 1.0, ..PointerEvent::new(PointerKind::Drag, 150.0, 150.0) }); + drain_area(&t, &cx); + let o = t.overlays(&cx); + let b = o + .iter() + .filter_map(|o| match o { + Overlay::Path { path, .. } => Some(vectorcraft_geom::Shape::bounding_box(path)), + Overlay::SharedPath { path, .. } => Some(vectorcraft_geom::Shape::bounding_box(&**path)), + _ => None, + }) + .reduce(|a, b| a.union(b)) + .unwrap_or_else(|| panic!("{o:?}")); + // The level tip 20 by 5 pt swept from x 50 to 150. + let want = (40.0, 147.5, 160.0, 152.5); + assert!([b.x0 - want.0, b.y0 - want.1, b.x1 - want.2, b.y1 - want.3].iter().all(|e| e.abs() < 0.01), "{b:?}"); + t.pointer(&cx, &PointerEvent { pressure: 1.0, ..PointerEvent::new(PointerKind::Up, 150.0, 150.0) }); +} + +/// The outline of a long Eraser drag whose tip turns and changes shape with the pen is built a +/// bounded amount per frame, and once finished it shows nothing inside the area: no point of it +/// lies well inside the area of any step, each step with the tip halfway along it. +#[test] +fn the_outline_of_a_long_varied_eraser_drag_is_bounded_and_shows_nothing_inside() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = ToolContext { precise_cursors: true, ..cx(&d, &s, &p) }; + let mut t = GestureTool::new("eraser"); + for (k, v) in [ + ("size", json!(12)), + ("roundness", json!(40)), + ("angleMode", json!("pressure")), + ("angleVariation", json!(90)), + ("roundnessMode", json!("pressure")), + ("roundnessVariation", json!(30)), + ("sizeMode", json!("pressure")), + ("sizeVariation", json!(4)), + ] { + t.set_option(k, &v); + } + long_area_drag(&mut t, &cx, 700, |i| 0.2 + 0.7 * ((i % 37) as f32 / 37.0)); + drain_area(&t, &cx); + let shown = shown_points(&t.overlays(&cx)); + assert!(!shown.is_empty()); + let steps: Vec<(Affine, Point, Point, f64)> = (0..t.points.len() - 1) + .map(|j| { + let [angle, roundness, size] = t.tip_between(j); + let round = eraser_tip(angle, roundness).inverse(); + (round, round * t.points[j], round * t.points[j + 1], size / 2.0) + }) + .collect(); + for &(q, _) in &shown { + // A curve of an outline is checked at the middles of its pieces, so where it crosses the + // end of a narrow tip's area, the end of a piece can lie a little way inside it. + for &(round, a, b, r) in &steps { + let d = distance_to_line(round * q, (a, b)); + assert!(d > r * 0.85, "a point of the outline {d} from a step, inside its area of radius {r}, at {q:?}"); + } + } +} + #[test] fn smooth_needs_selection_and_brackets_resize() { let (d, _) = doc_with_rect(); diff --git a/crates/tools/src/guides/tests.rs b/crates/tools/src/guides/tests.rs index 16b46f6fb9..ecfd3a2edc 100644 --- a/crates/tools/src/guides/tests.rs +++ b/crates/tools/src/guides/tests.rs @@ -1120,14 +1120,15 @@ fn gradient_vector_ends_land_on_a_glyph_anchor() { let acts = tool.pointer(&c, &ev(PointerKind::Drag, near + Vec2::new(1.5, -1.0))); assert!(acts.is_empty(), "drag start, Snap to Glyph {glyphs}: {acts:?}"); tool.pointer(&c, &ev(PointerKind::Up, near + Vec2::new(1.5, -1.0))); - // The end handle of the rectangle's gradient dragged to the click lands on the anchor. + // The end handle of the rectangle's gradient Alt-dragged to the click lands on the anchor. let c = ToolContext { snap_to_glyph: glyphs, ..cx(&d, &on_rect, &p) }; let mut tool = GradientTool::default(); // Hovering over the handle (on the rectangle's edge) shows no guides. tool.pointer(&c, &ev(PointerKind::Move, Point::new(400.0, 100.0))); assert!(!tool.overlays(&c).iter().any(|o| matches!(o, Overlay::Label { .. })), "hover over the handle"); - tool.pointer(&c, &ev(PointerKind::Down, Point::new(400.0, 100.0))); - let v = preview(&tool.pointer(&c, &ev(PointerKind::Drag, click))); + let alt = |kind, q: Point| PointerEvent { mods: crate::Mods { alt: true, ..Default::default() }, ..ev(kind, q) }; + tool.pointer(&c, &alt(PointerKind::Down, Point::new(400.0, 100.0))); + let v = preview(&tool.pointer(&c, &alt(PointerKind::Drag, click))); assert_eq!(lands(at(&v["end"])), glyphs, "end handle, Snap to Glyph {glyphs}: {v}"); tool.pointer(&c, &ev(PointerKind::Up, click)); // The start handle dragged to the click lands on the anchor. diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 7a5650a25b..197d41aaaf 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -291,6 +291,9 @@ pub trait Tool: Send { /// another document became active. The Blend tool drops its first pick and stops adding to the /// blend it just made. fn history_moved(&mut self) {} + /// A press on the canvas went to the view tools (held Space, the middle button) and not to the + /// tool. The Live Paint Bucket counts it among the clicks a triple-click compares. + fn press_elsewhere(&mut self) {} /// Time passes while the pointer button is held (`dt` seconds since the last tick, whether or /// not the pointer moved): tools that keep working while the brush holds still (Twirl, Pucker, /// Bloat) act on it. The host supplies the time, so tests and agents drive it exactly. diff --git a/crates/tools/src/pen/tests.rs b/crates/tools/src/pen/tests.rs index 32c91318e6..badb8193a7 100644 --- a/crates/tools/src/pen/tests.rs +++ b/crates/tools/src/pen/tests.rs @@ -607,7 +607,7 @@ fn a_drag_from_the_first_anchor_always_closes() { fn alt_mid_close_keeps_the_turned_outgoing_handle() { use vectorcraft_geom::{Anchor, SubPath}; let anchors = vec![Anchor::smooth(Point::new(100.0, 300.0), Point::new(150.0, 300.0)), Anchor::corner(Point::new(200.0, 200.0))]; - let (mut d, id, s) = drawing(SubPath { anchors, closed: false }); + let (mut d, id, s) = drawing(SubPath::new(anchors, false)); let p = paint(); let mut t = PenTool { drawing: true, ..PenTool::default() }; assert_eq!(t.pointer(&cx(&d, &s, &p), &PointerEvent::new(PointerKind::Down, 100.0, 300.0)), close_press(id, Point::new(100.0, 300.0))); @@ -634,7 +634,7 @@ fn alt_mid_close_keeps_the_turned_outgoing_handle() { fn space_moves_the_closing_anchor() { use vectorcraft_geom::{Anchor, SubPath}; let anchors = vec![Anchor::smooth(Point::new(100.0, 300.0), Point::new(150.0, 300.0)), Anchor::corner(Point::new(200.0, 200.0))]; - let (mut d, id, s) = drawing(SubPath { anchors, closed: false }); + let (mut d, id, s) = drawing(SubPath::new(anchors, false)); let p = paint(); let mut t = PenTool { drawing: true, ..PenTool::default() }; assert_eq!(t.pointer(&cx(&d, &s, &p), &PointerEvent::new(PointerKind::Down, 100.0, 300.0)), close_press(id, Point::new(100.0, 300.0))); diff --git a/crates/tools/src/xform/gradient.rs b/crates/tools/src/xform/gradient.rs index 117df38463..2a97b94c9e 100644 --- a/crates/tools/src/xform/gradient.rs +++ b/crates/tools/src/xform/gradient.rs @@ -6,11 +6,14 @@ //! pointer; a click inside selected art applies the gradient from that point. //! //! The annotator is a bar from a round start handle to a square end handle. Drag the start handle -//! (or the bar) to move the gradient, the end handle to change its length and angle, and just past -//! the end to rotate it. A vector drawn on the art, a click that applies one, and the dragged -//! handles snap as drawn points do (the anchors and paths of the art, and with Snap to Glyph the -//! guides of live type); Shift keeps the dragged end or handle at 45° steps from the Constrain Angle -//! preference, snapping along that step. Colour stops sit under the bar: click the bar to add +//! (or the bar) to move the gradient, the end handle to change its length, and just past the end +//! to rotate it. The dragged end stays on the bar's line, never nearer the start than +//! `MIN_LENGTH`; Alt-drag the end handle to change the length and angle together. A vector drawn +//! on the art, a click that applies one, and the dragged handles snap as drawn points do (the +//! anchors and paths of the art, and with Snap to Glyph the guides of live type; the end handle +//! without Alt only onto points on the bar's line); Shift keeps the end of a drawn vector, the +//! Alt-dragged end handle or the start handle at 45° steps from the Constrain Angle preference, +//! snapping along that step. Colour stops sit under the bar: click the bar to add //! one, drag one to move it (Alt drags a copy), drag it off the bar to delete it, and drag a //! diamond above the bar to move a midpoint. Double-clicking a stop opens its popover. The //! selected stop (`gradient.selectStop`) is shared with the Gradient and Color panels: Delete or @@ -54,6 +57,9 @@ const LIGHT: [u8; 3] = [0xf0, 0xf0, 0xf0]; // Annotator layout and hit radii, in screen pixels. /// Start and end handles. const HANDLE: f64 = 5.0; +/// The end handle dragged without Alt stays at least this far from the start (or at the vector's +/// own length when that is shorter). +const MIN_LENGTH: f64 = 2.0 * HANDLE; /// The rotate zone reaches this far past the end handle. const ROTATE: f64 = 14.0; /// Stop chips sit this far below the bar. @@ -335,6 +341,19 @@ fn run_ticks(cx: &ToolContext, a: &Annotator) -> Vec { .collect() } +/// Where the end handle dragged to `p` lands when only the length changes: `p` projected onto the +/// line of `geom`'s vector, on the side of its end and no nearer the start than `min` (or the +/// vector's own length when that is shorter). None for a vector of no length. +fn along_bar(geom: &GradientGeom, p: Point, min: f64) -> Option { + let v = geom.end - geom.start; + let len = v.hypot(); + if len < 1e-12 { + return None; + } + let u = v / len; + Some(geom.start + u * (p - geom.start).dot(u).max(min.min(len))) +} + /// The vector a click applies to `id`: its current gradient's, else the default fit on its box. fn click_vector(cx: &ToolContext, id: NodeId) -> Option { let stroke = !cx.fill_active; @@ -444,7 +463,24 @@ impl GradientTool { let start = place(geom.start, geom.start + (p - g.at)); ("paint.setGradientGeom", Self::geom_params(cx, start, start + (geom.end - geom.start))) } - Grab::End(geom) => ("paint.setGradientGeom", Self::geom_params(cx, geom.start, place(geom.start, p))), + // Alt (or a vector of no length, which has no direction to keep) moves the end freely. + Grab::End(geom) if mods.alt || geom.length() < 1e-12 => { + ("paint.setGradientGeom", Self::geom_params(cx, geom.start, place(geom.start, p))) + } + Grab::End(geom) => { + // Only the length changes: the end slides along the bar's line. It snaps only to a + // target on that line; elsewhere it follows the pointer, with no guides. + let min = cx.tol(MIN_LENGTH); + let q = snap.drag(cx, p, Some(&Leave::segment(cx, geom.start, false))); + let end = match along_bar(geom, q, min) { + Some(e) if e.distance(q) <= cx.tol(0.5) => e, + _ => { + snap.clear(); + along_bar(geom, p, min).unwrap_or(geom.end) + } + }; + ("paint.setGradientGeom", Self::geom_params(cx, geom.start, end)) + } Grab::Rotate { geom, from } => { let dir = (Affine::rotate(-from) * (p - geom.start).to_point()).to_vec2(); let dir = if mods.shift { constrain(dir) } else { dir }; diff --git a/crates/tools/src/xform/gradient/tests.rs b/crates/tools/src/xform/gradient/tests.rs index bdfa981c34..54648a9527 100644 --- a/crates/tools/src/xform/gradient/tests.rs +++ b/crates/tools/src/xform/gradient/tests.rs @@ -111,8 +111,9 @@ fn the_end_handle_changes_only_the_end_and_the_start_moves_both() { let p = paint(); let cx = cx(&d, &s, &p); let mut t = GradientTool::default(); - t.pointer(&cx, &ev(PointerKind::Down, Point::new(200.0, 150.0))); - let v = preview(&t.pointer(&cx, &ev(PointerKind::Drag, Point::new(220.0, 170.0)))).clone(); + // Alt-drag moves the end freely: the length and the angle change together. + t.pointer(&cx, &with(ALT, ev(PointerKind::Down, Point::new(200.0, 150.0)))); + let v = preview(&t.pointer(&cx, &with(ALT, ev(PointerKind::Drag, Point::new(220.0, 170.0))))).clone(); assert_eq!((point(&v["start"]), point(&v["end"])), (Point::new(100.0, 150.0), Point::new(220.0, 170.0))); assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, Point::new(220.0, 170.0))), vec![Action::Commit]); // The start handle moves the whole vector. @@ -121,6 +122,32 @@ fn the_end_handle_changes_only_the_end_and_the_start_moves_both() { assert_eq!((point(&v["start"]), point(&v["end"])), (Point::new(110.0, 140.0), Point::new(210.0, 140.0))); } +/// A plain drag of the end handle changes only the length: the end stays on the bar's line, with +/// Shift too, never nearer the start than `MIN_LENGTH`, and it does not snap to a target off +/// that line. +#[test] +fn a_plain_drag_of_the_end_handle_changes_only_the_length() { + let (d, s) = graded(two()); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = GradientTool::default(); + let drag = |t: &mut GradientTool, m: Mods, to: Point| { + t.pointer(&cx, &with(m, ev(PointerKind::Down, Point::new(200.0, 150.0)))); + let v = preview(&t.pointer(&cx, &with(m, ev(PointerKind::Drag, to)))).clone(); + let guides = t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Label { .. })); + t.pointer(&cx, &with(m, ev(PointerKind::Up, to))); + (point(&v["start"]), point(&v["end"]), guides) + }; + let start = Point::new(100.0, 150.0); + assert_eq!(drag(&mut t, Mods::default(), Point::new(220.0, 170.0)), (start, Point::new(220.0, 150.0), false)); + assert_eq!(drag(&mut t, SHIFT, Point::new(230.0, 100.0)), (start, Point::new(230.0, 150.0), false)); + // Near the rectangle's corner, off the line: no snap. + assert_eq!(drag(&mut t, Mods::default(), Point::new(202.0, 197.0)), (start, Point::new(202.0, 150.0), false)); + // Dragged back past the start, the end stops short of it. + let (_, end, _) = drag(&mut t, Mods::default(), Point::new(60.0, 160.0)); + assert!(end.distance(Point::new(100.0 + cx.tol(MIN_LENGTH), 150.0)) < 1e-9, "{end:?}"); +} + #[test] fn past_the_end_rotates_and_shift_snaps() { let (d, s) = graded(two()); @@ -140,9 +167,9 @@ fn handles_snap_to_anchors_and_shift_uses_the_constrain_angle() { let p = paint(); let mut cx = cx(&d, &s, &p); let mut t = GradientTool::default(); - // The end handle dragged near the rectangle's corner lands on it, with a guide label. - t.pointer(&cx, &ev(PointerKind::Down, Point::new(200.0, 150.0))); - let v = preview(&t.pointer(&cx, &ev(PointerKind::Drag, Point::new(202.0, 197.0)))).clone(); + // The end handle Alt-dragged near the rectangle's corner lands on it, with a guide label. + t.pointer(&cx, &with(ALT, ev(PointerKind::Down, Point::new(200.0, 150.0)))); + let v = preview(&t.pointer(&cx, &with(ALT, ev(PointerKind::Drag, Point::new(202.0, 197.0))))).clone(); assert_eq!(point(&v["end"]), Point::new(200.0, 200.0)); assert!(t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Label { text, .. } if text == "anchor"))); t.pointer(&cx, &ev(PointerKind::Up, Point::new(202.0, 197.0))); @@ -156,12 +183,13 @@ fn handles_snap_to_anchors_and_shift_uses_the_constrain_angle() { let v = preview(&t.pointer(&cx2, &ev(PointerKind::Drag, Point::new(150.0, 130.0)))).clone(); assert_eq!(point(&v["start"]), Point::new(100.0, 100.0)); t.pointer(&cx2, &ev(PointerKind::Up, Point::new(150.0, 130.0))); - // Constrain Angle 30: Shift gives 30 and 75 degrees (and no snapping). + // Constrain Angle 30: Shift with Alt gives 30 and 75 degrees (and no snapping). cx.constrain_angle = 30.0; let angle = |v: &Value| GradientGeom { start: point(&v["start"]), end: point(&v["end"]), aspect: 1.0, focal: None }.angle_deg(); + let shift_alt = Mods { alt: true, ..SHIFT }; for (to, want) in [(Point::new(190.0, 100.0), 30.0), (Point::new(125.0, 60.0), 75.0)] { - t.pointer(&cx, &ev(PointerKind::Down, Point::new(200.0, 150.0))); - let v = preview(&t.pointer(&cx, &with(SHIFT, ev(PointerKind::Drag, to)))).clone(); + t.pointer(&cx, &with(shift_alt, ev(PointerKind::Down, Point::new(200.0, 150.0)))); + let v = preview(&t.pointer(&cx, &with(shift_alt, ev(PointerKind::Drag, to)))).clone(); assert!((angle(&v) - want).abs() < 1e-9, "{want}: {v}"); t.pointer(&cx, &ev(PointerKind::Up, to)); } diff --git a/crates/trace/Cargo.toml b/crates/trace/Cargo.toml index a605a69adb..ad76667886 100644 --- a/crates/trace/Cargo.toml +++ b/crates/trace/Cargo.toml @@ -11,9 +11,11 @@ workspace = true [dependencies] vectorcraft-geom = { workspace = true } kurbo = { workspace = true } -image = { workspace = true } +craft-image-codecs = { workspace = true } serde = { workspace = true } thiserror = { workspace = true } [dev-dependencies] serde_json = { workspace = true } +# Test fixtures only: the JPEG-block test needs the block artifacts of the encoder it was tuned on. +image = { workspace = true } diff --git a/crates/trace/src/layers.rs b/crates/trace/src/layers.rs index 04f687b46b..7a8375f24e 100644 --- a/crates/trace/src/layers.rs +++ b/crates/trace/src/layers.rs @@ -5,13 +5,13 @@ use super::params::{Method, Mode, TraceParams}; use super::pipeline::TracedPath; #[cfg(test)] use super::pipeline::{bw_tones, left_out}; +#[cfg(test)] +use super::quantize; use super::raster::{Raster, TraceError}; use super::{ AtomicUsize, Crack, Loop, Ordering, PathData, Quantized, TRANSPARENT, TracedGradient, TracedShape, centerline, contour, fit, logo, shapes, trace_mask, }; -#[cfg(test)] -use super::{denoise, quantize}; /// What tracing one colour layer needs. pub(crate) struct Layers<'a> { @@ -1005,7 +1005,10 @@ impl Layers<'_> { pub(crate) fn shift_probe(img: &Raster, params: &TraceParams) -> Vec<[f64; 4]> { let (w, h) = (img.width as usize, img.height as usize); let mut q = quantize(img, params); - denoise(&mut q.labels, w, h, params.noise as usize); + let labs = super::quantize::palette_labs(&q.palette); + let source = + super::quantize::Source { labs: &labs, rgba: &img.rgba, blended: &[], gray: matches!(params.mode, Mode::Grayscale | Mode::BlackAndWhite) }; + super::quantize::denoise_nearest(&mut q.labels, w, h, params.noise as usize, &[], Some(&source)); let n = q.palette.len(); let rank: Vec = (0..n).collect(); let gradients = vec![None; n]; diff --git a/crates/trace/src/opaque.rs b/crates/trace/src/opaque.rs index 52e80a368d..7a0b87d9e0 100644 --- a/crates/trace/src/opaque.rs +++ b/crates/trace/src/opaque.rs @@ -3,7 +3,7 @@ use vectorcraft_geom::{Affine, PathData}; -use crate::raster::{MAX_PIXELS, fit_size, gif_first_frame_pixels}; +use crate::raster::{MAX_PIXELS, fit_size, gif_first_frame_pixels, trace_header}; use crate::{Mode, Raster, TraceError, TraceParams, trace_within}; /// The most pixels [`opaque_outline`] traces: a larger image is reduced to this many first, @@ -24,26 +24,49 @@ pub const ALPHA_MAX_DECODE_BYTES: u64 = 256 << 20; /// than [`MAX_PIXELS`] (64 megapixels), or whose samples take more than [`ALPHA_MAX_DECODE_BYTES`], /// gives [`TraceError::TooLarge`] before it is decoded. pub fn decode_alpha(bytes: &[u8]) -> Result)>, TraceError> { - use image::ImageDecoder; - let decode_err = |e: image::ImageError| TraceError::Decode(e.to_string()); - let reader = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().map_err(|e| TraceError::Decode(e.to_string()))?; - let decoder = reader.into_decoder().map_err(decode_err)?; - let (w, h) = decoder.dimensions(); + use craft_image_codecs::{ChannelLayout, DecodeOptions, Limits, RasterColorType, SampleType, decode_with}; + let decode_err = |e: craft_image_codecs::CodecError| TraceError::Decode(e.to_string()); + if let Some(info) = trace_header(bytes, MAX_PIXELS, ALPHA_MAX_DECODE_BYTES)? { + if info.width == 0 || info.height == 0 { + return Err(TraceError::Empty); + } + let might_have_alpha = match info.color_type { + RasterColorType::GrayAlpha | RasterColorType::Rgba | RasterColorType::CmykAlpha => true, + RasterColorType::Rgb => info.channels > 3, + RasterColorType::Gray => info.channels > 1, + // The shared TIFF inspector reports the base photometric type even + // when an ExtraSamples channel carries alpha. + RasterColorType::Cmyk => info.channels > 4, + RasterColorType::Lab => info.channels > 3, + RasterColorType::Indexed => true, + _ => false, + }; + if !might_have_alpha { + return Ok(None); + } + let pixels = u64::from(info.width) * u64::from(info.height); + let frame = gif_first_frame_pixels(bytes).unwrap_or(0); + let total_bytes = pixels.saturating_mul(u64::from(info.channels)).saturating_mul(u64::from(info.bits_per_sample.max(8).div_ceil(8))); + if pixels.max(frame) > MAX_PIXELS || total_bytes > ALPHA_MAX_DECODE_BYTES { + return Err(TraceError::TooLarge { width: info.width, height: info.height, max: MAX_PIXELS >> 20 }); + } + } else if gif_first_frame_pixels(bytes).is_some_and(|p| p > MAX_PIXELS) { + return Err(TraceError::TooLarge { width: 0, height: 0, max: MAX_PIXELS >> 20 }); + } + let opts = + DecodeOptions { keep_orientation: true, limits: Limits { max_pixels: MAX_PIXELS, max_alloc: ALPHA_MAX_DECODE_BYTES, ..Limits::default() } }; + let img = decode_with(bytes, &opts).map_err(decode_err)?; + let (w, h) = (img.width(), img.height()); if w == 0 || h == 0 { return Err(TraceError::Empty); } - if !decoder.color_type().has_alpha() { + if !img.layout().has_alpha() { return Ok(None); } - let pixels = u64::from(w) * u64::from(h); - let frame = gif_first_frame_pixels(bytes).unwrap_or(0); - if pixels.max(frame) > MAX_PIXELS || decoder.total_bytes() > ALPHA_MAX_DECODE_BYTES { - return Err(TraceError::TooLarge { width: w, height: h, max: MAX_PIXELS >> 20 }); - } - let alpha: Vec = match image::DynamicImage::from_decoder(decoder).map_err(decode_err)? { - image::DynamicImage::ImageRgba8(img) => img.as_raw().as_chunks::<4>().0.iter().map(|p| p[3]).collect(), - image::DynamicImage::ImageLumaA8(img) => img.as_raw().as_chunks::<2>().0.iter().map(|p| p[1]).collect(), - img => img.to_rgba8().as_raw().as_chunks::<4>().0.iter().map(|p| p[3]).collect(), + let alpha: Vec = match (img.layout(), img.sample_type()) { + (ChannelLayout::Rgba, SampleType::U8) => img.data().as_chunks::<4>().0.iter().map(|p| p[3]).collect(), + (ChannelLayout::GrayA, SampleType::U8) => img.data().as_chunks::<2>().0.iter().map(|p| p[1]).collect(), + _ => img.to_rgba8().as_chunks::<4>().0.iter().map(|p| p[3]).collect(), }; Ok(Some((w, h, alpha))) } @@ -265,28 +288,77 @@ mod tests { } /// `img` encoded as `format`. - fn encoded(img: image::DynamicImage, format: image::ImageFormat) -> Vec { - let mut out = vec![]; - img.write_to(&mut std::io::Cursor::new(&mut out), format).unwrap(); - out + fn encoded(img: &craft_image_codecs::Image, format: craft_image_codecs::Format) -> Vec { + craft_image_codecs::encode(img, format, &Default::default()).unwrap() } #[test] fn decode_alpha_reads_the_alpha_of_formats_that_have_one() { - let px = |x: u32, y: u32| image::Rgba([10, 20, 30, u8::try_from((x + 4 * y) * 16).unwrap()]); - let rgba = image::DynamicImage::ImageRgba8(image::RgbaImage::from_fn(4, 4, px)); - let want: Vec = (0..16).map(|i| u8::try_from(i * 16).unwrap()).collect(); - for (name, img) in [ - ("rgba", rgba.clone()), - ("gray and alpha", image::DynamicImage::ImageLumaA8(rgba.to_luma_alpha8())), - ("16 bits", image::DynamicImage::ImageRgba16(rgba.to_rgba16())), - ] { - let got = decode_alpha(&encoded(img, image::ImageFormat::Png)).unwrap(); + use craft_image_codecs::{ChannelLayout, Format, Image, SampleType}; + let mut rgba_bytes = Vec::with_capacity(4 * 4 * 4); + let mut luma_a_bytes = Vec::with_capacity(4 * 4 * 2); + let mut rgba16_bytes = Vec::with_capacity(4 * 4 * 8); + let mut rgb_bytes = Vec::with_capacity(4 * 4 * 3); + let mut want = Vec::with_capacity(16); + for y in 0..4u32 { + for x in 0..4u32 { + let a = u8::try_from((x + 4 * y) * 16).unwrap(); + want.push(a); + rgba_bytes.extend_from_slice(&[10, 20, 30, a]); + luma_a_bytes.extend_from_slice(&[18, a]); + let a16 = u16::from(a) * 257; + for v in [10u16 * 257, 20 * 257, 30 * 257, a16] { + rgba16_bytes.extend_from_slice(&v.to_ne_bytes()); + } + rgb_bytes.extend_from_slice(&[10, 20, 30]); + } + } + let rgba = Image::from_u8(4, 4, ChannelLayout::Rgba, rgba_bytes).unwrap(); + let luma_a = Image::from_u8(4, 4, ChannelLayout::GrayA, luma_a_bytes).unwrap(); + let rgba16 = Image::from_raw(4, 4, ChannelLayout::Rgba, SampleType::U16, rgba16_bytes).unwrap(); + for (name, img) in [("rgba", rgba), ("gray and alpha", luma_a), ("16 bits", rgba16)] { + let got = decode_alpha(&encoded(&img, Format::Png)).unwrap(); assert_eq!(got, Some((4, 4, want.clone())), "{name}"); } - let rgb = image::DynamicImage::ImageRgb8(rgba.to_rgb8()); - assert_eq!(decode_alpha(&encoded(rgb.clone(), image::ImageFormat::Png)).unwrap(), None); - assert_eq!(decode_alpha(&encoded(rgb, image::ImageFormat::Jpeg)).unwrap(), None); + let rgb = Image::from_u8(4, 4, ChannelLayout::Rgb, rgb_bytes).unwrap(); + assert_eq!(decode_alpha(&encoded(&rgb, Format::Png)).unwrap(), None); + assert_eq!(decode_alpha(&encoded(&rgb, Format::Jpeg)).unwrap(), None); assert!(decode_alpha(b"not an image").is_err()); } + + #[test] + fn decode_alpha_expands_gray_and_rgb_png_transparency_keys() { + // Original synthetic 2x1 PNGs: first pixel matches tRNS; second is opaque. + // Generated from PNG chunks and zlib scanlines, without an external image asset. + let gray: &[u8] = &[ + 137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 2, 0, 0, 0, 1, 8, 0, 0, 0, 0, 209, 73, 32, 86, 0, 0, 0, 2, 116, + 82, 78, 83, 0, 0, 118, 147, 205, 56, 0, 0, 0, 11, 73, 68, 65, 84, 120, 156, 99, 96, 168, 7, 0, 0, 130, 0, 128, 32, 18, 25, 54, 0, 0, 0, + 0, 73, 69, 78, 68, 174, 66, 96, 130, + ]; + let rgb: &[u8] = &[ + 137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 2, 0, 0, 0, 1, 8, 2, 0, 0, 0, 123, 64, 232, 221, 0, 0, 0, 6, 116, + 82, 78, 83, 0, 255, 0, 0, 0, 0, 164, 194, 192, 29, 0, 0, 0, 15, 73, 68, 65, 84, 120, 156, 99, 248, 207, 192, 192, 240, 159, 1, 0, 7, 255, + 1, 255, 1, 127, 137, 167, 0, 0, 0, 0, 73, 69, 78, 68, 174, 66, 96, 130, + ]; + for bytes in [gray, rgb] { + assert_eq!(decode_alpha(bytes).unwrap(), Some((2, 1, vec![0, 255]))); + } + } + + #[test] + fn decode_alpha_preserves_cmyk_and_lab_tiff_extra_samples() { + use craft_image_codecs::{ChannelLayout, Format, Image}; + for (layout, samples) in + [(ChannelLayout::CmykA, vec![10, 20, 30, 40, 0, 50, 60, 70, 80, 255]), (ChannelLayout::LabA, vec![128, 128, 128, 0, 192, 128, 128, 255])] + { + let img = Image::from_u8(2, 1, layout, samples).unwrap(); + assert_eq!(decode_alpha(&encoded(&img, Format::Tiff)).unwrap(), Some((2, 1, vec![0, 255])), "{layout:?}"); + } + for (layout, samples) in + [(ChannelLayout::Cmyk, vec![10, 20, 30, 40, 50, 60, 70, 80]), (ChannelLayout::Lab, vec![128, 128, 128, 192, 128, 128])] + { + let img = Image::from_u8(2, 1, layout, samples).unwrap(); + assert_eq!(decode_alpha(&encoded(&img, Format::Tiff)).unwrap(), None, "{layout:?}"); + } + } } diff --git a/crates/trace/src/params.rs b/crates/trace/src/params.rs index 156d6fbef2..7b850fc344 100644 --- a/crates/trace/src/params.rs +++ b/crates/trace/src/params.rs @@ -82,8 +82,10 @@ pub struct TraceParams { pub paths: f64, /// Corners 0–100: higher keeps more corners. pub corners: f64, - /// Noise: areas smaller than this many pixels are ignored. (Flat Logo mode: areas smaller than - /// `noise / 10` pixels of the source image.) + /// Noise: areas smaller than this many pixels are ignored: each joins the color it shares the + /// longest border with, or, when that color is far from its own, the color beside it nearest + /// its source pixels. (Flat Logo mode: areas smaller than `noise / 10` pixels of the source + /// image.) pub noise: u32, pub method: Method, /// Ignore Color: drop the areas of one colour (no background shape): white, unless @@ -244,10 +246,10 @@ pub fn preset(name: &str) -> Option { "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), + "6 colors" => color(6, 50.0, 50.0, 8, Method::Abutting), + "16 colors" => color(16, 50.0, 50.0, 8, 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), + "black and white logo" => bw(128, 50.0, 75.0, 5, 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), diff --git a/crates/trace/src/pipeline.rs b/crates/trace/src/pipeline.rs index cb635e7493..235447bee4 100644 --- a/crates/trace/src/pipeline.rs +++ b/crates/trace/src/pipeline.rs @@ -250,9 +250,11 @@ fn trace_paths(img: &Raster, params: &TraceParams, max_anchors: usize, steps: &( let (mut q, rare) = quantize::quantize_keeping(without.as_ref().unwrap_or(img), params); go_on()?; // The semi-transparent edge of a cut-out image traces as the color beside it. - if matches!(params.mode, Mode::Color | Mode::Grayscale) { - quantize::settle_cut_edges(&mut q, img, params.mode == Mode::Grayscale); - } + let blended = if matches!(params.mode, Mode::Color | Mode::Grayscale) { + quantize::settle_cut_edges(&mut q, img, params.mode == Mode::Grayscale) + } else { + Vec::new() + }; drop(without); // Each gradient is a palette entry of its own (its colour: the gradient's middle). let mut gradients: Vec> = vec![None; q.palette.len()]; @@ -270,7 +272,12 @@ fn trace_paths(img: &Raster, params: &TraceParams, max_anchors: usize, steps: &( drop(grays); // Noise clears specks, not the regions of a rare colour Automatic kept on purpose. let keep: Vec = q.palette.iter().map(|c| rare.contains(c)).collect(); - quantize::denoise_keeping(&mut q.labels, w, h, params.noise as usize, &keep); + // A speck far from the color around it joins the color beside it nearest its own pixels. + let labs = quantize::palette_labs(&q.palette); + let source = + quantize::Source { labs: &labs, rgba: &img.rgba, blended: &blended, gray: matches!(params.mode, Mode::Grayscale | Mode::BlackAndWhite) }; + quantize::denoise_nearest(&mut q.labels, w, h, params.noise as usize, &keep, Some(&source)); + drop(blended); go_on()?; // Ignore Color, background only: the labels traced, with the ignored color's areas that reach // the edge left out. Its other areas are traced with the rest. Edges are still placed by diff --git a/crates/trace/src/quantize.rs b/crates/trace/src/quantize.rs index a54fdfacc7..ea8fa00ac8 100644 --- a/crates/trace/src/quantize.rs +++ b/crates/trace/src/quantize.rs @@ -11,7 +11,9 @@ mod rare; use cut_edge::{choosing_pixels, compact, settled, settled_wide, settles_wide}; pub(crate) use cut_edge::{continuous_tone, settle_cut_edges}; pub use denoise::denoise; +#[cfg(test)] pub(crate) use denoise::denoise_keeping; +pub(crate) use denoise::{Source, denoise_nearest}; pub use palette::FULL_TONE_MAX; use palette::{Bin, HistKey, TracedAs, Used, color_palette, flat_count, flat_palette, kmeans_1d, labs, nearest_1d, nearest_lab, nearest_library}; #[cfg(test)] @@ -296,6 +298,11 @@ fn oklab(c: [f64; 3]) -> [f64; 3] { ] } +/// [`oklab`] of each palette color. +pub(crate) fn palette_labs(palette: &[[u8; 3]]) -> Vec<[f64; 3]> { + palette.iter().map(|c| oklab(c.map(f64::from))).collect() +} + /// [`oklab`] of an sRGB colour, for the tests. #[cfg(test)] pub(crate) fn tests_oklab(c: [u8; 3]) -> [f64; 3] { diff --git a/crates/trace/src/quantize/cut_edge.rs b/crates/trace/src/quantize/cut_edge.rs index 4578fbe7fc..61a9db4c8e 100644 --- a/crates/trace/src/quantize/cut_edge.rs +++ b/crates/trace/src/quantize/cut_edge.rs @@ -594,12 +594,15 @@ pub(super) fn compact(mut labels: Vec, palette: Vec<[u8; 3]>) -> Quantized /// when one of the fully opaque pixels it reaches has it, or when its color is a blend of none of /// them, as with a thin semi-transparent outline of another color. Pixels outside the image do not /// count as transparent. With `gray` (Grayscale), a pixel's color is its gray (see [`luma`]). -pub(crate) fn settle_cut_edges(q: &mut Quantized, img: &Raster, gray: bool) { +/// Returns which cut-edge pixels are a blend of the color of a fully opaque pixel they reach (see +/// [`edge_blend_of`]), whether or not they took that color (empty when `q` does not match `img`). +pub(crate) fn settle_cut_edges(q: &mut Quantized, img: &Raster, gray: bool) -> Vec { let (w, h) = (img.width as usize, img.height as usize); let px = img.rgba.as_chunks::<4>().0; if q.labels.len() != w * h || px.len() != w * h { - return; + return Vec::new(); } + let mut blended = vec![false; w * h]; let color = |p: &[u8; 4]| if gray { [luma(*p); 3] } else { [p[0], p[1], p[2]] }; let edge = cut_edge(img); let mut changed = false; @@ -627,6 +630,7 @@ pub(crate) fn settle_cut_edges(q: &mut Quantized, img: &Raster, gray: bool) { } } }); + blended[i] = !near.is_empty(); if keep || near.is_empty() { continue; } @@ -641,6 +645,7 @@ pub(crate) fn settle_cut_edges(q: &mut Quantized, img: &Raster, gray: bool) { if changed { *q = compact(std::mem::take(&mut q.labels), std::mem::take(&mut q.palette)); } + blended } /// Calls `visit` with the index of each fully opaque pixel of `img` within two pixels of the pixel diff --git a/crates/trace/src/quantize/denoise.rs b/crates/trace/src/quantize/denoise.rs index a929691466..e320194b6d 100644 --- a/crates/trace/src/quantize/denoise.rs +++ b/crates/trace/src/quantize/denoise.rs @@ -4,20 +4,59 @@ use super::rare::RARE_ISLAND; /// Merge whole 4-connected regions, smallest first, into their most common neighbouring label. /// The merge order does not depend on `min_area`: a higher threshold continues the same sequence /// instead of splitting a region already merged at a lower threshold. Transparency is a barrier. +/// It reads only the labels. A trace also reads the image, and a speck far from the color around +/// it joins the color beside it nearest its pixels instead. pub fn denoise(labels: &mut [u16], w: usize, h: usize, min_area: usize) { denoise_keeping(labels, w, h, min_area, &[]); } +/// How far apart (Oklab × 100) a small region's color and the color it shares the longest +/// border with must be before it merges into the color beside it that is nearest its source +/// pixels instead (among those with at least [`NEAREST_BORDER`] of the longest border): a dark +/// speck on the edge of a light area joins the dark outline beside it, not the light area. +pub(crate) const NEAREST_APART: f64 = 10.0; + +/// See [`NEAREST_APART`]. +pub(crate) const NEAREST_BORDER: f64 = 0.1; + +/// The fewest pixels a region needs for [`NEAREST_APART`] to apply when two or more colors tie +/// for its longest border. Such a lone pixel merges by border alone: on an anti-aliased corner it +/// holds a mix of the colors on both sides, and joining the nearer one can cut the corner off a +/// shape. +pub(crate) const NEAREST_PIXELS: u32 = 2; + +/// The colors [`denoise_nearest`] compares a small region with. +pub(crate) struct Source<'a> { + /// Each label's color in Oklab × 100 ([`super::palette_labs`]). + pub labs: &'a [[f64; 3]], + /// The prepared image the labels were made from, 4 bytes a pixel. + pub rgba: &'a [u8], + /// The pixels along a cut edge that [`super::settle_cut_edges`] finds to be the color of an opaque pixel beside + /// them blended with the transparent background. They are not read. + pub blended: &'a [bool], + /// Whether the labels are grays (Grayscale, Black and White): the pixels are compared as their gray + /// ([`super::luma`]). + pub gray: bool, +} + /// [`denoise`], except that a region of a label `keep` marks (a rare colour kept on purpose, see /// [`rare_colours`]) that is at least [`RARE_ISLAND`] pixels stays whatever `min_area` is: Noise /// clears specks, not a colour's only regions. Smaller regions of it go as any other. pub(crate) fn denoise_keeping(labels: &mut [u16], w: usize, h: usize, min_area: usize, keep: &[bool]) { + denoise_nearest(labels, w, h, min_area, keep, None); +} + +/// [`denoise_keeping`]; with `source`, a region below `min_area` whose color is at least +/// [`NEAREST_APART`] from the color it shares the longest border with merges into the color +/// beside it nearest its source pixels, averaged, among those sharing at least [`NEAREST_BORDER`] +/// of the longest border ([`NEAREST_PIXELS`] limits this for a single pixel). Every region below +/// `min_area` still goes. +pub(crate) fn denoise_nearest(labels: &mut [u16], w: usize, h: usize, min_area: usize, keep: &[bool], source: Option<&Source>) { use std::cmp::Reverse; use std::collections::BinaryHeap; // Every index below is a `u32`, so a pixel costs 8 bytes and a region 18 instead of a `Vec` per region. An image // of `u32::MAX` pixels or more (far above the decoder's cap) is left as it is. - const NONE: u32 = u32::MAX; if min_area <= 1 || w == 0 || h == 0 || w.checked_mul(h) != Some(labels.len()) || labels.len() >= NONE as usize { return; } @@ -66,14 +105,8 @@ pub(crate) fn denoise_keeping(labels: &mut [u16], w: usize, h: usize, min_area: colour.push(label); parent.push(id); } - fn find(parent: &mut [u32], mut a: u32) -> u32 { - while parent[a as usize] != a { - let up = parent[parent[a as usize] as usize]; - parent[a as usize] = up; - a = up; - } - a - } + // Only when it can be read: the labels' colors and the source pixels must cover every label and every pixel. + let source = source.filter(|s| colour.iter().all(|&c| (c as usize) < s.labs.len()) && labels.len().checked_mul(4) == Some(s.rgba.len())); // Only regions below `min_area` are ever taken from the queue; a larger one ends the loop. let mut pending: BinaryHeap<_> = (0..size.len() as u32).filter(|&id| (size[id as usize] as usize) < min_area).map(|id| Reverse((size[id as usize], id))).collect(); @@ -110,9 +143,24 @@ pub(crate) fn denoise_keeping(labels: &mut [u16], w: usize, h: usize, min_area: by_colour.clear(); by_colour.extend(borders.iter().map(|&(other, border)| (colour[other as usize], border))); merge_counts(&mut by_colour); - let Some(&(chosen, _)) = by_colour.iter().max_by_key(|(label, border)| (*border, Reverse(*label))) else { + let Some(&(mut chosen, longest)) = by_colour.iter().max_by_key(|(label, border)| (*border, Reverse(*label))) else { continue; // an opaque island surrounded only by transparency stays intact }; + if let Some(source) = source + && (area >= NEAREST_PIXELS || by_colour.iter().filter(|&&(_, border)| border == longest).count() == 1) + && let Some(own) = source.labs.get(colour[id as usize] as usize) + && distance(own, source.labs.get(chosen as usize)) >= NEAREST_APART + && let Some(mean) = mean_lab(head[id as usize], &next, source) + { + let to = |c: u16| distance(&mean, source.labs.get(c as usize)); + if let Some(&(nearest, _)) = by_colour + .iter() + .filter(|&&(_, border)| border as f64 >= NEAREST_BORDER * longest as f64) + .min_by(|a, b| to(a.0).total_cmp(&to(b.0)).then(b.1.cmp(&a.1))) + { + chosen = nearest; + } + } // All adjacent regions of the chosen colour become connected by this merge. Absorb // them together, keeping the largest one as the survivor. let Some(target) = borders @@ -143,6 +191,46 @@ pub(crate) fn denoise_keeping(labels: &mut [u16], w: usize, h: usize, min_area: } } +/// The end of a pixel list, and the region of a transparent pixel. +const NONE: u32 = u32::MAX; + +/// The root of `a` in the union-find `parent`, halving the paths on the way. +fn find(parent: &mut [u32], mut a: u32) -> u32 { + while parent[a as usize] != a { + let up = parent[parent[a as usize] as usize]; + parent[a as usize] = up; + a = up; + } + a +} + +/// The source pixels of the list that starts at `first` (linked through `next`), averaged, in Oklab × 100, read as +/// `source` says, leaving out the blended cut-edge pixels. `None` when every pixel is one of them. +fn mean_lab(first: u32, next: &[u32], source: &Source) -> Option<[f64; 3]> { + let (mut sum, mut n) = ([0.0f64; 3], 0u32); + let mut pixel = first; + while pixel != NONE { + let blended = source.blended.get(pixel as usize).copied().unwrap_or(false); + if !blended && let Some(&[r, g, b, a]) = source.rgba.get(pixel as usize * 4..pixel as usize * 4 + 4) { + let p = if source.gray { [f64::from(super::luma([r, g, b, a])); 3] } else { [r, g, b].map(f64::from) }; + for (s, v) in sum.iter_mut().zip(p) { + *s += v; + } + n += 1; + } + pixel = next.get(pixel as usize).copied().unwrap_or(NONE); + } + if n == 0 { + return None; + } + Some(super::oklab(sum.map(|s| s / f64::from(n)))) +} + +/// The distance between two colors in Oklab × 100; infinite when `q` is missing. +fn distance(p: &[f64; 3], q: Option<&[f64; 3]>) -> f64 { + q.map_or(f64::INFINITY, |q| (0..3).map(|k| (p[k] - q[k]).powi(2)).sum::().sqrt()) +} + /// Sort `(key, count)` pairs and add up the counts of equal keys. fn merge_counts(pairs: &mut Vec<(K, usize)>) { pairs.sort_unstable_by_key(|p| p.0); @@ -285,6 +373,185 @@ mod tests { } } + /// A light ground, a dark ink, a tone barely darker than the ground and a dark brown close to the ink. + const GROUND_INK_TONE_BROWN: [[u8; 3]; 4] = [[235, 225, 210], [30, 25, 20], [228, 218, 203], [50, 42, 35]]; + + /// `labels` denoised at `min_area`, reading the source image that paints each label its palette color. + fn denoised_nearest(labels: &[u16], w: usize, h: usize, min_area: usize) -> Vec { + let labs = crate::quantize::palette_labs(&GROUND_INK_TONE_BROWN); + let rgba: Vec = + labels.iter().flat_map(|&l| GROUND_INK_TONE_BROWN.get(l as usize).copied().unwrap_or([0; 3]).into_iter().chain([255])).collect(); + let mut out = labels.to_vec(); + denoise_nearest(&mut out, w, h, min_area, &[], Some(&Source { labs: &labs, rgba: &rgba, blended: &[], gray: false })); + out + } + + /// A ground with a dark line two pixels wide down column 12 and 13, and a 2 × 2 speck of `speck` at (10, 10) that + /// touches the line on one side and the ground on three. + fn speck_beside_a_line(speck: u16) -> (Vec, usize, usize) { + let (w, h) = (30, 30); + let mut labels = vec![0u16; w * h]; + for y in 0..h { + labels[y * w + 12] = 1; + labels[y * w + 13] = 1; + } + for (x, y) in SPECK { + labels[y * w + x] = speck; + } + (labels, w, h) + } + + const SPECK: [(usize, usize); 4] = [(10, 10), (11, 10), (10, 11), (11, 11)]; + + /// A dark speck mostly on the light ground but touching a dark line joins the line, the color nearest it, not the + /// ground it shares more border with. + #[test] + fn a_dark_speck_beside_a_dark_line_joins_the_line() { + let (labels, w, h) = speck_beside_a_line(3); + let out = denoised_nearest(&labels, w, h, 15); + for (x, y) in SPECK { + assert_eq!(out[y * w + x], 1, "({x}, {y})"); + } + let mut blind = labels.clone(); + denoise_keeping(&mut blind, w, h, 15, &[]); + assert_eq!(blind[10 * w + 10], 0, "by border alone it joins the ground"); + } + + /// A speck whose color is close to the color it shares the longest border with joins that color, as before, + /// even though another color touches it. + #[test] + fn a_speck_close_to_its_longest_border_color_joins_it() { + let (labels, w, h) = speck_beside_a_line(2); + let out = denoised_nearest(&labels, w, h, 15); + let mut blind = labels.clone(); + denoise_keeping(&mut blind, w, h, 15, &[]); + assert_eq!(out, blind); + assert_eq!(out[10 * w + 10], 0); + } + + /// A color that touches the speck along less than a tenth of its longest border is not chosen, however near. + #[test] + fn a_color_with_a_short_border_is_not_chosen() { + let (w, h) = (30, 30); + let mut labels = vec![0u16; w * h]; + // A 3 × 3 speck of brown in the ground, and a line of ink 16 pixels long (above Noise) that touches the speck at + // one pixel edge. + for y in 10..13 { + for x in 10..13 { + labels[y * w + x] = 3; + } + } + for x in 13..29 { + labels[10 * w + x] = 1; + } + // The brown speck has 11 pixel edges against the ground and 1 against the ink: 1 < 0.1 × 11. + let out = denoised_nearest(&labels, w, h, 15); + assert_eq!(out[11 * w + 11], 0); + assert!(out[10 * w + 13..10 * w + 29].iter().all(|&l| l == 1), "the line stays"); + } + + /// A lone pixel tied between two colors for its longest border merges by border alone, even when the other + /// color is nearer its source pixel. + #[test] + fn a_lone_pixel_tied_between_colors_merges_by_border() { + let (w, h) = (20, 20); + // Ground in the top-left, ink everywhere else, and one brown pixel at the corner with two edges on each. + let mut labels: Vec = (0..w * h).map(|i| u16::from(i % w >= 11 || i / w >= 11)).collect(); + labels[10 * w + 10] = 3; + let out = denoised_nearest(&labels, w, h, 5); + let mut blind = labels.clone(); + denoise_keeping(&mut blind, w, h, 5, &[]); + assert_eq!(out, blind); + assert_eq!(out[10 * w + 10], 0); + // With the ground one column wider the pixel has three edges on the ground and one on the ink: no longer tied, + // it joins the ink, the color nearest it. + for y in 0..11 { + labels[y * w + 11] = 0; + } + let out = denoised_nearest(&labels, w, h, 5); + assert_eq!(out[10 * w + 10], 1); + } + + /// Every region below Noise still goes: the nearest-color merge only changes where it goes. + #[test] + fn noise_still_removes_every_region_below_it() { + let (w, h) = (60, 50); + for seed in 1..6 { + let labels = noisy(w, h, 4, 0, seed); + for min_area in [2, 3, 5, 8, 15, 25] { + let out = denoised_nearest(&labels, w, h, min_area); + let mut seen = vec![false; w * h]; + for start in 0..w * h { + if seen[start] { + continue; + } + seen[start] = true; + let mut stack = vec![start]; + let mut count = 0; + while let Some(i) = stack.pop() { + count += 1; + let (x, y) = (i % w, i / w); + for j in [(x > 0).then(|| i - 1), (x + 1 < w).then(|| i + 1), (y > 0).then(|| i - w), (y + 1 < h).then(|| i + w)] + .into_iter() + .flatten() + { + if !seen[j] && out[j] == out[i] { + seen[j] = true; + stack.push(j); + } + } + } + assert!(count >= min_area, "seed {seed}, Noise {min_area}: a region of {count} pixels at {start}"); + } + } + } + } + + /// Without colors or a source image for every label and pixel, every region merges as it always did. + #[test] + fn a_source_that_does_not_cover_the_labels_is_not_read() { + let (labels, w, h) = speck_beside_a_line(3); + let mut blind = labels.clone(); + denoise_keeping(&mut blind, w, h, 15, &[]); + let labs = crate::quantize::palette_labs(&GROUND_INK_TONE_BROWN[..2]); + // Every pixel ink: read, the speck would join the line. + let rgba: Vec = (0..w * h).flat_map(|_| [30, 25, 20, 255]).collect(); + let mut out = labels.clone(); + denoise_nearest(&mut out, w, h, 15, &[], Some(&Source { labs: &labs, rgba: &rgba, blended: &[], gray: false })); + assert_eq!(out, blind); + let labs = crate::quantize::palette_labs(&GROUND_INK_TONE_BROWN); + let mut out = labels.clone(); + denoise_nearest(&mut out, w, h, 15, &[], Some(&Source { labs: &labs, rgba: &rgba[4..], blended: &[], gray: false })); + assert_eq!(out, blind); + let mut out = labels.clone(); + denoise_nearest(&mut out, w, h, 15, &[], Some(&Source { labs: &labs, rgba: &rgba, blended: &[], gray: false })); + assert_eq!(out[10 * w + 10], 1, "a source that covers them is read"); + } + + /// A speck made only of cut-edge pixels that are the color beside them blended with the transparent background + /// merges by border alone. + #[test] + fn a_speck_of_blended_cut_edge_pixels_merges_by_border() { + let (labels, w, h) = speck_beside_a_line(3); + let labs = crate::quantize::palette_labs(&GROUND_INK_TONE_BROWN); + let rgba: Vec = + labels.iter().flat_map(|&l| GROUND_INK_TONE_BROWN.get(l as usize).copied().unwrap_or([0; 3]).into_iter().chain([255])).collect(); + let mut blended = vec![false; w * h]; + for (x, y) in SPECK { + blended[y * w + x] = true; + } + let mut out = labels.clone(); + denoise_nearest(&mut out, w, h, 15, &[], Some(&Source { labs: &labs, rgba: &rgba, blended: &blended, gray: false })); + let mut blind = labels.clone(); + denoise_keeping(&mut blind, w, h, 15, &[]); + assert_eq!(out, blind); + // One pixel that is not such a blend is enough to read it. + blended[10 * w + 10] = false; + let mut out = labels.clone(); + denoise_nearest(&mut out, w, h, 15, &[], Some(&Source { labs: &labs, rgba: &rgba, blended: &blended, gray: false })); + assert_eq!(out[10 * w + 10], 1); + } + /// A minimum so large that regions keep merging into big ones. #[test] fn compact_denoise_matches_the_reference_with_a_large_min_area() { diff --git a/crates/trace/src/raster.rs b/crates/trace/src/raster.rs index 51312c685a..492b3b4eed 100644 --- a/crates/trace/src/raster.rs +++ b/crates/trace/src/raster.rs @@ -28,6 +28,68 @@ pub const MAX_PIXELS: u64 = 64 << 20; /// to [`MAX_PIXELS`] (192 megapixels: 768 MB decoded); larger images are refused. pub const MAX_SOURCE_PIXELS: u64 = 192 << 20; +/// Header facts for tracing, without reserving a PNG's full decoded pixel buffer. +/// The shared allocation probe runs before the decoder's plausibility checks so the caller's +/// size refusal wins even for a large header-only file. The streaming reader still checks the +/// PNG structure and plausibility, and reports the expanded layout (including tRNS alpha). +pub(crate) fn trace_header(bytes: &[u8], max_pixels: u64, max_alloc: u64) -> Result, TraceError> { + use craft_image_codecs::{ChannelLayout, Format, Limits, PngDecodeRows, RasterColorType, RasterInspection}; + let decode_err = |e: craft_image_codecs::CodecError| TraceError::Decode(e.to_string()); + // Refuse a GIF frame larger than its logical screen before inspection's + // plausibility check can turn the caller's size refusal into a decode error. + if gif_first_frame_pixels(bytes).is_some_and(|pixels| pixels > max_pixels) { + return Err(TraceError::TooLarge { width: 0, height: 0, max: max_pixels >> 20 }); + } + if craft_image_codecs::detect(bytes) != Some(Format::Png) { + return craft_image_codecs::inspect_raster(bytes).map_err(decode_err); + } + let (width, height) = craft_image_codecs::probe_allocation_size(bytes).map_err(decode_err)?; + if u64::from(width) * u64::from(height) > max_pixels { + return Err(TraceError::TooLarge { width, height, max: max_pixels >> 20 }); + } + // The allocation probe validates the IHDR prefix. For explicit alpha layouts, its + // sample width also gives a lower bound on decoded bytes before plausibility checks. + // Preserve the alpha caller's TooLarge refusal for header-only RGBA16/GrayA images; + // the shared reader still validates CRCs, transparency expansion, and all other layouts. + let alpha_bytes_per_pixel = match bytes.get(24..26) { + Some([8, 4]) => 2, + Some([16, 4]) | Some([8, 6]) => 4, + Some([16, 6]) => 8, + _ => 0, + }; + if (u64::from(width) * u64::from(height)).saturating_mul(alpha_bytes_per_pixel) > max_alloc { + return Err(TraceError::TooLarge { width, height, max: max_pixels >> 20 }); + } + let limits = Limits { max_pixels, max_alloc, ..Limits::default() }; + let rows = PngDecodeRows::new_streaming(bytes, &limits).map_err(decode_err)?; + let h = rows.header(); + let color_type = match h.layout { + ChannelLayout::Gray => RasterColorType::Gray, + ChannelLayout::GrayA => RasterColorType::GrayAlpha, + ChannelLayout::Rgb => RasterColorType::Rgb, + ChannelLayout::Rgba => RasterColorType::Rgba, + _ => RasterColorType::Other, + }; + Ok(Some(RasterInspection { + width: h.width, + height: h.height, + channels: h.layout.channels() as u8, + bits_per_sample: (h.sample.bytes() * 8) as u8, + color_type, + palette: None, + transparent_index: None, + })) +} + +/// Reuse an already-normalized RGBA8 decode instead of allocating a second full pixel buffer. +fn into_rgba8(img: craft_image_codecs::Image) -> Vec { + if img.layout() == craft_image_codecs::ChannelLayout::Rgba && img.sample_type() == craft_image_codecs::SampleType::U8 { + img.into_data() + } else { + img.to_rgba8() + } +} + /// The largest size with `w : h`'s aspect of at most `max` pixels (each side at least 1). pub(crate) fn fit_size(w: u32, h: u32, max: u64) -> (u32, u32) { let pixels = u64::from(w) * u64::from(h); @@ -158,62 +220,84 @@ impl Raster { } /// Decode PNG / JPEG / WebP / GIF bytes (at most [`MAX_PIXELS`], checked before decoding). pub fn decode(bytes: &[u8]) -> Result { - let decode_err = |e: image::ImageError| TraceError::Decode(e.to_string()); - let reader = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().map_err(|e| TraceError::Decode(e.to_string()))?; - let (w, h) = reader.into_dimensions().map_err(decode_err)?; + if let Some(info) = trace_header(bytes, MAX_PIXELS, craft_image_codecs::Limits::default().max_alloc)? { + if info.width == 0 || info.height == 0 { + return Err(TraceError::Empty); + } + if u64::from(info.width) * u64::from(info.height) > MAX_PIXELS || gif_first_frame_pixels(bytes).is_some_and(|p| p > MAX_PIXELS) { + return Err(TraceError::TooLarge { width: info.width, height: info.height, max: MAX_PIXELS >> 20 }); + } + } else if gif_first_frame_pixels(bytes).is_some_and(|p| p > MAX_PIXELS) { + return Err(TraceError::TooLarge { width: 0, height: 0, max: MAX_PIXELS >> 20 }); + } + let opts = craft_image_codecs::DecodeOptions { + // Match rendering and trace placement: coordinates refer to stored pixels. + keep_orientation: true, + limits: craft_image_codecs::Limits { max_pixels: MAX_PIXELS, ..craft_image_codecs::Limits::default() }, + }; + let img = craft_image_codecs::decode_with(bytes, &opts).map_err(|e| TraceError::Decode(e.to_string()))?; + let (w, h) = (img.width(), img.height()); if w == 0 || h == 0 { return Err(TraceError::Empty); } - if u64::from(w) * u64::from(h) > MAX_PIXELS || gif_first_frame_pixels(bytes).is_some_and(|p| p > MAX_PIXELS) { - return Err(TraceError::TooLarge { width: w, height: h, max: MAX_PIXELS >> 20 }); - } - let img = image::load_from_memory(bytes).map_err(decode_err)?.to_rgba8(); - let (w, h) = img.dimensions(); - Ok(Self { width: w, height: h, rgba: img.into_raw() }) + Ok(Self { width: w, height: h, rgba: into_rgba8(img) }) } /// Decode as [`Raster::decode`], but an image of more than [`MAX_PIXELS`] (up to /// [`MAX_SOURCE_PIXELS`]) is scaled down, aspect kept, to the largest size within /// [`MAX_PIXELS`] instead of being refused: a 300 ppi scan of a poster traces at slightly /// less than its own resolution. The caller maps the result back with `width` / `height`. pub fn decode_to_fit(bytes: &[u8]) -> Result { - let decode_err = |e: image::ImageError| TraceError::Decode(e.to_string()); - let reader = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().map_err(|e| TraceError::Decode(e.to_string()))?; - let (w, h) = reader.into_dimensions().map_err(decode_err)?; - if w == 0 || h == 0 { - return Err(TraceError::Empty); - } - let pixels = u64::from(w) * u64::from(h); - if pixels <= MAX_PIXELS { - return Self::decode(bytes); - } - if pixels > MAX_SOURCE_PIXELS { - return Err(TraceError::TooLarge { width: w, height: h, max: MAX_SOURCE_PIXELS >> 20 }); + if let Some(info) = trace_header(bytes, MAX_SOURCE_PIXELS, if cfg!(target_arch = "wasm32") { 512 << 20 } else { MAX_SOURCE_PIXELS * 4 })? { + if info.width == 0 || info.height == 0 { + return Err(TraceError::Empty); + } + let pixels = u64::from(info.width) * u64::from(info.height); + if pixels <= MAX_PIXELS && !gif_first_frame_pixels(bytes).is_some_and(|p| p > MAX_PIXELS) { + return Self::decode(bytes); + } + if pixels > MAX_SOURCE_PIXELS { + return Err(TraceError::TooLarge { width: info.width, height: info.height, max: MAX_SOURCE_PIXELS >> 20 }); + } + if gif_first_frame_pixels(bytes).is_some_and(|p| p > MAX_SOURCE_PIXELS) { + return Err(TraceError::TooLarge { width: info.width, height: info.height, max: MAX_SOURCE_PIXELS >> 20 }); + } + } else if gif_first_frame_pixels(bytes).is_some_and(|p| p > MAX_SOURCE_PIXELS) { + return Err(TraceError::TooLarge { width: 0, height: 0, max: MAX_SOURCE_PIXELS >> 20 }); } // Decoded within the allocation the source limit needs; the web keeps file import's 512 MB. // A deeper image (16 bits a channel) that needs more fails with a decode error. - if gif_first_frame_pixels(bytes).is_some_and(|p| p > MAX_SOURCE_PIXELS) { - return Err(TraceError::TooLarge { width: w, height: h, max: MAX_SOURCE_PIXELS >> 20 }); + let opts = craft_image_codecs::DecodeOptions { + // Match rendering and trace placement: coordinates refer to stored pixels. + keep_orientation: true, + limits: craft_image_codecs::Limits { + max_pixels: MAX_SOURCE_PIXELS, + max_alloc: if cfg!(target_arch = "wasm32") { 512 << 20 } else { MAX_SOURCE_PIXELS * 4 }, + ..craft_image_codecs::Limits::default() + }, + }; + let img = craft_image_codecs::decode_with(bytes, &opts).map_err(|e| TraceError::Decode(e.to_string()))?; + let (w, h) = (img.width(), img.height()); + if w == 0 || h == 0 { + return Err(TraceError::Empty); } - let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().map_err(|e| TraceError::Decode(e.to_string()))?; - 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); - Ok(Self::fitted(&reader.decode().map_err(decode_err)?.into_rgba8(), MAX_PIXELS)) + let rgba = into_rgba8(img); + if u64::from(w) * u64::from(h) <= MAX_PIXELS { + return Ok(Self { width: w, height: h, rgba }); + } + Ok(Self::fitted(&Self { width: w, height: h, rgba }, 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); + pub(crate) fn fitted(img: &Self, max: u64) -> Self { + let (nw, nh) = fit_size(img.width, img.height, max); // Box-filtered: every source pixel counts, so thin lines and anti-aliased edges survive. - Self { width: nw, height: nh, rgba: box_reduced(img.as_raw(), w, h, nw, nh) } + Self { width: nw, height: nh, rgba: box_reduced(&img.rgba, img.width, img.height, nw, nh) } } /// Encode as PNG. pub fn encode_png(&self) -> Vec { - let mut out = Vec::new(); - if let Some(img) = image::RgbaImage::from_raw(self.width, self.height, self.rgba.clone()) { - let _ = img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png); - } - out + let Ok(img) = craft_image_codecs::Image::from_u8(self.width, self.height, craft_image_codecs::ChannelLayout::Rgba, self.rgba.clone()) else { + return Vec::new(); + }; + craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &Default::default()).unwrap_or_default() } /// Pixel `(x, y)`; transparent black outside the raster (or past the end of a raster whose /// fields were set to a size its bytes don't have). diff --git a/crates/trace/src/seam.rs b/crates/trace/src/seam.rs index b17d1dd6da..b0c6447d8a 100644 --- a/crates/trace/src/seam.rs +++ b/crates/trace/src/seam.rs @@ -107,7 +107,7 @@ fn fills(paths: &[TracedPath], size: (u32, u32)) -> Option { continue; } if sp.closed && marks.iter().all(|&m| m) { - runs.push(SubPath::new(sp.anchors.clone(), true)); + runs.push(sp.clone()); continue; } // Start after an unmarked segment, so that a run across the subpath's first anchor diff --git a/crates/trace/src/tests.rs b/crates/trace/src/tests.rs index 85e9d09778..7e037c8b70 100644 --- a/crates/trace/src/tests.rs +++ b/crates/trace/src/tests.rs @@ -716,13 +716,35 @@ fn a_cut_out_edge_in_grayscale_ties_by_its_gray() { let t = TRANSPARENT; let q = Quantized { labels: vec![0, 2, 1, t, t, t], palette: vec![[50, 50, 50], [150, 150, 150], [90, 90, 90]] }; let mut gray = q.clone(); - crate::quantize::settle_cut_edges(&mut gray, &img, true); + let marked = crate::quantize::settle_cut_edges(&mut gray, &img, true); assert_eq!(gray.palette.get(gray.labels[1] as usize), Some(&[50, 50, 50])); + assert_eq!(marked, [false, true, false, false, false, false], "the edge pixel is marked as a blend"); let mut color = q; crate::quantize::settle_cut_edges(&mut color, &img, false); assert_eq!(color.palette.get(color.labels[1] as usize), Some(&[150, 150, 150])); } +#[test] +fn a_cut_out_edge_pixel_already_of_the_color_beside_it_is_marked_when_a_blend_of_it() { + // A semi-transparent dark red edge pixel between opaque red and blue pixels, already labeled red: it keeps red, + // and is marked as a blend for Noise. A purple one labeled red is a blend of neither pixel's color alone and is + // not marked. + for (edge, blend) in [([128, 0, 0, 192], true), ([128, 0, 128, 192], false)] { + let img = Raster::from_fn(3, 2, |x, y| match (x, y) { + (0, 0) => [255, 0, 0, 255], + (1, 0) => edge, + (2, 0) => [0, 0, 255, 255], + _ => [0, 0, 0, 0], + }); + let t = TRANSPARENT; + let q = Quantized { labels: vec![0, 0, 1, t, t, t], palette: vec![[255, 0, 0], [0, 0, 255]] }; + let mut settled = q.clone(); + let marked = crate::quantize::settle_cut_edges(&mut settled, &img, false); + assert_eq!(settled, q, "{edge:?}"); + assert_eq!(marked, [false, blend, false, false, false, false], "{edge:?}"); + } +} + #[test] fn a_semi_transparent_line_across_a_gap_keeps_its_own_color() { // A light block, a transparent column, then a semi-transparent tan line: the block lies within @@ -761,8 +783,9 @@ fn a_thin_semi_transparent_outline_keeps_its_own_color() { let q = quantize(&img, &TraceParams { mode, colors: 3, ..TraceParams::default() }); assert_ne!(q.labels[9 * 60 + 30], q.labels[30 * 60 + 30], "{mode:?}, alpha {alpha}: the outline has a color of its own"); let mut settled = q.clone(); - crate::quantize::settle_cut_edges(&mut settled, &img, mode == Mode::Grayscale); + let marked = crate::quantize::settle_cut_edges(&mut settled, &img, mode == Mode::Grayscale); assert_eq!(settled, q, "{mode:?}, alpha {alpha}"); + assert!(!marked.contains(&true), "{mode:?}, alpha {alpha}: the outline is no blend of the square"); } } } @@ -899,10 +922,10 @@ fn presets_have_their_paths_corners_and_noise() { ("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), + ("6 Colors", 50.0, 50.0, 8), + ("16 Colors", 50.0, 50.0, 8), ("Shades of Gray", 50.0, 50.0, 15), - ("Black and White Logo", 50.0, 75.0, 25), + ("Black and White Logo", 50.0, 75.0, 5), ("Sketched Art", 50.0, 50.0, 20), ("Silhouettes", 50.0, 50.0, 90), ("Line Art", 50.0, 75.0, 20), @@ -1123,7 +1146,7 @@ fn scaling_down_weighs_color_by_alpha() { // 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 decoded = Raster::decode(&half_clear.encode_png()).unwrap(); let fitted = Raster::fitted(&decoded, 2); assert_eq!((fitted.width, fitted.height), (2, 1)); assert_eq!(fitted.rgba, [[200, 30, 30, 128]; 2].concat()); @@ -1928,7 +1951,9 @@ fn contour_spread(res: &TraceResult) -> (f64, usize) { #[test] fn the_borders_of_a_gradients_bands_follow_its_contours() { - let res = trace(&wavy_bands(), &sixteen_colors()); + // At the Noise this test was written for: at 16 Colors' Noise 8 the 6 levels of noise leave more + // small regions along the borders. + let res = trace(&wavy_bands(), &TraceParams { noise: 15, ..sixteen_colors() }); // The square's sides are edges: it keeps its four corners. let [l, t, r, b] = WAVY_SQUARE; let square = res.paths.iter().find(|p| p.color.iter().all(|&c| c < 40)).expect("the dark square"); @@ -2174,7 +2199,8 @@ fn small_accents_of_other_colors_leave_a_tinted_photo_continuous_tone() { } } -/// `img` saved as a JPEG of `quality` and read back. +/// `img` saved as a JPEG of `quality` and read back. The `image` crate's encoder stays the fixture: +/// `a_jpegs_blocks_are_not_traced_as_steps` measures block artifacts, which differ by encoder. fn through_jpeg(img: &Raster, quality: u8) -> Raster { let rgb: Vec = img.rgba.chunks(4).flat_map(|p| [p[0], p[1], p[2]]).collect(); let mut bytes = vec![]; @@ -4033,4 +4059,75 @@ fn a_gif_frame_larger_than_its_screen_is_refused_before_decoding() { gif.extend([2, 1, 0, 0, 0x3B]); assert!(matches!(Raster::decode(&gif), Err(TraceError::TooLarge { .. })), "{:?}", Raster::decode(&gif).err()); assert!(matches!(Raster::decode_to_fit(&gif), Err(TraceError::TooLarge { .. }))); + assert!(matches!(decode_alpha(&gif), Err(TraceError::TooLarge { .. }))); +} + +// Synthetic PNG chunks for transparency/orientation regression fixtures. +fn png_test_chunk(kind: &[u8; 4], data: &[u8]) -> Vec { + let mut out = (data.len() as u32).to_be_bytes().to_vec(); + out.extend(kind); + out.extend(data); + let mut crc = !0u32; + for &b in &out[4..] { + crc ^= u32::from(b); + for _ in 0..8 { + crc = if crc & 1 != 0 { 0xedb8_8320 ^ (crc >> 1) } else { crc >> 1 }; + } + } + out.extend((!crc).to_be_bytes()); + out +} + +#[test] +fn alpha_decode_keeps_rgb_and_grayscale_png_transparency_keys() { + use craft_image_codecs::{ChannelLayout, Format, Image}; + for (layout, samples, key) in + [(ChannelLayout::Rgb, vec![10, 20, 30, 40, 50, 60], vec![0, 10, 0, 20, 0, 30]), (ChannelLayout::Gray, vec![10, 40], vec![0, 10])] + { + let image = Image::from_u8(2, 1, layout, samples).unwrap(); + let mut png = craft_image_codecs::encode(&image, Format::Png, &Default::default()).unwrap(); + // A transparency key precedes IDAT, immediately after the IHDR chunk. + png.splice(33..33, png_test_chunk(b"tRNS", &key)); + assert_eq!(decode_alpha(&png).unwrap(), Some((2, 1, vec![0, 255]))); + } +} + +#[test] +fn trace_and_alpha_keep_stored_pixels_with_exif_orientation() { + use craft_image_codecs::{ChannelLayout, Format, Image}; + // Little-endian TIFF IFD containing Orientation=6 (90 degrees clockwise). + let exif = [b'I', b'I', 42, 0, 8, 0, 0, 0, 1, 0, 0x12, 1, 3, 0, 1, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0]; + let raster = Raster::from_fn(3, 2, |x, y| [x as u8 * 60, y as u8 * 90, 17, (x + 3 * y) as u8 * 40]); + let mut png = raster.encode_png(); + png.splice(33..33, png_test_chunk(b"eXIf", &exif)); + for actual in [Raster::decode(&png).unwrap(), Raster::decode_to_fit(&png).unwrap()] { + assert_eq!((actual.width, actual.height), (3, 2)); + assert_eq!(actual.rgba, raster.rgba); + } + assert_eq!(decode_alpha(&png).unwrap(), Some((3, 2, raster.rgba.as_chunks::<4>().0.iter().map(|p| p[3]).collect()))); + + let image = + Image::from_u8(3, 2, ChannelLayout::Rgb, raster.rgba.as_chunks::<4>().0.iter().flat_map(|p| p[..3].iter().copied()).collect()).unwrap(); + let mut jpeg = craft_image_codecs::encode(&image, Format::Jpeg, &Default::default()).unwrap(); + let expected = Raster::decode(&jpeg).unwrap(); + let mut app1 = vec![0xff, 0xe1]; + app1.extend(((exif.len() + 8) as u16).to_be_bytes()); + app1.extend(b"Exif\0\0"); + app1.extend(exif); + jpeg.splice(2..2, app1); + for actual in [Raster::decode(&jpeg).unwrap(), Raster::decode_to_fit(&jpeg).unwrap()] { + assert_eq!((actual.width, actual.height), (3, 2)); + assert_eq!(actual.rgba, expected.rgba); + } +} + +#[test] +fn alpha_rejects_oversized_png_before_decoding() { + assert!(matches!(decode_alpha(&png_header(30_000, 30_000)), Err(TraceError::TooLarge { .. }))); + assert!(matches!(decode_alpha(&png_header(64, 64)), Err(TraceError::Decode(_)))); + let mut deep = png_header(7000, 6000); + deep[24] = 16; + let ihdr = png_test_chunk(b"IHDR", &deep[16..29]); + deep.splice(8..33, ihdr); + assert!(matches!(decode_alpha(&deep), Err(TraceError::TooLarge { .. }))); } diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 2ea7ac8079..92a942f4c5 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -54,6 +54,9 @@ log = { workspace = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] craft-ui = { workspace = true, features = ["native-windows"] } craft-update = { workspace = true } +# The local date and time the status bar's Date and Time readout shows (`chrono::Local`). Already in +# Cargo.lock with the time-zone crates `clock` uses. +chrono = { workspace = true, features = ["clock"] } [target.'cfg(target_arch = "wasm32")'.dependencies] # `now_ms` (src/lib.rs) reads the page's `performance.now()` with this crate in the web build. It is diff --git a/crates/ui-egui/src/addons.rs b/crates/ui-egui/src/addons.rs index 522f82bd2b..b63c32af59 100644 --- a/crates/ui-egui/src/addons.rs +++ b/crates/ui-egui/src/addons.rs @@ -9,6 +9,7 @@ pub mod cutting; pub mod document; pub mod enclosing_lasso; pub mod image; +pub mod packaging; pub mod pathtools; pub mod pen; pub mod select; @@ -30,6 +31,7 @@ pub fn plugin_menu() -> Vec { Item::Sub("Document Tools", document::menu()), Item::Sub("Enclosing Lasso", enclosing_lasso::menu()), Item::Sub("Image Tools", image::menu()), + Item::Sub("Packaging Tools", packaging::menu()), Item::Sub("Path Precision Tools", pathtools::menu()), Item::Sub("Selection Tools", select::menu()), Item::Sub("Smart Pen", pen::menu()), diff --git a/crates/ui-egui/src/addons/packaging.rs b/crates/ui-egui/src/addons/packaging.rs new file mode 100644 index 0000000000..1c70bef5d0 --- /dev/null +++ b/crates/ui-egui/src/addons/packaging.rs @@ -0,0 +1,134 @@ +//! Packaging Tools' submenu (Object › Plug-ins › Packaging Tools) and its Fold Lines panel. The +//! panel lists the fold line roles, each with its swatch's chip and how many of the selected objects +//! have it (of the whole document while nothing is selected); clicking a role gives the selected +//! paths that role (`addon.packaging.setRole`). Its menu's Role Swatches… picks the swatch that +//! carries a role (`addon.packaging.setRoleSwatch`). + +use egui::{Align, Layout, Sense, Ui, vec2}; +use serde_json::{Value, json}; + +use crate::VectorcraftApp; +use crate::menus::Item; +use crate::panels::{empty_state, pstate, set_pstate}; +use crate::widgets::{self, dim_label}; + +/// The panel's id (`window.panel {panel: "foldLines"}`). +pub const ID: &str = "foldLines"; +/// The command that gives objects a role. +pub const SET_ROLE: &str = "addon.packaging.setRole"; +/// The command that picks a role's swatch. +pub const SET_ROLE_SWATCH: &str = "addon.packaging.setRoleSwatch"; +/// The roles by name, as `addon.packaging.setRole` and Role Swatches… take them. +pub const ROLES: &[(&str, &str)] = + &[("Cut Line", "cut"), ("Crease Line", "crease"), ("Partial Cut Line", "partialCut"), ("Perforation Line", "perforation")]; + +/// Where the panel keeps the last `addon.packaging.roles` answer (panel state). +const STATE: &str = "fold-lines"; + +/// Object › Plug-ins › Packaging Tools. +pub fn menu() -> Vec { + let make = |label, role: &str| Item::Cmd(label, SET_ROLE, json!({ "role": role })); + vec![ + Item::Cmd("Fold Lines", "window.panel", json!({ "panel": ID })), + Item::Sep, + make("Make Cut Line", "cut"), + make("Make Crease Line", "crease"), + make("Make Partial Cut Line", "partialCut"), + make("Make Perforation Line", "perforation"), + ] +} + +/// One role row: (role id, swatch name, the swatch's paint if the document has it, count). +type Row = (String, String, Option, u64); + +/// The panel's rows for one document state. +#[derive(Clone, Default)] +struct Rows { + /// What they were read for: the document, its revision and its selection. + key: Option<(u64, u64, Vec)>, + rows: Vec, +} + +/// The rows for the active document as it is now, read again only when it changed. +fn rows(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec { + let Some(st) = app.session.active() else { return vec![] }; + let key = (st.uid, st.revision, st.selection.objects.iter().map(|id| id.0).collect::>()); + let mut kept: Rows = pstate(ctx, STATE); + if kept.key.as_ref() == Some(&key) { + return kept.rows; + } + let answer = app.session.execute("addon.packaging.roles", &json!({})).unwrap_or(Value::Null); + let d = app.session.active().map(|st| st.doc.clone()); + let row = |r: &Value| { + let swatch = r["swatch"].as_str()?.to_string(); + let paint = d.as_ref().and_then(|d| d.swatch(&swatch)).map(|s| s.paint.clone()); + Some((r["role"].as_str()?.to_string(), swatch, paint, r["count"].as_u64()?)) + }; + kept = Rows { key: Some(key), rows: answer["roles"].as_array().into_iter().flatten().filter_map(row).collect() }; + set_pstate(ctx, STATE, kept.clone()); + kept.rows +} + +pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { + let Some(st) = app.session.active() else { + empty_state(ui, "scissors", tl!("No document"), tl!("Open a document to mark its fold lines.")); + return; + }; + let selected = !st.selection.is_empty(); + if !selected { + dim_label(ui, tl!("No objects are selected.")); + ui.add_space(4.0); + } + let mut picked = None; + for (role, swatch, paint, count) in rows(app, ui.ctx()) { + let label = ROLES.iter().find(|(_, id)| *id == role).map_or(role.as_str(), |(l, _)| *l); + let clicked = ui + .add_enabled_ui(selected, |ui| { + ui.horizontal(|ui| { + let (chip, _) = ui.allocate_exact_size(vec2(14.0, 14.0), Sense::hover()); + widgets::paint_chip(ui, chip, paint.as_ref().unwrap_or(&vectorcraft_color::Paint::None)); + let resp = ui.selectable_label(false, tl!(label)).on_hover_text(swatch.as_str()); + ui.with_layout(Layout::right_to_left(Align::Center), |ui| dim_label(ui, &count.to_string())); + resp.clicked() + }) + .inner + }) + .inner; + if clicked { + picked = Some(role); + } + } + if let Some(role) = picked + && let Err(e) = app.run(SET_ROLE, json!({ "role": role })) + { + app.status(e); + } +} + +/// Role Swatches… (the dialog of `addon.packaging.setRoleSwatch`): when another role is picked, its +/// Swatch field shows that role's current swatch. `__role` keeps the role the field was filled for. +pub(crate) fn follow_role(app: &mut VectorcraftApp, d: &mut crate::state::Dialog) { + let role = d.str("role"); + if d.str("__role") == role { + return; + } + let answer = app.session.execute("addon.packaging.roles", &json!({})).unwrap_or(Value::Null); + let current = answer["roles"].as_array().into_iter().flatten().find(|r| r["role"] == role.as_str()).and_then(|r| r["swatch"].as_str()); + if let Some(swatch) = current { + d.fields.insert("swatch".into(), json!(swatch)); + } + d.fields.insert("__role".into(), json!(role)); +} + +/// The panel's ≡ menu: Role Swatches… opens the options of `addon.packaging.setRoleSwatch` on the +/// Cut role and its current swatch. +pub fn panel_menu(app: &mut VectorcraftApp, ui: &mut Ui) { + if widgets::menu_item(ui, tl!("Role Swatches…"), app.session.active().is_some(), false) { + let swatch = rows(app, ui.ctx()).into_iter().find(|r| r.0 == "cut").map_or_else(|| "Cut".to_string(), |r| r.1); + let (id, p) = crate::menus::click_target("Role Swatches…", SET_ROLE_SWATCH, &json!({ "role": "cut", "swatch": swatch })); + crate::menus::invoke(app, &id, p); + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/addons/packaging/tests.rs b/crates/ui-egui/src/addons/packaging/tests.rs new file mode 100644 index 0000000000..cfe9909dc8 --- /dev/null +++ b/crates/ui-egui/src/addons/packaging/tests.rs @@ -0,0 +1,133 @@ +use serde_json::json; +use vectorcraft_engine::Session; + +use super::{ID, ROLES, SET_ROLE, SET_ROLE_SWATCH, show}; +use crate::tests_labels::painted_text; +use crate::{VectorcraftApp, menus}; + +/// An app with two rectangles, nothing selected → (app, their ids). +fn app() -> (VectorcraftApp, u64, u64) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let rect = |app: &mut VectorcraftApp, x: f64| { + app.run("shape.rectangle", json!({"x": x, "y": 20, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap() + }; + let (a, b) = (rect(&mut app, 20.0), rect(&mut app, 100.0)); + app.run("select.none", json!({})).unwrap(); + (app, a, b) +} + +#[test] +fn the_plugins_submenu_opens_the_panel_and_makes_each_kind_of_line() { + let (mut app, a, _) = app(); + let entries = menus::menu_entries(&app); + let under = |label: &str| entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Packaging Tools"] && e.label == label); + let item = under("Fold Lines").expect("listed"); + assert_eq!((item.command.as_deref(), &item.params), (Some("window.panel"), &json!({ "panel": ID }))); + for (label, role) in + [("Make Cut Line", "cut"), ("Make Crease Line", "crease"), ("Make Partial Cut Line", "partialCut"), ("Make Perforation Line", "perforation")] + { + let e = under(label).unwrap_or_else(|| panic!("{label} listed")); + assert_eq!((e.command.as_deref(), &e.params), (Some(SET_ROLE), &json!({ "role": role })), "{label}"); + } + assert!(!crate::panel_docking::showing(&app.ui, ID)); + menus::invoke(&mut app, "window.panel", item.params.clone()); + assert!(crate::panel_docking::showing(&app.ui, ID), "the panel opens"); + app.run("select.set", json!({"ids": [a]})).unwrap(); + let make = under("Make Partial Cut Line").unwrap(); + let (target, p) = menus::click_target(&make.label, SET_ROLE, &make.params); + menus::invoke(&mut app, &target, p); + let r = app.session.execute("addon.packaging.roles", &json!({"ids": [a]})).unwrap(); + assert_eq!(r["roles"][2]["count"], json!(1), "{r}"); +} + +#[test] +fn the_panel_counts_the_roles_and_says_when_nothing_is_selected() { + let (mut app, a, b) = app(); + app.run(SET_ROLE, json!({"role": "cut", "ids": [a, b]})).unwrap(); + app.run("select.none", json!({})).unwrap(); + let text = painted_text(&mut app, show); + assert!(text.contains("No objects are selected."), "{text}"); + for (label, _) in ROLES { + assert!(text.contains(label), "{label}: {text}"); + } + assert!(text.contains('2'), "the document's two cut lines: {text}"); + app.run("select.set", json!({"ids": [a]})).unwrap(); + let text = painted_text(&mut app, show); + assert!(!text.contains("No objects are selected."), "{text}"); + assert!(text.contains('1') && !text.contains('2'), "the selection's one cut line: {text}"); +} + +/// A click on the panel row that screen readers name `label`. egui finds what the pointer is over +/// from the frame before, so the move gets a frame of its own. +fn click_row(app: &mut VectorcraftApp, label: &str) { + crate::i18n::set_current(crate::i18n::Lang::EN); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + let mut time = 0.0; + let mut frame = |app: &mut VectorcraftApp, events: Vec| { + time += 0.1; + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(300.0, 200.0)); + let input = egui::RawInput { events, time: Some(time), screen_rect: Some(screen), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| show(app, ui)); + out.textures_delta.clear(); + out + }; + frame(app, vec![]); + let out = frame(app, vec![]); + let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; + let node = nodes.iter().find(|(_, n)| n.label() == Some(label)); + let b = node.unwrap_or_else(|| panic!("no row named {label:?}")).1.bounds().expect("bounds"); + let at = egui::pos2((b.x0 + b.x1) as f32 * 0.5, (b.y0 + b.y1) as f32 * 0.5); + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + frame(app, vec![egui::Event::PointerMoved(at)]); + frame(app, vec![button(true)]); + frame(app, vec![button(false)]); +} + +#[test] +fn clicking_a_row_gives_the_selection_that_role_and_does_nothing_without_one() { + let (mut app, a, b) = app(); + click_row(&mut app, "Crease Line"); + let none = app.session.execute("addon.packaging.roles", &json!({"ids": [a, b]})).unwrap(); + assert_eq!(none["roles"][1]["count"], json!(0), "nothing selected: {none}"); + app.run("select.set", json!({"ids": [a]})).unwrap(); + click_row(&mut app, "Crease Line"); + let r = app.session.execute("addon.packaging.roles", &json!({"ids": [a, b]})).unwrap(); + assert_eq!(r["roles"][1]["count"], json!(1), "{r}"); +} + +#[test] +fn role_swatches_opens_the_options_of_its_command() { + let (target, p) = menus::click_target("Role Swatches…", SET_ROLE_SWATCH, &json!({"role": "cut", "swatch": "Cut"})); + assert_eq!((target.as_str(), &p["command"]), ("ui.paramDialog", &json!(SET_ROLE_SWATCH))); + let doc = vectorcraft_engine::find_command(SET_ROLE_SWATCH).unwrap().params; + let ids: Vec<&str> = ROLES.iter().map(|(_, id)| *id).collect(); + assert!(doc.contains(&format!("role: {}", ids.join("|"))), "{doc}"); +} + +#[test] +fn role_swatches_shows_the_swatch_of_the_role_picked() { + let (mut app, a, _) = app(); + app.run(SET_ROLE, json!({"role": "crease", "ids": [a]})).unwrap(); + app.run("swatch.edit", json!({"name": "Crease", "newName": "Score"})).unwrap(); + let mut d = crate::state::Dialog::new("command", json!({"role": "cut", "swatch": "Cut"})); + super::follow_role(&mut app, &mut d); + assert_eq!(d.str("swatch"), "Cut"); + d.fields.insert("role".into(), json!("crease")); + super::follow_role(&mut app, &mut d); + assert_eq!(d.str("swatch"), "Score", "the Crease role's swatch"); + // A swatch typed for the same role stays. + d.fields.insert("swatch".into(), json!("Ink")); + super::follow_role(&mut app, &mut d); + assert_eq!(d.str("swatch"), "Ink"); + assert_eq!(crate::dialogs::form::params(&d), json!({"role": "crease", "swatch": "Ink"}), "the dialog sends no __role"); +} + +#[test] +fn the_panel_without_a_document_asks_for_one() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let text = painted_text(&mut app, show); + assert!(text.contains("No document"), "{text}"); +} diff --git a/crates/ui-egui/src/canvas/input.rs b/crates/ui-egui/src/canvas/input.rs index e7e5c0394b..d811ad3bac 100644 --- a/crates/ui-egui/src/canvas/input.rs +++ b/crates/ui-egui/src/canvas/input.rs @@ -121,6 +121,7 @@ pub(super) fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respo { // Middle-button drag pans the view whatever the tool. ui.data_mut(|dd| dd.insert_temp(drag_id(), Drag::Pan { start, center: v.center, middle: true })); + app.session.tool_press_elsewhere(); app.session.tool_hover_ended(view); } else if let Some(d) = drag { // The pointer gone (a pen lifted with its press), the drag ends where it was last seen. @@ -342,6 +343,9 @@ fn begin_drag(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, p: Pos2) { if !space && matches!(d, Drag::ZoomBox { .. } | Drag::ZoomScrub { .. } | Drag::Pan { .. } | Drag::RotateView { .. }) { crate::shortcuts::note_tool_use(app); } + if !matches!(d, Drag::Tool) { + app.session.tool_press_elsewhere(); + } // Panning, zooming or turning the view takes the pointer from the tool's hover. if !tool_holds(d) { app.session.tool_hover_ended(view); diff --git a/crates/ui-egui/src/canvas/task_bar.rs b/crates/ui-egui/src/canvas/task_bar.rs index c3321195c0..9c6bcadd71 100644 --- a/crates/ui-egui/src/canvas/task_bar.rs +++ b/crates/ui-egui/src/canvas/task_bar.rs @@ -75,6 +75,27 @@ fn shape_tool_on_shape(app: &VectorcraftApp) -> bool { }) } +/// Whether the Smooth tool is in use with a selected path it can smooth +/// ([`vectorcraft_tools::draw2::can_smooth`]). The answer is kept in `ctx` for the document's +/// revision, which moves with every change of the document or the selection, so an unchanged +/// selection is not walked again each frame. +fn smooth_tool_on_paths(app: &VectorcraftApp, ctx: &egui::Context) -> bool { + if app.session.tool_id() != "smooth" { + return false; + } + let Some(st) = app.session.active() else { return false }; + let id = task_bar_id().with("smooth"); + let key = (st.uid, st.revision); + if let Some((k, found)) = ctx.data(|d| d.get_temp::<((u64, u64), bool)>(id)) + && k == key + { + return found; + } + let found = vectorcraft_tools::draw2::can_smooth(&st.doc, &st.selection); + ctx.data_mut(|d| d.insert_temp(id, (key, found))); + found +} + /// Whether the bar shows its blank canvas actions, Draw (Pencil) and Place Image: a selection tool is /// in use and the active document has no artwork, only layers and guides. fn blank_canvas(app: &VectorcraftApp) -> bool { @@ -130,7 +151,9 @@ pub(crate) fn task_bar_shows_type(app: &VectorcraftApp) -> bool { /// While a basic shape tool (Rectangle, Rounded Rectangle, Ellipse, Polygon or Star) has one closed /// path selected, as after it draws one, the bar offers Edit Path, Fill and Stroke, and Shape /// Properties for a live rectangle, rounded rectangle, ellipse or polygon; with nothing selected, or -/// any other selection, those tools show no bar. Selected type also shows the font family, font +/// any other selection, those tools show no bar. While the Smooth tool has a path it can smooth +/// selected, the bar shows the tool's Fidelity field and Tool Options…; with no such path it shows +/// no bar. Selected type also shows the font family, font /// style and Font Size controls before its Fill. /// While a Type tool edits type, or has type selected, the bar shows only those controls and the /// Fill. When one row would be wider than the canvas, the font controls take a row of their own, @@ -150,7 +173,10 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { // A basic shape tool with its shape selected offers Edit Path, Fill, Stroke and the shape's // properties, as the same help page describes. let shaping = shape_tool_on_shape(app); - if !(on_artboards || typing || blank || shaping || selection_tool_with_selection(app)) { + // The Smooth tool with a path to smooth offers its option, Fidelity, as the same help page + // describes for the Smooth tool, and Tool Options… for its dialog. + let smoothing = smooth_tool_on_paths(app, ui.ctx()); + if !(on_artboards || typing || blank || shaping || smoothing || selection_tool_with_selection(app)) { return; } // Selected type has the font controls too, as the help page describes @@ -197,15 +223,7 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { // Edit Path: the Direct Selection tool, to edit the path's anchors. let edit_path = || (tl!("Edit Path"), "dc-direct", "tool.select", json!({"tool": "directSelection"})); if on_artboards { - // As in the reference app, the Artboard tool offers to resize, duplicate and export the - // artboards (), - // and to rearrange them (). - items.push((tl!("Resize"), "move-diagonal-2", TASK_BAR_ARTBOARD_OPTIONS, none())); - items.push((tl!("Duplicate"), "copy", TASK_BAR_DUPLICATE_ARTBOARDS, none())); - if st.doc.artboards.len() > 1 { - items.push((tl!("Rearrange All"), "dc-rearrange", TASK_BAR_REARRANGE_ARTBOARDS, none())); - } - items.push((tl!("Export"), "share-2", "file.exportForScreens", none())); + artboard_items(&mut items, st.doc.artboards.len()); } else if blank { // Draw (Pencil) switches to the Pencil tool; Place Image picks files for the Place dialog. items.push((tl!("Draw (Pencil)"), "pencil", "tool.select", json!({"tool": "pencil"}))); @@ -213,6 +231,10 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { } else if shaping { // A basic shape tool's one action; its Fill, Stroke and Shape Properties follow as chips. items.push(edit_path()); + } else if smoothing { + // The Fidelity field, then Tool Options… for the dialog that shows it with its slider. + items.push((tl!("Fidelity:"), "", TASK_BAR_FIDELITY, none())); + items.push((tl!("Tool Options…"), "settings", "tool.options", json!({"tool": "smooth"}))); } else if !typing { // The selection tools' object actions. A Type tool's bar leaves them out, Create Outlines // and the type conversions included. @@ -319,8 +341,9 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { // The selected objects' Fill, Stroke, Recolor Artwork (when they have colours to recolour) and // Lock (a basic shape's properties instead), left out with the Artboard tool and on a blank // canvas, which have no selected objects. A Type tool's bar has the Fill alone. A basic shape - // tool's bar has the Fill, the Stroke and a live shape's Shape Properties. - let objects = !on_artboards && !blank; + // tool's bar has the Fill, the Stroke and a live shape's Shape Properties. The Smooth tool's bar + // has none of them. + let objects = !on_artboards && !blank && !smoothing; let chips: Vec = [ (objects, Chip::Fill), (objects && !typing, Chip::Stroke), @@ -330,7 +353,8 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { .into_iter() .filter_map(|(shown, chip)| shown.then_some(chip)) .collect(); - let widths: Vec = items.iter().map(|(label, _, cmd, _)| if icon_only(cmd) { BAR_MORE } else { action_width(ui, label) }).collect(); + let widths: Vec = items.iter().map(|(label, _, cmd, _)| item_width(ui, label, cmd)).collect(); + let fidelity = app.session.tool_options()["fidelity"].as_f64(); let font_w = fonts.then(|| { let w = crate::panels::character::TASK_BAR_WIDTHS; w.iter().sum::() + BAR_GAP * (w.len() - 1) as f32 @@ -408,16 +432,7 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { if *at != Some(row) { continue; } - // The convert buttons show their icon alone, named by their hover text, as - // the Control bar's do. - let clicked = if icon_only(cmd) { - widgets::icon_button(ui, icon, label, false, BAR_MORE).clicked() - } else { - action_button(ui, &t, label, icon) - }; - if clicked { - run = Some((*cmd, params.clone())); - } + run = bar_item(ui, &t, (*label, *icon, *cmd, params), fidelity).or(run.take()); } // Type's font family, font style and Font Size, which act as the Character // panel's do: on the characters a Type tool selects, else on the selected type. @@ -510,6 +525,9 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { // The convert buttons convert the direct-selected anchors, as the Control bar's buttons do. Some((TASK_BAR_TO_CORNER, _)) => crate::menus::invoke(app, "path.convertAnchors", json!({"to": "corner"})), Some((TASK_BAR_TO_SMOOTH, _)) => crate::menus::invoke(app, "path.convertAnchors", json!({"to": "smooth"})), + // Fidelity listed in More Options, on a canvas too narrow for its field: the Smooth tool's + // Tool Options, which show it. + Some((TASK_BAR_FIDELITY, _)) => crate::menus::invoke(app, "tool.options", json!({"tool": "smooth"})), Some((c, p)) => crate::menus::invoke(app, c, p), None => {} } @@ -658,6 +676,61 @@ fn action_width(ui: &Ui, label: &str) -> f32 { ui.painter().layout_no_wrap(label.to_string(), egui::FontId::proportional(13.0), Color32::PLACEHOLDER).size().x + 38.0 } +/// The width of the Smooth tool's Fidelity on the Contextual Task Bar: its label, the gap and the +/// field. +fn fidelity_width(ui: &Ui) -> f32 { + widgets::text_width(ui, fidelity_label(tl!("Fidelity:"), &Tokens::get(ui.ctx()))) + BAR_GAP + crate::dialogs::freehand::FIDELITY_FIELD_W +} + +/// The Fidelity field's label, `label`, as the bar draws it. +fn fidelity_label(label: &str, t: &Tokens) -> egui::RichText { + egui::RichText::new(label).size(13.0).color(t.text_strong) +} + +/// The width of the Contextual Task Bar's item `label` that runs `cmd`. +fn item_width(ui: &Ui, label: &str, cmd: &str) -> f32 { + match cmd { + TASK_BAR_FIDELITY => fidelity_width(ui), + _ if icon_only(cmd) => BAR_MORE, + _ => action_width(ui, label), + } +} + +/// One of the Contextual Task Bar's items, `label` with `icon`, which runs `cmd` with `params`, and +/// the Smooth tool's `fidelity`. Returns the command to run when it was used. +fn bar_item( + ui: &mut Ui, + t: &Tokens, + (label, icon, cmd, params): (&str, &str, &'static str, &serde_json::Value), + fidelity: Option, +) -> Option<(&'static str, serde_json::Value)> { + // The Smooth tool's Fidelity, labeled, sets the tool's option as it is typed or stepped. + if cmd == TASK_BAR_FIDELITY { + return fidelity_slot(ui, t, label, fidelity); + } + // The convert buttons show their icon alone, named by their hover text, as the Control bar's do. + let clicked = if icon_only(cmd) { widgets::icon_button(ui, icon, label, false, BAR_MORE).clicked() } else { action_button(ui, t, label, icon) }; + clicked.then(|| (cmd, params.clone())) +} + +/// The Smooth tool's Fidelity on the Contextual Task Bar, `label` and a field showing the tool's +/// `fidelity` (nothing without one). Returns the command that sets a new value typed or stepped to. +fn fidelity_slot(ui: &mut Ui, t: &Tokens, label: &str, fidelity: Option) -> Option<(&'static str, serde_json::Value)> { + let v = fidelity?; + let x = fidelity_field(ui, t, label, v).filter(|x| *x != v)?; + Some(("tool.setOption", json!({"tool": "smooth", "values": {"fidelity": x}}))) +} + +/// The Smooth tool's Fidelity on the Contextual Task Bar: `label` and a field showing `v`, centered +/// in a row of the bar. Returns the value typed or stepped to. +fn fidelity_field(ui: &mut Ui, t: &Tokens, label: &str, v: f64) -> Option { + ui.allocate_ui_with_layout(vec2(fidelity_width(ui), BAR_ROW), egui::Layout::left_to_right(egui::Align::Center), |ui| { + widgets::field_label(ui, fidelity_label(label, t)); + crate::dialogs::freehand::fidelity_field(ui, "task-bar-fidelity", v, "smooth") + }) + .inner +} + /// One of the Contextual Task Bar's action buttons: `icon` and `label`, named for screen readers. /// Returns whether it was clicked. fn action_button(ui: &mut Ui, t: &Tokens, label: &str, icon: &str) -> bool { @@ -743,6 +816,20 @@ fn paint_chip(ui: &mut Ui, t: &Tokens, paint: &vectorcraft_color::Paint, mixed: resp.on_hover_text(tip).clicked() } +/// The Contextual Task Bar's items with the Artboard tool in a document of `artboards` artboards: +/// Resize, Duplicate, Rearrange All (with two or more) and Export. +fn artboard_items(items: &mut Vec<(&'static str, &'static str, &'static str, serde_json::Value)>, artboards: usize) { + // As in the reference app, the Artboard tool offers to resize, duplicate and export the + // artboards (), + // and to rearrange them (). + items.push((tl!("Resize"), "move-diagonal-2", TASK_BAR_ARTBOARD_OPTIONS, json!({}))); + items.push((tl!("Duplicate"), "copy", TASK_BAR_DUPLICATE_ARTBOARDS, json!({}))); + if artboards > 1 { + items.push((tl!("Rearrange All"), "dc-rearrange", TASK_BAR_REARRANGE_ARTBOARDS, json!({}))); + } + items.push((tl!("Export"), "share-2", "file.exportForScreens", json!({}))); +} + /// The Contextual Task Bar's Center on Top and Center on Bottom, as in the Type menu, for type on a /// closed path. fn center_on_path_items(app: &VectorcraftApp, items: &mut Vec<(&'static str, &'static str, &'static str, serde_json::Value)>) { @@ -755,6 +842,9 @@ fn center_on_path_items(app: &VectorcraftApp, items: &mut Vec<(&'static str, &'s } } +/// The Contextual Task Bar's Fidelity field with the Smooth tool. +const TASK_BAR_FIDELITY: &str = "taskBar.fidelity"; + /// The Contextual Task Bar's Image Trace button: a trace with the Default preset. const TASK_BAR_IMAGE_TRACE: &str = "taskBar.imageTrace"; diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index 0d8eb858ae..7e48fc244e 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -28,9 +28,9 @@ pub(crate) use control_bar::{Fit, group_separator, left_out, link_reserve}; #[cfg(test)] use hints::hint_segments; pub use hints::{hint_bar, hint_strings}; -pub use status_bar::status_bar; +pub use status_bar::{StatusBarShow, deserialize_status_bar_show, set_status_bar_show, status_bar}; #[cfg(test)] -use status_bar::{StatusReadoutWidths, status_readouts}; +use status_bar::{StatusReadoutWidths, color_profile_name, date_time_label, status_readouts}; #[cfg(test)] use tabs::{CLOSE_BEFORE_TITLE, first_tab_shown, tab_drop, tab_groups, tab_title}; pub use tabs::{doc_tabs, isolation_bar, step_document}; diff --git a/crates/ui-egui/src/chrome/status_bar.rs b/crates/ui-egui/src/chrome/status_bar.rs index 1e946b56da..45cd600771 100644 --- a/crates/ui-egui/src/chrome/status_bar.rs +++ b/crates/ui-egui/src/chrome/status_bar.rs @@ -73,19 +73,37 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { app.status(e); } ui.separator(); - let tool = vectorcraft_tools::tool_info(app.session.tool_id()) - .map(|t| { - // The catalog keys carry the full label ("Selection Tool"); only English drops the suffix. - let shown = tl!(t.label); - if crate::i18n::current() == crate::i18n::Lang::EN { shown.trim_end_matches(" Tool") } else { shown } - }) - .unwrap_or(""); - // The tool name leaves the status message its least width and ends in an ellipsis first. + let (info, next) = info_text(app); + if let Some(secs) = next { + ui.ctx().request_repaint_after(std::time::Duration::from_secs(secs)); + } + // The info field leaves the status message its least width and ends in an ellipsis first. + // An empty readout shows a dash, so the field can still be clicked. let room = (ui.available_width() - MESSAGE_MIN - ui.spacing().item_spacing.x).max(0.0); - ui.scope(|ui| { - ui.set_max_width(room); - clipped_label(ui, egui::RichText::new(tool).size(11.5).color(t.text_dim)); + let shown = if info.is_empty() { "–" } else { info.as_str() }; + let field = ui + .scope(|ui| { + ui.set_max_width(room); + clipped_label(ui, egui::RichText::new(shown).size(11.5).color(t.text_dim)) + }) + .inner + .interact(Sense::click()); + let mut pick = None; + egui::Popup::menu(&field).show(|ui| { + ui.menu_button(tl!("Show"), |ui| { + for show in StatusBarShow::ALL { + if widgets::menu_item_name(ui, show.label(), true, app.ui.status_bar_show == show) { + pick = Some(show); + ui.close(); + } + } + }); }); + if let Some(show) = pick + && let Err(e) = app.run("view.statusBarShow", json!({ "show": show.param() })) + { + app.status(e); + } status_readouts(app, ui, &t); }); }); @@ -95,6 +113,152 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { /// The least width the status message keeps when the window is narrow. const MESSAGE_MIN: f32 = 180.0; +/// What the status bar's info field shows, chosen from the Show menu that a click on the field +/// opens (`view.statusBarShow`). Kept with the UI state ([`crate::UiState::status_bar_show`]). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub enum StatusBarShow { + /// The name of the artboard the navigator shows. + ArtboardName, + /// The name of the tool in use. + #[default] + CurrentTool, + /// The date and time. + DateTime, + /// How many steps the active document can undo and redo. + Undos, + /// The profile the active document's colors use. + ColorProfile, +} + +impl StatusBarShow { + /// Every choice, in the Show menu's order. + pub const ALL: [StatusBarShow; 5] = + [StatusBarShow::ArtboardName, StatusBarShow::CurrentTool, StatusBarShow::DateTime, StatusBarShow::Undos, StatusBarShow::ColorProfile]; + + /// The `show` param of `view.statusBarShow`. + pub fn param(self) -> &'static str { + match self { + StatusBarShow::ArtboardName => "artboardName", + StatusBarShow::CurrentTool => "currentTool", + StatusBarShow::DateTime => "dateTime", + StatusBarShow::Undos => "undos", + StatusBarShow::ColorProfile => "colorProfile", + } + } + + /// The choice whose param is `param`. + pub fn from_param(param: &str) -> Option { + StatusBarShow::ALL.into_iter().find(|s| s.param() == param) + } + + /// The Show menu's label, in the interface language. + pub fn label(self) -> &'static str { + match self { + StatusBarShow::ArtboardName => tl!("Artboard Name"), + StatusBarShow::CurrentTool => tl!("Current Tool"), + StatusBarShow::DateTime => tl!("Date and Time"), + StatusBarShow::Undos => tl!("Number of Undos"), + StatusBarShow::ColorProfile => tl!("Document Color Profile"), + } + } +} + +/// Serde reader for the saved choice ([`crate::UiState::status_bar_show`]): a value this version +/// does not know reads as Current Tool. +pub fn deserialize_status_bar_show<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + let v = ::deserialize(d)?; + Ok(v.as_str().and_then(StatusBarShow::from_param).unwrap_or_default()) +} + +/// `view.statusBarShow {show}`: the info field shows that readout from now on → the choice. +pub fn set_status_bar_show(app: &mut VectorcraftApp, p: &serde_json::Value) -> Result { + let key = "show"; + let Some(show) = p.get(key).and_then(serde_json::Value::as_str).and_then(StatusBarShow::from_param) else { + let all: Vec<&str> = StatusBarShow::ALL.iter().map(|s| s.param()).collect(); + return Err(format!("`{key}` must be one of {}", all.join(", "))); + }; + app.ui.status_bar_show = show; + Ok(json!(show.param())) +} + +/// The info field's text for the choice in the Show menu, and for Date and Time the seconds until +/// the minute it shows ends (when the bar draws again). +pub(super) fn info_text(app: &VectorcraftApp) -> (String, Option) { + let st = app.session.active(); + match app.ui.status_bar_show { + StatusBarShow::CurrentTool => { + let tool = vectorcraft_tools::tool_info(app.session.tool_id()) + .map(|t| { + // The catalog keys carry the full label ("Selection Tool"); only English drops the suffix. + let shown = tl!(t.label); + if crate::i18n::current() == crate::i18n::Lang::EN { shown.trim_end_matches(" Tool") } else { shown } + }) + .unwrap_or(""); + (tool.to_string(), None) + } + StatusBarShow::ArtboardName => { + let name = st.and_then(|d| { + let n = d.doc.artboards.len(); + d.doc.artboards.get(crate::panels::artboards::selected(app, n)).map(|a| a.name.clone()) + }); + (name.unwrap_or_default(), None) + } + StatusBarShow::DateTime => { + let (text, next) = date_time_now(); + (text, Some(next)) + } + StatusBarShow::Undos => { + let text = st.map(|d| format!("{}: {} {}: {}", tl!("Undos"), d.history.undo.len(), tl!("Redos"), d.history.redo.len())); + (text.unwrap_or_default(), None) + } + StatusBarShow::ColorProfile => (st.map(|d| color_profile_name(&d.doc)).unwrap_or_default(), None), + } +} + +/// The profile `doc`'s colors use for its color mode, as the context it draws through has it +/// ([`vectorcraft_engine::cmd::colormgmt::doc_cms`]): the one assigned (Edit › Assign Profile), else +/// the working space of that mode (Edit › Color Settings), also when the assigned one is not +/// available. +pub(super) fn color_profile_name(doc: &vectorcraft_doc::Document) -> String { + let cms = vectorcraft_engine::cmd::colormgmt::doc_cms(doc); + let settings = cms.settings(); + let name = match doc.color_mode { + vectorcraft_doc::ColorMode::Rgb => &settings.rgb, + vectorcraft_doc::ColorMode::Cmyk => &settings.cmyk, + }; + vectorcraft_color::cms::canonical_name(name).to_string() +} + +/// `[year, month, day, hour, minute, second]` as the info field shows it: `2026-11-15 14:03`. +pub(super) fn date_time_label([y, mo, d, h, mi, _]: [i64; 6]) -> String { + format!("{y:04}-{mo:02}-{d:02} {h:02}:{mi:02}") +} + +/// The local date and time ([`date_time_label`]) and the seconds until the minute ends. +#[cfg(not(target_arch = "wasm32"))] +fn date_time_now() -> (String, u64) { + use chrono::{Datelike, Timelike}; + let now = chrono::Local::now(); + let parts = [ + i64::from(now.year()), + i64::from(now.month()), + i64::from(now.day()), + i64::from(now.hour()), + i64::from(now.minute()), + i64::from(now.second()), + ]; + (date_time_label(parts), 60 - u64::from(now.second().min(59))) +} + +/// The web build reads no time zone, so it shows the date and time in UTC. +#[cfg(target_arch = "wasm32")] +fn date_time_now() -> (String, u64) { + let secs = web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).map_or(0, |d| d.as_secs()); + let parts = vectorcraft_doc::metadata::civil(i64::try_from(secs).unwrap_or(i64::MAX)); + (format!("{} UTC", date_time_label(parts)), 60 - u64::try_from(parts[5].clamp(0, 59)).unwrap_or(0)) +} + /// A label that ends in an ellipsis when it is wider than the room left in `ui`. Only a cut label /// shows its full text in a tooltip; screen readers always receive the full text. pub(super) fn clipped_label(ui: &mut Ui, text: impl Into) -> egui::Response { diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 2e4e974256..d4a7c7f0e8 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -576,6 +576,155 @@ fn a_clipped_tool_name_shows_in_full_on_hover() { } } +/// The texts of one status bar frame after `events`, `dt` seconds after the last one. +fn status_after(app: &mut crate::VectorcraftApp, ctx: &egui::Context, dt: f64, events: Vec) -> Vec { + let t = ctx.input(|i| i.time) + dt; + bar_frame(app, ctx, 1400.0, Some(t), events, super::status_bar).0 +} + +/// A press and release of the primary button at `pos`. +fn click_at(pos: egui::Pos2) -> Vec { + let button = |pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + vec![egui::Event::PointerMoved(pos), button(true), button(false)] +} + +/// The center of the first text that is `text`. +fn text_center(texts: &[StatusText], text: &str) -> egui::Pos2 { + let at = texts.iter().find(|t| t.text == text).unwrap_or_else(|| panic!("no {text:?} in {texts:?}")); + at.clip.intersect(at.bounds).center() +} + +/// The status bar's info field shows the readout `view.statusBarShow` chooses: the navigator's +/// artboard name, the tool in use, the date and time, the undo and redo counts, or the document's +/// color profile. +#[test] +fn the_status_bar_info_field_shows_the_chosen_readout() { + let (mut app, ctx) = status_readout_app(); + let texts = status_after(&mut app, &ctx, 0.1, vec![]); + assert!(texts.iter().any(|t| t.text == "Selection"), "Current Tool by default: {texts:?}"); + + app.run("artboard.new", json!({"x": 200, "y": 0, "width": 100, "height": 100, "name": "Back Cover"})).unwrap(); + app.run("view.statusBarShow", json!({"show": "artboardName"})).unwrap(); + let first = app.session.active().unwrap().doc.artboards[0].name.clone(); + assert!(status_after(&mut app, &ctx, 0.1, vec![]).iter().any(|t| t.text == first), "the first artboard's name"); + app.run("view.goToArtboard", json!({"index": 1})).unwrap(); + assert!(status_after(&mut app, &ctx, 0.1, vec![]).iter().any(|t| t.text == "Back Cover"), "the navigator's artboard"); + + app.run("view.statusBarShow", json!({"show": "undos"})).unwrap(); + let counts = |app: &crate::VectorcraftApp| { + let h = &app.session.active().unwrap().history; + format!("Undos: {} Redos: {}", h.undo.len(), h.redo.len()) + }; + let before = app.session.active().unwrap().history.undo.len(); + app.session.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + assert_eq!(counts(&app), format!("Undos: {} Redos: 0", before + 1)); + assert!(status_after(&mut app, &ctx, 0.1, vec![]).iter().any(|t| t.text == counts(&app))); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(counts(&app), format!("Undos: {before} Redos: 1")); + assert!(status_after(&mut app, &ctx, 0.1, vec![]).iter().any(|t| t.text == counts(&app)), "the redo step counts"); + + app.run("view.statusBarShow", json!({"show": "colorProfile"})).unwrap(); + let working = vectorcraft_color::cms::working_settings(); + let mode_working = |app: &crate::VectorcraftApp| match app.session.active().unwrap().doc.color_mode { + vectorcraft_doc::ColorMode::Rgb => working.rgb.clone(), + vectorcraft_doc::ColorMode::Cmyk => working.cmyk.clone(), + }; + let untagged = vectorcraft_color::cms::canonical_name(&mode_working(&app)).to_string(); + assert_eq!(super::color_profile_name(&app.session.active().unwrap().doc), untagged, "untagged: the working space"); + assert!(status_after(&mut app, &ctx, 0.1, vec![]).iter().any(|t| t.text == untagged)); + // A profile assigned for the document's color mode shows; one that is not available shows the + // working space the document draws through. + let (key, assigned) = match app.session.active().unwrap().doc.color_mode { + vectorcraft_doc::ColorMode::Rgb => ("rgb", vectorcraft_color::cms::PROPHOTO_RGB), + vectorcraft_doc::ColorMode::Cmyk => ("cmyk", vectorcraft_color::cms::DEVICE_CMYK), + }; + app.run("edit.assignProfile", json!({ key: assigned })).unwrap(); + assert!(status_after(&mut app, &ctx, 0.1, vec![]).iter().any(|t| t.text == assigned), "the assigned profile"); + let st = app.session.active_mut().unwrap(); + std::sync::Arc::make_mut(&mut st.doc).color_profiles = + vectorcraft_doc::ColorProfiles { rgb: Some("Not Installed".into()), cmyk: Some("Not Installed".into()) }; + assert!(status_after(&mut app, &ctx, 0.1, vec![]).iter().any(|t| t.text == untagged), "an unavailable profile: the working space"); + + app.run("view.statusBarShow", json!({"show": "dateTime"})).unwrap(); + let texts = status_after(&mut app, &ctx, 0.1, vec![]); + let is_date = |s: &str| { + let b = s.as_bytes(); + b.len() == 16 + && b.iter().enumerate().all(|(i, c)| match i { + 4 | 7 => *c == b'-', + 10 => *c == b' ', + 13 => *c == b':', + _ => c.is_ascii_digit(), + }) + }; + assert!(texts.iter().any(|t| is_date(&t.text)), "a date and time: {texts:?}"); + assert_eq!(super::date_time_label([2026, 3, 7, 9, 5, 59]), "2026-03-07 09:05"); + + // Without a document the field shows a dash, which can still be clicked. + app.run("view.statusBarShow", json!({"show": "undos"})).unwrap(); + while app.session.active().is_some() { + app.session.execute("file.close", &json!({})).unwrap(); + } + assert!(status_after(&mut app, &ctx, 0.1, vec![]).iter().any(|t| t.text == "–")); +} + +/// A click on the info field opens its Show menu, which checks the readout shown and changes it. +#[test] +fn a_click_on_the_info_field_opens_the_show_menu() { + let (mut app, ctx) = status_readout_app(); + status_after(&mut app, &ctx, 1.0, vec![egui::Event::PointerGone]); + let texts = status_after(&mut app, &ctx, 0.1, vec![]); + let field = text_center(&texts, "Selection"); + status_after(&mut app, &ctx, 0.1, click_at(field)); + let texts = status_after(&mut app, &ctx, 0.1, vec![]); + let show = text_center(&texts, "Show"); + status_after(&mut app, &ctx, 0.1, vec![egui::Event::PointerMoved(show)]); + status_after(&mut app, &ctx, 0.5, vec![]); + let texts = status_after(&mut app, &ctx, 0.5, vec![]); + for label in [" Artboard Name", "✓ Current Tool", " Date and Time", " Number of Undos", " Document Color Profile"] { + assert!(texts.iter().any(|t| t.text == label), "no {label:?} in {texts:?}"); + } + let undos = text_center(&texts, " Number of Undos"); + status_after(&mut app, &ctx, 0.1, vec![egui::Event::PointerMoved(egui::pos2(undos.x, show.y)), egui::Event::PointerMoved(undos)]); + status_after(&mut app, &ctx, 0.1, click_at(undos)); + assert_eq!(app.ui.status_bar_show, super::StatusBarShow::Undos); + assert_eq!(crate::menus::checked(&app, "view.statusBarShow", &json!({"show": "undos"})), Some(true)); + assert_eq!(crate::menus::checked(&app, "view.statusBarShow", &json!({"show": "currentTool"})), Some(false)); +} + +/// `view.statusBarShow` takes only the five readouts, leaving the choice as it was otherwise, and the +/// choice is saved with the UI state, which reads a value it does not know as Current Tool. +#[test] +fn the_status_bar_show_choice_is_checked_and_saved() { + let (mut app, _ctx) = status_readout_app(); + assert_eq!(app.run("view.statusBarShow", json!({"show": "dateTime"})).unwrap(), json!("dateTime")); + for bad in [json!({}), json!({"show": "zoom"}), json!({"show": 2}), json!({"show": null}), json!({"show": "DateTime"})] { + let err = app.run("view.statusBarShow", bad.clone()).unwrap_err(); + assert!(err.contains("`show` must be one of artboardName, currentTool, dateTime, undos, colorProfile"), "{bad}: {err}"); + assert_eq!(app.ui.status_bar_show, super::StatusBarShow::DateTime, "{bad} leaves the choice"); + } + let saved = serde_json::to_value(&app.ui).unwrap(); + assert_eq!(saved["status_bar_show"], json!("dateTime")); + let read: crate::state::UiState = serde_json::from_value(saved.clone()).unwrap(); + assert_eq!(read.status_bar_show, super::StatusBarShow::DateTime); + for (stored, shown) in [ + (json!("colorProfile"), super::StatusBarShow::ColorProfile), + (json!("zoom"), super::StatusBarShow::CurrentTool), + (json!(7), super::StatusBarShow::CurrentTool), + ] { + let mut v = saved.clone(); + v["status_bar_show"] = stored; + assert_eq!(serde_json::from_value::(v).unwrap().status_bar_show, shown); + } + let mut v = saved; + v.as_object_mut().unwrap().remove("status_bar_show"); + assert_eq!( + serde_json::from_value::(v).unwrap().status_bar_show, + super::StatusBarShow::CurrentTool, + "state saved before it" + ); +} + /// Busy-job transitions preserve message placement, labels and accessibility. #[test] fn background_activity_keeps_the_status_message_origin() { diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 1ab327d3b2..85a2543a6a 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -22,6 +22,7 @@ pub mod brush_options; pub mod brush_replace_art; pub mod bullets_numbering; pub mod char_style_options; +pub mod check_spelling; pub mod color_balance; pub mod color_guide_options; mod color_picker; @@ -97,6 +98,7 @@ pub mod plugin; mod png_options; pub mod print; pub mod print_presets; +pub mod psd_import; mod psd_options; pub mod raster_effects; pub mod rearrange_artboards; @@ -417,6 +419,7 @@ registry! { PluginStopped: [safe_mode::STOPPED] => safe_mode::STOPPED_SPEC, SafeMode: [safe_mode::KIND] => safe_mode::SPEC, DxfImport: [dxf_import::KIND] => dxf_import::SPEC, + PsdImport: [psd_import::KIND] => psd_import::SPEC, RasterFormatOptions: ["tiffOptions", "bmpOptions", "tgaOptions"] => png_options::SPEC, SaveForWeb: [save_for_web::KIND] => save_for_web::SPEC, PsdOptions: ["psdOptions"] => png_options::SPEC, @@ -458,6 +461,7 @@ registry! { EditSelection: [edit_selection::KIND] => edit_selection::SPEC, EditViews: [edit_views::KIND] => edit_views::SPEC, EditCustomDictionary: [custom_dictionary::KIND] => custom_dictionary::SPEC, + CheckSpelling: [check_spelling::KIND] => check_spelling::SPEC, PerspectivePlane: [perspective_plane::KIND] => perspective_plane::SPEC, LayerOptions: [layer_options::KIND] => layer_options::SPEC, LayersPanelOptions: [layers_panel_options::KIND] => layers_panel_options::SPEC, @@ -588,6 +592,7 @@ pub fn accepts_field(d: &Dialog, field: &str) -> bool { /// Options setting set this way for several rows is sent to every row (Template also sets Lock /// and Dim Images, as its checkbox does). A DXF Options preset set this way sets its fields, as /// one picked from its menu does, and the preset it shows follows the DXF options set this way. +/// A Graph Data Column Width set this way sets every column, as Cell Style's does. pub fn set_field(d: &mut Dialog, field: String, value: Value) { if d.kind == brush_options::KIND { brush_art_options::note_set(d, &field); @@ -602,10 +607,14 @@ pub fn set_field(d: &mut Dialog, field: String, value: Value) { crate::prefs_dialog::note_set(d, &field, &value); } let dxf = (d.kind == dxf_options::KIND).then(|| field.clone()); + let graph = (d.kind == graph_data::KIND).then(|| field.clone()); d.fields.insert(field, value); if let Some(field) = dxf { dxf_options::note_set(d, &field); } + if let Some(field) = graph { + graph_data::note_set(d, &field); + } } /// The fields `ui.dialog.set` can set on `d`, sorted: those it holds other than its `__` ones, the diff --git a/crates/ui-egui/src/dialogs/char_style_options.rs b/crates/ui-egui/src/dialogs/char_style_options.rs index 8915c48216..02515a3b89 100644 --- a/crates/ui-egui/src/dialogs/char_style_options.rs +++ b/crates/ui-egui/src/dialogs/char_style_options.rs @@ -26,13 +26,40 @@ const NUMBERS: &[&str] = &["size", "leading", "kerning", "tracking"]; /// The on, off or unset checkboxes. const SWITCHES: &[&str] = &["underline", "strikethrough", "standardVerticalRoman"]; /// The attributes of Advanced Character Formats, in the order the section shows them. -const ADVANCED: &[&str] = - &["h_scale", "v_scale", "baseline_shift", "tcyUpDown", "tcyLeftRight", "rotation", "akiLeft", "akiRight", "tsume", "language"]; +const ADVANCED: &[&str] = &[ + "h_scale", + "v_scale", + "baseline_shift", + "tcyUpDown", + "tcyLeftRight", + "rotation", + "akiLeft", + "akiRight", + "tsume", + "diacriticHorizontal", + "diacriticVertical", + "language", +]; /// The number fields of Advanced Character Formats. -const ADVANCED_NUMBERS: &[&str] = &["h_scale", "v_scale", "baseline_shift", "tcyUpDown", "tcyLeftRight", "rotation", "akiLeft", "akiRight", "tsume"]; +const ADVANCED_NUMBERS: &[&str] = &[ + "h_scale", + "v_scale", + "baseline_shift", + "tcyUpDown", + "tcyLeftRight", + "rotation", + "akiLeft", + "akiRight", + "tsume", + "diacriticHorizontal", + "diacriticVertical", +]; /// The Insert Aki Left and Right fields, which take the Character panel's presets and stop at /// [`vectorcraft_doc::text::MAX_AKI`]. const AKI: [&str; 2] = ["akiLeft", "akiRight"]; +/// The Adjust Horizontal and Vertical Diacritic Position fields, which take the Character panel's +/// presets and stop at [`vectorcraft_doc::text::MAX_DIACRITIC_POSITION`] either way. +const DIACRITIC: [&str; 2] = ["diacriticHorizontal", "diacriticVertical"]; /// The attributes of Character Color. const COLOR: &[&str] = &["fill", "stroke", "stroke_width", "overprint_fill", "overprint_stroke"]; /// The fields of Character Color: the fill and stroke paints, their tints in percent, the stroke @@ -103,6 +130,8 @@ pub(super) const SPEC: DialogSpec = DialogSpec { "akiLeft", "akiRight", "tsume", + "diacriticHorizontal", + "diacriticVertical", "language", "fill", "fill_tint", @@ -295,6 +324,8 @@ fn optional_number(d: &Dialog, key: &str) -> Result, String> { "akiLeft" => tl!("Insert Aki Left"), "akiRight" => tl!("Insert Aki Right"), "tsume" => tl!("Tsume"), + "diacriticHorizontal" => tl!("Adjust Horizontal Diacritic Position"), + "diacriticVertical" => tl!("Adjust Vertical Diacritic Position"), "fill_tint" => tl!("Fill Tint"), "stroke_tint" => tl!("Stroke Tint"), "stroke_width" => tl!("Weight"), @@ -344,6 +375,9 @@ fn optional_number(d: &Dialog, key: &str) -> Result, String> { let n = if AKI.contains(&key) { n.clamp(0.0, vectorcraft_doc::text::MAX_AKI) } else { n }; // Tsume stops at 0% and 100% the same way. let n = if key == "tsume" { n.clamp(0.0, vectorcraft_doc::text::MAX_TSUME) } else { n }; + // The diacritic positions stop at the largest value the style takes either way. + let max = vectorcraft_doc::text::MAX_DIACRITIC_POSITION; + let n = if DIACRITIC.contains(&key) { n.clamp(-max, max) } else { n }; Ok(Some(json!(n))) } } @@ -622,7 +656,7 @@ pub(crate) fn reset_basic(d: &mut Dialog) { } } -/// Reset Panel in Advanced Character Formats: its ten attributes become unset. +/// Reset Panel in Advanced Character Formats: its twelve attributes become unset. pub(crate) fn reset_advanced(d: &mut Dialog) { d.fields.insert("__resetAdvanced".into(), json!(true)); for key in ADVANCED_NUMBERS { @@ -777,8 +811,9 @@ pub(crate) fn basic_body(ui: &mut egui::Ui, d: &mut Dialog) { } /// Advanced Character Formats: Horizontal Scale, Vertical Scale, Baseline Shift, the Tate-chu-yoko -/// Up/Down and Left/Right, Character Rotation, Insert Aki Left and Right and Tsume (with the -/// Character panel's presets) and Language, each empty (unset) or set. +/// Up/Down and Left/Right, Character Rotation, Insert Aki Left and Right, Tsume and the Adjust +/// Horizontal and Vertical Diacritic Positions (with the Character panel's presets) and Language, +/// each empty (unset) or set. pub(crate) fn advanced_body(ui: &mut egui::Ui, d: &mut Dialog) { egui::Grid::new("character-style-advanced").num_columns(2).spacing([18.0, 8.0]).show(ui, |ui| { for (key, caption, unit) in [ @@ -820,6 +855,18 @@ pub(crate) fn advanced_body(ui: &mut egui::Ui, d: &mut Dialog) { ui.label("%"); }); ui.end_row(); + let presets: Vec = crate::panels::character::DIACRITIC_PRESETS.iter().map(f64::to_string).collect(); + let presets: Vec<&str> = presets.iter().map(String::as_str).collect(); + for (key, caption) in + [("diacriticHorizontal", tl!("Adjust Horizontal Diacritic Position")), ("diacriticVertical", tl!("Adjust Vertical Diacritic Position"))] + { + let row = ui.label(caption); + let value = if d.fields.get(key).is_none_or(Value::is_null) { String::new() } else { d.str(key) }; + if let Some(v) = ui.label_inputs_by(row.id, |ui| crate::widgets::text_presets(ui, (KIND, key), &value, &presets, 160.0)) { + d.fields.insert(key.into(), json!(v)); + } + ui.end_row(); + } let row = ui.label(tl!("Language:")); let names: Vec<&str> = std::iter::once(" ").chain(vectorcraft_doc::setup::LANGUAGES.iter().map(|(name, _, _)| *name)).collect(); let current = d.fields.get("language").and_then(Value::as_str).unwrap_or("").to_string(); @@ -1882,6 +1929,55 @@ mod tests { assert!(t.runs.iter().all(|r| (r.style.aki_left, r.style.aki_right) == (250.0, 1000.0))); } + /// The Adjust Diacritic Positions in Advanced Character Formats: empty is unset, a typed value + /// stops at -1000 and 1000, Reset Panel unsets them, and the fields are drawn and commit to the + /// style and the text set in it. + #[test] + fn diacritic_position_fields_show_set_reset_and_commit() { + let d = dialog_for(json!({"diacriticHorizontal": -250.0, "size": 12.0})); + assert_eq!((d.fields["diacriticHorizontal"].clone(), d.fields["diacriticVertical"].clone()), (json!(-250.0), json!(""))); + assert_eq!(edited_attrs(&d).unwrap(), attrs(json!({"diacriticHorizontal": -250.0, "size": 12.0}))); + let mut d = dialog_for(json!({"diacriticHorizontal": -250.0})); + d.fields.insert("diacriticHorizontal".into(), json!("")); + for (typed, kept) in [("0", 0.0), ("150", 150.0), ("5000", 1000.0), ("-5000", -1000.0)] { + d.fields.insert("diacriticVertical".into(), json!(typed)); + assert_eq!(edited_attrs(&d).unwrap(), attrs(json!({"diacriticVertical": kept})), "{typed}"); + } + d.fields.insert("diacriticHorizontal".into(), json!("left")); + assert_eq!(edited_attrs(&d).unwrap_err(), "Adjust Horizontal Diacritic Position must be a number"); + let mut d = dialog_for(json!({"diacriticHorizontal": 100.0, "diacriticVertical": 200.0, "size": 12.0})); + d.fields.insert("section".into(), json!("advanced")); + reset_section(&mut d); + assert_eq!(edited_attrs(&d).unwrap(), attrs(json!({"size": 12.0}))); + + let mut app = app(); + app.run("charStyle.new", json!({"name": "Body", "attrs": {"size": 24.0}})).unwrap(); + let id = app.run("text.create", json!({"x": 10, "y": 40, "text": "بَب"})).unwrap()["id"].as_u64().unwrap(); + app.run("charStyle.apply", json!({"name": "Body", "id": id})).unwrap(); + open(&mut app, "Body").unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 900.0)); + let mut d = app.ui.dialog.clone().unwrap(); + let input = egui::RawInput { screen_rect: Some(screen), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| advanced_body(ui, &mut d)); + let texts = texts_of(&out); + out.textures_delta.clear(); + for label in ["Adjust Horizontal Diacritic Position", "Adjust Vertical Diacritic Position"] { + assert!(texts.iter().any(|(text, _)| text == label), "{label} is drawn: {texts:?}"); + } + { + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("diacriticHorizontal".into(), json!("-120")); + d.fields.insert("diacriticVertical".into(), json!("3000")); + } + super::super::confirm(&mut app).unwrap(); + let state = app.session.doc().unwrap(); + assert_eq!(state.doc.char_styles[0].attrs, attrs(json!({"size": 24.0, "diacriticHorizontal": -120.0, "diacriticVertical": 1000.0}))); + let vectorcraft_doc::NodeKind::Text(t) = &state.doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind else { panic!("text") }; + assert!(t.runs.iter().all(|r| (r.style.diacritic_horizontal, r.style.diacritic_vertical) == (-120.0, 1000.0))); + } + /// Tsume in Advanced Character Formats: empty is unset, an explicit 0 stays set, a typed value /// stops at 0 and 100, Reset Panel unsets it, and the field is drawn and commits to the style /// and the text set in it. diff --git a/crates/ui-egui/src/dialogs/check_spelling.rs b/crates/ui-egui/src/dialogs/check_spelling.rs new file mode 100644 index 0000000000..5f0bb8693e --- /dev/null +++ b/crates/ui-egui/src/dialogs/check_spelling.rs @@ -0,0 +1,1101 @@ +//! Edit › Spelling › Check Spelling…: walk through unknown words in the selection or the whole +//! document, displaying the unrecognized word in its sentence context, with suggestions, and +//! Ignore, Ignore All, Change, Change All, Add to Dictionary, and Done / Cancel. +//! +//! Fields: +//! - `not_in_dictionary`: the current unrecognized word +//! - `context`: sentence context containing the unrecognized word +//! - `context_before`, `context_word`, `context_after`: parts of the sentence context +//! - `suggestions`: alternative words suggested by the dictionary +//! - `selected_suggestion`: the suggestion currently selected +//! - `change_to`: the replacement word (from suggestions or typed) +//! - `node_id`, `start`, `end`, `lang`: location of the current misspelling +//! - `ids`: object IDs checked (None: entire document) +//! - `skipped`: list of `[node_id, start]` skipped by Ignore +//! - `done`: whether spell checking has finished (or no unrecognized words found) + +use std::collections::BTreeMap; +use std::ops::Range; + +use serde_json::{Value, json}; + +use super::{DialogAction, DialogResult, DialogSpec}; +use crate::state::Dialog; +use crate::theme::Tokens; +use crate::{VectorcraftApp, widgets}; + +/// The dialog kind of Check Spelling. +pub const KIND: &str = "checkSpelling"; + +/// The command its menu item runs. +pub const COMMAND: &str = "ui.checkSpelling"; + +pub(super) const SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("Check Spelling").into(), + body_with_actions: Some(body), + confirm, + ok: None, + min_width: 480.0, + max_width: Some(560.0), + ..DialogSpec::FORM +}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Action { + Ignore, + IgnoreAll, + Change, + ChangeAll, + AddToDictionary, + Done, + Cancel, +} + +/// Open Check Spelling on the active document's type. +pub fn open(app: &mut VectorcraftApp) -> Result { + if app.session.active().is_none() { + return Err("no document".into()); + } + let doc_uid = app.session.doc().map_err(|e| e.to_string())?.uid; + let (ids, remaining_ids): (Option>, Vec) = { + let st = app.session.doc().map_err(|e| e.to_string())?; + let selected = &st.selection.objects; + if !selected.is_empty() { + let selected_ids: Vec = selected.iter().map(|n| n.0).collect(); + (Some(selected_ids.clone()), selected_ids) + } else { + let mut all_ordered = Vec::new(); + st.doc.walk(|n| { + if matches!(n.kind, vectorcraft_doc::NodeKind::Text(_)) && st.doc.is_editable(n.id) { + all_ordered.push(n.id.0); + } + }); + (None, all_ordered) + } + }; + let mut d = Dialog::new( + KIND, + json!({ + "doc_uid": doc_uid, + "ids": ids, + "remaining_ids": remaining_ids, + "skipped": [], + "not_in_dictionary": "", + "context": "", + "context_before": "", + "context_word": "", + "context_after": "", + "change_to": "", + "suggestions": [], + "selected_suggestion": null, + "node_id": null, + "start": null, + "end": null, + "lang": null, + "done": false, + }), + ); + advance(app, &mut d)?; + app.ui.dialog = Some(d); + Ok(Value::Null) +} + +fn get_skipped(d: &Dialog) -> Vec<(u64, u64)> { + d.fields + .get("skipped") + .and_then(Value::as_array) + .map(|arr| { + arr.iter() + .filter_map(|pair| { + let a = pair.as_array()?; + if a.len() == 2 { Some((a[0].as_u64()?, a[1].as_u64()?)) } else { None } + }) + .collect() + }) + .unwrap_or_default() +} + +fn set_skipped(d: &mut Dialog, skipped: &[(u64, u64)]) { + let arr: Vec = skipped.iter().map(|&(id, start)| json!([id, start])).collect(); + d.fields.insert("skipped".into(), json!(arr)); +} + +/// Extracts the sentence containing `range` within `text`, returning (before, word, after). +pub fn extract_sentence_context(text: &str, range: Range) -> (String, String, String) { + let empty = (String::new(), String::new(), String::new()); + if range.start > range.end { + return empty; + } + let Some(word_slice) = text.get(range.clone()) else { + return empty; + }; + let word = word_slice.to_string(); + + let Some(before_slice) = text.get(..range.start) else { + return empty; + }; + let nl_start = before_slice.rfind('\n').map(|idx| idx + 1); + let mut punct_start = None; + for (idx, ch) in before_slice.char_indices() { + if (ch == '.' || ch == '!' || ch == '?') && before_slice.get(idx + ch.len_utf8()..).is_some_and(|s| s.starts_with(char::is_whitespace)) { + punct_start = Some(idx + ch.len_utf8()); + } + } + let start_idx = match (nl_start, punct_start) { + (Some(nl), Some(p)) => nl.max(p), + (Some(nl), None) => nl, + (None, Some(p)) => p, + (None, None) => 0, + }; + + let Some(after_slice) = text.get(range.end..) else { + return empty; + }; + let nl_end = after_slice.find('\n'); + let mut punct_end = None; + for (idx, ch) in after_slice.char_indices() { + if ch == '.' || ch == '!' || ch == '?' { + let next_idx = idx + ch.len_utf8(); + if next_idx >= after_slice.len() || after_slice.get(next_idx..).is_some_and(|s| s.starts_with(char::is_whitespace)) { + punct_end = Some(next_idx); + break; + } + } + } + let end_offset = match (nl_end, punct_end) { + (Some(nl), Some(p)) => nl.min(p), + (Some(nl), None) => nl, + (None, Some(p)) => p, + (None, None) => after_slice.len(), + }; + + let mut before = text.get(start_idx..range.start).unwrap_or("").trim_start().to_string(); + let mut after = after_slice.get(..end_offset).unwrap_or("").trim_end().to_string(); + + const MAX_SIDE: usize = 120; + if before.len() > MAX_SIDE { + let target = before.len() - MAX_SIDE; + let split_idx = before.char_indices().map(|(idx, _)| idx).find(|&idx| idx >= target).unwrap_or(before.len()); + let suffix = before.get(split_idx..).unwrap_or(""); + before = match suffix.find(' ') { + Some(space) => format!("…{}", suffix.get(space..).unwrap_or("")), + None => format!("…{suffix}"), + }; + } + if after.len() > MAX_SIDE { + let split_idx = after.char_indices().map(|(idx, _)| idx).take_while(|&idx| idx <= MAX_SIDE).last().unwrap_or(0); + let prefix = after.get(..split_idx).unwrap_or(""); + after = match prefix.rfind(' ') { + Some(space) => format!("{}…", prefix.get(..space).unwrap_or("")), + None => format!("{prefix}…"), + }; + } + + (before, word, after) +} + +fn set_done(d: &mut Dialog) { + d.fields.insert("done".into(), json!(true)); + d.fields.insert("not_in_dictionary".into(), json!("")); + d.fields.insert("context".into(), json!(tl!("The spell check is complete."))); + d.fields.insert("context_before".into(), json!("")); + d.fields.insert("context_word".into(), json!("")); + d.fields.insert("context_after".into(), json!("")); + d.fields.insert("suggestions".into(), json!([])); + d.fields.insert("selected_suggestion".into(), Value::Null); + d.fields.insert("change_to".into(), json!("")); + d.fields.insert("node_id".into(), Value::Null); + d.fields.insert("start".into(), Value::Null); + d.fields.insert("end".into(), Value::Null); + d.fields.insert("lang".into(), Value::Null); +} + +/// Advance to the next unrecognized word or complete the spell check. +pub fn advance(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { + let mut remaining_ids: Vec = + d.fields.get("remaining_ids").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_u64).collect()).unwrap_or_default(); + + if remaining_ids.is_empty() && d.fields.get("ids").is_none_or(Value::is_null) { + let st = app.session.doc().map_err(|e| e.to_string())?; + st.doc.walk(|n| { + if matches!(n.kind, vectorcraft_doc::NodeKind::Text(_)) && st.doc.is_editable(n.id) { + remaining_ids.push(n.id.0); + } + }); + d.fields.insert("remaining_ids".into(), json!(remaining_ids)); + } + + let skipped = get_skipped(d); + + loop { + if remaining_ids.is_empty() { + set_done(d); + return Ok(()); + } + + let check_res = app.run("text.spelling.check", json!({ "ids": remaining_ids })).map_err(|e| e.to_string())?; + let words = check_res.get("words").and_then(Value::as_array).cloned().unwrap_or_default(); + let more = check_res.get("more").and_then(Value::as_bool).unwrap_or(false); + + let next_word = words + .iter() + .find(|w| { + let id = w.get("id").and_then(Value::as_u64).unwrap_or(0); + let start = w.get("start").and_then(Value::as_u64).unwrap_or(0); + !skipped.contains(&(id, start)) + }) + .cloned(); + + if let Some(w) = next_word { + let id = w["id"].as_u64().unwrap_or(0); + let start = w["start"].as_u64().unwrap_or(0) as usize; + let end = w["end"].as_u64().unwrap_or(0) as usize; + let word = w["word"].as_str().unwrap_or("").to_string(); + let lang = w["lang"].as_str().unwrap_or("en").to_string(); + + let (before, target, after) = { + let st = app.session.doc().map_err(|e| e.to_string())?; + if let Some(vectorcraft_doc::NodeKind::Text(t)) = st.doc.node(vectorcraft_doc::NodeId(id)).map(|n| &n.kind) { + extract_sentence_context(&t.plain_text(), start..end) + } else { + (String::new(), word.clone(), String::new()) + } + }; + + let sugg_res = app.run("text.spelling.suggest", json!({ "word": word, "lang": lang, "max": 10 })).map_err(|e| e.to_string())?; + let suggestions: Vec = sugg_res + .get("suggestions") + .and_then(Value::as_array) + .map(|a| a.iter().filter_map(Value::as_str).map(String::from).collect()) + .unwrap_or_default(); + + let change_to = suggestions.first().cloned().unwrap_or_else(|| word.clone()); + let full_context = format!("{before}{target}{after}"); + + d.fields.insert("not_in_dictionary".into(), json!(word)); + d.fields.insert("context".into(), json!(full_context)); + d.fields.insert("context_before".into(), json!(before)); + d.fields.insert("context_word".into(), json!(target)); + d.fields.insert("context_after".into(), json!(after)); + d.fields.insert("suggestions".into(), json!(suggestions)); + d.fields.insert("selected_suggestion".into(), json!(suggestions.first().cloned())); + d.fields.insert("change_to".into(), json!(change_to)); + d.fields.insert("node_id".into(), json!(id)); + d.fields.insert("start".into(), json!(start)); + d.fields.insert("end".into(), json!(end)); + d.fields.insert("lang".into(), json!(lang)); + d.fields.insert("done".into(), json!(false)); + return Ok(()); + } + + if more && !words.is_empty() { + let last_id = words.last().and_then(|w| w.get("id")).and_then(Value::as_u64).unwrap_or(0); + if let Some(pos) = remaining_ids.iter().position(|&id| id == last_id) + && pos > 0 + { + remaining_ids.drain(0..pos); + d.fields.insert("remaining_ids".into(), json!(remaining_ids)); + continue; + } + if remaining_ids.len() > 1 { + remaining_ids.remove(0); + d.fields.insert("remaining_ids".into(), json!(remaining_ids)); + continue; + } + } + + set_done(d); + return Ok(()); + } +} + +fn check_doc_uid(app: &VectorcraftApp, d: &Dialog) -> Result<(), String> { + let doc_uid = d.fields.get("doc_uid").and_then(Value::as_u64); + let active_uid = app.session.active().map(|st| st.uid); + if doc_uid.is_some() && doc_uid != active_uid { + return Err("the document was switched".into()); + } + Ok(()) +} + +fn ignore(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { + check_doc_uid(app, d)?; + if d.bool("done") { + return Ok(()); + } + let id = d.fields.get("node_id").and_then(Value::as_u64).unwrap_or(0); + let start = d.fields.get("start").and_then(Value::as_u64).unwrap_or(0); + let mut skipped = get_skipped(d); + skipped.push((id, start)); + set_skipped(d, &skipped); + advance(app, d) +} + +fn ignore_all(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { + check_doc_uid(app, d)?; + if d.bool("done") { + return Ok(()); + } + let word = d.str("not_in_dictionary"); + if !word.is_empty() { + app.run("text.spelling.ignoreAll", json!({ "word": word })).map_err(|e| e.to_string())?; + } + advance(app, d) +} + +fn change(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { + check_doc_uid(app, d)?; + if d.bool("done") { + return Ok(()); + } + let id = d.fields.get("node_id").and_then(Value::as_u64).unwrap_or(0); + let start = d.fields.get("start").and_then(Value::as_u64).unwrap_or(0) as usize; + let end = d.fields.get("end").and_then(Value::as_u64).unwrap_or(0) as usize; + let expected_word = d.str("not_in_dictionary"); + let change_to = d.str("change_to"); + if !change_to.trim().is_empty() && id > 0 { + let text_matches = { + let st = app.session.doc().map_err(|e| e.to_string())?; + if let Some(vectorcraft_doc::NodeKind::Text(t)) = st.doc.node(vectorcraft_doc::NodeId(id)).map(|n| &n.kind) { + let plain = t.plain_text(); + plain.get(start..end).map(|s| s == expected_word).unwrap_or(false) + } else { + false + } + }; + + if text_matches { + app.run("text.editRange", json!({ "id": id, "start": start, "end": end, "insert": change_to })).map_err(|e| e.to_string())?; + } else { + return advance(app, d); + } + } + advance(app, d) +} + +fn change_all(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { + check_doc_uid(app, d)?; + if d.bool("done") { + return Ok(()); + } + let word = d.str("not_in_dictionary"); + let change_to = d.str("change_to"); + if word.is_empty() || change_to.trim().is_empty() { + return advance(app, d); + } + let initial_ids = d.fields.get("ids").cloned().unwrap_or(Value::Null); + let skipped = get_skipped(d); + + let mut undo_group_started = false; + let mut execute_changes = || -> Result<(), String> { + let mut replaced_spans: Vec<(u64, usize, usize)> = Vec::new(); + let mut all_commands = Vec::new(); + loop { + let check_res = app.run("text.spelling.check", json!({ "ids": initial_ids })).map_err(|e| e.to_string())?; + let words = check_res.get("words").and_then(Value::as_array).cloned().unwrap_or_default(); + let more = check_res.get("more").and_then(Value::as_bool).unwrap_or(false); + + let mut by_node: BTreeMap> = BTreeMap::new(); + let mut new_edits = 0; + for w in &words { + let id = w.get("id").and_then(Value::as_u64).unwrap_or(0); + let start = w.get("start").and_then(Value::as_u64).unwrap_or(0) as usize; + let end = w.get("end").and_then(Value::as_u64).unwrap_or(0) as usize; + let w_str = w.get("word").and_then(Value::as_str).unwrap_or(""); + if skipped.contains(&(id, start as u64)) { + continue; + } + if replaced_spans.iter().any(|&(r_id, r_start, r_end)| r_id == id && start >= r_start && start < r_end) { + continue; + } + if w_str.eq_ignore_ascii_case(&word) { + by_node.entry(id).or_default().push((start, end)); + new_edits += 1; + } + } + + if new_edits == 0 { + break; + } + + let new_len = change_to.len() as isize; + for (r_id, r_start, r_end) in &mut replaced_spans { + if let Some(ranges) = by_node.get(r_id) { + let delta: isize = ranges.iter().filter(|(_, end)| *end <= *r_start).map(|(start, end)| new_len - (*end - *start) as isize).sum(); + *r_start = (*r_start as isize + delta).max(0) as usize; + *r_end = (*r_end as isize + delta).max(0) as usize; + } + } + for (&id, ranges) in &by_node { + for &(start, _) in ranges { + let delta: isize = ranges + .iter() + .filter(|(_, other_end)| *other_end <= start) + .map(|(other_start, other_end)| new_len - (*other_end - *other_start) as isize) + .sum(); + let post_start = (start as isize + delta).max(0) as usize; + let post_end = post_start + change_to.len(); + replaced_spans.push((id, post_start, post_end)); + } + } + + let mut batch_commands = Vec::new(); + for (id, mut ranges) in by_node { + ranges.sort_by_key(|a| std::cmp::Reverse(a.0)); + for (start, end) in ranges { + batch_commands.push(json!({ + "command": "text.editRange", + "params": { + "id": id, + "start": start, + "end": end, + "insert": change_to, + } + })); + } + } + + if !batch_commands.is_empty() { + if batch_commands.len() == 1 && !more && all_commands.is_empty() && !undo_group_started { + let cmd = &batch_commands[0]; + app.run(cmd["command"].as_str().unwrap_or("text.editRange"), cmd["params"].clone()).map_err(|e| e.to_string())?; + break; + } else if more { + if !undo_group_started { + app.run("edit.undoGroup.begin", json!({ "label": "Change All" })).map_err(|e| e.to_string())?; + undo_group_started = true; + } + app.run("command.batch", json!({ "label": "Change All", "commands": batch_commands })).map_err(|e| e.to_string())?; + continue; + } else { + all_commands.extend(batch_commands); + break; + } + } + + break; + } + + if !all_commands.is_empty() { + if all_commands.len() == 1 && !undo_group_started { + let cmd = &all_commands[0]; + app.run(cmd["command"].as_str().unwrap_or("text.editRange"), cmd["params"].clone()).map_err(|e| e.to_string())?; + } else { + app.run("command.batch", json!({ "label": "Change All", "commands": all_commands })).map_err(|e| e.to_string())?; + } + } + Ok(()) + }; + + let res = execute_changes(); + if undo_group_started { + let cancel = res.is_err(); + let _ = app.run("edit.undoGroup.end", json!({ "cancel": cancel })); + } + res?; + advance(app, d) +} + +fn add_to_dictionary(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { + check_doc_uid(app, d)?; + if d.bool("done") { + return Ok(()); + } + let word = d.str("not_in_dictionary"); + if !word.is_empty() { + app.run("text.spelling.addWord", json!({ "word": word })).map_err(|e| e.to_string())?; + } + advance(app, d) +} + +fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAction { + let doc_uid = d.fields.get("doc_uid").and_then(Value::as_u64); + let active_uid = app.session.active().map(|st| st.uid); + if doc_uid.is_some() && doc_uid != active_uid { + return DialogAction::Cancel; + } + + if let Some(act) = d.fields.remove("action").and_then(|v| v.as_str().map(String::from)) { + let res = match act.as_str() { + "ignore" => ignore(app, d), + "ignoreAll" => ignore_all(app, d), + "change" => change(app, d), + "changeAll" => change_all(app, d), + "addToDictionary" => add_to_dictionary(app, d), + "done" | "cancel" => return DialogAction::Cancel, + _ => Ok(()), + }; + if let Err(e) = res { + app.status(&e); + d.fields.insert("error".into(), json!(e)); + } else { + d.fields.remove("error"); + } + } + + let mut action_to_run = None; + let done = d.bool("done"); + let before = d.str("context_before"); + let target = d.str("context_word"); + let after = d.str("context_after"); + let mut change_to = d.str("change_to"); + let suggestions: Vec = d + .fields + .get("suggestions") + .and_then(Value::as_array) + .map(|a| a.iter().filter_map(Value::as_str).map(String::from).collect()) + .unwrap_or_default(); + + let can_change = !done && !change_to.trim().is_empty(); + + if crate::shortcuts::pressed_anew(ui.ctx(), egui::Key::Enter) + || ui.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Key { key: egui::Key::Enter, pressed: true, repeat: false, .. }))) + { + if can_change { + action_to_run = Some(Action::Change); + } else if done { + return DialogAction::Cancel; + } + } + if ui.input(|i| i.key_pressed(egui::Key::Escape)) { + return DialogAction::Cancel; + } + + let action_col_width = 110.0; + let col_spacing = 16.0; + let text_col_width = (ui.available_width() - action_col_width - col_spacing).clamp(200.0, 320.0); + + ui.horizontal_top(|ui| { + ui.vertical(|ui| { + ui.set_width(text_col_width); + if done { + ui.add_space(20.0); + widgets::dim_label(ui, tl!("The spell check is complete.")); + ui.add_space(80.0); + } else { + widgets::dim_label(ui, tl!("Not in Dictionary:")); + ui.group(|ui| { + ui.set_width(text_col_width); + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing.x = 0.0; + if !before.is_empty() { + ui.label(&before); + } + let t = Tokens::get(ui.ctx()); + ui.add(egui::Label::new(egui::RichText::new(&target).color(t.accent).strong().underline())); + if !after.is_empty() { + ui.label(&after); + } + }); + }); + + ui.add_space(8.0); + widgets::dim_label(ui, tl!("Change to:")); + let field_id = ui.scope_id().with(("dlg-text", "change_to")); + widgets::take_dialog_focus(ui, field_id, &change_to); + if ui.add(egui::TextEdit::singleline(&mut change_to).id(field_id).desired_width(text_col_width)).changed() { + d.fields.insert("change_to".into(), json!(change_to)); + } + + ui.add_space(8.0); + widgets::dim_label(ui, tl!("Suggestions:")); + widgets::list_box(ui, |ui| { + ui.set_width(text_col_width); + let row = ui.spacing().interact_size.y; + egui::ScrollArea::vertical().id_salt("check-spelling-suggestions").min_scrolled_height(140.0).max_height(140.0).show_rows( + ui, + row, + suggestions.len(), + |ui, range| { + ui.set_width(ui.available_width()); + for s in suggestions.get(range).unwrap_or_default() { + let is_selected = change_to == *s; + if ui.selectable_label(is_selected, s.as_str()).clicked() { + d.fields.insert("change_to".into(), json!(s)); + d.fields.insert("selected_suggestion".into(), json!(s)); + } + } + }, + ); + }); + } + }); + + ui.add_space(col_spacing); + + ui.vertical(|ui| { + let w = action_col_width; + if ui.add_enabled_ui(!done, |ui| widgets::flat_button_fit(ui, tl!("Ignore"), w).clicked()).inner { + action_to_run = Some(Action::Ignore); + } + ui.add_space(6.0); + if ui.add_enabled_ui(!done, |ui| widgets::flat_button_fit(ui, tl!("Ignore All"), w).clicked()).inner { + action_to_run = Some(Action::IgnoreAll); + } + ui.add_space(6.0); + if ui.add_enabled_ui(can_change, |ui| widgets::flat_button_fit(ui, tl!("Change"), w).clicked()).inner { + action_to_run = Some(Action::Change); + } + ui.add_space(6.0); + if ui.add_enabled_ui(can_change, |ui| widgets::flat_button_fit(ui, tl!("Change All"), w).clicked()).inner { + action_to_run = Some(Action::ChangeAll); + } + ui.add_space(6.0); + if ui.add_enabled_ui(!done, |ui| widgets::flat_button_fit(ui, tl!("Add to Dictionary"), w).clicked()).inner { + action_to_run = Some(Action::AddToDictionary); + } + ui.add_space(16.0); + if widgets::flat_button_fit(ui, tl!("Done"), w).clicked() { + action_to_run = Some(Action::Done); + } + ui.add_space(6.0); + if widgets::flat_button_fit(ui, tl!("Cancel"), w).clicked() { + action_to_run = Some(Action::Cancel); + } + }); + }); + + if let Some(act) = action_to_run { + let res = match act { + Action::Ignore => ignore(app, d), + Action::IgnoreAll => ignore_all(app, d), + Action::Change => change(app, d), + Action::ChangeAll => change_all(app, d), + Action::AddToDictionary => add_to_dictionary(app, d), + Action::Done | Action::Cancel => return DialogAction::Cancel, + }; + if let Err(e) = res { + app.status(&e); + d.fields.insert("error".into(), json!(e)); + } else { + d.fields.remove("error"); + } + } + + DialogAction::None +} + +fn confirm(app: &mut VectorcraftApp, _: &Dialog) -> DialogResult { + app.ui.dialog = None; + Ok(Value::Null) +} + +#[cfg(test)] +mod tests { + use egui::{Event, PointerButton, Pos2, Rect, vec2}; + use serde_json::json; + + use crate::VectorcraftApp; + + const WORD_A: &str = "zqvspella"; + const WORD_B: &str = "zqvspellb"; + const WORD_C: &str = "zqvspellc"; + + fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + app + } + + fn text(app: &mut VectorcraftApp, y: f64, text: &str) -> u64 { + app.run("text.create", json!({"x": 10, "y": y, "text": text})).unwrap()["id"].as_u64().unwrap() + } + + fn forget(app: &mut VectorcraftApp, words: &[&str]) { + for w in words { + let _ = app.run("text.spelling.removeWord", json!({ "word": w })); + } + } + + fn context() -> egui::Context { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + ctx + } + + fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> Vec<(String, Rect)> { + let time = ctx.input(|i| i.time) + 0.25; + let screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))); + let raw = egui::RawInput { screen_rect, events, time: Some(time), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| crate::dialogs::show(app, ui.ctx())); + out.textures_delta.clear(); + fn walk(s: &egui::Shape, v: &mut Vec<(String, Rect)>) { + match s { + egui::Shape::Text(t) => v.push((t.galley.text().to_string(), Rect::from_min_size(t.pos, t.galley.size()))), + egui::Shape::Vec(s) => s.iter().for_each(|s| walk(s, v)), + _ => {} + } + } + let mut v = vec![]; + out.shapes.iter().for_each(|c| walk(&c.shape, &mut v)); + v + } + + fn click(app: &mut VectorcraftApp, ctx: &egui::Context, label: &str) -> Vec<(String, Rect)> { + frame(app, ctx, vec![]); + let texts = frame(app, ctx, vec![]); + let at = texts.iter().find(|(t, _)| t == label).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("no `{label}` in {texts:?}")); + let press = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(app, ctx, vec![Event::PointerMoved(at)]); + frame(app, ctx, vec![press(true)]); + frame(app, ctx, vec![press(false)]); + frame(app, ctx, vec![]) + } + + fn key_press(app: &mut VectorcraftApp, ctx: &egui::Context, key: egui::Key) { + let down = Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + frame(app, ctx, vec![down]); + let up = Event::Key { key, physical_key: None, pressed: false, repeat: false, modifiers: egui::Modifiers::NONE }; + frame(app, ctx, vec![up]); + } + + #[test] + fn test_extract_sentence_context() { + let text = "First sentence. Here is teh sample typo! Third sentence."; + let (before, word, after) = super::extract_sentence_context(text, 24..27); + assert_eq!(word, "teh"); + assert_eq!(before, "Here is "); + assert_eq!(after, " sample typo!"); + + let single = "Hello world"; + let (b, w, a) = super::extract_sentence_context(single, 6..11); + assert_eq!(w, "world"); + assert_eq!(b, "Hello "); + assert_eq!(a, ""); + + #[allow(clippy::reversed_empty_ranges)] + let (b_inv, w_inv, a_inv) = super::extract_sentence_context(single, 10..5); + assert!(w_inv.is_empty() && b_inv.is_empty() && a_inv.is_empty()); + + // Multibyte UTF-8 regression test (e.g. 61 copies of 'é', which is 122 bytes) + let after_multibyte = format!("word {}", "é".repeat(70)); + let (b_mb, w_mb, a_mb) = super::extract_sentence_context(&after_multibyte, 0..4); + assert_eq!(w_mb, "word"); + assert_eq!(b_mb, ""); + assert!(a_mb.ends_with('…')); + + let before_multibyte = format!("{} typo end.", "é".repeat(70)); + let typo_start = "é".repeat(70).len() + 1; + let typo_end = typo_start + 4; + let (b_mb2, w_mb2, a_mb2) = super::extract_sentence_context(&before_multibyte, typo_start..typo_end); + assert_eq!(w_mb2, "typo"); + assert!(b_mb2.starts_with('…')); + assert_eq!(a_mb2, " end."); + + // Stale / out-of-bounds or non-char boundary offsets never panic + let (b_oob, w_oob, a_oob) = super::extract_sentence_context(single, 5..50); + assert!(w_oob.is_empty() && b_oob.is_empty() && a_oob.is_empty()); + + let utf8_sample = "Héllo world"; + let (b_mid, w_mid, a_mid) = super::extract_sentence_context(utf8_sample, 2..4); + assert!(w_mid.is_empty() && b_mid.is_empty() && a_mid.is_empty()); + } + + #[test] + fn menu_opens_check_spelling_dialog() { + let mut app = app(); + text(&mut app, 50.0, &format!("Hello {WORD_A} world")); + + let e = crate::menus::menu_entries(&app).into_iter().find(|e| e.label == "Check Spelling…").expect("in Edit menu"); + assert_eq!(e.command.as_deref(), Some(super::COMMAND)); + assert!(e.enabled); + + crate::menus::invoke(&mut app, super::COMMAND, json!({})); + let d = app.ui.dialog.as_ref().expect("Check Spelling dialog opens"); + assert_eq!(d.kind, super::KIND); + assert_eq!(d.str("not_in_dictionary"), WORD_A); + assert!(d.str("context").contains(WORD_A)); + assert!(!d.bool("done")); + } + + #[test] + fn check_spelling_word_replacement_and_undo_redo() { + let mut app = app(); + let id = text(&mut app, 50.0, &format!("Prefix {WORD_A} suffix")); + + super::open(&mut app).unwrap(); + let ctx = context(); + + // Change replacement word + app.ui.dialog.as_mut().unwrap().fields.insert("change_to".into(), json!("replacement")); + click(&mut app, &ctx, "Change"); + + // Verify word replacement in the document + let plain = { + let st = app.session.doc().unwrap(); + match &st.doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind { + vectorcraft_doc::NodeKind::Text(t) => t.plain_text(), + _ => panic!("not text"), + } + }; + assert_eq!(plain, "Prefix replacement suffix"); + + // Verify one-step undo brings the original word back + app.run("edit.undo", json!({})).unwrap(); + let plain_undone = { + let st = app.session.doc().unwrap(); + match &st.doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind { + vectorcraft_doc::NodeKind::Text(t) => t.plain_text(), + _ => panic!("not text"), + } + }; + assert_eq!(plain_undone, format!("Prefix {WORD_A} suffix")); + + // Verify redo re-applies the replacement + app.run("edit.redo", json!({})).unwrap(); + let plain_redone = { + let st = app.session.doc().unwrap(); + match &st.doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind { + vectorcraft_doc::NodeKind::Text(t) => t.plain_text(), + _ => panic!("not text"), + } + }; + assert_eq!(plain_redone, "Prefix replacement suffix"); + } + + #[test] + fn check_spelling_change_all_in_one_undo_step() { + let mut app = app(); + let a = text(&mut app, 50.0, &format!("First {WORD_B} here and {WORD_B} again")); + let b = text(&mut app, 100.0, &format!("Second {WORD_B} line")); + app.run("select.none", json!({})).unwrap(); + + super::open(&mut app).unwrap(); + let ctx = context(); + + app.ui.dialog.as_mut().unwrap().fields.insert("change_to".into(), json!("replaced")); + click(&mut app, &ctx, "Change All"); + + let plain_a = { + let st = app.session.doc().unwrap(); + match &st.doc.node(vectorcraft_doc::NodeId(a)).unwrap().kind { + vectorcraft_doc::NodeKind::Text(t) => t.plain_text(), + _ => panic!("not text"), + } + }; + let plain_b = { + let st = app.session.doc().unwrap(); + match &st.doc.node(vectorcraft_doc::NodeId(b)).unwrap().kind { + vectorcraft_doc::NodeKind::Text(t) => t.plain_text(), + _ => panic!("not text"), + } + }; + assert_eq!(plain_a, "First replaced here and replaced again"); + assert_eq!(plain_b, "Second replaced line"); + + // Single undo reverts all changes made by Change All + app.run("edit.undo", json!({})).unwrap(); + let plain_a_undone = { + let st = app.session.doc().unwrap(); + match &st.doc.node(vectorcraft_doc::NodeId(a)).unwrap().kind { + vectorcraft_doc::NodeKind::Text(t) => t.plain_text(), + _ => panic!("not text"), + } + }; + let plain_b_undone = { + let st = app.session.doc().unwrap(); + match &st.doc.node(vectorcraft_doc::NodeId(b)).unwrap().kind { + vectorcraft_doc::NodeKind::Text(t) => t.plain_text(), + _ => panic!("not text"), + } + }; + assert_eq!(plain_a_undone, format!("First {WORD_B} here and {WORD_B} again")); + assert_eq!(plain_b_undone, format!("Second {WORD_B} line")); + } + + #[test] + fn check_spelling_dictionary_addition() { + let mut app = app(); + forget(&mut app, &[WORD_C]); + text(&mut app, 50.0, &format!("Look at {WORD_C} here")); + + super::open(&mut app).unwrap(); + let ctx = context(); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("not_in_dictionary"), WORD_C); + + click(&mut app, &ctx, "Add to Dictionary"); + + // Verify WORD_C was added to user dictionary + let dict = app.run("text.spelling.dictionary", json!({})).unwrap(); + let words = dict["words"].as_array().unwrap(); + assert!(words.contains(&json!(WORD_C))); + + // Dialog should now have completed because no other unknown words exist + assert!(app.ui.dialog.as_ref().unwrap().bool("done")); + + forget(&mut app, &[WORD_C]); + } + + #[test] + fn check_spelling_ignore_and_ignore_all() { + let mut app = app(); + text(&mut app, 50.0, &format!("{WORD_A} then {WORD_B}")); + + super::open(&mut app).unwrap(); + let ctx = context(); + + // First word is WORD_A + assert_eq!(app.ui.dialog.as_ref().unwrap().str("not_in_dictionary"), WORD_A); + + // Clicking Ignore moves to WORD_B without modifying the document or ignore list + click(&mut app, &ctx, "Ignore"); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("not_in_dictionary"), WORD_B); + assert!(!app.session.doc().unwrap().spelling_ignored.contains(WORD_A)); + + // Clicking Ignore All adds WORD_B to the document's spelling_ignored list + click(&mut app, &ctx, "Ignore All"); + assert!(app.session.doc().unwrap().spelling_ignored.contains(WORD_B)); + assert!(app.ui.dialog.as_ref().unwrap().bool("done")); + } + + #[test] + fn check_spelling_keyboard_navigation() { + let mut app = app(); + let id = text(&mut app, 50.0, &format!("Item {WORD_A} text")); + + super::open(&mut app).unwrap(); + let ctx = context(); + + app.ui.dialog.as_mut().unwrap().fields.insert("change_to".into(), json!("fixed")); + + // Enter triggers Change + key_press(&mut app, &ctx, egui::Key::Enter); + + let plain = { + let st = app.session.doc().unwrap(); + match &st.doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind { + vectorcraft_doc::NodeKind::Text(t) => t.plain_text(), + _ => panic!("not text"), + } + }; + assert_eq!(plain, "Item fixed text"); + assert!(app.ui.dialog.as_ref().unwrap().bool("done")); + + // When done, Enter closes the dialog + key_press(&mut app, &ctx, egui::Key::Enter); + assert!(app.ui.dialog.is_none(), "Enter on done closes dialog"); + + // Enter when change_to is empty and review is unfinished leaves dialog open + text(&mut app, 100.0, &format!("More {WORD_A}")); + super::open(&mut app).unwrap(); + assert!(!app.ui.dialog.as_ref().unwrap().bool("done")); + app.ui.dialog.as_mut().unwrap().fields.insert("change_to".into(), json!("")); + key_press(&mut app, &ctx, egui::Key::Enter); + assert!(app.ui.dialog.is_some(), "Enter with empty change_to leaves dialog open"); + + // Test Escape closes dialog + key_press(&mut app, &ctx, egui::Key::Escape); + assert!(app.ui.dialog.is_none(), "Escape closes dialog"); + } + + #[test] + fn check_spelling_selected_group_finds_nested_text() { + let mut app = app(); + let t = text(&mut app, 50.0, &format!("Grouped {WORD_A} item")); + app.run("select.set", json!({ "ids": [t] })).unwrap(); + let g = app.run("object.group", json!({})).unwrap(); + let group_id = g["id"].as_u64().unwrap(); + app.run("select.set", json!({ "ids": [group_id] })).unwrap(); + + super::open(&mut app).unwrap(); + let d = app.ui.dialog.as_ref().expect("dialog opens"); + assert_eq!(d.str("not_in_dictionary"), WORD_A); + } + + #[test] + fn check_spelling_when_no_misspellings() { + let mut app = app(); + text(&mut app, 50.0, "All correctly spelled English words here"); + + super::open(&mut app).unwrap(); + let d = app.ui.dialog.as_ref().expect("dialog opens"); + assert!(d.bool("done")); + assert!(d.str("context").contains("The spell check is complete.")); + + let ctx = context(); + click(&mut app, &ctx, "Done"); + assert!(app.ui.dialog.is_none()); + } + + #[test] + fn check_spelling_refused_on_document_switch() { + let mut app = app(); + text(&mut app, 50.0, &format!("Text {WORD_A} here")); + + super::open(&mut app).unwrap(); + assert!(app.ui.dialog.is_some()); + + // Create a new document, switching active document UID + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + + let ctx = context(); + frame(&mut app, &ctx, vec![]); + assert!(app.ui.dialog.is_none(), "switching documents closes spelling dialog"); + } + + #[test] + fn test_extract_sentence_context_multiline() { + let text = "First sentence.\nSecond line with teh typo.\nThird line ends."; + let range = text.find("teh").map(|idx| idx..idx + 3).unwrap(); + let (before, word, after) = super::extract_sentence_context(text, range); + assert_eq!(word, "teh"); + assert_eq!(before, "Second line with "); + assert_eq!(after, " typo."); + assert!(!before.contains("First")); + assert!(!after.contains("Third")); + + let text2 = "Far before. Near before.\nLine with teh typo. Near after.\nFar after."; + let range2 = text2.find("teh").map(|idx| idx..idx + 3).unwrap(); + let (b2, w2, a2) = super::extract_sentence_context(text2, range2); + assert_eq!(w2, "teh"); + assert_eq!(b2, "Line with "); + assert_eq!(a2, " typo."); + assert!(!b2.contains("Near before")); + assert!(!a2.contains("Near after")); + } + + #[test] + fn check_spelling_ignores_uneditable_text() { + let mut app = app(); + let editable_id = text(&mut app, 50.0, &format!("Prefix {WORD_A} suffix")); + let locked_id = text(&mut app, 100.0, &format!("Prefix {WORD_B} suffix")); + + // Lock the second text object + app.run("select.set", json!({ "ids": [locked_id] })).unwrap(); + app.run("object.lock", json!({})).unwrap(); + app.run("select.set", json!({ "ids": [] })).unwrap(); + + super::open(&mut app).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.str("not_in_dictionary"), WORD_A); + + let rem = d.fields.get("remaining_ids").and_then(serde_json::Value::as_array).unwrap(); + assert!(rem.iter().any(|v| v.as_u64() == Some(editable_id))); + assert!(!rem.iter().any(|v| v.as_u64() == Some(locked_id))); + } + + #[test] + fn check_spelling_change_all_containing_target_word_terminates() { + let mut app = app(); + let t1 = text(&mut app, 50.0, &format!("Prefix {WORD_A} suffix")); + + super::open(&mut app).unwrap(); + assert!(app.ui.dialog.is_some()); + + // Replace WORD_A with something containing WORD_A + let ctx = context(); + let replacement = format!("{WORD_A}abc"); + app.ui.dialog.as_mut().unwrap().fields.insert("change_to".into(), json!(replacement)); + + click(&mut app, &ctx, "Change All"); + // Change All successfully replaced WORD_A; advance moves to the new word + assert_eq!(app.ui.dialog.as_ref().unwrap().str("not_in_dictionary"), format!("{WORD_A}abc")); + + let st = app.session.doc().unwrap(); + let t1_text = match &st.doc.node(vectorcraft_doc::NodeId(t1)).unwrap().kind { + vectorcraft_doc::NodeKind::Text(t) => t.plain_text(), + _ => panic!("not text"), + }; + assert!(t1_text.contains(&format!("{WORD_A}abc"))); + } +} diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index 64e3f13e64..7afe37ec0b 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -22,6 +22,9 @@ pub(super) const SPEC: DialogSpec = DialogSpec { let cmyk = app.session.active().is_some_and(|s| s.doc.color_mode == vectorcraft_doc::ColorMode::Cmyk); let choices = |k: &str| rasterize_color_models(&command, k, cmyk).or_else(|| choices(&command, k)); form::param_fields(ui, d, &|k| lengths.contains(&k), &choices, &rank, app.session.general_unit()); + if command == crate::addons::packaging::SET_ROLE_SWATCH { + crate::addons::packaging::follow_role(app, d); + } if linked && d.fields.get("rowGutter") == d.fields.get("__rowGutterLinked") && let Some(g) = d.fields.get("gutter").cloned() @@ -159,6 +162,7 @@ fn order(command: &str) -> &'static [&'static str] { &["background", "colors", "contiguous", "match", "tolerance", "softness"] } crate::addons::cutting::BRIDGES => &["width", "count", "direction", "keepOriginal"], + crate::addons::packaging::SET_ROLE_SWATCH => &["role", "swatch"], _ => &[], } } @@ -168,6 +172,7 @@ fn choices(command: &str, key: &str) -> Option { match (command, key) { ("type.pathOptions", "effect") => Some(crate::menus::PATH_EFFECTS), ("type.pathOptions", "alignToPath") => Some(PATH_ALIGN), + (crate::addons::packaging::SET_ROLE_SWATCH, "role") => Some(crate::addons::packaging::ROLES), (crate::addons::typetools::RELEASE, "mode") => Some(crate::addons::typetools::RELEASE_MODES), (crate::addons::cutting::BRIDGES, "direction") => Some(crate::addons::cutting::BRIDGE_DIRECTIONS), ("text.areaOptions", "fit") => Some(AREA_FIT), diff --git a/crates/ui-egui/src/dialogs/effect.rs b/crates/ui-egui/src/dialogs/effect.rs index cd089e04bd..5a4799d22d 100644 --- a/crates/ui-egui/src/dialogs/effect.rs +++ b/crates/ui-egui/src/dialogs/effect.rs @@ -321,12 +321,12 @@ fn center_round(x: f64) -> f64 { /// 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"]`. +/// and height. The center the box shows, kept within 0 to 1, goes 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"); @@ -404,9 +404,12 @@ fn blur_center(ui: &mut egui::Ui, d: &mut Dialog) { }); }); }); - if c != before { - d.fields.insert(kx.into(), json!(c[0])); - d.fields.insert(ky.into(), json!(c[1])); + // A saved center outside the bounds is drawn at the nearest edge, and the fields hold that + // edge too, so OK sends the center the box shows. + for (key, v) in [(kx, c[0]), (ky, c[1])] { + if d.fields.get(key).and_then(Value::as_f64) != Some(v) { + d.fields.insert(key.into(), json!(v)); + } } } @@ -1502,4 +1505,38 @@ mod tests { "OK applies it" ); } + + /// A Radial Blur whose saved Blur Center lies outside the object's bounds (a document written + /// by hand or by another build) opens with the center at the nearest edge, and OK stores that + /// edge instead of sending the saved value, which `effect.setParams` refuses. + #[test] + fn radial_blur_center_outside_the_bounds_opens_at_the_edge_and_ok_keeps_it() { + 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.apply", json!({"effect": RADIAL_BLUR, "params": {"amount": 20}})).unwrap(); + { + let st = app.session.doc_mut().unwrap(); + let d = std::sync::Arc::make_mut(&mut st.doc); + let fx = &mut d.node_mut(vectorcraft_doc::NodeId(id)).unwrap().appearance.effects[0]; + fx.params["centerX"] = json!(1.5); + fx.params["centerY"] = json!(-0.25); + } + app.run("effect.dialog", json!({"effect": RADIAL_BLUR, "index": 0})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, Default::default()); + for k in 0..4 { + let input = egui::RawInput { time: Some(f64::from(k) * 0.05), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| super::super::show(&mut app, ui.ctx())); + out.textures_delta.clear(); + } + let field = |k: &str| app.ui.dialog.as_ref().unwrap().fields.get(k).and_then(Value::as_f64); + assert_eq!((field("centerX"), field("centerY")), (Some(1.0), Some(0.0)), "the fields hold the center the box shows"); + 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.params["centerX"].as_f64(), fx.params["centerY"].as_f64()), (Some(1.0), Some(0.0)), "OK stores the edge"); + } } diff --git a/crates/ui-egui/src/dialogs/export_for_screens.rs b/crates/ui-egui/src/dialogs/export_for_screens.rs index 5b28affa2f..96b5f63c27 100644 --- a/crates/ui-egui/src/dialogs/export_for_screens.rs +++ b/crates/ui-egui/src/dialogs/export_for_screens.rs @@ -638,15 +638,16 @@ fn edit_artboard_name( 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() { + // Escape and Enter also end the edit in the first frame that draws the field. + if cancel || enter || (!*focus && response.lost_focus()) { if !cancel { *rename = Some((*b, std::mem::take(text))); } response.surrender_focus(); *editing = None; + } else if *focus { + widgets::focus_field(ui, field, text); + *focus = false; } (false, true) } else { @@ -654,6 +655,10 @@ fn edit_artboard_name( if let Some(board) = board && response.double_clicked() { + // A name still typed for an artboard whose field this frame has not drawn yet is kept. + if let Some((b, text, _)) = editing.take() { + *rename = Some((b, text)); + } *editing = Some((board, name.into(), true)); ui.ctx().request_repaint(); // If both releases arrived this frame, the first click did not toggle the row. diff --git a/crates/ui-egui/src/dialogs/freehand.rs b/crates/ui-egui/src/dialogs/freehand.rs index bc7dd47212..93e3a1c2ff 100644 --- a/crates/ui-egui/src/dialogs/freehand.rs +++ b/crates/ui-egui/src/dialogs/freehand.rs @@ -104,6 +104,23 @@ fn fidelity_step(v: f64, n: f64) -> f64 { v } +/// The unit of tool `tool`'s Fidelity. The Pencil's, the Paintbrush's and the Smooth tool's +/// Fidelity is on screen, the same at any zoom (#5729); the Blob Brush's is in points. +fn fidelity_unit(tool: &str) -> &'static str { + if matches!(tool, "pencil" | "paintbrush" | "smooth") { "px" } else { "pt" } +} + +/// Width of the Fidelity field. +pub(crate) const FIDELITY_FIELD_W: f32 = FIELD_W; + +/// The Fidelity field of tool `tool`, showing `v` to two decimals from the tool's lowest Fidelity to +/// 100 and stepping by [`fidelity_step`], named by the label drawn just before it. Returns the value +/// typed or stepped to. The Contextual Task Bar shows the Smooth tool's. +pub(crate) fn fidelity_field(ui: &mut egui::Ui, id: &str, v: f64, tool: &str) -> Option { + let min = vectorcraft_tools::draw2::min_fidelity(tool); + widgets::range_field_stepped(ui, id, v, min..=100.0, fidelity_unit(tool), 2, FIELD_W, fidelity_step) +} + /// Where Fidelity `v` sits on a slider over `(min, max)`, from 0 to 1. The rail is logarithmic, so /// the low values, where the stroke is followed closely, get as much of it as the high ones /// (0.01–1 takes most of a 0.01–20 rail, in the tool's unit). @@ -211,9 +228,7 @@ fn fidelity(ui: &mut egui::Ui, d: &mut Dialog) { let v = d.f64("fidelity", 1.5); let tool = d.str("tool"); let rail = (vectorcraft_tools::draw2::min_fidelity(&tool), FIDELITY_MAX); - // The Pencil's, the Paintbrush's and the Smooth tool's Fidelity is on screen, the same at any - // zoom (#5729). - let unit = if matches!(tool.as_str(), "pencil" | "paintbrush" | "smooth") { "px" } else { "pt" }; + let unit = fidelity_unit(&tool); let rail_w = label_w(ui); let mut new = None; ui.label(egui::RichText::new(tl!("Fidelity:")).size(12.5).color(t.text)); @@ -222,7 +237,7 @@ fn fidelity(ui: &mut egui::Ui, d: &mut Dialog) { let (x, _, keyed) = widgets::color_slider_stepped(ui, "freehand-fidelity", tl!("Fidelity:"), Some(shown), fidelity_at(v, rail), rail_w, &|_| t.input_border); new = x.map(|x| fidelity_from(x, rail)).or(keyed); - if let Some(x) = widgets::range_field_stepped(ui, "freehand-fidelity-field", v, rail.0..=100.0, unit, 2, FIELD_W, fidelity_step) { + if let Some(x) = fidelity_field(ui, "freehand-fidelity-field", v, &tool) { new = Some(x); } }); diff --git a/crates/ui-egui/src/dialogs/freehand/tests.rs b/crates/ui-egui/src/dialogs/freehand/tests.rs index 1b41fc0886..3a73d6f3bb 100644 --- a/crates/ui-egui/src/dialogs/freehand/tests.rs +++ b/crates/ui-egui/src/dialogs/freehand/tests.rs @@ -172,7 +172,7 @@ fn live_curve_fitting_off_shows_the_points_until_the_release_fits_them() { let pointer = |kind, (x, y)| vectorcraft_tools::PointerEvent::new(kind, x, y); let newest = |app: &VectorcraftApp| { let doc = &app.session.doc().unwrap().doc; - doc.layers[0].children().unwrap().last().unwrap().path_data().unwrap().subpaths[0].anchors.clone() + doc.layers[0].children().unwrap().last().unwrap().path_data().unwrap().subpaths[0].anchors.to_vec() }; crate::canvas::dispatch(app, &pointer(vectorcraft_tools::PointerKind::Down, pts[0]), view); for p in &pts[1..] { diff --git a/crates/ui-egui/src/dialogs/graph_data.rs b/crates/ui-egui/src/dialogs/graph_data.rs index ecfb0c303e..90cc7d9f55 100644 --- a/crates/ui-egui/src/dialogs/graph_data.rs +++ b/crates/ui-egui/src/dialogs/graph_data.rs @@ -7,13 +7,15 @@ //! don't move the caret in the entry box). Pasting tab- or line-separated text fills the cells from //! the picked one. Import Data reads a tab-separated text file, Transpose row/column swaps rows and //! columns, Switch x/y swaps a scatter graph's y and x columns, Cell Style sets the number of -//! decimals the sheet shows and its columns' width, and Revert reads the graph's data again. Apply -//! (`graph.setData` with its series, categories and rows) redraws the graph and leaves the window -//! open. +//! decimals the sheet shows and the width of every column, dragging a column's right edge sets that +//! column's width (in whole digits, 0 to 20, as Cell Style), and Revert reads the graph's data +//! again. Apply (`graph.setData` with its series, categories and rows) redraws the graph and leaves +//! the window open. //! //! Fields: `grid` (rows of cell texts), `sel` ([row, column]), `entry` (the picked cell's text -//! being edited), `decimals` (null: as typed), `width` (digits), `__graph` (the graph's id) and -//! `__scatter`. +//! being edited), `decimals` (null: as typed), `width` (digits), `widths` (a column's own width in +//! digits by its index, null or missing: `width`; setting `width` empties it), `__graph` (the graph's +//! id) and `__scatter`. use serde_json::{Value, json}; use vectorcraft_doc::{MAX_GRAPH_CATEGORIES, MAX_GRAPH_SERIES}; @@ -62,7 +64,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { let entry = cell(&grid, 0, 1); app.ui.dialog = Some(Dialog::new( KIND, - json!({ "grid": grid, "sel": [0, 1], "entry": entry, "decimals": null, "width": 7, "__graph": id, "__scatter": scatter }), + json!({ "grid": grid, "sel": [0, 1], "entry": entry, "decimals": null, "width": 7, "widths": [], "__graph": id, "__scatter": scatter }), )); Ok(Value::Null) } @@ -355,7 +357,7 @@ fn import(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { } /// Draw the graph-data sheet: keyboard cell movement, block paste, import, transpose, switch-x/y -/// and revert actions, decimals and column width, and only the cells in view. +/// and revert actions, decimals and column widths, and only the cells in view. fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let entry_id = egui::Id::unique("graph-data-entry"); if ui.memory(|m| m.has_focus(entry_id)) { @@ -435,37 +437,20 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { ui.add_space(12.0); widgets::dim_label(ui, tl!("Column Width:")); let mut w = d.fields.get("width").and_then(Value::as_u64).unwrap_or(7); - if ui.add(egui::DragValue::new(&mut w).range(0..=MAX_WIDTH)).changed() { - d.fields.insert("width".into(), json!(w)); + let r = ui.add(egui::DragValue::new(&mut w).range(0..=MAX_WIDTH)); + // A value entered with Enter sets every column, also when it is the width shown. Leaving the + // field without a new value keeps the columns' own widths. + if r.changed() || (r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter))) { + set_width(d, w); } }); ui.add_space(6.0); - let at = sel(d); - let (rows, cols) = extent(d, at); - let decimals = d.fields.get("decimals").and_then(Value::as_u64); - let w = (d.fields.get("width").and_then(Value::as_u64).unwrap_or(7).min(MAX_WIDTH) as f32 * 7.0 + 10.0).max(12.0); - let mut clicked = None; - widgets::list_box(ui, |ui| { - // Only the cells in view are drawn: a graph's sheet can be 10,001 × 257. - egui::ScrollArea::both().id_salt("graph-data-sheet").max_height(280.0).auto_shrink([false, false]).show_viewport(ui, |ui, view| { - let (cw, ch) = (w + 1.0, ROW_H); - ui.set_min_size(egui::vec2(cols as f32 * cw, rows as f32 * ch)); - let origin = ui.max_rect().min; - let span = |lo: f32, hi: f32, size: f32, n: usize| ((lo / size).floor().max(0.0) as usize, ((hi / size).ceil().max(0.0) as usize).min(n)); - let (r0, r1) = span(view.min.y, view.max.y, ch, rows); - let (c0, c1) = span(view.min.x, view.max.x, cw, cols); - for r in r0..r1 { - for c in c0..c1 { - let rect = egui::Rect::from_min_size(origin + egui::vec2(c as f32 * cw, r as f32 * ch), egui::vec2(w, ch - 1.0)); - let text = shown(cell_at(d, r, c), decimals); - let b = egui::Button::selectable((r, c) == at, egui::RichText::new(text).monospace()).truncate(); - if ui.put(rect, b).clicked() && (r, c) != (0, 0) { - clicked = Some((r, c)); - } - } - } - }); - }); + let (clicked, resized) = sheet(ui, d); + if let Some((c, n)) = resized + && n != col_digits(d, c) + { + set_col_digits(d, c, n); + } if let Some(to) = clicked { pick(d, to); ui.memory_mut(|mem| mem.request_focus(entry_id)); @@ -479,6 +464,143 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { false } +/// Cell Style's Column Width in digits. +fn width(d: &Dialog) -> u64 { + d.fields.get("width").and_then(Value::as_u64).unwrap_or(7).min(MAX_WIDTH) +} + +/// A column's width in digits: its own when its edge was dragged, else Cell Style's. +fn col_digits(d: &Dialog, c: usize) -> u64 { + d.fields.get("widths").and_then(|w| w.get(c)).and_then(Value::as_u64).unwrap_or_else(|| width(d)).min(MAX_WIDTH) +} + +/// Cell Style's Column Width: every column `n` digits wide, the ones given their own width too. +fn set_width(d: &mut Dialog, n: u64) { + d.fields.insert("width".into(), json!(n.min(MAX_WIDTH))); + note_set(d, "width"); +} + +/// `ui.dialog.set` set `field`: a Column Width sets every column, as Cell Style's does. +pub(super) fn note_set(d: &mut Dialog, field: &str) { + if field == "width" { + d.fields.insert("widths".into(), json!([])); + } +} + +/// Set column `c`'s own width in digits (at most MAX_WIDTH). +fn set_col_digits(d: &mut Dialog, c: usize, n: u64) { + if c >= MAX_COLS { + return; + } + let widths = d.fields.entry("widths").or_insert_with(|| json!([])); + if !widths.is_array() { + *widths = json!([]); + } + let Some(widths) = widths.as_array_mut() else { return }; + if widths.len() <= c { + widths.resize(c + 1, Value::Null); + } + if let Some(w) = widths.get_mut(c) { + *w = json!(n.min(MAX_WIDTH)); + } +} + +/// A column `n` digits wide, in points on the sheet. +fn digits_px(n: u64) -> f32 { + (n.min(MAX_WIDTH) as f32 * 7.0 + 10.0).max(12.0) +} + +/// The width in digits nearest to `px` points, within Cell Style's 0 to MAX_WIDTH. +fn px_digits(px: f32) -> u64 { + if px.is_finite() { ((px - 10.0) / 7.0).round().clamp(0.0, MAX_WIDTH as f32) as u64 } else { 0 } +} + +/// The id of column `c`'s right edge on the sheet. +fn edge_id(c: usize) -> egui::Id { + egui::Id::unique(("graph-data-column-edge", c)) +} + +/// The cell clicked on the sheet ([row, column]), and the column whose edge is dragged with its width +/// in digits. +type SheetInput = (Option<(usize, usize)>, Option<(usize, u64)>); + +/// Draw the sheet's cells in view, each column at its own width. Returns the cell clicked, and the +/// column whose right edge is being dragged with the width in digits the pointer gives it. +fn sheet(ui: &mut egui::Ui, d: &Dialog) -> SheetInput { + let at = sel(d); + let (rows, cols) = extent(d, at); + let decimals = d.fields.get("decimals").and_then(Value::as_u64); + // Each column's left edge, and the sheet's width last: a column is its width and a 1-point gap. + let mut xs = Vec::with_capacity(cols + 1); + let mut x = 0.0; + xs.push(x); + for c in 0..cols { + x += digits_px(col_digits(d, c)) + 1.0; + xs.push(x); + } + let left = |c: usize| xs.get(c).copied().unwrap_or(x); + let (mut clicked, mut resized) = (None, None); + widgets::list_box(ui, |ui| { + // Only the cells in view are drawn: a graph's sheet can be 10,001 × 257. + egui::ScrollArea::both().id_salt("graph-data-sheet").max_height(280.0).auto_shrink([false, false]).show_viewport(ui, |ui, view| { + let ch = ROW_H; + ui.set_min_size(egui::vec2(x, rows as f32 * ch)); + let origin = ui.max_rect().min; + let (r0, r1) = ((view.min.y / ch).floor().max(0.0) as usize, ((view.max.y / ch).ceil().max(0.0) as usize).min(rows)); + // The columns that reach into the view. + let c0 = (0..cols).find(|&c| left(c + 1) > view.min.x).unwrap_or(cols); + let c1 = (c0..cols).find(|&c| left(c) >= view.max.x).unwrap_or(cols); + for r in r0..r1 { + for c in c0..c1 { + let size = egui::vec2(left(c + 1) - left(c) - 1.0, ch - 1.0); + let rect = egui::Rect::from_min_size(origin + egui::vec2(left(c), r as f32 * ch), size); + let text = shown(cell_at(d, r, c), decimals); + let b = egui::Button::selectable((r, c) == at, egui::RichText::new(text).monospace()).truncate(); + if ui.put(rect, b).clicked() && (r, c) != (0, 0) { + clicked = Some((r, c)); + } + } + } + // A column's right edge, over the rows in view: dragging it sets that column's width. The + // edge being dragged stays in the loop when it leaves the view, so the drag goes on, also in + // the frame it is released. + let (top, bottom) = (origin.y + r0 as f32 * ch, origin.y + r1 as f32 * ch); + let dragged = ui + .ctx() + .dragged_id() + .or_else(|| ui.ctx().drag_stopped_id()) + .and_then(|id| (0..cols).find(|&c| edge_id(c) == id)) + .filter(|c| !(c0..c1).contains(c)); + for c in (c0..c1).chain(dragged) { + let gap = origin.x + left(c + 1) - 0.5; + let edge = egui::Rect::from_x_y_ranges(gap - 3.0..=gap + 3.0, top..=bottom); + let h = ui.interact(edge, edge_id(c), egui::Sense::drag()).on_hover_cursor(egui::CursorIcon::ResizeColumn); + // The width is the column's width when the drag started plus how far the pointer has + // moved since, so a scroll offset that changes with the sheet's width doesn't change it. + if h.drag_started() + && let Some(p) = ui.input(|i| i.pointer.press_origin()).or_else(|| h.interact_pointer_pos()) + { + ui.data_mut(|m| m.insert_temp(edge_id(c), (p.x, left(c + 1) - left(c) - 1.0))); + } + if h.dragged() { + ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeColumn); + } + // The release can come in the same frame as the last move: it sets the width too. + if (h.dragged() || h.drag_stopped()) + && let Some(p) = h.interact_pointer_pos() + && let Some((x0, w0)) = ui.data(|m| m.get_temp::<(f32, f32)>(edge_id(c))) + { + resized = Some((c, px_digits(w0 + p.x - x0))); + } + if h.drag_stopped() { + ui.data_mut(|m| m.remove::<(f32, f32)>(edge_id(c))); + } + } + }); + }); + (clicked, resized) +} + #[cfg(test)] mod tests { use serde_json::json; @@ -685,6 +807,171 @@ mod tests { assert_eq!(sel(app.ui.dialog.as_ref().unwrap()), (0, 1), "Up"); } + /// Dragging a column's right edge shows the column-resize pointer and sets that column's width in + /// whole digits, the columns after it moving along; the other columns keep Cell Style's width. + /// A drag past 20 digits stops at 20, and Cell Style's Column Width then sets every column. + #[test] + fn dragging_a_column_edge_sets_that_columns_width() { + let (mut app, _) = app_with(",a,b\nQ1,1,2", "column"); + open(&mut app).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let frame = |app: &mut VectorcraftApp, events: Vec| { + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| super::super::show(app, ui.ctx())); + out.textures_delta.clear(); + out.platform_output.cursor_icon + }; + let button = + |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + let edge = |c: usize| ctx.read_response(edge_id(c)).map(|r| r.rect).unwrap_or_else(|| panic!("column {c}'s edge is drawn")); + let drag = |app: &mut VectorcraftApp, c: usize, dx: f32| { + let at = edge(c).center(); + frame(app, vec![egui::Event::PointerMoved(at), button(at, true)]); + for step in 1..=4 { + frame(app, vec![egui::Event::PointerMoved(at + egui::vec2(dx * step as f32 / 4.0, 0.0))]); + } + frame(app, vec![button(at + egui::vec2(dx, 0.0), false)]); + frame(app, vec![egui::Event::PointerMoved(egui::pos2(0.0, 0.0))]); + }; + let digits = |app: &VectorcraftApp| { + let d = app.ui.dialog.as_ref().unwrap(); + (0..4).map(|c| col_digits(d, c)).collect::>() + }; + frame(&mut app, vec![]); + frame(&mut app, vec![]); + // The window takes its place over the first frames: hover where the edge is now. + let hovered = (0..10).any(|_| frame(&mut app, vec![egui::Event::PointerMoved(edge(1).center())]) == egui::CursorIcon::ResizeColumn); + assert!(hovered, "hovering an edge shows the column-resize pointer"); + let (one, two) = (edge(1).center().x, edge(2).center().x); + // 70 points is 10 digits. + drag(&mut app, 1, 70.0); + assert_eq!(digits(&app), [7, 17, 7, 7]); + let moved = [edge(1).center().x - one, edge(2).center().x - two]; + assert!(moved.iter().all(|m| (m - 70.0).abs() < 0.01), "the columns after it move along: {moved:?}"); + drag(&mut app, 2, -500.0); + assert_eq!(digits(&app), [7, 17, 0, 7], "no narrower than 0 digits"); + drag(&mut app, 0, 500.0); + assert_eq!(digits(&app), [20, 17, 0, 7], "no wider than 20 digits"); + let d = app.ui.dialog.as_mut().unwrap(); + set_width(d, 9); + assert_eq!(digits(&app), [9; 4], "Cell Style sets every column"); + } + + /// A drag whose last move comes in the frame it is released sets the width to where it was + /// released. A held drag on a sheet scrolled to its right end keeps its width while the scroll + /// offset follows the narrower sheet. Entering the width that Column Width shows sets every + /// column, the dragged ones too. + #[test] + fn a_column_drag_ends_where_released_and_the_shown_width_entered_sets_every_column() { + let rows: Vec> = (0..3).map(|i| vec![i as f64; 30]).collect(); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("graph.create", json!({"type": "column", "x": 0, "y": 0, "width": 200, "height": 150, "rows": rows})).unwrap(); + open(&mut app).unwrap(); + let cols = extent(app.ui.dialog.as_ref().unwrap(), (0, 1)).1; + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1280.0, 900.0)); + let frame = |app: &mut VectorcraftApp, events: Vec| { + let mut out = + ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| super::super::show(app, ui.ctx())); + out.textures_delta.clear(); + out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default() + }; + let button = + |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + let edge = |c: usize| ctx.read_response(edge_id(c)).map(|r| r.rect).unwrap_or_else(|| panic!("column {c}'s edge is drawn")); + let digits = |app: &VectorcraftApp, c: usize| col_digits(app.ui.dialog.as_ref().unwrap(), c); + for _ in 0..3 { + frame(&mut app, vec![]); + } + // The last move and the release in one frame: 70 points is 10 digits. + let at = edge(1).center(); + frame(&mut app, vec![egui::Event::PointerMoved(at), button(at, true)]); + let to = at + egui::vec2(70.0, 0.0); + frame(&mut app, vec![egui::Event::PointerMoved(to), button(to, false)]); + frame(&mut app, vec![egui::Event::PointerMoved(egui::pos2(0.0, 0.0))]); + assert_eq!(digits(&app, 1), 17, "the width where the drag was released"); + // Scroll the sheet to its right end, then narrow a column by 5 digits and hold the pointer still. + let over = edge(1).center() - egui::vec2(20.0, 0.0); + let wheel = egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(-100_000.0, 0.0), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }; + frame(&mut app, vec![egui::Event::PointerMoved(over), wheel]); + for _ in 0..30 { + frame(&mut app, vec![]); + } + let c = cols - 2; + let at = edge(c).center(); + frame(&mut app, vec![egui::Event::PointerMoved(at), button(at, true)]); + for step in 1..=5 { + frame(&mut app, vec![egui::Event::PointerMoved(at - egui::vec2(7.0 * step as f32, 0.0))]); + } + for _ in 0..10 { + frame(&mut app, vec![]); + } + assert_eq!(digits(&app, c), 2, "a held drag keeps its width"); + let to = at - egui::vec2(35.0, 0.0); + frame(&mut app, vec![button(to, false)]); + frame(&mut app, vec![egui::Event::PointerMoved(egui::pos2(0.0, 0.0))]); + assert_eq!(digits(&app, c), 2, "the width where the drag was released"); + // Column Width still shows 7: entering 7 there sets every column to 7. + let nodes = frame(&mut app, vec![]); + let label = nodes + .iter() + .find(|(_, n)| n.role() == egui::accesskit::Role::Label && n.value() == Some("Column Width:")) + .and_then(|(_, n)| n.bounds()) + .expect("the Column Width label is drawn"); + let field = nodes + .iter() + .filter(|(_, n)| n.role() == egui::accesskit::Role::SpinButton) + .filter_map(|(_, n)| n.bounds()) + .filter(|b| b.x0 >= label.x1 && b.y0 < label.y1 && b.y1 > label.y0) + .min_by(|a, b| a.x0.total_cmp(&b.x0)) + .expect("the Column Width field is drawn"); + let at = egui::pos2(((field.x0 + field.x1) / 2.0) as f32, ((field.y0 + field.y1) / 2.0) as f32); + let click = |app: &mut VectorcraftApp, at| { + frame(app, vec![egui::Event::PointerMoved(at), button(at, true)]); + frame(app, vec![button(at, false)]); + frame(app, vec![]); + }; + // Clicking into the field and away from it, without a new value, keeps the columns' widths. + click(&mut app, at); + click(&mut app, egui::pos2(((label.x0 + label.x1) / 2.0) as f32, ((label.y0 + label.y1) / 2.0) as f32)); + assert_eq!((digits(&app, 1), digits(&app, c), digits(&app, 0)), (17, 2, 7), "leaving the field keeps the widths"); + click(&mut app, at); + frame(&mut app, vec![egui::Event::Text("7".into())]); + let enter = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + frame(&mut app, vec![enter]); + frame(&mut app, vec![]); + assert_eq!((digits(&app, 1), digits(&app, c), digits(&app, 0)), (7, 7, 7), "Column Width sets every column"); + } + + #[test] + fn a_column_width_in_points_maps_to_whole_digits() { + for n in 0..=MAX_WIDTH { + assert_eq!(px_digits(digits_px(n)), n); + } + assert_eq!((px_digits(-40.0), px_digits(1e9), px_digits(f32::NAN)), (0, MAX_WIDTH, 0)); + let mut d = Dialog::new(KIND, json!({ "width": 7 })); + set_col_digits(&mut d, 3, 99); + set_col_digits(&mut d, MAX_COLS, 5); + assert_eq!((col_digits(&d, 2), col_digits(&d, 3)), (7, MAX_WIDTH)); + assert_eq!(d.fields["widths"].as_array().map(Vec::len), Some(4), "a column past the sheet is left alone"); + // `width` set by `ui.dialog.set` sets every column too, also when set back to the width before. + for w in [12, 7] { + crate::dialogs::set_field(&mut d, "width".into(), json!(w)); + assert_eq!((col_digits(&d, 2), col_digits(&d, 3)), (w, w)); + } + set_col_digits(&mut d, 1, 4); + assert_eq!((col_digits(&d, 1), col_digits(&d, 3)), (4, 7), "a drag after it gives that column its own width"); + } + /// How many buttons (the sheet's cells and the window's own) Graph Data draws in the second of two /// frames in a 1280 × 900 window, for a graph of `categories` rows of `series` values. fn buttons_drawn(categories: usize, series: usize) -> usize { diff --git a/crates/ui-egui/src/dialogs/para_style_options.rs b/crates/ui-egui/src/dialogs/para_style_options.rs index a78790d692..d63d43be89 100644 --- a/crates/ui-egui/src/dialogs/para_style_options.rs +++ b/crates/ui-egui/src/dialogs/para_style_options.rs @@ -361,7 +361,12 @@ pub(crate) fn edited_attrs(d: &Dialog) -> Result, String> { } let same = unchanged("composer", "__resetComposition"); - keep_or(&mut attrs, "composer", same, choice("composer").filter(|v| matches!(v.as_str(), Some("singleLine" | "everyLine")))); + keep_or( + &mut attrs, + "composer", + same, + choice("composer").filter(|v| matches!(v.as_str(), Some("singleLine" | "everyLine" | "standardSingleLine" | "standardEveryLine"))), + ); let same = unchanged("roman_hanging", "__resetComposition"); keep_or(&mut attrs, "roman_hanging", same, switch("roman_hanging")); @@ -637,7 +642,9 @@ fn choice(ui: &mut egui::Ui, d: &mut Dialog, key: &str, options: &[(&str, &str)] let shown = options.iter().find(|(value, _)| *value == selected).map_or("", |(_, label)| *label); let labels: Vec<&str> = std::iter::once(" ").chain(options.iter().map(|(_, label)| *label)).collect(); ui.add_enabled_ui(enabled, |ui| { - if let Some(i) = crate::widgets::dropdown(ui, (KIND, key), shown, &labels, 190.0) { + // shortcut: 7 pt per character approximates the widest label; measure the text when a label wraps. + let width = (labels.iter().map(|l| l.chars().count()).max().unwrap_or(0) as f32 * 7.0).max(190.0); + if let Some(i) = crate::widgets::dropdown(ui, (KIND, key), shown, &labels, width) { d.fields.insert(key.into(), if i == 0 { Value::Null } else { options.get(i - 1).map_or(Value::Null, |(value, _)| json!(value)) }); } }); @@ -842,11 +849,16 @@ pub(crate) fn clear_tabs(d: &mut Dialog) { d.fields.remove("__tabEdited"); } -/// Composition: the Single-line or Every-line Composer, and Roman Hanging Punctuation. +/// Composition: the Middle Eastern & South Asian or Standard, Single-line or Every-line Composer, and Roman Hanging Punctuation. pub(crate) fn composition_body(ui: &mut egui::Ui, d: &mut Dialog) { egui::Grid::new("paragraph-style-composition").num_columns(2).spacing([18.0, 8.0]).show(ui, |ui| { let row = ui.label(tl!("Composition")); - let composers = [("singleLine", tl!("Single-line Composer")), ("everyLine", tl!("Every-line Composer"))]; + let composers = [ + ("singleLine", tl!("Middle Eastern & South Asian Single-line Composer")), + ("everyLine", tl!("Middle Eastern & South Asian Every-line Composer")), + ("standardSingleLine", tl!("Standard Single-line Composer")), + ("standardEveryLine", tl!("Standard Every-line Composer")), + ]; ui.label_inputs_by(row.id, |ui| choice(ui, d, "composer", &composers, true)); ui.end_row(); switch(ui, d, "roman_hanging", tl!("Roman Hanging Punctuation"), true); @@ -857,7 +869,7 @@ pub(crate) fn composition_body(ui: &mut egui::Ui, d: &mut Dialog) { /// unset; Hyphenation Zone is also inactive with the Every-line Composer, which does not use it. pub(crate) fn hyphenation_body(ui: &mut egui::Ui, d: &mut Dialog) { let on = d.fields.get("hyphenate").and_then(Value::as_bool) == Some(true); - let single_line = d.fields.get("composer").and_then(Value::as_str) == Some("singleLine"); + let single_line = matches!(d.fields.get("composer").and_then(Value::as_str), Some("singleLine" | "standardSingleLine")); egui::Grid::new("paragraph-style-hyphenation").num_columns(2).spacing([18.0, 8.0]).show(ui, |ui| { switch(ui, d, "hyphenate", tl!("Hyphenation"), true); for (key, suffix) in [ diff --git a/crates/ui-egui/src/dialogs/psd_import.rs b/crates/ui-egui/src/dialogs/psd_import.rs new file mode 100644 index 0000000000..950b15c763 --- /dev/null +++ b/crates/ui-egui/src/dialogs/psd_import.rs @@ -0,0 +1,628 @@ +//! PSD Import Options: opening a PSD or PSB file with two or more layers or with slices, or +//! placing one without Link, asks whether its layers become objects or one flat image, whether +//! hidden layers come in, and whether its slices come in (Import Slices, offered only for a file +//! with slices) +//! (). +//! A linked file shows its flat image, so placing with Link doesn't ask. The two-layer threshold, +//! the starting choices, Import Slices applying to both conversions and remembering the choices +//! are VectorCraft's own. +//! +//! Fields: `mode` (`open` | `place`), `name`, `path?`, `width`, `height` (the canvas, px), +//! `layers`, `hidden` and `slices` (counts, from `document.psdInfo`), `convert` (`objects` | +//! `flatten`), `hiddenLayers` and `importSlices`. `__place` keeps the other `file.place` params. +//! The file's bytes stay in [`crate::state::UiState::dialog_file`]. OK opens or places the file +//! with `layers`, `hiddenLayers` and (for a file with slices) `importSlices`, and remembers the +//! choices for the next file; errors keep the dialog open. + +use serde_json::{Value, json}; +use vectorcraft_engine::cmd::fileio; + +use super::DialogSpec; +use super::import_pdf::{DialogFile, other_place_params, place_source, with_file}; +use crate::state::Dialog; +use crate::{VectorcraftApp, io, widgets}; + +pub const KIND: &str = "psdImport"; + +pub(super) const SPEC: DialogSpec = DialogSpec { + heading: |d| if d.str("mode") == "place" { tl!("Place PSD") } else { tl!("PSD Import Options") }.into(), + body, + confirm, + min_width: 380.0, + ..DialogSpec::FORM +}; + +/// The fewest layers a file has for the dialog to ask. +const MIN_LAYERS: usize = 2; + +/// Open `bytes` (or place them with the `file.place` params `place`) through the dialog when they +/// are a PSD or PSB file with [`MIN_LAYERS`] layers or more, or with slices; false when they aren't +/// (the loader then opens or places the file, or says why it can't). +pub fn offer(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option, place: Option<&Value>) -> bool { + let Ok(info) = fileio::psd_info(bytes) else { return false }; + if info.layers < MIN_LAYERS && info.slices == 0 { + return false; + } + app.ui.dialog_file = Some(DialogFile::new(bytes.to_vec())); + let (layers, hidden, slices) = last_choices(app); + let mut fields = json!({ + "mode": if place.is_some() { "place" } else { "open" }, + "name": name, + "width": info.width, + "height": info.height, + "layers": info.layers, + "hidden": info.hidden, + "slices": info.slices, + "convert": if layers { "objects" } else { "flatten" }, + "hiddenLayers": hidden, + "importSlices": slices, + }); + if let Some(p) = path { + fields["path"] = json!(p); + } + if let Some(p) = place { + fields["__place"] = other_place_params(p, &["layers", "hiddenLayers", "importSlices"]); + } + app.ui.dialog = Some(Dialog::new(KIND, fields)); + true +} + +/// `file.place` with params `p` asks first (true) when they embed a PSD or PSB file (`link: false`, +/// or the file's bytes) and give no `layers`. +pub fn offer_place(app: &mut VectorcraftApp, p: &Value) -> bool { + let embedded = p.get("path").is_none() || p.get("link").and_then(Value::as_bool) == Some(false); + if !embedded || p.get("layers").is_some() { + return false; + } + let Some((name, bytes, path)) = place_source(app, p, |ext| matches!(ext, "psd" | "pdd" | "psb")) else { return false }; + offer(app, &name, &bytes, path, Some(p)) +} + +/// The PSD Import Options chosen last (layers, hidden layers, slices), at first Convert Layers to +/// Objects without hidden layers, with Import Slices. +fn last_choices(app: &VectorcraftApp) -> (bool, bool, bool) { + let last = |k: &str, default: bool| app.ui.psd_import.get(k).and_then(Value::as_bool).unwrap_or(default); + (last("layers", true), last("hiddenLayers", false), last("importSlices", true)) +} + +/// Several files placed without Link load the place cursor without asking: the `file.place.queue` +/// params `q` take the PSD Import Options chosen last, which apply to each PSD or PSB file among them. +pub fn queue_options(app: &VectorcraftApp, q: &mut Value) { + let (layers, hidden, slices) = last_choices(app); + q["layers"] = json!(layers); + if layers && hidden { + q["hiddenLayers"] = json!(true); + } + q["importSlices"] = json!(slices); +} + +/// `file.place` params `p` placed without asking (Show Import Options off) that embed a PSD or PSB +/// file and give no `layers` take the PSD Import Options chosen last; `hiddenLayers` and +/// `importSlices` that the params give are kept. +pub fn last_options(app: &VectorcraftApp, p: &mut Value) { + let embedded = p.get("path").is_none() || p.get("link").and_then(Value::as_bool) == Some(false); + let name = p.get("path").or_else(|| p.get("name")).and_then(Value::as_str).unwrap_or_default(); + if embedded && p.get("layers").is_none() && matches!(fileio::extension(name).as_str(), "psd" | "pdd" | "psb") { + let (layers, hidden, slices) = last_choices(app); + p["layers"] = json!(layers); + if layers && hidden && p.get("hiddenLayers").is_none() { + p["hiddenLayers"] = json!(true); + } + if p.get("importSlices").is_none() { + p["importSlices"] = json!(slices); + } + if p.get("path").is_none() { + // A file from bytes has no file to link to; it may carry the Place dialog's Link. + p["link"] = json!(false); + } + } +} + +/// OK: open or place the file with the choices. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let file = app.ui.dialog_file.clone().ok_or("the file is no longer loaded")?; + let layers = d.str("convert") != "flatten"; + let hidden = layers && d.bool("hiddenLayers"); + // Import Slices is a choice only for a file with slices; otherwise the one made last stays. + let has_slices = d.fields.get("slices").and_then(Value::as_u64).unwrap_or(0) > 0; + let slices = if has_slices { d.bool("importSlices") } else { last_choices(app).2 }; + app.ui.psd_import = json!({ "layers": layers, "hiddenLayers": d.bool("hiddenLayers"), "importSlices": slices }); + let r = if d.str("mode") == "place" { + let mut p = with_file(d.fields.get("__place"), d, &file); + p["layers"] = json!(layers); + if layers || has_slices { + // Layers and slices are always embedded; a file from bytes may carry the Place dialog's + // Link. + p["link"] = json!(false); + } + if hidden { + p["hiddenLayers"] = json!(true); + } + if has_slices { + p["importSlices"] = json!(slices); + } + crate::place::run_for_user(app, &p).map(|_| ()) + } else { + let path = d.fields.get("path").and_then(Value::as_str).map(str::to_string); + let mut p = json!({ "layers": layers, "hiddenLayers": hidden }); + if has_slices { + p["importSlices"] = json!(slices); + } + io::open_document(app, &d.str("name"), &file.bytes, path, &p).map(|_| ()) + }; + match r { + Ok(()) => { + // Placing may have opened another dialog; only this one closes. + if app.ui.dialog.as_ref().is_some_and(|x| x.kind == KIND) { + app.ui.dialog = None; + } + Ok(Value::Null) + } + Err(e) => { + app.ui.dialog = Some(d.clone()); + Err(e) + } + } +} + +fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + let count = |k: &str| d.fields.get(k).and_then(Value::as_u64).unwrap_or(0); + widgets::dim_label(ui, &format!("{} × {} px · {}: {}", count("width"), count("height"), tl!("Layers"), count("layers"))); + // Offered only for a file with slices, with either conversion. + let sliced = count("slices") > 0; + ui.add_space(8.0); + let convert = d.str("convert") != "flatten"; + if widgets::radio(ui, tl!("Convert Layers to Objects"), convert, true) { + d.fields.insert("convert".into(), json!("objects")); + } + ui.horizontal(|ui| { + ui.add_space(22.0); + let on = d.bool("hiddenLayers"); + if widgets::check(ui, tl!("Import Hidden Layers"), on && convert, convert) { + d.fields.insert("hiddenLayers".into(), json!(!on)); + } + }); + if widgets::radio(ui, tl!("Flatten Layers to a Single Image"), !convert, true) { + d.fields.insert("convert".into(), json!("flatten")); + } + ui.add_space(8.0); + let on = d.bool("importSlices"); + if widgets::check(ui, tl!("Import Slices"), on && sliced, sliced) { + d.fields.insert("importSlices".into(), json!(!on)); + } + false +} + +#[cfg(test)] +mod tests { + use vectorcraft_engine::Session; + use vectorcraft_engine::doc::NodeKind; + + use super::*; + + /// A PSD file of three layers, the middle one hidden, written by `document.export`. + fn layered() -> Vec { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 20, "height": 20})).unwrap(); + let back = s.doc().unwrap().doc.layers[0].id.0; + s.execute("layer.setProps", &json!({"id": back, "name": "Back"})).unwrap(); + for (name, color) in [("Back", "#ff0000"), ("Middle", "#00ff00"), ("Front", "#0000ff")] { + if name != "Back" { + s.execute("layer.new", &json!({ "name": name })).unwrap(); + } + s.execute("paint.setFill", &json!({ "color": color })).unwrap(); + s.execute("shape.rectangle", &json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap(); + } + let middle = s.doc().unwrap().doc.layers[1].id.0; + s.execute("layer.setProps", &json!({"id": middle, "visible": false})).unwrap(); + let r = s.execute("document.export", &json!({"format": "psd", "hiddenLayers": true})).unwrap(); + vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap() + } + + fn app() -> VectorcraftApp { + VectorcraftApp::new(Session::new(), Default::default()) + } + + fn frame(app: &mut VectorcraftApp) -> String { + crate::tests_labels::painted_text(app, |app, ui| super::super::show(app, ui.ctx())) + } + + fn set(app: &mut VectorcraftApp, k: &str, v: Value) { + app.ui.dialog.as_mut().unwrap().fields.insert(k.into(), v); + } + + fn layer_names(app: &VectorcraftApp) -> Vec<(String, bool)> { + app.session.doc().unwrap().doc.layers.iter().map(|l| (l.name.clone().unwrap_or_default(), l.visible)).collect() + } + + #[test] + fn opening_a_layered_file_asks_for_the_import_options() { + let psd = layered(); + let mut app = app(); + io::open_bytes(&mut app, "poster.psd", &psd, None).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.kind.as_str(), d.str("mode"), d.str("convert"), d.bool("hiddenLayers")), (KIND, "open".into(), "objects".into(), false)); + assert_eq!((&d.fields["layers"], &d.fields["hidden"], &d.fields["width"]), (&json!(3), &json!(1), &json!(20))); + assert!(app.session.active().is_none(), "nothing opens before OK"); + let text = frame(&mut app); + for label in [ + "PSD Import Options", + "20 × 20 px", + "Layers: 3", + "Convert Layers to Objects", + "Import Hidden Layers", + "Flatten Layers to a Single Image", + "OK", + ] { + assert!(text.contains(label), "{label} in {text}"); + } + // Layers as objects, hidden ones left out. + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(layer_names(&app), [("Back".to_string(), true), ("Front".to_string(), true)]); + // With Import Hidden Layers the hidden layer comes in hidden. + io::open_bytes(&mut app, "poster.psd", &psd, None).unwrap(); + set(&mut app, "hiddenLayers", json!(true)); + frame(&mut app); + super::super::confirm(&mut app).unwrap(); + assert_eq!(layer_names(&app), [("Back".to_string(), true), ("Middle".to_string(), false), ("Front".to_string(), true)]); + // Flatten opens one image, and the next file starts from the choices made last. + io::open_bytes(&mut app, "poster.psd", &psd, None).unwrap(); + assert!(app.ui.dialog.as_ref().unwrap().bool("hiddenLayers"), "remembered"); + set(&mut app, "convert", json!("flatten")); + frame(&mut app); + super::super::confirm(&mut app).unwrap(); + let st = app.session.doc().unwrap(); + assert_eq!(st.doc.layers.len(), 1); + assert!(matches!(st.doc.layers[0].children().map(Vec::as_slice), Some([one]) if matches!(one.kind, NodeKind::Image(_)))); + io::open_bytes(&mut app, "poster.psd", &psd, None).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("convert"), "flatten"); + } + + #[test] + fn files_with_fewer_than_two_layers_open_without_asking() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 20, "height": 20})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap(); + let one = s.execute("document.export", &json!({"format": "psd"})).unwrap(); + let flat = s.execute("document.export", &json!({"format": "psd", "layers": false})).unwrap(); + for r in [one, flat] { + let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap(); + let mut app = app(); + io::open_bytes(&mut app, "one.psd", &bytes, None).unwrap(); + assert!(app.ui.dialog.is_none()); + assert!(app.session.active().is_some()); + } + } + + #[test] + fn placing_without_link_asks_and_places_the_layers_as_a_group() { + let b64 = vectorcraft_format::base64_encode(&layered()); + let mut app = app(); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let r = crate::place::run_for_user(&mut app, &json!({"name": "poster.psd", "dataBase64": b64, "at": [50, 50]})).unwrap(); + assert_eq!(r["dialog"], KIND); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.str("mode"), &d.fields["__place"]), ("place".into(), &json!({"at": [50, 50]}))); + assert!(frame(&mut app).contains("Place PSD")); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + let st = app.session.doc().unwrap(); + let [id] = st.selection.objects[..] else { panic!("one object is selected") }; + let g = st.doc.node(id).unwrap(); + assert!(matches!(g.kind, NodeKind::Group { .. })); + let names: Vec<&str> = g.children().unwrap().iter().filter_map(|c| c.name.as_deref()).collect(); + assert_eq!(names, ["Back", "Front"]); + // Flatten places the merged image. + crate::place::run_for_user(&mut app, &json!({"name": "poster.psd", "dataBase64": b64})).unwrap(); + set(&mut app, "convert", json!("flatten")); + super::super::confirm(&mut app).unwrap(); + let st = app.session.doc().unwrap(); + let [id] = st.selection.objects[..] else { panic!("one object is selected") }; + assert!(matches!(st.doc.node(id).unwrap().kind, NodeKind::Image(_))); + } + + /// The OK of the dialog a drop on a canvas opened places in the document the file was dropped + /// on, made active again, even when another document became active meanwhile; it doesn't + /// place when that document has been reverted or closed since. + #[test] + fn a_dropped_files_ok_places_in_the_document_it_was_dropped_on() { + use crate::place::{DropAt, DropTarget}; + let psd = layered(); + let mut app = app(); + for _ in 0..2 { + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + } + let drop_on_first = |app: &mut VectorcraftApp| { + app.session.set_active(0); + let st = app.session.doc().unwrap(); + let target = DropTarget::Place(DropAt { doc: st.uid, reverts: st.reverts, at: vectorcraft_geom::Point::new(50.0, 50.0), embed: true }); + crate::place::drop_files(app, vec![(target, ("poster.psd".into(), None, psd.clone()))]); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND)); + // Another document becomes active while the dialog is open. + app.session.set_active(1); + }; + let objects = + |app: &VectorcraftApp, i: usize| app.session.documents()[i].doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum::(); + drop_on_first(&mut app); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!((objects(&app, 0), objects(&app, 1)), (1, 0), "placed in the document it was dropped on"); + assert_eq!(app.session.active_index(), Some(0), "which is active again"); + // Reverted meanwhile: the dialog stays open with the reason, and nothing is placed. + drop_on_first(&mut app); + let first = app.session.documents()[0].uid; + app.session.document_mut(first).unwrap().reverts += 1; + let e = super::super::confirm(&mut app).unwrap_err(); + assert!(e.contains("was reverted"), "{e}"); + assert_eq!((objects(&app, 0), objects(&app, 1)), (1, 0)); + // Closed meanwhile. + app.ui.dialog = None; + drop_on_first(&mut app); + app.session.close_document(0); + let e = super::super::confirm(&mut app).unwrap_err(); + assert!(e.contains("was closed"), "{e}"); + assert_eq!(objects(&app, 0), 0); + } + + #[test] + fn several_files_placed_without_link_take_the_last_choices() { + let dir = std::env::temp_dir().join(format!("vc-psd-import-queue-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let paths: Vec = ["a.psd", "b.psd"] + .iter() + .map(|n| { + let p = dir.join(n); + std::fs::write(&p, layered()).unwrap(); + p.to_string_lossy().into_owned() + }) + .collect(); + // Place both through the Place dialog, then click the cursor once for each: what was placed. + let place_two = |app: &mut VectorcraftApp, link: bool| -> Vec { + let files: Vec = paths.iter().map(|p| json!({ "path": p })).collect(); + let d = Dialog::new(crate::dialogs::place::KIND, json!({"files": files, "link": link, "template": false})); + crate::place::confirm(app, &d).unwrap(); + assert!(app.ui.dialog.is_none(), "the cursor loads without asking"); + let view = vectorcraft_engine::ViewInfo::default(); + (0..2) + .map(|_| { + for kind in [vectorcraft_tools::PointerKind::Down, vectorcraft_tools::PointerKind::Up] { + for r in app.session.pointer(&vectorcraft_tools::PointerEvent::new(kind, 10.0, 10.0), view).unwrap() { + if let vectorcraft_engine::UiRequest::Place(p) = r { + crate::place::place_from_cursor(app, &p); + } + } + } + let st = app.session.doc().unwrap(); + let [id] = st.selection.objects[..] else { panic!("one object is placed") }; + st.doc.node(id).unwrap().clone() + }) + .collect() + }; + let visible = |n: &vectorcraft_engine::doc::Node| -> Vec { n.children().unwrap().iter().map(|c| c.visible).collect() }; + let mut app = app(); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + // At first, Convert Layers to Objects without hidden layers. + for n in place_two(&mut app, false) { + assert!(matches!(n.kind, NodeKind::Group { .. })); + assert_eq!(visible(&n), [true, true]); + } + // Then the choices made last. + app.ui.psd_import = json!({"layers": true, "hiddenLayers": true}); + for n in place_two(&mut app, false) { + assert_eq!(visible(&n), [true, false, true]); + } + app.ui.psd_import = json!({"layers": false, "hiddenLayers": true}); + assert!(place_two(&mut app, false).iter().all(|n| matches!(n.kind, NodeKind::Image(_)))); + // Placed with Link, the files keep their flat images. + app.ui.psd_import = json!({"layers": true, "hiddenLayers": false}); + assert!(place_two(&mut app, true).iter().all(|n| matches!(n.kind, NodeKind::Image(_)))); + std::fs::remove_dir_all(&dir).ok(); + } + + /// `psd` with a slices resource (1050, version 6) holding one user slice over its top-left + /// 10 × 10 px, named "cell". + fn sliced(psd: &[u8]) -> Vec { + let ustr = |s: &str| -> Vec { + let units: Vec = s.encode_utf16().collect(); + let mut b = (units.len() as u32).to_be_bytes().to_vec(); + b.extend(units.iter().flat_map(|u| u.to_be_bytes())); + b + }; + let mut data = 6u32.to_be_bytes().to_vec(); + data.extend([0u8; 16]); + data.extend(ustr("")); + data.extend(1u32.to_be_bytes()); + // ID, group ID, origin (made by the user), name, type (Image), left, top, right, bottom. + data.extend([1u32, 0, 2].iter().flat_map(|v| v.to_be_bytes())); + data.extend(ustr("cell")); + data.extend([1u32, 0, 0, 10, 10].iter().flat_map(|v| v.to_be_bytes())); + // URL, target, message, alt text, cell text is HTML, cell text, alignments, color. + for _ in 0..4 { + data.extend(ustr("")); + } + data.push(0); + data.extend(ustr("")); + data.extend([0u8; 12]); + let u32_at = |at: usize| u32::from_be_bytes(psd[at..at + 4].try_into().unwrap()) as usize; + let colors = 26 + 4 + u32_at(26); + let len = u32_at(colors); + let mut block = b"8BIM".to_vec(); + block.extend(1050u16.to_be_bytes()); + block.extend([0, 0]); + block.extend((data.len() as u32).to_be_bytes()); + block.extend(&data); + block.resize(block.len().next_multiple_of(2), 0); + let mut out = psd[..colors].to_vec(); + out.extend(((len + block.len()) as u32).to_be_bytes()); + out.extend(&psd[colors + 4..colors + 4 + len]); + out.extend(block); + out.extend(&psd[colors + 4 + len..]); + out + } + + fn slice_names(app: &VectorcraftApp) -> Vec { + app.session.doc().unwrap().doc.slices.iter().map(|s| s.options.name.clone()).collect() + } + + #[test] + fn a_file_with_slices_asks_with_import_slices_on_either_conversion() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 20, "height": 20})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap(); + let r = s.execute("document.export", &json!({"format": "psd"})).unwrap(); + // One layer: without slices it opens at once, with them it asks. + let psd = sliced(&vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap()); + let mut app = app(); + io::open_bytes(&mut app, "one.psd", &psd, None).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.kind.as_str(), &d.fields["slices"], d.bool("importSlices")), (KIND, &json!(1), true)); + assert!(frame(&mut app).contains("Import Slices")); + // Flatten keeps Import Slices: the merged image opens with the slice. + set(&mut app, "convert", json!("flatten")); + super::super::confirm(&mut app).unwrap(); + assert_eq!(slice_names(&app), ["cell"]); + // Left off, the slice stays out, and the next file starts from that choice. + io::open_bytes(&mut app, "one.psd", &psd, None).unwrap(); + set(&mut app, "importSlices", json!(false)); + super::super::confirm(&mut app).unwrap(); + assert!(slice_names(&app).is_empty()); + io::open_bytes(&mut app, "one.psd", &psd, None).unwrap(); + assert!(!app.ui.dialog.as_ref().unwrap().bool("importSlices"), "remembered"); + // A layered file without slices keeps the choice made last for the next sliced one. + app.ui.dialog = None; + io::open_bytes(&mut app, "poster.psd", &layered(), None).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["slices"], json!(0)); + set(&mut app, "importSlices", json!(true)); + super::super::confirm(&mut app).unwrap(); + assert_eq!(app.ui.psd_import["importSlices"], json!(false)); + } + + #[test] + fn placing_a_sliced_file_without_link_brings_its_slices_with_the_art() { + let b64 = vectorcraft_format::base64_encode(&sliced(&layered())); + let mut app = app(); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + crate::place::run_for_user(&mut app, &json!({"name": "poster.psd", "dataBase64": b64, "at": [50, 50]})).unwrap(); + assert!(app.ui.dialog.as_ref().unwrap().bool("importSlices")); + super::super::confirm(&mut app).unwrap(); + let st = app.session.doc().unwrap(); + assert_eq!(st.doc.slices.len(), 1); + assert_eq!(st.doc.slices[0].rect, vectorcraft_geom::Rect::new(40.0, 40.0, 50.0, 50.0)); + // Several files placed together take the choice made last. + let mut q = json!({}); + app.ui.psd_import = json!({"layers": true, "importSlices": false}); + queue_options(&app, &mut q); + assert_eq!(q["importSlices"], json!(false)); + } + + #[test] + fn placing_with_show_import_options_off_takes_the_last_choices() { + let b64 = vectorcraft_format::base64_encode(&sliced(&layered())); + let mut app = app(); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + // The file's bytes carry the Place dialog's Link, which they have no file for. + let place = |app: &mut VectorcraftApp, slices: Option| { + let mut p = json!({"name": "poster.psd", "dataBase64": b64, "link": true, "showImportOptions": false}); + if let Some(s) = slices { + p["importSlices"] = json!(s); + } + crate::place::run_for_user(app, &p).unwrap(); + assert!(app.ui.dialog.is_none(), "placed without asking"); + let st = app.session.doc().unwrap(); + let [id] = st.selection.objects[..] else { panic!("one object is selected") }; + (st.doc.node(id).unwrap().kind.clone(), st.doc.slices.len()) + }; + // At first, Convert Layers to Objects with Import Slices. + let (kind, slices) = place(&mut app, None); + assert!(matches!(kind, NodeKind::Group { .. })); + assert_eq!(slices, 1); + // An `importSlices` the params give is kept. + let (kind, slices) = place(&mut app, Some(false)); + assert!(matches!(kind, NodeKind::Group { .. })); + assert_eq!(slices, 1, "no new slice"); + // Then the choices made last. + app.ui.psd_import = json!({"layers": false, "importSlices": false}); + let (kind, slices) = place(&mut app, None); + assert!(matches!(kind, NodeKind::Image(_))); + assert_eq!(slices, 1, "no new slice"); + let (_, slices) = place(&mut app, Some(true)); + assert_eq!(slices, 2, "the given importSlices brings the slice in"); + } + + #[test] + fn files_from_bytes_placed_with_link_take_the_last_choices() { + let files: Vec = ["a.psd", "b.psd"].iter().map(|n| json!({ "name": n })).collect(); + let mut app = app(); + for n in ["a.psd", "b.psd"] { + app.place.picked.push((n.to_string(), sliced(&layered()))); + } + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + // The dialog's Link is on, but files from bytes have no file to link to. + let d = Dialog::new(crate::dialogs::place::KIND, json!({"files": files, "link": true, "template": false, "showImportOptions": false})); + crate::place::confirm(&mut app, &d).unwrap(); + assert!(app.ui.dialog.is_none(), "the cursor loads without asking"); + let view = vectorcraft_engine::ViewInfo::default(); + for kind in [vectorcraft_tools::PointerKind::Down, vectorcraft_tools::PointerKind::Up] { + for r in app.session.pointer(&vectorcraft_tools::PointerEvent::new(kind, 10.0, 10.0), view).unwrap() { + if let vectorcraft_engine::UiRequest::Place(p) = r { + crate::place::place_from_cursor(&mut app, &p); + } + } + } + let st = app.session.doc().unwrap(); + let [id] = st.selection.objects[..] else { panic!("one object is placed") }; + // At first, Convert Layers to Objects with Import Slices. + assert!(matches!(st.doc.node(id).unwrap().kind, NodeKind::Group { .. })); + assert_eq!(st.doc.slices.len(), 1); + } + + #[test] + fn a_cursor_loaded_with_show_import_options_on_asks_for_each_psd_file() { + let dir = std::env::temp_dir().join(format!("vc-psd-import-asks-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let paths: Vec = ["a.psd", "b.psd"] + .iter() + .map(|n| { + let p = dir.join(n); + std::fs::write(&p, layered()).unwrap(); + p.to_string_lossy().into_owned() + }) + .collect(); + let files: Vec = paths.iter().map(|p| json!({ "path": p })).collect(); + let services = crate::Services { read: Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))), ..Default::default() }; + let mut app = VectorcraftApp::new(Session::new(), services); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + // The choices made last would place the layers without asking with Show Import Options off. + app.ui.psd_import = json!({"layers": true, "importSlices": true}); + let d = Dialog::new(crate::dialogs::place::KIND, json!({"files": files, "link": false, "template": false, "showImportOptions": true})); + crate::place::confirm(&mut app, &d).unwrap(); + assert!(app.ui.dialog.is_none(), "the cursor loads without asking"); + assert_eq!(app.session.tool_options()["count"], 2); + // A click on the canvas: the file the cursor's request names asks. + let view = vectorcraft_engine::ViewInfo::default(); + for kind in [vectorcraft_tools::PointerKind::Down, vectorcraft_tools::PointerKind::Up] { + for r in app.session.pointer(&vectorcraft_tools::PointerEvent::new(kind, 10.0, 10.0), view).unwrap() { + if let vectorcraft_engine::UiRequest::Place(p) = r { + crate::place::place_from_cursor(&mut app, &p); + } + } + } + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND), "the clicked file asks"); + std::fs::remove_dir_all(&dir).ok(); + } + + #[test] + fn scripted_places_and_places_that_give_layers_dont_ask() { + let b64 = vectorcraft_format::base64_encode(&layered()); + let mut app = app(); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + // `file.place` run as a command places at once, as before. + let r = crate::place::run(&mut app, &json!({"name": "poster.psd", "dataBase64": b64})).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(r["format"], "psd"); + // The user's place with `layers` given doesn't ask either. + crate::place::run_for_user(&mut app, &json!({"name": "poster.psd", "dataBase64": b64, "layers": false})).unwrap(); + assert!(app.ui.dialog.is_none()); + } +} diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index 3bdddb3498..238205216e 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -11,7 +11,9 @@ //! model), New Row (a row with no current colors above the first selected row, or at the top, //! with that row's new color; it recolors nothing until Merge moves colors into it), Merge and //! Separate, Randomize order or -//! saturation and brightness, Reset, the Method and Limit to Library (its folder button imports a +//! saturation and brightness, Find (with it on, the art of the selected rows shows as the preview +//! shows it, their current colors with Preview off, and the rest of the selected art shows its +//! current colors dimmed; a second click shows the art as before), Reset, the Method and Limit to Library (its folder button imports a //! library file and limits to it; a library's colours apply as its swatches: a spot colour stays a //! spot colour, and joins the document's swatches). Edit tab: a hue and //! saturation wheel with a marker per new colour (drag one; with linked handles they all turn and @@ -50,7 +52,8 @@ //! `globalAdjust` in every slider mode), `display` (the Edit tab's `smooth`, `segmented` or `bars`; //! unset: `smooth`), `themePicker` (the Color Theme Picker is on), `themePicks` (its picks, as //! `recolor.pickTheme`'s `picks`; a new list recolors the rows), `weights` (one per row, as -//! `recolor.weigh`'s; a new list moves the rows' current colors toward them). Changing `colors`, a +//! `recolor.weigh`'s; a new list moves the rows' current colors toward them), `findColors` (Find is +//! on; it shows the art so on the Assign tab, with art and rows selected). Changing `colors`, a //! preserve flag or `limitTo` reduces the rows again (and drops `weights`). use egui::{Rect, Sense, Ui, pos2, vec2}; @@ -163,7 +166,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { "preserveWhite": kept("preserveWhite", true), "preserveBlack": kept("preserveBlack", true), "preserveGrays": kept("preserveGrays", false), "limitTo": limit, "group": group, "groupName": if new_group { Some(NEW_GROUP) } else { group }, "tab": "assign", "rule": Harmony::Complementary.id(), "linked": true, - "preview": true, THEME_PICKER: false, THEME_PICKS: [], WEIGHTS: null, "__art": art, "__assign": assign, "__newGroup": new_group, + "preview": true, THEME_PICKER: false, THEME_PICKS: [], WEIGHTS: null, FIND: false, "__art": art, "__assign": assign, "__newGroup": new_group, }); let mut d = Dialog::new(KIND, fields); // Without art the rows are there from the start: limit them now (art's rows snap as they reduce). @@ -217,6 +220,8 @@ fn sync(app: &mut VectorcraftApp, d: &mut Dialog) { } snap(app, d, &mut rows); d.fields.insert("rows".into(), Value::Array(rows)); + // Find dims the preserved colors with the rows that aren't selected. + d.fields.insert(PRESERVED.into(), r["preserved"].clone()); d.fields.insert("__sel".into(), json!([])); // The new rows hold no slider edit. d.fields.remove(COMPS); @@ -590,6 +595,102 @@ fn apply_params(d: &Dialog) -> Value { p } +/// The Find button's field, and the tint of its current color that the art of the rows that +/// aren't selected shows while it is on (VectorCraft's own amount: [`Color::tinted`]). +const FIND: &str = "findColors"; +const FIND_DIM: f32 = 0.25; +/// The tints tried when a dimmed color is one a selected row lists: [`FIND_DIM`] and each lighter +/// one a percent apart, down to 1%. +const FIND_TRIES: usize = 25; +/// The colors of the art that the rows leave out (Preserve White, Black and Grays), as +/// `recolor.reduce` returned them. +const PRESERVED: &str = "__preserved"; + +/// A row's current color as `recolor.apply` matches it: an exact color (its key, parsed whatever +/// its case or spacing), or `Err` with the hex of a "#rrggbb" entry, which matches every color +/// shown as that hex. +type FindEntry = Result; + +fn find_entry(k: &Value) -> Option { + match k.as_str() { + Some(s) => ColorKey::parse(s).map(Ok).or_else(|| color_value(k).map(|c| Err(c.to_hex()))), + None => color_value(k).map(|c| Ok(ColorKey::of(&c))), + } +} + +/// While Find is on, on the Assign tab with art and rows selected: what the art previews instead of +/// [`apply_params`], as `command.batch` parameters. A first `recolor.apply` gives each current color +/// of the rows that aren't selected, and each preserved color, its [`FIND_DIM`] tint, or the nearest lighter one when that is a +/// color a selected row lists (a color a selected row also lists stays); +/// with Preview on, a second recolors the selected rows as [`apply_params`] would (the other rows +/// excluded, no color group rewritten). None otherwise, and when there is nothing to dim with +/// Preview off. OK still applies [`apply_params`]. +fn find_params(d: &Dialog) -> Option { + if !d.bool(FIND) || !d.bool("__art") || d.str("tab") == "edit" { + return None; + } + let rs = rows(d); + let sel: Vec = selection(d).into_iter().filter(|i| *i < rs.len()).collect(); + if sel.is_empty() { + return None; + } + let keys = |r: &Value| r["from"].as_array().cloned().unwrap_or_default(); + let found: Vec = sel.iter().flat_map(|&i| keys(&rs[i])).collect(); + // The selected rows' entries as `recolor.apply` reads them: exact colors and "#rrggbb" ones. + let found: Vec = found.iter().filter_map(find_entry).collect(); + let found_keys: Vec = found.iter().filter_map(|e| e.as_ref().ok().copied()).collect(); + let found_hex_entries: Vec = found.iter().filter_map(|e| e.as_ref().err().cloned()).collect(); + let found_hex: Vec = found.iter().map(|e| e.as_ref().map_or_else(Clone::clone, |k| k.color().to_hex())).collect(); + // A dimmed color must not be one the second step recolors (by its key, or by its hex as a + // "#rrggbb" entry matches): the nearest lighter tint that is none of them is taken instead. + let dimmed = |c: Color| { + (0..FIND_TRIES) + .map(|n| c.tinted(FIND_DIM - n as f32 * 0.01)) + .find(|t| !found_keys.contains(&ColorKey::of(t)) && !found_hex_entries.contains(&t.to_hex())) + .map(|t| key(&t)) + }; + // The current colors of the rows that aren't selected, and the preserved colors. + let preserved = d.fields.get(PRESERVED).and_then(Value::as_array).cloned().unwrap_or_default(); + let others = rs.iter().enumerate().filter(|(i, _)| !sel.contains(i)).flat_map(|(_, r)| keys(r)).chain(preserved); + let mut dim = serde_json::Map::new(); + // A color a selected row lists stays, and so does one shown as the same hex when either entry is + // "#rrggbb" (it matches both). Two keys of the same hex are separate colors. + let listed = |k: &Value| match find_entry(k) { + Some(Ok(key)) => found_keys.contains(&key) || found_hex_entries.contains(&key.color().to_hex()), + Some(Err(hex)) => found_hex.contains(&hex), + None => false, + }; + for k in others.filter(|k| !listed(k)) { + // A string entry keeps its own form ("#rrggbb" matches by hex); a color value goes by its key. + let name = match k.as_str() { + Some(s) => Some(s.to_string()), + None => color_value(&k).map(|c| ColorKey::of(&c).to_string()), + }; + if let (Some(to), Some(name)) = (color_value(&k).and_then(dimmed), name) { + dim.insert(name, to); + } + } + let mut commands = vec![]; + if !dim.is_empty() { + commands.push(json!({"command": CMD, "params": {"map": dim}})); + } + if d.bool("preview") { + let mut p = apply_params(d); + let mut only = rs; + for (_, r) in only.iter_mut().enumerate().filter(|(i, _)| !sel.contains(i)) { + r["exclude"] = json!(true); + } + p["map"] = Value::Array(only); + if let Some(p) = p.as_object_mut() { + for k in ["group", "groupColors", "rename"] { + p.remove(k); + } + } + commands.push(json!({"command": CMD, "params": p})); + } + (!commands.is_empty()).then(|| json!({"commands": commands})) +} + fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { sync(app, d); sync_theme(app, d); @@ -650,7 +751,15 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { } sync(app, d); if d.bool("__art") { - form::preview(app, ui, d, "Recolor Artwork", CMD, apply_params(d)); + match find_params(d) { + // Find shows the art so with Preview off too. + Some(p) => { + ui.add_space(8.0); + form::preview_check(ui, d); + form::preview_now(app, d, "Recolor Artwork", "command.batch", p); + } + None => form::preview(app, ui, d, "Recolor Artwork", CMD, apply_params(d)), + } } if let Some(c) = pick.and_then(|i| Some((i, to_color(rows(d).get(i)?)?))) { *d = super::color_picker::over_recolor(d, c.1, c.0); @@ -874,6 +983,10 @@ fn assign_tab(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut } } } + let finding = d.bool(FIND); + if widgets::icon_button_enabled(ui, "search", tl!("Find the selected colors in the artwork"), finding, d.bool("__art"), 24.0).clicked() { + d.fields.insert(FIND.into(), json!(!finding)); + } if widgets::icon_button(ui, "rotate-ccw", tl!("Reset the rows to the artwork's colors"), false, 24.0).clicked() { d.fields.remove("__reduced"); d.fields.remove(COMPS); @@ -2104,6 +2217,172 @@ mod tests { assert_eq!(new_colors(&app), [json!("rgb 0 255 0"), json!("rgb 255 255 0")]); } + /// Find previews nothing of its own while it is off, on the Edit tab, without art or without a + /// selected row. On, a first `recolor.apply` dims each current color of the other rows (a color + /// a selected row also lists stays), and with Preview on a second recolors the selected rows + /// alone, without rewriting the color group. + #[test] + fn find_dims_the_colors_of_the_rows_not_selected() { + let mut d = Dialog::new( + KIND, + json!({"rows": rows(), "__art": true, "preview": true, "method": "exact", "limitTo": "", "group": "G", "groupName": "H", "__sel": [0]}), + ); + assert_eq!(find_params(&d), None, "off"); + d.fields.insert(FIND.into(), json!(true)); + let dim = |k: &str| key(&color_value(&json!(k)).unwrap().tinted(FIND_DIM)); + let p = find_params(&d).expect("on"); + let cmds = p["commands"].as_array().unwrap(); + assert_eq!(cmds.len(), 2); + assert_eq!(cmds[0]["command"], CMD); + assert_eq!( + cmds[0]["params"]["map"], + json!({"rgb 0 0 255": dim("rgb 0 0 255"), "rgb 0 0 128": dim("rgb 0 0 128"), "rgb 0 255 0": dim("rgb 0 255 0")}) + ); + assert_eq!(dim("rgb 0 0 255"), json!("rgb 191.25 191.25 255"), "a quarter of the color, the rest white"); + let second = &cmds[1]["params"]; + assert_eq!(second["map"][0], rows()[0], "the selected row recolors as it would"); + assert_eq!((second["map"][1]["exclude"].clone(), second["map"][2]["exclude"].clone()), (json!(true), json!(true))); + assert!(second.get("group").is_none() && second.get("rename").is_none(), "{second}"); + // A color that a selected row lists as a hex stays. + let mut e = d.clone(); + let mut rs = rows(); + rs[0]["from"] = json!(["#0000ff"]); + e.fields.insert("rows".into(), json!(rs)); + let map = find_params(&e).unwrap()["commands"][0]["params"]["map"].clone(); + assert!(map.get("rgb 0 0 255").is_none() && map.get("rgb 0 0 128").is_some(), "{map}"); + // A color a selected row lists by its key keeps only that color: another key of the same hex + // dims, and a hex entry of it stays (it would dim the selected color too). + let mut e = d.clone(); + let mut rs = rows(); + rs[0]["from"] = json!(["rgb 191 191 255"]); + rs[1]["from"] = json!(["rgb 191.25 191.25 255", "#bfbfff"]); + e.fields.insert("rows".into(), json!(rs)); + let map = find_params(&e).unwrap()["commands"][0]["params"]["map"].clone(); + assert!(map.get("rgb 191.25 191.25 255").is_some() && map.get("#bfbfff").is_none(), "{map}"); + // A key is read whatever its case or spacing, as `recolor.apply` reads it. + let mut e = d.clone(); + let mut rs = rows(); + rs[0]["from"] = json!(["RGB 191 191 255"]); + rs[1]["from"] = json!(["rgb 191 191 255", "rgb 0 0 128"]); + e.fields.insert("rows".into(), json!(rs)); + let map = find_params(&e).unwrap()["commands"][0]["params"]["map"].clone(); + assert!(map.get("rgb 191 191 255").is_none() && map.get("rgb 0 0 128").is_some(), "{map}"); + // The preserved colors dim too. + let mut e = d.clone(); + e.fields.insert(PRESERVED.into(), json!(["rgb 0 0 0"])); + assert_eq!(find_params(&e).unwrap()["commands"][0]["params"]["map"]["rgb 0 0 0"], dim("rgb 0 0 0")); + // A color given as a value instead of a string dims under its key, as `recolor.apply` reads it. + let mut e = d.clone(); + let mut rs = rows(); + rs[1]["from"] = json!([[0.0, 0.0, 1.0], {"c": 0, "m": 100, "y": 100, "k": 0}]); + e.fields.insert("rows".into(), json!(rs)); + let map = find_params(&e).unwrap()["commands"][0]["params"]["map"].clone(); + assert_eq!(map["rgb 0 0 255"], dim("rgb 0 0 255"), "{map}"); + assert_eq!(map["cmyk 0 100 100 0"], dim("cmyk 0 100 100 0"), "{map}"); + // A color a selected row lists is not dimmed; with Preview off only the dimming runs. + let mut rs = rows(); + rs[2]["from"] = json!(["rgb 0 255 0", "rgb 255 0 0"]); + d.fields.insert("rows".into(), json!(rs)); + d.fields.insert("preview".into(), json!(false)); + let p = find_params(&d).unwrap(); + assert_eq!(p["commands"].as_array().map(Vec::len), Some(1)); + assert!(p["commands"][0]["params"]["map"].get("rgb 255 0 0").is_none(), "{p}"); + // A dimmed color that a selected row lists would be recolored with it: a lighter tint is taken. + let mut rs = rows(); + rs[0]["from"] = json!(["rgb 255 0 0", "rgb 191.25 191.25 255"]); + d.fields.insert("rows".into(), json!(rs)); + let p = find_params(&d).unwrap(); + let to = color_value(&p["commands"][0]["params"]["map"]["rgb 0 0 255"]).unwrap(); + assert_eq!(to.to_hex(), "#c2c2ff", "{p}"); + // So is one that a selected "#rrggbb" entry matches by its hex. + rs[0]["from"] = json!(["rgb 255 0 0", "#bfbfff"]); + d.fields.insert("rows".into(), json!(rs)); + let p = find_params(&d).unwrap(); + let to = color_value(&p["commands"][0]["params"]["map"]["rgb 0 0 255"]).unwrap(); + assert_eq!(to.to_hex(), "#c2c2ff", "{p}"); + // When the twenty tints from 25% through 6% are all listed, the 5% tint is taken. + let blue = color_value(&json!("rgb 0 0 255")).unwrap(); + let tint = |n: usize| key(&blue.tinted(FIND_DIM - n as f32 * 0.01)); + let mut from = vec![json!("rgb 255 0 0")]; + from.extend((0..20).map(tint)); + rs[0]["from"] = json!(from); + d.fields.insert("rows".into(), json!(rs)); + let p = find_params(&d).unwrap(); + assert_eq!(p["commands"][0]["params"]["map"]["rgb 0 0 255"], tint(20), "{p}"); + // Another key of the same hex matches only itself, so the tint is kept. + rs[0]["from"] = json!(["rgb 255 0 0", "rgb 191 191 255"]); + d.fields.insert("rows".into(), json!(rs)); + let p = find_params(&d).unwrap(); + assert_eq!(p["commands"][0]["params"]["map"]["rgb 0 0 255"], dim("rgb 0 0 255"), "{p}"); + // Every row selected with Preview off: nothing to show. + d.fields.insert("__sel".into(), json!([0, 1, 2])); + assert_eq!(find_params(&d), None); + for (k, v) in [("__sel", json!([])), ("__sel", json!([7])), ("tab", json!("edit")), ("__art", json!(false))] { + let mut e = d.clone(); + e.fields.insert("preview".into(), json!(true)); + e.fields.insert("__sel".into(), json!([0])); + e.fields.insert(k.into(), v.clone()); + assert_eq!(find_params(&e), None, "{k}: {v}"); + } + } + + /// In the dialog, Find with the red art's row selected shows the red art's new color and the + /// blue art dimmed, with Preview off the red art's own color; off again, the art shows as the + /// preview has it. Cancel leaves the art as it was with no undo step, and OK with Find on + /// applies the rows to all the art, as one undo step. + #[test] + fn find_shows_the_selected_rows_art_and_dims_the_rest() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + let [red, blue] = theme_setup(&mut app, &ctx); + let undo = app.session.doc().unwrap().history.undo.len(); + let set = |app: &mut VectorcraftApp, k: &str, v: Value| { + app.ui.dialog.as_mut().unwrap().fields.insert(k.into(), v); + }; + let rs = json!([{"from": ["rgb 255 0 0"], "to": "rgb 0 255 0"}, {"from": ["rgb 0 0 255"], "to": "rgb 255 255 0"}]); + set(&mut app, "rows", rs.clone()); + set(&mut app, "__sel", json!([0])); + frame(&mut app, &ctx, 0.1, vec![], 0); + let fills = |app: &VectorcraftApp| (fill_hex(app, red), fill_hex(app, blue)); + assert_eq!(fills(&app), ("#00ff00".into(), "#ffff00".into()), "off: the preview"); + set(&mut app, FIND, json!(true)); + frame(&mut app, &ctx, 0.2, vec![], 0); + assert_eq!(fills(&app), ("#00ff00".into(), "#bfbfff".into()), "on: the other art dimmed"); + set(&mut app, "preview", json!(false)); + frame(&mut app, &ctx, 0.3, vec![], 0); + assert_eq!(fills(&app), ("#ff0000".into(), "#bfbfff".into()), "Preview off: the current colors"); + set(&mut app, "__sel", json!([1])); + frame(&mut app, &ctx, 0.4, vec![], 0); + assert_eq!(fills(&app), ("#ffbfbf".into(), "#0000ff".into()), "the other row selected"); + set(&mut app, FIND, json!(false)); + frame(&mut app, &ctx, 0.5, vec![], 0); + assert_eq!(fills(&app), ("#ff0000".into(), "#0000ff".into()), "off with Preview off: the art as it is"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo, "Find records no undo step"); + set(&mut app, FIND, json!(true)); + frame(&mut app, &ctx, 0.6, vec![], 0); + crate::dialogs::cancel(&mut app); + assert!(app.ui.dialog.is_none()); + assert_eq!(fills(&app), ("#ff0000".into(), "#0000ff".into()), "Cancel: the art as it was"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); + // A black square joins the selection: Preserve Black leaves it out of the rows. + let black = square(&mut app, 70.0, "#000000"); + let undo = app.session.doc().unwrap().history.undo.len(); + app.run("select.set", json!({"ids": [red, blue, black]})).unwrap(); + app.run("ui.recolorDialog", json!({})).unwrap(); + set(&mut app, "method", json!(Method::Exact.id())); + frame(&mut app, &ctx, 1.0, vec![], 0); + set(&mut app, "rows", rs); + set(&mut app, "__sel", json!([0])); + set(&mut app, FIND, json!(true)); + frame(&mut app, &ctx, 1.1, vec![], 0); + assert_eq!(fills(&app), ("#00ff00".into(), "#bfbfff".into())); + assert_eq!(fill_hex(&app, black), "#bfbfbf", "the preserved black dims too"); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(fills(&app), ("#00ff00".into(), "#ffff00".into()), "OK applies the rows to all the art"); + assert_eq!(fill_hex(&app, black), "#000000", "and keeps the preserved black"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + } + /// In a CMYK document colors opened alone are saved as a new color group in their own model. #[test] fn a_new_group_from_colors_keeps_their_model_in_a_cmyk_document() { diff --git a/crates/ui-egui/src/dialogs/revolve.rs b/crates/ui-egui/src/dialogs/revolve.rs index 8978805ac8..1325794e00 100644 --- a/crates/ui-egui/src/dialogs/revolve.rs +++ b/crates/ui-egui/src/dialogs/revolve.rs @@ -262,7 +262,8 @@ fn extrude_controls(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) { }); } -/// Rotation presets, rotation and perspective for Extrude & Bevel, Inflate and Rotate. +/// Rotation presets, rotation and perspective for Extrude & Bevel, Inflate and Rotate, and the +/// classic 3D effects, which have the track cube below the presets. fn view_controls(ui: &mut egui::Ui, d: &mut Dialog) { heading(ui, tl!("Rotation")); let names = [ @@ -296,6 +297,9 @@ fn view_controls(ui: &mut egui::Ui, d: &mut Dialog) { d.fields.extend([("rotationX".into(), json!(x)), ("rotationY".into(), json!(y)), ("rotationZ".into(), json!(z))]); } }); + if vectorcraft_effects::is_classic_three_d(&d.str("__effect")) { + super::three_d_classic::track_cube(ui, d); + } for (key, name) in [("rotationX", tl!("Rotation X")), ("rotationY", tl!("Rotation Y")), ("rotationZ", tl!("Rotation Z"))] { number(ui, d, key, name, (-180.0, 180.0), "°", 2, None); } diff --git a/crates/ui-egui/src/dialogs/revolve/tests.rs b/crates/ui-egui/src/dialogs/revolve/tests.rs index fd802f83f0..834f873e1e 100644 --- a/crates/ui-egui/src/dialogs/revolve/tests.rs +++ b/crates/ui-egui/src/dialogs/revolve/tests.rs @@ -52,6 +52,22 @@ impl Harness { } } + /// Scrolls the dialog's body to its end with the wheel over `text`, and lets the scroll finish. + fn scroll_to_end(&mut self, text: &str) { + let p = self.rect(text).center(); + let wheel = Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: vec2(0.0, -4000.0), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }; + self.frame(vec![Event::PointerMoved(p), wheel]); + for _ in 0..60 { + self.frame(vec![]); + } + } + fn rect(&self, text: &str) -> Rect { self.texts.iter().find(|(s, _)| s == text).map(|(_, r)| *r).unwrap_or_else(|| panic!("missing text {text:?}")) } @@ -61,6 +77,11 @@ impl Harness { self.ctx.read_response(Id::unique(id)).unwrap().rect } + /// The open dialog's track cube. + fn cube_id(&self) -> Id { + super::super::three_d_classic::cube_id(&self.app.ui.dialog.as_ref().unwrap().kind) + } + fn click(&mut self, p: Pos2) { self.frame(vec![Event::PointerMoved(p), button(p, true)]); self.frame(vec![button(p, false)]); @@ -338,17 +359,12 @@ fn classic_extrude_bevel_shows_its_options_and_applies_as_one_step() { } h.click(h.rect("Lighting").center()); h.settle(); - for text in [ - "Surface", - "Plastic", - "Light Intensity", - "Ambient Light", - "Highlight Intensity", - "Highlight Size", - "Blend Steps", - "Shading Color", - "Draw Hidden Faces", - ] { + for text in ["Surface", "Plastic", "Move Light to Back", "Light Intensity"] { + h.rect(text); + } + // The lighting sphere makes the tab taller than the dialog's body, which scrolls. + h.scroll_to_end("Light Intensity"); + for text in ["Ambient Light", "Highlight Intensity", "Highlight Size", "Blend Steps", "Shading Color", "Draw Hidden Faces"] { h.rect(text); } assert!(h.ctx.read_response(Id::unique(("revolve-reset", "highlightSize"))).unwrap().enabled()); @@ -399,7 +415,11 @@ fn classic_revolve_shows_its_options_and_applies_as_one_step() { } h.click(h.rect("Lighting").center()); h.settle(); - for text in ["Surface", "Plastic", "Light Intensity", "Ambient Light", "Highlight Size", "Blend Steps", "Shading Color"] { + for text in ["Surface", "Plastic", "Move Light to Back", "Light Intensity"] { + h.rect(text); + } + h.scroll_to_end("Light Intensity"); + for text in ["Ambient Light", "Highlight Size", "Blend Steps", "Shading Color"] { h.rect(text); } assert!(!h.texts.iter().any(|(t, _)| t == "Draw Hidden Faces"), "every face is drawn"); @@ -437,7 +457,11 @@ fn classic_rotate_shows_its_options_and_applies_as_one_step() { assert!(!h.texts.iter().any(|(t, _)| t == "Object" || t == "Depth" || t == "Angle"), "no Object tab"); h.click(h.rect("Lighting").center()); h.settle(); - for text in ["Surface", "Diffuse", "Light Intensity", "Ambient Light", "Blend Steps", "Shading Color"] { + for text in ["Surface", "Diffuse", "Move Light to Back", "Light Intensity"] { + h.rect(text); + } + h.scroll_to_end("Light Intensity"); + for text in ["Ambient Light", "Blend Steps", "Shading Color"] { h.rect(text); } assert!( @@ -460,6 +484,88 @@ fn classic_rotate_shows_its_options_and_applies_as_one_step() { assert_eq!(h.app.session.doc().unwrap().doc, before); } +/// The classic effects' track cube: a drag on its face turns the object live and the presets show +/// Custom, Escape during a drag puts the angles back, the ring turns Z alone, the arrow keys turn +/// it with the keyboard focus, and OK keeps it all as one undo step. The newer effects have no cube. +#[test] +fn the_track_cube_turns_the_classic_effects_live_in_one_undo_step() { + use vectorcraft_effects::{CLASSIC_EXTRUDE, CLASSIC_REVOLVE, CLASSIC_ROTATE, EXTRUDE, ROTATE}; + let square = "M100 100 L200 100 L200 200 L100 200 Z"; + for effect in [EXTRUDE, ROTATE] { + let mut h = Harness::with(square, effect, vec2(1400.0, 1000.0)); + h.app.ui.dialog.as_mut().unwrap().fields.insert("__tab".into(), json!("rotation")); + h.settle(); + assert!(!h.texts.iter().any(|(t, _)| t == "Track cube"), "{effect} has no track cube"); + } + for effect in [CLASSIC_EXTRUDE, CLASSIC_REVOLVE] { + let mut h = Harness::with(square, effect, vec2(1400.0, 1000.0)); + h.app.ui.dialog.as_mut().unwrap().fields.insert("__tab".into(), json!("rotation")); + h.settle(); + h.rect("Track cube"); + } + let mut h = Harness::with(square, CLASSIC_ROTATE, vec2(1400.0, 1000.0)); + let before = h.app.session.doc().unwrap().doc.clone(); + h.settle(); + h.rect("Off-Axis Front"); + let start = ["rotationX", "rotationY", "rotationZ"].map(|k| h.value(k)); + let cube = h.ctx.read_response(h.cube_id()).unwrap().rect; + // A face, dragged right: the object turns, the document previews it, and the preset is Custom. + h.drag(cube.center(), vec2(30.0, 0.0)); + let turned = ["rotationX", "rotationY", "rotationZ"].map(|k| h.value(k)); + assert_ne!(turned, start, "the drag turned the object"); + h.rect("Custom"); + let fx = |h: &Harness| { + let state = h.app.session.doc().unwrap(); + state.doc.node(state.selection.objects[0]).unwrap().appearance.effects[0].params.clone() + }; + assert_eq!(fx(&h)["rotationY"].as_f64(), Some(turned[1]), "the preview follows the cube"); + // Escape during a drag puts the angles back and keeps the dialog open. + let p = cube.center(); + h.frame(vec![Event::PointerMoved(p), button(p, true)]); + h.frame(vec![Event::PointerMoved(p + vec2(0.0, 30.0))]); + h.frame(vec![Event::PointerMoved(p + vec2(0.0, 40.0))]); + assert_ne!(h.value("rotationX"), turned[0]); + h.frame(vec![Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }]); + h.frame(vec![button(p + vec2(0.0, 40.0), false)]); + h.settle(); + assert!(h.app.ui.dialog.is_some(), "Escape ends the drag, not the dialog"); + assert_eq!(["rotationX", "rotationY", "rotationZ"].map(|k| h.value(k)), turned); + // The ring turns in the screen plane: Z alone. + let top = pos2(cube.center().x, cube.center().y - 53.5); + h.drag(top, vec2(12.0, 2.0)); + assert_eq!((h.value("rotationX"), h.value("rotationY")), (turned[0], turned[1])); + assert!(h.value("rotationZ") > turned[2], "clockwise: {} -> {}", turned[2], h.value("rotationZ")); + // With the keyboard focus (the drags gave it), Right turns about the screen's vertical axis. + let z = h.value("rotationZ"); + assert!(h.ctx.memory(|m| m.has_focus(h.cube_id())), "the drag gave the cube the keyboard focus"); + h.frame(vec![Event::Key { key: egui::Key::PageUp, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }]); + h.settle(); + assert!((h.value("rotationZ") - (z - 1.0)).abs() < 0.011, "Page Up turns 1° counterclockwise"); + let y = h.value("rotationY"); + h.frame(vec![Event::Key { key: egui::Key::ArrowRight, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }]); + h.settle(); + assert_ne!(h.value("rotationY"), y, "Right turns the cube"); + let last = h.value("rotationZ"); + dialogs::confirm(&mut h.app).unwrap(); + assert_eq!(fx(&h)["rotationZ"].as_f64(), Some(last)); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc().unwrap().doc, before); +} + +/// A mixed rotation (the 3D and Materials panel's selected effects differ) leaves the cube off. +#[test] +fn the_track_cube_is_off_while_a_rotation_is_mixed() { + use vectorcraft_effects::CLASSIC_ROTATE; + let mut h = Harness::with("M100 100 L200 100 L200 200 L100 200 Z", CLASSIC_ROTATE, vec2(1400.0, 1000.0)); + h.app.ui.dialog.as_mut().unwrap().fields.insert("rotationX".into(), Value::Null); + h.settle(); + let cube = h.ctx.read_response(h.cube_id()).unwrap().rect; + h.drag(cube.center(), vec2(30.0, 0.0)); + let d = h.app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.fields.get("rotationX"), Some(&Value::Null)); + assert!(!h.ctx.read_response(h.cube_id()).unwrap().sense.senses_drag()); +} + #[test] fn extrude_bevel_options_enable_with_a_bevel_shape() { let mut h = Harness::with("M100 100 L200 100 L200 200 L100 200 Z", vectorcraft_effects::EXTRUDE, vec2(1400.0, 1000.0)); diff --git a/crates/ui-egui/src/dialogs/revolve_gizmo.rs b/crates/ui-egui/src/dialogs/revolve_gizmo.rs index c99e7ab83e..a7fe804679 100644 --- a/crates/ui-egui/src/dialogs/revolve_gizmo.rs +++ b/crates/ui-egui/src/dialogs/revolve_gizmo.rs @@ -42,8 +42,10 @@ fn drag_id() -> Id { Id::unique("revolve-gizmo-drag") } +/// Is a rotation or light gesture in progress, on the artboard or on the classic 3D effects' track +/// cube? pub(crate) fn dragging(ctx: &egui::Context) -> bool { - ctx.data(|m| m.get_temp::(drag_id())).is_some() + ctx.data(|m| m.get_temp::(drag_id())).is_some() || super::three_d_classic::cube_dragging(ctx) } pub(super) fn clear(ctx: &egui::Context) { diff --git a/crates/ui-egui/src/dialogs/revolve_lights.rs b/crates/ui-egui/src/dialogs/revolve_lights.rs index 1a4116b7ee..3d522b624a 100644 --- a/crates/ui-egui/src/dialogs/revolve_lights.rs +++ b/crates/ui-egui/src/dialogs/revolve_lights.rs @@ -1,6 +1,8 @@ //! The lighting widget on the 3D and Materials panel's Lighting tab for Extrude & Bevel, Revolve, -//! Inflate and Rotate: a sphere that shows each of the effect's lights +//! Inflate and Rotate, and on the Lighting tab of the 3D (Classic) effects in both the panel and the +//! options dialog: a sphere that shows each of the effect's lights //! at its Rotation and Height, a filled sun in front of the object and a hollow one behind it. +//! The 3D (Classic) effects' lights have no color, so their suns are white. //! Dragging a light moves it on its side of the object, a press selects it in the list of lights, //! and the button below the sphere moves the selected light to the back or the front of the object. //! Each light takes the keyboard focus, where the arrow keys move it, and has a name for screen @@ -82,15 +84,20 @@ fn round(n: f64) -> f64 { } /// The effect's lights: each light of its list, or its single light, with the effect's defaults for -/// the settings a light leaves out or the selected effects hold with different values (null). +/// the settings a light leaves out or the selected effects hold with different values (null). A 3D +/// (Classic) effect's lights are white whatever color a list light carries, since it shades +/// without light color. pub(crate) fn lights(d: &Dialog) -> Vec { - let defaults = vectorcraft_effects::default_params(&d.str("__effect")).unwrap_or(json!({})); + let effect = d.str("__effect"); + let colored = !vectorcraft_effects::is_classic_three_d(&effect); + let defaults = vectorcraft_effects::default_params(&effect).unwrap_or(json!({})); let list = explicit_lights(d).cloned().unwrap_or_else(|| vec![light_record(d)]); list.iter() .map(|light| { let value = |key: &str, field: &str| light.get(key).filter(|v| !v.is_null()).or_else(|| defaults.get(field)).cloned().unwrap_or(Value::Null); - let [r, g, b] = value("color", "lightColor") + let color = if colored { value("color", "lightColor") } else { Value::Null }; + let [r, g, b] = color .as_str() .filter(|s| s.len() == 7 && s.starts_with('#')) .and_then(vectorcraft_color::Color::from_hex) @@ -143,10 +150,12 @@ pub(super) fn show(ui: &mut egui::Ui, d: &mut Dialog) { let order = (0..lights.len()).filter(|&i| i != current).chain([current]); let mut moved = None; let enabled = ui.is_enabled(); + // The panel and a 3D (Classic) options dialog can both show the sphere at once. + let panel = d.bool("__panel"); for index in order { let light = lights.get(index).copied().unwrap_or(first); let at = center + light.offset() * radius; - let id = Id::unique(("three-d-lighting-widget", index)); + let id = Id::unique(("three-d-lighting-widget", panel, index)); let response = ui.interact(Rect::from_center_size(at, Vec2::splat((SUN + 4.0) * 2.0)), id, Sense::click_and_drag()); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Slider, enabled, light.name(index))); // A light the pointer took, or that the keyboard focus reached, becomes the selected light and diff --git a/crates/ui-egui/src/dialogs/save_pdf.rs b/crates/ui-egui/src/dialogs/save_pdf.rs index 225c2cee52..4f8bdf7667 100644 --- a/crates/ui-egui/src/dialogs/save_pdf.rs +++ b/crates/ui-egui/src/dialogs/save_pdf.rs @@ -325,6 +325,19 @@ pub(super) fn pick(ui: &mut egui::Ui, d: &mut Dialog, path: &str, wid true } +/// [`pick`] with a first entry, `unset`, for a setting that isn't set: shown while the value at +/// `path` isn't one of the choices, and stored as [`vectorcraft_pdf::UNSET_CHOICE`] when chosen. +fn pick_or_unset(ui: &mut egui::Ui, d: &mut Dialog, path: &str, width: f32, unset: &str) -> bool { + let current = choice_index::(d, path).map_or(0, |i| i + 1); + let lang = crate::i18n::current(); + let labels: Vec<&str> = std::iter::once(unset).chain(T::LABELS.iter().map(|label| choice_label(lang, path, label))).collect(); + let label = labels.get(current).copied().unwrap_or(unset); + let Some(i) = widgets::dropdown_with(ui, path, label, &labels, width, |_| true) else { return false }; + let id = i.checked_sub(1).and_then(|i| T::IDS.get(i)).copied().unwrap_or(vectorcraft_pdf::UNSET_CHOICE); + set(d, path, json!(id)); + true +} + /// Printer mark styles use adjectives, separately from interface language names. pub(super) fn choice_label<'a>(lang: crate::i18n::Lang, path: &str, label: &'a str) -> &'a str { if path == "marks.kind" { crate::i18n::tr_ctx(lang, "mark-style", label) } else { crate::i18n::tr(lang, label) } @@ -663,8 +676,9 @@ fn output(ui: &mut egui::Ui, d: &mut Dialog) { .collect(); row(ui, tl!("Destination:"), |ui| profile_pick(ui, d, "output.destination", &destinations, 2, converting)); row(ui, tl!("Profile inclusion:"), |ui| { - // A standard decides whether colours are tagged. - ui.add_enabled_ui(standard == Standard::None, |ui| pick::(ui, d, "output.profiles", 300.0, |_| true)); + // A standard decides whether colours are tagged. Not set, colors are untagged and gray and + // RGB images keep their profiles (shown as Default). + ui.add_enabled_ui(standard == Standard::None, |ui| pick_or_unset::(ui, d, "output.profiles", 300.0, tl!("Default"))); }); if standard.cmyk_only() { note(ui, tl!("PDF/X-1a files are CMYK: every colour is converted to the destination (blank: the output intent's CMYK profile), untagged.")); diff --git a/crates/ui-egui/src/dialogs/tests_modal.rs b/crates/ui-egui/src/dialogs/tests_modal.rs index c202094102..06eef4d2c6 100644 --- a/crates/ui-egui/src/dialogs/tests_modal.rs +++ b/crates/ui-egui/src/dialogs/tests_modal.rs @@ -532,7 +532,7 @@ fn simplify_slider_and_dialog_simplify_only_the_direct_selected_part_of_a_path() let anchors: Vec<_> = (0..=40).map(|i| json!({"x": 20 + i * 8, "y": 150.0 + 60.0 * (f64::from(i) / 6.0).sin()})).collect(); let id = app.run("path.create", json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap(); let path = |app: &VectorcraftApp| { - app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).and_then(|n| n.path_data()).expect("a path").subpaths[0].anchors.clone() + app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).and_then(|n| n.path_data()).expect("a path").subpaths[0].anchors.to_vec() }; let original = path(&app); let run: Vec<_> = (10..=30).map(|i| json!([0, i])).collect(); diff --git a/crates/ui-egui/src/dialogs/tests_screens.rs b/crates/ui-egui/src/dialogs/tests_screens.rs index e26c82de60..b99405ecfe 100644 --- a/crates/ui-egui/src/dialogs/tests_screens.rs +++ b/crates/ui-egui/src/dialogs/tests_screens.rs @@ -1547,3 +1547,78 @@ fn an_artboard_name_stays_with_its_document() { assert_eq!(names(&app, 1), ["Artboard 1", "Artboard 2"]); assert!(log.borrow().is_empty(), "renaming must not export"); } + +/// Escape or Enter in the first frame that draws an artboard's name field closes the field, and +/// the dialog stays open. +#[test] +fn a_key_in_the_first_frame_of_an_artboard_name_closes_it() { + for view in ["grid", "list"] { + for key in [egui::Key::Escape, egui::Key::Enter] { + let (mut app, log) = app(2, true); + open(&mut app); + set(&mut app, "view", json!(view)); + let mut h = ScreensFrame::new(); + let out = h.settle(&mut app); + let at = screen_text_at(&out, "1 Artboard 1"); + 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() }], + ); + } + // The double-click opened the field in the last frame; this frame draws it first. + h.time += 0.1; + let input = egui::RawInput { + events: vec![egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }], + 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!(!h.ctx.egui_wants_keyboard_input(), "{view}, {key:?}: the field closes"); + assert_eq!(kind(&app), Some(export_for_screens::KIND), "{view}, {key:?}"); + assert_eq!(app.session.active().unwrap().doc.artboards[0].name, "Artboard 1", "{view}, {key:?}"); + assert!(log.borrow().is_empty(), "{view}, {key:?}: the key must not export"); + } + } +} + +/// A double-click on an earlier artboard's name, both clicks in one frame, renames the artboard +/// whose name was being typed before it opens the new field. +#[test] +fn double_clicking_another_artboard_name_keeps_the_typed_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 double_click = |h: &mut ScreensFrame, app: &mut VectorcraftApp, at: egui::Pos2| { + h.frame(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(app, events); + h.settle(app); + }; + let out = h.settle(&mut app); + let first = screen_text_at(&out, "1 Artboard 1"); + double_click(&mut h, &mut app, screen_text_at(&out, "2 Artboard 2")); + assert!(h.ctx.egui_wants_keyboard_input(), "{view}: the double-click opens the name"); + h.frame(&mut app, vec![egui::Event::Text("Typed".into())]); + h.time += 1.0; + double_click(&mut h, &mut app, first); + let names: Vec = app.session.active().unwrap().doc.artboards.iter().map(|a| a.name.clone()).collect(); + assert_eq!(names, ["Artboard 1", "Typed"], "{view}"); + assert!(h.ctx.egui_wants_keyboard_input(), "{view}: the second double-click opens its name"); + assert_eq!(field(&app, "boards"), before, "{view}"); + assert!(log.borrow().is_empty(), "{view}: renaming must not export"); + } +} diff --git a/crates/ui-egui/src/dialogs/tests_track_cube.rs b/crates/ui-egui/src/dialogs/tests_track_cube.rs new file mode 100644 index 0000000000..9b99efb105 --- /dev/null +++ b/crates/ui-egui/src/dialogs/tests_track_cube.rs @@ -0,0 +1,184 @@ +//! The track cube's rotations, grips and gestures. +use super::*; +use egui::pos2; +use vectorcraft_effects::ROTATION_PRESETS; + +const SAMPLES: [[f64; 3]; 6] = + [[0.0, 0.0, 0.0], [-21.88, -23.4, 9.06], [27.0, -39.0, 53.0], [170.0, 10.0, -95.5], [-120.0, 75.0, 33.0], [45.0, -35.26, 30.0]]; + +fn close(a: [f64; 3], b: [f64; 3]) -> bool { + a.iter().zip(b).all(|(a, b)| tidy(a - b).abs() < 0.011) +} + +fn same_rotation(a: M3, b: M3) -> bool { + a.iter().flatten().zip(b.iter().flatten()).all(|(a, b)| (a - b).abs() < 1e-3) +} + +/// The cube turns as the 3D effects turn the art: each object axis lands where the effects' own +/// view rotation puts it. +#[test] +fn the_cube_rotates_as_the_effects_do() { + for angles in SAMPLES { + let m = rotation(angles); + let view = vectorcraft_three_d::Revolve { rotation_x: angles[0], rotation_y: angles[1], rotation_z: angles[2], ..Default::default() }; + for (axis, p) in view.view_axes().into_iter().enumerate() { + assert!((m[0][axis] - p.x).abs() < 1e-9 && (m[1][axis] - p.y).abs() < 1e-9, "{angles:?} axis {axis}"); + } + } +} + +/// Reading the angles back gives the same angles, presets included, Back's 180° and the gimbal +/// positions Left and Right (Y at ±90°) among them. +#[test] +fn angles_read_back_as_they_were_set() { + for angles in SAMPLES.into_iter().chain(ROTATION_PRESETS.iter().map(|(_, a)| *a)) { + let back = angles_of(rotation(angles), angles); + assert!(close(back, angles), "{angles:?} read back as {back:?}"); + assert!(same_rotation(rotation(back), rotation(angles))); + } + assert_eq!(angles_of(rotation([0.0, 180.0, 0.0]), [0.0, 180.0, 0.0]), [0.0, 180.0, 0.0], "Back stays Back, not -180°"); +} + +#[test] +fn angles_stay_in_the_fields_range_to_a_hundredth() { + assert_eq!(tidy(180.0), 180.0); + assert_eq!(tidy(-180.0), 180.0); + assert_eq!(tidy(190.004), -170.0); + assert_eq!(tidy(-0.001), 0.0); + assert!(tidy(-0.001).is_sign_positive()); +} + +fn drag(grip: Grip, angles: [f64; 3], from: Pos2, to: Pos2, shift: bool) -> [f64; 3] { + let mut g = + CubeDrag { grip, matrix: rotation(angles), origin: from, last: from, lock: None, fields: Default::default(), pass: 0, owner: Id::NULL }; + // In five steps, as a pointer moves. + let mut near = angles; + for k in 1..=5 { + let p = from + (to - from) * (k as f32 / 5.0); + g.matrix = drag_turn(&mut g, p, pos2(0.0, 0.0), shift); + g.last = p; + near = angles_of(g.matrix, near); + } + near +} + +/// The ring turns in the screen plane, which the effects apply last: only Z changes, by the angle +/// swept, clockwise on the screen. +#[test] +fn the_ring_turns_z_only() { + for angles in SAMPLES { + let after = drag(Grip::Ring, angles, pos2(0.0, -53.0), pos2(53.0, 0.0), false); + assert!(close(after, [angles[0], angles[1], angles[2] + 90.0]), "{angles:?} -> {after:?}"); + } +} + +/// An edge turns about its own object axis. The effects turn X first, so an X edge changes X alone. +#[test] +fn an_x_edge_turns_x_only_and_other_edges_keep_their_axis() { + let start = [-21.88, -23.4, 9.06]; + let after = drag(Grip::Edge(0), start, pos2(0.0, 0.0), pos2(0.0, -40.0), false); + assert!((after[0] - start[0]).abs() > 5.0, "X turned: {after:?}"); + assert!((after[1] - start[1]).abs() < 0.02 && (after[2] - start[2]).abs() < 0.02, "Y and Z kept: {after:?}"); + for axis in 0..3 { + let after = drag(Grip::Edge(axis), start, pos2(0.0, 0.0), pos2(30.0, -30.0), false); + let (m0, m1) = (rotation(start), rotation(after)); + let column = |m: M3| [m[0][axis], m[1][axis], m[2][axis]]; + let (a, b) = (column(m0), column(m1)); + assert!(a.iter().zip(b).all(|(a, b)| (a - b).abs() < 1e-3), "axis {axis} stays put: {a:?} {b:?}"); + assert!(!same_rotation(m0, m1), "axis {axis}: the cube turned"); + } +} + +/// A face drag across the screen turns about the screen's vertical axis, the front toward the +/// drag; Shift keeps a slanted drag to that axis. +#[test] +fn a_face_drag_turns_the_front_toward_the_pointer_and_shift_keeps_one_axis() { + let front = [0.0, 0.0, 0.0]; + let right = drag(Grip::Face, front, pos2(0.0, 0.0), pos2(40.0, 0.0), false); + assert!(close(right, [0.0, 20.0, 0.0]), "{right:?}"); + // The front (+Z) turns toward +X. + assert!(rotation(right)[0][2] > 0.3); + let down = drag(Grip::Face, front, pos2(0.0, 0.0), pos2(0.0, 40.0), false); + assert!(close(down, [-20.0, 0.0, 0.0]), "{down:?}"); + assert!(rotation(down)[1][2] > 0.3, "the front turns down"); + let slanted = drag(Grip::Face, front, pos2(0.0, 0.0), pos2(40.0, 12.0), true); + assert!(close(slanted, [0.0, 20.0, 0.0]), "Shift across: {slanted:?}"); + let steep = drag(Grip::Face, front, pos2(0.0, 0.0), pos2(10.0, -40.0), true); + assert!(close(steep, [20.0, 0.0, 0.0]), "Shift up: {steep:?}"); + let free = drag(Grip::Face, front, pos2(0.0, 0.0), pos2(40.0, 12.0), false); + assert!(free[0].abs() > 1.0, "without Shift a slanted drag also tilts: {free:?}"); +} + +/// A gesture ends when the cube stops being drawn during it (its dialog closed, or the Rotation tab +/// was left), so Escape is not held back for a cube that is no longer there. +#[test] +fn a_drag_ends_when_the_cube_is_no_longer_drawn() { + let ctx = egui::Context::default(); + let run = |draw: &mut dyn FnMut(&mut egui::Ui)| ctx.run_ui(Default::default(), draw).textures_delta.clear(); + run(&mut |ui| { + let pass = ui.ctx().cumulative_pass_nr(); + let drag = CubeDrag { + grip: Grip::Face, + matrix: rotation([0.0; 3]), + origin: Pos2::ZERO, + last: Pos2::ZERO, + lock: None, + fields: Default::default(), + pass, + owner: Id::NULL, + }; + ui.data_mut(|m| m.insert_temp(cube_drag_id(), drag)); + assert!(cube_dragging(ui.ctx())); + }); + assert!(cube_dragging(&ctx), "the next pass still sees the gesture"); + for _ in 0..2 { + run(&mut |_| {}); + } + assert!(!cube_dragging(&ctx), "two passes without the cube end the gesture"); +} + +/// With the 3D and Materials panel and a 3D dialog both showing a cube, a gesture on one cube is +/// left alone by the other: Escape there does not put the first cube's settings into it. +#[test] +fn a_cube_leaves_a_gesture_on_the_other_cube_alone() { + let ctx = egui::Context::default(); + let mut d = Dialog::new("effect", json!({ "rotationX": 10.0, "rotationY": 0.0, "rotationZ": 0.0 })); + let escape = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + let input = egui::RawInput { events: vec![escape], ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + let pass = ui.ctx().cumulative_pass_nr(); + let other = CubeDrag { + grip: Grip::Face, + matrix: rotation([50.0, 0.0, 0.0]), + origin: Pos2::ZERO, + last: Pos2::ZERO, + lock: None, + fields: json!({ "rotationX": 50.0, "rotationY": 0.0, "rotationZ": 0.0 }).as_object().cloned().unwrap_or_default(), + pass, + owner: cube_id(crate::panels::three_d::ID), + }; + assert_ne!(cube_id(crate::panels::three_d::ID), cube_id(&d.kind), "each cube has its own focus"); + ui.data_mut(|m| m.insert_temp(cube_drag_id(), other)); + track_cube(ui, &mut d); + }); + out.textures_delta.clear(); + assert_eq!(d.f64("rotationX", 0.0), 10.0, "the dialog keeps its own rotation"); + // The button is up in that pass, and the other cube, drawn later, still has the release to handle. + assert!(ctx.data(|m| m.get_temp::(cube_drag_id())).is_some(), "the other cube's gesture is still there"); +} + +/// The centre is on the front face, the ring's band on the ring, and an edge's middle on that edge. +#[test] +fn grips_follow_what_is_under_the_pointer() { + let m = rotation([-21.88, -23.4, 9.06]); + let center = pos2(100.0, 100.0); + assert_eq!(grip_at(m, center, center), Grip::Face); + assert_eq!(grip_at(m, center, center + vec2(0.0, -(RING_IN + RING_OUT) / 2.0)), Grip::Ring); + for (i, j, axis) in edges().filter(|&(i, _, axis)| edge_visible(m, i, axis)) { + let middle = corner(m, center, i) + (corner(m, center, j) - corner(m, center, i)) * 0.5; + assert_eq!(grip_at(m, center, middle), Grip::Edge(axis), "edge {i}-{j}"); + } + // Facing front: four faces are edge-on and hidden, so only the front's edges show. + let m = rotation([0.0, 0.0, 0.0]); + assert_eq!(edges().filter(|&(i, _, axis)| edge_visible(m, i, axis)).count(), 4); +} diff --git a/crates/ui-egui/src/dialogs/text_import.rs b/crates/ui-egui/src/dialogs/text_import.rs index a52e9f47fe..99128cc321 100644 --- a/crates/ui-egui/src/dialogs/text_import.rs +++ b/crates/ui-egui/src/dialogs/text_import.rs @@ -165,4 +165,25 @@ mod tests { assert_eq!(t.plain_text(), "one two\nthree", "one paragraph per block"); assert_eq!(st.history.undo.len(), 1); } + + /// A text file dropped on a canvas is placed by the dialog's OK in the document it was dropped + /// on, even when another document became active meanwhile. + #[test] + fn a_dropped_text_files_ok_places_in_the_document_it_was_dropped_on() { + use crate::place::{DropAt, DropTarget}; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + for _ in 0..2 { + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + } + app.session.set_active(0); + let st = app.session.doc().unwrap(); + let target = DropTarget::Place(DropAt { doc: st.uid, reverts: st.reverts, at: vectorcraft_geom::Point::new(100.0, 100.0), embed: true }); + crate::place::drop_files(&mut app, vec![(target, ("notes.txt".into(), None, b"one".to_vec()))]); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND)); + app.session.set_active(1); + super::super::confirm(&mut app).unwrap(); + let objects = |i: usize| app.session.documents()[i].doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum::(); + assert_eq!((objects(0), objects(1)), (1, 0), "placed in the document it was dropped on"); + assert_eq!(app.session.active_index(), Some(0)); + } } diff --git a/crates/ui-egui/src/dialogs/three_d_classic.rs b/crates/ui-egui/src/dialogs/three_d_classic.rs index 22c18df97e..e8c0e5c122 100644 --- a/crates/ui-egui/src/dialogs/three_d_classic.rs +++ b/crates/ui-egui/src/dialogs/three_d_classic.rs @@ -1,15 +1,17 @@ //! The own controls of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic) in the //! compact 3D dialog: the extrude and bevel options, or the revolve options, on the Object tab -//! (Rotate (Classic) has none), and the surface with its lights, highlight, blend steps, shading -//! color and Preserve Spot Colors on the Lighting tab. Position (presets, rotation, perspective) is the Rotation tab every 3D -//! effect shares. +//! (Rotate (Classic) has none), and the surface with its lighting sphere, lights, highlight, blend +//! steps, shading color and Preserve Spot Colors on the Lighting tab. Position (presets, rotation, perspective) is the Rotation tab every 3D +//! effect shares; the classic effects add the track cube to it ([`track_cube`]). +use egui::{Color32, Id, Pos2, Rect, Sense, Stroke, Vec2, vec2}; use serde_json::{Value, json}; use vectorcraft_doc::Unit; use vectorcraft_effects::{CLASSIC_EXTRUDE, CLASSIC_REVOLVE, CLASSIC_ROTATE}; use super::revolve::{c3, choice, heading, label, light_list, light_record, number, reset_dot, selected_light, store_selected, toggle}; use crate::state::Dialog; +use crate::theme::Tokens; /// Depth and cap, then the bevel: its shape, its height and whether it is added around the shape /// or carved into it. @@ -40,16 +42,18 @@ pub(super) fn revolve_controls(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) { choice(ui, d, "edge", tl!("Axis side"), &sides); } -/// The surface, then for Diffuse and Plastic the lights, Ambient Light, the highlight (Plastic -/// only, and not for Rotate (Classic), which has no Plastic surface), Blend Steps, Shading Color and -/// Preserve Spot Colors (unavailable while Shading Color is Custom); Draw Hidden Faces last, for Extrude & Bevel (Classic) (Revolve (Classic) draws every face, and -/// Rotate (Classic)'s plane is seen from either side). +/// The surface, then for Diffuse and Plastic the lighting sphere, the lights, Ambient Light, the +/// highlight (Plastic only, and not for Rotate (Classic), which has no Plastic surface), Blend Steps, +/// Shading Color and Preserve Spot Colors (unavailable while Shading Color is Custom); Draw Hidden +/// Faces last, for Extrude & Bevel (Classic) (Revolve (Classic) draws every face, and Rotate +/// (Classic)'s plane is seen from either side). The sphere shows in the dialog as well as in the panel. pub(super) fn surface_controls(ui: &mut egui::Ui, d: &mut Dialog) { let id = d.str("__effect"); let effect = if id == CLASSIC_ROTATE { CLASSIC_ROTATE } else { CLASSIC_EXTRUDE }; choice(ui, d, "surface", tl!("Surface"), &options_of(effect, "surface")); let surface = d.str("surface"); ui.add_enabled_ui(surface == "diffuse" || surface == "plastic", |ui| { + super::revolve_lights::show(ui, d); light_list(ui, d); let mut selected = selected_light(d); let before = light_record(&selected); @@ -113,3 +117,403 @@ fn shading_custom(ui: &mut egui::Ui, d: &mut Dialog) { } }); } + +/// The settings the track cube turns, as every 3D effect names them. +const ROTATION_KEYS: [&str; 3] = ["rotationX", "rotationY", "rotationZ"]; +/// The track cube's box side, its cube's half edge, and its ring's inner and outer radius (points). +const CUBE_BOX: f32 = 124.0; +const CUBE_HALF: f32 = 25.0; +const RING_IN: f32 = 47.0; +const RING_OUT: f32 = 60.0; +/// How far an edge reaches for the pointer (points). +const EDGE_REACH: f32 = 5.0; +/// Degrees one point of pointer movement turns the cube. +const DEGREES_PER_POINT: f64 = 0.5; + +/// A 3×3 rotation, rows first. +type M3 = [[f64; 3]; 3]; + +/// The rotation that X, Y and Z angles in degrees make, as the 3D effects apply them: X first, then +/// Y, then Z, in view space (x right, y down, z toward the viewer). +fn rotation(angles: [f64; 3]) -> M3 { + let [(sx, cx), (sy, cy), (sz, cz)] = angles.map(|a| a.to_radians().sin_cos()); + [[cz * cy, cz * sy * sx - sz * cx, cz * sy * cx + sz * sx], [sz * cy, sz * sy * sx + cz * cx, sz * sy * cx - cz * sx], [-sy, cy * sx, cy * cx]] +} + +fn multiply(a: M3, b: M3) -> M3 { + std::array::from_fn(|i| std::array::from_fn(|j| (0..3).map(|k| a[i][k] * b[k][j]).sum())) +} + +/// The unit vector along axis `axis` (0 X, 1 Y, 2 Z). +fn unit(axis: usize) -> [f64; 3] { + std::array::from_fn(|i| if i == axis { 1.0 } else { 0.0 }) +} + +/// A turn of `degrees` about the unit vector `axis`. +fn turn(axis: [f64; 3], degrees: f64) -> M3 { + let (s, c) = degrees.to_radians().sin_cos(); + let t = 1.0 - c; + let [x, y, z] = axis; + [ + [t * x * x + c, t * x * y - s * z, t * x * z + s * y], + [t * x * y + s * z, t * y * y + c, t * y * z - s * x], + [t * x * z - s * y, t * y * z + s * x, t * z * z + c], + ] +} + +/// An angle as the rotation fields hold it: above -180° up to 180°, to a hundredth of a degree. +fn tidy(degrees: f64) -> f64 { + let wrapped = 180.0 - (180.0 - degrees).rem_euclid(360.0); + (wrapped * 100.0).round() / 100.0 + 0.0 +} + +/// The X, Y and Z angles of rotation `m`. Of the two sets of angles that make it, the one nearest +/// `near` (so a turn moves the fields as little as it can); with Y at ±90°, where X and Z turn about +/// the same axis, X keeps its value from `near`. +fn angles_of(m: M3, near: [f64; 3]) -> [f64; 3] { + let y = (-m[2][0]).clamp(-1.0, 1.0).asin().to_degrees(); + let candidates = if m[2][1].hypot(m[2][2]) < 1e-9 { + let x = near[0]; + let z = if y > 0.0 { x - m[0][1].atan2(m[1][1]).to_degrees() } else { (-m[0][1]).atan2(m[1][1]).to_degrees() - x }; + [Some([x, y, z]), None] + } else { + let x = m[2][1].atan2(m[2][2]).to_degrees(); + let z = m[1][0].atan2(m[0][0]).to_degrees(); + [Some([x, y, z]), Some([x + 180.0, 180.0 - y, z + 180.0])] + }; + let distance = |a: &[f64; 3]| a.iter().zip(near).map(|(a, b)| tidy(a - b).abs()).sum::(); + candidates.into_iter().flatten().min_by(|a, b| distance(a).total_cmp(&distance(b))).unwrap_or(near).map(tidy) +} + +/// Where corner `i` of the cube (bit 0 for +X, bit 1 for +Y, bit 2 for +Z) is drawn. +fn corner(m: M3, center: Pos2, i: usize) -> Pos2 { + let p: [f64; 3] = std::array::from_fn(|b| if i >> b & 1 == 1 { 1.0 } else { -1.0 }); + let v: [f64; 3] = std::array::from_fn(|r| (0..3).map(|k| m[r][k] * p[k]).sum()); + center + vec2(v[0] as f32, v[1] as f32) * CUBE_HALF +} + +/// The corners of the face square to `axis` on its positive or negative side, in order round it. +fn face_corners(axis: usize, positive: bool) -> [usize; 4] { + let (b, c) = (1 << ((axis + 1) % 3), 1 << ((axis + 2) % 3)); + let side = if positive { 1 << axis } else { 0 }; + [0, b, b | c, c].map(|k| side | k) +} + +/// Does the face square to `axis` on that side face the viewer? +fn face_visible(m: M3, axis: usize, positive: bool) -> bool { + m[2][axis] * if positive { 1.0 } else { -1.0 } > 1e-6 +} + +/// The 12 edges: (from corner, to corner, the object axis it runs along). +fn edges() -> impl Iterator { + (0..3).flat_map(|axis| (0..8).filter(move |i| i >> axis & 1 == 0).map(move |i| (i, i | 1 << axis, axis))) +} + +/// Is the edge from corner `i` along `axis` on a face the viewer sees? +fn edge_visible(m: M3, i: usize, axis: usize) -> bool { + [(axis + 1) % 3, (axis + 2) % 3].into_iter().any(|other| face_visible(m, other, i >> other & 1 == 1)) +} + +/// What a press on the track cube takes hold of. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Grip { + /// A face: a free turn, or with Shift about the screen's horizontal or vertical axis. + Face, + /// An edge: a turn about the object axis the edge runs along. + Edge(usize), + /// The ring round the cube: a turn in the plane of the screen. + Ring, +} + +/// The z of the cross product of two screen vectors: positive when `b` is clockwise from `a`. +fn cross(a: Vec2, b: Vec2) -> f32 { + a.x * b.y - a.y * b.x +} + +fn segment_distance(p: Pos2, a: Pos2, b: Pos2) -> f32 { + let line = b - a; + let t = ((p - a).dot(line) / line.length_sq().max(1e-6)).clamp(0.0, 1.0); + p.distance(a + line * t) +} + +/// What the pointer at `p` takes hold of on a cube drawn at `m` about `center`: the nearest edge +/// within reach, else a face, else the ring, else (in the box's corners) a face's free turn. +fn grip_at(m: M3, center: Pos2, p: Pos2) -> Grip { + let edge = edges() + .filter(|&(i, _, axis)| edge_visible(m, i, axis)) + .map(|(i, j, axis)| (segment_distance(p, corner(m, center, i), corner(m, center, j)), axis)) + .filter(|(distance, _)| *distance <= EDGE_REACH) + .min_by(|a, b| a.0.total_cmp(&b.0)); + if let Some((_, axis)) = edge { + return Grip::Edge(axis); + } + let on_face = (0..3).flat_map(|axis| [(axis, true), (axis, false)]).filter(|&(axis, side)| face_visible(m, axis, side)).any(|(axis, side)| { + let points = face_corners(axis, side).map(|i| corner(m, center, i)); + let sides: [f32; 4] = std::array::from_fn(|k| cross(points[(k + 1) % 4] - points[k], p - points[k])); + sides.iter().all(|s| *s >= 0.0) || sides.iter().all(|s| *s <= 0.0) + }); + let distance = p.distance(center); + if !on_face && (RING_IN - 3.0..=RING_OUT + 3.0).contains(&distance) { Grip::Ring } else { Grip::Face } +} + +/// The turn in degrees, clockwise on the screen, from `from` to `to` about `center`. +fn sweep(from: Pos2, to: Pos2, center: Pos2) -> f64 { + let (a, b) = (from - center, to - center); + if a.length() < 2.0 || b.length() < 2.0 { + return 0.0; + } + f64::from(cross(a, b)).atan2(f64::from(a.dot(b))).to_degrees() +} + +/// A track cube gesture in progress. +#[derive(Clone)] +struct CubeDrag { + grip: Grip, + /// The rotation so far, kept unrounded so a long drag does not drift. + matrix: M3, + origin: Pos2, + last: Pos2, + /// With Shift, the screen axis the drag keeps to (0 X, 1 Y), chosen once it has moved 3 points. + lock: Option, + /// The settings before the gesture, which Escape puts back. + fields: serde_json::Map, + /// The last pass that drew the cube during the gesture. + pass: u64, + /// The cube the gesture started on. The 3D and Materials panel and a 3D dialog can each show + /// a cube at the same time, and only this one follows the gesture. + owner: Id, +} + +impl CubeDrag { + /// Was the cube drawn in this pass or the one before? When it was not (its dialog closed, or + /// the Rotation tab or the panel was left during the drag), the gesture is over. + fn live(&self, pass: u64) -> bool { + self.pass.saturating_add(1) >= pass + } +} + +/// The track cube of the dialog or panel of kind `kind`. The 3D and Materials panel and a 3D +/// dialog can show a cube at the same time, each with its own keyboard focus. +pub(super) fn cube_id(kind: &str) -> Id { + Id::unique(("three-d-track-cube", kind)) +} + +fn cube_drag_id() -> Id { + Id::unique("three-d-track-cube-drag") +} + +/// Is a track cube gesture in progress? +pub(super) fn cube_dragging(ctx: &egui::Context) -> bool { + let pass = ctx.cumulative_pass_nr(); + ctx.data(|m| m.get_temp::(cube_drag_id())).is_some_and(|g| g.live(pass)) +} + +/// The rotation after the pointer moves from `drag.last` to `p` on a cube about `center`. +fn drag_turn(drag: &mut CubeDrag, p: Pos2, center: Pos2, shift: bool) -> M3 { + let m = drag.matrix; + let delta = p - drag.last; + let (mut dx, mut dy) = (f64::from(delta.x), f64::from(delta.y)); + match drag.grip { + Grip::Face => { + if shift { + let total = p - drag.origin; + if drag.lock.is_none() && total.length() >= 3.0 { + drag.lock = Some(usize::from(total.x.abs() >= total.y.abs())); + } + match drag.lock { + // Across the screen turns about its vertical (Y) axis, up and down about X. + Some(1) => dy = 0.0, + Some(_) => dx = 0.0, + None => return m, + } + } + let length = dx.hypot(dy); + if length < 1e-9 { + return m; + } + // The front follows the pointer: right turns it toward +X, down toward +Y. + multiply(turn([-dy / length, dx / length, 0.0], length * DEGREES_PER_POINT), m) + } + Grip::Ring => multiply(turn(unit(2), sweep(drag.last, p, center)), m), + Grip::Edge(axis) => { + let w = [m[0][axis], m[1][axis], m[2][axis]]; + let across = w[0].hypot(w[1]); + // An axis pointing at the viewer turns like the ring, on the side it points to. + let degrees = + if w[2].abs() > 0.9 { sweep(drag.last, p, center) * w[2].signum() } else { (dx * w[1] - dy * w[0]) / across * DEGREES_PER_POINT }; + multiply(m, turn(unit(axis), degrees)) + } + } +} + +/// The track cube on the Rotation tab of Extrude & Bevel (Classic), Revolve (Classic) and Rotate +/// (Classic): a cube drawn at the current X, Y and Z rotation (the object's front blue, its top and +/// bottom light gray, its sides mid gray and its back dark gray) inside a ring. +/// +/// Dragging a face turns the object freely; with Shift the turn keeps to the screen's vertical axis +/// (a drag across) or its horizontal axis (a drag up or down), whichever the drag follows first. +/// Dragging an edge turns it about the object axis the edge runs along (X red, Y green, Z blue; the +/// edge takes its axis's color while hovered or dragged), and dragging in the ring turns it in the +/// plane of the screen. Escape during a drag puts the angles back. With the keyboard focus, the +/// arrow keys turn it about the screen's axes and Page Up and Page Down in the screen plane, 1° a +/// press (15° with Shift). The angles go to `rotationX`, `rotationY` and `rotationZ` only when they +/// change, and the dialog's preview applies them; OK records them as one undo step. The cube is off +/// while a rotation setting is mixed (the 3D and Materials panel's selected effects differ). +pub(super) fn track_cube(ui: &mut egui::Ui, d: &mut Dialog) { + let defaults = vectorcraft_effects::default_params(&d.str("__effect")).unwrap_or(json!({})); + let mixed = ROTATION_KEYS.iter().any(|k| d.fields.get(*k).is_some_and(Value::is_null)); + let now = ROTATION_KEYS.map(|k| d.f64(k, defaults.get(k).and_then(Value::as_f64).unwrap_or(0.0))); + let mut next = None; + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 6.0; + let name = tl!("Track cube"); + label(ui, name); + let (rect, _) = ui.allocate_exact_size(Vec2::splat(CUBE_BOX), Sense::hover()); + let enabled = ui.is_enabled() && !mixed; + let id = cube_id(&d.kind); + let resp = ui.interact(rect, id, if enabled { Sense::click_and_drag() } else { Sense::hover() }); + let center = rect.center(); + let value = format!("X {:.2}°, Y {:.2}°, Z {:.2}°", now[0], now[1], now[2]); + resp.widget_info(|| egui::WidgetInfo { + current_text_value: Some(value.clone()), + ..egui::WidgetInfo::labeled(egui::Role::Slider, enabled, name) + }); + if enabled + && resp.drag_started() + && let Some(origin) = ui.input(|i| i.pointer.press_origin()) + { + // A value being typed ends first; the cube then takes the keyboard focus below. + ui.ctx().memory_mut(|m| m.stop_text_input()); + let matrix = rotation(now); + let pass = ui.ctx().cumulative_pass_nr(); + let drag = CubeDrag { + grip: grip_at(matrix, center, origin), + matrix, + origin, + last: origin, + lock: None, + fields: d.fields.clone(), + pass, + owner: id, + }; + ui.data_mut(|m| m.insert_temp(cube_drag_id(), drag)); + } + if enabled && (resp.drag_started() || resp.clicked()) { + resp.request_focus(); + } + let pass = ui.ctx().cumulative_pass_nr(); + // A gesture on the other cube (the panel's or the dialog's) is left to that cube. + let mut drag = ui.data(|m| m.get_temp::(cube_drag_id())).filter(|g| g.owner == id); + if drag.as_ref().is_some_and(|g| !g.live(pass)) { + ui.data_mut(|m| m.remove::(cube_drag_id())); + drag = None; + } + if let Some(current) = &mut drag { + current.pass = pass; + if ui.input_mut(|i| i.consume_key(i.modifiers, egui::Key::Escape)) { + d.fields = current.fields.clone(); + d.fields.remove(super::form::PREVIEWED); + ui.data_mut(|m| m.remove::(cube_drag_id())); + drag = None; + } else { + if let Some(p) = resp.interact_pointer_pos() { + let shift = ui.input(|i| i.modifiers.shift); + current.matrix = drag_turn(current, p, center, shift); + current.last = p; + next = Some(angles_of(current.matrix, now)); + } + ui.data_mut(|m| m.insert_temp(cube_drag_id(), current.clone())); + } + } + // Only this cube's gesture ends here; the other cube may still have the release to handle. + if drag.is_some() && (resp.drag_stopped() || !ui.input(|i| i.pointer.primary_down())) { + ui.data_mut(|m| m.remove::(cube_drag_id())); + } + if enabled && resp.has_focus() { + use egui::{Key, Modifiers}; + ui.memory_mut(|m| { + m.set_focus_lock_filter(id, egui::EventFilter { horizontal_arrows: true, vertical_arrows: true, ..Default::default() }) + }); + let mut m = rotation(now); + let mut turned = false; + for (key, axis, sign) in [ + (Key::ArrowRight, 1, 1.0), + (Key::ArrowLeft, 1, -1.0), + (Key::ArrowUp, 0, 1.0), + (Key::ArrowDown, 0, -1.0), + (Key::PageDown, 2, 1.0), + (Key::PageUp, 2, -1.0), + ] { + // Shift first: a key without modifiers also matches the key with Shift. + for (modifiers, step) in [(Modifiers::SHIFT, 15.0), (Modifiers::NONE, 1.0)] { + while ui.input_mut(|i| i.consume_key(modifiers, key)) { + m = multiply(turn(unit(axis), sign * step), m); + turned = true; + } + } + } + if turned { + next = Some(angles_of(m, now)); + } + } + let shown = next.unwrap_or(now); + let hovered = drag.as_ref().map(|g| g.grip).or_else(|| resp.hover_pos().filter(|_| enabled).map(|p| grip_at(rotation(shown), center, p))); + if enabled && (resp.hovered() || drag.is_some()) { + ui.ctx().set_cursor_icon(match (hovered, drag.is_some()) { + (Some(Grip::Edge(_)), _) => egui::CursorIcon::ResizeHorizontal, + (_, true) => egui::CursorIcon::Grabbing, + _ => egui::CursorIcon::Grab, + }); + } + paint_cube(ui, rect, rotation(shown), hovered, enabled, resp.has_focus()); + resp.on_hover_text(tl!("Drag a face, an edge or the ring to rotate. Shift turns about one screen axis.")); + }); + if let Some(angles) = next + && angles.iter().zip(now).any(|(a, b)| (a - b).abs() > 1e-9) + { + for (key, angle) in ROTATION_KEYS.into_iter().zip(angles) { + d.fields.insert(key.into(), json!(angle)); + } + } +} + +/// Draws the track cube at rotation `m` in `rect`, with the grip under the pointer or in hand lit. +fn paint_cube(ui: &egui::Ui, rect: Rect, m: M3, active: Option, enabled: bool, focused: bool) { + let t = Tokens::get(ui.ctx()); + let fade = |c: Color32| if enabled { c } else { c.gamma_multiply(0.4) }; + let painter = ui.painter_at(rect); + let center = rect.center(); + painter.rect_filled(rect, 2.0, t.input); + let ring = if active == Some(Grip::Ring) { 0.6 } else { 0.3 }; + painter.circle_stroke(center, (RING_IN + RING_OUT) / 2.0, Stroke::new(RING_OUT - RING_IN, fade(t.axis_z.gamma_multiply(ring)))); + // Front blue; top and bottom light, sides mid and back dark gray. Only faces turned to the + // viewer are drawn, and on a cube those never overlap. + for (axis, side) in (0..3).flat_map(|axis| [(axis, true), (axis, false)]) { + if !face_visible(m, axis, side) { + continue; + } + let fill = match (axis, side) { + (2, true) => t.axis_z, + (2, false) => Color32::from_gray(90), + (1, _) => Color32::from_gray(205), + _ => Color32::from_gray(155), + }; + let points: Vec = face_corners(axis, side).iter().map(|&i| corner(m, center, i)).collect(); + painter.add(egui::Shape::convex_polygon(points, fade(fill), Stroke::NONE)); + } + let colors = [t.axis_x, t.axis_y, t.axis_z]; + for (i, j, axis) in edges() { + if !edge_visible(m, i, axis) { + continue; + } + let lit = active == Some(Grip::Edge(axis)); + let stroke = if lit { Stroke::new(2.5, fade(colors[axis])) } else { Stroke::new(1.0, fade(t.text_dim)) }; + painter.line_segment([corner(m, center, i), corner(m, center, j)], stroke); + } + let border = if focused { t.accent } else { t.input_border }; + painter.rect_stroke(rect, 2.0, Stroke::new(1.0, border), egui::StrokeKind::Inside); +} + +#[cfg(test)] +#[path = "tests_track_cube.rs"] +mod tests; diff --git a/crates/ui-egui/src/dialogs/variables.rs b/crates/ui-egui/src/dialogs/variables.rs index dad6e3f43b..8151df4e33 100644 --- a/crates/ui-egui/src/dialogs/variables.rs +++ b/crates/ui-egui/src/dialogs/variables.rs @@ -140,11 +140,18 @@ pub fn open(app: &mut VectorcraftApp, id: &str, preselect: Option<&str>) -> bool /// Variable Options' Name and Kind fields for the variable `name`: its name, and its kind as /// `variable.rename` takes it (empty for a variable of unknown kind, which OK leaves as it is). -/// [`FILLED`] records which variable they were filled for. +/// [`FILLED`] records which variable they were filled for. Once they were, only a field that is +/// still unset (null, as setting the Variable field leaves it) is filled. fn fill_variable_options(vars: &Variables, name: &str, fields: &mut serde_json::Map) { - let kind = vars.variable(name).map(|v| v.kind).filter(|k| *k != VariableKind::Unknown).map(VariableKind::label).unwrap_or_default(); - fields.insert("newName".into(), json!(name)); - fields.insert("kind".into(), json!(kind)); + let refill = fields.get(FILLED).and_then(Value::as_str) != Some(name); + let unset = |fields: &serde_json::Map, key: &str| matches!(fields.get(key), None | Some(Value::Null)); + if refill || unset(fields, "newName") { + fields.insert("newName".into(), json!(name)); + } + if refill || unset(fields, "kind") { + let kind = vars.variable(name).map(|v| v.kind).filter(|k| *k != VariableKind::Unknown).map(VariableKind::label).unwrap_or_default(); + fields.insert("kind".into(), json!(kind)); + } fields.insert(FILLED.into(), json!(name)); } @@ -212,9 +219,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { label(ui, tl!("Variable")); dropdown(ui, d, "variable", &variable_names, 220.0); let picked = d.str("variable"); - if picked != d.str(FILLED) { - fill_variable_options(vars, &picked, &mut d.fields); - } + fill_variable_options(vars, &picked, &mut d.fields); ui.end_row(); label(ui, tl!("Name")); text(ui, d, "newName", 220.0); @@ -305,7 +310,8 @@ fn set_text(d: &mut Dialog, key: &str, s: String) { /// /// In Variable Options, setting the Variable field clears Name and Kind, which OK reads as the /// variable's own name and kind, until a frame fills them from it; setting Name or Kind ties them -/// to the variable already named, so no frame fills them over. +/// to the variable already named, so no frame fills them over, and a frame fills only the one +/// still cleared. pub(super) fn note_set(d: &mut Dialog, field: &str) { d.fields.remove(&empty_marker(field)); if d.str("__command") == "variable.rename" { @@ -669,4 +675,46 @@ mod tests { let d = app.ui.dialog.as_ref().unwrap(); assert_eq!((d.str("newName"), d.str("kind")), ("Flag".to_string(), "visibility".to_string())); } + + #[test] + fn variable_options_fills_the_field_left_unset_after_the_variable_changes() { + let mut app = app_with_variables(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let frame = |app: &mut VectorcraftApp| { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| crate::dialogs::show(app, ui.ctx())); + out.textures_delta.clear(); + }; + + // Kind alone: Name shows the newly picked variable's name. + open(&mut app, "variable.rename", Some("Title")); + { + let d = app.ui.dialog.as_mut().unwrap(); + crate::dialogs::set_field(d, "variable".into(), json!("Badge")); + crate::dialogs::set_field(d, "kind".into(), json!("text")); + } + frame(&mut app); + { + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.str("newName"), d.str("kind")), ("Badge".to_string(), "text".to_string())); + } + + // Name alone: Kind shows the newly picked variable's kind. + open(&mut app, "variable.rename", Some("Title")); + { + let d = app.ui.dialog.as_mut().unwrap(); + crate::dialogs::set_field(d, "variable".into(), json!("Badge")); + crate::dialogs::set_field(d, "newName".into(), json!("Flag")); + } + frame(&mut app); + { + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.str("newName"), d.str("kind")), ("Flag".to_string(), "visibility".to_string())); + } + + // OK still renames Badge and keeps its kind. + crate::dialogs::confirm(&mut app).unwrap(); + let kind_of = |name: &str| app.session.active().and_then(|st| st.doc.variables.variable(name).map(|v| v.kind)); + assert_eq!((kind_of("Flag"), kind_of("Badge")), (Some(VariableKind::Visibility), None)); + } } diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 377df81a72..8a59c7e567 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -682,14 +682,22 @@ const MESSAGE_DEPTH: usize = 5; /// Translate a status or error message for display (see the module docs). Unknown messages, and /// parts of them (file names, numbers, a reason with no entry, a JSON object or array such as /// `{"objects": [...]}`, a value the message quotes in `"…"`, `“…”` or backticks, such as a -/// symbol's name), stay as they are. A part that starts with `{` or `[` is translated only -/// when it is a whole message with an exact entry, such as `[x, y] (two numbers)`. +/// symbol's name), stay as they are. A part that starts with `{` is translated only when it is a +/// whole message with an exact entry. A part that starts with `[` is translated when it has an +/// exact entry, such as `[x, y] (two numbers)`, or when it fits a template that starts with `[` +/// and an index of digits, such as an effect's refusal ``[0] `id`: {why}``. pub fn message(lang: Lang, s: &str) -> String { message_at(lang, s, MESSAGE_DEPTH) } fn message_at(lang: Lang, s: &str, depth: usize) -> String { - let Some((forms, caps)) = lang.catalog().message_forms(s) else { return s.to_string() }; + fill_message(lang, s, lang.catalog().message_forms(s), depth) +} + +/// `s` shown through the catalog entry `found` matched for it, its placeholder values translated +/// in turn while `depth` lasts. +fn fill_message(lang: Lang, s: &str, found: Option<(&[String], catalog::Captures<'_, '_>)>, depth: usize) -> String { + let Some((forms, caps)) = found else { return s.to_string() }; let count = caps.iter().find(|(k, _)| *k == "n").and_then(|(_, v)| v.parse::().ok()); let form = count.map_or(forms.len().saturating_sub(1), |n| (lang.0.plural)(n).min(forms.len().saturating_sub(1))); let Some(template) = forms.get(form) else { return s.to_string() }; @@ -697,8 +705,10 @@ fn message_at(lang: Lang, s: &str, depth: usize) -> String { let nested = |v: &str| { if depth <= 1 || quoted(v) { v.to_string() - } else if v.starts_with(['{', '[']) { + } else if v.starts_with('{') { exact_translation(lang.catalog(), v).unwrap_or_else(|| v.to_string()) + } else if v.starts_with('[') { + fill_message(lang, v, lang.catalog().indexed_message_forms(v), depth - 1) } else { message_at(lang, v, depth - 1) } diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 269048c279..61e90c789d 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1054,7 +1054,10 @@ font-technology Variable Променливи Every (minutes) На всеки (минути) Every option is at its default. Всички опции са в състояние по подразбиране. Every option matches {base}. Всички опции съответстват на {base}. - Every-line Composer Композитор за всеки ред + Middle Eastern & South Asian Single-line Composer Ред по ред композитор (Близък изток и Южна Азия) + Middle Eastern & South Asian Every-line Composer Композитор за всеки ред (Близък изток и Южна Азия) + Standard Single-line Composer Стандартен ред по ред композитор + Standard Every-line Composer Стандартен композитор за всеки ред Exact dash lengths Точни дължини на тиретата Exceptions (comma separated) Изключения (разделени със запетаи) Exclude Изключване @@ -1348,6 +1351,14 @@ font-technology Variable Променливи Previous Artboard Предишна работна област Next Artboard Следваща работна област Last Artboard Последна работна област + Status Bar Show Показване в лентата на състоянието + Artboard Name Име на работната област + Current Tool Текущ инструмент + Date and Time Дата и час + Number of Undos Брой отмени + Document Color Profile Цветови профил на документа + Undos Отмени + Redos Повторения Go To Link Към връзката GPL palettes keep solid colours only, as RGB. Палитрите GPL запазват само плътни цветове като RGB. GPU Performance Производителност на графичния процесор @@ -1367,6 +1378,8 @@ font-technology Variable Променливи Graph Диаграма Graph Data Данни за диаграма Graph Type Тип диаграма + Graph Type… Тип диаграма… + Graph Data… Данни за диаграма… Graph Options Опции на диаграмата Left Axis Лява ос Right Axis Дясна ос @@ -1482,6 +1495,7 @@ font-technology Variable Променливи Show smooth color wheel Показване на плавно цветово колело Show segmented color wheel Показване на сегментирано цветово колело Show color bars Показване на цветни ленти + Find the selected colors in the artwork Намиране на избраните цветове в илюстрацията Harmony Sets Набори от хармонии Height Височина Height: Височина: @@ -2636,6 +2650,8 @@ font-technology Variable Променливи Insert Aki Left Вмъкване на аки отляво Insert Aki Right Вмъкване на аки отдясно Tsume Цуме + Adjust Horizontal Diacritic Position Коригиране на хоризонталната позиция на диакритиците + Adjust Vertical Diacritic Position Коригиране на вертикалната позиция на диакритиците Character Direction Посока на знаците Digits Цифри Arabic Арабски @@ -3360,7 +3376,6 @@ digits Malayalam Малаялам Single Left Quotation Mark Лява единична кавичка Single Quotes: Единични кавички: Single Right Quotation Mark Дясна единична кавичка - Single-line Composer Ред по ред композитор Toggle Line Composer Превключване на композитора на редове Sixth Space Шесто разстояние Size Размер @@ -5140,6 +5155,7 @@ effect Soft Меко Change Panel Layout Промяна на оформлението на панела Close Panel Затваряне на панела Collapse Panel Group Свиване на групата панели + Cycle Display Sizes Превключване на размерите на показване Move Panel Преместване на панела Group with Групиране с Resize panels Преоразмеряване на панели @@ -5181,6 +5197,8 @@ effect Soft Меко Step up or down Стъпка нагоре или надолу Drag values or labels. Double-click a value to type. Плъзнете стойности или етикети. Кликнете двукратно върху стойност за въвеждане. Drag rings to rotate. Shift snaps to 15°. Плъзнете пръстените за завъртане. Shift прилепва към 15°. + Track cube Куб за завъртане + Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. Плъзнете стена, ръб или пръстена за завъртане. Shift завърта около една ос на екрана. Drag the light, or its rings. Shift snaps to 15°. Плъзнете светлината или нейните пръстени. Shift прилепва към 15°. Keep visible surfaces only when expanding Запазване само на видимите повърхности при разширяване Trim covered geometry on Expand Appearance. Live preview keeps the full surface. Transparent paints and surfaces exceeding visibility limits retain all faces. Изрязване на закритата геометрия при разширяване на оформлението. Живият преглед запазва цялата повърхност. Прозрачните бои и повърхности, надвишаващи границите на видимост, запазват всички лица. @@ -6985,3 +7003,21 @@ breakText Glyphs Глифи Nest Shapes… Подреждане на форми… Nest Shapes Подреждане на форми Roll Ролка + Packaging Tools Инструменти за опаковки + Fold Lines Линии на сгъване + Make Cut Line Направи линия за рязане + Make Crease Line Направи линия за биговане + Make Partial Cut Line Направи линия за частично рязане + Make Perforation Line Направи линия за перфорация + Make Fold Line Направи линия на сгъване + Role Swatches… Образци за видовете линии… + Role Swatches Образци за видовете линии + Role Вид линия + Cut Line Линия за рязане + Crease Line Линия за биговане + Partial Cut Line Линия за частично рязане + Perforation Line Линия за перфорация + No objects are selected. Няма избрани обекти. + Open a document to mark its fold lines. Отворете документ, за да отбележите линиите му на сгъване. + Remove Fold Line Role Премахни вида на линията +@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer трябва да е "singleLine", "everyLine", "standardSingleLine" или "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 07f55531dd..b3a4eefc2f 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -1015,6 +1015,7 @@ Change Panel Layout Promijeni raspored panela Close Panel Zatvori panel Collapse Panel Group Skupi grupu panela + Cycle Display Sizes Mijenjaj veličine prikaza Move Panel Pomakni panel Group with Grupiši sa Resize panels Promijeni veličinu panela @@ -1035,6 +1036,8 @@ Step up or down Korak gore ili dolje Drag values or labels. Double-click a value to type. Prevucite vrijednosti ili oznake. Dvostruki klik na vrijednost za upis. Drag rings to rotate. Shift snaps to 15°. Prevucite prstenove za rotaciju. Shift hvata na 15°. + Track cube Kocka za rotaciju + Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. Prevucite stranu, ivicu ili prsten za rotaciju. Shift rotira oko jedne ose ekrana. Drag the light, or its rings. Shift snaps to 15°. Prevucite svjetlo ili njegove prstenove. Shift hvata na 15°. lighting Light Svjetlo Keep visible surfaces only when expanding Pri proširivanju zadrži samo vidljive površine @@ -1085,6 +1088,14 @@ lighting Light Svjetlo Previous Artboard Prethodna radna ploča Next Artboard Sljedeća radna ploča Last Artboard Posljednja radna ploča + Status Bar Show Prikaz u traci stanja + Artboard Name Naziv radne ploče + Current Tool Trenutni alat + Date and Time Datum i vrijeme + Number of Undos Broj poništavanja + Document Color Profile Profil boja dokumenta + Undos Poništavanja + Redos Ponavljanja Graphic Style Options… Opcije grafičkog stila… Symbol Options Opcije simbola Symbol Options… Opcije simbola… @@ -1596,6 +1607,8 @@ lighting Light Svjetlo Insert Aki Left Umetni aki lijevo Insert Aki Right Umetni aki desno Tsume Tsume + Adjust Horizontal Diacritic Position Podesi vodoravni položaj dijakritika + Adjust Vertical Diacritic Position Podesi okomiti položaj dijakritika Character Direction Smjer znakova Digits Cifre Arabic Arapski @@ -2028,7 +2041,10 @@ digits Malayalam Malajalam Tabular Lining Tabelarne brojke Tabular Oldstyle Tabelarne stare brojke Titling Alternates Alternative za naslove - Every-line Composer Slagač svih redova + Middle Eastern & South Asian Single-line Composer Slagač jednog reda (Bliski istok i Južna Azija) + Middle Eastern & South Asian Every-line Composer Slagač svih redova (Bliski istok i Južna Azija) + Standard Single-line Composer Standardni slagač jednog reda + Standard Every-line Composer Standardni slagač svih redova First-line Left Indent Lijeva uvlaka prvog reda Hyphenation… Rastavljanje riječi… Words Longer Than: Riječi duže od: @@ -2068,7 +2084,6 @@ digits Malayalam Malajalam East Asian Composition Settings Postavke istočnoazijske kompozicije Korean Composition Settings Postavke korejske kompozicije Select a text object to edit its paragraph attributes. Odaberite tekstualni objekat da uredite njegove atribute pasusa. - Single-line Composer Slagač jednog reda Toggle Line Composer Uključi/isključi Line Composer Space After Paragraph Razmak nakon pasusa Space Before Paragraph Razmak prije pasusa @@ -2896,6 +2911,7 @@ digits Malayalam Malajalam Show smooth color wheel Prikaži glatki kotač boja Show segmented color wheel Prikaži segmentirani kotač boja Show color bars Prikaži trake boja + Find the selected colors in the artwork Pronađi odabrane boje u crtežu Harmony Rules Pravila harmonije Keep this row's colors (exclude) Zadrži boje ovog reda (isključi) Limit to Library: Ograniči na biblioteku: @@ -3584,6 +3600,8 @@ theme Appearance Izgled Create Graph Kreiraj grafikon Graph Data Podaci grafikona Graph Type Vrsta grafikona + Graph Type… Vrsta grafikona… + Graph Data… Podaci grafikona… Graph Options Opcije grafikona Left Axis Lijeva osa Right Axis Desna osa @@ -7038,3 +7056,21 @@ shape Open Otvoren Nest Shapes… Slaganje oblika… Nest Shapes Slaganje oblika Roll Rolna + Packaging Tools Alati za ambalažu + Fold Lines Linije savijanja + Make Cut Line Napravi liniju rezanja + Make Crease Line Napravi liniju bigovanja + Make Partial Cut Line Napravi liniju djelimičnog rezanja + Make Perforation Line Napravi liniju perforacije + Make Fold Line Napravi liniju savijanja + Role Swatches… Uzorci boja za vrste linija… + Role Swatches Uzorci boja za vrste linija + Role Vrsta linije + Cut Line Linija rezanja + Crease Line Linija bigovanja + Partial Cut Line Linija djelimičnog rezanja + Perforation Line Linija perforacije + No objects are selected. Nijedan objekat nije odabran. + Open a document to mark its fold lines. Otvorite dokument da označite njegove linije savijanja. + Remove Fold Line Role Ukloni vrstu linije +@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer mora biti "singleLine", "everyLine", "standardSingleLine" ili "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 05e9004bcb..2f9f1d8fdc 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -772,6 +772,7 @@ antiAlias Sharp Nítid Preserve Numbers Conserva els números Coarse Dots Punts gruixuts Collapse Panel Group Replega el grup de panells + Cycle Display Sizes Alterna les mides de visualització Collapse Panels to Icons Replega els panells a icones Collapse to Icons Replega a icones Collate Intercala @@ -1347,6 +1348,8 @@ antiAlias Sharp Nítid Drag out from a corner, or click two straight lines, then click to place. Arrossega cap enfora des d’una cantonada, o fes clic en dues línies rectes i després fes clic per col·locar-ho. Drag out from a segment, or click two points, then click to place. Arrossega cap enfora des d’un segment, o fes clic en dos punts i després fes clic per col·locar-ho. Drag rings to rotate. Shift snaps to 15°. Arrossega els anells per girar. La tecla Maj ajusta a 15°. + Track cube Cub de rotació + Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. Arrossega una cara, una aresta o l'anell per girar. La tecla Maj gira al voltant d'un eix de la pantalla. Drag the art to move it on the paper Arrossega la il·lustració per moure-la sobre el paper Drag the light, or its rings. Shift snaps to 15°. Arrossega el llum o els seus anells. La tecla Maj ajusta a 15°. Drag to float as a toolbar Arrossega per surar com a barra d’eines @@ -1537,7 +1540,10 @@ antiAlias Sharp Nítid Every (minutes) Cada (minuts) Every option is at its default. Totes les opcions són al valor predeterminat. Every option matches {base}. Totes les opcions coincideixen amb {base}. - Every-line Composer Composició línia per línia + Middle Eastern & South Asian Single-line Composer Compositor d’una línia (Orient Pròxim i Àsia Meridional) + Middle Eastern & South Asian Every-line Composer Composició línia per línia (Orient Pròxim i Àsia Meridional) + Standard Single-line Composer Compositor estàndard d’una línia + Standard Every-line Composer Composició estàndard línia per línia Exact Exacte Exact dash lengths Longituds de guió exactes Example: {name} Exemple: {name} @@ -1905,6 +1911,8 @@ digits Malayalam Malaiàlam Graph Design Disseny del gràfic Graph Marker Marcador del gràfic Graph Type Tipus de gràfic + Graph Type… Tipus de gràfic… + Graph Data… Dades del gràfic… Graph Options Opcions del gràfic Left Axis Eix esquerre Right Axis Eix dret @@ -2020,6 +2028,7 @@ digits Malayalam Malaiàlam Show smooth color wheel Mostra la roda de color contínua Show segmented color wheel Mostra la roda de color segmentada Show color bars Mostra les barres de color + Find the selected colors in the artwork Troba els colors seleccionats a l’obra Harmony Sets Conjunts d’harmonia HDTV 1080p HDTV 1080p HDTV 720p HDTV 720p @@ -2325,6 +2334,14 @@ digits Malayalam Malaiàlam Enclosing Lasso Llaç envoltant Last Últim Last Artboard Últim tauler + Status Bar Show Mostra a la barra d'estat + Artboard Name Nom del tauler + Current Tool Eina actual + Date and Time Data i hora + Number of Undos Nombre de desfets + Document Color Profile Perfil de color del document + Undos Desfets + Redos Refets Last commit Últim commit Last Effect: {name} Últim efecte: {name} Last Effect: {} Últim efecte: {} @@ -2481,6 +2498,7 @@ digits Malayalam Malaiàlam Load Variable Library Carrega la biblioteca de variables Load Variable Library… Carrega la biblioteca de variables… Save Variable Library… Desa la biblioteca de variables… +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml «Importa» llegeix un fitxer d’origen de dades amb l’extensió .csv, .tsv, .txt o .xml @msg a variable library holds text variables, and the document has none una biblioteca de variables conté variables de text, i el document no en té cap @msg variable `{name}` can't be saved in a variable library: rename it to start with a letter or `_`, without spaces or symbols other than `-`, `_` and `.` la variable `{name}` no es pot desar en una biblioteca de variables: canvieu-li el nom perquè comenci amb una lletra o `_`, sense espais ni símbols que no siguin `-`, `_` i `.` @msg {k} has control characters {k} conté caràcters de control @@ -3417,6 +3435,8 @@ digits Malayalam Malaiàlam Insert Aki Left Insereix aki a l'esquerra Insert Aki Right Insereix aki a la dreta Tsume Tsume + Adjust Horizontal Diacritic Position Ajusta la posició horitzontal dels diacrítics + Adjust Vertical Diacritic Position Ajusta la posició vertical dels diacrítics Proportional Lining Xifres proporcionals alineades Position: Posició: Default Position Posició predeterminada @@ -4395,7 +4415,6 @@ digits Malayalam Malaiàlam Single Quotes: Cometes simples: Single Right Quotation Mark Cometa simple dreta Single Word Justification: Justificació d’una sola paraula: - Single-line Composer Compositor d’una línia Sixth Space Espai de sisena part Size Mida Size Tile to Art Ajusta la mida del mosaic a l’art @@ -5709,6 +5728,17 @@ digits Malayalam Malaiàlam @msg `name` must be the name of a script engine `name` ha de ser el nom d'un motor d'scripts @msg the main script engine is new for each run and is never kept, so it cannot be dropped el motor d'scripts principal és nou a cada execució i no es conserva mai, per tant no es pot descartar @msg there is no script engine named {name} no hi ha cap motor d'scripts anomenat {name} +@msg `answers` must be a list of answers `answers` ha de ser una llista de respostes +@msg `answers` has more than {MAX_ANSWERS} answers `answers` té més de {MAX_ANSWERS} respostes +@msg `answers` is larger than 1 MiB `answers` ocupa més d'1 MiB +@msg must be an object with `kind` and `value` ha de ser un objecte amb `kind` i `value` +@msg must have exactly `kind` and `value` ha de tenir exactament `kind` i `value` +@msg is an alert's answer, whose `value` must be "ok" és la resposta d'un alert, i el seu `value` ha de ser "ok" +@msg is a confirm's answer, whose `value` must be true or false és la resposta d'un confirm, i el seu `value` ha de ser true o false +@msg is longer than 16 KiB ocupa més de 16 KiB +@msg is a prompt's answer, whose `value` must be a string or null és la resposta d'un prompt, i el seu `value` ha de ser una cadena o null +@msg must have `kind` alert, confirm or prompt ha de tenir `kind` alert, confirm o prompt +@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` només és per a una execució sense ningú a qui preguntar: a l'aplicació, la persona respon cada quadre de diàleg @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ç @@ -6521,6 +6551,8 @@ digits Malayalam Malaiàlam @msg unknown option `{path}.{k}` opció desconeguda `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) sobreimpressions desconegudes `{o}` (preserve, simulate o discard) @msg unknown panel `{raw}` panell desconegut `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` no té mides de visualització per alternar +@msg the panels are not shown els panells no es mostren @msg panels can't be shown in Presentation Mode els panells no es poden mostrar en el mode de presentació @msg unknown parameter `{key}`; did you mean `{near}`? paràmetre desconegut `{key}`; volies dir `{near}`? @msg unknown parameter `{key}`; the command takes no parameters paràmetre desconegut `{key}`; l’ordre no admet cap paràmetre @@ -6670,6 +6702,7 @@ digits Malayalam Malaiàlam @msg {what} points outside memory {what} apunta fora de la memòria @msg `angle` must be a number `angle` ha de ser un nombre @msg `aspect` must be from 0.01 to 100 `aspect` ha d’estar entre 0.01 i 100 +@msg `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 `axes` ha de ser [a, b, c, d], cadascun entre -1000 i 1000, amb a·d - b·c com a mínim a 0.001 de 0 @msg `cap` must be "butt", "round" or "square" `cap` ha de ser "butt", "round" o "square" @msg `fillRule` must be "nonzero" or "evenodd" `fillRule` ha de ser "nonzero" o "evenodd" @msg `helpUrl` must be an https:// address of at most {MAX_HELP_URL} bytes `helpUrl` ha de ser una adreça https:// de {MAX_HELP_URL} bytes com a màxim @@ -7536,6 +7569,19 @@ breakText Glyphs Glifs Not Aligned to Pixel Grid No alineat a la quadrícula de píxels @msg only paths and compound paths can be aligned to the pixel grid només els traçats i els traçats compostos es poden alinear a la quadrícula de píxels @msg side is left or right, not `{s}` side ha de ser left o right, no `{s}` +@msg side is left or right, not `{v}` side ha de ser left o right, no `{v}` +@msg order is a whole number from 0 to {others}, not `{v}` order ha de ser un nombre enter de 0 a {others}, no `{v}` +@msg toolbar (a toolbar's name) must be a string toolbar (el nom d’una barra d’eines) ha de ser una cadena +@msg no toolbar named `{name}` no hi ha cap barra d’eines anomenada `{name}` +@msg toolbar name can't be empty el nom de la barra d’eines no pot ser buit +@msg a toolbar name has at most {MAX_NAME} characters un nom de barra d’eines té com a màxim {MAX_NAME} caràcters +@msg there is already a toolbar named `{name}` ja hi ha una barra d’eines anomenada `{name}` +@msg there is already a toolbar named `{to}` ja hi ha una barra d’eines anomenada `{to}` +@msg a workspace keeps at most {MAX} toolbars un espai de treball conté com a màxim {MAX} barres d’eines +@msg name (a toolbar's name) must be a string name (el nom d’una barra d’eines) ha de ser una cadena +@msg name (a toolbar's name) is required cal name (el nom d’una barra d’eines) +@msg to (the new name) is required cal to (el nom nou) +@msg name must be a toolbar's name name ha de ser el nom d’una barra d’eines Ignore All Ignora-ho tot Add to Dictionary Afegeix al diccionari No Suggestions No hi ha suggeriments @@ -7748,3 +7794,21 @@ breakText Glyphs Glifs @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ó + Packaging Tools Eines d’embalatge + Fold Lines Línies de plegat + Make Cut Line Converteix en línia de tall + Make Crease Line Converteix en línia d’hendit + Make Partial Cut Line Converteix en línia de tall parcial + Make Perforation Line Converteix en línia de perforació + Make Fold Line Converteix en línia de plegat + Role Swatches… Mostres dels tipus de línia… + Role Swatches Mostres dels tipus de línia + Role Tipus de línia + Cut Line Línia de tall + Crease Line Línia d’hendit + Partial Cut Line Línia de tall parcial + Perforation Line Línia de perforació + No objects are selected. No hi ha cap objecte seleccionat. + Open a document to mark its fold lines. Obre un document per marcar-ne les línies de plegat. + Remove Fold Line Role Elimina el tipus de línia +@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer ha de ser "singleLine", "everyLine", "standardSingleLine" o "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/catalog.rs b/crates/ui-egui/src/i18n/catalog.rs index f2fab1fcfa..cbb2c5b702 100644 --- a/crates/ui-egui/src/i18n/catalog.rs +++ b/crates/ui-egui/src/i18n/catalog.rs @@ -219,8 +219,13 @@ impl Catalog { } // Templates that start with text before those that start with a placeholder, so // `plug-in manifest: {0}` wins over `{_1} is {_2} bytes (limit {_3})` for a message it - // wraps; then most literal text first, so `Couldn't open {name}: {e}` wins over `{path}: {e}`. - c.templates.sort_by_key(|t| (matches!(t.pieces.first(), Some(Piece::Hole(_))), std::cmp::Reverse(t.literal))); + // wraps; then the longest text before the first placeholder, so `` `answers[{i}]` {e} `` wins + // over `` `{key}` must be true or false `` for a message it wraps; then most literal text + // first, so `Couldn't open {name}: {e}` wins over `{path}: {e}`. + c.templates.sort_by_key(|t| { + let lead = if let Some(Piece::Text(text)) = t.pieces.first() { text.len() } else { 0 }; + (matches!(t.pieces.first(), Some(Piece::Hole(_))), std::cmp::Reverse(lead), std::cmp::Reverse(t.literal)) + }); c } @@ -257,6 +262,28 @@ impl Catalog { self.templates.iter().find_map(|t| t.captures(s).map(|caps| (t.forms.as_slice(), caps))) } + /// [`Catalog::message_forms`] for a part of a message that starts with `[`, which may be a JSON + /// array: an exact `@msg` entry, else only a template that starts with a literal `[` and a + /// placeholder whose value is an index of ASCII digits, such as ``[{j}] `{_1}`: {why}``. An + /// array such as ``["] `x`: b"]`` fits that template's text, but not its index. + pub fn indexed_message_forms<'a>(&self, s: &'a str) -> Option<(&[String], Captures<'_, 'a>)> { + if let Some(tr) = self.messages.get(s) { + return Some((std::slice::from_ref(tr), Vec::new())); + } + if s.len() > MAX_MESSAGE_LEN { + return None; + } + self.templates.iter().find_map(|t| { + let [Piece::Text(open), Piece::Hole(index), ..] = t.pieces.as_slice() else { return None }; + if open != "[" { + return None; + } + let caps = t.captures(s)?; + let digits = caps.iter().any(|(k, v)| k == index && v.bytes().all(|b| b.is_ascii_digit())); + digits.then_some((t.forms.as_slice(), caps)) + }) + } + /// The translation of a status or error message that has an exact `@msg` entry, as written in /// the catalog (`{{` and `}}` for literal braces); templates are not tried. pub fn exact_message(&self, s: &str) -> Option<&str> { diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index cb37d0e83f..4628b89a1d 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1035,6 +1035,7 @@ Change Panel Layout Změnit rozložení panelů Close Panel Zavřít panel Collapse Panel Group Sbalit skupinu panelů + Cycle Display Sizes Přepínat velikosti zobrazení Move Panel Přesunout panel Group with Seskupit s Resize panels Změnit velikost panelů @@ -1057,6 +1058,8 @@ Step up or down O krok nahoru nebo dolů Drag values or labels. Double-click a value to type. Upravte hodnoty přetažením čísel nebo popisků. Dvojím kliknutím na hodnotu ji zadáte. Drag rings to rotate. Shift snaps to 15°. Otáčejte přetažením prstenců. Shift nastaví kroky po 15°. + Track cube Otočná krychle + Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. Otáčejte přetažením stěny, hrany nebo prstence. Shift otáčí kolem jedné osy obrazovky. Drag the light, or its rings. Shift snaps to 15°. Přetáhněte světlo nebo jeho prstence. Shift nastaví kroky po 15°. lighting Light Světlo Keep visible surfaces only when expanding Při rozložení ponechat pouze viditelné povrchy @@ -1109,6 +1112,14 @@ lighting Light Světlo Previous Artboard Předchozí pracovní plocha Next Artboard Další pracovní plocha Last Artboard Poslední pracovní plocha + Status Bar Show Zobrazit ve stavovém řádku + Artboard Name Název pracovní plochy + Current Tool Aktuální nástroj + Date and Time Datum a čas + Number of Undos Počet kroků zpět + Document Color Profile Barevný profil dokumentu + Undos Zpět + Redos Znovu Graphic Style Options… Možnosti grafického stylu… Symbol Options Možnosti symbolu Symbol Options… Možnosti symbolu… @@ -1624,6 +1635,8 @@ lighting Light Světlo Insert Aki Left Vložit aki vlevo Insert Aki Right Vložit aki vpravo Tsume Tsume + Adjust Horizontal Diacritic Position Upravit vodorovnou polohu diakritiky + Adjust Vertical Diacritic Position Upravit svislou polohu diakritiky Character Direction Směr znaků Digits Číslice Arabic Arabské @@ -2101,7 +2114,8 @@ digits Malayalam Malajálamské Tabular Lining Tabulkové verzálkové Tabular Oldstyle Tabulkové minuskové Titling Alternates Titulkové alternativy - Every-line Composer Sazba všech řádků + Middle Eastern & South Asian Every-line Composer Sazba všech řádků (Blízký východ a Jižní Asie) + Standard Every-line Composer Standardní sazba všech řádků First-line Left Indent Odsazení prvního řádku zleva Hyphenation… Dělení slov… Words Longer Than: Slova delší než: @@ -2141,7 +2155,8 @@ digits Malayalam Malajálamské East Asian Composition Settings Nastavení východoasijské sazby Korean Composition Settings Nastavení korejské sazby Select a text object to edit its paragraph attributes. Vyberte textový objekt, abyste mohli upravit atributy jeho odstavce. - Single-line Composer Sazba jednoho řádku + Middle Eastern & South Asian Single-line Composer Sazba jednoho řádku (Blízký východ a Jižní Asie) + Standard Single-line Composer Standardní sazba jednoho řádku Toggle Line Composer Přepnout sazbu řádků Space After Paragraph Mezera za odstavcem Space Before Paragraph Mezera před odstavcem @@ -2974,6 +2989,7 @@ digits Malayalam Malajálamské Show smooth color wheel Zobrazit plynulé barevné kolo Show segmented color wheel Zobrazit segmentované barevné kolo Show color bars Zobrazit barevné pruhy + Find the selected colors in the artwork Najít vybrané barvy v kresbě Harmony Rules Pravidla harmonie Keep this row's colors (exclude) Ponechat barvy tohoto řádku (vyloučit) Limit to Library: Omezit na knihovnu: @@ -3680,6 +3696,8 @@ theme Appearance Motiv Create Graph Vytvořit graf Graph Data Data grafu Graph Type Typ grafu + Graph Type… Typ grafu… + Graph Data… Data grafu… Graph Options Možnosti grafu Left Axis Levá osa Right Axis Pravá osa @@ -4798,6 +4816,7 @@ imageTrace Outline Obrys @msg `name` must be the name of a script engine `name` musí být název skriptovacího jádra @msg the main script engine is new for each run and is never kept, so it cannot be dropped hlavní skriptovací jádro je pro každý běh nové a nikdy se neuchovává, proto je nelze zahodit @msg there is no script engine named {name} skriptovací jádro s názvem {name} neexistuje +@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` je jen pro běh, kde se nemá koho zeptat: v aplikaci odpovídá na každý dialog uživatel @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 @@ -5423,6 +5442,8 @@ imageTrace Outline Obrys @msg unknown option `{path}.{k}` neznámá možnost `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) neznámé přetisky `{o}` (preserve, simulate nebo discard) @msg unknown panel `{raw}` neznámý panel `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` nemá velikosti zobrazení k přepínání +@msg the panels are not shown panely nejsou zobrazeny @msg panels can't be shown in Presentation Mode v režimu prezentace nelze panely zobrazit @msg unknown preference `{key}` neznámá předvolba `{key}` @msg Preferences imported. Předvolby byly importovány. @@ -6275,6 +6296,7 @@ mark-style Japanese Japonské Export Data Sets… Exportovat sady dat… Load Variable Library… Načíst knihovnu proměnných… Save Variable Library… Uložit knihovnu proměnných… +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml „Importovat“ čte soubor zdroje dat s příponou .csv, .tsv, .txt nebo .xml @msg a variable library holds text variables, and the document has none knihovna proměnných obsahuje textové proměnné a dokument žádné nemá @msg variable `{name}` can't be saved in a variable library: rename it to start with a letter or `_`, without spaces or symbols other than `-`, `_` and `.` proměnnou `{name}` nelze uložit do knihovny proměnných: přejmenujte ji tak, aby začínala písmenem nebo `_` a neobsahovala mezery ani jiné symboly než `-`, `_` a `.` @msg {k} has control characters {k} obsahuje řídicí znaky @@ -7804,6 +7826,7 @@ breakText Glyphs Glyfy @msg Image Trace failed: {e} Vektorizace obrazu selhala: {e} @msg Image Trace finished, but its document was closed Vektorizace obrazu skončila, ale její dokument byl zavřen @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Vektorizace obrazu skončila, ale obraz nebo jeho nastavení se mezitím změnily: vektorizujte ho znovu +@msg Image Trace finished, but its document was reverted: trace it again Vektorizace obrazu skončila, ale její dokument byl vrácen k uložené verzi: vektorizujte ho znovu @msg Import SVG Filter reads SVG files, not SVGZ Importovat filtr SVG čte soubory SVG, ne SVGZ @msg Invalid dimension offset Neplatné odsazení kóty @msg Invalid point Neplatný bod @@ -7977,6 +8000,7 @@ breakText Glyphs Glyfy @msg `names` must be an array of style names `names` musí být pole názvů stylů @msg `new` is a design name, or true `new` je název návrhu, nebo true @msg `origin` must be [x, y] in points `origin` musí být [x, y] v bodech +@msg `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 `axes` musí být [a, b, c, d], každé od -1000 do 1000, a a·d - b·c se musí od 0 lišit alespoň o 0.001 @msg `path` must be a folder `path` musí být složka @msg `path` must be a path object `path` musí být objekt cesty @msg `picks` must be an array (got {v}) `picks` musí být pole (zadáno {v}) @@ -8382,7 +8406,7 @@ breakText Glyphs Glyfy @msg column: true floats the whole column and takes no onto, above or below column: true uvolní celý sloupec jako plovoucí a nepřijímá onto, above ani below @msg command must be a shape.* command command musí být příkaz shape.* @msg commands[{i}]: missing `command` commands[{i}]: chybí `command` -@msg composer must be "singleLine" or "everyLine" composer musí být "singleLine" nebo "everyLine" +@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer musí být "singleLine", "everyLine", "standardSingleLine" nebo "standardEveryLine" @msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes složené tvary přijímají cesty, složené cesty, skupiny, složené tvary, text, prolnutí a obálky @msg compound {_1} must contain exactly one open path to join složený objekt {_1} musí ke spojení obsahovat právě jednu otevřenou cestu @msg connect needs a path other than the one extended connect vyžaduje jinou cestu než tu prodlužovanou @@ -9578,3 +9602,20 @@ breakText Glyphs Glyfy @msg turn on at least one side zapněte alespoň jednu stranu @msg with no hem and no grommets there is nothing to mark bez lemu a bez průchodek není co označit @msg {saving} failed: {e} {saving} se nezdařilo: {e} + Packaging Tools Nástroje pro obaly + Fold Lines Linie skladu + Make Cut Line Vytvořit linii řezu + Make Crease Line Vytvořit linii bigu + Make Partial Cut Line Vytvořit linii částečného řezu + Make Perforation Line Vytvořit linii perforace + Make Fold Line Vytvořit linii skladu + Role Swatches… Vzorník typů linií… + Role Swatches Vzorník typů linií + Role Typ linie + Cut Line Linie řezu + Crease Line Linie bigu + Partial Cut Line Linie částečného řezu + Perforation Line Linie perforace + No objects are selected. Nejsou vybrány žádné objekty. + Open a document to mark its fold lines. Otevřete dokument, abyste označili jeho linie skladu. + Remove Fold Line Role Odstranit typ linie diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 442ea36859..8b822be042 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -145,6 +145,18 @@ @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 `answers` must be a list of answers `answers` skal være en liste med svar +@msg `answers` has more than {MAX_ANSWERS} answers `answers` har flere end {MAX_ANSWERS} svar +@msg `answers` is larger than 1 MiB `answers` er større end 1 MiB +@msg `answers[{i}]` {e} `answers[{i}]` {e} +@msg must be an object with `kind` and `value` skal være et objekt med `kind` og `value` +@msg must have exactly `kind` and `value` skal have præcis `kind` og `value` +@msg is an alert's answer, whose `value` must be "ok" er svaret på en alert, hvis `value` skal være "ok" +@msg is a confirm's answer, whose `value` must be true or false er svaret på en confirm, hvis `value` skal være true eller false +@msg is longer than 16 KiB er længere end 16 KiB +@msg is a prompt's answer, whose `value` must be a string or null er svaret på en prompt, hvis `value` skal være en streng eller null +@msg must have `kind` alert, confirm or prompt skal have `kind` alert, confirm eller prompt +@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` er kun til en kørsel uden nogen at spørge: i appen besvarer personen hver dialog @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} @@ -427,6 +439,7 @@ @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 `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 `axes` skal være [a, b, c, d], hver fra -1000 til 1000, med a·d - b·c mindst 0,001 fra 0 @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 @@ -1568,6 +1581,7 @@ Change Panel Layout Skift panelets layout Close Panel Luk panel Collapse Panel Group Skjul panelgruppe + Cycle Display Sizes Skift mellem visningsstørrelser Move Panel Flyt panel Group with Gruppér med Resize panels Tilpas størrelse på paneler @@ -1587,6 +1601,8 @@ Reset all Revolve settings to their defaults. Nulstil alle indstillinger for omdrejning til standardværdierne. Drag values or labels. Double-click a value to type. Træk i værdier eller etiketter. Dobbeltklik på en værdi for at indtaste. Drag rings to rotate. Shift snaps to 15°. Træk i ringe for at rotere. Shift fastgør til 15°. + Track cube Rotationsterning + Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. Træk i en flade, en kant eller ringen for at rotere. Shift roterer om én skærmakse. Drag the light, or its rings. Shift snaps to 15°. Træk i lyset eller dets ringe. Shift fastgør til 15°. lighting Light Lys Keep visible surfaces only when expanding Behold kun synlige flader ved udvidelse @@ -2143,6 +2159,8 @@ lighting Light Lys Insert Aki Left Indsæt aki til venstre Insert Aki Right Indsæt aki til højre Tsume Tsume + Adjust Horizontal Diacritic Position Juster vandret placering af diakritiske tegn + Adjust Vertical Diacritic Position Juster lodret placering af diakritiske tegn Character Direction Tegnretning Digits Cifre Arabic Arabisk @@ -2520,7 +2538,10 @@ digits Malayalam Malayalam Tabular Lining Tabulære versalcifre Tabular Oldstyle Tabulære mediævalcifre Titling Alternates Titelalternativer - Every-line Composer Hverlinjesætter + Middle Eastern & South Asian Single-line Composer Enlinjesætter (Mellemøsten og Sydasien) + Middle Eastern & South Asian Every-line Composer Hverlinjesætter (Mellemøsten og Sydasien) + Standard Single-line Composer Standard-enlinjesætter + Standard Every-line Composer Standard-hverlinjesætter First-line Left Indent Venstre indrykning af første linje Hyphenation… Orddeling… Justification… Justering… @@ -2552,7 +2573,6 @@ digits Malayalam Malayalam East Asian Composition Settings Indstillinger for østasiatisk komposition Korean Composition Settings Indstillinger for koreansk komposition Select a text object to edit its paragraph attributes. Markér et tekstobjekt for at redigere dets afsnitsattributter. - Single-line Composer Enlinjesætter Toggle Line Composer Skift linjesætter Space After Paragraph Mellemrum efter afsnit Space Before Paragraph Mellemrum før afsnit @@ -3367,6 +3387,7 @@ digits Malayalam Malayalam Show smooth color wheel Vis glat farvehjul Show segmented color wheel Vis segmenteret farvehjul Show color bars Vis farvebjælker + Find the selected colors in the artwork Find de valgte farver i grafikken Harmony Rules Harmoniregler Keep this row's colors (exclude) Behold farverne i denne række (ekskludér) Limit to Library: Begræns til bibliotek: @@ -4022,6 +4043,8 @@ theme Appearance Udseende Create Graph Opret graf Graph Data Grafdata Graph Type Graftype + Graph Type… Graftype… + Graph Data… Grafdata… Graph Options Grafindstillinger Left Axis Venstre akse Right Axis Højre akse @@ -5399,6 +5422,7 @@ imageTrace Outline Kontur @msg plug-in failed: {0} plug-in fejlede: {0} @msg plug-in manifest: {0} plug-in-manifest: {0} @msg plug-in output: {0} plug-in-output: {0} +@msg [{j}] `{_1}`: {why} [{j}] `{_1}`: {why} @msg plug-in parameters: {0} plug-in-parametre: {0} @msg plug-in trapped: {0} plug-in'et blev fanget: {0} @msg print settings are not an object printindstillingerne er ikke et objekt @@ -5533,6 +5557,8 @@ imageTrace Outline Kontur @msg unknown option `{path}.{k}` ukendt indstilling `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) ukendt overprint `{o}` (preserve, simulate eller discard) @msg unknown panel `{raw}` ukendt panel `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` har ingen visningsstørrelser at skifte mellem +@msg the panels are not shown panelerne vises ikke @msg unknown preference `{key}` ukendt præference `{key}` @msg Preferences imported. Præferencerne er importeret. @msg not a preferences file: {e} ikke en præferencefil: {e} @@ -6307,6 +6333,7 @@ mark-style Japanese Japansk Export Data Sets… Eksportér datasæt… Load Variable Library… Indlæs variabelbibliotek… Save Variable Library… Gem variabelbibliotek… +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml »Importér« læser en datakildefil med filtypenavnet .csv, .tsv, .txt eller .xml @msg a variable library holds text variables, and the document has none et variabelbibliotek indeholder tekstvariabler, og dokumentet har ingen @msg variable `{name}` can't be saved in a variable library: rename it to start with a letter or `_`, without spaces or symbols other than `-`, `_` and `.` variablen `{name}` kan ikke gemmes i et variabelbibliotek: omdøb den, så den begynder med et bogstav eller `_`, uden mellemrum eller andre symboler end `-`, `_` og `.` @msg data set `{name}` holds a control character, which a variable library can't hold datasættet `{name}` indeholder et kontroltegn, som et variabelbibliotek ikke kan indeholde @@ -6514,6 +6541,14 @@ swatch Bright Violet Kraftig violet Color wheel Farvehjul First Artboard Første kunstplade Last Artboard Sidste kunstplade + Status Bar Show Vis i statuslinjen + Artboard Name Kunstpladens navn + Current Tool Aktuelt værktøj + Date and Time Dato og klokkeslæt + Number of Undos Antal fortrydelser + Document Color Profile Dokumentets farveprofil + Undos Fortrydelser + Redos Gentagelser Next Artboard Næste kunstplade Previous Artboard Forrige kunstplade Step up or down Trinvis op eller ned @@ -7571,6 +7606,19 @@ breakText Glyphs Glyffer Align New Objects to Pixel Grid Juster nye objekter efter pixelgitter Not Aligned to Pixel Grid Ikke justeret efter pixelgitter @msg side is left or right, not `{s}` side er left eller right, ikke `{s}` +@msg side is left or right, not `{v}` side er left eller right, ikke `{v}` +@msg order is a whole number from 0 to {others}, not `{v}` order er et heltal fra 0 til {others}, ikke `{v}` +@msg toolbar (a toolbar's name) must be a string toolbar (navnet på en værktøjslinje) skal være en streng +@msg no toolbar named `{name}` ingen værktøjslinje med navnet `{name}` +@msg toolbar name can't be empty navnet på en værktøjslinje må ikke være tomt +@msg a toolbar name has at most {MAX_NAME} characters navnet på en værktøjslinje har højst {MAX_NAME} tegn +@msg there is already a toolbar named `{name}` der findes allerede en værktøjslinje med navnet `{name}` +@msg there is already a toolbar named `{to}` der findes allerede en værktøjslinje med navnet `{to}` +@msg a workspace keeps at most {MAX} toolbars et arbejdsområde gemmer højst {MAX} værktøjslinjer +@msg name (a toolbar's name) must be a string name (navnet på en værktøjslinje) skal være en streng +@msg name (a toolbar's name) is required name (navnet på en værktøjslinje) er påkrævet +@msg to (the new name) is required to (det nye navn) er påkrævet +@msg name must be a toolbar's name name skal være navnet på en værktøjslinje Edit Custom Dictionary Redigér egen ordliste Entry: Opslag: # Script Console @@ -7656,3 +7704,21 @@ breakText Glyphs Glyffer Nest Shapes… Pak figurer tæt… Nest Shapes Pak figurer tæt Roll Rulle + Packaging Tools Emballageværktøjer + Fold Lines Foldelinjer + Make Cut Line Gør til skærelinje + Make Crease Line Gør til rillelinje + Make Partial Cut Line Gør til delvis skærelinje + Make Perforation Line Gør til perforeringslinje + Make Fold Line Gør til foldelinje + Role Swatches… Farveprøver for linjetyper… + Role Swatches Farveprøver for linjetyper + Role Linjetype + Cut Line Skærelinje + Crease Line Rillelinje + Partial Cut Line Delvis skærelinje + Perforation Line Perforeringslinje + No objects are selected. Ingen objekter er markeret. + Open a document to mark its fold lines. Åbn et dokument for at markere dets foldelinjer. + Remove Fold Line Role Fjern linjetype +@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer skal være "singleLine", "everyLine", "standardSingleLine" eller "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 22b6c437db..752a60accd 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1056,7 +1056,8 @@ font-technology Variable Variabel Every (minutes) Alle (Minuten) Every option is at its default. Alle Optionen haben ihren Standardwert. Every option matches {base}. Alle Optionen entsprechen {base}. - Every-line Composer Alle-Zeilen-Setzer + Middle Eastern & South Asian Every-line Composer Alle-Zeilen-Setzer (Naher Osten und Südasien) + Standard Every-line Composer Standard-Alle-Zeilen-Setzer Exact dash lengths Exakte Strichlängen Exceptions (comma separated) Ausnahmen (durch Kommas getrennt) Exclude Schnittmenge entfernen @@ -1393,6 +1394,14 @@ file-filter Templates Vorlagen Previous Artboard Vorherige Zeichenfläche Next Artboard Nächste Zeichenfläche Last Artboard Letzte Zeichenfläche + Status Bar Show In Statusleiste anzeigen + Artboard Name Name der Zeichenfläche + Current Tool Aktuelles Werkzeug + Date and Time Datum und Uhrzeit + Number of Undos Anzahl der Rückgängig-Schritte + Document Color Profile Farbprofil des Dokuments + Undos Rückgängig + Redos Wiederholen Go To Link Gehe zu Verknüpfung GPL palettes keep solid colours only, as RGB. GPL-Paletten enthalten nur einfarbige Farben, als RGB. GPU Performance GPU-Leistung @@ -1412,6 +1421,8 @@ file-filter Templates Vorlagen Graph Diagramm Graph Data Diagrammdaten Graph Type Diagrammtyp + Graph Type… Diagrammtyp… + Graph Data… Diagrammdaten… Graph Options Diagrammoptionen Left Axis Linke Achse Right Axis Rechte Achse @@ -1527,6 +1538,7 @@ file-filter Templates Vorlagen Show smooth color wheel Stufenlosen Farbkreis anzeigen Show segmented color wheel Segmentierten Farbkreis anzeigen Show color bars Farbbalken anzeigen + Find the selected colors in the artwork Ausgewählte Farben in der Grafik finden Harmony Sets Harmoniesätze Height Höhe Height: Höhe: @@ -2679,6 +2691,8 @@ mark-style Japanese Japanisch Insert Aki Left Aki links einfügen Insert Aki Right Aki rechts einfügen Tsume Tsume + Adjust Horizontal Diacritic Position Horizontale Position diakritischer Zeichen anpassen + Adjust Vertical Diacritic Position Vertikale Position diakritischer Zeichen anpassen Character Direction Zeichenrichtung Digits Ziffern Arabic Arabisch @@ -3421,7 +3435,8 @@ digits Malayalam Malayalam Single Left Quotation Mark Einfaches öffnendes Anführungszeichen Single Quotes: Einfache Anführungszeichen: Single Right Quotation Mark Einfaches schließendes Anführungszeichen - Single-line Composer Einzeilen-Setzer + Middle Eastern & South Asian Single-line Composer Einzeilen-Setzer (Naher Osten und Südasien) + Standard Single-line Composer Standard-Einzeilen-Setzer Toggle Line Composer Zeilensetzer umschalten Sixth Space Sechstelgeviert-Leerzeichen Size Größe @@ -5032,6 +5047,8 @@ theme Appearance Erscheinungsbild @msg unknown option `{path}.{k}` unbekannte Option `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) unbekannter Wert für overprints `{o}` (preserve, simulate oder discard) @msg unknown panel `{raw}` unbekanntes Bedienfeld `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` hat keine Anzeigegrößen zum Durchlaufen +@msg the panels are not shown die Bedienfelder werden nicht angezeigt @msg panels can't be shown in Presentation Mode im Präsentationsmodus können keine Bedienfelder angezeigt werden @msg unknown preference `{key}` unbekannte Voreinstellung `{key}` @msg Preferences imported. Voreinstellungen importiert. @@ -5491,6 +5508,7 @@ theme Appearance Erscheinungsbild Change Panel Layout Bedienfeldanordnung ändern Close Panel Bedienfeld schließen Collapse Panel Group Bedienfeldgruppe minimieren + Cycle Display Sizes Anzeigegrößen durchlaufen Move Panel Bedienfeld verschieben Group with Gruppieren mit Resize panel window Bedienfeldfenster skalieren @@ -5520,6 +5538,8 @@ theme Appearance Erscheinungsbild # 3D and Materials › Revolve: its options dialog and gizmos. Axis side Achsenseite Drag rings to rotate. Shift snaps to 15°. Ziehen Sie die Ringe, um zu drehen. Mit Shift in 15°-Schritten. + Track cube Rotationswürfel + Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. Ziehen Sie eine Fläche, eine Kante oder den Ring, um zu drehen. Mit Shift um eine Bildschirmachse. Drag the light, or its rings. Shift snaps to 15°. Ziehen Sie das Licht oder seine Ringe. Mit Shift in 15°-Schritten. lighting Light Licht Drag values or labels. Double-click a value to type. Ziehen Sie Werte oder Beschriftungen. Doppelklicken Sie auf einen Wert, um ihn einzugeben. @@ -5858,6 +5878,7 @@ effect Soft Weich Export Data Sets… Datensätze exportieren… Load Variable Library… Variablenbibliothek laden… Save Variable Library… Variablenbibliothek speichern… +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml „Importieren“ liest eine Datenquelldatei mit der Endung .csv, .tsv, .txt oder .xml @msg a variable library holds text variables, and the document has none eine Variablenbibliothek enthält Textvariablen, und das Dokument hat keine @msg variable `{name}` can't be saved in a variable library: rename it to start with a letter or `_`, without spaces or symbols other than `-`, `_` and `.` die Variable `{name}` kann nicht in einer Variablenbibliothek gespeichert werden: Benennen Sie sie so um, dass sie mit einem Buchstaben oder `_` beginnt, ohne Leerzeichen oder andere Symbole als `-`, `_` und `.` @msg data set `{name}` holds a control character, which a variable library can't hold der Datensatz `{name}` enthält ein Steuerzeichen, das eine Variablenbibliothek nicht enthalten kann @@ -7261,6 +7282,7 @@ breakText Glyphs Glyphen @msg `answer` for this {kind} dialog must be one of: {_1} `answer` für dieses {kind}-Dialogfeld muss eines der folgenden sein: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` hat mehr als {MAX_ANSWERS} Antworten @msg `answers` is larger than 1 MiB `answers` ist größer als 1 MiB +@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` ist nur für einen Lauf ohne jemanden, der gefragt werden kann: In der App beantwortet die Person jeden Dialog @msg `answers` must be a list of answers `answers` muss eine Liste von Antworten sein @msg `artboard` must be the index of an artboard of the document `artboard` muss der Index einer Zeichenfläche des Dokuments sein @msg `artboardsAt` must be [x, y] `artboardsAt` muss [x, y] sein @@ -7292,6 +7314,7 @@ breakText Glyphs Glyphen @msg `name` must be a name that is not empty `name` muss ein nicht leerer Name sein @msg `name` must not be empty `name` darf nicht leer sein @msg `origin` must be [x, y] in points `origin` muss [x, y] in Punkt sein +@msg `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 `axes` muss [a, b, c, d] sein, jeweils von -1000 bis 1000, mit a·d - b·c mindestens 0,001 von 0 entfernt @msg `picks` must be an array (got {v}) `picks` muss ein Array sein (erhalten: {v}) @msg `picks` must hold 1 to {MAX_PICKS} picks (got {_1}) `picks` muss 1 bis {MAX_PICKS} Auswahlen enthalten (erhalten: {_1}) @msg `radius` must be 0 or more `radius` muss 0 oder größer sein @@ -7649,6 +7672,7 @@ breakText Glyphs Glyphen @msg Image Trace failed: {e} Bildnachzeichner fehlgeschlagen: {e} @msg Image Trace finished, but its document was closed Bildnachzeichner abgeschlossen, aber sein Dokument wurde geschlossen @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Bildnachzeichner abgeschlossen, aber das Bild oder seine Einstellungen haben sich inzwischen geändert: Zeichnen Sie es erneut nach +@msg Image Trace finished, but its document was reverted: trace it again Bildnachzeichner abgeschlossen, aber sein Dokument wurde auf die letzte Version zurückgesetzt: Zeichnen Sie es erneut nach @msg Invalid dimension offset Ungültiger Bemaßungsversatz @msg Invalid point Ungültiger Punkt @msg Join: a subpath went missing Zusammenfügen: Ein Teilpfad ist verloren gegangen @@ -8063,7 +8087,7 @@ breakText Glyphs Glyphen @msg column: true floats the whole column and takes no onto, above or below column: true macht die ganze Spalte schwebend und nimmt kein onto, above oder below @msg command must be a shape.* command command muss ein shape.*-Befehl sein @msg commands[{i}]: missing `command` commands[{i}]: `command` fehlt -@msg composer must be "singleLine" or "everyLine" composer muss „singleLine“ oder „everyLine“ sein +@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer muss „singleLine“, „everyLine“, „standardSingleLine“ oder „standardEveryLine“ sein @msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes zusammengesetzte Formen nehmen Pfade, zusammengesetzte Pfade, Gruppen, zusammengesetzte Formen, Text, Angleichungen und Verzerrungshüllen @msg compound {_1} must contain exactly one open path to join zusammengesetzter Pfad {_1} muss genau einen offenen Pfad zum Zusammenfügen enthalten @msg connect end must be "start" or "end" connect end muss „start“ oder „end“ sein @@ -9176,3 +9200,20 @@ breakText Glyphs Glyphen Nest Shapes… Formen verschachteln… Nest Shapes Formen verschachteln Roll Rolle + Packaging Tools Verpackungswerkzeuge + Fold Lines Faltlinien + Make Cut Line Als Schnittlinie festlegen + Make Crease Line Als Rilllinie festlegen + Make Partial Cut Line Als Teilschnittlinie festlegen + Make Perforation Line Als Perforationslinie festlegen + Make Fold Line Als Faltlinie festlegen + Role Swatches… Farbfelder der Linienarten… + Role Swatches Farbfelder der Linienarten + Role Linienart + Cut Line Schnittlinie + Crease Line Rilllinie + Partial Cut Line Teilschnittlinie + Perforation Line Perforationslinie + No objects are selected. Es sind keine Objekte ausgewählt. + Open a document to mark its fold lines. Öffnen Sie ein Dokument, um seine Faltlinien festzulegen. + Remove Fold Line Role Linienart entfernen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 7afffee7d6..9b32ea177c 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1021,7 +1021,10 @@ font-technology Variable Μεταβλητές Every (minutes) Κάθε (λεπτά) Every option is at its default. Όλες οι επιλογές έχουν τις προεπιλεγμένες τιμές τους. Every option matches {base}. Όλες οι επιλογές ταιριάζουν με το {base}. - Every-line Composer Σύνθεση όλων των γραμμών + Middle Eastern & South Asian Single-line Composer Σύνθεση μονής γραμμής (Μέση Ανατολή και Νότια Ασία) + Middle Eastern & South Asian Every-line Composer Σύνθεση όλων των γραμμών (Μέση Ανατολή και Νότια Ασία) + Standard Single-line Composer Τυπική σύνθεση μονής γραμμής + Standard Every-line Composer Τυπική σύνθεση όλων των γραμμών Exact dash lengths Ακριβή μήκη παυλών Exceptions (comma separated) Εξαιρέσεις (χωρισμένες με κόμμα) Exclude Εξαίρεση @@ -1323,6 +1326,14 @@ font-technology Variable Μεταβλητές Previous Artboard Προηγούμενος πίνακας σχεδίασης Next Artboard Επόμενος πίνακας σχεδίασης Last Artboard Τελευταίος πίνακας σχεδίασης + Status Bar Show Εμφάνιση στη γραμμή κατάστασης + Artboard Name Όνομα πίνακα σχεδίασης + Current Tool Τρέχον εργαλείο + Date and Time Ημερομηνία και ώρα + Number of Undos Αριθμός αναιρέσεων + Document Color Profile Χρωματικό προφίλ εγγράφου + Undos Αναιρέσεις + Redos Επαναλήψεις Go To Link Μετάβαση στη σύνδεση GPL palettes keep solid colours only, as RGB. Οι παλέτες GPL διατηρούν μόνο συμπαγή χρώματα σε RGB. GPU Performance Απόδοση GPU @@ -1342,6 +1353,8 @@ font-technology Variable Μεταβλητές Graph Γράφημα Graph Data Δεδομένα γραφήματος Graph Type Τύπος γραφήματος + Graph Type… Τύπος γραφήματος… + Graph Data… Δεδομένα γραφήματος… Graph Options Επιλογές γραφήματος Left Axis Αριστερός άξονας Right Axis Δεξιός άξονας @@ -1457,6 +1470,7 @@ font-technology Variable Μεταβλητές Show smooth color wheel Εμφάνιση ομαλού χρωματικού τροχού Show segmented color wheel Εμφάνιση τμηματοποιημένου χρωματικού τροχού Show color bars Εμφάνιση χρωματικών ράβδων + Find the selected colors in the artwork Εύρεση των επιλεγμένων χρωμάτων στο σχέδιο Harmony Sets Σύνολα χρωματικής αρμονίας Height Ύψος Height: Ύψος: @@ -2485,6 +2499,18 @@ axis Both Και τα δύο @msg `name` must be the name of a script engine το `name` πρέπει να είναι το όνομα μιας μηχανής σεναρίων @msg the main script engine is new for each run and is never kept, so it cannot be dropped η κύρια μηχανή σεναρίων είναι νέα σε κάθε εκτέλεση και δεν διατηρείται ποτέ, οπότε δεν μπορεί να απορριφθεί @msg there is no script engine named {name} δεν υπάρχει μηχανή σεναρίων με όνομα {name} +@msg `answers` must be a list of answers το `answers` πρέπει να είναι λίστα απαντήσεων +@msg `answers` has more than {MAX_ANSWERS} answers το `answers` έχει περισσότερες από {MAX_ANSWERS} απαντήσεις +@msg `answers` is larger than 1 MiB το `answers` είναι μεγαλύτερο από 1 MiB +@msg `answers[{i}]` {e} το `answers[{i}]` {e} +@msg must be an object with `kind` and `value` πρέπει να είναι αντικείμενο με `kind` και `value` +@msg must have exactly `kind` and `value` πρέπει να έχει ακριβώς `kind` και `value` +@msg is an alert's answer, whose `value` must be "ok" είναι απάντηση σε alert, οπότε το `value` πρέπει να είναι "ok" +@msg is a confirm's answer, whose `value` must be true or false είναι απάντηση σε confirm, οπότε το `value` πρέπει να είναι true ή false +@msg is longer than 16 KiB είναι μεγαλύτερο από 16 KiB +@msg is a prompt's answer, whose `value` must be a string or null είναι απάντηση σε prompt, οπότε το `value` πρέπει να είναι συμβολοσειρά ή null +@msg must have `kind` alert, confirm or prompt πρέπει να έχει `kind` alert, confirm ή prompt +@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog το `answers` είναι μόνο για εκτέλεση χωρίς κανέναν να ερωτηθεί: στην εφαρμογή, το άτομο απαντά σε κάθε παράθυρο διαλόγου @msg Running a script Εκτελείται σενάριο @msg Copied the script report Η αναφορά του σεναρίου αντιγράφηκε @msg Copied the link info Οι πληροφορίες συνδέσμου αντιγράφηκαν @@ -2703,6 +2729,7 @@ effect Soft Απαλό Change Panel Layout Αλλαγή διάταξης πάνελ Close Panel Κλείσιμο πάνελ Collapse Panel Group Σύμπτυξη ομάδας πάνελ + Cycle Display Sizes Εναλλαγή μεγεθών εμφάνισης Move Panel Μετακίνηση πάνελ Group with Ομαδοποίηση με Resize panels Αλλαγή μεγέθους πάνελ @@ -3477,6 +3504,8 @@ theme Appearance Εμφάνιση Insert Aki Left Εισαγωγή aki αριστερά Insert Aki Right Εισαγωγή aki δεξιά Tsume Tsume + Adjust Horizontal Diacritic Position Προσαρμογή οριζόντιας θέσης διακριτικών + Adjust Vertical Diacritic Position Προσαρμογή κατακόρυφης θέσης διακριτικών Arabic Αραβικά Hindi Χίντι Farsi Περσικά @@ -4006,7 +4035,6 @@ digits Malayalam Μαλαγιάλαμ Single Left Quotation Mark Μονό αριστερό εισαγωγικό Single Quotes: Μονά εισαγωγικά: Single Right Quotation Mark Μονό δεξί εισαγωγικό - Single-line Composer Σύνθεση μονής γραμμής Toggle Line Composer Εναλλαγή σύνθεσης γραμμών Sixth Space Διάστημα ενός έκτου Size Tile to Art Προσαρμογή μεγέθους πλακιδίου στο σχέδιο @@ -5060,6 +5088,8 @@ digits Malayalam Μαλαγιάλαμ @msg unknown option `{path}.{k}` άγνωστη επιλογή `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) άγνωστη επιλογή υπερεκτύπωσης `{o}` (preserve, simulate ή discard) @msg unknown panel `{raw}` άγνωστος πίνακας `{raw}` +@msg `{panel}` has no display sizes to cycle ο πίνακας `{panel}` δεν έχει μεγέθη εμφάνισης για εναλλαγή +@msg the panels are not shown οι πίνακες δεν εμφανίζονται @msg panels can't be shown in Presentation Mode τα πλαίσια δεν μπορούν να εμφανιστούν στη λειτουργία παρουσίασης @msg unknown preference `{key}` άγνωστη προτίμηση `{key}` @msg Preferences imported. Οι προτιμήσεις εισήχθησαν. @@ -5410,6 +5440,8 @@ digits Malayalam Μαλαγιάλαμ Step up or down Ένα βήμα πάνω ή κάτω Drag values or labels. Double-click a value to type. Σύρετε τιμές ή ετικέτες. Κάντε διπλό κλικ σε μια τιμή για πληκτρολόγηση. Drag rings to rotate. Shift snaps to 15°. Σύρετε τους δακτυλίους για περιστροφή. Με Shift γίνεται προσκόλληση ανά 15°. + Track cube Κύβος περιστροφής + Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. Σύρετε μια έδρα, μια ακμή ή τον δακτύλιο για περιστροφή. Με Shift η περιστροφή γίνεται γύρω από έναν άξονα της οθόνης. Drag the light, or its rings. Shift snaps to 15°. Σύρετε την πηγή φωτός ή τους δακτυλίους της. Με Shift γίνεται προσκόλληση ανά 15°. Keep visible surfaces only when expanding Διατήρηση μόνο ορατών επιφανειών κατά την ανάπτυξη Trim covered geometry on Expand Appearance. Live preview keeps the full surface. Transparent paints and surfaces exceeding visibility limits retain all faces. Αποκοπή καλυμμένης γεωμετρίας κατά την Ανάπτυξη εμφάνισης. Η ζωντανή προεπισκόπηση διατηρεί ολόκληρη την επιφάνεια. Διαφανή γεμίσματα και επιφάνειες που υπερβαίνουν τα όρια ορατότητας διατηρούν όλες τις έδρες. @@ -6132,6 +6164,7 @@ effect Points Σημεία Export Data Sets… Εξαγωγή συνόλων δεδομένων… Load Variable Library… Φόρτωση βιβλιοθήκης μεταβλητών… Save Variable Library… Αποθήκευση βιβλιοθήκης μεταβλητών… +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml Η «Εισαγωγή» διαβάζει αρχείο προέλευσης δεδομένων με κατάληξη .csv, .tsv, .txt ή .xml @msg a variable library holds text variables, and the document has none μια βιβλιοθήκη μεταβλητών περιέχει μεταβλητές κειμένου και το έγγραφο δεν έχει καμία @msg variable `{name}` can't be saved in a variable library: rename it to start with a letter or `_`, without spaces or symbols other than `-`, `_` and `.` η μεταβλητή `{name}` δεν μπορεί να αποθηκευτεί σε βιβλιοθήκη μεταβλητών: μετονομάστε την ώστε να ξεκινά με γράμμα ή `_`, χωρίς κενά ή σύμβολα εκτός από `-`, `_` και `.` @msg {k} has control characters {k} περιέχει χαρακτήρες ελέγχου @@ -6508,6 +6541,7 @@ axis Y Axis Άξονας Y @msg {what} points outside memory το {what} δείχνει εκτός μνήμης @msg `angle` must be a number το `angle` πρέπει να είναι αριθμός @msg `aspect` must be from 0.01 to 100 το `aspect` πρέπει να είναι από 0.01 έως 100 +@msg `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 το `axes` πρέπει να είναι [a, b, c, d], καθένα από -1000 έως 1000, με το a·d - b·c να απέχει τουλάχιστον 0.001 από το 0 @msg `cap` must be "butt", "round" or "square" το `cap` πρέπει να είναι "butt", "round" ή "square" @msg `fillRule` must be "nonzero" or "evenodd" το `fillRule` πρέπει να είναι "nonzero" ή "evenodd" @msg `helpUrl` must be an https:// address of at most {MAX_HELP_URL} bytes το `helpUrl` πρέπει να είναι διεύθυνση https:// έως {MAX_HELP_URL} byte @@ -7508,6 +7542,19 @@ breakText Glyphs Γλύφοι Not Aligned to Pixel Grid Μη στοιχισμένα στο πλέγμα εικονοστοιχείων @msg only paths and compound paths can be aligned to the pixel grid μόνο διαδρομές και σύνθετες διαδρομές μπορούν να στοιχιστούν στο πλέγμα εικονοστοιχείων @msg side is left or right, not `{s}` το side είναι left ή right, όχι `{s}` +@msg side is left or right, not `{v}` το side είναι left ή right, όχι `{v}` +@msg order is a whole number from 0 to {others}, not `{v}` το order είναι ακέραιος αριθμός από 0 έως {others}, όχι `{v}` +@msg toolbar (a toolbar's name) must be a string το toolbar (το όνομα μιας γραμμής εργαλείων) πρέπει να είναι συμβολοσειρά +@msg no toolbar named `{name}` δεν υπάρχει γραμμή εργαλείων με όνομα `{name}` +@msg toolbar name can't be empty το όνομα της γραμμής εργαλείων δεν μπορεί να είναι κενό +@msg a toolbar name has at most {MAX_NAME} characters ένα όνομα γραμμής εργαλείων έχει το πολύ {MAX_NAME} χαρακτήρες +@msg there is already a toolbar named `{name}` υπάρχει ήδη γραμμή εργαλείων με όνομα `{name}` +@msg there is already a toolbar named `{to}` υπάρχει ήδη γραμμή εργαλείων με όνομα `{to}` +@msg a workspace keeps at most {MAX} toolbars ένας χώρος εργασίας κρατά το πολύ {MAX} γραμμές εργαλείων +@msg name (a toolbar's name) must be a string το name (το όνομα μιας γραμμής εργαλείων) πρέπει να είναι συμβολοσειρά +@msg name (a toolbar's name) is required απαιτείται το name (το όνομα μιας γραμμής εργαλείων) +@msg to (the new name) is required απαιτείται το to (το νέο όνομα) +@msg name must be a toolbar's name το name πρέπει να είναι όνομα γραμμής εργαλείων Ignore All Παράβλεψη όλων Add to Dictionary Προσθήκη στο λεξικό No Suggestions Καμία πρόταση @@ -7721,3 +7768,21 @@ breakText Glyphs Γλύφοι @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} εικονοστοιχεία ανά πλευρά): μειώστε την ανάλυση + Packaging Tools Εργαλεία συσκευασίας + Fold Lines Γραμμές δίπλωσης + Make Cut Line Δημιουργία γραμμής κοπής + Make Crease Line Δημιουργία γραμμής πτύχωσης + Make Partial Cut Line Δημιουργία γραμμής μερικής κοπής + Make Perforation Line Δημιουργία γραμμής διάτρησης + Make Fold Line Δημιουργία γραμμής δίπλωσης + Role Swatches… Δείγματα χρωμάτων τύπων γραμμής… + Role Swatches Δείγματα χρωμάτων τύπων γραμμής + Role Τύπος γραμμής + Cut Line Γραμμή κοπής + Crease Line Γραμμή πτύχωσης + Partial Cut Line Γραμμή μερικής κοπής + Perforation Line Γραμμή διάτρησης + No objects are selected. Δεν έχουν επιλεγεί αντικείμενα. + Open a document to mark its fold lines. Ανοίξτε ένα έγγραφο για να σημειώσετε τις γραμμές δίπλωσής του. + Remove Fold Line Role Αφαίρεση τύπου γραμμής +@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" το composer πρέπει να είναι "singleLine", "everyLine", "standardSingleLine" ή "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index adaa7a8dc6..9c81265e9d 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1077,7 +1077,10 @@ font-technology Variable Variables Every (minutes) Cada (minutos) Every option is at its default. Todas las opciones tienen su valor predeterminado. Every option matches {base}. Todas las opciones coinciden con {base}. - Every-line Composer Composición de todas las líneas + Middle Eastern & South Asian Single-line Composer Composición de una línea (Oriente Medio y Sur de Asia) + Middle Eastern & South Asian Every-line Composer Composición de todas las líneas (Oriente Medio y Sur de Asia) + Standard Single-line Composer Composición estándar de una línea + Standard Every-line Composer Composición estándar de todas las líneas Exact dash lengths Longitudes exactas de guion Exceptions (comma separated) Excepciones (separadas por comas) Exclude Excluir @@ -1402,6 +1405,14 @@ font-technology Variable Variables Previous Artboard Mesa de trabajo anterior Next Artboard Mesa de trabajo siguiente Last Artboard Última mesa de trabajo + Status Bar Show Mostrar en la barra de estado + Artboard Name Nombre de la mesa de trabajo + Current Tool Herramienta actual + Date and Time Fecha y hora + Number of Undos Número de deshacer + Document Color Profile Perfil de color del documento + Undos Deshacer + Redos Rehacer Go To Link Ir al vínculo GPL palettes keep solid colours only, as RGB. Las paletas GPL solo conservan colores sólidos, en RGB. GPU Performance Rendimiento de GPU @@ -1421,6 +1432,8 @@ font-technology Variable Variables Graph Gráfico Graph Data Datos del gráfico Graph Type Tipo de gráfico + Graph Type… Tipo de gráfico… + Graph Data… Datos del gráfico… Graph Options Opciones de gráfico Left Axis Eje izquierdo Right Axis Eje derecho @@ -1536,6 +1549,7 @@ font-technology Variable Variables Show smooth color wheel Mostrar rueda de color continua Show segmented color wheel Mostrar rueda de color segmentada Show color bars Mostrar barras de color + Find the selected colors in the artwork Buscar los colores seleccionados en la ilustración Harmony Sets Conjuntos de armonía Height Altura Height: Altura: @@ -2714,6 +2728,8 @@ font-technology Variable Variables Insert Aki Left Insertar aki a la izquierda Insert Aki Right Insertar aki a la derecha Tsume Tsume + Adjust Horizontal Diacritic Position Ajustar posición horizontal de los diacríticos + Adjust Vertical Diacritic Position Ajustar posición vertical de los diacríticos Character Direction Dirección de caracteres Digits Dígitos Arabic Árabes @@ -3453,7 +3469,6 @@ digits Malayalam Malayálam Single Left Quotation Mark Comilla simple de apertura Single Quotes: Comillas simples: Single Right Quotation Mark Comilla simple de cierre - Single-line Composer Composición de una línea Toggle Line Composer Alternar composición de líneas Sixth Space Sexto de espacio Size Tamaño @@ -4482,6 +4497,17 @@ axis Both Ambos @msg `name` must be the name of a script engine `name` debe ser el nombre de un motor de scripts @msg the main script engine is new for each run and is never kept, so it cannot be dropped el motor de scripts principal es nuevo en cada ejecución y nunca se conserva, por lo que no se puede descartar @msg there is no script engine named {name} no hay ningún motor de scripts llamado {name} +@msg `answers` must be a list of answers `answers` debe ser una lista de respuestas +@msg `answers` has more than {MAX_ANSWERS} answers `answers` tiene más de {MAX_ANSWERS} respuestas +@msg `answers` is larger than 1 MiB `answers` ocupa más de 1 MiB +@msg must be an object with `kind` and `value` debe ser un objeto con `kind` y `value` +@msg must have exactly `kind` and `value` debe tener exactamente `kind` y `value` +@msg is an alert's answer, whose `value` must be "ok" es la respuesta de un alert, cuyo `value` debe ser "ok" +@msg is a confirm's answer, whose `value` must be true or false es la respuesta de un confirm, cuyo `value` debe ser true o false +@msg is longer than 16 KiB ocupa más de 16 KiB +@msg is a prompt's answer, whose `value` must be a string or null es la respuesta de un prompt, cuyo `value` debe ser una cadena o null +@msg must have `kind` alert, confirm or prompt debe tener `kind` alert, confirm o prompt +@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` solo es para una ejecución sin nadie a quien preguntar: en la aplicación, la persona responde cada cuadro de diálogo @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 @@ -5111,6 +5137,8 @@ axis Both Ambos @msg unknown option `{path}.{k}` opción desconocida `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) sobreimpresiones desconocidas `{o}` (preserve, simulate o discard) @msg unknown panel `{raw}` panel desconocido `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` no tiene tamaños de visualización que alternar +@msg the panels are not shown los paneles no se muestran @msg panels can't be shown in Presentation Mode los paneles no se pueden mostrar en el modo de presentación @msg unknown preference `{key}` preferencia desconocida `{key}` @msg Preferences imported. Preferencias importadas. @@ -5486,6 +5514,7 @@ axis Both Ambos Change Panel Layout Cambiar distribución de paneles Close Panel Cerrar panel Collapse Panel Group Contraer grupo de paneles + Cycle Display Sizes Alternar tamaños de visualización Move Panel Mover panel Group with Agrupar con Resize panels Cambiar tamaño de los paneles @@ -5531,6 +5560,8 @@ axis Both Ambos Step up or down Subir o bajar un paso Drag values or labels. Double-click a value to type. Arrastra los valores o las etiquetas. Haz doble clic en un valor para escribir. Drag rings to rotate. Shift snaps to 15°. Arrastra los anillos para girar. Shift ajusta a pasos de 15°. + Track cube Cubo de rotación + Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. Arrastra una cara, una arista o el anillo para girar. Shift gira sobre un eje de la pantalla. Drag the light, or its rings. Shift snaps to 15°. Arrastra la luz o sus anillos. Shift ajusta a pasos de 15°. lighting Light Luz Keep visible surfaces only when expanding Conservar solo superficies visibles al expandir @@ -6220,6 +6251,7 @@ mark-style Japanese Japonesas Export Data Sets… Exportar conjuntos de datos… Load Variable Library… Cargar biblioteca de variables… Save Variable Library… Guardar biblioteca de variables… +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml «Importar» lee un archivo de origen de datos con extensión .csv, .tsv, .txt o .xml @msg a variable library holds text variables, and the document has none una biblioteca de variables contiene variables de texto y el documento no tiene ninguna @msg variable `{name}` can't be saved in a variable library: rename it to start with a letter or `_`, without spaces or symbols other than `-`, `_` and `.` la variable `{name}` no se puede guardar en una biblioteca de variables: cámbiele el nombre para que empiece por una letra o `_`, sin espacios ni símbolos distintos de `-`, `_` y `.` @msg {k} has control characters {k} contiene caracteres de control @@ -6497,6 +6529,7 @@ axis Y Axis Eje Y @msg {what} points outside memory {what} apunta fuera de la memoria @msg `angle` must be a number `angle` debe ser un número @msg `aspect` must be from 0.01 to 100 `aspect` debe estar entre 0.01 y 100 +@msg `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 `axes` debe ser [a, b, c, d], cada uno entre -1000 y 1000, con a·d - b·c a al menos 0.001 de 0 @msg `cap` must be "butt", "round" or "square" `cap` debe ser "butt", "round" o "square" @msg `fillRule` must be "nonzero" or "evenodd" `fillRule` debe ser "nonzero" o "evenodd" @msg `helpUrl` must be an https:// address of at most {MAX_HELP_URL} bytes `helpUrl` debe ser una dirección https:// de {MAX_HELP_URL} bytes como máximo @@ -7613,6 +7646,19 @@ breakText Glyphs Glifos Not Aligned to Pixel Grid No alineado con cuadrícula de píxeles @msg only paths and compound paths can be aligned to the pixel grid solo los trazados y los trazados compuestos se pueden alinear con la cuadrícula de píxeles @msg side is left or right, not `{s}` side es left o right, no `{s}` +@msg side is left or right, not `{v}` side es left o right, no `{v}` +@msg order is a whole number from 0 to {others}, not `{v}` order es un número entero de 0 a {others}, no `{v}` +@msg toolbar (a toolbar's name) must be a string toolbar (el nombre de una barra de herramientas) debe ser una cadena de texto +@msg no toolbar named `{name}` no hay ninguna barra de herramientas llamada `{name}` +@msg toolbar name can't be empty el nombre de la barra de herramientas no puede estar vacío +@msg a toolbar name has at most {MAX_NAME} characters el nombre de una barra de herramientas tiene como máximo {MAX_NAME} caracteres +@msg there is already a toolbar named `{name}` ya hay una barra de herramientas llamada `{name}` +@msg there is already a toolbar named `{to}` ya hay una barra de herramientas llamada `{to}` +@msg a workspace keeps at most {MAX} toolbars un espacio de trabajo guarda como máximo {MAX} barras de herramientas +@msg name (a toolbar's name) must be a string name (el nombre de una barra de herramientas) debe ser una cadena de texto +@msg name (a toolbar's name) is required Se requiere name (el nombre de una barra de herramientas) +@msg to (the new name) is required Se requiere to (el nuevo nombre) +@msg name must be a toolbar's name name debe ser el nombre de una barra de herramientas Ignore All Omitir todo Add to Dictionary Añadir al diccionario No Suggestions No hay sugerencias @@ -7709,3 +7755,21 @@ breakText Glyphs Glifos Nest Shapes… Anidar formas… Nest Shapes Anidar formas Roll Rollo + Packaging Tools Herramientas de embalaje + Fold Lines Líneas de plegado + Make Cut Line Convertir en línea de corte + Make Crease Line Convertir en línea de hendido + Make Partial Cut Line Convertir en línea de corte parcial + Make Perforation Line Convertir en línea de perforación + Make Fold Line Convertir en línea de plegado + Role Swatches… Muestras de los tipos de línea… + Role Swatches Muestras de los tipos de línea + Role Tipo de línea + Cut Line Línea de corte + Crease Line Línea de hendido + Partial Cut Line Línea de corte parcial + Perforation Line Línea de perforación + No objects are selected. No hay objetos seleccionados. + Open a document to mark its fold lines. Abre un documento para marcar sus líneas de plegado. + Remove Fold Line Role Quitar tipo de línea +@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer debe ser "singleLine", "everyLine", "standardSingleLine" o "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 3aac57b1ee..67897bbe68 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -1018,6 +1018,7 @@ Change Panel Layout Muuta paneelien asettelua Close Panel Sulje paneeli Collapse Panel Group Kutista paneeliryhmä + Cycle Display Sizes Vaihda näyttökokoa Move Panel Siirrä paneelia Group with Ryhmitä kohteen kanssa Resize panels Muuta paneelien kokoa @@ -1038,6 +1039,8 @@ Step up or down Askel ylös tai alas Drag values or labels. Double-click a value to type. Vedä arvoja tai nimiöitä. Kirjoita arvo kaksoisnapsauttamalla. Drag rings to rotate. Shift snaps to 15°. Kierrä vetämällä renkaita. Vaihto kohdistaa 15°:n välein. + Track cube Kiertokuutio + Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. Kierrä vetämällä tahkoa, särmää tai rengasta. Vaihto kiertää yhden näytön akselin ympäri. Drag the light, or its rings. Shift snaps to 15°. Vedä valoa tai sen renkaita. Vaihto kohdistaa 15°:n välein. lighting Light Valo Keep visible surfaces only when expanding Säilytä laajennettaessa vain näkyvät pinnat @@ -1088,6 +1091,14 @@ lighting Light Valo Previous Artboard Edellinen piirtoalusta Next Artboard Seuraava piirtoalusta Last Artboard Viimeinen piirtoalusta + Status Bar Show Näytä tilarivillä + Artboard Name Piirtoalustan nimi + Current Tool Nykyinen työkalu + Date and Time Päivämäärä ja aika + Number of Undos Kumousten määrä + Document Color Profile Asiakirjan väriprofiili + Undos Kumoukset + Redos Uudelleentekot Graphic Style Options… Grafiikkatyylin asetukset… Symbol Options Symbolin asetukset Symbol Options… Symbolin asetukset… @@ -1599,6 +1610,8 @@ lighting Light Valo Insert Aki Left Lisää aki vasemmalle Insert Aki Right Lisää aki oikealle Tsume Tsume + Adjust Horizontal Diacritic Position Säädä tarkkeiden vaakasijaintia + Adjust Vertical Diacritic Position Säädä tarkkeiden pystysijaintia Character Direction Merkkien suunta Digits Numerot Arabic Arabia @@ -2062,7 +2075,10 @@ digits Malayalam Malajalam Tabular Lining Taulukkonumerot Tabular Oldstyle Vanhanaikaiset taulukkonumerot Titling Alternates Otsikkovaihtoehdot - Every-line Composer Kaikkien rivien asettelu + Middle Eastern & South Asian Single-line Composer Yhden rivin asettelu (Lähi-itä ja Etelä-Aasia) + Middle Eastern & South Asian Every-line Composer Kaikkien rivien asettelu (Lähi-itä ja Etelä-Aasia) + Standard Single-line Composer Tavallinen yhden rivin asettelu + Standard Every-line Composer Tavallinen kaikkien rivien asettelu First-line Left Indent Ensimmäisen rivin vasen sisennys Hyphenation… Tavutus… Words Longer Than: Sanat, jotka ovat pidempiä kuin: @@ -2102,7 +2118,6 @@ digits Malayalam Malajalam East Asian Composition Settings Itäaasialaisen ladonnan asetukset Korean Composition Settings Korean ladonnan asetukset Select a text object to edit its paragraph attributes. Valitse tekstiobjekti, jonka kappalemääritteitä haluat muokata. - Single-line Composer Yhden rivin asettelu Toggle Line Composer Vaihda rivien asettelu Space After Paragraph Väli kappaleen jälkeen Space Before Paragraph Väli ennen kappaletta @@ -2918,6 +2933,7 @@ digits Malayalam Malajalam Show smooth color wheel Näytä liukuva väriympyrä Show segmented color wheel Näytä segmentoitu väriympyrä Show color bars Näytä väripalkit + Find the selected colors in the artwork Etsi valitut värit kuvituksesta Harmony Rules Harmoniasäännöt Keep this row's colors (exclude) Säilytä tämän rivin värit (jätä pois) Limit to Library: Rajoita kirjastoon: @@ -3618,6 +3634,8 @@ theme Appearance Ulkoasu Create Graph Luo kaavio Graph Data Kaavion tiedot Graph Type Kaavion tyyppi + Graph Type… Kaavion tyyppi… + Graph Data… Kaavion tiedot… Graph Options Kaavion asetukset Left Axis Vasen akseli Right Axis Oikea akseli @@ -4712,6 +4730,17 @@ imageTrace Outline Ääriviiva @msg `name` must be the name of a script engine `name` on oltava skriptimoottorin nimi @msg the main script engine is new for each run and is never kept, so it cannot be dropped pääskriptimoottori on uusi jokaisella ajolla eikä sitä koskaan säilytetä, joten sitä ei voi poistaa @msg there is no script engine named {name} skriptimoottoria nimeltä {name} ei ole +@msg `answers` must be a list of answers `answers` on oltava vastausten luettelo +@msg `answers` has more than {MAX_ANSWERS} answers kohteessa `answers` on yli {MAX_ANSWERS} vastausta +@msg `answers` is larger than 1 MiB `answers` on suurempi kuin 1 MiB +@msg must be an object with `kind` and `value` on oltava objekti, jossa on `kind` ja `value` +@msg must have exactly `kind` and `value` siinä on oltava täsmälleen `kind` ja `value` +@msg is an alert's answer, whose `value` must be "ok" on alert-vastaus, joten sen `value`-arvon on oltava "ok" +@msg is a confirm's answer, whose `value` must be true or false on confirm-vastaus, joten sen `value`-arvon on oltava true tai false +@msg is longer than 16 KiB on pidempi kuin 16 KiB +@msg is a prompt's answer, whose `value` must be a string or null on prompt-vastaus, joten sen `value`-arvon on oltava merkkijono tai null +@msg must have `kind` alert, confirm or prompt `kind`-arvon on oltava alert, confirm tai prompt +@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` on vain ajolle, jossa ei ole ketään kysyttävää: sovelluksessa henkilö vastaa jokaiseen valintaikkunaan @msg Running a script Suoritetaan komentosarjaa @msg Copied the script report Komentosarjan raportti kopioitiin @msg Copied the link info Linkin tiedot kopioitiin @@ -5324,6 +5353,8 @@ imageTrace Outline Ääriviiva @msg unknown option `{path}.{k}` tuntematon asetus `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) tuntematon päällepainatusten käsittely `{o}` (preserve, simulate tai discard) @msg unknown panel `{raw}` tuntematon paneeli `{raw}` +@msg `{panel}` has no display sizes to cycle paneelissa `{panel}` ei ole vaihdettavia näyttökokoja +@msg the panels are not shown paneelit eivät ole näkyvissä @msg panels can't be shown in Presentation Mode paneeleja ei voi näyttää esitystilassa @msg unknown preference `{key}` tuntematon asetus `{key}` @msg Preferences imported. Asetukset tuotiin. @@ -6143,6 +6174,7 @@ mark-style Japanese Japanilainen Export Data Sets… Vie tietojoukot… Load Variable Library… Lataa muuttujakirjasto… Save Variable Library… Tallenna muuttujakirjasto… +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml ”Tuo” lukee tietolähdetiedoston, jonka tunniste on .csv, .tsv, .txt tai .xml @msg a variable library holds text variables, and the document has none muuttujakirjasto sisältää tekstimuuttujia, eikä asiakirjassa ole yhtään @msg variable `{name}` can't be saved in a variable library: rename it to start with a letter or `_`, without spaces or symbols other than `-`, `_` and `.` muuttujaa `{name}` ei voi tallentaa muuttujakirjastoon: nimeä se uudelleen niin, että se alkaa kirjaimella tai merkillä `_` eikä sisällä välilyöntejä tai muita symboleja kuin `-`, `_` ja `.` @msg {k} has control characters {k} sisältää ohjausmerkkejä @@ -6586,6 +6618,7 @@ axis Y Axis Y-akseli @msg {what} points outside memory {what} osoittaa muistin ulkopuolelle @msg `angle` must be a number `angle` on oltava luku @msg `aspect` must be from 0.01 to 100 `aspect` on oltava 0.01 ja 100 välillä +@msg `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 `axes` on oltava [a, b, c, d], kukin -1000 ja 1000 välillä, ja a·d - b·c:n on oltava vähintään 0.001:n päässä 0:sta @msg `cap` must be "butt", "round" or "square" `cap` on oltava "butt", "round" tai "square" @msg `fillRule` must be "nonzero" or "evenodd" `fillRule` on oltava "nonzero" tai "evenodd" @msg `helpUrl` must be an https:// address of at most {MAX_HELP_URL} bytes `helpUrl` on oltava enintään {MAX_HELP_URL} tavun https://-osoite @@ -7590,6 +7623,19 @@ breakText Glyphs Merkit Not Aligned to Pixel Grid Ei tasattu pikseliruudukkoon @msg only paths and compound paths can be aligned to the pixel grid vain polut ja yhdistelmäpolut voi tasata pikseliruudukkoon @msg side is left or right, not `{s}` side on left tai right, ei `{s}` +@msg side is left or right, not `{v}` side on left tai right, ei `{v}` +@msg order is a whole number from 0 to {others}, not `{v}` order on kokonaisluku, vähintään 0 ja enintään {others}, ei `{v}` +@msg toolbar (a toolbar's name) must be a string toolbar-arvon (työkalurivin nimi) on oltava merkkijono +@msg no toolbar named `{name}` ei työkaluriviä nimeltä `{name}` +@msg toolbar name can't be empty työkalurivin nimi ei voi olla tyhjä +@msg a toolbar name has at most {MAX_NAME} characters työkalurivin nimessä on enintään {MAX_NAME} merkkiä +@msg there is already a toolbar named `{name}` työkalurivi nimeltä `{name}` on jo olemassa +@msg there is already a toolbar named `{to}` työkalurivi nimeltä `{to}` on jo olemassa +@msg a workspace keeps at most {MAX} toolbars työtilassa on enintään {MAX} työkaluriviä +@msg name (a toolbar's name) must be a string name-arvon (työkalurivin nimi) on oltava merkkijono +@msg name (a toolbar's name) is required name (työkalurivin nimi) vaaditaan +@msg to (the new name) is required to (uusi nimi) vaaditaan +@msg name must be a toolbar's name name-arvon on oltava työkalurivin nimi Ignore All Ohita kaikki Add to Dictionary Lisää sanastoon No Suggestions Ei ehdotuksia @@ -7805,3 +7851,21 @@ breakText Glyphs Merkit @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 + Packaging Tools Pakkaustyökalut + Fold Lines Taittoviivat + Make Cut Line Tee leikkausviiva + Make Crease Line Tee nuuttausviiva + Make Partial Cut Line Tee osittainen leikkausviiva + Make Perforation Line Tee rei’itysviiva + Make Fold Line Tee taittoviiva + Role Swatches… Viivatyyppien värimallit… + Role Swatches Viivatyyppien värimallit + Role Viivatyyppi + Cut Line Leikkausviiva + Crease Line Nuuttausviiva + Partial Cut Line Osittainen leikkausviiva + Perforation Line Rei’itysviiva + No objects are selected. Objekteja ei ole valittu. + Open a document to mark its fold lines. Avaa asiakirja, niin voit merkitä sen taittoviivat. + Remove Fold Line Role Poista viivatyyppi +@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer on oltava "singleLine", "everyLine", "standardSingleLine" tai "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8456251424..9c04f43b1b 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1072,7 +1072,10 @@ font-technology Variable Variables Every (minutes) Toutes les (minutes) Every option is at its default. Toutes les options ont leur valeur par défaut. Every option matches {base}. Toutes les options correspondent à {base}. - Every-line Composer Compositeur multiligne + Middle Eastern & South Asian Single-line Composer Compositeur ligne par ligne (Moyen-Orient et Asie du Sud) + Middle Eastern & South Asian Every-line Composer Compositeur multiligne (Moyen-Orient et Asie du Sud) + Standard Single-line Composer Compositeur standard ligne par ligne + Standard Every-line Composer Compositeur standard multiligne Exact dash lengths Longueurs de tirets exactes Exceptions (comma separated) Exceptions (séparées par des virgules) Exclude Exclusion @@ -1396,6 +1399,14 @@ font-technology Variable Variables Previous Artboard Plan de travail précédent Next Artboard Plan de travail suivant Last Artboard Dernier plan de travail + Status Bar Show Afficher dans la barre d'état + Artboard Name Nom du plan de travail + Current Tool Outil actif + Date and Time Date et heure + Number of Undos Nombre d'annulations + Document Color Profile Profil colorimétrique du document + Undos Annulations + Redos Rétablissements Go To Link Atteindre le lien GPL palettes keep solid colours only, as RGB. Les palettes GPL ne conservent que les couleurs unies, en RVB. GPU Performance Performances GPU @@ -1415,6 +1426,8 @@ font-technology Variable Variables Graph Graphe Graph Data Données du graphe Graph Type Type de graphe + Graph Type… Type de graphe… + Graph Data… Données du graphe… Graph Options Options du graphe Left Axis Axe gauche Right Axis Axe droit @@ -1529,6 +1542,7 @@ font-technology Variable Variables Show smooth color wheel Afficher la roue chromatique continue Show segmented color wheel Afficher la roue chromatique segmentée Show color bars Afficher les barres de couleur + Find the selected colors in the artwork Rechercher les couleurs sélectionnées dans l’illustration Harmony Rules: Règles d’harmonie : Harmony Sets Ensembles d’harmonies Height Hauteur @@ -2706,6 +2720,8 @@ font-technology Variable Variables Insert Aki Left Insérer un aki à gauche Insert Aki Right Insérer un aki à droite Tsume Tsume + Adjust Horizontal Diacritic Position Ajuster la position horizontale des signes diacritiques + Adjust Vertical Diacritic Position Ajuster la position verticale des signes diacritiques Character Direction Direction des caractères Digits Chiffres Arabic Arabes @@ -3445,7 +3461,6 @@ digits Malayalam Malayalam Single Left Quotation Mark Guillemet simple ouvrant Single Quotes: Guillemets simples : Single Right Quotation Mark Guillemet simple fermant - Single-line Composer Compositeur ligne par ligne Toggle Line Composer Basculer le compositeur de lignes Sixth Space Espace d’un sixième Size Taille @@ -4471,6 +4486,7 @@ axis Both Les deux @msg `name` must be the name of a script engine `name` doit être le nom d'un moteur de script @msg the main script engine is new for each run and is never kept, so it cannot be dropped le moteur de script principal est nouveau à chaque exécution et n'est jamais conservé, il ne peut donc pas être supprimé @msg there is no script engine named {name} il n'y a aucun moteur de script nommé {name} +@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` est réservé à une exécution sans personne à qui demander : dans l'application, la personne répond à chaque boîte de dialogue @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 @@ -5098,6 +5114,8 @@ axis Both Les deux @msg unknown option `{path}.{k}` option inconnue `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) surimpressions inconnues `{o}` (preserve, simulate ou discard) @msg unknown panel `{raw}` panneau inconnu `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` n’a pas de tailles d’affichage à parcourir +@msg the panels are not shown les panneaux ne sont pas affichés @msg panels can't be shown in Presentation Mode les panneaux ne peuvent pas être affichés en mode Présentation @msg unknown preference `{key}` préférence inconnue `{key}` @msg Preferences imported. Préférences importées. @@ -5492,6 +5510,7 @@ effect Soft Doux Change Panel Layout Modifier la disposition des panneaux Close Panel Fermer le panneau Collapse Panel Group Réduire le groupe de panneaux + Cycle Display Sizes Parcourir les tailles d’affichage Move Panel Déplacer le panneau Group with Regrouper avec Resize panels Redimensionner les panneaux @@ -5535,6 +5554,8 @@ effect Soft Doux Step up or down Augmenter ou diminuer d’un cran Drag values or labels. Double-click a value to type. Faites glisser les valeurs ou les libellés. Double-cliquez sur une valeur pour la saisir. Drag rings to rotate. Shift snaps to 15°. Faites glisser les anneaux pour tourner. Maj contraint par pas de 15°. + Track cube Cube de rotation + Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. Faites glisser une face, une arête ou l'anneau pour tourner. Maj fait tourner autour d'un axe de l'écran. Drag the light, or its rings. Shift snaps to 15°. Faites glisser la lumière ou ses anneaux. Maj contraint par pas de 15°. Keep visible surfaces only when expanding Conserver uniquement les surfaces visibles lors de la décomposition Trim covered geometry on Expand Appearance. Live preview keeps the full surface. Transparent paints and surfaces exceeding visibility limits retain all faces. Découpe la géométrie masquée lors de la décomposition de l’aspect. L’aperçu conserve toute la surface. Les peintures transparentes et les surfaces dépassant les limites de visibilité conservent toutes les faces. @@ -6270,6 +6291,7 @@ theme Appearance Apparence Export Data Sets… Exporter des jeux de données… Load Variable Library… Charger une bibliothèque de variables… Save Variable Library… Enregistrer une bibliothèque de variables… +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml « Importer » lit un fichier de source de données d’extension .csv, .tsv, .txt ou .xml @msg a variable library holds text variables, and the document has none une bibliothèque de variables contient des variables de texte, et le document n’en a aucune @msg variable `{name}` can't be saved in a variable library: rename it to start with a letter or `_`, without spaces or symbols other than `-`, `_` and `.` la variable `{name}` ne peut pas être enregistrée dans une bibliothèque de variables : renommez-la pour qu’elle commence par une lettre ou `_`, sans espaces ni symboles autres que `-`, `_` et `.` @msg {k} has control characters {k} contient des caractères de contrôle @@ -7672,6 +7694,7 @@ breakText Glyphs Glyphes @msg Image Trace failed: internal error: its thread stopped (please report this bug) Échec de la vectorisation de l’image : erreur interne : son thread s’est arrêté (merci de signaler ce bogue) @msg Image Trace failed: {e} Échec de la vectorisation de l’image : {e} @msg Image Trace finished, but its document was closed La vectorisation de l’image est terminée, mais son document a été fermé +@msg Image Trace finished, but its document was reverted: trace it again La vectorisation de l’image est terminée, mais son document a été rétabli à la version précédente : vectorisez-la à nouveau @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again La vectorisation de l’image est terminée, mais l’image ou ses réglages ont changé entre-temps : vectorisez-la à nouveau @msg Import SVG Filter reads SVG files, not SVGZ Importer un filtre SVG lit les fichiers SVG, pas SVGZ @msg Invalid dimension offset Décalage de cote non valide @@ -7844,6 +7867,7 @@ breakText Glyphs Glyphes @msg `names` must be an array of style names `names` doit être une liste de noms de styles @msg `new` is a design name, or true `new` est un nom de motif, ou true @msg `origin` must be [x, y] in points `origin` doit être [x, y] en points +@msg `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 `axes` doit être [a, b, c, d], chacun compris entre -1000 et 1000, avec a·d - b·c à au moins 0.001 de 0 @msg `path` must be a folder `path` doit être un dossier @msg `path` must be a path object `path` doit être un objet tracé @msg `picks` must be an array (got {v}) `picks` doit être une liste (reçu : {v}) @@ -8243,7 +8267,7 @@ breakText Glyphs Glyphes @msg column: true floats the whole column and takes no onto, above or below column: true rend flottante toute la colonne et n’accepte ni onto, ni above, ni below @msg command must be a shape.* command command doit être une commande shape.* @msg commands[{i}]: missing `command` commands[{i}] : `command` manquant -@msg composer must be "singleLine" or "everyLine" composer doit valoir "singleLine" ou "everyLine" +@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer doit être "singleLine", "everyLine", "standardSingleLine" ou "standardEveryLine" @msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes les formes composées acceptent les tracés, tracés transparents, groupes, formes composées, textes, dégradés de formes et enveloppes @msg compound {_1} must contain exactly one open path to join le tracé transparent {_1} doit contenir exactement un tracé ouvert à joindre @msg connect end must be "start" or "end" l’extrémité de connect doit valoir "start" ou "end" @@ -9563,4 +9587,21 @@ breakText Glyphs Glyphes @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é + Packaging Tools Outils d’emballage + Fold Lines Lignes de pliage + Make Cut Line Convertir en ligne de découpe + Make Crease Line Convertir en ligne de rainage + Make Partial Cut Line Convertir en ligne de découpe partielle + Make Perforation Line Convertir en ligne de perforation + Make Fold Line Convertir en ligne de pliage + Role Swatches… Nuances des types de ligne… + Role Swatches Nuances des types de ligne + Role Type de ligne + Cut Line Ligne de découpe + Crease Line Ligne de rainage + Partial Cut Line Ligne de découpe partielle + Perforation Line Ligne de perforation + No objects are selected. Aucun objet n’est sélectionné. + Open a document to mark its fold lines. Ouvrez un document pour marquer ses lignes de pliage. + Remove Fold Line Role Supprimer le type de ligne @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 2ff32c7e3e..4807c7ec25 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -611,6 +611,7 @@ Closing bracket with no opening one ખુલતા કૌંસ વગરનો બંધ થતો કૌંસ Coincidence: સંયોગ: Collapse Panel Group પેનલ ગ્રૂપ સંકોચો + Cycle Display Sizes પ્રદર્શન કદ બદલો Collapse Panels to Icons પેનલ્સને આઇકનમાં સંકોચો Collapse to Icons આઇકનમાં સંકોચો Collate ક્રમમાં ગોઠવો @@ -1067,6 +1068,8 @@ Drag art or swatches here, or use + to add the selection's colors and text styles. અહીં આર્ટ અથવા સ્વેચ ખેંચો, અથવા પસંદગીના રંગો અને ટેક્સ્ટ સ્ટાઇલ ઉમેરવા + વાપરો. Drag onto art to apply this appearance આ દેખાવ લાગુ કરવા આર્ટ પર ખેંચો Drag rings to rotate. Shift snaps to 15°. ફેરવવા રિંગ્સ ખેંચો. Shift 15° પર સ્નેપ કરે છે. + Track cube ફેરવવાનો ઘન + Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. ફેરવવા ફલક, ધાર અથવા રિંગ ખેંચો. Shift સ્ક્રીનની એક અક્ષની આસપાસ ફેરવે છે. Drag the art to move it on the paper કાગળ પર ખસેડવા આર્ટ ખેંચો Drag the light, or its rings. Shift snaps to 15°. લાઇટ અથવા તેની રિંગ્સ ખેંચો. Shift 15° પર સ્નેપ કરે છે. Drag to float as a toolbar ટૂલબાર તરીકે ફ્લોટ કરવા ખેંચો @@ -1241,7 +1244,6 @@ Every (minutes) દર (મિનિટ) Every option is at its default. દરેક વિકલ્પ ડિફૉલ્ટ પર છે. Every option matches {base}. દરેક વિકલ્પ {base} સાથે મેળ ખાય છે. - Every-line Composer એવરી-લાઇન કમ્પોઝર Exact dash lengths ચોક્કસ ડેશ લંબાઈ Exceptions (comma separated) અપવાદો (અલ્પવિરામથી અલગ) Exclude બાકાત રાખો @@ -1547,6 +1549,8 @@ Graph Design ગ્રાફ ડિઝાઇન Graph Marker ગ્રાફ માર્કર Graph Type ગ્રાફ પ્રકાર + Graph Type… ગ્રાફ પ્રકાર… + Graph Data… ગ્રાફ ડેટા… Graph Options ગ્રાફ વિકલ્પો Left Axis ડાબી અક્ષ Right Axis જમણી અક્ષ @@ -1908,6 +1912,14 @@ Lasso Tool લાસો ટૂલ Last છેલ્લું Last Artboard છેલ્લું આર્ટબોર્ડ + Status Bar Show સ્ટેટસ બારમાં બતાવો + Artboard Name આર્ટબોર્ડનું નામ + Current Tool વર્તમાન ટૂલ + Date and Time તારીખ અને સમય + Number of Undos પૂર્વવત્ કરવાની સંખ્યા + Document Color Profile દસ્તાવેજની રંગ પ્રોફાઇલ + Undos પૂર્વવત્ + Redos ફરીથી કરો Last Effect: {name} છેલ્લી ઇફેક્ટ: {name} Last Effect… છેલ્લી ઇફેક્ટ… Last Page છેલ્લું પેજ @@ -3554,6 +3566,7 @@ Show all plates બધી પ્લેટ બતાવો Show axis અક્ષ બતાવો Show color bars રંગ બાર બતાવો + Find the selected colors in the artwork પસંદ કરેલા રંગો આર્ટવર્કમાં શોધો Show handles when multiple anchors are selected બહુવિધ એન્કર પસંદ હોય ત્યારે હૅન્ડલ બતાવો Show in Folder ફોલ્ડરમાં બતાવો Show its progress, see Cancel and write log lines તેની પ્રગતિ બતાવવી, રદ કરવાની વિનંતી જોવી અને લૉગ લાઇનો લખવી @@ -3582,7 +3595,6 @@ Single Quotes: એકલ અવતરણ ચિહ્નો: Single Right Quotation Mark જમણું એકલ અવતરણ ચિહ્ન Single Word Justification: એક શબ્દ જસ્ટિફિકેશન: - Single-line Composer સિંગલ-લાઇન કમ્પોઝર Sixth Space છઠ્ઠી જગ્યા Size કદ Size Tile to Art ટાઇલનું કદ આર્ટ પ્રમાણે કરો @@ -4435,6 +4447,8 @@ antiAlias Sharp શાર્પ Preview: પ્રીવ્યૂ: Insert Aki Left ડાબે અકી ઉમેરો Insert Aki Right જમણે અકી ઉમેરો + Adjust Horizontal Diacritic Position ડાયાક્રિટિકની આડી સ્થિતિ ગોઠવો + Adjust Vertical Diacritic Position ડાયાક્રિટિકની ઊભી સ્થિતિ ગોઠવો Conic Gradient કોનિક ગ્રેડિયન્ટ Diamond Gradient ડાયમંડ ગ્રેડિયન્ટ Include Placed Images પ્લેસ કરેલી ઇમેજો સામેલ કરો @@ -4765,3 +4779,25 @@ swatch [Registration] [રજિસ્ટ્રેશન] Repeat Objects પુનરાવર્તિત ઑબ્જેક્ટ્સ @msg `{path}` must be one of {_1}, not {got} `{path}` એ {_1}માંથી એક હોવું જોઈએ, {got} નહીં Path Length પાથની લંબાઈ + Packaging Tools પેકેજિંગ ટૂલ્સ + Fold Lines ફોલ્ડ લાઇન્સ + Make Cut Line કટ લાઇન બનાવો + Make Crease Line ક્રીઝ લાઇન બનાવો + Make Partial Cut Line આંશિક કટ લાઇન બનાવો + Make Perforation Line પર્ફોરેશન લાઇન બનાવો + Make Fold Line ફોલ્ડ લાઇન બનાવો + Role Swatches… લાઇન પ્રકારના સ્વેચ… + Role Swatches લાઇન પ્રકારના સ્વેચ + Role લાઇન પ્રકાર + Cut Line કટ લાઇન + Crease Line ક્રીઝ લાઇન + Partial Cut Line આંશિક કટ લાઇન + Perforation Line પર્ફોરેશન લાઇન + No objects are selected. કોઈ ઑબ્જેક્ટ પસંદ કરેલ નથી. + Open a document to mark its fold lines. તેની ફોલ્ડ લાઇન્સ ચિહ્નિત કરવા દસ્તાવેજ ખોલો. + Remove Fold Line Role લાઇન પ્રકાર દૂર કરો + Middle Eastern & South Asian Single-line Composer સિંગલ-લાઇન કમ્પોઝર (મધ્ય પૂર્વ અને દક્ષિણ એશિયા) + Middle Eastern & South Asian Every-line Composer એવરી-લાઇન કમ્પોઝર (મધ્ય પૂર્વ અને દક્ષિણ એશિયા) + Standard Single-line Composer સ્ટાન્ડર્ડ સિંગલ-લાઇન કમ્પોઝર + Standard Every-line Composer સ્ટાન્ડર્ડ એવરી-લાઇન કમ્પોઝર +@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer આમાંથી એક હોવું જોઈએ: "singleLine", "everyLine", "standardSingleLine" અથવા "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 8a74c4fe75..15582a2dbd 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -900,6 +900,7 @@ antiAlias Sharp शार्प Coarse Dots मोटे बिंदु Coincidence: संयोग: Collapse Panel Group पैनल समूह संक्षिप्त करें + Cycle Display Sizes प्रदर्शन आकार बदलें Collapse Panels to Icons सिकोड़ें करने के लिए पैनल Collapse to Icons प्रतीक के लिए पतन Collate कोलेट @@ -1508,6 +1509,8 @@ antiAlias Sharp शार्प Drag out from a corner, or click two straight lines, then click to place. एक कोने से बाहर खींचें, या दो सीधी रेखाओं पर क्लिक करें, फिर जगह पर क्लिक करें। Drag out from a segment, or click two points, then click to place. एक खंड से बाहर खींचें, या दो बिंदुओं पर क्लिक करें, फिर जगह पर क्लिक करें। Drag rings to rotate. Shift snaps to 15°. घुमाने के लिए रिंग ड्रैग करें। Shift से 15° पर स्नैप होता है। + Track cube घुमाने का घन + Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. घुमाने के लिए फलक, किनारा या रिंग ड्रैग करें। Shift से स्क्रीन के एक अक्ष के चारों ओर घूमता है। Drag the art to move it on the paper इसे कागज पर स्थानांतरित करने के लिए कला को खींचें Drag the light, or its rings. Shift snaps to 15°. लाइट या उसकी रिंग ड्रैग करें। Shift से 15° पर स्नैप होता है। Drag to float as a toolbar एक टूलबार के रूप में तैरने के लिए खींचें @@ -1718,7 +1721,8 @@ antiAlias Sharp शार्प Every (minutes) हर (मिनट) Every option is at its default. प्रत्येक ऑप्शन इसके डिफ़ॉल्ट रूप से होता है। Every option matches {base}. प्रत्येक ऑप्शन {base} से मेल खाता है। - Every-line Composer हर लाइन संगीतकार + Middle Eastern & South Asian Every-line Composer हर लाइन संगीतकार (मध्य पूर्व और दक्षिण एशिया) + Standard Every-line Composer मानक हर लाइन संगीतकार Exact सटीक Exact dash lengths सटीक डैश लंबाई Example: {name} उदाहरण: {name} @@ -2122,6 +2126,8 @@ antiAlias Sharp शार्प Graph Design ग्राफ़ डिजाइन Graph Marker ग्राफ़ मार्कर Graph Type ग्राफ़ टाइप + Graph Type… ग्राफ़ टाइप… + Graph Data… ग्राफ़ डेटा… Graph Options ग्राफ़ विकल्प Left Axis बायाँ एक्सिस Right Axis दायाँ एक्सिस @@ -2570,6 +2576,14 @@ antiAlias Sharp शार्प Lasso Tool लैस्सो टूल Last अंतिम Last Artboard अंतिम आर्टबोर्ड + Status Bar Show स्टेटस बार में दिखाएँ + Artboard Name आर्टबोर्ड का नाम + Current Tool मौजूदा टूल + Date and Time तारीख और समय + Number of Undos पूर्ववत करने की संख्या + Document Color Profile दस्तावेज़ की रंग प्रोफ़ाइल + Undos पूर्ववत + Redos फिर से करें Last commit अंतिम कमिट Last Effect: {} अंतिम इफ़ेक्ट: {} Last Effect: {name} अंतिम इफ़ेक्ट: {name} @@ -3762,6 +3776,8 @@ antiAlias Sharp शार्प Insert Aki Left बाईं ओर आकी जोड़ें Insert Aki Right दाईं ओर आकी जोड़ें Tsume त्सुमे + Adjust Horizontal Diacritic Position डायक्रिटिक की क्षैतिज स्थिति समायोजित करें + Adjust Vertical Diacritic Position डायक्रिटिक की लंबवत स्थिति समायोजित करें Proportional Oldstyle आनुपातिक ओल्डस्टाइल Protect Corners कॉर्नर को सुरक्षित रखें Proximity Guides निकटता गाइड @@ -4305,6 +4321,7 @@ antiAlias Sharp शार्प Save Transparency Flattener Preset ट्रांसपेरेंसी फ़्लैटनर प्रीसेट सेव करें Save Transparency Flattener Preset… ट्रांसपेरेंसी फ़्लैटनर प्रीसेट सेव करें… Save Variable Library… वेरिएबल लाइब्रेरी सेव करें… +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml "इम्पोर्ट करें" .csv, .tsv, .txt या .xml एक्सटेंशन वाली डेटा स्रोत फ़ाइल पढ़ता है Save… सेव… Saved सेव किए गए SAVED सेव किए गए @@ -4638,6 +4655,7 @@ antiAlias Sharp शार्प Show Center Mark शो सेंटर मार्क Show Code कोड दिखाएं Show color bars रंग सलाखों दिखाएँ + Find the selected colors in the artwork चयनित रंगों को आर्टवर्क में खोजें Show Color Groups रंग समूह दिखाएँ Show Color Swatches रंग स्वॉचेस दिखाएँ Show Corner Widget शो कॉर्नर विजेट @@ -4740,7 +4758,8 @@ antiAlias Sharp शार्प Single Quotes: एकल उद्धरण: Single Right Quotation Mark सिंगल राइट कोटेशन मार्क Single Word Justification: एकल शब्द जस्टिफ़िकेशन: - Single-line Composer एकल लाइन संगीतकार + Middle Eastern & South Asian Single-line Composer एकल लाइन संगीतकार (मध्य पूर्व और दक्षिण एशिया) + Standard Single-line Composer मानक एकल लाइन संगीतकार Sixth Space छठे हिस्से जितना स्पेस Size आकार Size Tile to Art आकार टाइल कला के लिए @@ -5711,6 +5730,7 @@ antiAlias Sharp शार्प @msg needs approval: it asks for {0}, which the user grants when installing it on its own स्वीकृति आवश्यक: यह {0} माँगता है, जिसे उपयोगकर्ता इसे अलग से स्थापित करते समय देता है @msg `angle` must be a number `angle` एक संख्या होना चाहिए @msg `aspect` must be from 0.01 to 100 `aspect` 0.01 से 100 तक होना चाहिए +@msg `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 `axes` [a, b, c, d] होना चाहिए, हर मान -1000 से 1000 तक, और a·d - b·c का 0 से अंतर कम से कम 0.001 होना चाहिए @msg `cap` must be "butt", "round" or "square" `cap` "butt", "round" या "square" होना चाहिए @msg `fillRule` must be "nonzero" or "evenodd" `fillRule` "nonzero" या "evenodd" होना चाहिए @msg `helpUrl` must be an https:// address of at most {MAX_HELP_URL} bytes `helpUrl` अधिकतम {MAX_HELP_URL} बाइट का https:// पता होना चाहिए @@ -6703,7 +6723,7 @@ antiAlias Sharp शार्प @msg command `{id}` is not available right now आदेश `{id}` अभी उपलब्ध नहीं है @msg command must be a shape.* command command कोई shape.* कमांड होना चाहिए @msg commands[{i}]: missing `command` आदेश [{i}]: लापता `command` -@msg composer must be "singleLine" or "everyLine" composer "singleLine" या "everyLine" होना चाहिए +@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer "singleLine", "everyLine", "standardSingleLine" या "standardEveryLine" होना चाहिए @msg compound {_1} must contain exactly one open path to join जोड़ने के लिए कंपाउंड {_1} में ठीक एक खुला पाथ होना चाहिए @msg compound paths can only contain paths यौगिक पाथ में केवल पाथ हो सकते हैं @msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes कंपाउंड शेप पाथ, कंपाउंड पाथ, समूह, कंपाउंड शेप, टाइप, ब्लेंड और एन्वेलप लेते हैं @@ -6821,6 +6841,18 @@ antiAlias Sharp शार्प @msg `name` must be the name of a script engine `name` किसी स्क्रिप्ट इंजन का नाम होना चाहिए @msg the main script engine is new for each run and is never kept, so it cannot be dropped मुख्य स्क्रिप्ट इंजन हर रन के लिए नया होता है और कभी रखा नहीं जाता, इसलिए इसे हटाया नहीं जा सकता @msg there is no script engine named {name} {name} नाम का कोई स्क्रिप्ट इंजन नहीं है +@msg `answers` must be a list of answers `answers` उत्तरों की सूची होनी चाहिए +@msg `answers` has more than {MAX_ANSWERS} answers `answers` में {MAX_ANSWERS} से अधिक उत्तर हैं +@msg `answers` is larger than 1 MiB `answers` 1 MiB से बड़ा है +@msg `answers[{i}]` {e} `answers[{i}]`: {e} +@msg must be an object with `kind` and `value` `kind` और `value` वाला ऑब्जेक्ट होना चाहिए +@msg must have exactly `kind` and `value` इसमें ठीक-ठीक `kind` और `value` होने चाहिए +@msg is an alert's answer, whose `value` must be "ok" यह alert का उत्तर है, इसलिए इसका `value` "ok" होना चाहिए +@msg is a confirm's answer, whose `value` must be true or false यह confirm का उत्तर है, इसलिए इसका `value` true या false होना चाहिए +@msg is longer than 16 KiB 16 KiB से लंबा है +@msg is a prompt's answer, whose `value` must be a string or null यह prompt का उत्तर है, इसलिए इसका `value` स्ट्रिंग या null होना चाहिए +@msg must have `kind` alert, confirm or prompt `kind` alert, confirm या prompt होना चाहिए +@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` केवल ऐसे रन के लिए है जिसमें पूछने के लिए कोई नहीं है: ऐप में, व्यक्ति हर डायलॉग का उत्तर देता है @msg Running a script स्क्रिप्ट चल रही है @msg Copied the script report Copied स्क्रिप्ट रिपोर्ट @msg Copied the link info लिंक जानकारी कॉपी की गई @@ -7116,6 +7148,7 @@ antiAlias Sharp शार्प @msg Image Trace failed: internal error: its thread stopped (please report this bug) इमेज ट्रेस विफल: आंतरिक त्रुटि: इसके धागे को बंद कर दिया (कृपया इस बग की रिपोर्ट करें) @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 Image Trace finished, but its document was reverted: trace it again इमेज ट्रेस समाप्त हो गया, लेकिन इसके डॉक्यूमेंट को मूल स्थिति में लाया गया: इसे फिर से ट्रेस करें @msg Image Trace: the traced image is missing इमेज ट्रेस: ज्ञात इमेज गायब है @msg image would be too large; lower the resolution इमेज बहुत बड़ी होगी; रिज़ॉल्यूशन कम करें @msg imageMap `{m}`: none, client or server imageMap `{m}`: none, client या server @@ -8596,6 +8629,8 @@ antiAlias Sharp शार्प @msg unknown overprints `{v}` (preserve, simulate or discard) अज्ञात ओवरप्रिंट `{v}` (preserve, simulate या discard) @msg unknown panel अज्ञात पैनल @msg unknown panel `{raw}` अज्ञात पैनल `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` के पास बदलने के लिए कोई प्रदर्शन आकार नहीं है +@msg the panels are not shown पैनल नहीं दिखाए गए हैं @msg panels can't be shown in Presentation Mode प्रस्तुति मोड में पैनल्स नहीं दिखाए जा सकते @msg unknown parameter `{key}`; did you mean `{near}`? अज्ञात पैरामीटर `{key}`; क्या आपको `{near}` का मतलब है? @msg unknown parameter `{key}`; the command takes no parameters अज्ञात पैरामीटर `{key}`; कमांड कोई पैरामीटर नहीं लेता है @@ -8945,6 +8980,8 @@ theme Appearance अपीयरेंस @msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` इंपोर्टर 1 से {MAX_EXTENSIONS} `extensions` घोषित करता है @msg an importer always gets an import's budget: leave `budget` out इंपोर्टर को हमेशा इंपोर्ट का बजट मिलता है: `budget` छोड़ दें @msg side is left or right, not `{s}` side left या right होना चाहिए, `{s}` नहीं +@msg side is left or right, not `{v}` side left या right होना चाहिए, `{v}` नहीं +@msg order is a whole number from 0 to {others}, not `{v}` order 0 से {others} तक की पूर्ण संख्या होनी चाहिए, `{v}` नहीं Ignore All सभी को अनदेखा करें Add to Dictionary शब्दकोश में जोड़ें No Suggestions कोई सुझाव नहीं @@ -9159,3 +9196,20 @@ theme Appearance अपीयरेंस Nest Shapes… आकृतियाँ सटाकर रखें… Nest Shapes आकृतियाँ सटाकर रखें Roll रोल + Packaging Tools पैकेजिंग टूल्स + Fold Lines फ़ोल्ड लाइनें + Make Cut Line कट लाइन बनाएँ + Make Crease Line क्रीज़ लाइन बनाएँ + Make Partial Cut Line आंशिक कट लाइन बनाएँ + Make Perforation Line परफ़ोरेशन लाइन बनाएँ + Make Fold Line फ़ोल्ड लाइन बनाएँ + Role Swatches… लाइन प्रकार के स्वॉचेस… + Role Swatches लाइन प्रकार के स्वॉचेस + Role लाइन प्रकार + Cut Line कट लाइन + Crease Line क्रीज़ लाइन + Partial Cut Line आंशिक कट लाइन + Perforation Line परफ़ोरेशन लाइन + No objects are selected. कोई ऑब्जेक्ट सिलेक्ट नहीं है। + Open a document to mark its fold lines. फ़ोल्ड लाइनें मार्क करने के लिए कोई डॉक्यूमेंट ओपन करें। + Remove Fold Line Role लाइन प्रकार हटाएँ diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index ec1774747e..8ddb1d34ca 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -686,6 +686,7 @@ font-technology Variable Változó Close Library Könyvtár bezárása Close Panel Panel bezárása Collapse Panel Group Panelcsoport összecsukása + Cycle Display Sizes Megjelenítési méretek váltása Close Path Útvonal lezárása Close paths when ends are within: Útvonalak lezárása, ha a végek távolsága legfeljebb: Clumped Csomós @@ -1208,6 +1209,8 @@ font-technology Variable Változó Drag art, colors and text styles here to reuse them across documents. Libraries are stored on this machine — no account required. Húzz ide grafikát, színeket és szövegstílusokat, hogy más dokumentumokban is használhasd őket. A könyvtárak ezen a gépen tárolódnak, fiók nem kell hozzájuk. Drag onto art to apply this appearance Grafikára húzva alkalmazza ezt a megjelenést Drag rings to rotate. Shift snaps to 15°. Forgatáshoz húzd a gyűrűket. Shift: illesztés 15°-onként. + Track cube Forgatókocka + Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. Forgatáshoz húzz egy lapot, egy élt vagy a gyűrűt. Shift: forgatás egy képernyőtengely körül. Drag the art to move it on the paper Húzd a grafikát a papíron való áthelyezéshez Drag the light, or its rings. Shift snaps to 15°. Húzd a fényt vagy a gyűrűit. Shift: illesztés 15°-onként. Drag to float as a toolbar Húzd el, hogy önálló eszköztárként lebegjen @@ -1368,7 +1371,10 @@ font-technology Variable Változó Every (minutes) Gyakoriság (perc) Every option is at its default. Minden beállítás az alapértéken áll. Every option matches {base}. Minden beállítás egyezik: {base}. - Every-line Composer Többsoros tördelő + Middle Eastern & South Asian Single-line Composer Egysoros tördelő (Közel-Kelet és Dél-Ázsia) + Middle Eastern & South Asian Every-line Composer Többsoros tördelő (Közel-Kelet és Dél-Ázsia) + Standard Single-line Composer Normál egysoros tördelő + Standard Every-line Composer Normál többsoros tördelő Exact Pontos Exact dash lengths Pontos vonalhosszak Exceptions (comma separated) Kivételek (vesszővel elválasztva) @@ -1744,6 +1750,14 @@ file-filter Templates Sablonok Previous Artboard Előző rajztábla Next Artboard Következő rajztábla Last Artboard Utolsó rajztábla + Status Bar Show Megjelenítés az állapotsorban + Artboard Name Rajztábla neve + Current Tool Aktuális eszköz + Date and Time Dátum és idő + Number of Undos Visszavonások száma + Document Color Profile Dokumentum színprofilja + Undos Visszavonások + Redos Újra Go to Conflict Ugrás az ütközésre Go To Link Ugrás a csatoláshoz Good Jó @@ -1771,6 +1785,8 @@ file-filter Templates Sablonok Graph Diagram Graph Data Diagramadatok Graph Type Diagramtípus + Graph Type… Diagramtípus… + Graph Data… Diagramadatok… Graph Options Diagrambeállítások Left Axis Bal tengely Right Axis Jobb tengely @@ -1940,6 +1956,7 @@ file-filter Templates Sablonok Show smooth color wheel Folytonos színkör megjelenítése Show segmented color wheel Szegmentált színkör megjelenítése Show color bars Színsávok megjelenítése + Find the selected colors in the artwork A kijelölt színek keresése a grafikában Harmony Sets Harmóniakészletek HDTV 1080p HDTV 1080p HDTV 720p HDTV 720p @@ -3276,6 +3293,8 @@ mark-style Japanese Japán Insert Aki Left Aki beszúrása balra Insert Aki Right Aki beszúrása jobbra Tsume Tsume + Adjust Horizontal Diacritic Position Mellékjelek vízszintes helyzetének igazítása + Adjust Vertical Diacritic Position Mellékjelek függőleges helyzetének igazítása Proportional Lining Arányos modern Position: Pozíció: Default Position Alapértelmezett pozíció @@ -4107,7 +4126,6 @@ mark-style Japanese Japán Single Left Quotation Mark Bal oldali szimpla idézőjel Single Quotes: Szimpla idézőjelek: Single Right Quotation Mark Jobb oldali szimpla idézőjel - Single-line Composer Egysoros tördelő Toggle Line Composer Sortördelő váltása Sixth Space Hatodkvirt-szóköz Size Méret @@ -5300,6 +5318,8 @@ imageTrace Outline Körvonal @msg `name` must be the name of a script engine a `name` értékének egy parancsfájlmotor nevének kell lennie @msg the main script engine is new for each run and is never kept, so it cannot be dropped a fő parancsfájlmotor minden futáshoz új, és sosem marad meg, ezért nem dobható el @msg there is no script engine named {name} nincs {name} nevű parancsfájlmotor +@msg `answers[{i}]` {e} `answers[{i}]`: {e} +@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog az `answers` csak olyan futtatáshoz való, ahol nincs kit megkérdezni: az alkalmazásban minden párbeszédpanelre a felhasználó válaszol @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 @@ -5937,6 +5957,8 @@ imageTrace Outline Körvonal @msg unknown option `{path}.{k}` ismeretlen beállítás: `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) ismeretlen felülnyomás-kezelés: `{o}` (preserve, simulate vagy discard) @msg unknown panel `{raw}` ismeretlen panel: `{raw}` +@msg `{panel}` has no display sizes to cycle a(z) `{panel}` panelnek nincsenek váltható megjelenítési méretei +@msg the panels are not shown a panelek nem láthatók @msg panels can't be shown in Presentation Mode bemutató módban a panelek nem jeleníthetők meg @msg unknown preference `{key}` ismeretlen beállítás: `{key}` @msg Preferences imported. A beállítások importálva. @@ -6258,6 +6280,7 @@ imageTrace Outline Körvonal Export Data Sets… Adatkészletek exportálása… Load Variable Library… Változókönyvtár betöltése… Save Variable Library… Változókönyvtár mentése… +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml Az „Importálás” .csv, .tsv, .txt vagy .xml kiterjesztésű adatforrásfájlt olvas be @msg a variable library holds text variables, and the document has none a változókönyvtár szöveges változókat tartalmaz, a dokumentumban pedig nincs ilyen @msg variable `{name}` can't be saved in a variable library: rename it to start with a letter or `_`, without spaces or symbols other than `-`, `_` and `.` a(z) `{name}` változó nem menthető változókönyvtárba: nevezze át úgy, hogy betűvel vagy `_` jellel kezdődjön, szóközök és a `-`, `_` és `.` jeltől eltérő szimbólumok nélkül @msg {k} has control characters {k} vezérlőkaraktereket tartalmaz @@ -7674,6 +7697,7 @@ breakText Glyphs Glifák @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 Image Trace finished, but its document was reverted: trace it again A képvektorizálás elkészült, de a dokumentumát visszaállították a mentett változatra: 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 @@ -7847,6 +7871,7 @@ breakText Glyphs Glifák @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 `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 `axes`: [a, b, c, d] kell, mindegyik -1000 és 1000 között, és a·d - b·c legalább 0.001-gyel térjen el 0-tól @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}) @@ -8252,7 +8277,7 @@ breakText Glyphs Glifák @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 composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer értéke "singleLine", "everyLine", "standardSingleLine" vagy "standardEveryLine" lehet @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 @@ -9565,3 +9590,20 @@ breakText Glyphs Glifák @msg {width} × {height} pixels is too large for JPEG (at most 65535 pixels a side): lower the resolution {width} × {height} pixel túl nagy a JPEG formátumhoz (oldalanként legfeljebb 65535 pixel): csökkentsd a felbontást @msg {width} × {height} pixels is too large for Targa (at most 65535 pixels a side): lower the resolution {width} × {height} pixel túl nagy a Targa formátumhoz (oldalanként legfeljebb 65535 pixel): csökkentsd a felbontást @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} pixel túl nagy a PSD formátumhoz (oldalanként legfeljebb {MAX_SIDE} pixel): csökkentsd a felbontást + Packaging Tools Csomagolóeszközök + Fold Lines Hajtásvonalak + Make Cut Line Vágóvonallá alakítás + Make Crease Line Bigvonallá alakítás + Make Partial Cut Line Részleges vágóvonallá alakítás + Make Perforation Line Perforációs vonallá alakítás + Make Fold Line Hajtásvonallá alakítás + Role Swatches… Vonaltípusok színmintái… + Role Swatches Vonaltípusok színmintái + Role Vonaltípus + Cut Line Vágóvonal + Crease Line Bigvonal + Partial Cut Line Részleges vágóvonal + Perforation Line Perforációs vonal + No objects are selected. Nincs kijelölt objektum. + Open a document to mark its fold lines. Nyiss meg egy dokumentumot a hajtásvonalai megjelöléséhez. + Remove Fold Line Role Vonaltípus eltávolítása diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index e1a003c623..8d7639c430 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -957,6 +957,7 @@ Change Panel Layout Ubah tata letak panel Close Panel Tutup panel Collapse Panel Group Ciutkan grup panel + Cycle Display Sizes Ganti ukuran tampilan Move Panel Pindahkan panel Group with Grupkan dengan Resize panels Ubah ukuran panel @@ -976,6 +977,8 @@ Reset all Revolve settings to their defaults. Atur ulang semua pengaturan Revolusi ke defaultnya. Drag values or labels. Double-click a value to type. Seret nilai atau label. Klik dua kali pada nilai untuk mengetik. Drag rings to rotate. Shift snaps to 15°. Seret cincin untuk memutar. Shift mengunci ke kelipatan 15°. + Track cube Kubus putar + Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. Seret sisi, tepi, atau cincin untuk memutar. Shift memutar pada satu sumbu layar. Drag the light, or its rings. Shift snaps to 15°. Seret cahaya atau cincinnya. Shift mengunci ke kelipatan 15°. lighting Light Cahaya Keep visible surfaces only when expanding Pertahankan hanya permukaan yang terlihat saat memperluas @@ -1532,6 +1535,8 @@ lighting Light Cahaya Insert Aki Left Sisipkan aki kiri Insert Aki Right Sisipkan aki kanan Tsume Tsume + Adjust Horizontal Diacritic Position Sesuaikan posisi horizontal diakritik + Adjust Vertical Diacritic Position Sesuaikan posisi vertikal diakritik Character Direction Arah karakter Digits Digit Arabic Arab @@ -1867,7 +1872,10 @@ digits Malayalam Malayalam Tabular Lining Lining tabular Tabular Oldstyle Oldstyle tabular Titling Alternates Alternatif judul - Every-line Composer Komposer tiap baris + Middle Eastern & South Asian Single-line Composer Komposer satu baris (Timur Tengah dan Asia Selatan) + Middle Eastern & South Asian Every-line Composer Komposer tiap baris (Timur Tengah dan Asia Selatan) + Standard Single-line Composer Komposer standar satu baris + Standard Every-line Composer Komposer standar tiap baris First-line Left Indent Indentasi kiri baris pertama Hyphenation… Pemenggalan kata… Justification… Justifikasi… @@ -1899,7 +1907,6 @@ digits Malayalam Malayalam East Asian Composition Settings Pengaturan komposisi Asia Timur Korean Composition Settings Pengaturan komposisi Korea Select a text object to edit its paragraph attributes. Pilih objek teks untuk mengedit atribut paragrafnya. - Single-line Composer Komposer satu baris Toggle Line Composer Alihkan komposer baris Space After Paragraph Spasi setelah paragraf Space Before Paragraph Spasi sebelum paragraf @@ -2714,6 +2721,7 @@ digits Malayalam Malayalam Show smooth color wheel Tampilkan roda warna halus Show segmented color wheel Tampilkan roda warna bersegmen Show color bars Tampilkan bilah warna + Find the selected colors in the artwork Temukan warna yang dipilih di karya seni Harmony Rules Aturan harmoni Keep this row's colors (exclude) Pertahankan warna baris ini (kecualikan) Limit to Library: Batasi ke pustaka: @@ -3369,6 +3377,8 @@ theme Appearance Tampilan Create Graph Buat grafik Graph Data Data grafik Graph Type Jenis grafik + Graph Type… Jenis grafik… + Graph Data… Data grafik… Graph Options Opsi grafik Left Axis Sumbu kiri Right Axis Sumbu kanan @@ -5858,6 +5868,14 @@ swatch Bright Violet Violet cerah Color wheel Roda warna First Artboard Artboard pertama Last Artboard Artboard terakhir + Status Bar Show Tampilkan di bilah status + Artboard Name Nama artboard + Current Tool Alat saat ini + Date and Time Tanggal dan waktu + Number of Undos Jumlah urungkan + Document Color Profile Profil warna dokumen + Undos Urungkan + Redos Ulangi Next Artboard Artboard berikutnya Previous Artboard Artboard sebelumnya Step up or down Naikkan atau turunkan bertahap @@ -7000,3 +7018,21 @@ breakText Glyphs Glif Nest Shapes… Susun Bentuk… Nest Shapes Susun Bentuk Roll Gulungan + Packaging Tools Alat kemasan + Fold Lines Garis lipat + Make Cut Line Jadikan garis potong + Make Crease Line Jadikan garis lekuk + Make Partial Cut Line Jadikan garis potong sebagian + Make Perforation Line Jadikan garis perforasi + Make Fold Line Jadikan garis lipat + Role Swatches… Swatch jenis garis… + Role Swatches Swatch jenis garis + Role Jenis garis + Cut Line Garis potong + Crease Line Garis lekuk + Partial Cut Line Garis potong sebagian + Perforation Line Garis perforasi + No objects are selected. Tidak ada objek yang dipilih. + Open a document to mark its fold lines. Buka dokumen untuk menandai garis lipatnya. + Remove Fold Line Role Hapus jenis garis +@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer harus "singleLine", "everyLine", "standardSingleLine", atau "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 7b09eeb9eb..1c0590ff98 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1086,7 +1086,8 @@ font-technology Variable Variabili Every (minutes) Ogni (minuti) Every option is at its default. Tutte le opzioni hanno il valore predefinito. Every option matches {base}. Tutte le opzioni corrispondono a {base}. - Every-line Composer Composizione su tutte le righe + Middle Eastern & South Asian Every-line Composer Composizione su tutte le righe (Medio Oriente e Asia meridionale) + Standard Every-line Composer Composizione standard su tutte le righe Exact dash lengths Lunghezze esatte dei trattini Exceptions (comma separated) Eccezioni (separate da virgole) Exclude Escludi @@ -1423,6 +1424,14 @@ file-filter Templates Modelli Previous Artboard Tavola da disegno precedente Next Artboard Tavola da disegno successiva Last Artboard Ultima tavola da disegno + Status Bar Show Mostra nella barra di stato + Artboard Name Nome tavola da disegno + Current Tool Strumento attivo + Date and Time Data e ora + Number of Undos Numero di annullamenti + Document Color Profile Profilo colore del documento + Undos Annullamenti + Redos Ripristini Go To Link Vai al collegamento GPL palettes keep solid colours only, as RGB. Le palette GPL conservano solo i colori pieni, in RGB. GPU Performance Prestazioni GPU @@ -1442,6 +1451,8 @@ file-filter Templates Modelli Graph Grafico Graph Data Dati grafico Graph Type Tipo di grafico + Graph Type… Tipo di grafico… + Graph Data… Dati grafico… Graph Options Opzioni grafico Left Axis Asse sinistro Right Axis Asse destro @@ -1557,6 +1568,7 @@ file-filter Templates Modelli Show smooth color wheel Mostra ruota dei colori continua Show segmented color wheel Mostra ruota dei colori segmentata Show color bars Mostra barre di colore + Find the selected colors in the artwork Trova i colori selezionati nella grafica Harmony Sets Gruppi di armonia Height Altezza Height: Altezza: @@ -2756,6 +2768,8 @@ mark-style Japanese Giapponese Insert Aki Left Inserisci aki a sinistra Insert Aki Right Inserisci aki a destra Tsume Tsume + Adjust Horizontal Diacritic Position Regola posizione orizzontale dei segni diacritici + Adjust Vertical Diacritic Position Regola posizione verticale dei segni diacritici Character Direction Direzione caratteri Digits Cifre Arabic Arabe @@ -3498,7 +3512,8 @@ digits Malayalam Malayalam Single Left Quotation Mark Virgoletta singola di apertura Single Quotes: Virgolette singole: Single Right Quotation Mark Virgoletta singola di chiusura - Single-line Composer Composizione su riga singola + Middle Eastern & South Asian Single-line Composer Composizione su riga singola (Medio Oriente e Asia meridionale) + Standard Single-line Composer Composizione standard su riga singola Toggle Line Composer Alterna composizione delle righe Sixth Space Spazio di un sesto Size Dimensione @@ -5161,6 +5176,8 @@ axis Both Entrambi @msg unknown option `{path}.{k}` opzione sconosciuta `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) valore di sovrastampa sconosciuto `{o}` (preserve, simulate o discard) @msg unknown panel `{raw}` pannello sconosciuto `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` non ha dimensioni di visualizzazione da scorrere +@msg the panels are not shown i pannelli non sono visualizzati @msg panels can't be shown in Presentation Mode i pannelli non possono essere mostrati in modalità presentazione @msg unknown preference `{key}` preferenza sconosciuta `{key}` @msg Preferences imported. Preferenze importate. @@ -5538,6 +5555,7 @@ effect Regular Normale Change Panel Layout Modifica disposizione dei pannelli Close Panel Chiudi pannello Collapse Panel Group Comprimi gruppo di pannelli + Cycle Display Sizes Scorri le dimensioni di visualizzazione Move Panel Sposta pannello Group with Raggruppa con Resize panels Ridimensiona pannelli @@ -5583,6 +5601,8 @@ effect Regular Normale Step up or down Aumenta o riduci di un passo Drag values or labels. Double-click a value to type. Trascina i valori o le etichette. Fai doppio clic su un valore per digitarlo. Drag rings to rotate. Shift snaps to 15°. Trascina gli anelli per ruotare. Shift usa incrementi di 15°. + Track cube Cubo di rotazione + Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. Trascina una faccia, uno spigolo o l'anello per ruotare. Shift ruota attorno a un asse dello schermo. Drag the light, or its rings. Shift snaps to 15°. Trascina la luce o i suoi anelli. Shift usa incrementi di 15°. lighting Light Luce Keep visible surfaces only when expanding Mantieni solo le superfici visibili durante l’espansione @@ -5895,6 +5915,7 @@ lighting Light Luce Export Data Sets… Esporta set di dati… Load Variable Library… Carica libreria di variabili… Save Variable Library… Salva libreria di variabili… +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml «Importa» legge un file di origine dati con estensione .csv, .tsv, .txt o .xml @msg a variable library holds text variables, and the document has none una libreria di variabili contiene variabili di testo e il documento non ne ha @msg variable `{name}` can't be saved in a variable library: rename it to start with a letter or `_`, without spaces or symbols other than `-`, `_` and `.` la variabile `{name}` non può essere salvata in una libreria di variabili: rinominala in modo che inizi con una lettera o `_`, senza spazi né simboli diversi da `-`, `_` e `.` @msg data set `{name}` holds a control character, which a variable library can't hold il set di dati `{name}` contiene un carattere di controllo, che una libreria di variabili non può contenere @@ -7300,6 +7321,7 @@ breakText Glyphs Glifi @msg `answer` for this {kind} dialog must be one of: {_1} `answer` per questa finestra di dialogo {kind} deve essere uno tra: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` ha più di {MAX_ANSWERS} risposte @msg `answers` is larger than 1 MiB `answers` supera 1 MiB +@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` è solo per un'esecuzione senza nessuno a cui chiedere: nell'app, la persona risponde a ogni finestra di dialogo @msg `answers` must be a list of answers `answers` deve essere un elenco di risposte @msg `artboard` must be the index of an artboard of the document `artboard` deve essere l'indice di una tavola da disegno del documento @msg `artboardsAt` must be [x, y] `artboardsAt` deve essere [x, y] @@ -7332,6 +7354,7 @@ breakText Glyphs Glifi @msg `name` must be a name that is not empty `name` deve essere un nome non vuoto @msg `name` must not be empty `name` non deve essere vuoto @msg `origin` must be [x, y] in points `origin` deve essere [x, y] in punti +@msg `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 `axes` deve essere [a, b, c, d], ciascuno compreso tra -1000 e 1000, con a·d - b·c distante almeno 0.001 da 0 @msg `picks` must be an array (got {v}) `picks` deve essere un array (ricevuto {v}) @msg `picks` must hold 1 to {MAX_PICKS} picks (got {_1}) `picks` deve contenere da 1 a {MAX_PICKS} scelte (ricevute {_1}) @msg `points` must hold from 2 to 100000 points `points` deve contenere da 2 a 100000 punti @@ -7699,6 +7722,7 @@ breakText Glyphs Glifi @msg Image Trace failed: {e} Ricalco immagine non riuscito: {e} @msg Image Trace finished, but its document was closed Ricalco immagine terminato, ma il suo documento è stato chiuso @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Ricalco immagine terminato, ma nel frattempo l'immagine o le sue impostazioni sono cambiate: ricalcala di nuovo +@msg Image Trace finished, but its document was reverted: trace it again Ricalco immagine terminato, ma il suo documento è stato ripristinato: ricalcala di nuovo @msg Invalid dimension offset Distanza della quota non valida @msg Invalid point Punto non valido @msg Join: a subpath went missing Unisci: un sottotracciato è andato perso @@ -8113,7 +8137,7 @@ breakText Glyphs Glifi @msg column: true floats the whole column and takes no onto, above or below column: true rende mobile l'intera colonna e non accetta onto, above o below @msg command must be a shape.* command command deve essere un comando shape.* @msg commands[{i}]: missing `command` commands[{i}]: `command` mancante -@msg composer must be "singleLine" or "everyLine" composer deve essere "singleLine" o "everyLine" +@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer deve essere "singleLine", "everyLine", "standardSingleLine" o "standardEveryLine" @msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes le forme composte accettano tracciati, tracciati composti, gruppi, forme composte, testo, fusioni e involucri @msg compound {_1} must contain exactly one open path to join il composto {_1} deve contenere esattamente un tracciato aperto da unire @msg connect end must be "start" or "end" end di connect deve essere "start" o "end" @@ -9210,3 +9234,20 @@ breakText Glyphs Glifi Nest Shapes… Annida forme… Nest Shapes Annida forme Roll Rotolo + Packaging Tools Strumenti di imballaggio + Fold Lines Linee di piega + Make Cut Line Trasforma in linea di taglio + Make Crease Line Trasforma in linea di cordonatura + Make Partial Cut Line Trasforma in linea di taglio parziale + Make Perforation Line Trasforma in linea di perforazione + Make Fold Line Trasforma in linea di piega + Role Swatches… Campioni dei tipi di linea… + Role Swatches Campioni dei tipi di linea + Role Tipo di linea + Cut Line Linea di taglio + Crease Line Linea di cordonatura + Partial Cut Line Linea di taglio parziale + Perforation Line Linea di perforazione + No objects are selected. Nessun oggetto selezionato. + Open a document to mark its fold lines. Apri un documento per segnarne le linee di piega. + Remove Fold Line Role Rimuovi tipo di linea diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 1afd8a863d..dedcdb328e 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -55,6 +55,8 @@ font-technology Variable バリアブル Insert Aki Left 前にアキを挿入 Insert Aki Right 後ろにアキを挿入 Tsume 文字ツメ + Adjust Horizontal Diacritic Position 発音区別符号の水平位置を調整 + Adjust Vertical Diacritic Position 発音区別符号の垂直位置を調整 Character Direction 文字の方向 Digits 数字 Arabic アラビア数字 @@ -1688,7 +1690,10 @@ antiAlias Sharp シャープ Every (minutes) 間隔 (分) Every option is at its default. すべてのオプションが初期値です。 Every option matches {base}. すべてのオプションが {base} と同じです。 - Every-line Composer すべての行を一括処理 + Middle Eastern & South Asian Single-line Composer 1 行ずつ組む (中東・南アジア) + Middle Eastern & South Asian Every-line Composer すべての行を一括処理 (中東・南アジア) + Standard Single-line Composer 1 行ずつ組む (標準) + Standard Every-line Composer すべての行を一括処理 (標準) Exact dash lengths 破線の長さを正確に保つ Exceptions (comma separated) 例外 (カンマ区切り) Exclusion 除外 @@ -1885,6 +1890,14 @@ antiAlias Sharp シャープ Previous Artboard 前のアートボード Next Artboard 次のアートボード Last Artboard 最後のアートボード + Status Bar Show ステータスバーの表示 + Artboard Name アートボード名 + Current Tool 現在のツール + Date and Time 日付と時刻 + Number of Undos 取り消し回数 + Document Color Profile ドキュメントのカラープロファイル + Undos 取り消し + Redos やり直し Gradient Fill: click to apply, drag onto art グラデーションの塗り: クリックで適用、アートにドラッグ Gradient Mesh グラデーションメッシュ Gradient Tool グラデーションツール @@ -1927,6 +1940,7 @@ antiAlias Sharp シャープ Show smooth color wheel 滑らかなカラーホイールを表示 Show segmented color wheel 分割カラーホイールを表示 Show color bars カラーバーを表示 + Find the selected colors in the artwork 選択したカラーをアートワーク内で検索 Height 高さ Height: 高さ: Help › Search Commands… ヘルプ › コマンドを検索… @@ -3282,7 +3296,6 @@ mark-style Japanese 日本式 Simulate Colored Paper 色紙をシミュレート Simulate Paper 紙色をシミュレート Single Quotes: 一重引用符: - Single-line Composer 1 行ずつ組む Toggle Line Composer 行の組版方式を切り替え Size Tile to Art タイルをアートワークのサイズに合わせる Move Tile with Art タイルをアートワークと一緒に移動 @@ -3861,6 +3874,8 @@ file-filter Templates テンプレート Gradient (. or Shift+.) グラデーション (. または Shift+.) Graph Data グラフデータ Graph Type グラフの種類 + Graph Type… グラフの種類… + Graph Data… グラフデータ… Graph Options グラフオプション Left Axis 左軸 Right Axis 右軸 @@ -5098,6 +5113,8 @@ swatch Bright Violet ビビッドバイオレット @msg give only one of onto, below and above onto、below、above のうち 1 つだけを指定してください @msg column must be true or a number from 1 column には true または 1 以上の数値を指定してください @msg unknown panel `{raw}` `{raw}` は不明なパネルです +@msg `{panel}` has no display sizes to cycle `{panel}` には切り替える表示サイズがありません +@msg the panels are not shown パネルが表示されていません @msg panels can't be shown in Presentation Mode プレゼンテーションモードではパネルを表示できません @msg x and y must both be numbers x と y はどちらも数値で指定してください @msg Downloaded {what} {what} をダウンロードしました @@ -5299,6 +5316,7 @@ swatch Bright Violet ビビッドバイオレット @msg `name` must be the name of a script engine `name` はスクリプトエンジンの名前にしてください @msg the main script engine is new for each run and is never kept, so it cannot be dropped メインのスクリプトエンジンは実行ごとに新しく作られ、保持されないため、破棄できません @msg there is no script engine named {name} {name} という名前のスクリプトエンジンはありません +@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` は尋ねる相手がいない実行専用です。アプリでは、各ダイアログに本人が回答します @msg Running a script スクリプトを実行中 @msg Copied the script report スクリプトのレポートをコピーしました @msg Copied the link info リンク情報をコピーしました @@ -5580,6 +5598,7 @@ effect Vertical 垂直 Change Panel Layout パネルの配置を変更 Close Panel パネルを閉じる Collapse Panel Group パネルグループを折りたたむ + Cycle Display Sizes 表示サイズを切り替え Move Panel パネルを移動 Group with グループ化先 Resize panels パネルのサイズを変更 @@ -5625,6 +5644,8 @@ effect Vertical 垂直 Step up or down 1 段階ずつ増減 Drag values or labels. Double-click a value to type. 数値やラベルをドラッグして調整。数値をダブルクリックすると入力できます。 Drag rings to rotate. Shift snaps to 15°. リングをドラッグして回転。Shiftで15°刻みに調整。 + Track cube 回転キューブ + Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. 面、辺、またはリングをドラッグして回転。Shiftで画面の1つの軸を中心に回転。 Drag the light, or its rings. Shift snaps to 15°. ライトやリングをドラッグ。Shiftで15°刻みに調整。 lighting Light ライト Keep visible surfaces only when expanding アピアランス分割時に見える面だけを保持 @@ -5939,6 +5960,7 @@ lighting Light ライト Export Data Sets… データセットを書き出し… Load Variable Library… 変数ライブラリを読み込み… Save Variable Library… 変数ライブラリを保存… +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml 「読み込み」は拡張子が .csv、.tsv、.txt、.xml のデータソースファイルを読み込みます @msg a variable library holds text variables, and the document has none 変数ライブラリにはテキスト変数を保存しますが、このドキュメントにはテキスト変数がありません @msg variable `{name}` can't be saved in a variable library: rename it to start with a letter or `_`, without spaces or symbols other than `-`, `_` and `.` 変数 `{name}` は変数ライブラリに保存できません: 英字または `_` で始まり、スペースや `-`、`_`、`.` 以外の記号を含まない名前に変更してください @msg {k} has control characters {k} に制御文字が含まれています @@ -6532,6 +6554,7 @@ axis Y Axis Y 軸 @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 `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 `axes` には [a, b, c, d] を指定してください (各値は -1000 から 1000、a·d - b·c は 0 から 0.001 以上離れた値) @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 個の点が必要です @@ -6900,6 +6923,7 @@ axis Y Axis Y 軸 @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 Image Trace finished, but its document was reverted: trace it again 画像トレースは完了しましたが、ドキュメントは保存済みの状態に戻されました: もう一度トレースしてください @msg Invalid dimension offset 寸法のオフセットが無効です @msg Invalid point 点が無効です @msg Join: a subpath went missing 連結: サブパスが見つからなくなりました @@ -7314,7 +7338,7 @@ axis Y Axis Y 軸 @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 composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer は "singleLine"、"everyLine"、"standardSingleLine"、"standardEveryLine" のいずれかにしてください @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" を指定してください @@ -9277,3 +9301,20 @@ breakText Glyphs 字形 @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} + Packaging Tools パッケージツール + Fold Lines 折り線 + Make Cut Line カット線にする + Make Crease Line 筋入れ線にする + Make Partial Cut Line 半抜き線にする + Make Perforation Line ミシン目線にする + Make Fold Line 折り線にする + Role Swatches… 線種のスウォッチ… + Role Swatches 線種のスウォッチ + Role 線種 + Cut Line カット線 + Crease Line 筋入れ線 + Partial Cut Line 半抜き線 + Perforation Line ミシン目線 + No objects are selected. オブジェクトが選択されていません。 + Open a document to mark its fold lines. ドキュメントを開くと折り線を設定できます。 + Remove Fold Line Role 線種を解除 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 28c75307c7..d9d75dd737 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -15,6 +15,2091 @@ # Left in English on purpose (`MENU_KEEP_AS_IS` in the tests): the product name, language names, # OpenType, the built-in workspace names and the bracketed perspective grid preset names. Keep # placeholders, ellipses and the leading/trailing spaces of fragments when editing. +# Georgian rows untranslated on main (catch-up, 2026-11-15) + Add as Single Graphic ერთ გრაფიკად დამატება + Expand as Wireframes კარკასებად გაშლა + Add art with Add as Single Graphic, or drop art here. დაამატეთ ნახატი ბრძანებით „ერთ გრაფიკად დამატება“ ან ჩამოაგდეთ ნახატი აქ. + Face მხარე + Graphics map onto the Plane, Extrude and Revolve object types. გრაფიკა თავსდება ობიექტის ტიპებზე „სიბრტყე“, „ამოწევა“ და „ბრუნვა“. + Line Gap სტრიქონებს შორის ღრეჩო + Manage Profiles პროფილების მართვა + Mapped graphics განთავსებული გრაფიკა + Materials მასალები + NEW DOCUMENT PROFILES ახალი დოკუმენტის პროფილები + Pick a graphic above to map it onto the object. აირჩიეთ გრაფიკა ზემოთ, რომ ობიექტზე განათავსოთ. + Remove Graphic გრაფიკის მოცილება + Replace the selected 3D objects with the edges of their faces, as stroked paths. მონიშნული 3D ობიექტების ჩანაცვლება მათი წახნაგების წიბოებით, კონტურიანი ტრაექტორიების სახით. + Select a 3D object to map the graphic onto it. მონიშნეთ 3D ობიექტი, რომ მასზე გრაფიკა განათავსოთ. + The selected objects have different graphics. მონიშნულ ობიექტებს სხვადასხვა გრაფიკა აქვს. + Word Gap სიტყვებს შორის ღრეჩო + Drop Script Engine სკრიპტის ძრავის მოცილება + Edit Paragraph Style აბზაცის სტილის რედაქტირება + Edit Profile პროფილის რედაქტირება + List Script Engines სკრიპტის ძრავების სია + Map Graphic გრაფიკის განთავსება + Move Object on Path ტრაექტორიაზე ობიექტის გადაადგილება + New Document Profiles ახალი დოკუმენტის პროფილები + Reset Profile პროფილის ჩამოყრა + Select Object on Path ტრაექტორიაზე ობიექტის მონიშვნა + Weather Icons ამინდის ხატულები +@msg 'caller', 'callee' and 'arguments' cannot be used on strict mode functions 'caller', 'callee' და 'arguments' მკაცრი რეჟიმის ფუნქციებში ვერ გამოიყენება +@msg 3D effects require finite coordinates within 100 million points 3D ეფექტებს სჭირდება სასრული კოორდინატები 100 მილიონი პუნქტის ფარგლებში +@msg 3D effects require one to ten lights 3D ეფექტებს სჭირდება ერთიდან ათამდე სინათლის წყარო +@msg A profile supports one Revolve effect. Edit the existing effect's options instead. პროფილს მხოლოდ ერთი „ბრუნვის“ ეფექტი შეიძლება ჰქონდეს. სანაცვლოდ შეცვალეთ არსებული ეფექტის პარამეტრები. +@msg Add Points at Crossings: a path went missing წერტილების დამატება გადაკვეთებზე: ერთ-ერთი ტრაექტორია დაიკარგა +@msg Alignment must be one of the choices სწორება უნდა იყოს ერთ-ერთი შემოთავაზებული ვარიანტი +@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 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 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-ად ბაიტების რიგის ნიშნით (BOM) +@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 Cannot write to the location of “{name}”; choose where to save it იქ, სადაც „{name}“ მდებარეობს, ჩაწერა შეუძლებელია; აირჩიეთ, სად შეინახოთ +@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 DCS files can only be placed linked: use File › Place with Link on DCS ფაილების განთავსება მხოლოდ ბმულით შეიძლება: გამოიყენეთ ფაილი › განთავსება და ჩართეთ „ბმული“ +@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 Date.prototype method called on a value that is not a Date object Date.prototype-ის მეთოდი გამოძახებულია მნიშვნელობაზე, რომელიც Date ობიექტი არ არის +@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 „შიგნით ხატვას“ სჭირდება ზუსტად ერთი მონიშნული ტრაექტორია, შედგენილი ტრაექტორია ან ტექსტი +@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 Error.prototype.toString was called on a value that is not an object Error.prototype.toString გამოძახებულია მნიშვნელობაზე, რომელიც ობიექტი არ არის +@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 Function.prototype.toString was called on a value that is not a function Function.prototype.toString გამოძახებულია მნიშვნელობაზე, რომელიც ფუნქცია არ არის +@msg GIF encoding failed: the palette image is malformed GIF-ის კოდირება ვერ მოხერხდა: პალიტრის გამოსახულება დაზიანებულია +@msg GIF encoding failed: {e} GIF-ის კოდირება ვერ მოხერხდა: {e} +@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 Import SVG Filter reads SVG files, not SVGZ „SVG ფილტრის იმპორტი“ კითხულობს SVG ფაილებს და არა SVGZ-ს +@msg Invalid dimension offset ზომის არასწორი წანაცვლება +@msg Invalid point არასწორი წერტილი +@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 JSON.parse: {why} (at offset {at}) JSON.parse: {why} (წანაცვლება {at}) +@msg JSON.stringify cannot write a structure that contains itself JSON.stringify ვერ ჩაწერს სტრუქტურას, რომელიც თავის თავს შეიცავს +@msg Join: a subpath went missing შეერთება: ერთ-ერთი ქვეტრაექტორია დაიკარგა +@msg Line Gap must be a number „სტრიქონებს შორის ღრეჩო“ უნდა იყოს რიცხვი +@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 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 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 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 QName.prototype.toString needs a QName QName.prototype.toString-ს სჭირდება QName +@msg Recolor Artwork is no longer open „ნახატის ხელახლა შეფერადება“ აღარ არის გახსნილი +@msg RegExp.prototype.{name} was called on a value that is not a RegExp object RegExp.prototype.{name} გამოძახებულია მნიშვნელობაზე, რომელიც RegExp ობიექტი არ არის +@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 is not UTF-8, UTF-16 or ISO 8859-1 SVG არ არის UTF-8, UTF-16 ან ISO 8859-1 +@msg SVG options: {e} SVG-ის პარამეტრები: {e} +@msg Save for Web settings: {e} „ვებისთვის შენახვის“ პარამეტრები: {e} +@msg Save writes one artboard: name one, or export several with document.export შენახვა ერთ სამუშაო დაფას წერს: მიუთითეთ ერთი, ან რამდენიმის ექსპორტისთვის გამოიყენეთ 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 მონიშნეთ ორი ან მეტი ობიექტი, ან ჯგუფი +@msg Shaper needs 1–64 source paths ფორმირებას სჭირდება 1–64 საწყისი ტრაექტორია +@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 Switch x/y is for scatter graphs „x/y-ის გაცვლა“ წერტილოვანი დიაგრამებისთვისაა +@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 Text options: {e} ტექსტის პარამეტრები: {e} +@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 The {name} profile could not be read, so the new document has the default settings: {reason} პროფილის „{name}“ წაკითხვა ვერ მოხერხდა, ამიტომ ახალ დოკუმენტს ნაგულისხმევი პარამეტრები აქვს: {reason} +@msg Too many Revolve faces for visibility evaluation ხილვადობის შესაფასებლად ბრუნვას ზედმეტად ბევრი წახნაგი აქვს +@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 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 Weed Box and Lines: no weeding line fits outside the art, and the weed box is off ნარჩენის მოსაცილებელი ჩარჩო და ხაზები: ნახატის გარეთ ნარჩენის მოსაცილებელი არცერთი ხაზი არ ეტევა, ნარჩენის ჩარჩო კი გამორთულია +@msg [{j}] `{_1}`: {why} [{j}] `{_1}`: {why} +@msg \\ at end of pattern \\ შაბლონის ბოლოს +@msg `alignOn` cannot be empty `alignOn` ცარიელი ვერ იქნება +@msg `alignOn` must be a string `alignOn` უნდა იყოს სტრიქონი +@msg `align` is start, center or end `align` არის start, center ან end +@msg `align` must be a string `align` უნდა იყოს სტრიქონი +@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 `answer` for this {kind} dialog must be one of: {_1} დიალოგისთვის (ტიპი: {kind}) `answer` უნდა იყოს ერთ-ერთი: {_1} +@msg `answers[{i}]` {e} `answers[{i}]` {e} +@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` must be a list of artboard indices `artboards` უნდა იყოს სამუშაო დაფების ინდექსების სია +@msg `artboards` names an artboard the document does not have `artboards` მიუთითებს სამუშაო დაფას, რომელიც დოკუმენტს არ აქვს +@msg `artboards` names an artboard twice `artboards` ერთსა და იმავე სამუშაო დაფას ორჯერ მიუთითებს +@msg `asset` is the asset id (see assets.list) `asset` არის რესურსის id (იხ. assets.list) +@msg `at` must be [x, y] (got {at}) `at` უნდა იყოს [x, y] (მიღებულია {at}) +@msg `at` must be a byte offset `at` უნდა იყოს ბაიტური წანაცვლება +@msg `at` must be a point [x, y] `at` უნდა იყოს წერტილი [x, y] +@msg `autoLeading` must be a number `autoLeading` უნდა იყოს რიცხვი +@msg `background` must be "", "matte" or #rrggbb `background` უნდა იყოს "", "matte" ან #rrggbb +@msg `beside` needs `side` `beside`-ს სჭირდება `side` +@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 `code` must be a whole number `code` უნდა იყოს მთელი რიცხვი +@msg `colorMode` must be one of rgb, cmyk `colorMode` უნდა იყოს ერთ-ერთი: rgb, cmyk +@msg `color` needs a `rule` to make the theme from `color`-ს სჭირდება `rule`, რომლითაც თემა შეიქმნება +@msg `colors` does not apply to the {name} reduction `colors` არ ვრცელდება ფერების შემცირების მეთოდზე „{name}“ +@msg `colors` is empty `colors` ცარიელია +@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 `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 0 to {MAX_COUNT} `count` უნდა იყოს მთელი რიცხვი 0-დან {MAX_COUNT}-მდე +@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` `destinationFolder` აუცილებელია, როცა destination არის `folder` +@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 `ditherAmount` must be a number from 0 to 100 `ditherAmount` უნდა იყოს რიცხვი 0-დან 100-მდე +@msg `each` is the value one design stands for, more than 0 `each` არის მნიშვნელობა, რომელსაც ერთი დიზაინი გამოხატავს; 0-ზე მეტი +@msg `end` must be "start" or "end" `end` უნდა იყოს "start" ან "end" +@msg `ends` applies to joining exactly two paths `ends` ვრცელდება ზუსტად ორი ტრაექტორიის შეერთებაზე +@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 `fidelity` must be from {lo} to {hi} pt `fidelity` უნდა იყოს {lo}-დან {hi} pt-მდე +@msg `files` must be 1 to 1000 paths of font files the last text.findFontFiles search found `files` უნდა იყოს შრიფტის ფაილების 1-დან 1000-მდე გზა, რომლებიც ბოლო text.findFontFiles ძიებამ იპოვა +@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 `folder` must be an absolute folder path `folder` უნდა იყოს საქაღალდის აბსოლუტური გზა +@msg `fontAxes` must be an object of axis tags and values, such as {{"wght": 650}} `fontAxes` უნდა იყოს ღერძების ტეგებისა და მნიშვნელობების ობიექტი, მაგალითად {{"wght": 650}} +@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` უნდა იყოს არაუარყოფითი მთელი რიცხვი +@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` ეკუთვნის ერთ სიმბოლოს და არა სიმბოლოს სტილს (მას text.setGlyphAlternate აყენებს) +@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 `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` is an object id, not {v} `id` ობიექტის id უნდა იყოს და არა {v} +@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` იღებს მაქსიმუმ {MAX_INSPECT_IDS} id-ს +@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 `index` უნდა იყოს მთელი რიცხვი +@msg `index` must be a whole number or null `index` უნდა იყოს მთელი რიცხვი ან null +@msg `indices` must be a non-empty array of item indices `indices` უნდა იყოს ელემენტების ინდექსების არაცარიელი მასივი +@msg `item` needs `index` `item`-ს სჭირდება `index` +@msg `items` is a list of {{kind, item}} `items` არის {{kind, item}} ჩანაწერების სია +@msg `items` is empty `items` ცარიელია +@msg `items` must be a list of {{id, anchors?}}, not {v} `items` უნდა იყოს {{id, anchors?}} ჩანაწერების სია და არა {v} +@msg `items` must be a list of {{id, points}} `items` უნდა იყოს {{id, points}} ჩანაწერების სია +@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 `kerningBefore` belongs to a line's first character, not to a character style (text.setRangeStyle sets it) `kerningBefore` ეკუთვნის სტრიქონის პირველ სიმბოლოს და არა სიმბოლოს სტილს (მას text.setRangeStyle აყენებს) +@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 `kinsokuType` must be "pushInFirst", "pushOutFirst" or "pushOutOnly" `kinsokuType` უნდა იყოს "pushInFirst", "pushOutFirst" ან "pushOutOnly" +@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 `leader` must be a string `leader` უნდა იყოს სტრიქონი +@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 `max` must be 1 to {MAX_SUGGESTIONS} `max` უნდა იყოს 1-დან {MAX_SUGGESTIONS}-მდე +@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 `name` must be a name that is not empty `name` უნდა იყოს არაცარიელი სახელი +@msg `name` must not be empty `name` არ უნდა იყოს ცარიელი +@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 `origin` must be [x, y] in points `origin` უნდა იყოს [x, y] პუნქტებში +@msg `path` must be a folder `path` უნდა იყოს საქაღალდე +@msg `path` must be a path object `path` უნდა იყოს ტრაექტორიის ობიექტი +@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 `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 `points` must hold from 2 to 100000 points `points` უნდა შეიცავდეს 2-დან 100000-მდე წერტილს +@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 `radius` must be 0 or more `radius` უნდა იყოს 0 ან მეტი +@msg `ratio` must be from 0.1 to 0.5 `ratio` უნდა იყოს 0.1-დან 0.5-მდე +@msg `rect` must be [x, y, width, height] `rect` უნდა იყოს [x, y, width, height] +@msg `rect` must be [x, y, width, height] with a positive size `rect` უნდა იყოს [x, y, width, height] დადებითი ზომით +@msg `rect` must be [x0, y0, x1, y1] (got {r}) `rect` უნდა იყოს [x0, y0, x1, y1] (მიღებულია {r}) +@msg `relation` must be overlap, inside or outside `relation` უნდა იყოს overlap, inside ან outside +@msg `replace` must be a string `replace` უნდა იყოს სტრიქონი +@msg `reversed` must be true or false `reversed` უნდა იყოს true ან false +@msg `rotate` must be a finite number `rotate` უნდა იყოს სასრული რიცხვი +@msg `rows` must be lists of numbers or nulls, not {r} `rows` უნდა იყოს რიცხვების ან null-ების სიები და არა {r} +@msg `rule` must be nonZero or evenOdd `rule` უნდა იყოს nonZero ან evenOdd +@msg `scale` must be a number from 0.001 to 1000 `scale` უნდა იყოს რიცხვი 0.001-დან 1000-მდე +@msg `scale` must be a number in (0, 100] `scale` უნდა იყოს რიცხვი (0, 100] შუალედში +@msg `scope.{key}` must be a non-empty array `scope.{key}` უნდა იყოს არაცარიელი მასივი +@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` არის სერიების ინდექსების არაცარიელი სია +@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 `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 `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` is the only path in series group `target` `source` ერთადერთი ტრაექტორიაა სერიის ჯგუფში `target` +@msg `source` must be `folder` or `datasets` `source` უნდა იყოს `folder` ან `datasets` +@msg `spacing` makes more than {MAX_COUNT} lines across the box `spacing` ჩარჩოში {MAX_COUNT}-ზე მეტ ხაზს ქმნის +@msg `spacing` must be a number `spacing` უნდა იყოს რიცხვი +@msg `spacing` must be a number of points, 0 or more, or "auto" `spacing` უნდა იყოს რიცხვი პუნქტებში (0 ან მეტი) ან "auto" +@msg `spacing` must be more than 0 and at most {MAX_DISTANCE} pt `spacing` უნდა იყოს 0-ზე მეტი და არაუმეტეს {MAX_DISTANCE} pt-ისა +@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` უნდა იყოს ორი მთელრიცხვა ინდექსი +@msg `symbol` must be a symbol name `symbol` უნდა იყოს სიმბოლოს სახელი +@msg `target` must be "object" or "contents", not {v} `target` უნდა იყოს "object" ან "contents" და არა {v} +@msg `target` must be an object of the same Objects on Path group as `member` `target` უნდა იყოს ობიექტი იმავე ტრაექტორიაზე ობიექტების ჯგუფიდან, რომელშიც `member` არის +@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` იღებს ერთი ობიექტის დასტის სტრიქონებს და არა გასწორებულ სტრიქონებს +@msg `tolerance` must be from 0 to 100 pt `tolerance` უნდა იყოს 0-დან 100 pt-მდე +@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` ერთსა და იმავე სახეობას ორჯერ მიუთითებს +@msg `version` must be 0 or {_1} `version` უნდა იყოს 0 ან {_1} +@msg `version` must be 0 or {newest} `version` უნდა იყოს 0 ან {newest} +@msg `view` is smallThumb, mediumThumb, largeThumb, smallList or largeList `view` არის smallThumb, mediumThumb, largeThumb, smallList ან largeList +@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} რიცხვის სია, თითო სტრიქონზე ერთი (მიღებულია {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 `{_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 `{base}` is larger than {_1} MB `{base}` {_1} MB-ზე დიდია +@msg `{base}` is not in the DCS file's folder `{base}` DCS ფაილის საქაღალდეში არ არის +@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}` holds more than {MAX_EDIT_WORDS} words `{key}` {MAX_EDIT_WORDS}-ზე მეტ სიტყვას შეიცავს +@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 0 or more `{key}` უნდა იყოს 0 ან მეტი +@msg `{key}` must be [min, desired, max] or {{min?, desired?, max?}}, in percent `{key}` უნდა იყოს [min, desired, max] ან {{min?, desired?, max?}}, პროცენტებში +@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 non-negative integer `{key}` უნდა იყოს არაუარყოფითი მთელი რიცხვი +@msg `{key}` must be a number or null, not {v} `{key}` უნდა იყოს რიცხვი ან null და არა {v} +@msg `{key}` must be a number {_1}..{_2} `{key}` უნდა იყოს რიცხვი {_1}..{_2} +@msg `{key}` must be a whole number of 0 or more `{key}` უნდა იყოს მთელი რიცხვი, 0 ან მეტი +@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 0 to {MAX_DISTANCE} pt `{key}` უნდა იყოს 0-დან {MAX_DISTANCE} pt-მდე +@msg `{key}` must be from 0.01 to 1000 pt `{key}` უნდა იყოს 0.01-დან 1000 pt-მდე +@msg `{key}` must be from {_1} to {shift_max} `{key}` უნდა იყოს {_1}-დან {shift_max}-მდე +@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} სიმბოლოსი +@msg `{key}` must hold single words of at most {_1} characters `{key}` უნდა შეიცავდეს ცალკეულ სიტყვებს, თითოეული არაუმეტეს {_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 `{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 `{name}` Word-ის დოკუმენტში არ არის UTF-8 ან UTF-16 ტექსტი +@msg `{name}` in the Word document is not well-formed XML: {e} `{name}` Word-ის დოკუმენტში სწორად აგებული XML არ არის: {e} +@msg `{name}` in the Word document nests elements more than {MAX_NESTING} deep `{name}` Word-ის დოკუმენტში შეიცავს {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 file of its own, which can only be found next to the DCS file's path `{name}` ცალკე ფაილია, რომლის პოვნაც მხოლოდ DCS ფაილის გვერდით შეიძლება +@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 `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: მინიმალური არ უნდა აღემატებოდეს სასურველს, ხოლო სასურველი — მაქსიმალურს +@msg `{name}`: {_1}: {e} `{name}`: {_1}: {e} +@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" +@msg `{to}` is empty or already used `{to}` ცარიელია ან უკვე გამოიყენება +@msg `{u}` is no Unicode character `{u}` Unicode სიმბოლო არ არის +@msg `{what}` is longer than {MAX_TEXT} bytes `{what}` {MAX_TEXT} ბაიტზე გრძელია +@msg `{what}` must be text `{what}` უნდა იყოს ტექსტი +@msg `{word}` isn't in the custom dictionary `{word}` მომხმარებლის ლექსიკონში არ არის +@msg a CMap has too many mappings CMap-ს ზედმეტად ბევრი შესაბამისობა აქვს +@msg a DXF drawing has one origin: pass useArtboards: true for one drawing per artboard DXF ნახაზს ერთი საწყისი წერტილი აქვს: თითო სამუშაო დაფაზე ცალკე ნახაზისთვის გადაეცით useArtboards: true +@msg a PDF presets file with over {_1} presets PDF-ის პრესეტების ფაილი {_1}-ზე მეტი პრესეტით +@msg a \\u escape needs four hexadecimal digits \\u ესკეიპ-მიმდევრობას ოთხი თექვსმეტობითი ციფრი სჭირდება +@msg a batch preview cannot switch documents პაკეტური წინასწარი ნახვა დოკუმენტებს ვერ გადართავს +@msg a brush named `{nn}` exists ფუნჯი სახელით `{nn}` უკვე არსებობს +@msg a comma in an XPath expression must separate function arguments XPath გამოსახულებაში მძიმე ფუნქციის არგუმენტებს უნდა გამოყოფდეს +@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 holds at most {_1} SVG filters დოკუმენტი შეიცავს მაქსიმუმ {_1} SVG ფილტრს +@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 დოკუმენტს შეიძლება ჰქონდეს მაქსიმუმ {MAX_SVG_SCRIPTS} დაკავშირებული JavaScript ფაილი +@msg a document with unsaved changes has no recovery copy შეუნახავი ცვლილებების მქონე დოკუმენტს აღდგენის ასლი არ აქვს +@msg a feConvolveMatrix filter's order is {x}×{y}, which overflows the kernel-size multiply usvg makes feConvolveMatrix ფილტრის რიგი არის {x}×{y}, რაც usvg-ის მიერ ბირთვის ზომის გამოთვლისას გადავსებას იწვევს +@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 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 host value has too many entries ჰოსტის მნიშვნელობას ზედმეტად ბევრი ჩანაწერი აქვს +@msg a host value is nested too deep ჰოსტის მნიშვნელობა ზედმეტად ღრმადაა ჩადგმული +@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 line can't run from a point to itself ხაზი წერტილიდან იმავე წერტილამდე ვერ გაივლის +@msg a line needs at least two points ხაზს სჭირდება მინიმუმ ორი წერტილი +@msg a name names one asset: give multiple: false, or one object სახელი ერთ რესურსს აღნიშნავს: მიუთითეთ multiple: false ან ერთი ობიექტი +@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 cannot be read რიცხვის წაკითხვა ვერ ხერხდება +@msg a number has no digits რიცხვს ციფრები არ აქვს +@msg a number's exponent has no digits რიცხვის ხარისხის მაჩვენებელს ციფრები არ აქვს +@msg a number's fraction has no digits რიცხვის წილად ნაწილს ციფრები არ აქვს +@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}) გვერდის ესკიზი უნდა შედგებოდეს RGB პიქსელებისგან, თითო მხარე 1-დან {THUMBNAIL_SIZE}-მდე (მიღებულია {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 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 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 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 სტრიქონი შეიცავს escape-მიმდევრობას, რომელიც JSON-ში არ არსებობს +@msg a string is not closed სტრიქონი არ არის დახურული +@msg a style named `{name}` already exists სტილი სახელით `{name}` უკვე არსებობს +@msg a style named `{to}` already exists სტილი სახელით `{to}` უკვე არსებობს +@msg a swatch exchange block is too long ფერის ნიმუშების გაცვლის ბლოკი ზედმეტად გრძელია +@msg a swatch exchange name is too long ფერის ნიმუშების გაცვლის სახელი ზედმეტად გრძელია +@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 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 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 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 ელემენტს ერთი და იმავე სახელის ორი ატრიბუტი აქვს +@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-ად მხოლოდ მაშინ გარდაიქმნება, როცა ერთი ელემენტი აქვს +@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 artboard is listed twice სამუშაო დაფა ორჯერაა ჩამოთვლილი +@msg an empty artboard has no width or height to scale to ცარიელ სამუშაო დაფას არ აქვს სიგანე ან სიმაღლე, რომელზეც მასშტაბირება შეიძლება +@msg an image could not be written: {e} გამოსახულების ჩაწერა ვერ მოხერხდა: {e} +@msg an image couldn't be decoded and is missing from the picture გამოსახულების დეკოდირება ვერ მოხერხდა და ის ნახატს აკლია +@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 image of {w} × {h} pixels is too large to convert (at most {_1} pixels) {w} × {h} პიქსელის გამოსახულება გარდასაქმნელად ზედმეტად დიდია (არაუმეტეს {_1} პიქსელი) +@msg an image that couldn't be read was left out გამოსახულება, რომლის წაკითხვაც ვერ მოხერხდა, გამოტოვებულია +@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 კუთხე და სიმრგვალე უნდა იყოს სასრული +@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 apply was called on a value that is not a function apply გამოძახებულია მნიშვნელობაზე, რომელიც ფუნქცია არ არის +@msg area must be a closed polygon of 3 to 100000 [x, y] points area უნდა იყოს შეკრული მრავალკუთხედი 3-დან 100000-მდე [x, y] წერტილით +@msg area type in a thread cannot use Dynamic Text: {frames} დაკავშირებულ ტექსტში არის ტექსტი ვერ გამოიყენებს დინამიკურ ტექსტს: {frames} +@msg area type needs a path that encloses an area არის ტექსტს სჭირდება ტრაექტორია, რომელიც არეს შემოსაზღვრავს +@msg area type {_1} is named twice არის ტექსტი {_1} ორჯერაა დასახელებული +@msg array literal too long მასივის ლიტერალი ზედმეტად გრძელია +@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 assignment to a constant binding მუდმივ ბმას მნიშვნელობა ვერ მიენიჭება +@msg at least one row that isn't excluded needs a weight above 0 მინიმუმ ერთ გამოურიცხავ სტრიქონს 0-ზე მეტი წილი სჭირდება +@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} არასწორი მორგება: {e} +@msg bad model {other} (keep, new or document) არასწორი მოდელი {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] არასწორი წერტილი {v}: მოსალოდნელია [x, y] +@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 blend must be a mode name blend უნდა იყოს რეჟიმის სახელი +@msg both sides of an XPath | must select nodes XPath-ის | ოპერატორის ორივე მხარემ კვანძები უნდა აირჩიოს +@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 open “{name}”: {e} „{name}“ ვერ იხსნება: {e} +@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 canceled გაუქმდა +@msg cannot align zip entries to {align} bytes zip-ის ჩანაწერების {align} ბაიტზე სწორება შეუძლებელია +@msg cannot convert the object to a primitive value ობიექტის პრიმიტიულ მნიშვნელობად გარდაქმნა შეუძლებელია +@msg cannot convert undefined or null to an object undefined-ის ან null-ის ობიექტად გარდაქმნა შეუძლებელია +@msg cannot distort a zero-size or non-finite bounding box ნულოვანი ზომის ან არასასრული შემომსაზღვრელი ჩარჩოს დეფორმაცია შეუძლებელია +@msg cannot move an object into itself ობიექტის საკუთარ თავში გადატანა შეუძლებელია +@msg cannot open the automation {kind} root `{_1}`: {e} ავტომატიზაციის ძირეული საქაღალდის ({kind}) `{_1}` გახსნა ვერ ხერხდება: {e} +@msg cannot read profile: {0} პროფილის წაკითხვა ვერ ხერხდება: {0} +@msg case must be upper|lower|title|sentence case უნდა იყოს upper|lower|title|sentence +@msg category `{c}`: one of {_1} კატეგორია `{c}`: დასაშვებია ერთ-ერთი: {_1} +@msg center must be [x, y] center უნდა იყოს [x, y] +@msg character dimensions cannot be represented with the source text transform სიმბოლოების ზომები წყარო ტექსტის გარდაქმნით ვერ გამოისახება +@msg character dimensions cannot be represented with the target text transform სიმბოლოების ზომები სამიზნე ტექსტის გარდაქმნით ვერ გამოისახება +@msg choose at least one artboard აირჩიეთ მინიმუმ ერთი სამუშაო დაფა +@msg choose at least one status აირჩიეთ მინიმუმ ერთი სტატუსი +@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 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 color.profile: no RGB or CMYK profile is called “{profile}” color.profile: RGB ან CMYK პროფილი სახელით „{profile}“ არ არსებობს +@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 ფერი, რეჟიმი და სპოტ-ფერი მხოლოდ მყარი ფერის ნიმუშებს ეხება +@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} შესაერთებლად ზუსტად ერთ ღია ტრაექტორიას უნდა შეიცავდეს +@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 continuation must be an array of path chunks continuation უნდა იყოს ტრაექტორიის ნაწილების მასივი +@msg continuation requires points continuation-ს სჭირდება წერტილები +@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 ფაილის კოპირება ვებში მიუწვდომელია +@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 უნდა იყოს 4 [x, y] წერტილი (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}`: art, trim, bleed და media ჩარჩოები მხოლოდ 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}` ორ მნიშვნელობას +@msg data set `{name}` is declared twice მონაცემთა ნაკრები `{name}` ორჯერაა გამოცხადებული +@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 თარიღი `{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 {{id, corners?}} with an object id, not {it} `items`-ის თითოეული ჩანაწერი არის {{id, corners?}} ობიექტის id-ით და არა {it} +@msg each of `items` is {{kind, item}} `items`-ის თითოეული ჩანაწერი არის {{kind, item}} +@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 row needs `from` თითოეულ სტრიქონს სჭირდება `from` +@msg each stop needs a position თითოეულ გადასვლის წერტილს სჭირდება პოზიცია +@msg each subpath needs an anchors array თითოეულ ქვეტრაექტორიას სჭირდება anchors მასივი +@msg each weight must be a number of 0 or more (got {v}) თითოეული წილი უნდა იყოს 0 ან მეტი რიცხვი (მიღებულია {v}) +@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"-ის სიიდან +@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 file name too long to zip: {_1} ფაილის სახელი zip-ში ჩასამატებლად ზედმეტად გრძელია: {_1} +@msg file name too long to zip: {name} ფაილის სახელი zip-ში ჩასამატებლად ზედმეტად გრძელია: {name} +@msg files must be {{name, dataBase64}} files უნდა იყოს {{name, dataBase64}} +@msg finally table {t} out of range finally ცხრილი {t} დიაპაზონს გარეთაა +@msg fit must be none|autoHeight|shrinkText|block, got {id} fit უნდა იყოს none|autoHeight|shrinkText|block, მიღებულია {id} +@msg flags cannot be given with a RegExp object RegExp ობიექტთან ერთად ალმების მითითება შეუძლებელია +@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}` +@msg formats must be an array of rows, not {v} formats უნდა იყოს სტრიქონების მასივი და არა {v} +@msg freeform line {i}: {e} freeform-ის ხაზი {i}: {e} +@msg freeform point {i}: {e} freeform-ის წერტილი {i}: {e} +@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 function declaration index out of range ფუნქციის გამოცხადების ინდექსი დიაპაზონს გარეთაა +@msg give `before` or `after`, not both მიუთითეთ `before` ან `after`, ორივე არა +@msg give `char`, `text`, `code` or `unicode` მიუთითეთ `char`, `text`, `code` ან `unicode` +@msg give `colors`, or `color` and `rule` მიუთითეთ `colors`, ან `color` და `rule` +@msg give `count` or `spacing`, not both მიუთითეთ `count` ან `spacing`, ორივე არა +@msg give `event`, such as onclick მიუთითეთ `event`, მაგალითად onclick +@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 `name`, an SVG filter's name მიუთითეთ `name`, SVG ფილტრის სახელი +@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 `path`, an SVG file, or `svg`, SVG text მიუთითეთ `path`, SVG ფაილი, ან `svg`, SVG ტექსტი +@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` (და `tolerance`, 0 ან მეტი) +@msg give `xml`, one SVG element მიუთითეთ `xml`, ერთი SVG ელემენტი +@msg give `{key}` or `{other}`, not both მიუთითეთ `{key}` ან `{other}`, ორივე არა +@msg give a mode or r/g/b, c/m/y/k, gray or tint adjustments მიუთითეთ რეჟიმი ან 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 +@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 exactly one of `at`, `rect` and `points` მიუთითეთ ზუსტად ერთი: `at`, `rect` ან `points` +@msg give exactly one of `path`, `data` and `dataBase64` მიუთითეთ ზუსტად ერთი: `path`, `data` ან `dataBase64` +@msg give formats or a preset, not both მიუთითეთ formats ან პრესეტი, ორივე არა +@msg give index or indexes, not both მიუთითეთ index ან indexes, ორივე არა +@msg give newName or delete მიუთითეთ newName ან delete +@msg give offset or by მიუთითეთ offset ან by +@msg give one element მიუთითეთ ერთი ელემენტი +@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 ან სვეტში მდებარეობა +@msg give opacity or blend მიუთითეთ opacity ან blend +@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": [{{"format": "png", "scale": "2x"}}]}} მიუთითეთ შესაცვლელი პარამეტრები, მაგ. {{"formats": [{{"format": "png", "scale": "2x"}}]}} +@msg give the style a name სტილს სახელი მიეცით +@msg give two or more style `names` მიუთითეთ ორი ან მეტი სტილის `names` +@msg give two or more swatches მიუთითეთ ორი ან მეტი ფერის ნიმუში +@msg give x, y, or a handle's length or angle მიუთითეთ x, y, ან სახელურის სიგრძე ან კუთხე +@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) გლიფი {_1} სიმბოლოს {ch} სტილით არ იხატება (მაგალითად, მთავრული, პატარა მთავრული ან ციფრების სისტემა) +@msg glyph {g} is not an alternate of {ch} in {_1} {_2} გლიფი {g} არ არის სიმბოლოს {ch} ალტერნატივა შრიფტში {_1} {_2} +@msg gradient must be "objects" or "mesh" gradient უნდა იყოს "objects" ან "mesh" +@msg grays must be "profile" or "black", not `{g}` grays უნდა იყოს "profile" ან "black" და არა `{g}` +@msg grayscale profiles can't be working spaces yet ნაცრისფერი გრადაციების პროფილები სამუშაო ფერთა სივრცედ ჯერ ვერ გამოიყენება +@msg gridColors must be a preset name or two colours gridColors უნდა იყოს პრესეტის სახელი ან ორი ფერი +@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 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 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 გამოკვეთეთ ორი ან მეტი სტრიქონი ერთ შრეში ან ჯგუფში +@msg highlight two or more rows to merge შესარწყმელად გამოკვეთეთ ორი ან მეტი სტრიქონი +@msg hvcC hvcC +@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 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 გამოსახულებები, რომლებიც ერთ ფაილში დასაშვებ პიქსელების მაქსიმუმს აჭარბებს, გამოტოვებულია +@msg images too large to read were left out წასაკითხად ზედმეტად დიდი გამოსახულებები გამოტოვებულია +@msg index out of range ინდექსი დიაპაზონს გარეთაა +@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 input contains NaN or infinite coordinates შეყვანილი მონაცემები შეიცავს NaN ან უსასრულო კოორდინატებს +@msg input path could not be closed შემავალი ტრაექტორიის შეკვრა ვერ მოხერხდა +@msg instances must be 1..1000 instances უნდა იყოს 1..1000 +@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 ICC profile: {0} არასწორი ICC პროფილი: {0} +@msg invalid `color` არასწორი `color` +@msg invalid anchor index {v}: expected a non-negative integer საყრდენი წერტილის არასწორი ინდექსი {v}: მოსალოდნელია არაუარყოფითი მთელი რიცხვი +@msg invalid anchor reference {v}: expected [subpath, anchor] საყრდენი წერტილის არასწორი მიმართვა {v}: მოსალოდნელია [subpath, anchor] +@msg invalid angle არასწორი კუთხე +@msg invalid array length მასივის არასწორი სიგრძე +@msg invalid brush: {e} არასწორი ფუნჯი: {e} +@msg invalid color არასწორი ფერი +@msg invalid colour {c} არასწორი ფერი {c} +@msg invalid delta არასწორი ნაზრდი +@msg invalid group არასწორი ჯგუფი +@msg invalid object id {v}: expected a non-negative integer ობიექტის არასწორი id {v}: მოსალოდნელია არაუარყოფითი მთელი რიცხვი +@msg invalid point არასწორი წერტილი +@msg invalid regular expression flag '{_1}' რეგულარული გამოსახულების არასწორი ალამი '{_1}' +@msg invalid regular expression: {m} არასწორი რეგულარული გამოსახულება: {m} +@msg invalid scale {scale} არასწორი მასშტაბი {scale} +@msg invalid size არასწორი ზომა +@msg invalid t არასწორი t +@msg invalid time value დროის არასწორი მნიშვნელობა +@msg invalid tolerance არასწორი დაშვება +@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 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 image is too large to read მისი გამოსახულება წასაკითხად ზედმეტად დიდია +@msg its localized names take more than {_1} KB მისი ლოკალიზებული სახელები {_1} KB-ზე მეტს იკავებს +@msg its metadata has no description მის მეტამონაცემებში აღწერა არ არის +@msg its metadata has no direct length მის მეტამონაცემებში პირდაპირი სიგრძე არ არის +@msg its objects are nested too deep ({e}) მისი ობიექტები ზედმეტად ღრმადაა ჩადგმული ({e}) +@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 მისი ფირფიტები ზედმეტად დიდია: {_1} ფირფიტა, თითო {w} × {h} პიქსელი +@msg its plates can't be kept together მისი ფირფიტების ერთად შენარჩუნება შეუძლებელია +@msg its shapes could not be combined into one მისი ფიგურების ერთში გაერთიანება ვერ მოხერხდა +@msg its tag table lists the `{_1}` tag more than once მის ტეგების ცხრილში ტეგი `{_1}` ერთზე მეტჯერაა ჩამოთვლილი +@msg join two different paths შეაერთეთ ორი სხვადასხვა ტრაექტორია +@msg jump to {pc}, past the end გადასვლა ბოლოს მიღმა: {pc} +@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 უნდა იყოს არაუარყოფითი სიგანეები +@msg legacyNameEncoding must be one of {_1} legacyNameEncoding უნდა იყოს ერთ-ერთი: {_1} +@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 localize: the first argument must be a localization object or a string localize: პირველი არგუმენტი უნდა იყოს ლოკალიზაციის ობიექტი ან სტრიქონი +@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`: მიუთითეთ ან მონიშნეთ ერთი ტექსტური ობიექტი +@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: new}}) აკლია `map` (სტრიქონები [{{from, to}}] ან {{current: new}}) +@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 `picks` აკლია `picks` +@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`: არაუარყოფითი მთელი რიცხვი +@msg missing `type` აკლია `type` +@msg missing `value` აკლია `value` +@msg missing `word` აკლია `word` +@msg missing `{key}` აკლია `{key}` +@msg missing `{k}` აკლია `{k}` +@msg missing anchor აკლია საყრდენი წერტილი +@msg missing anchors აკლია საყრდენი წერტილები +@msg missing anchors [[subpath, anchor]…] აკლია საყრდენი წერტილები [[subpath, anchor]…] +@msg missing array `{key}` აკლია მასივი `{key}` +@msg missing case აკლია case +@msg missing color აკლია ფერი +@msg missing commands აკლია ბრძანებები +@msg missing destination folder აკლია დანიშნულების საქაღალდე +@msg missing from აკლია from +@msg missing group აკლია ჯგუფი +@msg missing id or ids აკლია id ან ids +@msg missing ids აკლია ids +@msg missing indexes აკლია ინდექსები +@msg missing matrix [a,b,c,d,e,f] აკლია მატრიცა [a,b,c,d,e,f] +@msg missing name აკლია სახელი +@msg missing op აკლია op +@msg missing or invalid `color` აკლია ან არასწორია `color` +@msg missing or unknown `tool` აკლია ან უცნობია `tool` +@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 segment აკლია სეგმენტი +@msg missing stops აკლია გადასვლის წერტილები +@msg missing subpaths აკლია ქვეტრაექტორიები +@msg missing 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 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 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 საჭიროა ერთი საყრდენი წერტილი მაინც +@msg need at least one point საჭიროა ერთი წერტილი მაინც +@msg need at least two points საჭიროა ორი წერტილი მაინც +@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 needs points საჭიროა წერტილები +@msg nesting too deep ჩადგმა ზედმეტად ღრმაა +@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 HP-GL format HP-GL ფორმატი არ არის +@msg no New Document profile called `{shown}` ({_1}) ახალი დოკუმენტის პროფილი სახელით `{shown}` არ არის ({_1}) +@msg no PDF preset named `{n}` PDF პრესეტი სახელით `{n}` არ არის +@msg no SVG filter at index {k} SVG ფილტრი ინდექსით {k} არ არის +@msg no action set is current მიმდინარე მოქმედებების ნაკრები არ არის +@msg no active data set აქტიური მონაცემთა ნაკრები არ არის +@msg no appearance item {index} იერსახის ელემენტი {index} არ არის +@msg no arrowheads file here აქ ისრის წვერების ფაილი არ არის +@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 character has code {code} სიმბოლო კოდით {code} არ არის +@msg no colour ფერი არ არის +@msg no colour group `{group}` ფერების ჯგუფი `{group}` არ არის +@msg no colour group `{name}` ფერების ჯგუფი `{name}` არ არის +@msg no custom arrowhead {name} (see stroke.arrowheads.list) მომხმარებლის ისრის წვერი {name} არ არის (იხ. stroke.arrowheads.list) +@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 file to open გასახსნელი ფაილი არ არის +@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}` გრაფიკული სტილი `{n}` არ არის ბიბლიოთეკაში `{_1}` +@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 instructions ინსტრუქციები არ არის +@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 to rename სახელის შესაცვლელი შრე არ არის +@msg no layer {id} (see layer.list) შრე {id} არ არის (იხ. layer.list) +@msg no layers to export საექსპორტო შრეები არ არის +@msg no library `{key}` ბიბლიოთეკა `{key}` არ არის +@msg no metafile format metafile ფორმატი არ არის +@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 random numbers ({e}) შემთხვევითი რიცხვები მიუწვდომელია ({e}) +@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}` შენახული PDF პრესეტი სახელით `{name}` არ არის +@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 selected or given object has a visible 3D effect არცერთ მონიშნულ ან მითითებულ ობიექტს ხილული 3D ეფექტი არ აქვს +@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 artboard {v} ასეთი სამუშაო დაფა არ არის: {v} +@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}` ფერის ნიმუში ან ფერების ჯგუფი `{n}` არ არის ბიბლიოთეკაში `{_1}` +@msg no symbol named `{_1}` სიმბოლო სახელით `{_1}` არ არის +@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} already has the text variable `{_2}` კვანძს {_1} უკვე აქვს ტექსტური ცვლადი `{_2}` +@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 DCS file ეს არ არის DCS ფაილი +@msg not a PDF presets file (format `{_1}`) ეს არ არის PDF პრესეტების ფაილი (ფორმატი `{_1}`) +@msg not a PDF presets file: {e} ეს არ არის PDF პრესეტების ფაილი: {e} +@msg not a RegExp object ეს არ არის RegExp ობიექტი +@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 graphic style library: {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 regular expression ეს არ არის რეგულარული გამოსახულება +@msg not a stored or deflated central record ეს არ არის შეუკუმშავი (stored) ან deflate-ით შეკუმშული ცენტრალური ჩანაწერი +@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 a valid SVGZ file: {e} ეს არ არის სწორი SVGZ ფაილი: {e} +@msg not an action set file ({e}) ეს არ არის მოქმედებების ნაკრების ფაილი ({e}) +@msg not an action set: the text doesn't start with /version and a number ეს არ არის მოქმედებების ნაკრები: ტექსტი არ იწყება /version-ით და რიცხვით +@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 nothing to repeat გასამეორებელი არაფერია +@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 ობიექტს {_1} სჭირდება 3D ეფექტი +@msg object {_1} needs a 3D effect at index {index} ობიექტს {_1} სჭირდება 3D ეფექტი ინდექსზე {index} +@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 სიღრმისას ობიექტს ერთი მხარე აქვს: მისი გრაფიკა წინა მხარეზე განათავსეთ +@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}: ეფექტს „{name}“ ინდექსზე {index} განათების პრესეტები არ აქვს; მისი სინათლის წყაროები დააყენეთ effect.setParams-ით +@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 opacity must be a number opacity უნდა იყოს რიცხვი +@msg open a document to look for its linked files გახსენით დოკუმენტი მისი დაკავშირებული ფაილების მოსაძებნად +@msg operand too large ოპერანდი ზედმეტად დიდია +@msg options must be an object (see file.formatOptions) options უნდა იყოს ობიექტი (იხ. file.formatOptions) +@msg order is a whole number from 0 to {others}, not `{v}` order არის მთელი რიცხვი 0-დან {others}-მდე და არა `{v}` +@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: RGB ან CMYK პროფილი სახელით „{name}“ არ არის +@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 გადაფარული ფორმირების ტრაექტორიები ერთ შრეში ან ჯგუფში უნდა იყოს +@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 chunks must share their boundary point ტრაექტორიის ნაწილებს საერთო სასაზღვრო წერტილი უნდა ჰქონდეს +@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 pdfCompatible: false needs the artboards to keep the editable artwork when useArtboards is false pdfCompatible: false-ს სჭირდება, რომ სამუშაო დაფებმა რედაქტირებადი ნახატი შეინარჩუნონ, როცა useArtboards არის 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 point x must be a number წერტილის x უნდა იყოს რიცხვი +@msg point y must be a number წერტილის y უნდა იყოს რიცხვი +@msg points must be [t, left, right] with non-negative widths points უნდა იყოს [t, left, right] არაუარყოფითი სიგანეებით +@msg points must be [x,y] pairs points უნდა იყოს [x,y] წყვილები +@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 be finite canvas points points უნდა იყოს ტილოს სასრული წერტილები +@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 პოზიციები უნდა იყოს 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 პრესეტი `{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 profile colour space {other} is not RGB, CMYK or Gray პროფილის ფერთა სივრცე {other} არ არის RGB, CMYK ან Gray +@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 range out of order in character class სიმბოლოთა კლასში დიაპაზონი არასწორი რიგითაა +@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 reduce of an empty array with no initial value reduce ცარიელ მასივზე საწყისი მნიშვნელობის გარეშე შეუძლებელია +@msg registration must be 0..8 registration უნდა იყოს 0..8 +@msg regular expression flag '{_1}' given twice რეგულარული გამოსახულების ალამი '{_1}' ორჯერაა მითითებული +@msg regular expression too large რეგულარული გამოსახულება ზედმეტად დიდია +@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: მონიშნეთ ერთი ჩასანაცვლებელი ობიექტი +@msg resolution must be a number or screen|medium|high resolution უნდა იყოს რიცხვი ან screen|medium|high +@msg resolution must be between 1 and 2400 ppi გარჩევადობა უნდა იყოს 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 სტრიქონები და სვეტები უნდა იყოს 1..500 +@msg rows of objects whose appearances differ can't be reordered together სხვადასხვა იერსახის მქონე ობიექტების სტრიქონების ერთად გადალაგება შეუძლებელია +@msg sampled text would exceed the canvas (coordinates out of range) აღებული ტექსტი ტილოს გასცდებოდა (კოორდინატები დიაპაზონს გარეთაა) +@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 ნულისგან განსხვავებული უნდა იყოს +@msg scope must be selection or all (got {other}) scope უნდა იყოს selection ან all (მიღებულია {other}) +@msg scribble is too long ჯღაბნა ზედმეტად გრძელია +@msg script file is not UTF-8 text: {value} სკრიპტის ფაილი UTF-8 ტექსტი არ არის: {value} +@msg segment does not exist სეგმენტი არ არსებობს +@msg select a Shaper group მონიშნეთ ფორმირების ჯგუფი +@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 SVG filter მონიშნეთ SVG ფილტრი +@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 3D effect მონიშნეთ 3D ეფექტის მქონე ობიექტი +@msg select an object with a 3D effect, or give its id in ids მონიშნეთ 3D ეფექტის მქონე ობიექტი ან მიუთითეთ მისი id ids-ში +@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) მონიშნეთ არის ტექსტი და შეკრული ტრაექტორიები (არის ტექსტის ერთი ობიექტი მაინც) +@msg select area type whose first line can fit its frame მონიშნეთ არის ტექსტი, რომლის პირველი სტრიქონიც მის ჩარჩოში ეტევა +@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 შესაერთებლად მონიშნეთ ტრაექტორიის ზუსტად ორი ბოლო +@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 მონიშნეთ ერთი გადახლართვის ჯგუფი +@msg select one image or pass id მონიშნეთ ერთი გამოსახულება ან მიუთითეთ id +@msg select one layer, group or object to rename სახელის შესაცვლელად მონიშნეთ ერთი შრე, ჯგუფი ან ობიექტი +@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 art to weed მონიშნეთ ნახატი ნარჩენის მოსაცილებლად +@msg select the banner, or mark every artboard მონიშნეთ ბანერი ან ნიშნები დაუსვით ყველა სამუშაო დაფას +@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 გადასახლართად მონიშნეთ ორი ან მეტი ობიექტი +@msg select two or more slices to combine გასაერთიანებლად მონიშნეთ ორი ან მეტი ნაჭერი +@msg select type on a path მონიშნეთ ტრაექტორიაზე ტექსტი +@msg select type on a path or area type მონიშნეთ ტრაექტორიაზე ტექსტი ან არის ტექსტი +@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 side is left or right, not `{v}` side არის left ან right და არა `{v}` +@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 ზომა დადებითი უნდა იყოს +@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 საწყისი ტრაექტორიები ფორმირებისთვის ზედმეტად დიდია +@msg source text transform is collapsed or unrepresentable საწყისი ტექსტის გარდაქმნა გადაგვარებულია ან ვერ გამოისახება +@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-მდე (C, M, Y, K) +@msg stop {i}: {e} გადასვლის წერტილი {i}: {e} +@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 swatch exchange version {major}.{minor} isn't supported (only 1.x) ფერის ნიმუშების გაცვლის ვერსია {major}.{minor} მხარდაჭერილი არ არის (მხოლოდ 1.x) +@msg swatchConflict must be "merge" or "add", not {v} swatchConflict უნდა იყოს "merge" ან "add" და არა {v} +@msg table must be true or false table უნდა იყოს true ან false +@msg takes one name იღებს ერთ სახელს +@msg target text transform is collapsed or unrepresentable სამიზნე ტექსტის გარდაქმნა გადაგვარებულია ან ვერ გამოისახება +@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 makes too many pieces (at most 100000) or dash steps: simplify the dash pattern or make the dashes longer ეს ზედმეტად ბევრ ნაწილს (მაქსიმუმ 100000) ან ტირეების ნაბიჯს ქმნის: გაამარტივეთ ტირეების ნიმუში ან გაზარდეთ ტირეების სიგრძე +@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 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 PDF security settings were saved without their passwords: give openPassword or permissionsPassword again, or security without passwordRequired to export unprotected PDF-ის უსაფრთხოების პარამეტრები პაროლების გარეშეა შენახული: კვლავ მიუთითეთ openPassword ან permissionsPassword, ან დაუცველი ექსპორტისთვის მიუთითეთ security passwordRequired-ის გარეშე +@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 იშლება {0}-ზე მეტ ჩადგმულ SVG გამოსახულებად +@msg the SVG expands to more than {0} objects 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} 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 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 action set ids are not a list მოქმედებების ნაკრების იდენტიფიკატორები სია არ არის +@msg the active paint is not a gradient აქტიური საღებავი გრადიენტი არ არის +@msg the argument list is not an object არგუმენტების სია ობიექტი არ არის +@msg the artboards don't fit on the canvas: fewer artboards, less spacing or a smaller size სამუშაო დაფები ტილოზე არ ეტევა: შეამცირეთ სამუშაო დაფების რაოდენობა, დაშორება ან ზომა +@msg the artwork is too large for EPS: what follows 256 MB of PostScript was left out ნახატი EPS-ისთვის ზედმეტად დიდია: PostScript-ის 256 MB-ის შემდეგ დანარჩენი გამოტოვებულია +@msg the banner has no width or height ბანერს სიგანე ან სიმაღლე არ აქვს +@msg the bitmaps hold more pixels than one file may ბიტმაპები იმაზე მეტ პიქსელს შეიცავს, ვიდრე ერთ ფაილში ეტევა +@msg the character's size can't be measured სიმბოლოს ზომის გაზომვა შეუძლებელია +@msg the code runs past its last instruction კოდი თავისი ბოლო ინსტრუქციის მიღმა გრძელდება +@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 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 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 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 document already has an SVG filter named {name} დოკუმენტს უკვე აქვს SVG ფილტრი სახელით {name} +@msg the document has another SVG filter named {name}: use svgFilter.apply, or svgFilter.define with `replace` to edit it დოკუმენტს აქვს სხვა SVG ფილტრი სახელით {name}: გამოიყენეთ svgFilter.apply, ან მის შესაცვლელად svgFilter.define `replace`-ით +@msg the document has no SVG filter named {name} დოკუმენტს არ აქვს SVG ფილტრი სახელით {name} +@msg the document has no SVG filter named {r} დოკუმენტს არ აქვს SVG ფილტრი სახელით {r} +@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 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 isn't valid SVG: {e} ფაილი სწორი SVG არ არის: {e} +@msg the file names no plate ფაილი არცერთ ფირფიტას არ ასახელებს +@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 function's prototype is not an object ფუნქციის პროტოტიპი ობიექტი არ არის +@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 grommet inset is too large for the banner ლუვერების დაშორება კიდიდან ბანერისთვის ზედმეტად დიდია +@msg the guide is hidden or locked დამხმარე ხაზი დამალული ან ჩაკეტილია +@msg the header `{cell}` for `{name}` would read back as the variable `{other}`: rename one of them სათაური `{cell}` (ცვლადისთვის `{name}`) წაკითხვისას ცვლადად `{other}` აღიქმება: ერთ-ერთს სახელი გადაარქვით +@msg the hem is too deep for the banner ნაკეცი ბანერისთვის ზედმეტად ღრმაა +@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 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 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 line is too long, or the paths it passes too many, to check ხაზი ზედმეტად გრძელია, ან მის მიერ გადაკვეთილი ტრაექტორიები ზედმეტად ბევრია შესამოწმებლად +@msg the method needs an XML value მეთოდს XML მნიშვნელობა სჭირდება +@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 optimised image can't be read back: {e} ოპტიმიზებული გამოსახულების ხელახლა წაკითხვა შეუძლებელია: {e} +@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 parameters or body do not form one function პარამეტრები ან სხეული ერთ ფუნქციას არ ქმნის +@msg the parent must be a layer or sublayer მშობელი უნდა იყოს შრე ან ქვეშრე +@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 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 paths are too many or too tangled to find where they cross ტრაექტორიები ზედმეტად ბევრი ან ზედმეტად ჩახლართულია გადაკვეთის წერტილების საპოვნელად +@msg the pen table holds more than 255 pens კალმების ცხრილი 255-ზე მეტ კალამს შეიცავს +@msg the picture has no objects სურათს ობიექტები არ აქვს +@msg the pixel buffer doesn't match the image size პიქსელების ბუფერი გამოსახულების ზომას არ შეესაბამება +@msg the plates can't be kept ფირფიტების შენარჩუნება შეუძლებელია +@msg the position table does not match the instructions პოზიციების ცხრილი ინსტრუქციებს არ შეესაბამება +@msg the preview: {e} წინასწარი ხედი: {e} +@msg the program runs too long პროგრამა ზედმეტად დიდხანს მუშაობს +@msg the program uses too much memory პროგრამა ზედმეტად ბევრ მეხსიერებას იყენებს +@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 must have a width and a height მართკუთხედს უნდა ჰქონდეს სიგანე და სიმაღლე +@msg the rectangle needs a size and must lie on the canvas მართკუთხედს ზომა სჭირდება და ტილოზე უნდა მდებარეობდეს +@msg the rectangle or line reaches too many paths to check მართკუთხედი ან ხაზი ზედმეტად ბევრ ტრაექტორიას სწვდება შესამოწმებლად +@msg the request may not read the New Document profiles folder მოთხოვნას არ შეუძლია ახალი დოკუმენტის პროფილების საქაღალდის წაკითხვა +@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 has no width მონიშნულ ნახატს სიგანე არ აქვს +@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 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 selection has no outlines to weed around მონიშნულში არ არის კონტურები, რომელთა გარშემოც ნარჩენის მოცილება შეიძლება +@msg the shapes are too degenerate to combine ფიგურები ზედმეტად გადაგვარებულია გასაერთიანებლად +@msg the shapes cross themselves and each other too often to combine ფიგურები საკუთარ თავს და ერთმანეთს ზედმეტად ხშირად კვეთს გასაერთიანებლად +@msg the slice would leave the canvas ნაჭერი ტილოს გარეთ გავიდოდა +@msg the spacing makes more than {MAX_GROMMETS} grommets ასეთი დაშორებით {MAX_GROMMETS}-ზე მეტი ლუვერი გამოდის +@msg the spot colour couldn't be added სპოტ-ფერის დამატება ვერ მოხერხდა +@msg the subpath has no ends to extend (it is closed or a single point) ქვეტრაექტორიას გასაგრძელებელი ბოლოები არ აქვს (ის შეკრულია ან ერთი წერტილია) +@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 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 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 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 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 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 the {_1} plate can't be read: {e} ფირფიტის {_1} წაკითხვა შეუძლებელია: {e} +@msg the {_1} plate lies outside the file ფირფიტა {_1} ფაილის გარეთ მდებარეობს +@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 banner to mark ნიშნების დასასმელი ბანერი არ არის +@msg there is no library: create one first ბიბლიოთეკა არ არის: ჯერ შექმენით ის +@msg these paths are too degenerate for Shaper ეს ტრაექტორიები ფორმირებისთვის ზედმეტად გადაგვარებულია +@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 this warp's points can't be edited: use Reset with Mesh first ამ გაღუნვის წერტილების რედაქტირება შეუძლებელია: ჯერ გამოიყენეთ „ბადით ჩამოყრა“ +@msg thumbnail: no page {v} (the {what} has {count}) ესკიზი: გვერდი {v} არ არის ({what}: {count} გვერდი) +@msg tileRange of {what}: {e} tileRange ({what}): {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 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: getter-ის წყაროდ ჩაწერა შეუძლებელია +@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 large for a zip archive: package to a folder zip არქივისთვის ზედმეტად დიდია: შეფუთეთ საქაღალდეში +@msg too many Shaper edits ზედმეტად ბევრი ფორმირების ჩასწორება +@msg too many `points` (at most 100000) ზედმეტად ბევრი `points` (მაქსიმუმ 100000) +@msg too many arguments ზედმეტად ბევრი არგუმენტი +@msg too many characters: at most {MAX_CHARS} ზედმეტად ბევრი სიმბოლო: მაქსიმუმ {MAX_CHARS} +@msg too many classes ზედმეტად ბევრი კლასი +@msg too many dots for this size: lower the frequency ამ ზომისთვის ზედმეტად ბევრი წერტილია: შეამცირეთ სიხშირე +@msg too many filters over one file ერთ ფაილზე ზედმეტად ბევრი ფილტრია +@msg too many groups ზედმეტად ბევრი ჯგუფი +@msg too many layers for PSD (at most 32767) PSD-ისთვის ზედმეტად ბევრი შრეა (მაქსიმუმ 32767) +@msg too many overlapping paths for Shaper ფორმირებისთვის ზედმეტად ბევრი გადაფარვადი ტრაექტორიაა +@msg too many quantifiers ზედმეტად ბევრი კვანტიფიკატორი +@msg too many saved clips ზედმეტად ბევრი შენახული მომჭრელი ტრაექტორია +@msg too many saved graphics states ზედმეტად ბევრი შენახული გრაფიკული მდგომარეობა +@msg too many swatch exchange blocks ფერის ნიმუშების გაცვლის ზედმეტად ბევრი ბლოკი +@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 turn on at least one side ჩართეთ მინიმუმ ერთი მხარე +@msg two saved selections would be named `{_1}` ორ შენახულ მონიშნულს ერთი და იგივე სახელი ექნებოდა: `{_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}` უცნობი CMYK პროფილი `{name}` +@msg unknown File Info field `{k}` ფაილის ინფორმაციის უცნობი ველი `{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, hkna, ital; 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`) უცნობი OpenType შესაძლებლობა `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt, hkna, ital; გამოსართავად წინ დაურთეთ -; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom და aalt იღებს ალტერნატივის ნომერს ფორმით `tag=N`, სადაც N არის 0-დან {_1}-მდე, მაგალითად `salt=2`) +@msg unknown OpenType feature `{t}` in featureChanges (the tags `features` takes) უცნობი OpenType შესაძლებლობა `{t}` featureChanges-ში (ის ტეგები, რომლებსაც `features` იღებს) +@msg unknown PDF preset `{name}` (presets: {_1}) უცნობი PDF პრესეტი `{name}` (პრესეტები: {_1}) +@msg unknown Warp style გაღუნვის უცნობი სტილი +@msg unknown alignToPath `{a}` უცნობი alignToPath `{a}` +@msg unknown arrowhead {v} უცნობი ისრის წვერი {v} +@msg unknown artboardLayout key `{k}` (layout, columns, spacing, rightToLeft) artboardLayout-ის უცნობი გასაღები `{k}` (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 colour profile: {0} უცნობი ფერის პროფილი: {0} +@msg unknown dither `{d}` (diffusion, pattern, noise or none) უცნობი დიზერინგი `{d}` (diffusion, pattern, noise ან none) +@msg unknown effect `{e}` უცნობი ეფექტი `{e}` +@msg unknown end {e} უცნობი ბოლო {e} +@msg unknown flattenerPreset `{name}` (High Resolution, Medium Resolution, Low Resolution or a saved one: see flattener.presets.list) უცნობი flattenerPreset `{name}` (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} უცნობი from {f} +@msg unknown graph type `{t}` დიაგრამის უცნობი ტიპი `{t}` +@msg unknown grid colours `{name}` (one of {_1}) ბადის უცნობი ფერები `{name}` (ერთ-ერთი: {_1}) +@msg unknown gridType `{t}` უცნობი gridType `{t}` +@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}` +@msg unknown model `{other}` (keep, new or document) უცნობი მოდელი `{other}` (keep, new ან document) +@msg unknown op {o} უცნობი ოპერაცია {o} +@msg unknown order `{o}`: toggle, front, forward, backward or back უცნობი რიგი `{o}`: toggle, front, forward, backward ან back +@msg unknown overprints `{v}` (preserve, simulate or discard) უცნობი ზედდაბეჭდვა `{v}` (preserve, simulate ან discard) +@msg unknown panel უცნობი პანელი +@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 pieLegend `{v}` (none, standard or wedges) უცნობი pieLegend `{v}` (none, standard ან wedges) +@msg unknown piePosition `{v}` (even, ratio or stacked) უცნობი piePosition `{v}` (even, ratio ან stacked) +@msg unknown pieSort `{v}` (none, all or first) უცნობი pieSort `{v}` (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}` (double, single) +@msg unknown reduction `{reduction}` (selective, perceptual, adaptive, web, gray, blackWhite, uniform or document) უცნობი შემცირება `{reduction}` (selective, perceptual, adaptive, web, gray, blackWhite, uniform ან document) +@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}) უცნობი tileType `{t}` ({_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) უცნობი {key} `{v}` (none, short ან full) +@msg unknown {key} profile `{n}` უცნობი {key} პროფილი `{n}` +@msg unknown {k} key `{key}` (size, position) {k}: უცნობი გასაღები `{key}` (size, position) +@msg unmatched ')' დაუწყვილებელი ')' +@msg unreadable object წაუკითხავი ობიექტი +@msg unsafe destination file name დანიშნულების ფაილის სახელი სახიფათოა +@msg unterminated character class დაუსრულებელი სიმბოლოთა კლასი +@msg unterminated group დაუსრულებელი ჯგუფი +@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}` ორჯერაა გამოცხადებული +@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 width დიაპაზონს გარეთაა +@msg width/height must be > 0 width/height უნდა იყოს > 0 +@msg with no hem and no grommets there is nothing to mark ნაკეცისა და ლუვერების გარეშე ნიშნების დასასმელი არაფერია +@msg wordGap and lineGap need area type in the selection wordGap და lineGap პარამეტრებს მონიშნულში არის ტექსტი სჭირდება +@msg x and y must be finite numbers x და y სასრული რიცხვები უნდა იყოს +@msg x and y must be given together x და y ერთად უნდა იყოს მოცემული +@msg xpath needs its variables as an object xpath-ს ცვლადები ობიექტად სჭირდება +@msg xpath needs the expression as a string xpath-ს გამოსახულება სტრიქონად სჭირდება +@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 {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 {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 RGBA მონაცემები: {_1} ბაიტი {width} × {height} გამოსახულებისთვის +@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} clashes with a built-in profile name {_1} ჩაშენებული პროფილის სახელს ემთხვევა +@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} is not a folder: {e} {_1} საქაღალდე არ არის: {e} +@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} პაროლები შეიძლება შეიცავდეს მაქსიმუმ {MAX_LEGACY_PASSWORD} ASCII სიმბოლოს (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} აქ თითო სამუშაო დაფაზე ერთ ფაილს წერს: გამოიყენეთ document.export, ან დაასახელეთ ერთი სამუშაო დაფა +@msg {_1} × {_2} pixels is too large for GIF (at most 65535 pixels a side): lower the resolution {_1} × {_2} პიქსელი GIF-ისთვის ზედმეტად დიდია (მაქსიმუმ 65535 პიქსელი თითო მხარეზე): შეამცირეთ გარჩევადობა +@msg {_1} × {_2} pixels is too large for {_3} (at most {max} pixels a side): lower the scale {_1} × {_2} პიქსელი ზედმეტად დიდია ფორმატისთვის {_3} (მაქსიმუმ {max} პიქსელი თითო მხარეზე): შეამცირეთ მასშტაბი +@msg {_1}: belongs to another account {_1}: სხვა ანგარიშს ეკუთვნის +@msg {_1}: no usable transform to/from sRGB {_1}: sRGB-ში ან sRGB-დან გამოსაყენებელი გარდაქმნა არ არის +@msg {_1}: not a folder of its own {_1}: თავად საქაღალდე არ არის +@msg {_1}: not a plain file {_1}: ჩვეულებრივი ფაილი არ არის +@msg {_1}: {_2} and {_3} are in the way {_1}: ხელს უშლის {_2} და {_3} +@msg {code}: {0} {code}: {0} +@msg {dest}: {e} {dest}: {e} +@msg {dir}: {e} {dir}: {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}: 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}: can't read `{s}` as a length {k}: `{s}` სიგრძედ ვერ იკითხება +@msg {k}: custom must be a name {k}: custom სახელი უნდა იყოს +@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} is not a CMYK profile {name} CMYK პროფილი არ არის +@msg {name} is not an RGB profile {name} RGB პროფილი არ არის +@msg {name} must be a number {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 {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}: could not be read {path}: წაკითხვა ვერ მოხერხდა +@msg {path}: larger than {_1} MB {path}: {_1} MB-ზე დიდია +@msg {shown} is not an XPath 1.0 function {shown} XPath 1.0 ფუნქცია არ არის +@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} რესურსის იდენტიფიკატორი არ არის +@msg {v} names no layer or sublayer {v} არცერთ შრეს ან ქვეშრეს არ ასახელებს +@msg {what} can't be intertwined {what}: გადახლართვა შეუძლებელია +@msg {what} doesn't fit the paper with its bleed and marks {what} ჭრისპირა არითა და ნიშნებთან ერთად ქაღალდზე არ ეტევა +@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} ფურცელზე {MAX_COPIES_PER_SHEET}-ზე მეტ ასლს დაბეჭდავდა: გაადიდეთ მასშტაბი +@msg {what} would print on more than {MAX_TILES} tiles: scale it down {what} {MAX_TILES}-ზე მეტ ფილაზე დაიბეჭდებოდა: შეამცირეთ მასშტაბი +@msg {what} {i} out of range {what} {i} დიაპაზონს გარეთაა +@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} პიქსელი თითო მხარეზე): შეამცირეთ გარჩევადობა +@msg <{_1}> isn't an element of an SVG filter <{_1}> SVG ფილტრის ელემენტი არ არის +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` უნდა იყოს "document", {{artboards: [index, …]}} ან {{layers: [id, …]}} +@msg `style` must be "pencil" or "brush", not {v} `style` უნდა იყოს "pencil" ან "brush" და არა {v} +@msg action step {_1} (`{id}`) failed: {reason} მოქმედების ნაბიჯი {_1} (`{id}`) ვერ შესრულდა: {reason} +@msg an SVG filter has at most {MAX_PRIMITIVES} primitives SVG ფილტრს მაქსიმუმ {MAX_PRIMITIVES} პრიმიტივი აქვს +@msg an SVG filter has no event attributes such as {_1} SVG ფილტრს მოვლენის ატრიბუტები, როგორიცაა {_1}, არ აქვს +@msg an SVG filter is at most {_1} KB SVG ფილტრის ზომა მაქსიმუმ {_1} KB-ია +@msg an SVG filter's elements nest at most {MAX_DEPTH} deep SVG ფილტრის ელემენტები მაქსიმუმ {MAX_DEPTH} დონეზეა ჩადგმული +@msg an SVG filter's id is at most {MAX_NAME} characters SVG ფილტრის id მაქსიმუმ {MAX_NAME} სიმბოლოა +@msg an SVG filter's images are PNG, JPEG, GIF or WebP data: URLs SVG ფილტრის გამოსახულებები PNG, JPEG, GIF ან WebP data: URL-ებია +@msg an SVG filter's images have at most {MAX_IMAGE_PIXELS} pixels in all SVG ფილტრის გამოსახულებებს სულ მაქსიმუმ {MAX_IMAGE_PIXELS} პიქსელი აქვს +@msg commands[{i}]: `prefs.import` runs on its own, not as a batch step commands[{i}]: `prefs.import` ცალკე სრულდება და არა პაკეტის ნაბიჯად +@msg each font must be {{name, parts}} თითოეული შრიფტი უნდა იყოს {{name, parts}} +@msg feTurbulence's numOctaves is at most {MAX_OCTAVES} feTurbulence-ის numOctaves მაქსიმუმ {MAX_OCTAVES}-ია +@msg give fonts: [{{name, parts}}…] მიუთითეთ fonts: [{{name, parts}}…] +@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 no pattern `{pat}` პატერნი `{pat}` არ არის +@msg numbers out of order in {{}} quantifier {{}} კვანტიფიკატორში რიცხვები არასწორი რიგითაა +@msg plugin.remove: {_1}: {e}: nothing was removed plugin.remove: {_1}: {e}: არაფერი წაშლილა +@msg the element needs an id, the filter's name ელემენტს id სჭირდება — ფილტრის სახელი +@msg the SVG filter can't be drawn: check its primitives and their inputs SVG ფილტრის დახატვა შეუძლებელია: შეამოწმეთ მისი პრიმიტივები და მათი შესავლები +@msg the SVG filter has no primitives SVG ფილტრს პრიმიტივები არ აქვს +@msg the SVG filter is too large once its attributes are written out ატრიბუტების ჩაწერის შემდეგ SVG ფილტრი ზედმეტად დიდია +@msg the SVG filter isn't valid XML: {e} SVG ფილტრი სწორი XML არ არის: {e} +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) საღებავი თავისუფალი ფორმის გრადიენტი არ არის (გამოიყენეთ paint.editGradient {{kind: "freeform"}}) +@msg the plug-in store can't be locked პლაგინების საცავის ჩაკეტვა ვერ ხერხდება +@msg {C}: {_1}: {e}: nothing was installed {C}: {_1}: {e}: არაფერი დაყენებულა +@msg {EXPORT_SELECTION} must be true or false, not {v} {EXPORT_SELECTION} უნდა იყოს true ან false და არა {v} +@msg {what} is at most {max} {what} მაქსიმუმ {max}-ია + Automatic Plane Positioning სიბრტყის ავტომატური პოზიციონირება + Emboss რელიეფი + Glow ნათება + Hard Shadow მკვეთრი ჩრდილი + Heavy Blur ძლიერი გაბუნდოვნება + Rough Edges უსწორმასწორო კიდეები + Soft Blur რბილი გაბუნდოვნება + Soft Shadow რბილი ჩრდილი + Thicken გასქელება + Thin გათხელება + Anchor Point of Perspective Artwork პერსპექტიული გრაფიკის საყრდენი წერტილი + Intersection of Gridlines ბადის ხაზების გადაკვეთა +@msg Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options) სიბრტყის ავტომატური პოზიციონირება გამორთულია: ჩართეთ anchorPoint ან gridlineIntersection (perspective.widget.options) +@msg `artboard` must be a whole number `artboard` უნდა იყოს მთელი რიცხვი +@msg `artboard` must be an artboard's index `artboard` უნდა იყოს სამუშაო დაფის ინდექსი +@msg `artboards` must contain whole numbers `artboards` უნდა შეიცავდეს მთელ რიცხვებს +@msg `glyphForm` must be one of {_1} `glyphForm` უნდა იყოს ერთ-ერთი: {_1} +@msg `index` must be the index of an applied SVG filter `index` უნდა იყოს გამოყენებული SVG ფილტრის ინდექსი +@msg `{key}` must be a list of artboard indices `{key}` უნდა იყოს სამუშაო დაფების ინდექსების სია +@msg `{key}` must be a non-empty list of artboard indices `{key}` უნდა იყოს სამუშაო დაფების ინდექსების არაცარიელი სია +@msg `{key}` must be from 0 to {max} pt `{key}` უნდა იყოს 0-დან {max} pt-მდე +@msg `{key}` must contain whole numbers `{key}` უნდა შეიცავდეს მთელ რიცხვებს +@msg `{k}` isn't an export setting: {_1}, openLocation `{k}` ექსპორტის პარამეტრი არ არის: {_1}, openLocation +@msg a document holds at most {_1} SVG filters, and applying a default filter adds it დოკუმენტი მაქსიმუმ {_1} SVG ფილტრს იტევს, ნაგულისხმევი ფილტრის გამოყენება კი მას დოკუმენტს უმატებს +@msg a new document has no artboard ახალ დოკუმენტს სამუშაო დაფა არ აქვს +@msg anchorPoint must be true or false anchorPoint უნდა იყოს true ან false +@msg can't open `{_1}`: not a PDF `{_1}` ვერ გაიხსნა: PDF არ არის +@msg give `at` or `clear`, not both მიუთითეთ `at` ან `clear`, ორივე არა +@msg gridlineIntersection must be true or false gridlineIntersection უნდა იყოს true ან false +@msg linkPages can't be used with textAs: outlines: linked pages show the file's own type linkPages ვერ გამოიყენება textAs: outlines-თან ერთად: დაკავშირებული გვერდები ფაილის საკუთარ ტექსტს აჩვენებს +@msg linkPages can't open a file with a password: linked pages are read again without it linkPages პაროლით დაცულ ფაილს ვერ ხსნის: დაკავშირებული გვერდები ხელახლა პაროლის გარეშე იკითხება +@msg linkPages must be true or false linkPages უნდა იყოს true ან false +@msg linkPages needs the file's path: linked pages are read from it linkPages-ს ფაილის გზა სჭირდება: დაკავშირებული გვერდები ამ ფაილიდან იკითხება +@msg linkPages: `{file}` is over {_1} MB linkPages: `{file}` {_1} MB-ზე მეტია +@msg linkPages: `{file}` isn't a PDF or a PDF-compatible .ai file linkPages: `{file}` არ არის PDF ან PDF-თან თავსებადი .ai ფაილი +@msg no selected object fits on the sheet მონიშნული ობიექტებიდან არცერთი ფურცელზე არ ეტევა +@msg select at most {MAX_SHAPES} objects to nest განსალაგებლად მონიშნეთ მაქსიმუმ {MAX_SHAPES} ობიექტი +@msg sort `{x}`: name, kind, status or size დალაგების უცნობი გასაღები `{x}`: name, kind, status ან size +@msg the margin leaves no room on the sheet ზღვარი ფურცელზე ადგილს აღარ ტოვებს +@msg the perspective grid is hidden პერსპექტივის ბადე დამალულია +@msg the selection has nothing to nest მონიშნულში განსალაგებელი არაფერია +@msg the {_1} file holds no records {_1} ფაილი ჩანაწერებს არ შეიცავს +@msg the {_1} header is damaged {_1} ფაილის სათაური დაზიანებულია +@msg there is no artboard for the sheet ფურცლისთვის სამუშაო დაფა არ არის +@msg there is no artboard {i} სამუშაო დაფა {i} არ არსებობს +@msg tolerance must be 0 or more tolerance უნდა იყოს 0 ან მეტი +@msg {name} is a default SVG filter, and the document holds no copy of it to delete {name} ნაგულისხმევი SVG ფილტრია და დოკუმენტში მისი წასაშლელი ასლი არ არის +@msg `{key}` must be a number from 0 to 1 `{key}` უნდა იყოს რიცხვი 0-დან 1-მდე +@msg data set `{name}` holds a graph value for `{var}` with {_1} მონაცემთა ნაკრები `{name}` ცვლადისთვის `{var}` შეიცავს დიაგრამის მნიშვნელობას, რომელშიც {_1} +@msg data set `{name}` holds a graph value for `{var}` without rows or series მონაცემთა ნაკრები `{name}` ცვლადისთვის `{var}` შეიცავს დიაგრამის მნიშვნელობას სტრიქონებისა და სერიების გარეშე +@msg data set `{name}` holds an image value for `{var}` that isn't a file's absolute path მონაცემთა ნაკრები `{name}` ცვლადისთვის `{var}` შეიცავს გამოსახულების მნიშვნელობას, რომელიც ფაილის აბსოლუტური გზა არ არის +@msg data set `{set}` holds a graph value for `{var}` longer than {MAX_GRAPH_CSV} bytes მონაცემთა ნაკრები `{set}` ცვლადისთვის `{var}` შეიცავს დიაგრამის მნიშვნელობას, რომელიც {MAX_GRAPH_CSV} ბაიტზე გრძელია +@msg data set `{set}` holds a graph value for `{var}` with {_1} მონაცემთა ნაკრები `{set}` ცვლადისთვის `{var}` შეიცავს დიაგრამის მნიშვნელობას, რომელშიც {_1} +@msg data set `{set}` holds a value for `{_1}` that isn't {what} მონაცემთა ნაკრები `{set}` ცვლადისთვის `{_1}` შეიცავს მნიშვნელობას, რომელიც {what} არ არის +@msg data set `{set}` holds a value for `{var}` that isn't a graph's `data` element მონაცემთა ნაკრები `{set}` ცვლადისთვის `{var}` შეიცავს მნიშვნელობას, რომელიც დიაგრამის `data` ელემენტი არ არის +@msg match applies only with scope {scopes} match მხოლოდ scope-ის მნიშვნელობით {scopes} მოქმედებს +@msg match must be a paint as the document stores it match უნდა იყოს საღებავი იმ სახით, როგორც დოკუმენტი ინახავს +@msg scope applies to a click: leave out points scope დაწკაპებას ეხება: points არ მიუთითოთ +@msg scope must be "one", "connected" or "samePaint" scope უნდა იყოს "one", "connected" ან "samePaint" +@msg variable `{_1}` starts or ends with white space or holds a control character, which a variable library can't hold ცვლადი `{_1}` იწყება ან მთავრდება ჰარით ან შეიცავს მმართველ სიმბოლოს, რასაც ცვლადების ბიბლიოთეკა ვერ შეინახავს + Set Panel View პანელის ხედის დაყენება +@msg `panel` is swatches, graphicStyles or symbols `panel` უნდა იყოს swatches, graphicStyles ან symbols +@msg `showImportOptions` must be true or false `showImportOptions` უნდა იყოს true ან false +@msg `start` is a number up to 1 (below 0: before an open path's start) `start` არის რიცხვი 1-მდე (0-ზე ნაკლები: ღია ტრაექტორიის დასაწყისამდე) +@msg the character at byte {start} is not drawn: it falls before its path's start ბაიტზე {start} მდგომი სიმბოლო არ იხატება: ის ტრაექტორიის დასაწყისამდე ხვდება +@msg unknown `by` "{name}": expected one of {_1} უცნობი `by` "{name}": მოსალოდნელია ერთ-ერთი: {_1} +@msg {mode_key} is one of {ERASER_MODES}, not `{id}` {mode_key} არის ერთ-ერთი: {ERASER_MODES}, და არა `{id}` +@msg {mode_key} is one of {ERASER_MODES}, not {other} {mode_key} არის ერთ-ერთი: {ERASER_MODES}, და არა {other} +@msg {var_key} must be 0 or more {var_key} უნდა იყოს 0 ან მეტი +@msg {var_key} must be at most {most} {var_key} უნდა იყოს მაქსიმუმ {most} +@msg a linked image file is outside the read roots დაკავშირებული გამოსახულების ფაილი წაკითხვის ძირეული საქაღალდეების გარეთაა + Neon & Glow ნეონი და ნათება + Show Hidden Panels at Edge დამალული პანელების ჩვენება კიდესთან +@msg `anchor` must be a [subpath, anchor] pair `anchor` უნდა იყოს წყვილი [subpath, anchor] +@msg `anchor` needs `id`, the path the point is on `anchor`-ს სჭირდება `id`: ტრაექტორია, რომელზეც წერტილია +@msg `side` must be left, right or null `side` უნდა იყოს left, right ან null +@msg `{_1}`: U+{_2} is a control character or past U+FFFF `{_1}`: U+{_2} მმართველი სიმბოლოა ან U+FFFF-ს სცდება +@msg `{_1}`: a character set keeps at most {CUSTOM_CHARS_MAX} characters `{_1}`: სიმბოლოთა ნაკრები მაქსიმუმ {CUSTOM_CHARS_MAX} სიმბოლოს იტევს +@msg `{code}` is not a code from U+0000 to U+FFFF `{code}` არ არის კოდი U+0000-დან U+FFFF-მდე +@msg `{font}`: `{name}`: a character set keeps at most {CUSTOM_CHARS_MAX} characters `{font}`: `{name}`: სიმბოლოთა ნაკრები მაქსიმუმ {CUSTOM_CHARS_MAX} სიმბოლოს იტევს +@msg `{font}`: `{name}`: characters must be a string `{font}`: `{name}`: characters უნდა იყოს სტრიქონი +@msg `{font}`: `{name}`: {e} `{font}`: `{name}`: {e} +@msg `{font}`: each character set must be {{name, characters, font…}} `{font}`: თითოეული სიმბოლოთა ნაკრები უნდა იყოს {{name, characters, font…}} +@msg `{font}`: each character set needs a name `{font}`: თითოეულ სიმბოლოთა ნაკრებს სახელი სჭირდება +@msg `{font}`: unknown key `{k}` in a character set `{font}`: უცნობი გასაღები `{k}` სიმბოლოთა ნაკრებში +@msg `{name}` can't name a character set `{name}` ვერ იქნება სიმბოლოთა ნაკრების სახელი +@msg `{name}`: U+{code} is a control character or past U+FFFF `{name}`: U+{code} მმართველი სიმბოლოა ან U+FFFF-ს სცდება +@msg `{name}`: U+{code} is listed twice `{name}`: U+{code} ორჯერაა ჩამოთვლილი +@msg `{name}`: a character set keeps at most {CUSTOM_CHARS_MAX} characters `{name}`: სიმბოლოთა ნაკრები მაქსიმუმ {CUSTOM_CHARS_MAX} სიმბოლოს იტევს +@msg `{name}`: a composite font keeps at most {CUSTOM_SETS_MAX} character sets `{name}`: კომპოზიტური შრიფტი მაქსიმუმ {CUSTOM_SETS_MAX} სიმბოლოთა ნაკრებს იტევს +@msg `{name}`: custom must be a list of character sets `{name}`: custom უნდა იყოს სიმბოლოთა ნაკრებების სია +@msg `{raw}` can't name a character set (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` ვერ იქნება სიმბოლოთა ნაკრების სახელი (1-დან {COMPOSITE_NAME_MAX}-მდე სიმბოლო, მმართველი სიმბოლოების გარეშე) +@msg a composite font keeps at most {CUSTOM_SETS_MAX} character sets კომპოზიტური შრიფტი მაქსიმუმ {CUSTOM_SETS_MAX} სიმბოლოთა ნაკრებს იტევს +@msg anchor [{_1}, {_2}] of object {id} is not a selected anchor point ობიექტის {id} საყრდენი წერტილი [{_1}, {_2}] მონიშნული არ არის +@msg give `anchor` or `guide`, not both მიუთითეთ `anchor` ან `guide`, ორივე არა +@msg missing `newName` or `kind` აკლია `newName` ან `kind` +@msg no character set სიმბოლოთა ნაკრები არ არის +@msg no panels are docked on the {_1} side {_1} მხარეს პანელები მიმაგრებული არ არის +@msg select another anchor point to align to the key anchor საკვანძო საყრდენ წერტილზე გასასწორებლად მონიშნეთ კიდევ ერთი საყრდენი წერტილი +@msg the RGB policy can't be {_1} RGB-ის პოლიტიკა ვერ იქნება {_1} +@msg the composite fonts make a file larger than 4 MB, which Import can't read; export fewer of them კომპოზიტური შრიფტებით ფაილი 4 MB-ზე დიდი ხდება, რასაც იმპორტი ვერ წაიკითხავს; გააკეთეთ ნაკლები შრიფტის ექსპორტი +@msg the panels are not hidden პანელები დამალული არ არის +@msg the place cursor that asked for these import options is no longer loaded განთავსების კურსორი, რომელმაც იმპორტის ეს პარამეტრები მოითხოვა, აღარ არის ჩატვირთული +@msg two character sets are named `{name}` ორ სიმბოლოთა ნაკრებს ერთი სახელი აქვს: `{name}` +@msg unknown key `{k}`; a font takes name, parts and custom უცნობი გასაღები `{k}`; შრიფტი იღებს name, parts და custom +@msg {label} failed: {e} {label} ვერ შესრულდა: {e} + Glowing Edges… მანათობელი კიდეები… About VectorCraft VectorCraft-ის შესახებ Align to Path ტრაექტორიაზე სწორება @@ -170,7 +2255,7 @@ Place Image გამოსახულების განთავსება Remove Background ფონის მოშორება Background ფონი - Edge Color კიდის ფერი + Edge Color კიდეების ფერი Picked Colors არჩეული ფერები Corner Color კუთხეების ფერი Contiguous მომიჯნავე @@ -369,7 +2454,7 @@ Create Outlines კონტურებად გარდაქმნა Optical Margin Alignment ოპტიკური არშიის სწორება Dynamic Text დინამიკური ტექსტი - Dynamic Text Presets დინამიკური ტექსტის წინასწარი პარამეტრები + Dynamic Text Presets დინამიკური ტექსტის პრესეტები Arch თაღი @msg select point type or type on a path აირჩიეთ წერტილოვანი ტექსტი ან ტრაექტორიაზე ტექსტი @msg type on a path in a thread cannot use Dynamic Text: {frames} დაკავშირებულ ტექსტში ტრაექტორიაზე ტექსტი ვერ გამოიყენებს დინამიკურ ტექსტს: {frames} @@ -451,7 +2536,7 @@ Revolve (Classic)… ბრუნვა (კლასიკური)… Rotate (Classic)… შემობრუნება (კლასიკური)… Surface ზედაპირი - Wireframe მავთულის ჩარჩო + Wireframe კარკასი Render Settings რენდერის პარამეტრები No Shading დაჩრდილვის გარეშე Plastic პლასტიკური @@ -743,7 +2828,7 @@ Cracked Glaze დამსკდარი მინანქარი Mosaic Floor მოზაიკის იატაკი Quilted Squares ქვილთის კვადრატები - Leaded Glass ტყვიის მინა + Leaded Glass ტყვიის ვიტრაჟი Damp Paper ნესტიანი ქაღალდი Outlines and Rules კონტურები და ხაზები Hand-Drawn ხელით დახატული @@ -923,6 +3008,7 @@ Change Panel Layout პანელების განლაგების შეცვლა Close Panel პანელის დახურვა Collapse Panel Group პანელების ჯგუფის აკეცვა + Cycle Display Sizes ჩვენების ზომების გადართვა Move Panel პანელის გადაადგილება Group with ერთად დაჯგუფება Resize panels პანელების ზომის შეცვლა @@ -942,6 +3028,8 @@ Reset all Revolve settings to their defaults. ბრუნვის ყველა პარამეტრის ნაგულისხმევზე დაბრუნება. Drag values or labels. Double-click a value to type. გადაათრიეთ მნიშვნელობები ან წარწერები. მნიშვნელობის ასაკრეფად ორჯერ დაწკაპეთ. Drag rings to rotate. Shift snaps to 15°. შესაბრუნებლად გადაათრიეთ რგოლები. Shift მიაბამს 15°-ის ჯერად კუთხეებზე. + Track cube შემობრუნების კუბი + Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. შესაბრუნებლად გადაათრიეთ წახნაგი, წიბო ან რგოლი. Shift აბრუნებს ეკრანის ერთი ღერძის გარშემო. Drag the light, or its rings. Shift snaps to 15°. გადაათრიეთ სინათლე ან მისი რგოლები. Shift მიაბამს 15°-ის ჯერად კუთხეებზე. lighting Light სინათლე Keep visible surfaces only when expanding გაშლისას მხოლოდ ხილული ზედაპირების შენარჩუნება @@ -1469,6 +3557,8 @@ lighting Light სინათლე Insert Aki Left აკის ჩასმა მარცხნივ Insert Aki Right აკის ჩასმა მარჯვნივ Tsume ცუმე + Adjust Horizontal Diacritic Position დიაკრიტიკის ჰორიზონტალური პოზიციის მორგება + Adjust Vertical Diacritic Position დიაკრიტიკის ვერტიკალური პოზიციის მორგება Character Direction სიმბოლოების მიმართულება Digits ციფრები Arabic არაბული @@ -1485,14 +3575,14 @@ digits Telugu ტელუგუ digits Kannada კანადა digits Malayalam მალაიალამური Reset Panel პანელის ჩამოყრა - Roman Baseline ლათინური საბაზისო ხაზი + Roman Baseline რომაული საბაზისო ხაზი Select a text object to edit its character attributes. სიმბოლოების ატრიბუტების რედაქტირებისთვის მონიშნეთ ტექსტური ობიექტი. Show Options პარამეტრების ჩვენება Show Recent Colors ბოლოდროინდელი ფერების ჩვენება Toggle RGB Percent RGB-ის პროცენტებში ჩვენების გადართვა Small Caps პატარა მთავრული Small Caps (on the roadmap) პატარა მთავრული (სამომავლო გეგმაშია) - Standard Vertical Roman Alignment სტანდარტული ვერტიკალური ლათინური სწორება + Standard Vertical Roman Alignment სტანდარტული ვერტიკალური რომაული სწორება Strikethrough გადახაზული Character: სიმბოლო: Paragraph: აბზაცი: @@ -1653,7 +3743,7 @@ digits Malayalam მალაიალამური {glyph} is not an alternate of {sel} (U+{code}) as it stands in its word. {glyph} არ არის {sel} (U+{code})-ის ალტერნატივა იმ სახით, როგორც ის თავის სიტყვაშია. Double-click to insert {base} (U+{code}) instead: a presentation form does not join, the letter does. ორჯერ დაწკაპეთ ამის ნაცვლად {base} (U+{code}) ჩასასმელად: გამოსახვის ფორმა არ უკავშირდება, ასო უკავშირდება. Inserted {base} (U+{code}) instead of a presentation form: the font joins it to its neighbors by position. გამოსახვის ფორმის ნაცვლად ჩასმულია {base} (U+{code}): შრიფტი მას მეზობლებს პოზიციის მიხედვით აკავშირებს. - No OpenType feature draws this glyph here, so it replaces the character's glyph and may not join its neighbors. აქ არც ერთი OpenType ფუნქცია არ ხატავს ამ გლიფს, ამიტომ ის ანაცვლებს სიმბოლოს გლიფს და შეიძლება არ დაუკავშირდეს მეზობელ სიმბოლოებს. + No OpenType feature draws this glyph here, so it replaces the character's glyph and may not join its neighbors. აქ არც ერთი OpenType შესაძლებლობა არ ხატავს ამ გლიფს, ამიტომ ის ანაცვლებს სიმბოლოს გლიფს და შეიძლება არ დაუკავშირდეს მეზობელ სიმბოლოებს. Double-click to insert ორჯერ დაწკაპეთ ჩასასმელად Entire Font მთელი შრიფტი glyph {id} გლიფი {id} @@ -1685,7 +3775,7 @@ digits Malayalam მალაიალამური Points: clicks add free points წერტილები: დაწკაპუნებები ამატებს თავისუფალ წერტილებს Radial Gradient რადიალური გრადიენტი Conic Gradient კონუსური გრადიენტი - Diamond Gradient რომბული გრადიენტი + Diamond Gradient ბრილიანტისებრი გრადიენტი Reset to White, Black თეთრზე და შავზე დაბრუნება Reverse Gradient გრადიენტის შებრუნება Gradient Presets გრადიენტის პრესეტები @@ -1838,7 +3928,10 @@ digits Malayalam მალაიალამური Tabular Lining ცხრილური ხაზოვანი Tabular Oldstyle ცხრილური ძველებური Titling Alternates სათაურის ალტერნატივები - Every-line Composer აბზაცის მიხედვით აწყობა + Middle Eastern & South Asian Single-line Composer სტრიქონის მიხედვით აწყობა (შუა აღმოსავლეთი და სამხრეთ აზია) + Middle Eastern & South Asian Every-line Composer აბზაცის მიხედვით აწყობა (შუა აღმოსავლეთი და სამხრეთ აზია) + Standard Single-line Composer სტანდარტული სტრიქონის მიხედვით აწყობა + Standard Every-line Composer სტანდარტული აბზაცის მიხედვით აწყობა First-line Left Indent პირველი სტრიქონის მარცხენა შეწევა Hyphenation… სიტყვების გადატანა… Justification… სწორება… @@ -1864,13 +3957,12 @@ digits Malayalam მალაიალამური Hard მკაცრი Right Indent მარჯვენა შეწევა Right-to-Left Paragraph Direction აბზაცის მიმართულება მარჯვნიდან მარცხნივ - Roman Hanging Punctuation ლათინური გამოწეული პუნქტუაცია + Roman Hanging Punctuation რომაული გამოწეული პუნქტუაცია Korean Line Break Anywhere კორეული სტრიქონის გადატანა ნებისმიერ ადგილას Bunri-Kinshi Bunri-Kinshi East Asian Composition Settings აღმოსავლეთ აზიური აწყობის პარამეტრები Korean Composition Settings კორეული აწყობის პარამეტრები Select a text object to edit its paragraph attributes. აბზაცის ატრიბუტების რედაქტირებისთვის მონიშნეთ ტექსტური ობიექტი. - Single-line Composer სტრიქონის მიხედვით აწყობა Toggle Line Composer აწყობის რეჟიმის გადართვა Space After Paragraph ინტერვალი აბზაცის შემდეგ Space Before Paragraph ინტერვალი აბზაცის წინ @@ -2457,7 +4549,7 @@ digits Malayalam მალაიალამური @plural {n} folder|{n} folders {n} საქაღალდე @plural {n} file|{n} files {n} ფაილი @plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones გამოტოვებული საქაღალდეები: {n} — მაგ. სხვა აპლიკაციების, სისტემის და დამალული საქაღალდეები -@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read ვერ წაიკითხა საქაღალდეები ან ფაილები: {n} +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read საქაღალდეების ან ფაილების წაკითხვა ვერ მოხერხდა: {n} The search stopped at its limit: search a smaller folder. ძიება ზღვარზე შეჩერდა: მოძებნეთ უფრო პატარა საქაღალდეში. Copy only fonts you own or are licensed to install. დააკოპირეთ მხოლოდ ის შრიფტები, რომლებიც გეკუთვნით ან რომელთა დაყენების ლიცენზია გაქვთ. VectorCraft copies the fonts to {folder}. VectorCraft შრიფტებს აკოპირებს აქ: {folder}. @@ -2617,7 +4709,7 @@ digits Malayalam მალაიალამური Printer პრინტერი Printer profile: პრინტერის პროფილი: Printer: პრინტერი: - Rendering intent: რენდერინგის მიზანი: + Rendering intent: რენდერინგის განზრახვა: Same As Source წყაროს მსგავსად Save these settings as a print preset ამ პარამეტრების შენახვა ბეჭდვის პრესეტად Scaling: მასშტაბირება: @@ -2673,6 +4765,7 @@ digits Malayalam მალაიალამური Show smooth color wheel გლუვი ფერთა წრის ჩვენება Show segmented color wheel სეგმენტირებული ფერთა წრის ჩვენება Show color bars ფერთა ზოლების ჩვენება + Find the selected colors in the artwork არჩეული ფერების პოვნა ნახატში Keep this row's colors (exclude) ამ სტრიქონის ფერების შენარჩუნება (გამორიცხვა) Limit to Library: ბიბლიოთეკით შეზღუდვა: Link harmony colors ჰარმონიის ფერების დაკავშირება @@ -2685,7 +4778,7 @@ digits Malayalam მალაიალამური Recolor this row ამ სტრიქონის ხელახლა შეფერადება Reset the rows to the artwork's colors სტრიქონებისთვის ნახატის ფერების დაბრუნება Color Theme Picker ფერთა თემის ამრჩევი - Click or drag across the art to pick its colors; Shift adds more დააწკაპუნეთ ან გადაატარეთ ნახატზე მისი ფერების ასაღებად; Shift ამატებს კიდევ + Click or drag across the art to pick its colors; Shift adds more დაწკაპეთ ან გადაატარეთ ნახატზე მისი ფერების ასაღებად; Shift ამატებს კიდევ Prominent Colors გამოკვეთილი ფერები Save All Colors ყველა ფერის შენახვა Save Prominent Colors გამოკვეთილი ფერების შენახვა @@ -3254,9 +5347,11 @@ theme Appearance იერსახე Split Freeform Line თავისუფალი ხაზის გაყოფა Gradient Vector გრადიენტის ვექტორი Select Gradient Stop გრადიენტის გადასვლის წერტილის მონიშვნა - Create Graph გრაფიკის შექმნა - Graph Data გრაფიკის მონაცემები - Graph Type გრაფიკის ტიპი + Create Graph დიაგრამის შექმნა + Graph Data დიაგრამის მონაცემები + Graph Type დიაგრამის ტიპი + Graph Type… გრაფიკის ტიპი… + Graph Data… გრაფიკის მონაცემები… Graph Options გრაფიკის პარამეტრები Left Axis მარცხენა ღერძი Right Axis მარჯვენა ღერძი @@ -3980,7 +6075,7 @@ font-technology Variable ცვლადი The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. ნაგულისხმევი მნიშვნელობები გამოიყენება, როცა პარამეტრებში OK-ს დააჭერთ. იქ გაუქმება ინარჩუნებს თქვენს მიმდინარე პარამეტრებს. Smaller ↔ Larger უფრო პატარა ↔ უფრო დიდი Smart Guides (View → Smart Guides) ჭკვიანი დამხმარე ხაზები (ხედი → ჭკვიანი დამხმარე ხაზები) - Couldn't save recovery data: {e} აღდგენის მონაცემები ვერ შეინახა: {e} + Couldn't save recovery data: {e} აღდგენის მონაცემების შენახვა ვერ მოხერხდა: {e} Saved recovery data for {title} შენახულია აღდგენის მონაცემები: {title} Saving recovery data for {} ინახება აღდგენის მონაცემები: {} Alt Alt @@ -4202,12 +6297,12 @@ font-technology Variable ცვლადი @msg Couldn't place {name}: the document it was dropped on was reverted {name} ვერ განთავსდა: დოკუმენტი, რომელზეც ის ჩამოაგდეს, წინა ვერსიაზე დაბრუნდა @msg Couldn't place {name}: the document it was placed in was reverted {name} ვერ განთავსდა: დოკუმენტი, რომელშიც ის თავსდებოდა, წინა ვერსიაზე დაბრუნდა @msg Couldn't paste: the document it was pasted in was reverted ჩასმა ვერ მოხერხდა: დოკუმენტი, რომელშიც ის ჩაისმებოდა, წინა ვერსიაზე დაბრუნდა -@msg Couldn't read {name}: {e} {name} ვერ წაიკითხა: {e} -@msg Couldn't save recovery data: {e} აღდგენის მონაცემები ვერ შეინახა: {e} -@msg Couldn't save recovery data for {title}: {e}. Copies go to {folder}, the default recovery folder; to use another folder, set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) დოკუმენტის {title} აღდგენის მონაცემები ვერ შეინახა: {e}. ასლები ინახება საქაღალდეში {folder}, რომელიც აღდგენის ნაგულისხმევი საქაღალდეა; სხვა საქაღალდის გამოსაყენებლად მიუთითეთ პარამეტრები → ფაილების დამუშავება → მონაცემთა აღდგენა → საქაღალდე (recoveryFolder) -@msg Couldn't save recovery data for {title}: {e}. Copies go to {folder}, the folder set in Preferences; to use another folder, set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) დოკუმენტის {title} აღდგენის მონაცემები ვერ შეინახა: {e}. ასლები ინახება საქაღალდეში {folder}, რომელიც პარამეტრებშია მითითებული; სხვა საქაღალდის გამოსაყენებლად მიუთითეთ პარამეტრები → ფაილების დამუშავება → მონაცემთა აღდგენა → საქაღალდე (recoveryFolder) -@msg Couldn't save recovery data: {e}. Copies go to {folder}, the default recovery folder; to use another folder, set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) აღდგენის მონაცემები ვერ შეინახა: {e}. ასლები ინახება საქაღალდეში {folder}, რომელიც აღდგენის ნაგულისხმევი საქაღალდეა; სხვა საქაღალდის გამოსაყენებლად მიუთითეთ პარამეტრები → ფაილების დამუშავება → მონაცემთა აღდგენა → საქაღალდე (recoveryFolder) -@msg Couldn't save recovery data: {e}. Copies go to {folder}, the folder set in Preferences; to use another folder, set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) აღდგენის მონაცემები ვერ შეინახა: {e}. ასლები ინახება საქაღალდეში {folder}, რომელიც პარამეტრებშია მითითებული; სხვა საქაღალდის გამოსაყენებლად მიუთითეთ პარამეტრები → ფაილების დამუშავება → მონაცემთა აღდგენა → საქაღალდე (recoveryFolder) +@msg Couldn't read {name}: {e} ფაილის წაკითხვა ვერ მოხერხდა ({name}): {e} +@msg Couldn't save recovery data: {e} აღდგენის მონაცემების შენახვა ვერ მოხერხდა: {e} +@msg Couldn't save recovery data for {title}: {e}. Copies go to {folder}, the default recovery folder; to use another folder, set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) დოკუმენტის {title} აღდგენის მონაცემების შენახვა ვერ მოხერხდა: {e}. ასლები ინახება საქაღალდეში {folder}, რომელიც აღდგენის ნაგულისხმევი საქაღალდეა; სხვა საქაღალდის გამოსაყენებლად მიუთითეთ პარამეტრები → ფაილების დამუშავება → მონაცემთა აღდგენა → საქაღალდე (recoveryFolder) +@msg Couldn't save recovery data for {title}: {e}. Copies go to {folder}, the folder set in Preferences; to use another folder, set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) დოკუმენტის {title} აღდგენის მონაცემების შენახვა ვერ მოხერხდა: {e}. ასლები ინახება საქაღალდეში {folder}, რომელიც პარამეტრებშია მითითებული; სხვა საქაღალდის გამოსაყენებლად მიუთითეთ პარამეტრები → ფაილების დამუშავება → მონაცემთა აღდგენა → საქაღალდე (recoveryFolder) +@msg Couldn't save recovery data: {e}. Copies go to {folder}, the default recovery folder; to use another folder, set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) აღდგენის მონაცემების შენახვა ვერ მოხერხდა: {e}. ასლები ინახება საქაღალდეში {folder}, რომელიც აღდგენის ნაგულისხმევი საქაღალდეა; სხვა საქაღალდის გამოსაყენებლად მიუთითეთ პარამეტრები → ფაილების დამუშავება → მონაცემთა აღდგენა → საქაღალდე (recoveryFolder) +@msg Couldn't save recovery data: {e}. Copies go to {folder}, the folder set in Preferences; to use another folder, set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) აღდგენის მონაცემების შენახვა ვერ მოხერხდა: {e}. ასლები ინახება საქაღალდეში {folder}, რომელიც პარამეტრებშია მითითებული; სხვა საქაღალდის გამოსაყენებლად მიუთითეთ პარამეტრები → ფაილების დამუშავება → მონაცემთა აღდგენა → საქაღალდე (recoveryFolder) @msg Create Outlines: select text objects კონტურების შექმნა: მონიშნეთ ტექსტური ობიექტები @msg Create from Guides: the document has no artboard დამხმარე ხაზებიდან შექმნა: დოკუმენტს სამუშაო დაფა არ აქვს @msg Create from Guides: the guides make more than {MAX_PIECES} slices დამხმარე ხაზებიდან შექმნა: დამხმარე ხაზები {MAX_PIECES}-ზე მეტ ნაჭერს ქმნის @@ -4364,7 +6459,7 @@ font-technology Variable ცვლადი @msg `{name}` is a built-in preset and can't change: save it under another name `{name}` ჩაშენებული პრესეტია და მისი შეცვლა შეუძლებელია: შეინახეთ სხვა სახელით @msg `{name}` is a built-in preset and stays `{name}` ჩაშენებული პრესეტია და მისი წაშლა შეუძლებელია @msg a swatch or color group named `{n}` exists ფერის ნიმუში ან ფერების ჯგუფი სახელით `{n}` არსებობს -@msg a slice size must be a positive number of points ნაჭრის ზომა წერტილების დადებითი რიცხვი უნდა იყოს +@msg a slice size must be a positive number of points ნაჭრის ზომა უნდა იყოს დადებითი რიცხვი პუნქტებში @msg a stream runs past the end ნაკადი ბოლოს სცილდება @msg a stream's length is wrong ნაკადის სიგრძე არასწორია @msg a stream's length isn't a number ნაკადის სიგრძე რიცხვი არ არის @@ -4576,7 +6671,7 @@ font-technology Variable ცვლადი @msg not a VectorCraft file: {0} ეს არ არის VectorCraft-ის ფაილი: {0} @msg not a VectorCraft shortcut set (missing `overrides`) ეს არ არის VectorCraft-ის მალსახმობების ნაკრები (აკლია `overrides`) @msg not a graphic style library (format `{_1}`) ეს არ არის გრაფიკული სტილების ბიბლიოთეკა (ფორმატი `{_1}`) -@msg not a stored central record ეს არ არის შენახული ცენტრალური ჩანაწერი +@msg not a stored central record ეს არ არის შეუკუმშავი (stored) ცენტრალური ჩანაწერი @msg not a valid plug-in module: {0} ეს არ არის პლაგინის სწორი მოდული: {0} @msg not an EMF or WMF file ეს არ არის EMF ან WMF ფაილი @msg not an HP-GL file ეს არ არის HP-GL ფაილი @@ -4637,7 +6732,7 @@ font-technology Variable ცვლადი @msg select a blend მონიშნეთ გადასვლა @msg select a clip group მონიშნეთ მომჭრელი ჯგუფი @msg select a gradient mesh მონიშნეთ გრადიენტული ბადე -@msg select a linked image: an embedded one has no file მონიშნეთ მიბმული გამოსახულება: ჩაშენებულს ფაილი არ აქვს +@msg select a linked image: an embedded one has no file მონიშნეთ დაკავშირებული გამოსახულება: ჩაშენებულს ფაილი არ აქვს @msg select a repeat მონიშნეთ გამეორება @msg select a stroke with a variable width მონიშნეთ ცვლადი სიგანის კონტური @msg select a symbol instance მონიშნეთ სიმბოლოს ეგზემპლარი @@ -4654,7 +6749,7 @@ font-technology Variable ცვლადი @msg `match` must be distance or channels `match` უნდა იყოს distance ან channels @msg `{key}` must be from 0 to 100 `{key}` უნდა იყოს 0-დან 100-მდე @msg `colors` must list 1 to 16 colors, each hex (#rrggbb or #rgb) or black, white, red, green or blue `colors` უნდა შეიცავდეს 1-დან 16-მდე ფერს, თითოეულს თექვსმეტობით ფორმატში (#rrggbb ან #rgb) ან როგორც black, white, red, green ან blue -@msg the linked image shows its preview: embed or relink it first დაკავშირებული გამოსახულება გადახედვას აჩვენებს: ჯერ ჩააშენეთ ან ხელახლა მიაბით +@msg the linked image shows its preview: embed or relink it first დაკავშირებული გამოსახულება გადახედვას აჩვენებს: ჯერ ჩააშენეთ ან ხელახლა დააკავშირეთ @msg a CMYK image has no transparency to set CMYK გამოსახულებას არ აქვს დასაყენებელი გამჭვირვალობა @msg every pixel matches the background: no image would be left ყველა პიქსელი ემთხვევა ფონს: გამოსახულება აღარ დარჩებოდა @msg an image of {w} × {h} pixels is too large to change {w} × {h} პიქსელის გამოსახულება შესაცვლელად ზედმეტად დიდია @@ -4771,6 +6866,8 @@ font-technology Variable ცვლადი @msg unknown option `{path}.{k}` უცნობი პარამეტრი `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) უცნობი ზედდაბეჭდვა `{o}` (preserve, simulate ან discard) @msg unknown panel `{raw}` უცნობი პანელი `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` პანელს არ აქვს გადასართავი ჩვენების ზომები +@msg the panels are not shown პანელები არ ჩანს @msg panels can't be shown in Presentation Mode პრეზენტაციის რეჟიმში პანელების ჩვენება შეუძლებელია @msg unknown preference `{key}` უცნობი პარამეტრი `{key}` @msg Preferences imported. პარამეტრები იმპორტირებულია. @@ -4822,7 +6919,7 @@ font-technology Variable ცვლადი @msg {name}: CRC mismatch {name}: CRC არ ემთხვევა @msg {name}: no local header {name}: ლოკალური სათაური არ არის @msg {name}: no such recovery entry {name}: ასეთი აღდგენის ჩანაწერი არ არის -@msg {path} can't be found: relink it first {path} ვერ მოიძებნა: ჯერ ხელახლა მიაბით +@msg {path} can't be found: relink it first {path} ვერ მოიძებნა: ჯერ ხელახლა დააკავშირეთ @msg {path}: no file system here (pass dataBase64 to open; omit the path to get dataBase64) {path}: აქ ფაილური სისტემა არ არის (გასახსნელად გადაეცით dataBase64; dataBase64-ის მისაღებად გამოტოვეთ path) @msg {path}: {e} {path}: {e} @msg {status} ({e}) {status} ({e}) @@ -4845,7 +6942,7 @@ font-technology Variable ცვლადი @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} გაიხსნა, შენიშვნები: {n}: {first} @msgplural {notice}. Opened with {n} note: {first}|{notice}. Opened with {n} notes: {first} {notice}. გაიხსნა, შენიშვნები: {n}: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} შენახულია {path}, შენიშვნები: {n}: {first} -@msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first ჩაშენებულია გამოსახულებები: {n}; აკლია {missing}: ჯერ ხელახლა მიაბით +@msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first ჩაშენებულია გამოსახულებები: {n}; აკლია {missing}: ჯერ ხელახლა დააკავშირეთ @msgplural Embedded {n} image|Embedded {n} images ჩაშენებულია გამოსახულებები: {n} @msgplural Relinked {n} image|Relinked {n} images ხელახლა მიბმულია გამოსახულებები: {n} @msgplural Relinked {n} image; not in that folder: {names}|Relinked {n} images; not in that folder: {names} ხელახლა მიბმულია გამოსახულებები: {n}; იმ საქაღალდეში არ არის: {names} @@ -4853,10 +6950,10 @@ font-technology Variable ცვლადი @msgplural Updated {n} image|Updated {n} images განახლებულია გამოსახულებები: {n} @msgplural Replaced {n} image|Replaced {n} images ჩანაცვლებულია გამოსახულებები: {n} @msgplural Broke {n} link|Broke {n} links გაწყვეტილია ბმულები: {n} -@msgplural Broke {n} link; {missing} can't be read: relink or update them first|Broke {n} links; {missing} can't be read: relink or update them first გაწყვეტილია ბმულები: {n}; ვერ იკითხება {missing}: ჯერ ხელახლა მიაბით ან განაახლეთ -@msgplural {n} linked file can't be read here: its preview shows|{n} linked files can't be read here: their previews show მიბმული ფაილების წაკითხვა აქ ვერ ხერხდება ({n}): ჩანს მათი გადახედვა +@msgplural Broke {n} link; {missing} can't be read: relink or update them first|Broke {n} links; {missing} can't be read: relink or update them first გაწყვეტილია ბმულები: {n}; ვერ იკითხება {missing}: ჯერ ხელახლა დააკავშირეთ ან განაახლეთ +@msgplural {n} linked file can't be read here: its preview shows|{n} linked files can't be read here: their previews show დაკავშირებული ფაილების წაკითხვა აქ ვერ ხერხდება ({n}): ჩანს მათი გადახედვა @msgplural {n} image couldn't be decoded and shows as a crossed box|{n} images couldn't be decoded and show as crossed boxes სურათების დეკოდირება ვერ მოხერხდა ({n}): ისინი ჯვრით გადახაზული ჩარჩოებით ჩანს -@msgplural {n} linked image changed on disk: Update Links shows the new version|{n} linked images changed on disk: Update Links shows the new versions მიბმული გამოსახულებები შეიცვალა დისკზე ({n}): ბმულების განახლება აჩვენებს ახალ ვერსიებს +@msgplural {n} linked image changed on disk: Update Links shows the new version|{n} linked images changed on disk: Update Links shows the new versions დაკავშირებული გამოსახულებები შეიცვალა დისკზე ({n}): ბმულების განახლება აჩვენებს ახალ ვერსიებს @msgplural Updated {n} linked file changed on disk|Updated {n} linked files changed on disk განახლდა დისკზე შეცვლილი დაკავშირებული ფაილები: {n} @msg the document sets a bleed that this PDF/X file leaves out: turn on Use document bleed settings დოკუმენტი ადგენს ჭრისპირა არეს, რომელსაც ეს PDF/X ფაილი გამოტოვებს: ჩართეთ „დოკუმენტის ჭრისპირა არის პარამეტრების გამოყენება“ @msgplural Exported {what} with {n} note: {first}|Exported {what} with {n} notes: {first} ექსპორტირებულია {what}, შენიშვნები: {n}: {first} @@ -4955,13 +7052,13 @@ font-technology Variable ცვლადი @msg id {value} is a layer, not an object; move layers with layer.move id {value} შრეა და არა ობიექტი; შრეების გადასატანად გამოიყენეთ layer.move @msg automation filesystem access is not granted: read authority is absent: {path} ავტომატიზაციას ფაილურ სისტემაზე წვდომა არ აქვს: წაკითხვის უფლება არ არის: {path} @msg automation filesystem access is not granted: write authority is absent: {path} ავტომატიზაციას ფაილურ სისტემაზე წვდომა არ აქვს: ჩაწერის უფლება არ არის: {path} -@msg automation path rejected: outside the read root {root}: {path} ავტომატიზაციის გზა უარყოფილია: წაკითხვის ძირის {root} გარეთაა: {path} -@msg automation path rejected: outside the read roots {roots}: {path} ავტომატიზაციის გზა უარყოფილია: წაკითხვის ძირების {roots} გარეთაა: {path} -@msg a linked JavaScript file is outside the read roots დაკავშირებული JavaScript ფაილი წაკითხვის ძირების გარეთაა -@msg the library's file is outside the read roots ბიბლიოთეკის ფაილი წაკითხვის ძირების გარეთაა -@msg {file} names more than one linked JavaScript file {file} ერთზე მეტ დაკავშირებულ JavaScript ფაილს შეესაბამება -@msg automation path rejected: outside the write root {root}: {path} ავტომატიზაციის გზა უარყოფილია: ჩაწერის ძირის {root} გარეთაა: {path} -@msg automation path rejected: outside the write roots {roots}: {path} ავტომატიზაციის გზა უარყოფილია: ჩაწერის ძირების {roots} გარეთაა: {path} +@msg automation path rejected: outside the read root {root}: {path} ავტომატიზაციის გზა უარყოფილია: წაკითხვის ძირეული საქაღალდის {root} გარეთაა: {path} +@msg automation path rejected: outside the read roots {roots}: {path} ავტომატიზაციის გზა უარყოფილია: წაკითხვის ძირეული საქაღალდეების {roots} გარეთაა: {path} +@msg a linked JavaScript file is outside the read roots დაკავშირებული JavaScript ფაილი წაკითხვის ძირეული საქაღალდეების გარეთაა +@msg the library's file is outside the read roots ბიბლიოთეკის ფაილი წაკითხვის ძირეული საქაღალდეების გარეთაა +@msg {file} names more than one linked JavaScript file {file} ერთზე მეტ დაკავშირებულ JavaScript ფაილს ასახელებს +@msg automation path rejected: outside the write root {root}: {path} ავტომატიზაციის გზა უარყოფილია: ჩაწერის ძირეული საქაღალდის {root} გარეთაა: {path} +@msg automation path rejected: outside the write roots {roots}: {path} ავტომატიზაციის გზა უარყოფილია: ჩაწერის ძირეული საქაღალდეების {roots} გარეთაა: {path} @msg automation path rejected: path is empty ავტომატიზაციის გზა უარყოფილია: გზა ცარიელია @msg automation path rejected: a link that leads nowhere: {path} ავტომატიზაციის გზა უარყოფილია: ბმული არსად მიდის: {path} @msg automation path rejected: cannot resolve {path}: {e} ავტომატიზაციის გზა უარყოფილია: {path} ვერ გაირკვა: {e} @@ -5321,7 +7418,7 @@ font-technology Variable ცვლადი @msg every numbered name for {name} is taken in the document's folder დოკუმენტის საქაღალდეში {name}-ის ყველა დანომრილი სახელი დაკავებულია @msg No linked files to look for მოსაძებნი დაკავშირებული ფაილები არ არის @msg The link is inside a symbol, graph design, pattern or opacity mask and has no place on the canvas ბმული სიმბოლოში, დიაგრამის დიზაინში, პატერნში ან გაუმჭვირვალობის ნიღაბშია და ტილოზე ადგილი არ აქვს -@msg the art of a graph design in a graph series is drawn again from the design: edit the design to change it დიაგრამის სერიაში დიაგრამის დიზაინის გრაფიკა დიზაინიდან თავიდან იხატება: მის შესაცვლელად დაარედაქტირეთ დიზაინი +@msg the art of a graph design in a graph series is drawn again from the design: edit the design to change it დიაგრამის სერიაში დიაგრამის დიზაინის ნახატი დიზაინიდან თავიდან იხატება: მის შესაცვლელად დიზაინი შეცვალეთ Ruler Origin სახაზავების სათავე Reset Ruler Origin სახაზავების სათავის ჩამოყრა Artistic მხატვრული @@ -5705,7 +7802,7 @@ imageTrace Outline კონტური @msg vc.document{place} is too large for a script vc.document{place} ზედმეტად დიდია სკრიპტისთვის @msg vc.log: the log of this run is full vc.log: ამ გაშვების ჟურნალი სავსეა @msg this function's script run has ended ამ ფუნქციის სკრიპტის გაშვება დასრულდა -@msg the script made more host calls than one run may make სკრიპტმა იმაზე მეტი მასპინძლის გამოძახება შეასრულა, ვიდრე ერთ გაშვებას შეუძლია +@msg the script made more host calls than one run may make სკრიპტმა ჰოსტის იმაზე მეტი გამოძახება შეასრულა, ვიდრე ერთ გაშვებაშია დასაშვები @msg the script passed more data to and from commands than one run may pass სკრიპტმა ბრძანებებს და ბრძანებებიდან იმაზე მეტი მონაცემი გადასცა, ვიდრე ერთ გაშვებას შეუძლია @msg the script added more objects and data to the documents than one run may add სკრიპტმა დოკუმენტებს იმაზე მეტი ობიექტი და მონაცემი დაამატა, ვიდრე ერთ გაშვებას შეუძლია @msg {what}: the object is not a File or a Folder {what}: ობიექტი არც File-ია და არც Folder @@ -5716,6 +7813,7 @@ imageTrace Outline კონტური @msg `name` must be the name of a script engine `name` უნდა იყოს სკრიპტის ძრავის სახელი @msg the main script engine is new for each run and is never kept, so it cannot be dropped მთავარი სკრიპტის ძრავა ყოველი გაშვებისთვის ახალია და არასოდეს ინახება, ამიტომ მისი მოცილება შეუძლებელია @msg there is no script engine named {name} სკრიპტის ძრავა სახელით {name} არ არსებობს +@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` მხოლოდ ისეთი გაშვებისთვისაა, სადაც შესაკითხი არავინაა: აპში თითოეულ დიალოგს ადამიანი პასუხობს @msg Running a script სკრიპტი მუშაობს @msg Copied the script report კოპირებულია სკრიპტის ანგარიში @msg Copied the link info კოპირებულია ბმულის ინფორმაცია @@ -5834,8 +7932,8 @@ imageTrace Outline კონტური PDF-compatible PDF-თან თავსებადი Panels Except Tools and Control პანელები, ხელსაწყოებისა და მართვის პანელის გარდა Isolate Selected Object მონიშნული ობიექტის იზოლირება -@msg the file's layers weren't read ({_1}): it comes in as its page, in one layer ფაილის შრეები ვერ წაიკითხა ({_1}): ის გაიხსნება როგორც მისი გვერდი, ერთ შრეში -@msg the file's layers weren't read from its editing data ({_1}): they come from its PDF part ფაილის შრეები რედაქტირების მონაცემებიდან ვერ წაიკითხა ({_1}): ისინი მისი PDF ნაწილიდან აიღება +@msg the file's layers weren't read ({_1}): it comes in as its page, in one layer ფაილის შრეების წაკითხვა ვერ მოხერხდა ({_1}): ის გაიხსნება როგორც მისი გვერდი, ერთ შრეში +@msg the file's layers weren't read from its editing data ({_1}): they come from its PDF part ფაილის შრეების წაკითხვა რედაქტირების მონაცემებიდან ვერ მოხერხდა ({_1}): ისინი მისი PDF ნაწილიდან აიღება @msg the Color Picker is not open ფერის ამრჩევი გახსნილი არ არის @msg the Simplify slider is not open გამარტივების სლაიდერი გახსნილი არ არის @msg the Smooth slider is not open გაგლუვების სლაიდერი გახსნილი არ არის @@ -5849,7 +7947,7 @@ imageTrace Outline კონტური Preview (1 inch on the page) წინასწარი ნახვა (1 დუიმი გვერდზე) Set as Default ნაგულისხმევად დაყენება out from a highlighted edge to place its dimension | — გამოკვეთილი კიდიდან გარეთ, მისი ზომის დასასმელად | - two points, then move and click to place an aligned, horizontal or vertical dimension | — ორ წერტილზე, შემდეგ გადაადგილეთ და დააწკაპუნეთ გასწორებული, ჰორიზონტალური ან ვერტიკალური ზომის დასასმელად | + two points, then move and click to place an aligned, horizontal or vertical dimension | — ორ წერტილზე, შემდეგ გადაადგილეთ და დაწკაპეთ გასწორებული, ჰორიზონტალური ან ვერტიკალური ზომის დასასმელად | cancels | Double-click the tool for options — გაუქმება | პარამეტრებისთვის ორჯერ დაწკაპეთ ხელსაწყოზე Angular კუთხური Away from the Line ხაზისგან მოშორებით @@ -5930,13 +8028,14 @@ imageTrace Outline კონტური @msg span must be "object" or "selection", got {v} span უნდა იყოს "object" ან "selection", მიღებულია {v} @msg span: "selection" places a `gradient`, not a swatch span: "selection" ათავსებს `gradient`-ს და არა ფერის ნიმუშს @msg span: "selection" places a gradient: give `gradient` span: "selection" ათავსებს გრადიენტს: მიუთითეთ `gradient` -@msg span: "selection" places a linear, radial, conic or diamond gradient, not a freeform one span: "selection" ათავსებს წრფივ, რადიალურ, კონუსურ ან რომბულ გრადიენტს და არა თავისუფალი ფორმისას +@msg span: "selection" places a linear, radial, conic or diamond gradient, not a freeform one span: "selection" ათავსებს წრფივ, რადიალურ, კონუსურ ან ბრილიანტისებრ გრადიენტს და არა თავისუფალი ფორმისას @msg span: "selection" places the gradient itself: leave out `start` and `end` (they already place it in document coordinates) span: "selection" თავად ათავსებს გრადიენტს: გამოტოვეთ `start` და `end` (ისინი მას უკვე დოკუმენტის კოორდინატებში ათავსებენ) Make Image Dynamic გამოსახულების დინამიკურად ქცევა Import Data Sets… მონაცემთა ნაკრებების იმპორტი… Export Data Sets… მონაცემთა ნაკრებების ექსპორტი… Load Variable Library… ცვლადების ბიბლიოთეკის ჩატვირთვა… Save Variable Library… ცვლადების ბიბლიოთეკის შენახვა… +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml „იმპორტი“ კითხულობს მონაცემთა წყაროს ფაილს გაფართოებით .csv, .tsv, .txt ან .xml @msg a variable library holds text variables, and the document has none ცვლადების ბიბლიოთეკა ტექსტურ ცვლადებს შეიცავს, დოკუმენტს კი არცერთი არ აქვს @msg variable `{name}` can't be saved in a variable library: rename it to start with a letter or `_`, without spaces or symbols other than `-`, `_` and `.` ცვლადი `{name}` ვერ შეინახება ცვლადების ბიბლიოთეკაში: გადაარქვით სახელი ისე, რომ იწყებოდეს ასოთი ან `_`-ით, ჰარეების და `-`, `_` და `.`-ის გარდა სხვა სიმბოლოების გარეშე @msg {k} has control characters {k} შეიცავს მმართველ სიმბოლოებს @@ -6134,6 +8233,14 @@ imageTrace Outline კონტური JavaScript: JavaScript: Large Gaps დიდი ღრეჩოები Last Artboard ბოლო სამუშაო დაფა + Status Bar Show ჩვენება მდგომარეობის ზოლში + Artboard Name სამუშაო დაფის სახელი + Current Tool მიმდინარე ხელსაწყო + Date and Time თარიღი და დრო + Number of Undos დაბრუნებების რაოდენობა + Document Color Profile დოკუმენტის ფერის პროფილი + Undos დაბრუნებები + Redos ხელახლა შესრულებები Levels დონეები Library Panel Options ბიბლიოთეკის პანელის პარამეტრები Locate Library… ბიბლიოთეკის მოძებნა… @@ -6453,7 +8560,7 @@ axis Y Axis Y ღერძი @msg `method` must be classic, perceptual, hue-clockwise or hue-counterclockwise `method` უნდა იყოს classic, perceptual, hue-clockwise ან hue-counterclockwise @msg `spread` must be pad, repeat or reflect `spread` უნდა იყოს pad, repeat ან reflect @msg `repeats` must be a whole number from 1 to {MAX_REPEATS} `repeats` უნდა იყოს მთელი რიცხვი 1-დან {MAX_REPEATS}-მდე -@msg `spread` applies to linear, radial, conic and diamond gradients `spread` ეხება წრფივ, რადიალურ, კონუსურ და რომბულ გრადიენტებს +@msg `spread` applies to linear, radial, conic and diamond gradients `spread` ეხება წრფივ, რადიალურ, კონუსურ და ბრილიანტისებრ გრადიენტებს # Heavy plug-in filters (plugin.inspect, plug-in runs) Install “{name}”, which asks for a heavy budget? დავაყენოთ „{name}“, რომელიც დიდ გამოთვლით ბიუჯეტს ითხოვს? Each run may take up to {minutes} minutes and do {times} times the work other plug-ins may. It runs in the background, and you can cancel it. თითოეულ გაშვებას შეიძლება {minutes} წუთამდე დასჭირდეს და სხვა პლაგინებისთვის დაშვებულზე {times}-ჯერ მეტი სამუშაო შეასრულოს. ის ფონურ რეჟიმში მუშაობს და შეგიძლიათ გააუქმოთ. @@ -6507,6 +8614,7 @@ axis Y Axis Y ღერძი @msg {what} points outside memory {what} მეხსიერების გარეთ მიუთითებს @msg `angle` must be a number `angle` უნდა იყოს რიცხვი @msg `aspect` must be from 0.01 to 100 `aspect` უნდა იყოს 0.01-დან 100-მდე +@msg `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 `axes` უნდა იყოს [a, b, c, d], თითოეული -1000-დან 1000-მდე, ხოლო a·d - b·c უნდა განსხვავდებოდეს 0-ისგან მინიმუმ 0.001-ით @msg `cap` must be "butt", "round" or "square" `cap` უნდა იყოს "butt", "round" ან "square" @msg `fillRule` must be "nonzero" or "evenodd" `fillRule` უნდა იყოს "nonzero" ან "evenodd" @msg `helpUrl` must be an https:// address of at most {MAX_HELP_URL} bytes `helpUrl` უნდა იყოს https:// მისამართი, არაუმეტეს {MAX_HELP_URL} ბაიტისა @@ -7172,7 +9280,7 @@ anchor Points: წერტილები: @msg {label} must be a number of at least 0.1 {label} უნდა იყოს მინიმუმ 0,1 Advanced Character Formats სიმბოლოს დამატებითი ფორმატები Basic Paragraph Formats აბზაცის ძირითადი ფორმატები - Composition კომპოზიცია + Composition აწყობა Horizontal Scale ჰორიზონტალური მასშტაბი Vertical Scale ვერტიკალური მასშტაბი @msg {label} must be a number from {min} to {max} {label} უნდა იყოს რიცხვი {min}-დან {max}-მდე @@ -7765,3 +9873,21 @@ font-script Japanese იაპონური Nest Shapes… ფორმების განლაგება… Nest Shapes ფორმების განლაგება Roll რულონი + Packaging Tools შეფუთვის ხელსაწყოები + Fold Lines მოკეცვის ხაზები + Make Cut Line ჭრის ხაზად გადაქცევა + Make Crease Line ბიგის ხაზად გადაქცევა + Make Partial Cut Line ნაწილობრივი ჭრის ხაზად გადაქცევა + Make Perforation Line პერფორაციის ხაზად გადაქცევა + Make Fold Line მოკეცვის ხაზად გადაქცევა + Role Swatches… ხაზის ტიპების ფერის ნიმუშები… + Role Swatches ხაზის ტიპების ფერის ნიმუშები + Role ხაზის ტიპი + Cut Line ჭრის ხაზი + Crease Line ბიგის ხაზი + Partial Cut Line ნაწილობრივი ჭრის ხაზი + Perforation Line პერფორაციის ხაზი + No objects are selected. ობიექტები არ არის მონიშნული. + Open a document to mark its fold lines. გახსენით დოკუმენტი მისი მოკეცვის ხაზების მოსანიშნად. + Remove Fold Line Role ხაზის ტიპის მოხსნა +@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer უნდა იყოს "singleLine", "everyLine", "standardSingleLine" ან "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 566c1858d5..90f4e1f3fd 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -49,6 +49,8 @@ font-technology Variable 가변 Insert Aki Left 앞 아키 삽입 Insert Aki Right 뒤 아키 삽입 Tsume 츠메 + Adjust Horizontal Diacritic Position 발음 구별 기호 가로 위치 조정 + Adjust Vertical Diacritic Position 발음 구별 기호 세로 위치 조정 Character Direction 문자 방향 Digits 숫자 Arabic 아라비아어 @@ -1678,7 +1680,10 @@ antiAlias Sharp 날카롭게 Every (minutes) 간격 (분) Every option is at its default. 모든 옵션이 기본값입니다. Every option matches {base}. 모든 옵션이 {base}와(과) 같습니다. - Every-line Composer 전체 줄 컴포저 + Middle Eastern & South Asian Single-line Composer 한 줄 조판 (중동·남아시아) + Middle Eastern & South Asian Every-line Composer 전체 줄 컴포저 (중동·남아시아) + Standard Single-line Composer 표준 한 줄 조판 + Standard Every-line Composer 표준 전체 줄 컴포저 Exact dash lengths 정확한 대시 길이 Exceptions (comma separated) 예외 (쉼표로 구분) Exclusion 제외 @@ -1875,6 +1880,14 @@ antiAlias Sharp 날카롭게 Previous Artboard 이전 아트보드 Next Artboard 다음 아트보드 Last Artboard 마지막 아트보드 + Status Bar Show 상태 표시줄 표시 + Artboard Name 아트보드 이름 + Current Tool 현재 도구 + Date and Time 날짜 및 시간 + Number of Undos 실행 취소 횟수 + Document Color Profile 문서 색상 프로파일 + Undos 실행 취소 + Redos 다시 실행 Gradient Fill: click to apply, drag onto art 그레이디언트 칠: 클릭하여 적용, 아트웍에 끌어 놓기 Gradient Mesh 그레이디언트 메시 Gradient Tool 그레이디언트 도구 @@ -1917,6 +1930,7 @@ antiAlias Sharp 날카롭게 Show smooth color wheel 부드러운 색상환 표시 Show segmented color wheel 분할 색상환 표시 Show color bars 색상 막대 표시 + Find the selected colors in the artwork 선택한 색상을 아트웍에서 찾기 Height 높이 Height: 높이: Help › Search Commands… 도움말 › 명령 검색… @@ -3271,7 +3285,6 @@ mark-style Japanese 일본식 Simulate Colored Paper 색 용지 시뮬레이션 Simulate Paper 용지 시뮬레이션 Single Quotes: 작은따옴표: - Single-line Composer 한 줄 조판 Toggle Line Composer 줄 조판 방식 전환 Size Tile to Art 타일을 아트웍 크기에 맞춤 Move Tile with Art 아트웍과 함께 타일 이동 @@ -3849,6 +3862,8 @@ file-filter Templates 템플릿 Gradient (. or Shift+.) 그레이디언트 (. 또는 Shift+.) Graph Data 그래프 데이터 Graph Type 그래프 유형 + Graph Type… 그래프 유형… + Graph Data… 그래프 데이터… Graph Options 그래프 옵션 Left Axis 왼쪽 축 Right Axis 오른쪽 축 @@ -5025,6 +5040,8 @@ theme Appearance 외관 @msg give only one of onto, below and above onto, below, above 중 하나만 지정하세요 @msg column must be true or a number from 1 column은 true이거나 1 이상의 숫자여야 합니다 @msg unknown panel `{raw}` 알 수 없는 패널 `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}`에는 전환할 표시 크기가 없습니다 +@msg the panels are not shown 패널이 표시되지 않습니다 @msg panels can't be shown in Presentation Mode 프레젠테이션 모드에서는 패널을 표시할 수 없습니다 @msg x and y must both be numbers x와 y는 모두 숫자여야 합니다 @msg Downloaded {what} {what}을(를) 다운로드했습니다 @@ -5226,6 +5243,7 @@ theme Appearance 외관 @msg `name` must be the name of a script engine `name`은(는) 스크립트 엔진의 이름이어야 합니다 @msg the main script engine is new for each run and is never kept, so it cannot be dropped 기본 스크립트 엔진은 실행마다 새로 만들어지고 유지되지 않으므로 삭제할 수 없습니다 @msg there is no script engine named {name} 이름이 {name}인 스크립트 엔진이 없습니다 +@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers`는 물어볼 사람이 없는 실행에만 쓰입니다. 앱에서는 사람이 각 대화 상자에 답합니다 @msg Running a script 스크립트 실행 중 @msg Copied the script report 스크립트 보고서를 복사했습니다 @msg Copied the link info 링크 정보를 복사했습니다 @@ -5505,6 +5523,7 @@ effect Vertical 세로 Change Panel Layout 패널 레이아웃 변경 Close Panel 패널 닫기 Collapse Panel Group 패널 그룹 접기 + Cycle Display Sizes 표시 크기 전환 Move Panel 패널 이동 Group with 함께 그룹화 Resize panels 패널 크기 조절 @@ -5546,6 +5565,8 @@ effect Vertical 세로 Step up or down 한 단계 올리기 또는 내리기 Drag values or labels. Double-click a value to type. 값이나 레이블을 드래그하세요. 값을 더블클릭하면 입력할 수 있습니다. Drag rings to rotate. Shift snaps to 15°. 링을 드래그해 회전하세요. Shift를 누르면 15°씩 스냅됩니다. + Track cube 회전 큐브 + Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. 면, 모서리 또는 링을 드래그해 회전하세요. Shift를 누르면 화면의 한 축을 중심으로 회전합니다. Drag the light, or its rings. Shift snaps to 15°. 조명이나 링을 드래그하세요. Shift를 누르면 15°씩 스냅됩니다. lighting Light 광원 Keep visible surfaces only when expanding 확장 시 보이는 표면만 유지 @@ -5856,6 +5877,7 @@ lighting Light 광원 Export Data Sets… 데이터 세트 내보내기… Load Variable Library… 변수 라이브러리 불러오기… Save Variable Library… 변수 라이브러리 저장… +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml "가져오기"는 확장자가 .csv, .tsv, .txt 또는 .xml인 데이터 소스 파일을 읽습니다 @msg a variable library holds text variables, and the document has none 변수 라이브러리에는 텍스트 변수가 들어가는데 문서에 텍스트 변수가 없습니다 @msg variable `{name}` can't be saved in a variable library: rename it to start with a letter or `_`, without spaces or symbols other than `-`, `_` and `.` 변수 `{name}`은(는) 변수 라이브러리에 저장할 수 없습니다: 문자나 `_`로 시작하고 공백이나 `-`, `_`, `.` 이외의 기호가 없도록 이름을 바꾸세요 @msg {k} has control characters {k}에 제어 문자가 있습니다 @@ -7399,6 +7421,7 @@ breakText Glyphs 글리프 @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 Image Trace finished, but its document was reverted: trace it again 이미지 추적이 끝났지만 문서가 되돌려졌습니다: 다시 추적하세요 @msg Import SVG Filter reads SVG files, not SVGZ SVG 필터 가져오기는 SVGZ가 아닌 SVG 파일을 읽습니다 @msg Invalid dimension offset 잘못된 치수 오프셋 @msg Invalid point 잘못된 점 @@ -7572,6 +7595,7 @@ breakText Glyphs 글리프 @msg `names` must be an array of style names `names`은(는) 스타일 이름의 배열이어야 합니다 @msg `new` is a design name, or true `new`은(는) 디자인 이름 또는 true입니다 @msg `origin` must be [x, y] in points `origin`은(는) 포인트 단위의 [x, y]여야 합니다 +@msg `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 `axes`은(는) [a, b, c, d]여야 하며, 각 값은 -1000에서 1000 사이이고 a·d - b·c는 0에서 0.001 이상 떨어져야 합니다 @msg `path` must be a folder `path`은(는) 폴더여야 합니다 @msg `path` must be a path object `path`은(는) 패스 개체여야 합니다 @msg `picks` must be an array (got {v}) `picks`은(는) 배열이어야 합니다({v} 입력됨) @@ -7978,7 +8002,7 @@ breakText Glyphs 글리프 @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 composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer는 "singleLine", "everyLine", "standardSingleLine" 또는 "standardEveryLine"이어야 합니다 @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}에는 연결할 열린 패스가 정확히 하나 있어야 합니다 @msg connect needs a path other than the one extended connect에는 연장한 패스가 아닌 다른 패스가 필요합니다 @@ -9173,3 +9197,20 @@ breakText Glyphs 글리프 @msg {what} would print more than {MAX_COPIES_PER_SHEET} copies on a sheet: scale it up {what}은(는) 한 장에 {MAX_COPIES_PER_SHEET}개보다 많이 인쇄됩니다: 크기를 키우세요 @msg {what} would print on more than {MAX_TILES} tiles: scale it down {what}은(는) 타일 {MAX_TILES}개보다 많이 나뉘어 인쇄됩니다: 크기를 줄이세요 @msg {what} {i} out of range {what} {i}이(가) 범위를 벗어났습니다 + Packaging Tools 패키징 도구 + Fold Lines 접는 선 + Make Cut Line 재단선으로 만들기 + Make Crease Line 오시선으로 만들기 + Make Partial Cut Line 하프 컷 선으로 만들기 + Make Perforation Line 미싱선으로 만들기 + Make Fold Line 접는 선으로 만들기 + Role Swatches… 선 종류 견본… + Role Swatches 선 종류 견본 + Role 선 종류 + Cut Line 재단선 + Crease Line 오시선 + Partial Cut Line 하프 컷 선 + Perforation Line 미싱선 + No objects are selected. 선택한 개체가 없습니다. + Open a document to mark its fold lines. 접는 선을 지정하려면 문서를 여세요. + Remove Fold Line Role 선 종류 제거 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 6ea7ac9646..990e369f0f 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -145,6 +145,7 @@ @msg `name` must be the name of a script engine `name` moet de naam van een scriptengine zijn @msg the main script engine is new for each run and is never kept, so it cannot be dropped de hoofdscriptengine is bij elke uitvoering nieuw en wordt nooit bewaard, dus kan hij niet worden verwijderd @msg there is no script engine named {name} er is geen scriptengine met de naam {name} +@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` is alleen voor een uitvoering zonder iemand om te vragen: in de app beantwoordt de persoon elk dialoogvenster @msg Running a script Er wordt een script uitgevoerd @msg Data Recovery can't keep copies in {path}: {e} Gegevensherstel kan geen kopieën bewaren in {path}: {e} @msg Plug-ins can't be loaded from {path}: {e} Plug-ins kunnen niet worden geladen uit {path}: {e} @@ -1476,6 +1477,7 @@ Change Panel Layout Paneelindeling wijzigen Close Panel Paneel sluiten Collapse Panel Group Paneelgroep samenvouwen + Cycle Display Sizes Weergavegrootten doorlopen Move Panel Paneel verplaatsen Group with Groeperen met Resize panels Panelen van formaat wijzigen @@ -1495,6 +1497,8 @@ Reset all Revolve settings to their defaults. Stelt alle draai-instellingen opnieuw in op de standaardwaarden. Drag values or labels. Double-click a value to type. Sleep waarden of labels. Dubbelklik op een waarde om te typen. Drag rings to rotate. Shift snaps to 15°. Sleep de ringen om te roteren. Shift lijnt uit op 15°. + Track cube Rotatiekubus + Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. Sleep een vlak, een rand of de ring om te roteren. Shift roteert om één schermas. Drag the light, or its rings. Shift snaps to 15°. Sleep het licht of de ringen ervan. Shift lijnt uit op 15°. lighting Light Licht Keep visible surfaces only when expanding Alleen zichtbare oppervlakken behouden bij het uitbreiden @@ -2051,6 +2055,8 @@ lighting Light Licht Insert Aki Left Aki links invoegen Insert Aki Right Aki rechts invoegen Tsume Tsume + Adjust Horizontal Diacritic Position Horizontale positie van diakritische tekens aanpassen + Adjust Vertical Diacritic Position Verticale positie van diakritische tekens aanpassen Character Direction Tekenrichting Digits Cijfers Arabic Arabisch @@ -2428,7 +2434,10 @@ digits Malayalam Malayalam Tabular Lining Tabulaire lining Tabular Oldstyle Tabulaire oldstyle Titling Alternates Titelalternatieven - Every-line Composer Compositie per alinea + Middle Eastern & South Asian Single-line Composer Compositie per regel (Midden-Oosten en Zuid-Azië) + Middle Eastern & South Asian Every-line Composer Compositie per alinea (Midden-Oosten en Zuid-Azië) + Standard Single-line Composer Standaardcompositie per regel + Standard Every-line Composer Standaardcompositie per alinea First-line Left Indent Eerste regel links inspringen Hyphenation… Afbreken… Justification… Uitvullen… @@ -2460,7 +2469,6 @@ digits Malayalam Malayalam East Asian Composition Settings Instellingen voor Oost-Aziatische zetting Korean Composition Settings Instellingen voor Koreaanse zetting Select a text object to edit its paragraph attributes. Selecteer een tekstobject om de alineakenmerken ervan te bewerken. - Single-line Composer Compositie per regel Toggle Line Composer Compositiemethode wisselen Space After Paragraph Ruimte na alinea Space Before Paragraph Ruimte voor alinea @@ -3275,6 +3283,7 @@ digits Malayalam Malayalam Show smooth color wheel Vloeiend kleurenwiel tonen Show segmented color wheel Gesegmenteerd kleurenwiel tonen Show color bars Kleurbalken tonen + Find the selected colors in the artwork De geselecteerde kleuren zoeken in de artwork Harmony Rules Harmonieregels Keep this row's colors (exclude) De kleuren van deze rij behouden (uitsluiten) Limit to Library: Beperken tot bibliotheek: @@ -3930,6 +3939,8 @@ theme Appearance Vormgeving Create Graph Diagram maken Graph Data Diagramgegevens Graph Type Diagramtype + Graph Type… Diagramtype… + Graph Data… Diagramgegevens… Graph Options Diagramopties Left Axis Linkeras Right Axis Rechteras @@ -5442,6 +5453,8 @@ imageTrace Outline Contour @msg unknown option `{path}.{k}` onbekende optie `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) onbekende overdruk `{o}` (preserve, simulate of discard) @msg unknown panel `{raw}` onbekend paneel `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` heeft geen weergavegrootten om te doorlopen +@msg the panels are not shown de panelen worden niet getoond @msg unknown preference `{key}` onbekende voorkeur `{key}` @msg Preferences imported. Voorkeuren geïmporteerd. @msg not a preferences file: {e} geen voorkeurenbestand: {e} @@ -5726,6 +5739,7 @@ imageTrace Outline Contour @msg Image Trace failed: {e} Afbeelding traceren is mislukt: {e} @msg Image Trace finished, but its document was closed Afbeelding traceren is voltooid, maar het document ervan is gesloten @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Afbeelding traceren is voltooid, maar de afbeelding of de instellingen ervan zijn intussen gewijzigd: traceer de afbeelding opnieuw +@msg Image Trace finished, but its document was reverted: trace it again Afbeelding traceren is voltooid, maar het document ervan is teruggezet: traceer de afbeelding opnieuw @msg Import SVG Filter reads SVG files, not SVGZ SVG-filter importeren leest SVG-bestanden, geen SVGZ @msg Invalid dimension offset Ongeldige verschuiving van de maatlijn @msg Invalid point Ongeldig punt @@ -5900,6 +5914,7 @@ imageTrace Outline Contour @msg `names` must be an array of style names `names` moet een array van stijlnamen zijn @msg `new` is a design name, or true `new` is de naam van een ontwerp, of true @msg `origin` must be [x, y] in points `origin` moet [x, y] in punten zijn +@msg `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 `axes` moet [a, b, c, d] zijn, elk van -1000 tot 1000, met a·d - b·c minstens 0,001 van 0 af @msg `path` must be a folder `path` moet een map zijn @msg `path` must be a path object `path` moet een padobject zijn @msg `picks` must be an array (got {v}) `picks` moet een array zijn (kreeg {v}) @@ -6308,7 +6323,7 @@ imageTrace Outline Contour @msg column: true floats the whole column and takes no onto, above or below column: true laat de hele kolom zweven en accepteert geen onto, above of below @msg command must be a shape.* command command moet een shape.*-opdracht zijn @msg commands[{i}]: missing `command` commands[{i}]: `command` ontbreekt -@msg composer must be "singleLine" or "everyLine" composer moet "singleLine" of "everyLine" zijn +@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer moet "singleLine", "everyLine", "standardSingleLine" of "standardEveryLine" zijn @msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes samengestelde vormen accepteren paden, samengestelde paden, groepen, samengestelde vormen, tekst, mengsels en omvormingen @msg compound {_1} must contain exactly one open path to join samengesteld object {_1} moet precies één open pad bevatten om te verbinden @msg connect needs a path other than the one extended connect heeft een ander pad nodig dan het pad dat wordt verlengd @@ -8101,6 +8116,7 @@ mark-style Japanese Japans Export Data Sets… Gegevenssets exporteren… Load Variable Library… Variabelenbibliotheek laden… Save Variable Library… Variabelenbibliotheek opslaan… +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml ‘Importeren’ leest een gegevensbronbestand met de extensie .csv, .tsv, .txt of .xml @msg a variable library holds text variables, and the document has none een variabelenbibliotheek bevat tekstvariabelen, en het document heeft er geen @msg variable `{name}` can't be saved in a variable library: rename it to start with a letter or `_`, without spaces or symbols other than `-`, `_` and `.` variabele `{name}` kan niet in een variabelenbibliotheek worden opgeslagen: geef haar een naam die met een letter of `_` begint, zonder spaties of andere symbolen dan `-`, `_` en `.` @msg {k} has control characters {k} bevat stuurtekens @@ -8304,6 +8320,14 @@ swatch Bright Violet Felviolet Color wheel Kleurenwiel First Artboard Eerste tekenbord Last Artboard Laatste tekenbord + Status Bar Show Weergeven in statusbalk + Artboard Name Naam van tekenbord + Current Tool Huidig gereedschap + Date and Time Datum en tijd + Number of Undos Aantal ongedaan gemaakte stappen + Document Color Profile Kleurprofiel van document + Undos Ongedaan maken + Redos Opnieuw uitvoeren Next Artboard Volgende tekenbord Previous Artboard Vorige tekenbord Step up or down Stapsgewijs verhogen of verlagen @@ -9611,3 +9635,20 @@ breakText Glyphs Glyphs @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 + Packaging Tools Verpakkingsgereedschap + Fold Lines Vouwlijnen + Make Cut Line Snijlijn maken + Make Crease Line Rillijn maken + Make Partial Cut Line Halve snijlijn maken + Make Perforation Line Perforatielijn maken + Make Fold Line Vouwlijn maken + Role Swatches… Stalen van lijnsoorten… + Role Swatches Stalen van lijnsoorten + Role Lijnsoort + Cut Line Snijlijn + Crease Line Rillijn + Partial Cut Line Halve snijlijn + Perforation Line Perforatielijn + No objects are selected. Er zijn geen objecten geselecteerd. + Open a document to mark its fold lines. Open een document om de vouwlijnen te markeren. + Remove Fold Line Role Lijnsoort verwijderen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 53b3269f18..647a0c62bd 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -975,6 +975,7 @@ Change Panel Layout Zmień układ paneli Close Panel Zamknij panel Collapse Panel Group Zwiń grupę paneli + Cycle Display Sizes Przełącz rozmiary wyświetlania Move Panel Przesuń panel Group with Grupuj z Resize panels Zmień rozmiar paneli @@ -995,6 +996,8 @@ Step up or down Zwiększ lub zmniejsz o krok Drag values or labels. Double-click a value to type. Przeciągaj wartości lub etykiety. Kliknij dwukrotnie wartość, aby ją wpisać. Drag rings to rotate. Shift snaps to 15°. Przeciągaj pierścienie, aby obracać. Shift przyciąga co 15°. + Track cube Kostka obrotu + Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. Przeciągnij ścianę, krawędź lub pierścień, aby obracać. Shift obraca wokół jednej osi ekranu. Drag the light, or its rings. Shift snaps to 15°. Przeciągaj światło lub jego pierścienie. Shift przyciąga co 15°. lighting Light Światło Keep visible surfaces only when expanding Przy rozszerzaniu zachowaj tylko widoczne powierzchnie @@ -1045,6 +1048,14 @@ lighting Light Światło Previous Artboard Poprzedni obszar kompozycji Next Artboard Następny obszar kompozycji Last Artboard Ostatni obszar kompozycji + Status Bar Show Pokaż na pasku stanu + Artboard Name Nazwa obszaru kompozycji + Current Tool Bieżące narzędzie + Date and Time Data i godzina + Number of Undos Liczba cofnięć + Document Color Profile Profil kolorów dokumentu + Undos Cofnięcia + Redos Ponowienia Graphic Style Options… Opcje stylu graficznego… Symbol Options Opcje symbolu Symbol Options… Opcje symbolu… @@ -1537,6 +1548,8 @@ lighting Light Światło Insert Aki Left Wstaw aki z lewej Insert Aki Right Wstaw aki z prawej Tsume Tsume + Adjust Horizontal Diacritic Position Dostosuj poziome położenie znaków diakrytycznych + Adjust Vertical Diacritic Position Dostosuj pionowe położenie znaków diakrytycznych Character Direction Kierunek znaków Digits Cyfry Arabic Arabskie @@ -2019,7 +2032,8 @@ digits Malayalam Malajalam Tabular Lining Tabelaryczne nowoczesne Tabular Oldstyle Tabelaryczne nautyczne Titling Alternates Alternatywy tytułowe - Every-line Composer Kompozytor wielowierszowy + Middle Eastern & South Asian Every-line Composer Kompozytor wielowierszowy (Bliski Wschód i Azja Południowa) + Standard Every-line Composer Standardowy kompozytor wielowierszowy First-line Left Indent Wcięcie pierwszego wiersza Hyphenation… Dzielenie wyrazów… Words Longer Than: Wyrazy dłuższe niż: @@ -2059,7 +2073,8 @@ digits Malayalam Malajalam East Asian Composition Settings Ustawienia składu wschodnioazjatyckiego Korean Composition Settings Ustawienia składu koreańskiego Select a text object to edit its paragraph attributes. Zaznacz obiekt tekstowy, aby edytować atrybuty akapitu. - Single-line Composer Kompozytor jednowierszowy + Middle Eastern & South Asian Single-line Composer Kompozytor jednowierszowy (Bliski Wschód i Azja Południowa) + Standard Single-line Composer Standardowy kompozytor jednowierszowy Toggle Line Composer Przełącz kompozytor wierszy Space After Paragraph Odstęp po akapicie Space Before Paragraph Odstęp przed akapitem @@ -2884,6 +2899,7 @@ digits Malayalam Malajalam Show smooth color wheel Pokaż płynne koło kolorów Show segmented color wheel Pokaż segmentowe koło kolorów Show color bars Pokaż paski kolorów + Find the selected colors in the artwork Znajdź zaznaczone kolory w kompozycji Keep this row's colors (exclude) Zachowaj kolory tego wiersza (wyklucz) Limit to Library: Ogranicz do biblioteki: Link harmony colors Połącz kolory harmonii @@ -3559,6 +3575,8 @@ theme Appearance Wygląd Create Graph Utwórz wykres Graph Data Dane wykresu Graph Type Typ wykresu + Graph Type… Typ wykresu… + Graph Data… Dane wykresu… Graph Options Opcje wykresu Left Axis Lewa oś Right Axis Prawa oś @@ -5250,6 +5268,8 @@ imageTrace Outline Kontur @msg unknown option `{path}.{k}` nieznana opcja `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) nieznana wartość nadruków `{o}` (preserve, simulate lub discard) @msg unknown panel `{raw}` nieznany panel `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` nie ma rozmiarów wyświetlania do przełączania +@msg the panels are not shown panele nie są wyświetlane @msg panels can't be shown in Presentation Mode w trybie prezentacji nie można wyświetlić paneli @msg unknown preference `{key}` nieznana preferencja `{key}` @msg Preferences imported. Zaimportowano preferencje. @@ -6129,6 +6149,7 @@ mark-style Japanese Japońskie Export Data Sets… Eksportuj zestawy danych… Load Variable Library… Wczytaj bibliotekę zmiennych… Save Variable Library… Zapisz bibliotekę zmiennych… +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml „Importuj” wczytuje plik źródła danych z rozszerzeniem .csv, .tsv, .txt lub .xml @msg a variable library holds text variables, and the document has none biblioteka zmiennych zawiera zmienne tekstowe, a dokument nie ma żadnej @msg variable `{name}` can't be saved in a variable library: rename it to start with a letter or `_`, without spaces or symbols other than `-`, `_` and `.` nie można zapisać zmiennej `{name}` w bibliotece zmiennych: zmień jej nazwę tak, aby zaczynała się literą lub `_`, bez spacji i symboli innych niż `-`, `_` i `.` @msg {k} has control characters {k} zawiera znaki sterujące @@ -7535,6 +7556,7 @@ breakText Glyphs Glify @msg `answer` for this {kind} dialog must be one of: {_1} `answer` dla tego okna dialogowego {kind} musi mieć jedną z wartości: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` zawiera więcej niż {MAX_ANSWERS} odpowiedzi @msg `answers` is larger than 1 MiB `answers` ma rozmiar większy niż 1 MiB +@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` służy tylko do uruchomienia, w którym nie ma kogo zapytać: w aplikacji na każde okno dialogowe odpowiada użytkownik @msg `answers` must be a list of answers `answers` musi być listą odpowiedzi @msg `artboard` must be the index of an artboard of the document `artboard` musi być indeksem obszaru kompozycji dokumentu @msg `artboardsAt` must be [x, y] `artboardsAt` musi mieć postać [x, y] @@ -7567,6 +7589,7 @@ breakText Glyphs Glify @msg `name` must be a name that is not empty `name` musi być niepustą nazwą @msg `name` must not be empty `name` nie może być puste @msg `origin` must be [x, y] in points `origin` musi mieć postać [x, y] w punktach +@msg `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 `axes` musi mieć postać [a, b, c, d], każda wartość od -1000 do 1000, a a·d - b·c musi różnić się od 0 o co najmniej 0,001 @msg `picks` must be an array (got {v}) `picks` musi być tablicą (podano {v}) @msg `picks` must hold 1 to {MAX_PICKS} picks (got {_1}) `picks` musi zawierać od 1 do {MAX_PICKS} wskazań (podano {_1}) @msg `points` must hold from 2 to 100000 points `points` musi zawierać od 2 do 100000 punktów @@ -7942,6 +7965,7 @@ breakText Glyphs Glify @msg Image Trace failed: {e} Obrys obrazu nie powiódł się: {e} @msg Image Trace finished, but its document was closed Obrys obrazu został ukończony, ale jego dokument został zamknięty @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Obrys obrazu został ukończony, ale obraz lub jego ustawienia zmieniły się w międzyczasie: obrysuj go ponownie +@msg Image Trace finished, but its document was reverted: trace it again Obrys obrazu został ukończony, ale jego dokument został przywrócony: obrysuj go ponownie @msg Join: a subpath went missing Połącz: brakuje ścieżki podrzędnej @msg Lock Workspace is not available in VectorCraft Polecenie Zablokuj obszar roboczy nie jest dostępne w programie VectorCraft @msg Move Panel to New Window is not available: floating panels stay in the main window Polecenie Przenieś panel do nowego okna nie jest dostępne: panele pływające pozostają w oknie głównym @@ -8354,7 +8378,7 @@ breakText Glyphs Glify @msg column: true floats the whole column and takes no onto, above or below column: true odłącza całą kolumnę i nie przyjmuje onto, above ani below @msg command must be a shape.* command command musi być poleceniem shape.* @msg commands[{i}]: missing `command` commands[{i}]: brak `command` -@msg composer must be "singleLine" or "everyLine" composer musi mieć wartość "singleLine" lub "everyLine" +@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer musi mieć wartość "singleLine", "everyLine", "standardSingleLine" lub "standardEveryLine" @msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes kształty złożone przyjmują ścieżki, ścieżki złożone, grupy, kształty złożone, tekst, przejścia i koperty @msg compound {_1} must contain exactly one open path to join obiekt złożony {_1} musi zawierać dokładnie jedną otwartą ścieżkę do połączenia @msg connect needs a path other than the one extended connect wymaga ścieżki innej niż przedłużana @@ -9431,3 +9455,20 @@ breakText Glyphs Glify @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ść + Packaging Tools Narzędzia do opakowań + Fold Lines Linie zgięcia + Make Cut Line Utwórz linię cięcia + Make Crease Line Utwórz linię bigowania + Make Partial Cut Line Utwórz linię nacięcia + Make Perforation Line Utwórz linię perforacji + Make Fold Line Utwórz linię zgięcia + Role Swatches… Próbki rodzajów linii… + Role Swatches Próbki rodzajów linii + Role Rodzaj linii + Cut Line Linia cięcia + Crease Line Linia bigowania + Partial Cut Line Linia nacięcia + Perforation Line Linia perforacji + No objects are selected. Nie zaznaczono żadnych obiektów. + Open a document to mark its fold lines. Otwórz dokument, aby oznaczyć jego linie zgięcia. + Remove Fold Line Role Usuń rodzaj linii diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index c1ac7fcc1a..2c0817772d 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -966,7 +966,8 @@ antiAlias Sharp Nítido Every (minutes) A cada (minutos) Every option is at its default. Todas as opções estão no padrão. Every option matches {base}. Todas as opções correspondem a {base}. - Every-line Composer Compositor de Todas as Linhas + Middle Eastern & South Asian Every-line Composer Compositor de Todas as Linhas (Oriente Médio e Sul da Ásia) + Standard Every-line Composer Compositor Padrão de Todas as Linhas Exact dash lengths Comprimentos de tracejado exatos Exceptions (comma separated) Exceções (separadas por vírgula) Exclude Excluir @@ -1041,6 +1042,7 @@ antiAlias Sharp Nítido Export Data Sets… Exportar Conjuntos de Dados… Load Variable Library… Carregar Biblioteca de Variáveis… Save Variable Library… Salvar Biblioteca de Variáveis… +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml "Importar" lê um arquivo de fonte de dados com extensão .csv, .tsv, .txt ou .xml @msg a variable library holds text variables, and the document has none uma biblioteca de variáveis contém variáveis de texto, e o documento não tem nenhuma @msg variable `{name}` can't be saved in a variable library: rename it to start with a letter or `_`, without spaces or symbols other than `-`, `_` and `.` a variável `{name}` não pode ser salva em uma biblioteca de variáveis: renomeie-a para começar com uma letra ou `_`, sem espaços nem símbolos além de `-`, `_` e `.` @msg data set `{name}` holds a control character, which a variable library can't hold o conjunto de dados `{name}` contém um caractere de controle, que uma biblioteca de variáveis não pode conter @@ -1258,6 +1260,14 @@ antiAlias Sharp Nítido Previous Artboard Mesa de trabalho anterior Next Artboard Próxima mesa de trabalho Last Artboard Última mesa de trabalho + Status Bar Show Mostrar na barra de status + Artboard Name Nome da prancheta + Current Tool Ferramenta atual + Date and Time Data e hora + Number of Undos Número de ações desfeitas + Document Color Profile Perfil de cor do documento + Undos Desfazer + Redos Refazer Gradient Gradiente Gradient Fill: click to apply, drag onto art Preenchimento de Gradiente: clique para aplicar, arraste sobre a arte Gradient Finishes Finalizações de Gradiente @@ -1325,6 +1335,7 @@ antiAlias Sharp Nítido Show smooth color wheel Mostrar roda de cores contínua Show segmented color wheel Mostrar roda de cores segmentada Show color bars Mostrar barras de cores + Find the selected colors in the artwork Localizar as cores selecionadas na arte Harmony Sets Conjuntos de Harmonia Height Altura Height: Altura: @@ -2243,6 +2254,8 @@ antiAlias Sharp Nítido Insert Aki Left Inserir Aki à Esquerda Insert Aki Right Inserir Aki à Direita Tsume Tsume + Adjust Horizontal Diacritic Position Ajustar Posição Horizontal dos Diacríticos + Adjust Vertical Diacritic Position Ajustar Posição Vertical dos Diacríticos Character Direction Direção de Caracteres Digits Dígitos Arabic Arábicos @@ -2890,7 +2903,8 @@ digits Malayalam Malaiala Single Left Quotation Mark Aspa Esquerda Única Single Quotes: Aspas Simples: Single Right Quotation Mark Aspa Direita Única - Single-line Composer Compositor de Linha Única + Middle Eastern & South Asian Single-line Composer Compositor de Linha Única (Oriente Médio e Sul da Ásia) + Standard Single-line Composer Compositor Padrão de Linha Única Toggle Line Composer Alternar Compositor de Linhas Sixth Space Espaço de Sexto Size Tamanho @@ -3534,6 +3548,7 @@ imageTrace Outline Contorno Change Panel Layout Alterar Layout dos Painéis Close Panel Fechar Painel Collapse Panel Group Recolher Grupo de Painéis + Cycle Display Sizes Alternar Tamanhos de Exibição Move Panel Mover Painel Group with Agrupar com Resize panels Redimensionar painéis @@ -3554,6 +3569,8 @@ imageTrace Outline Contorno Step up or down Aumentar ou diminuir um passo Drag values or labels. Double-click a value to type. Arraste os valores ou rótulos. Clique duas vezes em um valor para digitá-lo. Drag rings to rotate. Shift snaps to 15°. Arraste os anéis para girar. Shift ajusta em incrementos de 15°. + Track cube Cubo de rotação + Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. Arraste uma face, uma aresta ou o anel para girar. Shift gira em torno de um eixo da tela. Drag the light, or its rings. Shift snaps to 15°. Arraste a luz ou seus anéis. Shift ajusta em incrementos de 15°. lighting Light Luz Keep visible surfaces only when expanding Manter apenas as superfícies visíveis ao expandir @@ -4480,6 +4497,8 @@ axis Both Ambos @msg unknown option `{path}.{k}` opção desconhecida `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) sobreimpressões desconhecidas `{o}` (preserve, simulate ou discard) @msg unknown panel `{raw}` painel desconhecido `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` não tem tamanhos de exibição para alternar +@msg the panels are not shown os painéis não estão sendo exibidos @msg panels can't be shown in Presentation Mode os painéis não podem ser mostrados no Modo de Apresentação @msg unknown preference `{key}` preferência desconhecida `{key}` @msg Preferences imported. Preferências importadas. @@ -4978,6 +4997,8 @@ axis Both Ambos Gradient (. or Shift+.) Gradiente (. ou Shift+.) Graph Data Dados do Gráfico Graph Type Tipo de Gráfico + Graph Type… Tipo de Gráfico… + Graph Data… Dados do Gráfico… Graph Options Opções do Gráfico Left Axis Eixo Esquerdo Right Axis Eixo Direito @@ -7866,6 +7887,7 @@ swatch Yellow Green Verde-amarelado @msg Image Trace failed: {e} O Rastreamento de Imagem falhou: {e} @msg Image Trace finished, but its document was closed O Rastreamento de Imagem terminou, mas o documento dele foi fechado @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again O Rastreamento de Imagem terminou, mas a imagem ou as configurações dela mudaram nesse meio-tempo: rastreie-a novamente +@msg Image Trace finished, but its document was reverted: trace it again O Rastreamento de Imagem terminou, mas o documento dele foi revertido: rastreie-a novamente @msg Import SVG Filter reads SVG files, not SVGZ Importar Filtro SVG lê arquivos SVG, não SVGZ @msg Invalid dimension offset Deslocamento de cota inválido @msg Invalid point Ponto inválido @@ -7913,6 +7935,7 @@ swatch Yellow Green Verde-amarelado @msg `answer` for this {kind} dialog must be one of: {_1} `answer` para esta caixa de diálogo {kind} deve ser um de: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` tem mais de {MAX_ANSWERS} respostas @msg `answers` is larger than 1 MiB `answers` tem mais de 1 MiB +@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` é só para uma execução sem ninguém a quem perguntar: no app, a pessoa responde a cada caixa de diálogo @msg `answers` must be a list of answers `answers` deve ser uma lista de respostas @msg `artboard` must be the index of an artboard of the document `artboard` deve ser o índice de uma prancheta do documento @msg `artboardsAt` must be [x, y] `artboardsAt` deve ser [x, y] @@ -8039,6 +8062,7 @@ swatch Yellow Green Verde-amarelado @msg `names` must be an array of style names `names` deve ser uma matriz de nomes de estilos @msg `new` is a design name, or true `new` é o nome de um projeto, ou true @msg `origin` must be [x, y] in points `origin` deve ser [x, y] em pontos +@msg `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 `axes` deve ser [a, b, c, d], cada um de -1000 a 1000, com a·d - b·c a pelo menos 0.001 de 0 @msg `path` must be a folder `path` deve ser uma pasta @msg `path` must be a path object `path` deve ser um objeto de caminho @msg `picks` must be an array (got {v}) `picks` deve ser uma matriz (recebido {v}) @@ -8444,7 +8468,7 @@ swatch Yellow Green Verde-amarelado @msg column: true floats the whole column and takes no onto, above or below column: true torna flutuante a coluna inteira e não aceita onto, above nem below @msg command must be a shape.* command command deve ser um comando shape.* @msg commands[{i}]: missing `command` commands[{i}]: falta `command` -@msg composer must be "singleLine" or "everyLine" composer deve ser "singleLine" ou "everyLine" +@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer deve ser "singleLine", "everyLine", "standardSingleLine" ou "standardEveryLine" @msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes formas compostas aceitam caminhos, caminhos compostos, grupos, formas compostas, texto, mesclagens e envelopes @msg compound {_1} must contain exactly one open path to join o composto {_1} deve conter exatamente um caminho aberto para unir @msg connect needs a path other than the one extended connect precisa de um caminho diferente do que foi estendido @@ -9649,3 +9673,20 @@ swatch Yellow Green Verde-amarelado Nest Shapes… Aninhar formas… Nest Shapes Aninhar formas Roll Rolo + Packaging Tools Ferramentas de Embalagem + Fold Lines Linhas de Dobra + Make Cut Line Transformar em Linha de Corte + Make Crease Line Transformar em Linha de Vinco + Make Partial Cut Line Transformar em Linha de Meio-Corte + Make Perforation Line Transformar em Linha de Perfuração + Make Fold Line Transformar em Linha de Dobra + Role Swatches… Amostras dos Tipos de Linha… + Role Swatches Amostras dos Tipos de Linha + Role Tipo de Linha + Cut Line Linha de Corte + Crease Line Linha de Vinco + Partial Cut Line Linha de Meio-Corte + Perforation Line Linha de Perfuração + No objects are selected. Nenhum objeto selecionado. + Open a document to mark its fold lines. Abra um documento para marcar suas linhas de dobra. + Remove Fold Line Role Remover Tipo de Linha diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index aeb5caed12..28db02bb34 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1075,7 +1075,10 @@ font-technology Variable Вариативные Every (minutes) Каждые (минут) Every option is at its default. Все параметры имеют значения по умолчанию. Every option matches {base}. Все параметры совпадают с {base}. - Every-line Composer Компоновщик всех строк + Middle Eastern & South Asian Single-line Composer Однострочный компоновщик (Ближний Восток и Южная Азия) + Middle Eastern & South Asian Every-line Composer Компоновщик всех строк (Ближний Восток и Южная Азия) + Standard Single-line Composer Стандартный однострочный компоновщик + Standard Every-line Composer Стандартный компоновщик всех строк Exact dash lengths Точная длина штрихов Exceptions (comma separated) Исключения (через запятую) Exclude Исключить @@ -1412,6 +1415,14 @@ file-filter Templates Шаблоны Previous Artboard Предыдущая монтажная область Next Artboard Следующая монтажная область Last Artboard Последняя монтажная область + Status Bar Show Показ в строке состояния + Artboard Name Имя монтажной области + Current Tool Текущий инструмент + Date and Time Дата и время + Number of Undos Число отмен + Document Color Profile Цветовой профиль документа + Undos Отмены + Redos Повторы Go To Link Перейти по ссылке GPL palettes keep solid colours only, as RGB. Палитры GPL сохраняют только сплошные цвета в RGB. GPU Performance Производительность GPU @@ -1431,6 +1442,8 @@ file-filter Templates Шаблоны Graph Диаграмма Graph Data Данные диаграммы Graph Type Тип диаграммы + Graph Type… Тип диаграммы… + Graph Data… Данные диаграммы… Graph Options Параметры диаграммы Left Axis Левая ось Right Axis Правая ось @@ -1546,6 +1559,7 @@ file-filter Templates Шаблоны Show smooth color wheel Показать плавный цветовой круг Show segmented color wheel Показать сегментированный цветовой круг Show color bars Показать цветовые полосы + Find the selected colors in the artwork Найти выбранные цвета в рисунке Harmony Sets Наборы гармонии Height Высота Height: Высота: @@ -2743,6 +2757,8 @@ mark-style Japanese Японский Insert Aki Left Вставить аки слева Insert Aki Right Вставить аки справа Tsume Цумэ + Adjust Horizontal Diacritic Position Настроить горизонтальное положение диакритических знаков + Adjust Vertical Diacritic Position Настроить вертикальное положение диакритических знаков Character Direction Направление символов Digits Цифры Arabic Арабские @@ -3485,7 +3501,6 @@ digits Malayalam Малаялам Single Left Quotation Mark Одинарная открывающая кавычка Single Quotes: Одинарные кавычки: Single Right Quotation Mark Одинарная закрывающая кавычка - Single-line Composer Однострочный компоновщик Toggle Line Composer Переключить компоновщик строк Sixth Space Шестая шпация Size Размер @@ -4519,6 +4534,17 @@ axis Both Оба @msg `name` must be the name of a script engine `name` должно быть именем движка скриптов @msg the main script engine is new for each run and is never kept, so it cannot be dropped основной движок скриптов создаётся заново для каждого запуска и никогда не сохраняется, поэтому его нельзя удалить @msg there is no script engine named {name} движка скриптов с именем {name} нет +@msg `answers` must be a list of answers `answers` должен быть списком ответов +@msg `answers` has more than {MAX_ANSWERS} answers в `answers` больше {MAX_ANSWERS} ответов +@msg `answers` is larger than 1 MiB `answers` больше 1 МиБ +@msg must be an object with `kind` and `value` должен быть объектом с `kind` и `value` +@msg must have exactly `kind` and `value` должен содержать ровно `kind` и `value` +@msg is an alert's answer, whose `value` must be "ok" является ответом на alert, поэтому его `value` должно быть "ok" +@msg is a confirm's answer, whose `value` must be true or false является ответом на confirm, поэтому его `value` должно быть true или false +@msg is longer than 16 KiB длиннее 16 КиБ +@msg is a prompt's answer, whose `value` must be a string or null является ответом на prompt, поэтому его `value` должно быть строкой или null +@msg must have `kind` alert, confirm or prompt должен иметь `kind` alert, confirm или prompt +@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` предназначен только для запуска, в котором некого спросить: в приложении человек сам отвечает на каждое диалоговое окно @msg Running a script Выполняется скрипт @msg Copied the script report Отчёт о сценарии скопирован @msg Copied the link info Сведения о связи скопированы @@ -5148,6 +5174,8 @@ axis Both Оба @msg unknown option `{path}.{k}` неизвестный параметр `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) неизвестные наложения `{o}` (preserve, simulate или discard) @msg unknown panel `{raw}` неизвестная панель `{raw}` +@msg `{panel}` has no display sizes to cycle у панели `{panel}` нет размеров отображения для переключения +@msg the panels are not shown панели не показаны @msg panels can't be shown in Presentation Mode в режиме презентации панели показать нельзя @msg unknown preference `{key}` неизвестная настройка `{key}` @msg Preferences imported. Настройки импортированы. @@ -5525,6 +5553,7 @@ axis Both Оба Change Panel Layout Изменить расположение панелей Close Panel Закрыть панель Collapse Panel Group Свернуть группу панелей + Cycle Display Sizes Переключить размеры отображения Move Panel Переместить панель Group with Сгруппировать с Resize panels Изменить размер панелей @@ -5570,6 +5599,8 @@ axis Both Оба Step up or down Шаг вверх или вниз Drag values or labels. Double-click a value to type. Перетаскивайте значения или подписи. Для ввода дважды щёлкните значение. Drag rings to rotate. Shift snaps to 15°. Перетаскивайте кольца для вращения. Shift задаёт шаг 15°. + Track cube Куб вращения + Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. Перетащите грань, ребро или кольцо для вращения. Shift вращает вокруг одной оси экрана. Drag the light, or its rings. Shift snaps to 15°. Перетаскивайте источник света или кольца. Shift задаёт шаг 15°. lighting Light Свет Keep visible surfaces only when expanding При разборе сохранять только видимые поверхности @@ -5882,6 +5913,7 @@ lighting Light Свет Export Data Sets… Экспортировать наборы данных… Load Variable Library… Загрузить библиотеку переменных… Save Variable Library… Сохранить библиотеку переменных… +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml «Импорт» читает файл источника данных с расширением .csv, .tsv, .txt или .xml @msg a variable library holds text variables, and the document has none библиотека переменных содержит текстовые переменные, а в документе их нет @msg variable `{name}` can't be saved in a variable library: rename it to start with a letter or `_`, without spaces or symbols other than `-`, `_` and `.` переменную `{name}` нельзя сохранить в библиотеке переменных: переименуйте её так, чтобы имя начиналось с буквы или `_` и не содержало пробелов и символов, кроме `-`, `_` и `.` @msg {k} has control characters {k} содержит управляющие символы @@ -6165,6 +6197,7 @@ axis Y Axis Ось Y @msg {what} points outside memory {what} указывает за пределы памяти @msg `angle` must be a number `angle` должно быть числом @msg `aspect` must be from 0.01 to 100 `aspect` должно быть от 0.01 до 100 +@msg `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 `axes` должно быть [a, b, c, d], каждое от -1000 до 1000, а a·d - b·c должно отличаться от 0 не менее чем на 0.001 @msg `cap` must be "butt", "round" or "square" `cap` должно быть "butt", "round" или "square" @msg `fillRule` must be "nonzero" or "evenodd" `fillRule` должно быть "nonzero" или "evenodd" @msg `helpUrl` must be an https:// address of at most {MAX_HELP_URL} bytes `helpUrl` должно быть адресом https:// длиной не более {MAX_HELP_URL} байт @@ -7828,9 +7861,6 @@ shape Open Открытый @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 `answer` for this {kind} dialog must be one of: {_1} `answer` для этого диалогового окна {kind} должно быть одним из: {_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` must be a list of artboard indices `artboards` должно быть списком индексов монтажных областей @@ -8574,10 +8604,6 @@ shape Open Открытый @msg invalid t недопустимое t @msg invalid time value недопустимое значение времени @msg invalid tolerance недопустимый допуск -@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} байт @@ -8705,9 +8731,6 @@ shape Open Открытый @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 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` # Messages that begin with a lowercase word, n to s. @msg name (a toolbar's name) is required требуется name (имя панели инструментов) @msg name (a toolbar's name) must be a string name (имя панели инструментов) должно быть строкой @@ -9673,4 +9696,22 @@ shape Open Открытый @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 пикселей по стороне): уменьшите разрешение + Packaging Tools Инструменты упаковки + Fold Lines Линии сгиба + Make Cut Line Сделать линией реза + Make Crease Line Сделать линией биговки + Make Partial Cut Line Сделать линией надреза + Make Perforation Line Сделать линией перфорации + Make Fold Line Сделать линией сгиба + Role Swatches… Образцы типов линий… + Role Swatches Образцы типов линий + Role Тип линии + Cut Line Линия реза + Crease Line Линия биговки + Partial Cut Line Линия надреза + Perforation Line Линия перфорации + No objects are selected. Объекты не выделены. + Open a document to mark its fold lines. Откройте документ, чтобы отметить его линии сгиба. + Remove Fold Line Role Убрать тип линии @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} пикселей — слишком большой размер для PSD (не более {MAX_SIDE} пикселей по стороне): уменьшите разрешение +@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer должен быть "singleLine", "everyLine", "standardSingleLine" или "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index d00172e6a0..2f19e59397 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1056,7 +1056,8 @@ font-technology Variable Variabla Every (minutes) Intervall (minuter) Every option is at its default. Alla alternativ har standardvärden. Every option matches {base}. Alla alternativ matchar {base}. - Every-line Composer Flerradssättning + Middle Eastern & South Asian Every-line Composer Flerradssättning (Mellanöstern och Sydasien) + Standard Every-line Composer Standard-flerradssättning Exact dash lengths Exakta strecklängder Exceptions (comma separated) Undantag (kommaavgränsade) Exclude Uteslut @@ -1361,6 +1362,14 @@ font-technology Variable Variabla Previous Artboard Föregående rityta Next Artboard Nästa rityta Last Artboard Sista ritytan + Status Bar Show Visa i statusfältet + Artboard Name Ritytans namn + Current Tool Aktuellt verktyg + Date and Time Datum och tid + Number of Undos Antal ångringar + Document Color Profile Dokumentets färgprofil + Undos Ångringar + Redos Gör om Go To Link Gå till länk GPL palettes keep solid colours only, as RGB. GPL-paletter sparar bara enfärgade färger, som RGB. GPU Performance GPU-prestanda @@ -1380,6 +1389,8 @@ font-technology Variable Variabla Graph Diagram Graph Data Diagramdata Graph Type Diagramtyp + Graph Type… Diagramtyp… + Graph Data… Diagramdata… Graph Options Diagramalternativ Left Axis Vänster axel Right Axis Höger axel @@ -1495,6 +1506,7 @@ font-technology Variable Variabla Show smooth color wheel Visa steglöst färghjul Show segmented color wheel Visa segmenterat färghjul Show color bars Visa färgstaplar + Find the selected colors in the artwork Hitta de markerade färgerna i teckningen Harmony Sets Harmoniuppsättningar Height Höjd Height: Höjd: @@ -2651,6 +2663,8 @@ font-technology Variable Variabla Insert Aki Left Infoga aki till vänster Insert Aki Right Infoga aki till höger Tsume Tsume + Adjust Horizontal Diacritic Position Justera vågrät position för diakritiska tecken + Adjust Vertical Diacritic Position Justera lodrät position för diakritiska tecken Character Direction Teckenriktning Digits Siffror Arabic Arabiska @@ -3375,7 +3389,8 @@ digits Malayalam Malayalam Single Left Quotation Mark Enkelt vänster citattecken Single Quotes: Enkla citattecken: Single Right Quotation Mark Enkelt höger citattecken - Single-line Composer Enradssättare + Middle Eastern & South Asian Single-line Composer Enradssättare (Mellanöstern och Sydasien) + Standard Single-line Composer Standard-enradssättare Toggle Line Composer Växla radsättare Sixth Space Sjättedelsblanksteg Size Storlek @@ -4392,6 +4407,18 @@ axis Both Båda @msg `name` must be the name of a script engine `name` måste vara namnet på en skriptmotor @msg the main script engine is new for each run and is never kept, so it cannot be dropped huvudskriptmotorn är ny för varje körning och sparas aldrig, så den kan inte tas bort @msg there is no script engine named {name} det finns ingen skriptmotor med namnet {name} +@msg `answers` must be a list of answers `answers` måste vara en lista med svar +@msg `answers` has more than {MAX_ANSWERS} answers `answers` har fler än {MAX_ANSWERS} svar +@msg `answers` is larger than 1 MiB `answers` är större än 1 MiB +@msg `answers[{i}]` {e} `answers[{i}]` {e} +@msg must be an object with `kind` and `value` måste vara ett objekt med `kind` och `value` +@msg must have exactly `kind` and `value` måste ha exakt `kind` och `value` +@msg is an alert's answer, whose `value` must be "ok" är svaret på en alert, vars `value` måste vara "ok" +@msg is a confirm's answer, whose `value` must be true or false är svaret på en confirm, vars `value` måste vara true eller false +@msg is longer than 16 KiB är längre än 16 KiB +@msg is a prompt's answer, whose `value` must be a string or null är svaret på en prompt, vars `value` måste vara en sträng eller null +@msg must have `kind` alert, confirm or prompt måste ha `kind` alert, confirm eller prompt +@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` är bara för en körning utan någon att fråga: i appen svarar personen på varje dialogruta @msg Running a script Kör ett skript @msg Copied the script report Kopierade skriptrapporten @msg Copied the link info Kopierade länkinfo @@ -5002,6 +5029,8 @@ axis Both Båda @msg unknown option `{path}.{k}` okänt alternativ `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) okänt värde för övertryck `{o}` (preserve, simulate eller discard) @msg unknown panel `{raw}` okänd panel `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` har inga visningsstorlekar att växla mellan +@msg the panels are not shown panelerna visas inte @msg panels can't be shown in Presentation Mode paneler kan inte visas i presentationsläge @msg unknown preference `{key}` okänd inställning `{key}` @msg Preferences imported. Inställningarna har importerats. @@ -5393,6 +5422,7 @@ effect Soft Mjuk Change Panel Layout Ändra panellayout Close Panel Stäng panel Collapse Panel Group Komprimera panelgrupp + Cycle Display Sizes Växla visningsstorlekar Move Panel Flytta panel Group with Gruppera med Resize panels Ändra storlek på paneler @@ -5434,6 +5464,8 @@ effect Soft Mjuk Step up or down Ett steg upp eller ned Drag values or labels. Double-click a value to type. Dra i värden eller etiketter. Dubbelklicka på ett värde för att skriva. Drag rings to rotate. Shift snaps to 15°. Dra i ringarna för att rotera. Shift fäster i steg om 15°. + Track cube Rotationskub + Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. Dra i en sida, en kant eller ringen för att rotera. Shift roterar runt en skärmaxel. Drag the light, or its rings. Shift snaps to 15°. Dra i ljuset eller dess ringar. Shift fäster i steg om 15°. Keep visible surfaces only when expanding Behåll endast synliga ytor vid expandering Trim covered geometry on Expand Appearance. Live preview keeps the full surface. Transparent paints and surfaces exceeding visibility limits retain all faces. Trimma dold geometri vid Expandera utseende. Live-förhandsgranskningen behåller hela ytan. Transparenta färger och ytor som överskrider synlighetsgränserna behåller alla sidoytor. @@ -6127,6 +6159,7 @@ theme Appearance Utseende Export Data Sets… Exportera datauppsättningar… Load Variable Library… Läs in variabelbibliotek… Save Variable Library… Spara variabelbibliotek… +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml ”Importera” läser en datakällfil med filändelsen .csv, .tsv, .txt eller .xml @msg a variable library holds text variables, and the document has none ett variabelbibliotek innehåller textvariabler, och dokumentet har inga @msg variable `{name}` can't be saved in a variable library: rename it to start with a letter or `_`, without spaces or symbols other than `-`, `_` and `.` variabeln `{name}` kan inte sparas i ett variabelbibliotek: byt namn på den så att den börjar med en bokstav eller `_`, utan mellanslag eller andra symboler än `-`, `_` och `.` @msg data set `{name}` holds a control character, which a variable library can't hold datauppsättningen `{name}` innehåller ett kontrolltecken, som ett variabelbibliotek inte kan innehålla @@ -6533,6 +6566,7 @@ axis Y Axis Y-axel @msg needs approval: it asks for {0}, which the user grants when installing it on its own kräver godkännande: det begär {0}, som användaren beviljar när pluginet installeras för sig @msg `angle` must be a number `angle` måste vara ett tal @msg `aspect` must be from 0.01 to 100 `aspect` måste vara från 0.01 till 100 +@msg `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 `axes` måste vara [a, b, c, d], vart och ett från -1000 till 1000, med a·d - b·c minst 0.001 från 0 @msg `cap` must be "butt", "round" or "square" `cap` måste vara "butt", "round" eller "square" @msg `fillRule` must be "nonzero" or "evenodd" `fillRule` måste vara "nonzero" eller "evenodd" @msg `helpUrl` must be an https:// address of at most {MAX_HELP_URL} bytes `helpUrl` måste vara en https://-adress på högst {MAX_HELP_URL} byte @@ -8011,7 +8045,7 @@ digits Hindi Hindi @msg column: true floats the whole column and takes no onto, above or below column: true gör hela kolumnen flytande och tar inte onto, above eller below @msg command must be a shape.* command command måste vara ett shape.*-kommando @msg commands[{i}]: missing `command` commands[{i}]: `command` saknas -@msg composer must be "singleLine" or "everyLine" composer måste vara "singleLine" eller "everyLine" +@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer måste vara "singleLine", "everyLine", "standardSingleLine" eller "standardEveryLine" @msg compound {_1} must contain exactly one open path to join sammansatt {_1} måste innehålla exakt en öppen bana att foga samman @msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes sammansatta former tar banor, sammansatta banor, grupper, sammansatta former, text, övergångar och kuvert @msg connect end must be "start" or "end" connect end måste vara "start" eller "end" @@ -8204,6 +8238,7 @@ digits Hindi Hindi @msg Image Trace failed: internal error: its thread stopped (please report this bug) Bildkalkering misslyckades: internt fel: dess tråd stoppades (rapportera gärna felet) @msg Image Trace finished, but its document was closed Bildkalkeringen är klar, men dess dokument har stängts @msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Bildkalkeringen är klar, men bilden eller dess inställningar ändrades under tiden: vektorisera den igen +@msg Image Trace finished, but its document was reverted: trace it again Bildkalkeringen är klar, men dess dokument har återgått till sparad version: vektorisera den igen @msg imageMap `{m}`: none, client or server imageMap `{m}`: none, client eller server @msg index out of range index utanför intervallet @msg instances must be 1..1000 instances måste vara 1..1000 @@ -8988,6 +9023,8 @@ digits Hindi Hindi Not Aligned to Pixel Grid Inte justerade mot pixelrutnät @msg only paths and compound paths can be aligned to the pixel grid bara banor och sammansatta banor kan justeras mot pixelrutnätet @msg side is left or right, not `{s}` side är left eller right, inte `{s}` +@msg side is left or right, not `{v}` side är left eller right, inte `{v}` +@msg order is a whole number from 0 to {others}, not `{v}` order är ett heltal från 0 till {others}, inte `{v}` Ignore All Ignorera alla Add to Dictionary Lägg till i ordlistan No Suggestions Inga förslag @@ -9236,4 +9273,21 @@ digits Hindi Hindi @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 + Packaging Tools Förpackningsverktyg + Fold Lines Falslinjer + Make Cut Line Gör till skärlinje + Make Crease Line Gör till biglinje + Make Partial Cut Line Gör till halvskärlinje + Make Perforation Line Gör till perforeringslinje + Make Fold Line Gör till falslinje + Role Swatches… Färgrutor för linjetyper… + Role Swatches Färgrutor för linjetyper + Role Linjetyp + Cut Line Skärlinje + Crease Line Biglinje + Partial Cut Line Halvskärlinje + Perforation Line Perforeringslinje + No objects are selected. Inga objekt är markerade. + Open a document to mark its fold lines. Öppna ett dokument för att markera dess falslinjer. + Remove Fold Line Role Ta bort linjetyp @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 da7d80282e..0659a076a5 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -2381,6 +2381,26 @@ fn a_repeated_placeholder_matches_the_same_text() { assert!(c.message("alert: the next answer is for prompt, not confirm").is_none()); } +/// Of two templates that start with text, the one with the longer text before its first +/// placeholder matches first, so a row that wraps a message takes it before a row with more text +/// in all whose placeholder would take part of it; a quoted name may still hold a backtick. +#[test] +fn the_longer_leading_text_matches_first() { + let c = Catalog::parse(concat!( + "@msg\t`{key}` must be true or false\tkey {key}\n", + "@msg\t`answers[{i}]` {e}\tanswer {i} {e}\n", + "@msg\tno brush named `{name}`\tbrush {name}\n", + )); + let (form, caps) = c.message("`select` must be true or false").expect("matches"); + assert_eq!((form, caps), ("key {key}", vec![("key", "select")])); + let (form, caps) = c.message("`answers[3]` is a confirm's answer, whose `value` must be true or false").expect("matches"); + assert_eq!((form, caps), ("answer {i} {e}", vec![("i", "3"), ("e", "is a confirm's answer, whose `value` must be true or false")])); + let (form, caps) = c.message("`a`b` must be true or false").expect("matches"); + assert_eq!((form, caps), ("key {key}", vec![("key", "a`b")])); + let (form, caps) = c.message("no brush named `a`b`").expect("matches"); + assert_eq!((form, caps), ("brush {name}", vec![("name", "a`b")])); +} + /// A template that starts with text matches a message it wraps before a template that starts /// with a placeholder, even one with more literal text, so the wrapped reason is translated by /// its own row. @@ -3193,6 +3213,72 @@ fn f(text: &str, n: usize) -> Result { assert!(message_literals_in(&["effects"]).contains("the SVG filter isn't valid XML: {e}")); } +/// The scan reads the message a `.map_err` closure gives with `return`, also from inside an `if` +/// branch or a `let` statement but not from a closure inside it, the last expression after a block +/// statement with no `;`, and the values a `let` statement gives a local that the closure returns, +/// and not those of a local the closure only passes elsewhere or writes into a format string, by +/// name or as a `format!` argument. +#[test] +fn message_scan_reads_returns_and_tails_and_skips_locals() { + let code = r#" +fn f(text: &str) -> Result { + let a = read(text).map_err(|_| { + return "the file cannot be read".to_string(); + })?; + let b = read(text).map_err(|e| { + if e.is_io() { + return format!("the disk failed: {e}"); + } + e.to_string() + })?; + let c = read(text).map_err(|e| { + if e.is_io() { cleanup(); } + format!("the file is cut short: {e}") + })?; + let d = read(text).map_err(|e| { + if e.is_io() { cleanup(); } + let level = if e.is_io() { "warning" } else { "error" }; + log_failure(level, &e); + format!("the file is not a library: {e}") + })?; + let g = read(text).map_err(|e| { + let kind = match e.kind() { + Kind::Gone => return GONE.into(), + _ => { "some other kind" } + }; + format!("the {kind} file is wrong") + })?; + let h = read(text).map_err(|e| { + let name = e.name().unwrap_or_else(|| return "unnamed source"); + let note = e.note().map(move |n| { return "noted source" }); + format!("the source {name} is gone") + })?; + let k = read(text).map_err(|e| { + let why = if e.is_deep() { format!("its objects are nested too deep ({e})") } else { e.to_string() }; + FormatError::NotVectorcraft(why) + })?; + let m = read(text).map_err(|e| { + let level = if e.is_io() { "warning" } else { "error" }; + format!("the file failed with a {}", level) + })?; + Ok(a) +} +"#; + let consts = [("GONE", "the file is gone")].map(|(k, v)| (k.to_string(), vec![v.to_string()])).into(); + let want = [ + "the file cannot be read", + "the disk failed: {e}", + "the file is cut short: {e}", + "the file is not a library: {e}", + "the file is gone", + "the {kind} file is wrong", + "the source {name} is gone", + "its objects are nested too deep ({e})", + "the file failed with a {_1}", + ]; + assert_eq!(source_messages(code, &[], &consts), want); +} + /// The scan reads the messages of an error handler that a `.map_err(name)` names: a closure bound /// to that name, up to its `;`, and a function of that name, each of its statements. #[test] @@ -3616,6 +3702,98 @@ fn wrongly_shaped_plugin_commands_errors_are_translated() { } } +/// The errors of the custom toolbar commands (Window › Toolbars, New Toolbar and Manage Toolbars, +/// `window.toolbar.dock` and `window.toolbar.float`) have an `@msg` row in every complete-message +/// catalog, and the status bar shows each one in the interface language with the toolbar's name, +/// the key and the values given kept; the error the command returns stays English. +#[test] +fn custom_toolbar_command_errors_are_translated() { + use serde_json::json; + let scanned = message_literals(); + let templates = [ + "toolbar (a toolbar's name) must be a string", + "no toolbar named `{name}`", + "toolbar name can't be empty", + "a toolbar name has at most {MAX_NAME} characters", + "there is already a toolbar named `{name}`", + "there is already a toolbar named `{to}`", + "a workspace keeps at most {MAX} toolbars", + "name (a toolbar's name) must be a string", + "name (a toolbar's name) is required", + "to (the new name) is required", + "name must be a toolbar's name", + "side is left or right, not `{s}`", + "side is left or right, not `{v}`", + "order is a whole number from 0 to {others}, not `{v}`", + "no dialog open", + "`{key}` must be true or false", + "x and y must both be numbers", + ]; + for template in templates { + assert!(scanned.contains(template), "the scan lists {template}"); + } + let mut missing = vec![]; + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + let (entries, _) = parse_entries(lang.0.source); + let rows: std::collections::BTreeSet<&str> = entries.iter().filter(|(ctx, _, _)| ctx == "@msg").map(|(_, src, _)| src.as_str()).collect(); + missing.extend(templates.iter().filter(|t| !rows.contains(*t)).map(|t| format!("{code}: {t}"))); + } + assert!(missing.is_empty(), "{} toolbar errors have no @msg row:\n{}", missing.len(), missing.join("\n")); + + let mut app = crate::VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + for name in ["Mine", "Pens"] { + app.run("window.toolbar.new", json!({ "name": name })).unwrap(); + } + app.run("window.toolbar.dock", json!({"name": "Pens", "side": "left"})).unwrap(); + let cases = [ + ("window.toolbar.new", json!({"name": 5}), "name (a toolbar's name) must be a string", vec![]), + ("window.toolbar.new", json!({"name": " "}), "toolbar name can't be empty", vec![]), + ("window.toolbar.new", json!({"name": "x".repeat(201)}), "a toolbar name has at most 200 characters", vec!["200"]), + ("window.toolbar.new", json!({"name": "Mine"}), "there is already a toolbar named `Mine`", vec!["`Mine`"]), + ("window.toolbar.rename", json!({"name": "Mine", "to": "Pens"}), "there is already a toolbar named `Pens`", vec!["`Pens`"]), + ("window.toolbar.rename", json!({"name": "Mine"}), "to (the new name) is required", vec![]), + ("window.toolbar.custom", json!({}), "name (a toolbar's name) is required", vec![]), + ("window.toolbar.custom", json!({"name": "Nope"}), "no toolbar named `Nope`", vec!["`Nope`"]), + ("window.toolbar.custom", json!({"name": "Mine", "show": "yes"}), "`show` must be true or false", vec!["`show`"]), + ("window.toolbar.duplicate", json!({"name": 3}), "name must be a toolbar's name", vec![]), + ("toolbar.addTool", json!({"tool": "pen", "toolbar": 5}), "toolbar (a toolbar's name) must be a string", vec![]), + ("window.toolbar.dock", json!({"name": "Mine", "side": "up"}), "side is left or right, not `up`", vec!["`up`"]), + ("window.toolbar.dock", json!({"name": "Mine", "side": 3}), "side is left or right, not `3`", vec!["`3`"]), + ( + "window.toolbar.dock", + json!({"name": "Mine", "side": "left", "order": 9}), + "order is a whole number from 0 to 1, not `9`", + vec!["1", "`9`"], + ), + ("window.toolbar.float", json!({"name": "Mine", "x": "a", "y": 1}), "x and y must both be numbers", vec![]), + ]; + let mut errors: Vec<(String, Vec<&str>)> = vec![]; + for (id, params, want, kept) in cases { + let e = app.run(id, params.clone()).unwrap_err(); + assert_eq!(e, want, "{id} {params}"); + errors.push((e, kept)); + } + // New Toolbar's OK with no dialog open, and a workspace that holds as many toolbars as it keeps. + errors.push((crate::custom_toolbars::confirm(&mut app).unwrap_err(), vec![])); + for i in app.ui.custom_toolbars.len()..crate::custom_toolbars::MAX { + app.run("window.toolbar.new", json!({ "name": format!("T{i}") })).unwrap(); + } + for (id, params) in [("window.toolbar.new", json!({"name": "Extra"})), ("window.toolbar.duplicate", json!({"name": "Mine"}))] { + let e = app.run(id, params).unwrap_err(); + assert_eq!(e, "a workspace keeps at most 64 toolbars", "{id}"); + errors.push((e, vec!["64"])); + } + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + for (e, kept) in &errors { + let shown = message(lang, e); + assert_ne!(shown, *e, "{code}: shown in English"); + assert!(kept.iter().all(|k| shown.contains(k)), "{code}: {e} -> {shown}"); + } + } +} + /// The warnings of an Image Trace with keepColors, which the status bar shows and the scan above /// doesn't read, are translated in each language of [`COMPLETE_MESSAGES`], with the colors kept. #[test] @@ -3727,6 +3905,96 @@ fn dataset_import_repeated_column_error_is_translated() { } } +/// The scan reads the refusals `script.run`'s `param(msg)` gives, and not the arguments of a type's +/// own function of that name. +#[test] +fn message_scan_reads_script_run_param_refusals() { + let code = r#" +fn f(p: &Value) -> Result<()> { + let grays = Grays::param(C, p)?; + let pick = Pick::param(p, C)?; + let _ = cmd::bad(C, "the name is too long"); + Err(param("`path` is empty")) +} +"#; + let engine: Vec<_> = ERROR_HELPERS.iter().filter(|(c, _, _)| *c == "engine").map(|&(_, call, before)| (call, before)).collect(); + let consts = [("C".to_string(), vec!["view.proofSetup".to_string()])].into(); + assert_eq!(source_messages(code, &engine, &consts), ["the name is too long", "`path` is empty"]); +} + +/// `script.run`'s refusals of `answers`, the list's own, an answer's at its index and the refusal +/// of `answers` in the app, are translated in every language that translates every message, with +/// the index, the counts and the code names kept. The command's error stays in English. +#[test] +fn script_answers_errors_are_translated() { + use serde_json::{Value, json}; + use vectorcraft_engine::{EngineError, Session}; + let reasons = [ + "must be an object with `kind` and `value`", + "must have exactly `kind` and `value`", + "is an alert's answer, whose `value` must be \"ok\"", + "is a confirm's answer, whose `value` must be true or false", + "is longer than 16 KiB", + "is a prompt's answer, whose `value` must be a string or null", + "must have `kind` alert, confirm or prompt", + ]; + let in_app = "`answers` is only for a run with nobody to ask: in the app, the person answers each dialog"; + let lists = ["`answers` must be a list of answers", "`answers` has more than {MAX_ANSWERS} answers", "`answers` is larger than 1 MiB"]; + let scanned = message_literals(); + for template in reasons.into_iter().chain(lists).chain(["`answers[{i}]` {e}", in_app]) { + assert!(scanned.contains(template), "{template}"); + } + let ok = json!({"kind": "alert", "value": "ok"}); + let wrong = [ + json!(1), + json!({"kind": "alert"}), + json!({"kind": "alert", "value": "yes"}), + json!({"kind": "confirm", "value": "yes"}), + json!({"kind": "prompt", "value": "x".repeat(16 * 1024 + 1)}), + json!({"kind": "prompt", "value": 1}), + json!({"kind": "beep", "value": 1}), + ]; + let run = |s: &mut Session, answers: Value| s.execute("script.run", &json!({"source": "1", "answers": answers})).unwrap_err(); + let mut s = Session::new(); + // Each error, with the English message the command gives and the reason an answer's holds. + let mut errors = vec![]; + for (reason, answer) in reasons.into_iter().zip(wrong) { + for at in [3, 9_999] { + let mut list = vec![ok.clone(); at]; + list.push(answer.clone()); + errors.push((run(&mut s, json!(list)), format!("`answers[{at}]` {reason}"), Some(reason))); + } + } + errors.push((run(&mut s, json!("ok")), lists[0].to_string(), None)); + errors.push((run(&mut s, json!(vec![ok.clone(); 10_001])), "`answers` has more than 10000 answers".to_string(), None)); + let long = json!({"kind": "prompt", "value": "x".repeat(16 * 1024)}); + errors.push((run(&mut s, json!(vec![long; 70])), lists[2].to_string(), None)); + s.script_frames = true; + errors.push((run(&mut s, json!([ok])), in_app.to_string(), None)); + for (e, want, reason) in &errors { + assert!(matches!(e, EngineError::BadParams { cmd, msg } if cmd == "script.run" && msg == want), "{e}"); + let line = e.to_string(); + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + let shown = message(lang, &line); + let inner = message(lang, want); + assert_ne!(inner, *want, "{code}"); + assert!(shown.contains(&inner) && !shown.contains("invalid parameters"), "{code}: {shown}"); + if let Some(reason) = reason { + let translated = message(lang, reason); + assert_ne!(translated, *reason, "{code}"); + assert!(inner.contains(&translated), "{code}: {inner}"); + } + let numbers: Vec<&str> = want.split(|c: char| !c.is_ascii_digit()).filter(|n| !n.is_empty()).collect(); + let names = ["`answers", "`kind`", "`value`", "true", "false", "null"]; + assert!(numbers.iter().chain(&names).all(|n| !want.contains(n) || shown.contains(n)), "{code}: {shown}"); + if want.ends_with("alert, confirm or prompt") { + assert!(["alert", "confirm", "prompt"].iter().all(|k| shown.contains(k)), "{code}: {shown}"); + } + } + } +} + /// The errors of a command's parameter schema are translated in every language that translates /// every message, with the parameter's path and the refused value kept. #[test] @@ -3913,7 +4181,8 @@ fn bracketed_message_parts_translate_only_as_exact_messages() { let point = message(lang, "[x, y] (two numbers)"); assert_ne!(point, "[x, y] (two numbers)", "{code}"); assert!(point.contains("[x, y]"), "{code}: {point}"); - for got in ["[1]", "[1, 2, 3]", r#"{"objects": [1]}"#, r#"[{"a": 1}, "b: c", …"#] { + // ``["] `x`: b"]`` fits the text of the effect refusal ``[{j}] `{_1}`: {why}`` but not its index. + for got in ["[1]", "[1, 2, 3]", r#"{"objects": [1]}"#, r#"[{"a": 1}, "b: c", …"#, r#"["] `x`: b"]"#] { let shown = message(lang, &format!("`center` must be [x, y] (two numbers), not {got}")); assert!(shown.contains(&point) && shown.contains(got), "{code}: {shown}"); let shown = message(lang, &format!("`p` must be an object, not {got}")); @@ -3922,6 +4191,42 @@ fn bracketed_message_parts_translate_only_as_exact_messages() { } } +/// An effect refusal inside another message (`plug-in output: …`, and an importer's `can't open …`) +/// is translated through its template with its reason, keeping the index and the effect id. +#[test] +fn nested_effect_refusals_translate_with_their_reason() { + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + let refusal = "[0] `fx`: nothing selected"; + let output = format!("plug-in output: objects[0].effects: {refusal}"); + for shown in [message(lang, refusal), message(lang, &output), message(lang, &format!("can't open `a.svg`: {output}"))] { + assert!(!shown.contains("nothing selected") && shown.contains("[0] `fx`"), "{code}: {shown}"); + } + } + let de = de(); + let refusal = "[0] `fx`: `radius` must be a number"; + assert_eq!(message(de, refusal), "[0] `fx`: `radius` muss eine Zahl sein"); + let output = format!("plug-in output: objects[0].effects: {refusal}"); + assert_eq!(message(de, &output), "Plug-in-Ausgabe: objects[0].effects: [0] `fx`: `radius` muss eine Zahl sein"); + assert_eq!( + message(de, &format!("can't open `a.svg`: {output}")), + "`a.svg` kann nicht geöffnet werden: Plug-in-Ausgabe: objects[0].effects: [0] `fx`: `radius` muss eine Zahl sein" + ); + assert_eq!( + message(de, "plug-in output: objects[12].effects: [3] `fx`: no row for this reason"), + "Plug-in-Ausgabe: objects[12].effects: [3] `fx`: no row for this reason" + ); + let selected = "[1] `fx`: nothing selected"; + assert_eq!( + message(de, &format!("plug-in output: objects[0].effects: {selected}")), + "Plug-in-Ausgabe: objects[0].effects: [1] `fx`: nichts ausgewählt" + ); + // Past the depth limit the refusal stays as it is. + let deep = format!("plug-in output: plug-in output: plug-in output: plug-in output: objects[0].effects: {selected}"); + let shown = message(de, &deep); + assert!(shown.ends_with(selected), "{shown}"); +} + /// The warning for a PDF/X file that leaves out the document's bleed is translated in every catalog, /// alone and in the status bar's note. #[test] @@ -4593,14 +4898,15 @@ const MESSAGE_MARKERS: &[&str] = &[".status(", "ui.status = ", "status = ", "Oth /// message: the engine's `bad(cmd, msg)` (`EngineError::BadParams`), `err(msg)` (`cmd/fileio`) /// and `error(msg)` (`cmd/dimension.rs`), the script host's `fail(msg)` (`script/files.rs`, /// `script/dollar.rs`) and `value(msg)`, which gives the messages the script `File` object's own -/// code throws (`script/files.rs`), and `.over(limit)` for a limit a run passes (`script/mod.rs`), -/// the PDF writer's `bad(why)` (`forms.rs`) and `failed(why)` (`encrypt.rs`, `linearize.rs`), the +/// code throws (`script/files.rs`), `.over(limit)` for a limit a run passes (`script/mod.rs`) and +/// `param(msg)` for `script.run`'s parameters (`cmd/scripts.rs`), the PDF writer's `bad(why)` (`forms.rs`) and `failed(why)` (`encrypt.rs`, `linearize.rs`), the /// plug-in host's `bad(what)` (a parameter's spec and dialog keys), `wrong(what)` (a parameter's /// value), `out_err(at, msg)` (plug-in output), `in_range(x, lo, hi, at, what)` and /// `unit(x, at, what)` (a painted effect's numbers) and `.read_packed(packed, what, max)` (the block /// a plug-in returned), and the script interpreter's methods that throw an error at a script: /// `.type_error(msg)`, `.throw(kind, msg)` and the XPath evaluator's `.error(msg)`. A helper that -/// starts with `.` is a method of any receiver. +/// starts with `.` is a method of any receiver; any other is a function, not a type's own function +/// of the same name (`Grays::param(C, p)`). const ERROR_HELPERS: &[(&str, &str, usize)] = &[ ("engine", "bad(", 1), ("engine", "err(", 0), @@ -4608,6 +4914,7 @@ const ERROR_HELPERS: &[(&str, &str, usize)] = &[ ("engine", "fail(", 0), ("engine", "value(", 0), ("engine", ".over(", 0), + ("engine", "param(", 0), ("pdf", "bad(", 0), ("pdf", "failed(", 0), ("plugins", "bad(", 0), @@ -4790,6 +5097,10 @@ fn source_messages(code: &str, helpers: &[(&str, usize)], consts: &std::collecti let in_helpers = helpers.iter().flat_map(|&(call, before)| { code.match_indices(call) .filter(|&(at, _)| call.starts_with('.') || !code[..at].ends_with(|c: char| c.is_alphanumeric() || c == '_' || c == '.')) + .filter(|&(at, _)| { + let owner = code[..at].strip_suffix("::").map(|p| p.rsplit(|c: char| !c.is_alphanumeric() && c != '_').next().unwrap_or("")); + !owner.is_some_and(|o| o.starts_with(|c: char| c.is_ascii_uppercase())) + }) // `format!(` given as a helper, and an `error(` helper that is an `#[error(…)]` attribute, take a format string. .filter_map(move |(at, _)| { skip_args(&code[at + call.len()..], before).map(|rest| (rest, call == "format!(" || code[..at].ends_with("#["))) @@ -4903,27 +5214,72 @@ fn statement(code: &str) -> &str { /// Where each value a closure can return starts, `body` being the text after its parameters: the /// body itself, each block or `if`/`else` branch in it (`{ ACB_CUT_SHORT.into() }`, not the -/// `{` of a `json!({…})` value), each `match` arm (`=>`) and each statement after a `;` (the -/// last expression of a block or a function body), up to the bracket that closes the call the -/// closure is given to or the function. +/// `{` of a `json!({…})` value), each `match` arm (`=>`), each statement after a `;` or after a +/// block statement's `}` (the last expression of a block or a function body) and the value of +/// each `return`, up to the bracket that closes the call the closure is given to or the function. +/// The blocks, arms and statements inside a `let` statement give a local its value, so they count +/// only when the local's name is used, outside a string literal and a `format!`, in a value the closure returns +/// (`let why = if … { format!("…") } else { … }; Error(why)`), and not when the local only goes +/// elsewhere (`let level = if … { "warning" } else { "error" }; log(level);`). A `return` counts +/// wherever it is, except inside a closure the body holds (`unwrap_or_else(|| return …)`). fn closure_returns(body: &str) -> Vec<&str> { - let mut out = vec![body]; - let (mut depth, mut chars) = (0usize, body.char_indices()); + let ident = |c: char| c.is_alphanumeric() || c == '_'; + // The name a `let` statement starting at `at` binds (empty for a pattern), if it is one. + let let_at = |at: usize| { + let rest = body[at..].trim_start().strip_prefix("let").filter(|r| r.starts_with(char::is_whitespace))?.trim_start(); + let rest = rest.strip_prefix("mut ").map_or(rest, str::trim_start); + Some(&rest[..rest.find(|c: char| !ident(c)).unwrap_or(rest.len())]) + }; + // Each place a value starts, with the `let` whose local it gives a value to, if any, and + // whether a `return` gives it. + let mut found: Vec<(&str, Option<&str>, bool)> = vec![(body, None, false)]; + // For each open bracket, the `quiet` and `in_let` of the text around it: `quiet` names the + // `let` that a value inside the bracket belongs to, `in_let` the `let` the statement is. + let mut outer = vec![]; + let (mut quiet, mut in_let, mut chars) = (None, let_at(0), body.char_indices()); + // Where the innermost closure in the body that a `return` would leave ends. + let mut inner_closure_end = 0; while let Some((at, c)) = chars.next() { match c { - '(' | '[' => depth += 1, - '{' => { - depth += 1; - if !body[..at].trim_end().ends_with('(') { - out.push(&body[at + 1..]); + '|' if at >= inner_closure_end => { + let before = body[..at].trim_end(); + let after_operator = before.ends_with(['(', ',', '=']) && !["==", "!=", "<=", ">="].iter().any(|op| before.ends_with(op)); + let opens = after_operator || (before.ends_with("move") && !before[..before.len() - 4].ends_with(ident)); + let params_end = if body[at + 1..].starts_with('|') { Some(at + 1) } else { body[at + 1..].find('|').map(|end| at + 1 + end) }; + if let Some(params_end) = params_end.filter(|_| opens) { + inner_closure_end = params_end + 1 + statement(&body[params_end + 1..]).len(); } } - ')' | ']' | '}' => match depth.checked_sub(1) { - Some(d) => depth = d, - None => break, - }, - ';' => out.push(&body[at + 1..]), - '=' if body[at + 1..].starts_with('>') => out.push(&body[at + 2..]), + '(' | '[' | '{' => { + outer.push((quiet, in_let)); + if c == '{' && !body[..at].trim_end().ends_with('(') { + found.push((&body[at + 1..], quiet.or(in_let), false)); + } + quiet = quiet.or(in_let); + in_let = if c == '{' { let_at(at + 1) } else { None }; + } + ')' | ']' | '}' => { + let Some(around) = outer.pop() else { break }; + (quiet, in_let) = around; + if c == '}' { + found.push((&body[at + 1..], quiet.or(in_let), false)); + if in_let.is_none() { + in_let = let_at(at + 1); + } + } + } + ';' => { + found.push((&body[at + 1..], quiet, false)); + in_let = let_at(at + 1); + } + '=' if body[at + 1..].starts_with('>') => found.push((&body[at + 2..], quiet.or(in_let), false)), + 'r' if at >= inner_closure_end + && body[at..].starts_with("return") + && !body[..at].ends_with(ident) + && !body[at + "return".len()..].starts_with(ident) => + { + found.push((&body[at + "return".len()..], None, true)); + } '"' => loop { match chars.next() { Some((_, '\\')) => { @@ -4936,6 +5292,69 @@ fn closure_returns(body: &str) -> Vec<&str> { _ => {} } } + // The values the closure returns: each `return`, and each expression that ends its block + // rather than a `;` (a block's start, which spans the whole block, aside). + let returned: Vec = found + .iter() + .filter(|&&(start, held, by_return)| { + let tail = !start.trim_start().starts_with('{') && !start[statement(start).len()..].starts_with(';'); + held.is_none() && (by_return || tail) + }) + .map(|(start, ..)| without_format_args(&without_strings(statement(start)))) + .collect(); + let used = |name: &str| !name.is_empty() && returned.iter().any(|value| holds_ascii_word(value, name)); + found.into_iter().filter(|&(_, held, _)| held.is_none_or(used)).map(|(start, ..)| start).collect() +} + +/// `code`, its string literals already emptied, with the arguments of each `format!(…)` removed: +/// a value written into a format string is part of a message, not one of its own. +fn without_format_args(code: &str) -> String { + let (mut out, mut rest) = (String::new(), code); + while let Some(at) = rest.find("format!(") { + out.push_str(&rest[..at + "format!(".len()]); + rest = &rest[at + "format!(".len()..]; + let mut depth = 0usize; + let end = rest.char_indices().find_map(|(i, c)| match c { + '(' | '[' | '{' => { + depth += 1; + None + } + ')' | ']' | '}' => match depth.checked_sub(1) { + Some(d) => { + depth = d; + None + } + None => Some(i), + }, + _ => None, + }); + rest = &rest[end.unwrap_or(rest.len())..]; + } + out.push_str(rest); + out +} + +/// `code` with the text of its string literals removed, the quotes kept. +fn without_strings(code: &str) -> String { + let (mut out, mut chars) = (String::new(), code.chars()); + while let Some(c) = chars.next() { + out.push(c); + if c == '"' { + loop { + match chars.next() { + Some('\\') => { + chars.next(); + } + Some('"') => { + out.push('"'); + break; + } + Some(_) => {} + None => break, + } + } + } + } out } diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 9a811ad35a..7639c326cb 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1048,7 +1048,10 @@ font-technology Variable Değişken Every (minutes) Her (dakika) Every option is at its default. Her seçenek varsayılan değerdedir. Every option matches {base}. Her seçenek {base} ile eşleşir. - Every-line Composer Her Satır Bestecisi + Middle Eastern & South Asian Single-line Composer Tek Satır Oluşturucu (Orta Doğu ve Güney Asya) + Middle Eastern & South Asian Every-line Composer Her Satır Bestecisi (Orta Doğu ve Güney Asya) + Standard Single-line Composer Standart Tek Satır Oluşturucu + Standard Every-line Composer Standart Her Satır Bestecisi Exact dash lengths Tam çizgi uzunlukları Exceptions (comma separated) İstisnalar (virgülle ayrılmış) Exclude Hariç tut @@ -1354,6 +1357,8 @@ font-technology Variable Değişken Graph Grafik Graph Data Grafik Verileri Graph Type Grafik Türü + Graph Type… Grafik Türü… + Graph Data… Grafik Verileri… Graph Options Grafik Seçenekleri Left Axis Sol Eksen Right Axis Sağ Eksen @@ -1458,6 +1463,7 @@ font-technology Variable Değişken Show smooth color wheel Kesintisiz renk tekerleğini göster Show segmented color wheel Bölümlü renk tekerleğini göster Show color bars Renk çubuklarını göster + Find the selected colors in the artwork Seçili renkleri resimde bul Harmony Sets Armoni Setleri Height Yükseklik Height: Yükseklik: @@ -2498,6 +2504,8 @@ shape Open Açık Insert Aki Left Sola Aki Ekle Insert Aki Right Sağa Aki Ekle Tsume Tsume + Adjust Horizontal Diacritic Position Yatay Aksan İşareti Konumunu Ayarla + Adjust Vertical Diacritic Position Dikey Aksan İşareti Konumunu Ayarla Digits Rakamlar Arabic Arapça Hindi Hintçe @@ -3251,7 +3259,6 @@ digits Malayalam Malayalam Single Left Quotation Mark Tek Sol Tırnak İşareti Single Quotes: Tek Alıntılar: Single Right Quotation Mark Tek Sağ Tırnak İşareti - Single-line Composer Tek Satır Oluşturucu Toggle Line Composer Satır Oluşturucuyu Değiştir Sixth Space Altıncı Uzay Size Boyut @@ -4255,6 +4262,7 @@ axis Both Her İkisi @msg `name` must be the name of a script engine `name` bir betik motorunun adı olmalıdır @msg the main script engine is new for each run and is never kept, so it cannot be dropped ana betik motoru her çalıştırmada yenidir ve hiç saklanmaz, bu yüzden bırakılamaz @msg there is no script engine named {name} {name} adlı bir betik motoru yok +@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` yalnızca sorulacak kimsenin olmadığı bir çalıştırma içindir: uygulamada her iletişim kutusunu kişi yanıtlar @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ı @@ -4873,6 +4881,8 @@ axis Both Her İkisi @msg unknown option `{path}.{k}` bilinmeyen seçenek `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) bilinmeyen üst baskılar `{o}` (preserve, simulate veya discard) @msg unknown panel `{raw}` bilinmeyen panel `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` panelinde geçiş yapılacak görüntü boyutu yok +@msg the panels are not shown paneller gösterilmiyor @msg panels can't be shown in Presentation Mode Sunum Modunda paneller gösterilemez @msg unknown preference `{key}` bilinmeyen tercih `{key}` @msg Preferences imported. Tercihler içe aktarıldı. @@ -5325,6 +5335,8 @@ effect Soft Yumuşak Reset all Revolve settings to their defaults. Tüm Revolve ayarlarını varsayılan değerlerine sıfırlayın. Drag values or labels. Double-click a value to type. Değerleri veya etiketleri sürükleyin. Yazmak için bir değeri çift tıklayın. Drag rings to rotate. Shift snaps to 15°. Döndürmek için halkaları sürükleyin. Kaydırma 15°'ye sabitlenir. + Track cube Döndürme küpü + Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. Döndürmek için bir yüzü, kenarı veya halkayı sürükleyin. Shift tek bir ekran ekseni etrafında döndürür. Drag the light, or its rings. Shift snaps to 15°. Işığı veya halkalarını sürükleyin. Kaydırma 15°'ye sabitlenir. Keep visible surfaces only when expanding Görünür yüzeyleri yalnızca genişletirken koruyun Trim covered geometry on Expand Appearance. Live preview keeps the full surface. Transparent paints and surfaces exceeding visibility limits retain all faces. Görünümü Genişlet'te kapsanan geometriyi kırpın. Canlı önizleme tüm yüzeyi korur. Şeffaf boyalar ve görünürlük sınırlarını aşan yüzeyler tüm yüzleri korur. @@ -6134,6 +6146,14 @@ theme Appearance Görünüm JavaScript: JavaScript: Large Gaps Büyük Boşluklar Last Artboard Son Çalışma Yüzeyi + Status Bar Show Durum Çubuğunda Göster + Artboard Name Çalışma Yüzeyi Adı + Current Tool Geçerli Araç + Date and Time Tarih ve Saat + Number of Undos Geri Alma Sayısı + Document Color Profile Belge Renk Profili + Undos Geri Al + Redos Yinele Levels Düzeyler Library Panel Options Kütüphane Paneli Seçenekleri Link JavaScript Files… JavaScript Dosyalarını Bağla… @@ -6380,6 +6400,7 @@ theme Appearance Görünüm Kashidas Keşide Load Variable Library… Değişken Kitaplığı Yükle… Save Variable Library… Değişken Kitaplığını Kaydet… +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml "İthalat" uzantısı .csv, .tsv, .txt veya .xml olan bir veri kaynağı dosyasını okur @msg a variable library holds text variables, and the document has none değişken kitaplığı metin değişkenleri içerir ve belgede hiç metin değişkeni yok @msg variable `{name}` can't be saved in a variable library: rename it to start with a letter or `_`, without spaces or symbols other than `-`, `_` and `.` `{name}` değişkeni değişken kitaplığına kaydedilemiyor: adını bir harf veya `_` ile başlayacak, boşluk ya da `-`, `_` ve `.` dışında simge içermeyecek şekilde değiştirin @msg {k} has control characters {k} denetim karakterleri içeriyor @@ -6476,6 +6497,7 @@ theme Appearance Görünüm @msg a new document refuses this file because of these variables: {names} yeni bir belge bu değişkenler nedeniyle bu dosyayı reddeder: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them `{name}` için `{header}` başlığı `{other}` değişkeni olarak okunur: birini yeniden adlandırın Collapse Panel Group Panel Grubunu Daralt + Cycle Display Sizes Görüntü Boyutları Arasında Geçiş Yap @msg panel is not in a dock group panel bir yuva grubunda değil @msg only a dock group above or below others collapses, not one beside another yalnızca diğerlerinin üstünde veya altındaki bir yuva grubu daraltılabilir, yanındaki değil @msg icon must be true or false icon true veya false olmalı @@ -6915,6 +6937,7 @@ axis Y Axis Y ekseni @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 `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 `axes` [a, b, c, d] olmalıdır; her biri -1000 ile 1000 arasında, a·d - b·c ise 0'dan en az 0.001 uzakta 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 @@ -7283,6 +7306,7 @@ axis Y Axis Y ekseni @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 Image Trace finished, but its document was reverted: trace it again Görüntü İzleme tamamlandı, ancak belgesi geri döndürüldü: 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 @@ -7697,7 +7721,7 @@ axis Y Axis Y ekseni @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 composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer "singleLine", "everyLine", "standardSingleLine" veya "standardEveryLine" 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 @@ -9532,3 +9556,20 @@ breakText Glyphs Glifler Nest Shapes… Şekilleri yerleştir… Nest Shapes Şekilleri yerleştir Roll Rulo + Packaging Tools Ambalaj Araçları + Fold Lines Katlama Çizgileri + Make Cut Line Kesim Çizgisi Yap + Make Crease Line Pilyaj Çizgisi Yap + Make Partial Cut Line Yarım Kesim Çizgisi Yap + Make Perforation Line Perforaj Çizgisi Yap + Make Fold Line Katlama Çizgisi Yap + Role Swatches… Çizgi Türü Renk Örnekleri… + Role Swatches Çizgi Türü Renk Örnekleri + Role Çizgi türü + Cut Line Kesim çizgisi + Crease Line Pilyaj çizgisi + Partial Cut Line Yarım kesim çizgisi + Perforation Line Perforaj çizgisi + No objects are selected. Hiçbir nesne seçili değil. + Open a document to mark its fold lines. Katlama çizgilerini işaretlemek için bir belgeyi açın. + Remove Fold Line Role Çizgi Türünü Kaldır diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 45f0f0fd26..b95631a14b 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1080,7 +1080,8 @@ font-technology Variable Варіативні Every (minutes) Кожен (хвилин) Every option is at its default. Усі параметри мають значення за промовчанням. Every option matches {base}. Усі параметри збігаються з {base}. - Every-line Composer Компонувальник всіх рядків + Middle Eastern & South Asian Every-line Composer Компонувальник всіх рядків (Близький Схід і Південна Азія) + Standard Every-line Composer Стандартний компонувальник всіх рядків Exact dash lengths Точна довжина штрихів Exceptions (comma separated) Винятки (через кому) Exclude Виключити @@ -1417,6 +1418,14 @@ file-filter Templates Шаблони Previous Artboard Попередня монтажна область Next Artboard Наступна монтажна область Last Artboard Остання монтажна область + Status Bar Show Показ у рядку стану + Artboard Name Назва монтажної області + Current Tool Поточний інструмент + Date and Time Дата й час + Number of Undos Кількість скасувань + Document Color Profile Колірний профіль документа + Undos Скасування + Redos Повтори Go To Link Перейти за посиланням GPL palettes keep solid colours only, as RGB. Палітри GPL зберігають лише суцільні кольори RGB. GPU Performance Продуктивність GPU @@ -1436,6 +1445,8 @@ file-filter Templates Шаблони Graph Діаграма Graph Data Дані діаграми Graph Type Тип діаграми + Graph Type… Тип діаграми… + Graph Data… Дані діаграми… Graph Options Параметри діаграми Left Axis Ліва вісь Right Axis Права вісь @@ -1551,6 +1562,7 @@ file-filter Templates Шаблони Show smooth color wheel Показати плавне колірне коло Show segmented color wheel Показати сегментоване колірне коло Show color bars Показати колірні смуги + Find the selected colors in the artwork Знайти вибрані кольори в малюнку Harmony Sets Набори гармонії Height Висота Height: Висота: @@ -2748,6 +2760,8 @@ mark-style Japanese Японський Insert Aki Left Вставити акі ліворуч Insert Aki Right Вставити акі праворуч Tsume Цуме + Adjust Horizontal Diacritic Position Налаштувати горизонтальне положення діакритичних знаків + Adjust Vertical Diacritic Position Налаштувати вертикальне положення діакритичних знаків Character Direction Напрямок символів Digits Цифри Arabic Арабські @@ -3490,7 +3504,8 @@ digits Malayalam Малаялам Single Left Quotation Mark Одинарна лапка, що відкриває Single Quotes: Одинарні лапки: Single Right Quotation Mark Одинарна лапка, що закриває - Single-line Composer Однорядковий компонувальник + Middle Eastern & South Asian Single-line Composer Однорядковий компонувальник (Близький Схід і Південна Азія) + Standard Single-line Composer Стандартний однорядковий компонувальник Toggle Line Composer Переключити компонувальник рядків Sixth Space Шоста шпація Size Розмір @@ -5145,6 +5160,8 @@ axis Both Обидві @msg unknown option `{path}.{k}` невідомий параметр `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) невідомі накладення `{o}` (preserve, simulate або discard) @msg unknown panel `{raw}` невідома панель `{raw}` +@msg `{panel}` has no display sizes to cycle панель `{panel}` не має розмірів відображення для перемикання +@msg the panels are not shown панелі не показано @msg panels can't be shown in Presentation Mode у режимі презентації панелі показати не можна @msg unknown preference `{key}` невідоме налаштування `{key}` @msg Preferences imported. Налаштування імпортовано. @@ -5520,6 +5537,7 @@ axis Both Обидві Change Panel Layout Змінити розташування панелей Close Panel Закрити панель Collapse Panel Group Згорнути групу панелей + Cycle Display Sizes Перемкнути розміри відображення Move Panel Перемістити панель Group with Згрупувати з Resize panels Змінити розмір панелей @@ -5563,6 +5581,8 @@ axis Both Обидві Step up or down Крок угору або вниз Drag values or labels. Double-click a value to type. Перетягуйте значення або підписи. Двічі клацніть значення, щоб увести його. Drag rings to rotate. Shift snaps to 15°. Перетягуйте кільця для обертання. Shift задає крок 15°. + Track cube Куб обертання + Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. Перетягніть грань, ребро або кільце для обертання. Shift обертає навколо однієї осі екрана. Drag the light, or its rings. Shift snaps to 15°. Перетягуйте джерело світла або його кільця. Shift задає крок 15°. Keep visible surfaces only when expanding Під час розгортання зберігати лише видимі поверхні Trim covered geometry on Expand Appearance. Live preview keeps the full surface. Transparent paints and surfaces exceeding visibility limits retain all faces. Обрізає приховану геометрію під час розгортання оформлення. Попередній перегляд зберігає всю поверхню. Прозорі заливки та поверхні, що перевищують обмеження видимості, зберігають усі грані. @@ -5875,6 +5895,7 @@ lighting Light Світло Export Data Sets… Експортувати набори даних… Load Variable Library… Завантажити бібліотеку змінних… Save Variable Library… Зберегти бібліотеку змінних… +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml «Імпорт» читає файл джерела даних із розширенням .csv, .tsv, .txt або .xml @msg a variable library holds text variables, and the document has none бібліотека змінних містить текстові змінні, а в документі їх немає @msg variable `{name}` can't be saved in a variable library: rename it to start with a letter or `_`, without spaces or symbols other than `-`, `_` and `.` змінну `{name}` не можна зберегти в бібліотеці змінних: перейменуйте її так, щоб ім’я починалося з літери або `_` і не містило пробілів і символів, крім `-`, `_` і `.` @msg {k} has control characters {k} містить керівні символи @@ -7410,6 +7431,7 @@ breakText Glyphs Гліфи @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 Image Trace finished, but its document was reverted: trace it again Трасування зображення завершено, але його документ було повернуто до збереженої версії: виконайте трасування ще раз @msg Import SVG Filter reads SVG files, not SVGZ Імпорт фільтра SVG читає файли SVG, а не SVGZ @msg Invalid dimension offset Неприпустиме зміщення розміру @msg Invalid point Неприпустима точка @@ -7456,6 +7478,7 @@ breakText Glyphs Гліфи @msg `answer` for this {kind} dialog must be one of: {_1} `answer` для цього діалогового вікна ({kind}) має бути одним з: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` містить понад {MAX_ANSWERS} відповідей @msg `answers` is larger than 1 MiB `answers` більший за 1 МіБ +@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` призначений лише для запуску, у якому немає кого запитати: у застосунку людина сама відповідає на кожне діалогове вікно @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] @@ -7581,6 +7604,7 @@ breakText Glyphs Гліфи @msg `names` must be an array of style names `names` має бути масивом імен стилів @msg `new` is a design name, or true `new` — це назва дизайну або true @msg `origin` must be [x, y] in points `origin` має бути [x, y] у пунктах +@msg `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 `axes` має бути [a, b, c, d], кожне від -1000 до 1000, а a·d - b·c має відрізнятися від 0 щонайменше на 0.001 @msg `path` must be a folder `path` має бути папкою @msg `path` must be a path object `path` має бути об’єктом-контуром @msg `picks` must be an array (got {v}) `picks` має бути масивом (отримано {v}) @@ -7980,7 +8004,7 @@ breakText Glyphs Гліфи @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 composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer має бути "singleLine", "everyLine", "standardSingleLine" або "standardEveryLine" @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} має містити рівно один відкритий контур для з’єднання @msg connect needs a path other than the one extended для connect потрібен контур, відмінний від того, що продовжується @@ -9185,3 +9209,20 @@ breakText Glyphs Гліфи Nest Shapes… Розкладка фігур… Nest Shapes Розкладка фігур Roll Рулон + Packaging Tools Інструменти пакування + Fold Lines Лінії згину + Make Cut Line Зробити лінією різу + Make Crease Line Зробити лінією біговки + Make Partial Cut Line Зробити лінією надрізу + Make Perforation Line Зробити лінією перфорації + Make Fold Line Зробити лінією згину + Role Swatches… Зразки типів ліній… + Role Swatches Зразки типів ліній + Role Тип лінії + Cut Line Лінія різу + Crease Line Лінія біговки + Partial Cut Line Лінія надрізу + Perforation Line Лінія перфорації + No objects are selected. Об’єкти не виділено. + Open a document to mark its fold lines. Відкрийте документ, щоб позначити його лінії згину. + Remove Fold Line Role Прибрати тип лінії diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 98a5629d11..3cc07d98cc 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -598,6 +598,7 @@ font-technology Variable Biến thiên Close Library Đóng thư viện Close Panel Đóng bảng Collapse Panel Group Thu gọn nhóm bảng + Cycle Display Sizes Chuyển kích thước hiển thị Close Path Đóng đường dẫn Close paths when ends are within: Đóng đường dẫn khi hai đầu cách nhau trong: Clumped Dạng cụm @@ -1100,6 +1101,8 @@ font-technology Variable Biến thiên Drag art, colors and text styles here to reuse them across documents. Libraries are stored on this machine — no account required. Kéo tác phẩm, màu và kiểu chữ vào đây để tái sử dụng trong các tài liệu. Thư viện được lưu trên máy này — không cần tài khoản. Drag onto art to apply this appearance Kéo lên tác phẩm để áp dụng diện mạo này Drag rings to rotate. Shift snaps to 15°. Kéo vòng để xoay. Shift khớp ở 15°. + Track cube Khối xoay + Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. Kéo một mặt, một cạnh hoặc vòng để xoay. Shift xoay quanh một trục màn hình. Drag the art to move it on the paper Kéo tác phẩm để di chuyển trên trang Drag the light, or its rings. Shift snaps to 15°. Kéo đèn hoặc vòng của nó. Shift khớp ở 15°. Drag to float as a toolbar Kéo để thả nổi thanh công cụ @@ -1257,7 +1260,10 @@ font-technology Variable Biến thiên Every (minutes) Mỗi (phút) Every option is at its default. Mọi tùy chọn đang ở mặc định. Every option matches {base}. Mọi tùy chọn khớp với {base}. - Every-line Composer Soạn theo từng dòng + Middle Eastern & South Asian Single-line Composer Soạn thảo một dòng (Trung Đông và Nam Á) + Middle Eastern & South Asian Every-line Composer Soạn theo từng dòng (Trung Đông và Nam Á) + Standard Single-line Composer Soạn thảo một dòng tiêu chuẩn + Standard Every-line Composer Soạn theo từng dòng tiêu chuẩn Exact dash lengths Độ dài nét đứt chính xác Exceptions (comma separated) Ngoại lệ (phân cách bằng dấu phẩy) Exclude Loại trừ @@ -1653,6 +1659,14 @@ file-filter Templates Mẫu Previous Artboard Bảng vẽ trước Next Artboard Bảng vẽ tiếp theo Last Artboard Bảng vẽ cuối cùng + Status Bar Show Hiển thị trên thanh trạng thái + Artboard Name Tên bảng vẽ + Current Tool Công cụ hiện tại + Date and Time Ngày và giờ + Number of Undos Số lần hoàn tác + Document Color Profile Hồ sơ màu của tài liệu + Undos Hoàn tác + Redos Làm lại Go To Link Đến liên kết Good Tốt GPL palettes keep solid colours only, as RGB. Bảng màu GPL chỉ lưu màu đặc theo RGB. @@ -1691,6 +1705,8 @@ file-filter Templates Mẫu Chop Design Cắt thiết kế Scale Design Co giãn thiết kế Graph Type Loại biểu đồ + Graph Type… Loại biểu đồ… + Graph Data… Dữ liệu biểu đồ… Graph Options Tùy chọn biểu đồ Left Axis Trục trái Right Axis Trục phải @@ -1787,6 +1803,7 @@ file-filter Templates Mẫu Show smooth color wheel Hiện bánh xe màu liền mạch Show segmented color wheel Hiện bánh xe màu phân đoạn Show color bars Hiện các thanh màu + Find the selected colors in the artwork Tìm các màu đã chọn trong tác phẩm Harmony Sets Bộ hài hòa màu Height Chiều cao Height: Chiều cao: @@ -3065,6 +3082,8 @@ mark-style Japanese Kiểu Nhật Insert Aki Left Chèn aki bên trái Insert Aki Right Chèn aki bên phải Tsume Tsume + Adjust Horizontal Diacritic Position Điều chỉnh vị trí ngang của dấu phụ + Adjust Vertical Diacritic Position Điều chỉnh vị trí dọc của dấu phụ Proportional Lining Số tỷ lệ đứng Position: Vị trí: Default Position Vị trí mặc định @@ -3850,7 +3869,6 @@ mark-style Japanese Kiểu Nhật Single Left Quotation Mark Dấu nháy đơn mở Single Quotes: Dấu nháy đơn: Single Right Quotation Mark Dấu nháy đơn đóng - Single-line Composer Soạn thảo một dòng Toggle Line Composer Chuyển đổi cách soạn dòng Sixth Space Dấu cách 1/6 Size Kích thước @@ -4956,6 +4974,17 @@ theme Appearance Giao diện @msg `name` must be the name of a script engine `name` phải là tên của một bộ máy tập lệnh @msg the main script engine is new for each run and is never kept, so it cannot be dropped bộ máy tập lệnh chính được tạo mới cho mỗi lần chạy và không bao giờ được giữ lại, nên không thể loại bỏ 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 `answers` must be a list of answers `answers` phải là một danh sách câu trả lời +@msg `answers` has more than {MAX_ANSWERS} answers `answers` có hơn {MAX_ANSWERS} câu trả lời +@msg `answers` is larger than 1 MiB `answers` lớn hơn 1 MiB +@msg must be an object with `kind` and `value` phải là một đối tượng có `kind` và `value` +@msg must have exactly `kind` and `value` phải có đúng `kind` và `value` +@msg is an alert's answer, whose `value` must be "ok" là câu trả lời cho alert, nên `value` phải là "ok" +@msg is a confirm's answer, whose `value` must be true or false là câu trả lời cho confirm, nên `value` phải là true hoặc false +@msg is longer than 16 KiB dài hơn 16 KiB +@msg is a prompt's answer, whose `value` must be a string or null là câu trả lời cho prompt, nên `value` phải là chuỗi hoặc null +@msg must have `kind` alert, confirm or prompt phải có `kind` là alert, confirm hoặc prompt +@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` chỉ dành cho lần chạy không có ai để hỏi: trong ứng dụng, người dùng trả lời từng hộp thoại @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 @@ -5670,6 +5699,8 @@ theme Appearance Giao diện @msg unknown option `{path}.{k}` tùy chọn không xác định `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) chế độ in đè không xác định `{o}` (preserve, simulate hoặc discard) @msg unknown panel `{raw}` bảng không xác định `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` không có kích thước hiển thị để chuyển +@msg the panels are not shown các bảng không được hiển thị @msg panels can't be shown in Presentation Mode không thể hiển thị bảng trong chế độ trình bày @msg unknown parameter `{key}`; did you mean `{near}`? tham số không xác định `{key}`; ý bạn là `{near}`? @msg unknown parameter `{key}`; the command takes no parameters tham số không xác định `{key}`; lệnh này không nhận tham số @@ -5880,6 +5911,7 @@ theme Appearance Giao diện Export Data Sets… Xuất tập dữ liệu… Load Variable Library… Tải thư viện biến số… Save Variable Library… Lưu thư viện biến số… +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml "Nhập" đọc tệp nguồn dữ liệu có phần mở rộng .csv, .tsv, .txt hoặc .xml @msg a variable library holds text variables, and the document has none thư viện biến số chứa các biến số văn bản, và tài liệu không có biến số văn bản nào @msg variable `{name}` can't be saved in a variable library: rename it to start with a letter or `_`, without spaces or symbols other than `-`, `_` and `.` không thể lưu biến số `{name}` vào thư viện biến số: hãy đổi tên để bắt đầu bằng một chữ cái hoặc `_`, không có khoảng trắng hay ký hiệu nào ngoài `-`, `_` và `.` @msg {k} has control characters {k} chứa ký tự điều khiển @@ -6163,6 +6195,7 @@ axis Y Axis Trục Y @msg {what} points outside memory {what} trỏ ra ngoài bộ nhớ @msg `angle` must be a number `angle` phải là một số @msg `aspect` must be from 0.01 to 100 `aspect` phải từ 0.01 đến 100 +@msg `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 `axes` phải là [a, b, c, d], mỗi số từ -1000 đến 1000, và a·d - b·c phải cách 0 ít nhất 0.001 @msg `cap` must be "butt", "round" or "square" `cap` phải là "butt", "round" hoặc "square" @msg `fillRule` must be "nonzero" or "evenodd" `fillRule` phải là "nonzero" hoặc "evenodd" @msg `helpUrl` must be an https:// address of at most {MAX_HELP_URL} bytes `helpUrl` phải là một địa chỉ https:// dài tối đa {MAX_HELP_URL} byte @@ -7166,6 +7199,19 @@ breakText Glyphs Glyph Not Aligned to Pixel Grid Chưa căn theo lưới pixel @msg only paths and compound paths can be aligned to the pixel grid chỉ đường dẫn và đường dẫn phức mới căn theo lưới pixel được @msg side is left or right, not `{s}` side là left hoặc right, không phải `{s}` +@msg side is left or right, not `{v}` side là left hoặc right, không phải `{v}` +@msg order is a whole number from 0 to {others}, not `{v}` order là số nguyên từ 0 đến {others}, không phải `{v}` +@msg toolbar (a toolbar's name) must be a string toolbar (tên một thanh công cụ) phải là chuỗi +@msg no toolbar named `{name}` không có thanh công cụ tên `{name}` +@msg toolbar name can't be empty tên thanh công cụ không được để trống +@msg a toolbar name has at most {MAX_NAME} characters tên thanh công cụ có tối đa {MAX_NAME} ký tự +@msg there is already a toolbar named `{name}` đã có thanh công cụ tên `{name}` +@msg there is already a toolbar named `{to}` đã có thanh công cụ tên `{to}` +@msg a workspace keeps at most {MAX} toolbars một không gian làm việc giữ tối đa {MAX} thanh công cụ +@msg name (a toolbar's name) must be a string name (tên một thanh công cụ) phải là chuỗi +@msg name (a toolbar's name) is required name (tên một thanh công cụ) là bắt buộc +@msg to (the new name) is required to (tên mới) là bắt buộc +@msg name must be a toolbar's name name phải là tên của một thanh công cụ Ignore All Bỏ qua tất cả Add to Dictionary Thêm vào từ điển No Suggestions Không có gợi ý @@ -7262,6 +7308,23 @@ breakText Glyphs Glyph 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 + Packaging Tools Công cụ bao bì + Fold Lines Đường gấp + Make Cut Line Đặt làm đường cắt + Make Crease Line Đặt làm đường cấn + Make Partial Cut Line Đặt làm đường cắt một phần + Make Perforation Line Đặt làm đường đục lỗ + Make Fold Line Đặt làm đường gấp + Role Swatches… Mẫu màu của các loại đường… + Role Swatches Mẫu màu của các loại đường + Role Loại đường + Cut Line Đường cắt + Crease Line Đường cấn + Partial Cut Line Đường cắt một phần + Perforation Line Đường đục lỗ + No objects are selected. Không có đối tượng nào được chọn. + Open a document to mark its fold lines. Mở tài liệu để đánh dấu các đường gấp của nó. + Remove Fold Line Role Bỏ loại đường # 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 @@ -7379,3 +7442,4 @@ breakText Glyphs Glyph @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 +@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer phải là "singleLine", "everyLine", "standardSingleLine" hoặc "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index f5fd59ee8b..f96d93d9ea 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1019,7 +1019,8 @@ antiAlias Sharp 锐利 Every (minutes) 每隔 (分钟) Every option is at its default. 所有选项皆为默认值。 Every option matches {base}. 所有选项皆与{base}相同。 - Every-line Composer 逐行排版器 + Middle Eastern & South Asian Every-line Composer 逐行排版器(中东和南亚) + Standard Every-line Composer 标准逐行排版器 Exact dash lengths 精确虚线长度 Exceptions (comma separated) 例外词 (逗号分隔) Exclude 差集 @@ -1352,6 +1353,14 @@ file-filter Templates 模板 Previous Artboard 上一个画板 Next Artboard 下一个画板 Last Artboard 最后一个画板 + Status Bar Show 状态栏显示 + Artboard Name 画板名称 + Current Tool 当前工具 + Date and Time 日期和时间 + Number of Undos 撤销次数 + Document Color Profile 文档颜色配置文件 + Undos 撤销 + Redos 重做 Go To Link 转到链接 GPL palettes keep solid colours only, as RGB. GPL 调板仅保留为 RGB 的纯色。 GPU Performance GPU 性能 @@ -1371,6 +1380,8 @@ file-filter Templates 模板 Graph 图表 Graph Data 图表数据 Graph Type 图表类型 + Graph Type… 图表类型… + Graph Data… 图表数据… Graph Options 图表选项 Left Axis 左轴 Right Axis 右轴 @@ -1485,6 +1496,7 @@ file-filter Templates 模板 Show smooth color wheel 显示平滑色轮 Show segmented color wheel 显示分段色轮 Show color bars 显示颜色条 + Find the selected colors in the artwork 在图稿中查找所选颜色 Harmony Sets 色彩调和组 Height 高度 Height: 高度: @@ -2609,6 +2621,8 @@ font-script Japanese 汉字 Insert Aki Left 在前方插入空白 Insert Aki Right 在后方插入空白 Tsume 比例间距 + Adjust Horizontal Diacritic Position 调整变音符号水平位置 + Adjust Vertical Diacritic Position 调整变音符号垂直位置 Character Direction 字符方向 Digits 数字 Arabic 阿拉伯数字 @@ -3312,7 +3326,8 @@ digits Malayalam 马拉雅拉姆数字 Single Left Quotation Mark 左单引号 Single Quotes: 单引号: Single Right Quotation Mark 右单引号 - Single-line Composer 单行排版器 + Middle Eastern & South Asian Single-line Composer 单行排版器(中东和南亚) + Standard Single-line Composer 标准单行排版器 Toggle Line Composer 切换行排版器 Sixth Space 六分之一空格 Size 大小 @@ -4779,6 +4794,8 @@ imageTrace Outline 轮廓 @msg give only one of onto, below and above onto、below 和 above 只能给出一个 @msg column must be true or a number from 1 column 必须是 true 或从 1 开始的数字 @msg unknown panel `{raw}` 未知面板 `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` 没有可切换的显示大小 +@msg the panels are not shown 面板未显示 @msg panels can't be shown in Presentation Mode 演示模式下无法显示面板 @msg x and y must both be numbers x 和 y 都必须是数字 @msg Downloaded {what} 已下载 {what} @@ -5820,6 +5837,7 @@ effect Vertical 垂直 Change Panel Layout 更改面板布局 Close Panel 关闭面板 Collapse Panel Group 折叠面板组 + Cycle Display Sizes 切换显示大小 Move Panel 移动面板 Group with 组合到 Resize panels 调整面板大小 @@ -5843,6 +5861,8 @@ effect Vertical 垂直 Step up or down 逐级增减 Drag values or labels. Double-click a value to type. 拖动数值或标签。双击数值即可输入。 Drag rings to rotate. Shift snaps to 15°. 拖动圆环旋转。按住 Shift 以 15° 为步长调整。 + Track cube 旋转立方体 + Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. 拖动面、边或圆环进行旋转。按住 Shift 绕一个屏幕轴旋转。 Drag the light, or its rings. Shift snaps to 15°. 拖动光源或圆环。按住 Shift 以 15° 为步长调整。 lighting Light 光源 Keep visible surfaces only when expanding 扩展时仅保留可见表面 @@ -6117,6 +6137,7 @@ lighting Light 光源 Export Data Sets… 导出数据集… Load Variable Library… 载入变量库… Save Variable Library… 保存变量库… +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml “导入”读取扩展名为 .csv、.tsv、.txt 或 .xml 的数据源文件 @msg a variable library holds text variables, and the document has none 变量库包含文本变量,而文档中没有文本变量 @msg variable `{name}` can't be saved in a variable library: rename it to start with a letter or `_`, without spaces or symbols other than `-`, `_` and `.` 无法将变量 `{name}` 保存到变量库中:请重命名,使其以字母或 `_` 开头,且不含空格或 `-`、`_`、`.` 以外的符号 @msg {k} has control characters {k} 包含控制字符 @@ -7516,6 +7537,7 @@ breakText Glyphs 字形 @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` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` 仅用于无人可问的运行:在应用中,由用户回答每个对话框 @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] @@ -7548,6 +7570,7 @@ breakText Glyphs 字形 @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 `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 `axes` 必须是 [a, b, c, d],每个值在 -1000 到 1000 之间,且 a·d - b·c 与 0 的差至少为 0.001 @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 个点 @@ -7926,6 +7949,7 @@ breakText Glyphs 字形 @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 Image Trace finished, but its document was reverted: trace it again 图像描摹已完成,但其文档已恢复:请重新描摹 @msg Invalid dimension offset 尺寸标注的偏移无效 @msg Invalid point 点无效 @msg Join: a subpath went missing 连接:有一条子路径丢失 @@ -8340,7 +8364,7 @@ breakText Glyphs 字形 @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 composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer 必须是 "singleLine"、"everyLine"、"standardSingleLine" 或 "standardEveryLine" @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} 必须恰好包含一条要连接的开放路径 @msg connect needs a path other than the one extended connect 需要一条不同于被延伸路径的路径 @@ -9416,4 +9440,21 @@ breakText Glyphs 字形 @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 像素):请降低分辨率 + Packaging Tools 包装工具 + Fold Lines 折线 + Make Cut Line 设为切割线 + Make Crease Line 设为压痕线 + Make Partial Cut Line 设为半切线 + Make Perforation Line 设为打孔线 + Make Fold Line 设为折线 + Role Swatches… 线条类型色板… + Role Swatches 线条类型色板 + Role 线条类型 + Cut Line 切割线 + Crease Line 压痕线 + Partial Cut Line 半切线 + Perforation Line 打孔线 + No objects are selected. 未选择任何对象。 + Open a document to mark its fold lines. 打开文档以标记其折线。 + Remove Fold Line Role 移除线条类型 @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/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 29599476be..6a962013ca 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1050,7 +1050,8 @@ font-technology Variable 可變 Every (minutes) 每隔 (分鐘) Every option is at its default. 所有選項皆為預設值。 Every option matches {base}. 所有選項皆與{base}相同。 - Every-line Composer 逐行排版程式 + Middle Eastern & South Asian Every-line Composer 逐行排版程式(中東與南亞) + Standard Every-line Composer 標準逐行排版程式 Exact dash lengths 精確虛線長度 Exceptions (comma separated) 例外 (以逗號分隔) Exclude 差集 @@ -1387,6 +1388,14 @@ file-filter Templates 範本 Previous Artboard 上一個工作區域 Next Artboard 下一個工作區域 Last Artboard 最後一個工作區域 + Status Bar Show 狀態列顯示 + Artboard Name 工作區域名稱 + Current Tool 目前工具 + Date and Time 日期和時間 + Number of Undos 復原次數 + Document Color Profile 文件色彩描述檔 + Undos 復原 + Redos 重做 Go To Link 前往連結 GPL palettes keep solid colours only, as RGB. GPL 調色盤僅保留純色,並以 RGB 儲存。 GPU Performance GPU 效能 @@ -1406,6 +1415,8 @@ file-filter Templates 範本 Graph 圖表 Graph Data 圖表資料 Graph Type 圖表類型 + Graph Type… 圖表類型… + Graph Data… 圖表資料… Graph Options 圖表選項 Left Axis 左軸 Right Axis 右軸 @@ -1522,6 +1533,7 @@ file-filter Templates 範本 Show smooth color wheel 顯示平滑色輪 Show segmented color wheel 顯示分段色輪 Show color bars 顯示顏色條 + Find the selected colors in the artwork 在圖稿中尋找所選顏色 Harmony Sets 色彩調和組 Height 高度 Height: 高度: @@ -2428,6 +2440,8 @@ file-filter Templates 範本 @msg give only one of onto, below and above onto、below 和 above 只能提供其中一個 @msg column must be true or a number from 1 column 必須是 true 或從 1 起算的數字 @msg unknown panel `{raw}` 未知的面板 `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` 沒有可切換的顯示大小 +@msg the panels are not shown 面板未顯示 @msg panels can't be shown in Presentation Mode 簡報模式下無法顯示面板 @msg x and y must both be numbers x 和 y 都必須是數字 @msg Downloaded {what} 已下載 {what} @@ -2626,6 +2640,7 @@ file-filter Templates 範本 @msg `name` must be the name of a script engine `name` 必須是指令碼引擎的名稱 @msg the main script engine is new for each run and is never kept, so it cannot be dropped 主指令碼引擎在每次執行時都是新的,從不保留,因此無法捨棄 @msg there is no script engine named {name} 沒有名為 {name} 的指令碼引擎 +@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` 僅適用於沒有人可詢問的執行:在應用程式中,由使用者回答每個對話框 @msg Running a script 正在執行指令碼 @msg Copied the script report 已複製指令碼報告 @msg Copied the link info 已複製連結資訊 @@ -3832,6 +3847,8 @@ font-script Japanese 漢字 Insert Aki Left 在前方插入空白 Insert Aki Right 在後方插入空白 Tsume 比例間距 + Adjust Horizontal Diacritic Position 調整變音符號水平位置 + Adjust Vertical Diacritic Position 調整變音符號垂直位置 Character Direction 字元方向 Digits 數字 Arabic 阿拉伯數字 @@ -4573,7 +4590,8 @@ digits Malayalam 馬來亞拉姆數字 Single Left Quotation Mark 左單引號 Single Quotes: 單引號: Single Right Quotation Mark 右單引號 - Single-line Composer 單行排版程式 + Middle Eastern & South Asian Single-line Composer 單行排版程式(中東與南亞) + Standard Single-line Composer 標準單行排版程式 Toggle Line Composer 切換行排版程式 Sixth Space 六分之一空格 Size 大小 @@ -5655,6 +5673,7 @@ effect Soft 柔和 Change Panel Layout 變更面板配置 Close Panel 關閉面板 Collapse Panel Group 摺疊面板群組 + Cycle Display Sizes 切換顯示大小 Move Panel 移動面板 Group with 群組至 Resize panels 調整面板大小 @@ -5678,6 +5697,8 @@ effect Soft 柔和 Step up or down 逐級增減 Drag values or labels. Double-click a value to type. 拖曳數值或標籤。按兩下數值即可輸入。 Drag rings to rotate. Shift snaps to 15°. 拖曳圓環旋轉。按住 Shift 以 15° 為間距調整。 + Track cube 旋轉立方體 + Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. 拖曳面、邊或圓環進行旋轉。按住 Shift 繞一個螢幕軸旋轉。 Drag the light, or its rings. Shift snaps to 15°. 拖曳光源或圓環。按住 Shift 以 15° 為間距調整。 lighting Light 光源 Keep visible surfaces only when expanding 展開時僅保留可見表面 @@ -5951,6 +5972,7 @@ lighting Light 光源 Export Data Sets… 匯出資料集… Load Variable Library… 載入變數資料庫… Save Variable Library… 儲存變數資料庫… +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml 「匯入」讀取副檔名為 .csv、.tsv、.txt 或 .xml 的資料來源檔案 @msg a variable library holds text variables, and the document has none 變數資料庫包含文字變數,但文件中沒有文字變數 @msg variable `{name}` can't be saved in a variable library: rename it to start with a letter or `_`, without spaces or symbols other than `-`, `_` and `.` 無法將變數 `{name}` 儲存到變數資料庫:請重新命名,使其以字母或 `_` 開頭,且不含空格或 `-`、`_`、`.` 以外的符號 @msg {k} has control characters {k} 包含控制字元 @@ -7476,6 +7498,7 @@ breakText Glyphs 字符 @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 `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 `axes` 必須是 [a, b, c, d],每個值介於 -1000 到 1000 之間,且 a·d - b·c 與 0 的差至少為 0.001 @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 個點 @@ -7854,6 +7877,7 @@ breakText Glyphs 字符 @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 Image Trace finished, but its document was reverted: trace it again 影像描圖已完成,但其文件已回復:請重新描圖 @msg Invalid dimension offset 尺寸標註位移無效 @msg Invalid point 點無效 @msg Join: a subpath went missing 連接:有一條子路徑不見了 @@ -8268,7 +8292,7 @@ breakText Glyphs 字符 @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 composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer 必須是 "singleLine"、"everyLine"、"standardSingleLine" 或 "standardEveryLine" @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} 必須剛好包含一條可連接的開放路徑 @msg connect needs a path other than the one extended connect 需要延伸路徑以外的另一條路徑 @@ -9226,4 +9250,21 @@ breakText Glyphs 字符 @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} 連同出血和標記無法容納於紙張 + Packaging Tools 包裝工具 + Fold Lines 摺線 + Make Cut Line 設為切割線 + Make Crease Line 設為壓痕線 + Make Partial Cut Line 設為半切線 + Make Perforation Line 設為打孔線 + Make Fold Line 設為摺線 + Role Swatches… 線條類型色票… + Role Swatches 線條類型色票 + Role 線條類型 + Cut Line 切割線 + Crease Line 壓痕線 + Partial Cut Line 半切線 + Perforation Line 打孔線 + No objects are selected. 未選取任何物件。 + Open a document to mark its fold lines. 開啟文件以標記其摺線。 + Remove Fold Line Role 移除線條類型 @msg {what} would print on more than {MAX_TILES} tiles: scale it down {what} 會列印在超過 {MAX_TILES} 個拼貼上:請縮小 diff --git a/crates/ui-egui/src/io/open.rs b/crates/ui-egui/src/io/open.rs index e0e4e4c404..11c02ca139 100644 --- a/crates/ui-egui/src/io/open.rs +++ b/crates/ui-egui/src/io/open.rs @@ -52,10 +52,12 @@ fn open_bytes_with(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Opt let load = if swatches { crate::panels::swatches::load_library } else { crate::panels::graphic_styles::load_library }; return load(app, p).map(|_| Value::Null); } - // A PDF with several pages or a password asks first (the Import PDF dialog), and so does a - // DXF drawing (DXF Import Options). + // A PDF with several pages or a password asks first (the Import PDF dialog), and so do a DXF + // drawing (DXF Import Options) and a PSD file with several layers or with slices (PSD Import + // Options), unless `p` says how its layers come in. if crate::dialogs::import_pdf::offer(app, name, bytes, path.clone(), None) || crate::dialogs::dxf_import::offer(app, name, bytes, path.clone(), None) + || (p.get("layers").is_none() && crate::dialogs::psd_import::offer(app, name, bytes, path.clone(), None)) { return Ok(Value::Null); } @@ -552,9 +554,11 @@ fn open_file_with(app: &mut VectorcraftApp, path: &str, background: bool, p: &Va check_import_size(path, false)?; let mut bytes = read(app, path)?; if background && opens_as(path).is_none() { - // A PDF with several pages or a password, or a DXF drawing, asks first, as at once. + // A PDF with several pages or a password, a DXF drawing, or a PSD file with several layers + // or with slices asks first, as at once. if crate::dialogs::import_pdf::offer(app, path, &bytes, Some(path.to_string()), None) || crate::dialogs::dxf_import::offer(app, path, &bytes, Some(path.to_string()), None) + || (p.get("layers").is_none() && crate::dialogs::psd_import::offer(app, path, &bytes, Some(path.to_string()), None)) { note_recent(app, path); return Ok(Value::Null); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 3f89789d5d..79b1f41100 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -2,7 +2,7 @@ //! //! The UI is thin: every action goes through [`VectorcraftApp::run`], which dispatches UI commands //! (view/window) here and everything else to the engine. The same entry point serves menus, -//! shortcuts, the ⌘K palette and the control channel ([`control`]). +//! shortcuts, the command palette ([`palette`], Help › Search Commands…) and the control channel ([`control`]). #![forbid(unsafe_code)] /// VectorCraft as craft-update knows it, with its 128 px icon and accent colour: the update diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index ab11dc5a10..32db24c1c7 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -298,6 +298,13 @@ fn open_view_dialog(app: &mut VectorcraftApp, id: &str, p: &Value) -> bool { } return true; } + // Check Spelling…: dialog to walk through unknown words. + if id == crate::dialogs::check_spelling::COMMAND && p.as_object().is_none_or(|o| o.is_empty()) { + if let Err(e) = crate::dialogs::check_spelling::open(app) { + app.status(e); + } + return true; + } // Edit Views…: the saved views in a list, to rename or delete. if id == "view.saved.edit" && p.as_object().is_none_or(|o| o.is_empty()) { if let Err(e) = crate::dialogs::edit_views::open(app) { diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index df3f08b55e..495e606d6c 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -455,6 +455,7 @@ fn run_ui_part5(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option go_to_artboard(app, p), + "view.statusBarShow" => crate::chrome::set_status_bar_show(app, p), // The navigator's four buttons as commands of their own, so Edit › Keyboard Shortcuts lists // them (view.goToArtboard needs an index, so a key alone can't run it). "view.firstArtboard" => go_to_artboard(app, &json!({ "index": "first" })), @@ -1089,6 +1090,7 @@ fn run_ui_part13(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::dialogs::blend_options::open(app), "ui.livePaintGapOptions" => crate::dialogs::live_paint_gaps::open(app), "ui.perspectivePlane" => crate::dialogs::perspective_plane::open(app, p), + crate::dialogs::check_spelling::COMMAND => crate::dialogs::check_spelling::open(app), _ => return None, }; diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index 98c13ec06e..d4dda4698b 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -63,6 +63,7 @@ pub fn checked(app: &VectorcraftApp, id: &str, p: &Value) -> Option { "view.rotate" => app.view().zip(p.get("angle").and_then(Value::as_f64)).is_some_and(|(view, a)| (view.rotation - a).abs() < 1e-9), "window.control" => app.ui.control_bar, "window.helpBar" => app.ui.help_bar, + "view.statusBarShow" => p.get("show").and_then(Value::as_str) == Some(app.ui.status_bar_show.param()), "window.control.dock" => p.get("edge").and_then(Value::as_str) == Some(crate::chrome::control_bar_placement(&app.ui)), "window.control.options" => p .get("group") @@ -281,7 +282,7 @@ pub fn enabled(app: &VectorcraftApp, id: &str) -> bool { .dialog .as_ref() .is_some_and(|d| crate::dialogs::para_style_options::is_paragraph_dialog(d) && crate::dialogs::para_style_options::can_reset(d)), - "ui.newArtboard" | "artboard.selectAll" => app.session.active().is_some(), + "ui.newArtboard" | "artboard.selectAll" | crate::dialogs::check_spelling::COMMAND => app.session.active().is_some(), "ui.sampleScreenColor" => crate::screen_color::available(app), "ui.newBrush" => app.session.active().is_some(), "ui.brushOptions" => crate::dialogs::brush_options::available(app), diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index b718b24080..ec8ec99018 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -97,7 +97,7 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { Sep, cp("Find and Replace…", "edit.findReplace", json!({"find": "", "replace": "", "matchCase": false, "wholeWord": false})), cp("Find Next", "edit.findNext", json!({"find": ""})), - sub("Spelling", vec![c("Auto Spell Check", "edit.autoSpellCheck"), todos("Check Spelling…", "Cmd+I")]), + sub("Spelling", vec![c("Auto Spell Check", "edit.autoSpellCheck"), c("Check Spelling…", crate::dialogs::check_spelling::COMMAND)]), // Edit › Edit Custom Dictionary…, beside Spelling, on the public Check and correct // spelling page. c("Edit Custom Dictionary…", crate::dialogs::custom_dictionary::COMMAND), diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 799c8da2f7..5b73f36ab6 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -168,6 +168,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} toggle a red underline under the words of the document's type its dictionaries don't know (text.spelling.check lists them), kept up to date as the type changes; type with effects isn't underlined → whether Auto Spell Check is on", ), + ( + crate::dialogs::check_spelling::COMMAND, + "Check Spelling…", + "Cmd+I", + "{} open the Check Spelling dialog to walk through unrecognized words with suggestions, ignore, change and dictionary options", + ), ("shortcuts.set", "Set Keyboard Shortcut", "", "{id: command id or tool:, shortcut: \"Cmd+Shift+K\" | \"\" (none) | null (default), force?}"), ("shortcuts.list", "List Keyboard Shortcuts", "", "{query?} → [{id, label, group, shortcut, default, overridden}]"), ("shortcuts.conflicts", "Keyboard Shortcut Conflicts", "", "{} → [{shortcut, ids}]"), @@ -393,7 +399,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "type.lineComposer", "Toggle Line Composer", "Cmd+Alt+Shift+C", - "{} the selected type's paragraphs (or those the Type tool's selection touches) use the Single-line Composer when they all use the Every-line Composer, else the Every-line Composer (text.setFormat {composer}) → \"singleLine\" | \"everyLine\"", + "{} the selected type's paragraphs (or those the Type tool's selection touches) use the Single-line Composer when they all use the Every-line Composer, else the Every-line Composer; paragraphs that all use a Standard composer keep it, any other mix takes the Middle Eastern & South Asian one (text.setFormat {composer}) → \"singleLine\" | \"everyLine\" | \"standardSingleLine\" | \"standardEveryLine\"", ), ( "type.hyphenate", @@ -433,6 +439,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ ), ("view.nextArtboard", "Next Artboard", "", "{} the navigator's Next Artboard button: view.goToArtboard {index: \"next\"} → {index}"), ("view.lastArtboard", "Last Artboard", "", "{} the navigator's Last Artboard button: view.goToArtboard {index: \"last\"} → {index}"), + ( + "view.statusBarShow", + "Status Bar Show", + "", + "{show: \"artboardName\" | \"currentTool\" | \"dateTime\" | \"undos\" | \"colorProfile\"} the status bar's Show menu (a click on its info field): the field shows the name of the artboard the navigator shows, the tool in use (the default), the date and time (local on the desktop, UTC on the web), the active document's undo and redo step counts, or the profile its colors use (the one assigned for its color mode, else, or when that one is not available, that mode's working space); kept with the UI state; any other value is an error → show", + ), ("view.edges", "Hide Edges", "Cmd+H", "{}"), ("view.artboards", "Hide Artboards", "Cmd+Shift+H", "{}"), ( @@ -645,6 +657,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{panel, collapsed?: bool} minimize the group holding a panel to its tabs (in a floating window, the window to its title bar), or restore it, as a double-click on a tab or the drag bar does; the same as window.panel.minimize {panel, minimized}. Without `collapsed` it toggles. Returns {panel, collapsed, layout}", ), + ( + "window.panel.cycleOptions", + "Cycle Display Sizes", + "", + "{panel} show a panel at its next display size, as the double triangle at the right end of its tab strip does: the sizes are the states of its panel menu's Show/Hide Options (Transparency: options and thumbnails, thumbnails alone, neither), largest first, and the smallest goes back to the largest; Align, Attributes, Character, Color, Flattener Preview, Gradient, Info, Paragraph, Stroke, Transform and Transparency have them. An unknown panel or one without display sizes is an error and changes nothing. Returns {panel, size: 0 for the largest, sizes: how many it has}", + ), ( "window.panel.float", "Float Panel", @@ -1616,7 +1634,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ crate::panels::actions::LOAD_SET, "Load Actions…", "", - "{path? | data?: the file's text} read an action set file (.vcactions) at path, else a picked one, and add its set after the Actions panel's sets; a set named like one in the panel gets the next free number (Print 2), and the other sets stay. Files of another version, over 8 MiB, with more than 1,000 actions or with an action of more than 10,000 steps are refused, and so is any set, .aia ones too, that Save Actions… would write larger than 8 MiB (a file with less white space, or a name that gets a number); the panel menu's Load Actions… (disabled where there is no open dialog, the web) → {set: index, name, actions: n}. An action set another app saved as text (.aia, starting /version; read with actionSet.read) comes in with its actions. A step with a label and no recorded values comes in when exactly one menu command has that label (in English or the interface language, any case, no final …), and that command is directly in a top menu, can be recorded in actions, is what its menu bar item runs with no values and opens no dialog (never a submenu's item, a file or document command, Paste, Undo, Redo or an add-on's command), with no params and excluded from playback when it is off in the file; the other steps, every step with no label and every step recorded with values (a recorded menu item too) among them, are left out → {set, name, actions, skipped: [{action, step: its label, else its name}] (the first 1,000), leftOut: n}, and the status bar says how many were left out; a set with no name takes the file's name, else Actions; a file actionSet.read marks truncated is refused, and text that starts /version and isn't an action set gives \"not an action set file\"", + "{path? | data?: the file's text} read an action set file (.vcactions) at path, else a picked one, and add its set after the Actions panel's sets; a set named like one in the panel gets the next free number (Print 2), and the other sets stay. Files of another version, over 8 MiB, with more than 1,000 actions or with an action of more than 10,000 steps are refused, and so is any set, .aia ones too, that Save Actions… would write larger than 8 MiB (a file with less white space, or a name that gets a number); the panel menu's Load Actions… (disabled where there is no open dialog, the web) → {set: index, name, actions: n}. An action set another app saved as text (.aia, starting /version; read with actionSet.read) comes in with its actions. A step with a label and no recorded values comes in when exactly one menu command has that label (in English or the interface language, any case, no final …), and that command is directly in a top menu, can be recorded in actions, is what its menu bar item runs with no values and opens no dialog (never a submenu's item, a file or document command, Paste, Undo, Redo or an add-on's command), with no params and excluded from playback when it is off in the file. A Set Selection step (found by its internal name, whatever its label) comes in as select.byNote {note, caseSensitive, wholeWord} when it has exactly three recorded values: text (ustring, UTF-8; 1 to 1,024 bytes once trimmed), word and case (boolean, 0 or 1); with any other values it is left out. The other steps, every other step with no label and every other step recorded with values (a recorded menu item too) among them, are left out → {set, name, actions, skipped: [{action, step: its label, else its name}] (the first 1,000), leftOut: n}, and the status bar says how many were left out; a set with no name takes the file's name, else Actions; a file actionSet.read marks truncated is refused, and text that starts /version and isn't an action set gives \"not an action set file\"", ), ( crate::panels::actions::DELETE_SETS, diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index 5b4913d552..0a4f01879d 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -316,7 +316,7 @@ fn apply(layout: &mut Layout, action: Action) -> Result Option> { if let Some(result) = crate::tools_float::command(app, id, params) { @@ -326,6 +326,7 @@ pub(crate) fn command(app: &mut VectorcraftApp, id: &str, params: &Value) -> Opt "window.panel" => return Some(show_panel(app, params)), "window.collapseDock" => return Some(crate::menus::opt_bool(params, "collapsed").and_then(|c| collapse_dock(app, c))), "window.panels.peek" => return Some(peek::command(app, params)), + "window.panel.cycleOptions" => return Some(sizes::command(app, params)), "window.panel.collapse" => { let minimized = match crate::menus::opt_bool(params, "collapsed") { Ok(c) => c, @@ -1472,13 +1473,21 @@ impl craft_ui::docking::DockContent for PanelContent<'_> { crate::panels::panel_menu_items(self.app, ui, id); } - fn group_header_width(&self, panels: &[String], _active: &String, floating: bool, _strip_width: f32) -> f32 { + fn group_header_width(&self, panels: &[String], active: &String, floating: bool, _strip_width: f32) -> f32 { let flyout = self.app.ui.open_panel.as_ref().is_some_and(|panel| panels.contains(panel)); - if floating || flyout { 52.0 } else { 28.0 } + let cycle = if sizes::has_sizes(active) { sizes::CELL } else { 0.0 }; + cycle + if floating || flyout { 52.0 } else { 28.0 } } fn group_header(&mut self, ui: &mut egui::Ui, panels: &[String], active: &String, floating: bool) { - let header = ui.max_rect(); + let mut header = ui.max_rect(); + // The double triangle comes first, for a panel with display sizes. + if sizes::has_sizes(active) { + let split = (header.left() + sizes::CELL).min(header.right()); + let cell = egui::Rect::from_min_max(header.min, egui::pos2(split, header.bottom())); + sizes::button(self.app, ui, cell, active); + header.min.x = split; + } let flyout = self.app.ui.open_panel.clone().filter(|panel| panels.contains(panel)); let menu_cell = if floating || flyout.is_some() { let split = (header.right() - 28.0).max(header.left()); @@ -1523,6 +1532,7 @@ impl craft_ui::docking::DockContent for PanelContent<'_> { } mod peek; +mod sizes; #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/panel_docking/peek.rs b/crates/ui-egui/src/panel_docking/peek.rs index baf147f4fd..ed43b80e3d 100644 --- a/crates/ui-egui/src/panel_docking/peek.rs +++ b/crates/ui-egui/src/panel_docking/peek.rs @@ -41,6 +41,8 @@ struct Shown { edge: Edge, /// When the pointer left them; `None` while it is over them or has not moved since they showed. left_at: Option, + /// Whether a press, a modal dialog, a popup or a flyout held them open last frame. + held: bool, } /// The session's state of the panels shown from the edges. @@ -102,9 +104,11 @@ pub(super) fn update(app: &mut VectorcraftApp, ctx: &egui::Context, area: egui:: return None; } let (now, pointer, down, moved) = ctx.input(|i| { - // A release counts as moving away: a press may have held the panels while it left them. - let moved = - i.pointer.delta() != egui::Vec2::ZERO || i.pointer.any_released() || i.events.iter().any(|e| matches!(e, egui::Event::PointerGone)); + // A release counts as moving away: a press may have held the panels while it left them. A + // pointer entering the window has no delta on its first frame, so the move event counts too. + let moved = i.pointer.delta() != egui::Vec2::ZERO + || i.pointer.any_released() + || i.events.iter().any(|e| matches!(e, egui::Event::PointerMoved(_) | egui::Event::PointerGone)); (i.time, i.pointer.hover_pos(), i.pointer.any_down(), moved) }); // A workspace switched to while panels show may dock none on that side. @@ -123,11 +127,15 @@ pub(super) fn update(app: &mut VectorcraftApp, ctx: &egui::Context, area: egui:: Edge::Right => p.x > uncovered.right(), } }); - if over || down || blocked || flyout { + let held = down || blocked || flyout; + if over || held { shown.left_at = None; - } else if moved || pointer.is_none() { + } else if moved || shown.held { + // A hold that ends with the pointer away from them counts as moving away, as closing a + // popup or flyout with Escape does not move the pointer. shown.left_at.get_or_insert(now); } + shown.held = held; match shown.left_at { Some(left) if now - left >= GRACE => { st.shown = None; @@ -160,7 +168,7 @@ pub(super) fn update(app: &mut VectorcraftApp, ctx: &egui::Context, area: egui:: }; if now - since >= DELAY { st.resting = None; - st.shown = Some(Shown { edge, left_at: None }); + st.shown = Some(Shown { edge, left_at: None, held: false }); return Some(edge); } st.resting = Some((edge, since)); @@ -233,7 +241,7 @@ pub(super) fn command(app: &mut VectorcraftApp, params: &Value) -> Result { diff --git a/crates/ui-egui/src/panel_docking/sizes.rs b/crates/ui-egui/src/panel_docking/sizes.rs new file mode 100644 index 0000000000..283b348696 --- /dev/null +++ b/crates/ui-egui/src/panel_docking/sizes.rs @@ -0,0 +1,128 @@ +//! A panel's display sizes: the double triangle at the end of its tab strip steps through them +//! (`window.panel.cycleOptions`). A size is a set of the panel's Hide Options, Hide Thumbnails +//! and Show Options states, the ones its panel menu already sets, so the menu and the control +//! always agree. The sizes go from the largest to the smallest, and the smallest is followed by +//! the largest again. A panel whose parts are in no size's states goes to its largest size. + +use serde_json::{Value, json}; + +use crate::VectorcraftApp; +use crate::panels::{pstate, set_pstate}; + +/// A part of a panel that can be hidden. +#[derive(Clone, Copy, Debug)] +enum Part { + /// A Hide flag the panel keeps with its panel state ([`pstate`]), true while hidden. + Hide(&'static str), + /// The Color panel's Hide Options, kept with the preferences. + ColorOptions, + /// The Flattener Preview panel's Show Options. + FlattenerOptions, +} + +/// A panel that has display sizes: its parts, and the parts each size hides, largest first. +struct Sizes { + panel: &'static str, + parts: &'static [Part], + sizes: &'static [&'static [bool]], +} + +/// Options shown, then hidden. +const OPTIONS: &[&[bool]] = &[&[false], &[true]]; + +/// The panels with display sizes. +const PANELS: &[Sizes] = &[ + Sizes { panel: "align", parts: &[Part::Hide("align-hide-options")], sizes: OPTIONS }, + Sizes { panel: "attributes", parts: &[Part::Hide("attr-hide-options")], sizes: OPTIONS }, + Sizes { panel: "character", parts: &[Part::Hide("ch-hide-options")], sizes: OPTIONS }, + Sizes { panel: "color", parts: &[Part::ColorOptions], sizes: OPTIONS }, + Sizes { panel: crate::panels::flattener_preview::ID, parts: &[Part::FlattenerOptions], sizes: OPTIONS }, + Sizes { panel: "gradient", parts: &[Part::Hide("gradient-hide-options")], sizes: OPTIONS }, + Sizes { panel: "info", parts: &[Part::Hide("info-hide-options")], sizes: OPTIONS }, + Sizes { panel: "paragraph", parts: &[Part::Hide("pa-hide-options")], sizes: OPTIONS }, + Sizes { panel: "stroke", parts: &[Part::Hide("stroke-hide-options")], sizes: OPTIONS }, + Sizes { panel: "transform", parts: &[Part::Hide("xf-hide-options")], sizes: OPTIONS }, + // Thumbnails and options, then thumbnails alone, then neither. + Sizes { + panel: "transparency", + parts: &[Part::Hide("tr-hide-thumbs"), Part::Hide("tr-hide-options")], + sizes: &[&[false, false], &[false, true], &[true, true]], + }, +]; + +fn sizes_of(panel: &str) -> Option<&'static Sizes> { + PANELS.iter().find(|s| s.panel == panel) +} + +/// Does `panel` have display sizes to step through? +pub(crate) fn has_sizes(panel: &str) -> bool { + sizes_of(panel).is_some() +} + +fn hidden(app: &VectorcraftApp, ctx: &egui::Context, part: Part) -> bool { + match part { + Part::Hide(key) => pstate(ctx, key), + Part::ColorOptions => app.ui.color_hide_options, + Part::FlattenerOptions => !app.ui.flattener_preview.show_options, + } +} + +fn set_hidden(app: &mut VectorcraftApp, ctx: &egui::Context, part: Part, hide: bool) { + match part { + Part::Hide(key) => set_pstate(ctx, key, hide), + Part::ColorOptions => app.ui.color_hide_options = hide, + Part::FlattenerOptions => app.ui.flattener_preview.show_options = !hide, + } +} + +/// The size `panel` shows now (0 is the largest), or `None` when its parts match no size. +fn current(app: &VectorcraftApp, ctx: &egui::Context, sizes: &Sizes) -> Option { + let now: Vec = sizes.parts.iter().map(|&part| hidden(app, ctx, part)).collect(); + sizes.sizes.iter().position(|size| *size == now.as_slice()) +} + +/// `window.panel.cycleOptions {panel}`: show `panel` at its next display size, as the double +/// triangle on its tab strip does. An unknown panel, a panel without display sizes, or no panels +/// drawn yet is an error, and then nothing changes. → {panel, size, sizes}: the size shown now +/// (0 is the largest) and how many sizes the panel has. +pub(crate) fn command(app: &mut VectorcraftApp, params: &Value) -> Result { + let raw = params.get("panel").and_then(Value::as_str).unwrap_or_default(); + let panel = super::normalize(raw).ok_or_else(|| format!("unknown panel `{raw}`"))?; + let sizes = sizes_of(panel).ok_or_else(|| format!("`{panel}` has no display sizes to cycle"))?; + let ctx = app.ui_ctx.clone().ok_or("the panels are not shown")?; + let next = current(app, &ctx, sizes).map_or(0, |i| (i + 1) % sizes.sizes.len()); + for (&part, &hide) in sizes.parts.iter().zip(sizes.sizes[next]) { + set_hidden(app, &ctx, part, hide); + } + ctx.request_repaint(); + Ok(json!({"panel": panel, "size": next, "sizes": sizes.sizes.len()})) +} + +/// Width of the double triangle's cell at the start of a group header. +pub(crate) const CELL: f32 = 20.0; + +/// Draw the double triangle for `panel` centered in `cell`; a click shows its next size. +pub(crate) fn button(app: &mut VectorcraftApp, ui: &mut egui::Ui, cell: egui::Rect, panel: &str) { + let rect = egui::Rect::from_center_size(cell.center(), egui::vec2(16.0_f32.min(cell.width()), 22.0_f32.min(cell.height()))); + if !rect.is_positive() { + return; + } + let label = tl!("Cycle Display Sizes"); + let response = ui.interact(rect, ui.scope_id().with(("cycle-display-sizes", panel)), egui::Sense::click()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), label)); + let tokens = crate::theme::Tokens::get(ui.ctx()); + let color = if response.hovered() || response.has_focus() { tokens.text_strong } else { tokens.text_dim }; + let c = rect.center(); + let (w, h, gap) = (3.5, 3.5, 1.5); + let painter = ui.painter().with_clip_rect(rect.intersect(ui.clip_rect())); + let up = vec![egui::pos2(c.x - w, c.y - gap), egui::pos2(c.x + w, c.y - gap), egui::pos2(c.x, c.y - gap - h)]; + let down = vec![egui::pos2(c.x - w, c.y + gap), egui::pos2(c.x, c.y + gap + h), egui::pos2(c.x + w, c.y + gap)]; + for points in [up, down] { + painter.add(egui::Shape::convex_polygon(points, color, egui::Stroke::NONE)); + } + if response.on_hover_text(label).clicked() + && let Err(error) = app.run("window.panel.cycleOptions", json!({"panel": panel})) + { + app.ui.status = error; + } +} diff --git a/crates/ui-egui/src/panel_docking/tests.rs b/crates/ui-egui/src/panel_docking/tests.rs index 2c95ff0e16..266f423838 100644 --- a/crates/ui-egui/src/panel_docking/tests.rs +++ b/crates/ui-egui/src/panel_docking/tests.rs @@ -642,6 +642,45 @@ fn window_panels_peek_rejects_what_it_cannot_show_and_changes_nothing() { h.app.ui.screen_mode = 0; } +#[test] +fn panels_shown_by_window_panels_peek_stay_until_the_pointer_moves_or_leaves_the_window() { + let mut h = Harness::new(); + let wide = hide_with_tab(&mut h); + assert_eq!(h.app.run("window.panels.peek", json!({"side": "right"})).unwrap(), json!("right")); + wait(&mut h, peek::GRACE * 2.0); + assert!(h.tab("properties").is_some(), "with no pointer movement, the panels stay"); + assert_eq!(inspect(&h.app, &h.ctx)["peek"], json!("right")); + h.frame(vec![Event::PointerMoved(wide.center())]); + wait(&mut h, peek::GRACE * 2.0); + assert!(h.tab("properties").is_none(), "the pointer moved away from them, so they hide"); + // The pointer leaving the window counts as moving away. + h.app.run("window.panels.peek", json!({"side": "right"})).unwrap(); + wait(&mut h, peek::GRACE * 2.0); + assert!(h.tab("properties").is_some()); + h.frame(vec![Event::PointerGone]); + wait(&mut h, peek::GRACE * 2.0); + assert!(h.tab("properties").is_none(), "the pointer left the window, so they hide"); + assert_eq!(inspect(&h.app, &h.ctx)["peek"], Value::Null); +} + +#[test] +fn panels_held_by_a_flyout_hide_after_it_closes_with_the_pointer_still_away_from_them() { + let mut h = Harness::new(); + let wide = hide_with_tab(&mut h); + // The pointer rests on the canvas, then outside the window, while a flyout holds the panels. + for away in [vec![Event::PointerMoved(wide.center())], vec![Event::PointerGone]] { + h.app.run("window.panels.peek", json!({"side": "right"})).unwrap(); + h.app.ui.open_panel = Some("swatches".into()); + h.frame(away); + wait(&mut h, peek::GRACE * 2.0); + assert!(h.tab("properties").is_some(), "an open flyout keeps them"); + h.app.ui.open_panel = None; + wait(&mut h, peek::GRACE * 2.0); + assert!(h.tab("properties").is_none(), "the flyout closed with the pointer away from them, so they hide"); + assert_eq!(inspect(&h.app, &h.ctx)["peek"], Value::Null); + } +} + #[test] fn edge_panels_are_the_docked_panels_on_each_side_of_the_canvas() { let layout = default_from(DockTab::ALL[0], &[], false, None, None); @@ -1702,3 +1741,116 @@ fn rail_flyout_collapse_arrow_closes_the_opening_icon_after_switching_tabs() { assert!(craft_ui::docking::flyout::(&h.ctx, area_id()).is_none()); assert_eq!(h.layout(), before, "all tabs and their active state stay in the rail"); } + +/// The texts `panel`'s menu draws, in the harness's context. +fn panel_menu_texts(h: &mut Harness, panel: &str) -> Vec { + fn texts(s: &egui::Shape, out: &mut Vec) { + match s { + egui::Shape::Text(t) => out.push(t.galley.text().trim().to_string()), + egui::Shape::Vec(v) => v.iter().for_each(|s| texts(s, out)), + _ => {} + } + } + let app = &mut h.app; + let mut out = h.ctx.run_ui(egui::RawInput { screen_rect: Some(SCREEN), ..Default::default() }, |ui| { + crate::panels::panel_menu_items(app, ui, panel); + }); + out.textures_delta.clear(); + let mut v = vec![]; + out.shapes.iter().for_each(|c| texts(&c.shape, &mut v)); + v +} + +fn cycle_button(h: &Harness, panel: &str) -> Option { + let panel = panel.to_string(); + h.ctx.read_response(area_id().with(("header", &panel)).with(("cycle-display-sizes", &panel))).map(|r| r.rect) +} + +/// Each panel with display sizes steps between the states its panel menu's Show/Hide Options +/// item sets, and the smallest size goes back to the largest. +#[test] +fn cycle_options_steps_through_the_states_the_panel_menu_sets() { + let mut h = Harness::new(); + for panel in ["align", "attributes", "character", "color", "gradient", "info", "paragraph", "stroke", "transform"] { + assert!(panel_menu_texts(&mut h, panel).iter().any(|t| t == "Hide Options"), "{panel} starts with its options"); + let r = h.app.run("window.panel.cycleOptions", json!({"panel": panel})).unwrap(); + assert_eq!(r, json!({"panel": panel, "size": 1, "sizes": 2}), "{panel}"); + assert!(panel_menu_texts(&mut h, panel).iter().any(|t| t == "Show Options"), "{panel} hides its options"); + let r = h.app.run("window.panel.cycleOptions", json!({"panel": panel})).unwrap(); + assert_eq!(r["size"], 0, "{panel}"); + assert!(panel_menu_texts(&mut h, panel).iter().any(|t| t == "Hide Options"), "{panel} shows them again"); + } + // The Flattener Preview's options start hidden: its first step shows them, as Show Options does. + assert!(!h.app.ui.flattener_preview.show_options); + let r = h.app.run("window.panel.cycleOptions", json!({"panel": "Flattener Preview"})).unwrap(); + assert_eq!(r, json!({"panel": crate::panels::flattener_preview::ID, "size": 0, "sizes": 2})); + assert!(h.app.ui.flattener_preview.show_options); + h.app.run("window.panel.cycleOptions", json!({"panel": crate::panels::flattener_preview::ID})).unwrap(); + assert!(!h.app.ui.flattener_preview.show_options); + // Transparency: thumbnails and options, thumbnails alone, neither, and back. + let shown = |h: &mut Harness| { + let t = panel_menu_texts(h, "transparency"); + (t.iter().any(|t| t == "Hide Thumbnails"), t.iter().any(|t| t == "Hide Options")) + }; + assert_eq!(shown(&mut h), (true, true)); + for (size, want) in [(1, (true, false)), (2, (false, false)), (0, (true, true))] { + let r = h.app.run("window.panel.cycleOptions", json!({"panel": "transparency"})).unwrap(); + assert_eq!((r["size"].clone(), r["sizes"].clone()), (json!(size), json!(3))); + assert_eq!(shown(&mut h), want, "size {size}"); + } + // Options hidden with the thumbnails shown matches no size, so the next step is the largest. + crate::panels::set_pstate(&h.ctx, "tr-hide-thumbs", true); + assert_eq!(h.app.run("window.panel.cycleOptions", json!({"panel": "transparency"})).unwrap()["size"], 0); + assert_eq!(shown(&mut h), (true, true)); +} + +/// An unknown panel, a panel without display sizes or a missing `panel` is an error, and the +/// panels keep their sizes. +#[test] +fn cycle_options_rejects_panels_without_sizes() { + let mut h = Harness::new(); + for (params, error) in [ + (json!({"panel": "nope"}), "unknown panel `nope`"), + (json!({}), "unknown panel ``"), + (json!({"panel": 3}), "unknown panel ``"), + (json!({"panel": "layers"}), "`layers` has no display sizes to cycle"), + (json!({"panel": "swatches"}), "`swatches` has no display sizes to cycle"), + ] { + assert_eq!(h.app.run("window.panel.cycleOptions", params.clone()).unwrap_err(), error, "{params}"); + } + assert!(panel_menu_texts(&mut h, "stroke").iter().any(|t| t == "Hide Options")); + assert!(!h.app.ui.color_hide_options); +} + +/// The double triangle shows on the tab strip of a panel with display sizes, docked or floating, +/// and a click on it shows the panel's next size; other panels have none. +#[test] +fn the_double_triangle_on_the_tab_strip_cycles_the_display_sizes() { + let mut h = Harness::new(); + h.ctx.enable_accesskit(); + h.frame(vec![]); + assert!(cycle_button(&h, "properties").is_none() && cycle_button(&h, "layers").is_none(), "the main column's panels have no sizes"); + h.app.run("window.panel.float", json!({"panel": "stroke"})).unwrap(); + for _ in 0..3 { + h.frame(vec![]); + } + let control = cycle_button(&h, "stroke").expect("a floating Stroke panel has the double triangle"); + assert!(h.nodes.iter().any(|(_, node)| node.label() == Some("Cycle Display Sizes")), "screen readers name it"); + let menu = h.ctx.read_response(area_id().with(("header", &"stroke".to_string())).with(("panel-menu", &"stroke".to_string()))).unwrap().rect; + assert!(!menu.intersects(control), "the double triangle and the menu have separate hit targets"); + h.click(control.center()); + assert!(crate::panels::pstate::(&h.ctx, "stroke-hide-options"), "a click hides the options"); + assert!(floating_window(&h.layout(), "stroke").is_some(), "the panel stays where it is"); + h.click(control.center()); + assert!(!crate::panels::pstate::(&h.ctx, "stroke-hide-options"), "a second click shows them again"); + // A docked panel's tab strip has it too, and a floating panel without sizes does not. + h.app.run("window.panel.dock", json!({"panel": "color", "anchor": "layers", "zone": "below"})).unwrap(); + h.app.run("window.panel.float", json!({"panel": "swatches"})).unwrap(); + for _ in 0..3 { + h.frame(vec![]); + } + let control = cycle_button(&h, "color").expect("a docked Color panel has the double triangle"); + h.click(control.center()); + assert!(h.app.ui.color_hide_options); + assert!(cycle_button(&h, "swatches").is_none()); +} diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index a36e9c245d..487d501054 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -190,6 +190,7 @@ pub fn show_icon_panel(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { learn::ID => learn::show(app, ui), crate::addons::cleanup::ID => crate::addons::cleanup::show(app, ui), crate::addons::color::ID => crate::addons::color::show(app, ui), + crate::addons::packaging::ID => crate::addons::packaging::show(app, ui), crate::addons::pathtools::ID => crate::addons::pathtools::show(app, ui), crate::addons::pathtools::shape::ID => crate::addons::pathtools::shape::show(app, ui), crate::addons::pen::ID => crate::addons::pen::show(app, ui), @@ -245,6 +246,7 @@ pub fn panel_menu_items(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) -> bool variables::ID => variables::menu(app, ui), script_console::ID => script_console::menu(app, ui), "actions" => actions::menu(app, ui), + crate::addons::packaging::ID => crate::addons::packaging::panel_menu(app, ui), id if library_panel::parse(id).is_some() => library_panel::menu(app, ui, id), _ => return false, } diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index a7f32611cc..1c5509e9ae 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -4237,6 +4237,125 @@ mod tests { assert_eq!(r["skipped"], json!([{"action": "A", "step": "group"}, {"action": "A", "step": "Ungroup"}])); assert_eq!(r["leftOut"], 2); } + + /// A Set Selection step written from scratch, as `/event-N` text: its label (none when empty), + /// whether it is on, and its recorded values, each the text inside a `/parameter-N` block. + fn set_selection_event(n: usize, label: &str, on: bool, values: &[String]) -> String { + let hex = |t: &[u8]| format!("[ {} {} ]", t.len(), t.iter().map(|b| format!("{b:02x}")).collect::()); + let label = if label.is_empty() { String::new() } else { format!("/localizedName {} ", hex(label.as_bytes())) }; + let params: String = values.iter().enumerate().map(|(i, v)| format!("/parameter-{} {{ {v} }} ", i + 1)).collect(); + format!( + "/event-{n} {{ /useRulersIn1stQuadrant 0 /internalName (adobe_setSelection) {label}/isOn {} /isOff 0 /parameterCount {} {params}}} ", + u8::from(on), + values.len() + ) + } + + /// The recorded values of a Set Selection step: the note's bytes, then Whole Word and Case + /// Sensitive. + fn set_selection_values(note: &[u8], whole_word: u8, case_sensitive: u8) -> Vec { + let hex = |t: &[u8]| format!("[ {} {} ]", t.len(), t.iter().map(|b| format!("{b:02x}")).collect::()); + vec![ + format!("/key 1952807028 /showInPalette 4294967295 /type (ustring) /value {}", hex(note)), + format!("/key 2003792484 /showInPalette 4294967295 /type (boolean) /value {whole_word}"), + format!("/key 1667330917 /showInPalette 4294967295 /type (boolean) /value {case_sensitive}"), + ] + } + + /// Load Actions… reads an `.aia` Set Selection step, found by its internal name whatever its + /// label, as a Select Object step with its note (trimmed), Case Sensitive and Whole Word, in any + /// order; a step that is off stays excluded. The set saves to VectorCraft's own file and loads + /// back the same, and playing it selects the objects with that note. + #[test] + fn load_actions_reads_set_selection_steps_as_select_object() { + let mut reordered = set_selection_values("Größe ✓".as_bytes(), 1, 0); + reordered.reverse(); + let events = [ + set_selection_event(1, "Set Selection", true, &set_selection_values(b" Badge front ", 0, 1)), + set_selection_event(2, "Auswahl festlegen", true, &reordered), + set_selection_event(3, "", false, &set_selection_values(b"Off", 1, 1)), + ] + .concat(); + let text = format!("/version 3 /name [ 5 4e6f746573 ] /actionCount 1 /action-1 {{ /name [ 1 41 ] /eventCount 3 {events}}}"); + let mut app = app_with_sets(); + let r = app.run(LOAD_SET, json!({ "data": text })).unwrap(); + assert_eq!((r["leftOut"].clone(), r["skipped"].clone()), (json!(0), json!([]))); + let step = |note: &str, case_sensitive: bool, whole_word: bool| { + (SELECT_OBJECT_STEP.to_string(), json!({"note": note, "caseSensitive": case_sensitive, "wholeWord": whole_word})) + }; + let expected = [step("Badge front", true, false), step("Größe ✓", false, true), step("Off", true, true)]; + assert_eq!(app.ui.action_sets[3].actions[0].steps, expected); + assert_eq!(app.ui.action_sets[3].actions[0].excluded_steps, [2].into()); + + let saved = files::write_set(&app.ui.action_sets[3]); + assert!(saved.contains("\"version\": 4"), "{saved}"); + app.run(LOAD_SET, json!({ "data": saved })).unwrap(); + assert_eq!(app.ui.action_sets[4].actions[0].steps, expected); + assert_eq!(app.ui.action_sets[4].actions[0].excluded_steps, [2].into()); + + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let mut ids = vec![]; + for x in [0, 50] { + ids.push(app.run("shape.rectangle", json!({"x": x, "y": 0, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap()); + } + app.run("attributes.set", json!({"ids": [ids[1]], "note": "Badge front"})).unwrap(); + app.run("select.all", json!({})).unwrap(); + app.ui.action_sets[3].actions[0].excluded_steps = [1, 2].into(); + play(&mut app, 3, 0).unwrap(); + let selected: Vec = app.session.active().unwrap().selection.objects.iter().map(|id| id.0).collect(); + assert_eq!(selected, [ids[1]], "the step selected the object with the note"); + } + + /// A Set Selection step whose recorded values are not exactly the note (UTF-8 text, not empty + /// once trimmed, at most 1,024 bytes) and the two options (each 0 or 1), with the right types and + /// no other value, is left out, listed by its label (else its internal name) and counted; no step + /// comes in with a missing option filled in. A value whose byte count is wrong refuses the file. + #[test] + fn set_selection_steps_with_bad_values_are_left_out() { + let good = || set_selection_values(b"Badge", 0, 0); + let with = |i: usize, value: &str| { + let mut v = good(); + v[i] = value.to_string(); + v + }; + let mut extra = good(); + extra.push("/key 1 /type (boolean) /value 0".into()); + let mut duplicate = good(); + duplicate[0] = good()[2].clone(); + let bad: Vec> = vec![ + good()[1..].to_vec(), + vec![good()[0].clone(), good()[1].clone()], + extra, + duplicate, + with(0, "/key 1952807028 /type (ustring) /value [ 2 c328 ]"), + with(0, "/key 1952807028 /type (ustring) /value [ 3 202020 ]"), + with(0, &format!("/key 1952807028 /type (ustring) /value [ 1025 {} ]", "61".repeat(1025))), + with(0, "/key 1952807028 /type (text) /value [ 5 4261646765 ]"), + with(0, "/key 1952807028 /type (ustring) /value 5"), + with(1, "/key 2003792484 /type (boolean) /value 2"), + with(1, "/key 2003792484 /type (integer) /value 1"), + with(2, "/key 1667330917 /type (boolean) /value 1.0"), + with(2, "/key 1667330917 /type (boolean)"), + with(2, "/key 1 /type (boolean) /value 1"), + ]; + let events: String = bad.iter().enumerate().map(|(i, values)| set_selection_event(i + 1, "Set Selection", true, values)).collect(); + let events = events + &set_selection_event(bad.len() + 1, "", true, &[]); + let text = format!("/version 3 /name [ 3 426164 ] /action-1 {{ /name [ 1 41 ] {events}}}"); + let mut app = app_with_sets(); + let r = app.run(LOAD_SET, json!({ "data": text })).unwrap(); + assert!(app.ui.action_sets[3].actions[0].steps.is_empty(), "{:?}", app.ui.action_sets[3].actions[0].steps); + assert_eq!(r["leftOut"], bad.len() + 1); + let names: Vec<&str> = r["skipped"].as_array().unwrap().iter().map(|s| s["step"].as_str().unwrap()).collect(); + let mut expected = vec!["Set Selection"; bad.len()]; + expected.push("adobe_setSelection"); + assert_eq!(names, expected); + assert_eq!(app.ui.status, format!("Loaded “Bad”: {} steps were left out", bad.len() + 1)); + + let wrong_count = set_selection_event(1, "Set Selection", true, &with(0, "/key 1952807028 /type (ustring) /value [ 6 4261646765 ]")); + let text = format!("/version 3 /action-1 {{ {wrong_count}}}"); + assert_eq!(app.run(LOAD_SET, json!({ "data": text })).unwrap_err(), "the action set file can't be read in full"); + assert_eq!(app.ui.action_sets.len(), 4, "no set added"); + } /// Load Actions… picks action set files of both kinds, and a set another app saved without a /// name takes the file's name, or `Actions` when there is no file; one named like a set in the /// panel gets the next free number. A file that isn't UTF-8 still reads. A set past the reader's diff --git a/crates/ui-egui/src/panels/actions/files.rs b/crates/ui-egui/src/panels/actions/files.rs index 0d19a0bf2b..5bdd0b9a98 100644 --- a/crates/ui-egui/src/panels/actions/files.rs +++ b/crates/ui-egui/src/panels/actions/files.rs @@ -15,7 +15,7 @@ //! version 6 so older builds refuse them rather than fail at that step. Other sets use version 1, and //! earlier version 1 to 5 files still work. //! Load Actions… also reads the action sets another app saves as text (`.aia`, through -//! `actionSet.read`). +//! `actionSet.read`), a Set Selection step as a Select Object step. use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; @@ -398,6 +398,45 @@ fn step_commands() -> std::collections::HashMap> { by_label } +/// The `/internalName` of a step of another app's action set that selects objects by their note: the +/// Set Selection step. +const SET_SELECTION: &str = "adobe_setSelection"; // brand-ok: the step's internal name in the file format + +/// The `/key` of a Set Selection step's note (`text`), of its Whole Word option (`word`) and of its +/// Case Sensitive option (`case`): four characters read as a big-endian number. +const NOTE_KEY: i64 = 0x7465_7874; +const WHOLE_WORD_KEY: i64 = 0x776f_7264; +const CASE_SENSITIVE_KEY: i64 = 0x6361_7365; + +/// The Select Object step ([`super::SELECT_OBJECT_STEP`]) a Set Selection step of `actionSet.read`'s +/// answer stands for. The step must have exactly three recorded values, all kept: the note, of type +/// `ustring` and UTF-8, and Whole Word and Case Sensitive, each of type `boolean` and 0 or 1. The note +/// is as [`super::select_object_params`] takes it (trimmed, not empty, at most 1,024 bytes). Anything +/// else stands for nothing. +fn select_object_step(step: &Value) -> Option<(String, Value)> { + let values = step.get("values").and_then(Value::as_array)?; + if values.len() != 3 || step.get("params").and_then(Value::as_u64) != Some(3) { + return None; + } + let value = |key: i64, kind: &str| { + let mut found = values.iter().filter(|v| v.get("key").and_then(Value::as_i64) == Some(key)); + let v = found.next().filter(|v| v.get("type").and_then(Value::as_str) == Some(kind))?; + if found.next().is_some() { + return None; + } + v.get("value") + }; + let flag = |key: i64| match value(key, "boolean")?.as_i64()? { + 0 => Some(false), + 1 => Some(true), + _ => None, + }; + let note = value(NOTE_KEY, "ustring")?.as_str()?; + let params = json!({"note": note, "caseSensitive": flag(CASE_SENSITIVE_KEY)?, "wholeWord": flag(WHOLE_WORD_KEY)?}); + let (note, case_sensitive, whole_word) = super::select_object_params(¶ms).ok()?; + Some((super::SELECT_OBJECT_STEP.to_string(), json!({"note": note, "caseSensitive": case_sensitive, "wholeWord": whole_word}))) +} + /// The command a step of another app's action set stands for ([`step_commands`]). #[cfg(test)] pub(super) fn step_command(label: &str) -> Option<&'static str> { @@ -414,8 +453,9 @@ struct AiaLoad { } /// The set of `read`, `actionSet.read`'s answer, named `name` when the file gives none. A step comes -/// in as the command it stands for ([`step_name`], [`step_commands`]), with no params, and excluded -/// from playback when it is off in the file. An action with no name is called `Action N`. +/// in as the command it stands for ([`step_name`], [`step_commands`]), with no params, or a Set +/// Selection step as a Select Object step ([`select_object_step`]), and excluded from playback when +/// it is off in the file. An action with no name is called `Action N`. fn aia_set(read: &Value, name: &str) -> AiaLoad { let (mut skipped, mut left_out) = (vec![], 0usize); let commands = step_commands(); @@ -432,7 +472,12 @@ fn aia_set(read: &Value, name: &str) -> AiaLoad { let (mut steps, mut excluded_steps) = (vec![], std::collections::BTreeSet::new()); for s in a.get("steps").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default() { let (name, can_stand) = step_name(s); - let Some(id) = commands.get(&bare_label(&name)).copied().flatten().filter(|_| can_stand) else { + let step = if s.get("name").and_then(Value::as_str) == Some(SET_SELECTION) { + select_object_step(s) + } else { + commands.get(&bare_label(&name)).copied().flatten().filter(|_| can_stand).map(|id| (id.to_string(), json!({}))) + }; + let Some(step) = step else { left_out += 1; if skipped.len() < MAX_SKIPPED { skipped.push(json!({ "action": action, "step": name })); @@ -442,7 +487,7 @@ fn aia_set(read: &Value, name: &str) -> AiaLoad { if s.get("on").and_then(Value::as_bool) == Some(false) { excluded_steps.insert(steps.len()); } - steps.push((id.to_string(), json!({}))); + steps.push(step); } Action { excluded_steps, ..Action::new(action, steps) } }) @@ -496,7 +541,8 @@ fn load_aia(app: &mut VectorcraftApp, params: Value) -> Result { /// /// An action set another app saved as text (`.aia`, read with `actionSet.read`) comes in with its /// actions and the steps that stand for a VectorCraft command ([`step_name`], [`step_commands`]), -/// with no params; a step that is off in the file is excluded from playback. A set with no name is +/// with no params, and its Set Selection steps as Select Object steps ([`select_object_step`]); a +/// step that is off in the file is excluded from playback. A set with no name is /// called after the file, else `Actions`. The other steps are left out and listed, and the status /// bar says how many → `{set, name, actions, skipped: [{action, step}] (at most 1,000), leftOut: n}`. /// Such a file that `actionSet.read` marks `truncated` is refused, and so is one whose set Save diff --git a/crates/ui-egui/src/panels/asset_export.rs b/crates/ui-egui/src/panels/asset_export.rs index 39b3a0ea85..3fe249b7e3 100644 --- a/crates/ui-egui/src/panels/asset_export.rs +++ b/crates/ui-egui/src/panels/asset_export.rs @@ -7,7 +7,7 @@ //! desktop with Background Export on, on the background thread); the web downloads them. The //! screen button opens Export for Screens on its Assets tab. //! -//! Export 3D Object (the panel menu) collects the selected objects with a 3D effect as 3D assets, +//! Export 3D Object (the panel menu, and the 3D and Materials panel's button) collects the selected objects with a 3D effect as 3D assets, //! 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. //! @@ -207,6 +207,16 @@ fn run(app: &mut VectorcraftApp, cmd: &str, params: Value) -> Option { app.run(cmd, params).map_err(|e| app.status(e)).ok() } +/// Export 3D Object: collects objects `ids` (else the selection) as 3D assets (`assets.add3D`), and +/// selects their assets in the panel, including those that were assets already. +pub(crate) fn add_3d(app: &mut VectorcraftApp, ctx: &egui::Context, ids: Option<&[u64]>) -> Result<(), String> { + let p = ids.map_or_else(|| json!({}), |ids| json!({ "ids": ids })); + let r = app.run("assets.add3D", p)?; + let assets: Vec = r["assets"].as_array().into_iter().flatten().filter_map(Value::as_u64).collect(); + set_pstate(ctx, SELECTED, assets); + Ok(()) +} + /// Collect `ids` (else the selection) as assets (one of them all with `single`), and select them /// in the panel. fn collect(app: &mut VectorcraftApp, ctx: &egui::Context, ids: Option>, single: bool) { @@ -630,10 +640,9 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { collect(app, &ctx, None, false); } if menu_item(ui, tl!("Export 3D Object"), has_art, false) - && let Some(r) = run(app, "assets.add3D", json!({})) + && let Err(e) = add_3d(app, &ctx, None) { - let ids: Vec = r["assets"].as_array().into_iter().flatten().filter_map(Value::as_u64).collect(); - set_pstate(&ctx, SELECTED, ids); + app.status(e); } ui.separator(); if menu_item(ui, tl!("Select All Assets"), !all.is_empty(), false) { diff --git a/crates/ui-egui/src/panels/character.rs b/crates/ui-egui/src/panels/character.rs index 32de20ec95..746a8fbdf4 100644 --- a/crates/ui-egui/src/panels/character.rs +++ b/crates/ui-egui/src/panels/character.rs @@ -28,6 +28,8 @@ pub const SCALE_PRESETS: [f64; 8] = [25.0, 50.0, 75.0, 90.0, 100.0, 110.0, 125.0 pub const AKI_PRESETS: [f64; 4] = [0.0, 250.0, 500.0, 1000.0]; /// Tsume presets, in percent. pub const TSUME_PRESETS: [f64; 5] = [0.0, 25.0, 50.0, 75.0, 100.0]; +/// Adjust Horizontal and Vertical Diacritic Position presets, in thousandths of an em. +pub const DIACRITIC_PRESETS: [f64; 7] = [-200.0, -100.0, -50.0, 0.0, 50.0, 100.0, 200.0]; /// The stored character style: the selected range's (or the caret's) while the Type /// tool edits text, else the first selected text object's first run (including groups). With it, the paragraph @@ -881,9 +883,10 @@ fn cell(ui: &mut Ui, label: &str, tip: &str, add: impl FnOnce(&mut Ui)) { /// The Character panel's grid of fields, `w` wide: Font Size, Leading, Kerning and Tracking, /// then with `more` the scales, Baseline Shift and Character Rotation, and a row with the /// Anti-aliasing Method dropdown under Character Rotation (`s`: the style shown), and with Show East -/// Asian Options on a row with Insert Aki Left and Right and a row with Tsume. With Show Font -/// Height Options on, a row under Font Size holds the Set Font Height Reference dropdown. The -/// Properties panel shows its first rows. +/// Asian Options on a row with Insert Aki Left and Right and a row with Tsume, and with Show Indic +/// Options (the Middle Eastern options) on a row with Adjust Horizontal and Vertical Diacritic +/// Position. With Show Font Height Options on, a row under Font Size holds the Set Font Height +/// Reference dropdown. The Properties panel shows its first rows. pub(crate) fn metrics_grid(app: &mut VectorcraftApp, ui: &mut Ui, id: &str, s: &CharStyle, w: f32, more: bool) { let fw = ((w - 66.0) / 2.0).clamp(60.0, 100.0); let unit = app.session.type_unit(); @@ -986,6 +989,24 @@ pub(crate) fn metrics_grid(app: &mut VectorcraftApp, ui: &mut Ui, id: &str, s: & }); ui.end_row(); } + // Adjust Horizontal and Vertical Diacritic Position, with the Middle Eastern options: the + // marks of the characters move across and up, in thousandths of an em. + if app.session.prefs.show_indic_options { + let max = vectorcraft_doc::text::MAX_DIACRITIC_POSITION; + for (field, label, key, icon) in [ + ("ch-diacritic-h", tl!("Adjust Horizontal Diacritic Position"), "diacriticHorizontal", "´↔"), + ("ch-diacritic-v", tl!("Adjust Vertical Diacritic Position"), "diacriticVertical", "´↕"), + ] { + cell(ui, icon, label, |ui| { + let value = shared(app, |s| if key == "diacriticHorizontal" { s.diacritic_horizontal } else { s.diacritic_vertical }); + if let Some(v) = widgets::spin_plain(ui, field, value, "", 0, fw, 10.0, -max, &DIACRITIC_PRESETS) { + // The field stops at the largest value the command takes. + format(app, json!({ key: v.min(max) })); + } + }); + } + ui.end_row(); + } }); } @@ -1730,7 +1751,8 @@ fn fractional_widths_on(app: &VectorcraftApp) -> bool { /// character alignment, Proportional Metrics, Tate-chu-yoko, Warichu, Standard Vertical Roman Alignment and /// No Break off, Tate-chu-yoko Settings Up/Down and Left/Right 0, the default Warichu Settings (2 lines, no /// line gap, 50%, Auto alignment), Insert Aki Left and Right 0, Tsume 0, the Default character direction, -/// Kashidas on, the Default digits and the Em Box font height reference, whether or not Show East Asian +/// Kashidas on, the Default digits, Adjust Horizontal and Vertical Diacritic Position 0 and the Em Box +/// font height reference, whether or not Show East Asian /// Options, Show Indic Options and Show Font Height Options are on. Inside an undo group that is /// already open, the reset is part of that group's step. fn reset_panel(app: &mut VectorcraftApp) { @@ -1752,7 +1774,8 @@ fn reset_panel(app: &mut VectorcraftApp) { "tsume": d.tsume, "warichu": d.warichu, "warichuLines": d.warichu_lines, "warichuGap": d.warichu_gap, "warichuScale": d.warichu_scale, "warichuAlign": d.warichu_align, "standardVerticalRoman": d.standard_vertical_roman, "noBreak": d.no_break, "charDirection": "default", "kashidas": d.kashidas, - "digits": d.digits, "fontHeightReference": d.font_height_reference + "digits": d.digits, "diacriticHorizontal": d.diacritic_horizontal, "diacriticVertical": d.diacritic_vertical, + "fontHeightReference": d.font_height_reference }), ); set_anti_alias(app, TypeAntiAlias::Sharp); diff --git a/crates/ui-egui/src/panels/character/tests.rs b/crates/ui-egui/src/panels/character/tests.rs index adaf523e53..1e3e6acec4 100644 --- a/crates/ui-egui/src/panels/character/tests.rs +++ b/crates/ui-egui/src/panels/character/tests.rs @@ -782,6 +782,57 @@ fn insert_aki_fields_show_with_the_east_asian_options() { assert!(left(&app).iter().all(|v| *v == 1000.0), "{:?}", left(&app)); } +/// Adjust Horizontal and Vertical Diacritic Position are fields of the panel with the Middle +/// Eastern options only, and show the selected characters' values, blank where they differ. A value +/// typed past -1000 sets -1000. Bad values sent to the commands are errors that change nothing. +#[test] +fn diacritic_position_fields_show_with_the_middle_eastern_options() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let id = app.run("text.create", json!({"x": 20, "y": 50, "text": "بَبَ"})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.run("text.setFormat", json!({"diacriticHorizontal": 125, "diacriticVertical": -375})).unwrap(); + let text = crate::tests_labels::painted_text(&mut app, show); + assert!(!text.contains("´↔") && !text.contains("-375"), "{text}"); + app.session.prefs.show_indic_options = true; + let text = crate::tests_labels::painted_text(&mut app, show); + assert!(text.contains("´↔") && text.contains("´↕") && text.contains("125") && text.contains("-375"), "{text}"); + let undo = app.session.active().unwrap().history.undo.len(); + let doc = app.session.active().unwrap().doc.clone(); + for (cmd, params) in [ + ("text.setFormat", json!({"diacriticHorizontal": 1000.5})), + ("text.setFormat", json!({"diacriticVertical": "up"})), + ("text.setRangeStyle", json!({"id": id, "start": 0, "end": 2, "diacriticVertical": -1001})), + ("text.setRangeStyle", json!({"id": id, "start": 0, "end": 2, "diacriticHorizontal": true})), + ] { + let error = app.run(cmd, params.clone()).unwrap_err().to_string(); + assert!(error.contains("`diacritic"), "{cmd} {params}: {error}"); + } + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert!(app.session.active().unwrap().doc == doc); + // Setting the value the characters already have records no undo step. + app.run("text.setFormat", json!({"diacriticVertical": -375})).unwrap(); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + // Only the first letter and its fatha have -375: the Vertical field is blank. + app.run("text.setRangeStyle", json!({"id": id, "start": 4, "end": 8, "diacriticVertical": 0})).unwrap(); + let text = crate::tests_labels::painted_text(&mut app, show); + assert!(text.contains("125") && !text.contains("-375"), "{text}"); + use super::super::tests_appearance::{click, frame_events, text_rect}; + let ctx = egui::Context::default(); + let texts = frame_events(&ctx, &mut app, vec![], show); + click(&ctx, &mut app, text_rect(&texts, "125").center(), show); + let key = |key, modifiers| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }; + frame_events(&ctx, &mut app, vec![key(egui::Key::A, egui::Modifiers::COMMAND)], show); + frame_events(&ctx, &mut app, vec![egui::Event::Text("-1500".into())], show); + frame_events(&ctx, &mut app, vec![key(egui::Key::Enter, egui::Modifiers::NONE)], show); + frame_events(&ctx, &mut app, vec![], show); + let horizontal = |app: &VectorcraftApp| match &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => t.runs.iter().map(|r| r.style.diacritic_horizontal).collect::>(), + _ => panic!("text"), + }; + assert!(horizontal(&app).iter().all(|v| *v == -1000.0), "{:?}", horizontal(&app)); +} + /// Tsume is a field of the panel with the East Asian options only, and shows the selected /// characters' value, blank where they differ. A value typed past 100 sets 100. #[test] @@ -1487,6 +1538,8 @@ fn reset_panel_resets_every_attribute_but_the_font() { s.char_direction != d.char_direction, s.digits != d.digits, s.font_height_reference != d.font_height_reference, + s.diacritic_horizontal != d.diacritic_horizontal, + s.diacritic_vertical != d.diacritic_vertical, ] }; let custom = |app: &mut VectorcraftApp| { @@ -1496,16 +1549,17 @@ fn reset_panel_resets_every_attribute_but_the_font() { "id": id, "tracking": 50, "leading": 30, "kerning": 20, "baselineShift": 3, "hScale": 120, "vScale": 90, "rotation": 15, "underline": true, "strikethrough": true, "allCaps": true, "smallCaps": true, "position": "superscript", "charAlign": "emBoxCenter", "proportionalMetrics": true, "tateChuYoko": true, "tcyUpDown": 2, "tcyLeftRight": -3, - "akiLeft": 250, "akiRight": 500, "tsume": 50, "standardVerticalRoman": true, "noBreak": true, "charDirection": "rightToLeft", "digits": "hindi", "fontHeightReference": "capHeight" + "akiLeft": 250, "akiRight": 500, "tsume": 50, "standardVerticalRoman": true, "noBreak": true, "charDirection": "rightToLeft", "digits": "hindi", "fontHeightReference": "capHeight", + "diacriticHorizontal": 120, "diacriticVertical": -80 }), ) .unwrap(); }; let plain = runs(&app)[0].1.clone(); - assert_eq!(differs(&plain, &CharStyle::default()), [false; 25]); + assert_eq!(differs(&plain, &CharStyle::default()), [false; 27]); custom(&mut app); let styled = runs(&app)[0].1.clone(); - assert_eq!(differs(&styled, &CharStyle::default()), [true; 25]); + assert_eq!(differs(&styled, &CharStyle::default()), [true; 27]); app.run("select.set", json!({"ids": [id]})).unwrap(); reset_panel(&mut app); assert_eq!(runs(&app), [("One 12".to_string(), plain.clone())]); diff --git a/crates/ui-egui/src/panels/paragraph.rs b/crates/ui-egui/src/panels/paragraph.rs index 100540cbd0..3f1a56cee5 100644 --- a/crates/ui-egui/src/panels/paragraph.rs +++ b/crates/ui-egui/src/panels/paragraph.rs @@ -54,15 +54,29 @@ pub(crate) fn align(app: &mut VectorcraftApp, justify: &str) -> Result Result { text_style(app).ok_or("select some type first")?; - let id = if shared_composer(app) == Some(Composer::EveryLine) { "singleLine" } else { "everyLine" }; + let to_single = shared_para(app, |p| p.composer.is_single_line()) == Some(false); + let standard = shared_para(app, |p| p.composer.shapes_complex_scripts()) == Some(false); + let base = if standard { Composer::StandardEveryLine } else { Composer::EveryLine }; + let id = composer_id(base.with_breaking(to_single)); format(app, json!({ "composer": id })); Ok(json!(id)) } +/// The `text.setFormat` value of `composer`. +fn composer_id(composer: Composer) -> &'static str { + match composer { + Composer::SingleLine => "singleLine", + Composer::EveryLine => "everyLine", + Composer::StandardSingleLine => "standardSingleLine", + Composer::StandardEveryLine => "standardEveryLine", + } +} + /// `type.hyphenate` (Cmd+Alt+Shift+H): what the Hyphenate checkbox does, on the paragraphs the /// panel acts on. Returns whether they now hyphenate. pub(crate) fn toggle_hyphenate(app: &mut VectorcraftApp) -> Result { @@ -874,11 +888,14 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { } ui.separator(); let composer = shared_composer(app); - for (c, label, id) in - [(Composer::SingleLine, tl!("Single-line Composer"), "singleLine"), (Composer::EveryLine, tl!("Every-line Composer"), "everyLine")] - { + for (c, label) in [ + (Composer::SingleLine, tl!("Middle Eastern & South Asian Single-line Composer")), + (Composer::EveryLine, tl!("Middle Eastern & South Asian Every-line Composer")), + (Composer::StandardSingleLine, tl!("Standard Single-line Composer")), + (Composer::StandardEveryLine, tl!("Standard Every-line Composer")), + ] { if menu_item(ui, label, has, composer == Some(c)) { - format(app, json!({ "composer": id })); + format(app, json!({ "composer": composer_id(c) })); } } ui.separator(); diff --git a/crates/ui-egui/src/panels/paragraph/tests.rs b/crates/ui-egui/src/panels/paragraph/tests.rs index 25c05ce3fc..11fd7fbafc 100644 --- a/crates/ui-egui/src/panels/paragraph/tests.rs +++ b/crates/ui-egui/src/panels/paragraph/tests.rs @@ -82,6 +82,83 @@ fn paragraph_mixed_composer_checks_neither_menu_item() { assert_eq!(shared_composer(&app), Some(Composer::EveryLine)); } +/// Cmd+Alt+Shift+C switches between Single-line and Every-line and keeps what each paragraph's +/// composer does with complex scripts: a Standard composer toggles to the other Standard one. +#[test] +fn toggling_the_line_composer_keeps_the_shaping() { + let (mut app, id) = editing_text("A\nB\n"); + for (from, first, second) in [ + ("standardEveryLine", "standardSingleLine", "standardEveryLine"), + ("everyLine", "singleLine", "everyLine"), + ("standardSingleLine", "standardEveryLine", "standardSingleLine"), + ] { + app.run("text.setFormat", json!({"id": id, "composer": from})).unwrap(); + app.session.set_tool_option("selectAll", &json!(true)); + assert_eq!(toggle_composer(&mut app).unwrap(), json!(first), "{from}"); + assert_eq!(toggle_composer(&mut app).unwrap(), json!(second), "{from} again"); + } + // Paragraphs that break differently take Every-line, as before the Standard composers existed. + app.run("text.setFormat", json!({"id": id, "composer": "standardSingleLine"})).unwrap(); + app.run("text.setFormat", json!({"id": id, "start": 2, "end": 3, "composer": "singleLine"})).unwrap(); + app.session.set_tool_option("selectAll", &json!(true)); + assert_eq!(toggle_composer(&mut app).unwrap(), json!("everyLine")); + // Paragraphs that both break every-line but differ in shaping: Single-line, Middle Eastern & South Asian. + app.run("text.setFormat", json!({"id": id, "composer": "everyLine"})).unwrap(); + app.run("text.setFormat", json!({"id": id, "start": 2, "end": 3, "composer": "standardEveryLine"})).unwrap(); + app.session.set_tool_option("selectAll", &json!(true)); + assert_eq!(toggle_composer(&mut app).unwrap(), json!("singleLine")); +} + +/// The Paragraph panel menu lists the four composers, and ticks the one every selected paragraph has. +#[test] +fn the_paragraph_menu_sets_each_of_the_four_composers() { + let (mut app, id) = editing_text("A\nB\n"); + app.session.set_tool_option("selectAll", &json!(true)); + let ctx = egui::Context::default(); + let items = |app: &mut VectorcraftApp| { + let mut seen = vec![]; + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| menu(app, ui)); + out.textures_delta.clear(); + for shape in out.shapes { + collect_texts(&shape.shape, &mut seen); + } + seen + }; + fn collect_texts(shape: &egui::Shape, out: &mut Vec) { + match shape { + egui::Shape::Vec(v) => v.iter().for_each(|s| collect_texts(s, out)), + egui::Shape::Text(t) => out.push(t.galley.text().to_string()), + _ => {} + } + } + let labels = [ + ("singleLine", "Middle Eastern & South Asian Single-line Composer"), + ("everyLine", "Middle Eastern & South Asian Every-line Composer"), + ("standardSingleLine", "Standard Single-line Composer"), + ("standardEveryLine", "Standard Every-line Composer"), + ]; + // The menu lists all four, each row ticked (and only that one) when every selected paragraph has it. + for (value, _) in labels { + app.run("text.setFormat", json!({"id": id, "composer": value})).unwrap(); + app.session.set_tool_option("selectAll", &json!(true)); + let texts = items(&mut app); + for (v, label) in labels { + let row = if v == value { format!("✓ {label}") } else { format!(" {label}") }; + assert!(texts.contains(&row), "{value}: {row:?} in {texts:?}"); + } + } + // Choosing a row sets its composer: the row is a `text.setFormat {composer}` with the row's id. + for (value, want) in [ + ("standardEveryLine", Composer::StandardEveryLine), + ("singleLine", Composer::SingleLine), + ("standardSingleLine", Composer::StandardSingleLine), + ] { + app.run("text.setFormat", json!({"id": id, "composer": value})).unwrap(); + assert_eq!(shared_composer(&app), Some(want), "{value}"); + assert_eq!(composer_id(want), value); + } +} + #[test] fn paragraph_mixed_hyphenate_checks_off() { let (mut app, id) = editing_text("A\nB\n"); diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 99c444def1..500b967469 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -69,6 +69,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { objects_on_path_section(app, ui, &oop); divider(ui); } + graph::section(app, ui); if matches!(first.as_ref().map(|n| &n.kind), Some(NodeKind::Text(_))) { type_sections(app, ui); divider(ui); @@ -1050,6 +1051,7 @@ pub fn type_sections(app: &mut VectorcraftApp, ui: &mut Ui) { } pub(crate) mod dynamic_text; +pub(crate) mod graph; pub(crate) mod vertical_align; #[cfg(test)] diff --git a/crates/ui-egui/src/panels/properties/graph.rs b/crates/ui-egui/src/panels/properties/graph.rs new file mode 100644 index 0000000000..525b65f722 --- /dev/null +++ b/crates/ui-egui/src/panels/properties/graph.rs @@ -0,0 +1,110 @@ +//! The Properties panel's Graph section, for one selected graph or series of one graph picked with +//! Group Selection: Graph Type… and Graph Data… open the dialogs of Object › Graph › Type… and +//! Data… ([Format pie graphs](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/format-pie-graphs.html) +//! opens Graph Type from the Properties panel). Column… shows when every series it would change +//! draws columns or bars, and Marker… when every one draws lines, scatter points or radar lines; +//! both run the same route as their Object › Graph items. + +use egui::Ui; +use serde_json::json; +use vectorcraft_doc::{Document, GraphKind, MAX_GRAPH_SERIES, NodeId}; + +use crate::VectorcraftApp; +use crate::widgets::{self, divider, section_header}; + +/// The Graph section's optional buttons for the selection. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Shown { + /// Column… takes the series it would change. + pub(crate) column: bool, + /// Marker… takes the series it would change. + pub(crate) marker: bool, +} + +/// What the Graph section shows for the selection; `None` unless everything selected is one graph +/// or lies inside the same graph. +pub(crate) fn shown(app: &VectorcraftApp) -> Option { + let st = app.session.active()?; + let doc = &st.doc; + let mut graph = None; + for id in &st.selection.objects { + let g = graph_of(doc, *id)?; + if graph.is_some_and(|x| x != g) { + return None; + } + graph = Some(g); + } + let graph = graph?; + let spec = doc.node(graph)?.extras().graph.as_deref()?; + let count = spec.rows.iter().map(Vec::len).max().unwrap_or(0).min(MAX_GRAPH_SERIES); + // The series Column… and Marker… change: those picked with Group Selection when the selection is + // only series, else every series (as `graph.column` and `graph.marker` pick them). + let picked: Option> = st.selection.objects.iter().map(|id| series_of(doc, graph, *id).filter(|i| *i < count)).collect(); + let series = picked.unwrap_or_else(|| (0..count).collect()); + let kinds: Vec = series.iter().map(|i| spec.series_kind(*i)).collect(); + let all = |ks: &[GraphKind]| !kinds.is_empty() && kinds.iter().all(|k| ks.contains(k)); + Some(Shown { + column: all(&[GraphKind::Column, GraphKind::StackedColumn, GraphKind::Bar, GraphKind::StackedBar]), + marker: all(&[GraphKind::Line, GraphKind::Scatter, GraphKind::Radar]), + }) +} + +/// The graph `id` is or lies in. +fn graph_of(doc: &Document, id: NodeId) -> Option { + let mut cur = Some(id); + while let Some(c) = cur { + if doc.node(c).is_some_and(|n| n.extras().graph.is_some()) { + return Some(c); + } + cur = doc.parent_of(c); + } + None +} + +/// The index of the series of `graph` that `id` is or lies in; `None` for the graph itself, its +/// axes and its legend. +fn series_of(doc: &Document, graph: NodeId, id: NodeId) -> Option { + let mut cur = id; + loop { + let parent = doc.parent_of(cur)?; + if parent == graph { + return doc.node(cur)?.extras().series_index.and_then(|i| usize::try_from(i).ok()); + } + cur = parent; + } +} + +/// The Graph section for the selection, with the divider after it; nothing without a graph. +pub(crate) fn section(app: &mut VectorcraftApp, ui: &mut Ui) { + let Some(s) = shown(app) else { return }; + section_header(ui, tl!("Graph")); + let mut buttons = vec![(tl!("Graph Type…"), "graph.setType"), (tl!("Graph Data…"), "graph.setData")]; + if s.column { + buttons.push((tl!("Column…"), "graph.column")); + } + if s.marker { + buttons.push((tl!("Marker…"), "graph.marker")); + } + let full = ui.available_width(); + let w = (full - 6.0) / 2.0; + for pair in buttons.chunks(2) { + // Two buttons share a row while both labels fit in half of it; a longer translated label + // puts each button of the pair on a row of its own. + if pair.iter().all(|(label, _)| widgets::flat_button_fit_width(ui, label, 0.0) <= w) { + ui.horizontal(|ui| { + for (label, id) in pair { + if widgets::flat_button(ui, label, w).clicked() { + crate::menus::invoke(app, id, json!({})); + } + } + }); + } else { + for (label, id) in pair { + if widgets::flat_button_fit(ui, label, full).clicked() { + crate::menus::invoke(app, id, json!({})); + } + } + } + } + divider(ui); +} diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index 9300619765..dff640f2e2 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -2014,3 +2014,154 @@ fn dynamic_text_rows_follow_the_selected_area_type() { app.run("text.thread.create", json!({})).unwrap(); assert_eq!(dynamic_text::shown(&app).map(|s| (s.on, s.enabled)), Some((Some(false), false))); } + +/// A document with a graph of `kind` and three series, selected → the graph's id. +fn graph_doc(app: &mut VectorcraftApp, kind: &str, x: f64) -> u64 { + if app.session.active().is_none() { + app.run("file.new", json!({"width": 800, "height": 400})).unwrap(); + } + let csv = ",a,b,c\nQ1,1,2,3\nQ2,3,4,5"; + app.run("graph.create", json!({"type": kind, "x": x, "y": 0, "width": 200, "height": 150, "csv": csv})).unwrap()["id"].as_u64().unwrap() +} + +/// The ids of graph `graph`'s series groups, in series order. +fn series_groups(app: &VectorcraftApp, graph: u64) -> Vec { + let st = app.session.active().unwrap(); + let mut groups: Vec<(u32, u64)> = st + .doc + .node(vectorcraft_doc::NodeId(graph)) + .and_then(vectorcraft_doc::Node::children) + .into_iter() + .flatten() + .filter_map(|c| c.extras().series_index.map(|i| (i, c.id.0))) + .collect(); + groups.sort_unstable(); + groups.into_iter().map(|(_, id)| id).collect() +} + +/// One selected column graph has a Graph section with Graph Type…, Graph Data… and Column…, and +/// each button opens its Object › Graph dialog for the graph. +#[test] +fn one_selected_graph_has_a_graph_section_whose_buttons_open_the_graph_dialogs() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + graph_doc(&mut app, "column", 0.0); + assert_eq!(graph::shown(&app), Some(graph::Shown { column: true, marker: false })); + let ctx = egui::Context::default(); + let texts = frame(&mut app, &ctx, vec![]); + for label in ["Graph", "Graph Type…", "Graph Data…", "Column…"] { + assert!(texts.iter().any(|(t, _)| t == label), "no {label:?} in {texts:?}"); + } + assert!(!texts.iter().any(|(t, _)| t == "Marker…"), "{texts:?}"); + let press = |app: &mut VectorcraftApp, label: &str| { + let texts = panel_frame(app, &ctx, vec![], graph::section); + let at = texts.iter().find(|(t, _)| t == label).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("no {label:?} in {texts:?}")); + let b = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + panel_frame(app, &ctx, vec![Event::PointerMoved(at), b(true)], graph::section); + panel_frame(app, &ctx, vec![b(false)], graph::section); + app.ui.dialog.take().unwrap_or_else(|| panic!("{label:?} opened no dialog")) + }; + let d = press(&mut app, "Graph Type…"); + assert_eq!((d.kind.as_str(), d.str("type")), (crate::dialogs::graph_type::KIND, "column".to_string())); + assert_eq!(press(&mut app, "Graph Data…").kind, crate::dialogs::graph_data::KIND); + assert_eq!(press(&mut app, "Column…").kind, crate::dialogs::graph_design::COLUMN); +} + +/// At the panel's narrowest, Graph Type… and Graph Data… share a row in English, and a translated +/// label too long for half of the row puts each of them on a row of its own, drawn whole. +#[test] +fn the_graph_sections_long_labels_get_rows_of_their_own() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + graph_doc(&mut app, "column", 0.0); + let ctx = egui::Context::default(); + let width = 220.0; + let texts = |app: &mut VectorcraftApp| { + let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(width, 700.0))), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| graph::section(app, ui)); + out.textures_delta.clear(); + out.shapes + .iter() + .filter_map(|s| { + if let egui::Shape::Text(t) = &s.shape { + Some((t.galley.text().to_string(), Rect::from_min_size(t.pos, t.galley.size()))) + } else { + None + } + }) + .collect::>() + }; + let rect = |texts: &[(String, Rect)], label: &str| { + texts.iter().find(|(t, _)| t == label).map(|(_, r)| *r).unwrap_or_else(|| panic!("no {label:?} in {texts:?}")) + }; + crate::i18n::set_current(crate::i18n::Lang::EN); + let english = texts(&mut app); + assert_eq!(rect(&english, "Graph Type…").center().y, rect(&english, "Graph Data…").center().y, "{english:?}"); + crate::i18n::set_current(crate::i18n::Lang::from_code("de").expect("de registered")); + let german = texts(&mut app); + crate::i18n::set_current(crate::i18n::Lang::EN); + let (kind, data) = (rect(&german, "Diagrammtyp…"), rect(&german, "Diagrammdaten…")); + assert!(kind.bottom() <= data.top(), "{german:?}"); + for r in [kind, data] { + assert!(r.left() >= 0.0 && r.right() <= width, "{r:?} in {german:?}"); + } +} + +/// Column… shows when every series it would change draws columns or bars, Marker… when every one +/// draws lines, scatter points or radar lines: series picked with Group Selection count on their +/// own, and a combined graph selected whole shows neither. +#[test] +fn the_graph_sections_column_and_marker_follow_the_series_they_would_change() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let g = graph_doc(&mut app, "column", 0.0); + app.run("graph.setType", json!({"seriesIndexes": [1], "type": "line"})).unwrap(); + app.run("select.set", json!({"ids": [g]})).unwrap(); + assert_eq!(graph::shown(&app), Some(graph::Shown { column: false, marker: false }), "column and line series"); + let groups = series_groups(&app, g); + assert_eq!(groups.len(), 3, "{groups:?}"); + app.run("select.set", json!({"ids": [groups[1]]})).unwrap(); + assert_eq!(graph::shown(&app), Some(graph::Shown { column: false, marker: true }), "the line series"); + app.run("select.set", json!({"ids": [groups[0], groups[2]]})).unwrap(); + assert_eq!(graph::shown(&app), Some(graph::Shown { column: true, marker: false }), "the column series"); + app.run("select.set", json!({"ids": [groups[0], groups[1]]})).unwrap(); + assert_eq!(graph::shown(&app), Some(graph::Shown { column: false, marker: false }), "one of each"); + for (kind, shown) in [ + ("line", (false, true)), + ("scatter", (false, true)), + ("radar", (false, true)), + ("bar", (true, false)), + ("pie", (false, false)), + ("area", (false, false)), + ] { + let id = graph_doc(&mut app, kind, 300.0); + app.run("select.set", json!({"ids": [id]})).unwrap(); + assert_eq!(graph::shown(&app).map(|s| (s.column, s.marker)), Some(shown), "{kind}"); + app.run("edit.clear", json!({})).unwrap(); + } + // A graph whose data was cleared has no series for Column… or Marker… to change. + for kind in ["column", "line"] { + let id = graph_doc(&mut app, kind, 300.0); + app.run("graph.setData", json!({"id": id, "series": [], "categories": [], "rows": []})).unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + assert_eq!(graph::shown(&app), Some(graph::Shown { column: false, marker: false }), "an empty {kind} graph"); + app.run("edit.clear", json!({})).unwrap(); + } +} + +/// The Graph section shows only while everything selected is one graph or lies in it. +#[test] +fn the_graph_section_needs_one_graph_selected() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let a = graph_doc(&mut app, "column", 0.0); + let b = graph_doc(&mut app, "column", 300.0); + let rect = app.run("shape.rectangle", json!({"x": 600, "y": 0, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + for (ids, what) in [(vec![rect], "a rectangle"), (vec![a, rect], "a graph and a rectangle"), (vec![a, b], "two graphs")] { + app.run("select.set", json!({ "ids": ids })).unwrap(); + assert_eq!(graph::shown(&app), None, "{what}"); + let texts = frame(&mut app, &egui::Context::default(), vec![]); + assert!(!texts.iter().any(|(t, _)| t == "Graph Type…"), "{what}: {texts:?}"); + } + let groups = series_groups(&app, a); + app.run("select.set", json!({"ids": [groups[0], groups[1]]})).unwrap(); + assert!(graph::shown(&app).is_some(), "two series of one graph"); + app.run("select.set", json!({"ids": [groups[0], series_groups(&app, b)[0]]})).unwrap(); + assert_eq!(graph::shown(&app), None, "series of two graphs"); +} diff --git a/crates/ui-egui/src/panels/swatches.rs b/crates/ui-egui/src/panels/swatches.rs index bfc17c6687..a27c8b65ff 100644 --- a/crates/ui-egui/src/panels/swatches.rs +++ b/crates/ui-egui/src/panels/swatches.rs @@ -211,6 +211,43 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { body(app, ui, TILE); } +/// Item actions target the clicked swatch, independently of the paint or other selected chips. +fn item_context_menu(app: &mut VectorcraftApp, ui: &Ui, resp: &Response, e: &Entry) { + if e.is_folder() { + return; + } + let name = e.name(); + if resp.secondary_clicked() { + let selected = dnd::selection(app, ui); + if selected.last().map(String::as_str) != Some(name) { + set_pstate(ui.ctx(), "swatch-selected", vec![name.to_string()]); + set_pstate(ui.ctx(), "swatch-anchor", name.to_string()); + } + } + resp.context_menu(|ui| { + // Recheck the document each frame: a swatch can be deleted while its menu is open. + let enabled = app.session.active().and_then(|st| st.doc.swatch(name)).is_some_and(|s| !s.is_reserved()); + let command = if menu_item(ui, tl!("Swatch Options…"), enabled, false) { + Some("ui.swatchOptions") + } else if menu_item(ui, tl!("Duplicate Swatch"), enabled, false) { + Some("swatch.duplicate") + } else if menu_item(ui, tl!("Delete Swatch"), enabled, false) { + Some("swatch.delete") + } else { + None + }; + if let Some(command) = command { + if command == "swatch.delete" { + actions::delete(app, vec![name.to_string()], false); + } else { + // run reports failures through the app's status message. + let _ = app.run(command, json!({"name": name})); + } + ui.close(); + } + }); +} + /// The panel in a Fill/Stroke chip popover (the Control bar's and Properties'): the same body, its /// tiles under their own ids so it can be open beside the panel. pub(crate) fn popover(app: &mut VectorcraftApp, ui: &mut Ui) { diff --git a/crates/ui-egui/src/panels/swatches/body.rs b/crates/ui-egui/src/panels/swatches/body.rs index 96e003bcf1..2124774ada 100644 --- a/crates/ui-egui/src/panels/swatches/body.rs +++ b/crates/ui-egui/src/panels/swatches/body.rs @@ -52,8 +52,8 @@ pub(super) fn body(app: &mut VectorcraftApp, ui: &mut Ui, salt: &'static str) { // Without a selection the swatch of the active paint is highlighted. let fallback: Vec = if selected.is_empty() { active_swatch.into_iter().collect() } else { vec![] }; let sel = if selected.is_empty() { &fallback } else { &selected }; - let lit = app.session.active().map(|st| highlighted(&st.doc, sel)).unwrap_or_default(); - let is_sel = |name: &str| lit.contains(&name); + let lit: Vec = app.session.active().map(|st| highlighted(&st.doc, sel).into_iter().map(str::to_string).collect()).unwrap_or_default(); + let is_sel = |name: &str| lit.iter().any(|n| n == name); let mut ev = TileEvents::default(); // In a sized panel the list fills the space above the footer (#1638), as the Artboards list // does; elsewhere it keeps its 150 pt (200 pt for large thumbnails). @@ -84,6 +84,7 @@ pub(super) fn body(app: &mut VectorcraftApp, ui: &mut Ui, salt: &'static str) { Entry::Folder(_) => draw_folder(ui, chip), } list_row_name(ui, r, chip, crate::i18n::t_name("swatch", name)); + super::item_context_menu(app, ui, &resp, e); tile_input(ui, resp, e, &items, sel, true, &mut ev); } } else { @@ -104,6 +105,7 @@ pub(super) fn body(app: &mut VectorcraftApp, ui: &mut Ui, salt: &'static str) { } Entry::Folder(_) => folder_tile(ui, cell, is_sel(name)), } + super::item_context_menu(app, ui, &resp, e); tile_input(ui, resp, e, &items, sel, false, &mut ev); } } diff --git a/crates/ui-egui/src/panels/swatches/tests.rs b/crates/ui-egui/src/panels/swatches/tests.rs index 601c8dc627..6c3872e97f 100644 --- a/crates/ui-egui/src/panels/swatches/tests.rs +++ b/crates/ui-egui/src/panels/swatches/tests.rs @@ -4,6 +4,8 @@ use egui::{Event, Modifiers, PointerButton, Pos2}; use vectorcraft_color::Color; use vectorcraft_engine::Session; +mod context_menu; + fn app() -> VectorcraftApp { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); diff --git a/crates/ui-egui/src/panels/swatches/tests/context_menu.rs b/crates/ui-egui/src/panels/swatches/tests/context_menu.rs new file mode 100644 index 0000000000..3d1da44892 --- /dev/null +++ b/crates/ui-egui/src/panels/swatches/tests/context_menu.rs @@ -0,0 +1,190 @@ +//! Actual secondary-button events on the panel's grid cells and list rows. + +use super::*; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; + +fn harness(view: View) -> Harness<'static, VectorcraftApp> { + let mut first = true; + let builder = Harness::builder().with_size(vec2(300.0, 700.0)).with_accessibility_check(false); + // Optional local visual QA, following the Image Trace harness; captures stay untracked. + let builder = if std::env::var_os("VECTORCRAFT_SWATCHES_CAPTURE_DIR").is_some() { builder.wgpu() } else { builder }; + let mut h = builder.build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if std::mem::replace(&mut first, false) { + egui_extras::install_image_loaders(ui.ctx()); + crate::theme::install_fonts(ui.ctx()); + app.ui.swatches_view = view; + return; + } + show(app, ui); + }, + app(), + ); + h.run_steps(4); + h +} + +fn right_click(h: &mut Harness<'static, VectorcraftApp>, name: &str) { + let pos = h.ctx.read_response(egui::Id::unique((TILE, name))).expect("swatch response").rect.center(); + h.event(Event::PointerMoved(pos)); + h.run_steps(1); + for pressed in [true, false] { + h.event(Event::PointerButton { pos, button: PointerButton::Secondary, pressed, modifiers: Modifiers::NONE }); + h.run_steps(1); + } + h.run_steps(2); +} + +fn cancel_then_confirm_delete(h: &mut Harness<'static, VectorcraftApp>) { + let before = h.state().session.doc().unwrap().doc.clone(); + let undo = h.state().session.doc().unwrap().history.undo.len(); + let dialog = h.state().ui.dialog.as_ref().expect("delete asks first"); + assert_eq!(dialog.kind, crate::dialogs::confirm::KIND); + assert_eq!(dialog.str("message"), "Delete “Red”?"); + assert_eq!(dialog.str("detail"), "Art using a deleted global swatch keeps its colour."); + assert_eq!(dialog.str("__command"), "swatch.delete"); + assert_eq!(dialog.fields.get("__params"), Some(&json!({"names": ["Red"]}))); + assert_eq!(h.state().session.doc().unwrap().doc, before); + assert_eq!(h.state().session.doc().unwrap().history.undo.len(), undo); + crate::dialogs::cancel(h.state_mut()); + assert!(h.state().ui.dialog.is_none()); + assert_eq!(h.state().session.doc().unwrap().doc, before); + assert_eq!(h.state().session.doc().unwrap().history.undo.len(), undo); + right_click(h, "Red"); + h.get_by_label(" Delete Swatch").click(); + h.run_steps(3); + crate::dialogs::confirm(h.state_mut()).unwrap(); +} + +#[test] +fn right_click_selects_without_painting_and_dispatches_item_commands() { + for (view, _) in View::ALL { + for command in ["Swatch Options…", "Duplicate Swatch", "Delete Swatch"] { + let mut h = harness(view); + set_pstate(&h.ctx, "swatch-selected", vec!["Black".to_string()]); + let before = h.state().session.doc().unwrap().doc.clone(); + let paint = h.state().session.paint.fill.clone(); + let undo = h.state().session.doc().unwrap().history.undo.len(); + right_click(&mut h, "Red"); + assert_eq!(selected(&h.ctx), ["Red"], "{view:?}"); + assert_eq!(h.state().session.doc().unwrap().doc, before, "opening the menu leaves art unchanged"); + assert_eq!(h.state().session.paint.fill, paint, "selecting a context target does not apply its paint"); + assert_eq!(h.state().session.doc().unwrap().history.undo.len(), undo); + for label in [" Swatch Options…", " Duplicate Swatch", " Delete Swatch"] { + assert!(!h.get_by_label(label).accesskit_node().is_disabled(), "{view:?}: {label}"); + } + if command == "Swatch Options…" + && let Some(dir) = std::env::var_os("VECTORCRAFT_SWATCHES_CAPTURE_DIR") + { + let dir = std::path::PathBuf::from(dir); + std::fs::create_dir_all(&dir).unwrap(); + h.render().unwrap().save(dir.join(format!("{view:?}.png"))).unwrap(); + } + h.get_by_label(&format!(" {command}")).click(); + h.run_steps(3); + match command { + "Swatch Options…" => { + let dialog = h.state().ui.dialog.as_ref().expect("Swatch Options opened"); + assert_eq!(dialog.kind, KIND); + assert_eq!(dialog.str("__swatch"), "Red"); + assert_eq!(h.state().session.doc().unwrap().history.undo.len(), undo); + } + "Duplicate Swatch" => { + let doc = &h.state().session.doc().unwrap().doc; + assert_eq!(doc.swatch("Red copy").unwrap().paint, doc.swatch("Red").unwrap().paint); + assert!(doc.swatch("Black copy").is_none()); + assert_eq!(h.state().session.doc().unwrap().history.undo.len(), undo + 1); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!(h.state().session.doc().unwrap().doc, before); + } + "Delete Swatch" => { + assert_eq!(h.state().session.doc().unwrap().doc, before); + assert_eq!(h.state().session.doc().unwrap().history.undo.len(), undo); + cancel_then_confirm_delete(&mut h); + let doc = &h.state().session.doc().unwrap().doc; + assert!(doc.swatch("Red").is_none()); + assert!(doc.swatch("Black").is_some()); + assert_eq!(h.state().session.doc().unwrap().history.undo.len(), undo + 1); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!(h.state().session.doc().unwrap().doc, before); + } + other => panic!("unexpected menu action: {other}"), + } + } + } +} + +#[test] +fn reserved_swatches_have_disabled_item_actions() { + for (view, _) in View::ALL { + for name in ["[None]", REGISTRATION] { + let mut h = harness(view); + let before = h.state().session.doc().unwrap().doc.clone(); + let undo = h.state().session.doc().unwrap().history.undo.len(); + right_click(&mut h, name); + assert_eq!(selected(&h.ctx), [name]); + for label in [" Swatch Options…", " Duplicate Swatch", " Delete Swatch"] { + assert!(h.get_by_label(label).accesskit_node().is_disabled(), "{view:?}: {name}: {label}"); + } + // egui closes a context menu even when the clicked item is disabled. + h.get_by_label(" Delete Swatch").click(); + h.run_steps(2); + assert!(h.state().ui.dialog.is_none()); + assert_eq!(h.state().session.doc().unwrap().doc, before); + assert_eq!(h.state().session.doc().unwrap().history.undo.len(), undo); + } + } +} + +#[test] +fn right_clicking_the_active_panel_item_preserves_its_selection() { + for (view, _) in View::ALL { + let mut h = harness(view); + let names = vec!["Black".to_string(), "Red".to_string()]; + set_pstate(&h.ctx, "swatch-selected", names.clone()); + right_click(&mut h, "Red"); + assert_eq!(selected(&h.ctx), names); + h.get_by_label(" Delete Swatch").click(); + h.run_steps(3); + assert_eq!(h.state().ui.dialog.as_ref().unwrap().fields.get("__params"), Some(&json!({"names": ["Red"]}))); + crate::dialogs::confirm(h.state_mut()).unwrap(); + let doc = &h.state().session.doc().unwrap().doc; + assert!(doc.swatch("Black").is_some(), "only the clicked item is deleted"); + assert!(doc.swatch("Red").is_none()); + } +} + +#[test] +fn a_swatch_deleted_while_its_menu_is_open_disables_actions() { + let mut first = true; + // Keep the original response alive to exercise the stale-entry guard after external deletion. + let mut h = Harness::builder().with_size(vec2(300.0, 300.0)).with_accessibility_check(false).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if std::mem::replace(&mut first, false) { + crate::theme::install_fonts(ui.ctx()); + return; + } + let e = Entry::Swatch { name: "Red".into(), paint: Paint::solid(Color::BLACK), global: false, spot: false }; + let resp = ui.button("Target"); + item_context_menu(app, ui, &resp, &e); + }, + app(), + ); + h.run_steps(4); + h.get_by_label("Target").click_secondary(); + h.run_steps(3); + assert!(!h.get_by_label(" Duplicate Swatch").accesskit_node().is_disabled()); + h.state_mut().run("swatch.delete", json!({"name": "Red"})).unwrap(); + let before = h.state().session.doc().unwrap().doc.clone(); + let undo = h.state().session.doc().unwrap().history.undo.len(); + h.run_steps(3); + for label in [" Swatch Options…", " Duplicate Swatch", " Delete Swatch"] { + assert!(h.get_by_label(label).accesskit_node().is_disabled(), "{label}"); + } + h.get_by_label(" Duplicate Swatch").click(); + h.run_steps(2); + assert!(h.state().ui.dialog.is_none()); + assert_eq!(h.state().session.doc().unwrap().doc, before); + assert_eq!(h.state().session.doc().unwrap().history.undo.len(), undo); +} diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index 741b080635..fd77707fcd 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -287,7 +287,7 @@ pub(crate) fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui, reserve: f32) { { app.status(e); } - if ui.available_width() >= 4.0 { + if ui.available_width() >= reserve + 4.0 { ui.add_space(4.0); } } @@ -1789,4 +1789,29 @@ mod tests { h.get_by_label(" Select All Instances").click(); h.run_steps(2); } + + /// The Control bar's symbol instance controls leave the room `reserve` asks for after them, the + /// gap after the controls included, when the row has no room for any of them. + #[test] + fn control_bar_symbol_controls_leave_the_reserve_when_none_fits() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let art = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap()["id"].clone(); + let instance = app.run("symbol.new", json!({"name": "Mark", "ids": [art]})).unwrap()["id"].clone(); + app.run("select.set", json!({ "ids": [instance] })).unwrap(); + let ctx = egui::Context::default(); + let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(600.0, 100.0))), ..Default::default() }; + let mut room = None; + let mut out = ctx.run_ui(raw, |ui| { + ui.horizontal(|ui| { + // Two points more than the reserve: too little for Edit Symbol or Replace. + let reserve = ui.available_width() - 2.0; + control_bar(&mut app, ui, reserve); + room = Some((ui.available_width(), reserve)); + }); + }); + out.textures_delta.clear(); + let (left, reserve) = room.expect("the row was drawn"); + assert!(left >= reserve, "{left} pt left after the symbol controls, {reserve} pt reserved"); + } } diff --git a/crates/ui-egui/src/panels/tests_three_d.rs b/crates/ui-egui/src/panels/tests_three_d.rs index 6146bc4852..a2720abec4 100644 --- a/crates/ui-egui/src/panels/tests_three_d.rs +++ b/crates/ui-egui/src/panels/tests_three_d.rs @@ -839,9 +839,15 @@ fn quick_actions_show_on_the_object_tab_only() { /// An app with an Extrude & Bevel square given `params`, and the panel on its Lighting tab with the /// accessibility tree on. fn lighting_app(params: Value) -> (VectorcraftApp, egui::Context) { + lighting_app_of("threeD.extrude", params) +} + +/// An app with a square given 3D effect `effect` with `params`, and the panel on its Lighting tab +/// with the accessibility tree on. +fn lighting_app_of(effect: &str, params: Value) -> (VectorcraftApp, egui::Context) { use crate::panels::tests_appearance::{click, frame_events, text_rect}; let mut app = app(); - app.run("effect.apply", json!({"effect": "threeD.extrude", "item": null, "params": params})).unwrap(); + app.run("effect.apply", json!({"effect": effect, "item": null, "params": params})).unwrap(); let ctx = egui::Context::default(); crate::theme::install_fonts(&ctx); ctx.enable_accesskit(); @@ -1026,6 +1032,151 @@ fn the_arrow_keys_move_the_light_pressed_last() { assert_eq!(rotations, [json!(0.0), json!(-179.0)]); } +/// The Lighting tab of Extrude & Bevel (Classic) has the lighting sphere: dragging its light is one +/// undo step, the button below it moves the light behind the object, Add Light adds a light at the +/// front center of the sphere, and Delete Light removes the selected light but never the last one. +#[test] +fn the_classic_lighting_tab_has_the_lighting_sphere() { + use crate::dialogs::revolve_lights::RADIUS; + use crate::panels::tests_appearance::{click, frame_events, text_rect}; + use vectorcraft_effects::CLASSIC_EXTRUDE; + let (mut app, ctx) = lighting_app_of(CLASSIC_EXTRUDE, json!({})); + let (name, from) = light_node(&mut app, &ctx, 1); + assert_eq!(name, "Light 1: Rotation 125.3°, Height 30.0°"); + let light = crate::dialogs::revolve_lights::lights(&crate::state::Dialog::new( + "x", + json!({"__effect": CLASSIC_EXTRUDE, "lightRotation": vectorcraft_three_d::DEFAULT_LIGHT.0, "lightHeight": 30.0}), + ))[0]; + let center = from - light.offset() * RADIUS; + let history = undo_len(&app); + let rim = center + egui::vec2(RADIUS, 0.0); + for event in [pointer(from, None), pointer(from, Some(true)), pointer(rim, None)] { + frame_events(&ctx, &mut app, vec![event], show); + } + assert_eq!(merged_light(&app), (0.0, 0.0), "the light follows the pointer while it is down"); + assert_eq!(undo_len(&app), history); + frame_events(&ctx, &mut app, vec![pointer(rim, Some(false))], show); + frame_events(&ctx, &mut app, vec![], show); + assert_eq!(undo_len(&app), history + 1); + let texts = frame_events(&ctx, &mut app, vec![], show); + click(&ctx, &mut app, text_rect(&texts, "Move Light to Back").center(), show); + assert_eq!(undo_len(&app), history + 2); + assert_eq!(effect(&app).1["lightBehind"], json!(true)); + let texts = frame_events(&ctx, &mut app, vec![], show); + click(&ctx, &mut app, text_rect(&texts, "Add Light").center(), show); + assert_eq!(undo_len(&app), history + 3); + let (name, _) = light_node(&mut app, &ctx, 2); + assert_eq!(name, "Light 2: Rotation 0.0°, Height 90.0°", "a new light is at the front center"); + let count = |app: &VectorcraftApp| effect(app).1["lights"].as_array().map_or(1, Vec::len); + assert_eq!(count(&app), 2); + let texts = frame_events(&ctx, &mut app, vec![], show); + click(&ctx, &mut app, text_rect(&texts, "Delete Light").center(), show); + assert_eq!(count(&app), 1); + assert_eq!(undo_len(&app), history + 4); + let (name, _) = light_node(&mut app, &ctx, 1); + assert_eq!(name, "Light 1: Rotation 0.0°, Height 0.0°, Light behind the object", "the selected light was deleted"); + // One light stays: Delete Light does nothing then. + let texts = frame_events(&ctx, &mut app, vec![], show); + click(&ctx, &mut app, text_rect(&texts, "Delete Light").center(), show); + assert_eq!(count(&app), 1); + assert_eq!(undo_len(&app), history + 4); +} + +/// The 3D (Classic) options dialog shows the lighting sphere on its Lighting tab too, and the +/// sphere draws a 3D (Classic) effect's lights white, since those effects shade without light color. +#[test] +fn the_classic_options_dialog_has_the_lighting_sphere_with_white_lights() { + use crate::panels::tests_appearance::frame_events; + use vectorcraft_effects::{CLASSIC_REVOLVE, EXTRUDE}; + let mut app = app(); + app.run("effect.dialog", json!({"effect": CLASSIC_REVOLVE, "item": null})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("__gizmo".into(), json!("light")); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + ctx.enable_accesskit(); + let dialog = |app: &mut VectorcraftApp, ui: &mut egui::Ui| crate::dialogs::show(app, ui.ctx()); + frame_events(&ctx, &mut app, vec![], dialog); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| dialog(&mut app, ui)); + out.textures_delta.clear(); + let nodes: Vec<_> = out.platform_output.accesskit_update.map(|u| u.nodes.into_iter().map(|(_, n)| n).collect()).unwrap_or_default(); + assert!( + nodes.iter().any(|n| n.role() == egui::accesskit::Role::Slider && n.label() == Some("Light 1: Rotation 125.3°, Height 30.0°")), + "the dialog shows the sphere" + ); + let red = json!([{"color": "#ff0000", "rotation": 0.0, "height": 30.0}]); + let color = + |effect: &str| crate::dialogs::revolve_lights::lights(&crate::state::Dialog::new("x", json!({"__effect": effect, "lights": red})))[0].color; + assert_eq!(color(CLASSIC_REVOLVE), egui::Color32::WHITE); + assert_eq!(color(EXTRUDE), egui::Color32::from_rgb(255, 0, 0)); +} + +fn assets(app: &mut VectorcraftApp) -> Vec { + app.run("assets.list", json!({})).unwrap()["assets"].as_array().unwrap().clone() +} + +/// The panel always shows Export 3D Object; it adds only the selected objects that have a 3D +/// effect to Asset Export as 3D assets, in one undo step, selects their assets there and shows the +/// Asset Export panel. Run again, it records nothing and still selects them. +#[test] +fn export_3d_object_adds_the_selected_3d_objects_to_asset_export() { + let mut app = app(); + assert!(painted_text(&mut app, show).contains("Export 3D Object")); + let ctx = egui::Context::default(); + // Without a 3D object: an error, nothing recorded, no asset. + let history = undo_len(&app); + assert!(super::export_3d_object(&mut app, &ctx).is_err()); + assert_eq!((undo_len(&app), assets(&mut app).len()), (history, 0)); + let a = app.session.active().unwrap().selection.objects[0].0; + set_type(&mut app, "extrude").unwrap(); + app.run("layer.setProps", json!({"id": a, "name": "Box"})).unwrap(); + assert!(painted_text(&mut app, show).contains("Export 3D Object")); + let plain = app.run("shape.rectangle", json!({"x": 250, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + // A hidden 3D effect draws nothing to export: the object is left out like one without. + let hidden = app.run("shape.rectangle", json!({"x": 100, "y": 250, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + app.run("effect.apply", json!({"effect": "threeD.extrude", "item": null})).unwrap(); + app.run("effect.setParams", json!({"index": 0, "item": null, "visible": false})).unwrap(); + assert!(super::export_3d_object(&mut app, &ctx).is_err()); + app.run("select.set", json!({"ids": [plain, a, hidden]})).unwrap(); + assert_eq!(super::selected_3d_objects(&app), [a]); + assert!(!crate::panel_docking::visible(&app.ui, crate::panels::asset_export::ID)); + let history = undo_len(&app); + super::export_3d_object(&mut app, &ctx).unwrap(); + assert_eq!(undo_len(&app), history + 1); + let list = assets(&mut app); + assert_eq!(list.len(), 1, "{list:?}"); + assert_eq!((list[0]["name"].clone(), list[0]["format3D"].clone()), (json!("Box"), json!("usda"))); + let asset = list[0]["id"].as_u64().unwrap(); + assert_eq!(super::pstate::>(&ctx, "asset-export-selected"), [asset]); + assert!(crate::panel_docking::visible(&app.ui, crate::panels::asset_export::ID)); + // Already an asset: no undo step, the same asset selected again, the panel left showing. + super::set_pstate(&ctx, "asset-export-selected", Vec::::new()); + super::export_3d_object(&mut app, &ctx).unwrap(); + assert_eq!((undo_len(&app), assets(&mut app).len()), (history + 1, 1)); + assert_eq!(super::pstate::>(&ctx, "asset-export-selected"), [asset]); + assert!(crate::panel_docking::visible(&app.ui, crate::panels::asset_export::ID)); + // Undo takes the asset away. + app.run("edit.undo", json!({})).unwrap(); + assert!(assets(&mut app).is_empty()); +} + +/// A selected 3D object inside another selected 3D object is not collected on its own: the outer +/// object's asset holds it. +#[test] +fn export_3d_object_leaves_out_a_3d_object_inside_another() { + let mut app = app(); + let inner = app.session.active().unwrap().selection.objects[0].0; + set_type(&mut app, "extrude").unwrap(); + let other = app.run("shape.rectangle", json!({"x": 250, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [inner, other]})).unwrap(); + let group = app.run("object.group", json!({})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [group]})).unwrap(); + app.run("effect.apply", json!({"effect": "threeD.extrude", "item": null})).unwrap(); + app.run("select.set", json!({"ids": [inner, group]})).unwrap(); + let selected: Vec = app.session.active().unwrap().selection.objects.iter().map(|id| id.0).collect(); + assert!(selected.contains(&inner) && selected.contains(&group), "{selected:?}"); + assert_eq!(super::selected_3d_objects(&app), [group]); +} + #[test] fn changed_settings_lists_only_new_values() { let before = json!({"depth": 50.0, "cap": true, "bevel": "none"}); diff --git a/crates/ui-egui/src/panels/three_d.rs b/crates/ui-egui/src/panels/three_d.rs index 231a755de2..2611824cda 100644 --- a/crates/ui-egui/src/panels/three_d.rs +++ b/crates/ui-egui/src/panels/three_d.rs @@ -4,11 +4,13 @@ //! dialogs' own Object, Rotation and Lighting controls and the panel's Materials tab //! ([`materials`]); each change runs `effect.setParams` as one undo step, and a drag previews and //! commits once, when the pointer is released. While the Materials tab is open, the artboard shows -//! a handle on each mapped graphic, which drags it over its face. +//! a handle on each mapped graphic, which drags it over its face. At the bottom, Export 3D Object +//! adds the selected objects that have a 3D effect to Asset Export as 3D assets (`assets.add3D`) +//! and shows that panel with their assets selected. use egui::Ui; use serde_json::{Map, Value, json}; -use vectorcraft_doc::{Effect, Node}; +use vectorcraft_doc::{Effect, Node, NodeId}; use vectorcraft_effects::{CLASSIC_EXTRUDE, CLASSIC_REVOLVE, EXTRUDE, INFLATE, THREE_D_TYPES, is_three_d}; use super::{live_run, pstate, set_pstate}; @@ -49,6 +51,13 @@ fn find(n: &Node) -> Option { in_list(&n.appearance.effects, None).or_else(|| n.appearance.items.iter().enumerate().find_map(|(k, item)| in_list(item.effects(), Some(k)))) } +/// Does object `n` have a visible 3D effect (where [`find`] looks, in a visible fill or stroke), +/// the kind Export 3D Object exports, without copying its settings? +fn has_three_d(n: &Node) -> bool { + let in_list = |fx: &[Effect]| fx.iter().any(|e| e.visible && is_three_d(&e.id)); + in_list(&n.appearance.effects) || n.appearance.items.iter().any(|item| item.visible() && in_list(item.effects())) +} + /// The panel's object type of effect `id` (`plane`, `extrude`, `revolve` or `inflate`). pub(crate) fn type_of(id: &str) -> Option<&'static str> { THREE_D_TYPES.iter().find(|(_, effect)| *effect == id).map(|(kind, _)| *kind) @@ -229,6 +238,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if let Some(action) = materials::library(app, ui, false) { run_action(app, &ctx, action); } + export_button(app, ui, &ctx); return; }; if takes_render(&t.effect) { @@ -271,6 +281,50 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if let Some(action) = action { run_action(app, &ctx, action); } + export_button(app, ui, &ctx); +} + +/// The Export 3D Object button, available while a selected object has a 3D effect. An error goes +/// to the status bar. +fn export_button(app: &mut VectorcraftApp, ui: &mut Ui, ctx: &egui::Context) { + let any = app.session.active().is_some_and(|st| st.selection.objects.iter().any(|id| st.doc.node(*id).is_some_and(has_three_d))); + ui.add_space(10.0); + if ui.add_enabled(any, egui::Button::new(tl!("Export 3D Object"))).clicked() { + finish(app, ctx); + if let Err(e) = export_3d_object(app, ctx) { + app.ui.status = e; + } + } +} + +/// The selected objects that have a 3D effect, in tree order, leaving out each one inside another +/// listed one (that one's asset holds it). +pub(crate) fn selected_3d_objects(app: &VectorcraftApp) -> Vec { + let Some(st) = app.session.active() else { return vec![] }; + let found = st.selection.objects.iter().copied().filter(|id| st.doc.node(*id).is_some_and(has_three_d)); + let mut paths: Vec<(Vec, NodeId)> = st.doc.index_paths(found).into_iter().map(|(id, path)| (path, id)).collect(); + paths.sort_by(|a, b| a.0.cmp(&b.0)); + let mut kept: Vec<(Vec, NodeId)> = Vec::with_capacity(paths.len()); + for (path, id) in paths { + if !kept.last().is_some_and(|(outer, _)| path.starts_with(outer)) { + kept.push((path, id)); + } + } + kept.into_iter().map(|(_, id)| id.0).collect() +} + +/// Export 3D Object: adds the selected objects that have a 3D effect to Asset Export as 3D assets +/// (`assets.add3D`, one undo step, none when each is an asset already), selects their assets there +/// and shows the Asset Export panel. Objects without a 3D effect in the selection are left out. +pub(crate) fn export_3d_object(app: &mut VectorcraftApp, ctx: &egui::Context) -> Result<(), String> { + use super::asset_export; + let ids = selected_3d_objects(app); + // Without one, `assets.add3D` on the selection says why nothing was added. + asset_export::add_3d(app, ctx, (!ids.is_empty()).then_some(ids.as_slice()))?; + if !crate::panel_docking::visible(&app.ui, asset_export::ID) { + app.run("window.panel", json!({"panel": asset_export::ID}))?; + } + Ok(()) } /// Does 3D effect `id` take render settings (`render`)? Extrude & Bevel, Revolve, Inflate and Rotate diff --git a/crates/ui-egui/src/panels/variables.rs b/crates/ui-egui/src/panels/variables.rs index c67f46a603..c339605fd5 100644 --- a/crates/ui-egui/src/panels/variables.rs +++ b/crates/ui-egui/src/panels/variables.rs @@ -197,6 +197,18 @@ pub(crate) fn delete_active_dataset(app: &mut VectorcraftApp) { app.run("dataset.delete", json!({})).ok(); } +/// The Data Set box: a new name typed over the current data set's renames it with +/// `dataset.rename`, in one undo step. The same name runs nothing, so no undo step is added; an +/// empty or taken name is refused, and the status bar says why. +pub(crate) fn rename_active_dataset(app: &mut VectorcraftApp, from: &str, to: &str) { + if from.is_empty() || to.trim() == from { + return; + } + if let Err(e) = app.run("dataset.rename", json!({"name": from, "newName": to})) { + app.status(e); + } +} + /// Draw document variables, data sets and their two-row footer of capture and binding controls. pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let Some(st) = app.session.active() else { @@ -241,12 +253,17 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let locked = st.doc.variables.locked; let sort = st.variables_sort; - // The current data set across the top: its name, and the arrows that step through them. + // The current data set across the top: its name in a box that renames it, the list that + // chooses another, and the arrows that step through them. ui.horizontal(|ui| { widgets::field_label(ui, tl!("Data Set")); let names: Vec<&str> = sets.iter().map(|s| s.name.as_str()).collect(); let current = active.map(|s| s.name.as_str()).unwrap_or(""); - let picked = widgets::dropdown_names(ui, "variables-active", current, &names, 160.0); + let typed = ui.add_enabled_ui(active.is_some(), |ui| widgets::text_field(ui, "variables-active-name", Some(current), 134.0, 1)).inner; + if let Some(to) = typed { + rename_active_dataset(app, current, &to); + } + let picked = widgets::dropdown_names_named(ui, "variables-active", Some(tl!("Data Sets")), "", &names, 26.0); if let Some(name) = picked.and_then(|i| names.get(i)) && *name != current { @@ -413,6 +430,10 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { delete_active_dataset(app); } ui.separator(); + // One file dialog for either kind of data source; the extension picks the reader. + if widgets::menu_item(ui, tl!("Import…"), true, false) { + crate::picks::button(app, import_data_source); + } if widgets::menu_item(ui, tl!("Import Data Sets…"), true, false) { crate::picks::button(app, import_datasets); } @@ -436,6 +457,23 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { } } +/// Variables panel: Import… opens one file dialog for a CSV, TSV, TXT or XML file and runs +/// `variable.import` on the chosen file, which reads it by its extension. +fn import_data_source(app: &mut VectorcraftApp) { + let pick = crate::FilePick { + filters: vec![ + crate::FilePick::filter("Data sources", &["csv", "tsv", "txt", "xml"]), + crate::FilePick::filter("CSV", &["csv", "tsv", "txt"]), + crate::FilePick::filter("XML", &["xml"]), + ], + ..Default::default() + }; + let Some(path) = crate::picks::open(app, &pick) else { return }; + if let Err(e) = app.run("variable.import", json!({"path": path})) { + app.status(e); + } +} + /// Variables panel: Import Data Sets… opens a file dialog for a comma- or tab-separated file and runs `dataset.import` on the chosen file. fn import_datasets(app: &mut VectorcraftApp) { let pick = crate::FilePick { filters: vec![crate::FilePick::filter("CSV", &["csv", "tsv", "txt"])], ..Default::default() }; @@ -498,6 +536,123 @@ mod tests { assert!(text.contains("Name") && text.contains("Data Sets") && text.contains("Data Set 1"), "{text}"); } + /// Frames of the panel with input events, for typing into its Data Set box. + struct Driver { + ctx: egui::Context, + time: f64, + } + + impl Driver { + fn new() -> Self { + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + Self { ctx, time: 0.0 } + } + + fn frame(&mut self, app: &mut VectorcraftApp, events: Vec) -> egui::FullOutput { + self.time += 0.1; + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(320.0, 600.0)); + let input = egui::RawInput { events, time: Some(self.time), screen_rect: Some(screen), ..Default::default() }; + let mut out = self.ctx.run_ui(input, |ui| show(app, ui)); + out.textures_delta.clear(); + out + } + + /// The center of the panel's one text box, the Data Set box. + fn data_set_box(&mut self, app: &mut VectorcraftApp) -> egui::Pos2 { + use egui::accesskit::Role; + self.frame(app, vec![]); + let out = self.frame(app, vec![]); + let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; + let (_, node) = nodes.iter().find(|(_, n)| matches!(n.role(), Role::TextInput | Role::MultilineTextInput)).expect("the Data Set box"); + let b = node.bounds().expect("bounds"); + egui::pos2((b.x0 + b.x1) as f32 * 0.5, (b.y0 + b.y1) as f32 * 0.5) + } + + /// Clicks the Data Set box, replaces its text with `text` and presses Enter. + fn type_name(&mut self, app: &mut VectorcraftApp, text: &str) { + use egui::{Event, Key, Modifiers, PointerButton}; + let pos = self.data_set_box(app); + let (button, none) = (PointerButton::Primary, Modifiers::default()); + self.frame(app, vec![Event::PointerMoved(pos), Event::PointerButton { pos, button, pressed: true, modifiers: none }]); + self.frame(app, vec![Event::PointerButton { pos, button, pressed: false, modifiers: none }]); + let all = Modifiers { ctrl: true, command: true, ..Default::default() }; + let select_all = Event::Key { key: Key::A, physical_key: None, pressed: true, repeat: false, modifiers: all }; + self.frame(app, vec![select_all, Event::Text(text.into())]); + self.frame(app, vec![Event::Key { key: Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: none }]); + self.frame(app, vec![]); + } + } + + fn set_names(app: &mut VectorcraftApp) -> Vec { + let sets = app.run("dataset.list", json!({})).unwrap(); + sets["datasets"].as_array().unwrap().iter().map(|d| d["name"].as_str().unwrap_or_default().to_string()).collect() + } + + fn undo_steps(app: &VectorcraftApp) -> usize { + app.session.active().unwrap().history.undo.len() + } + + /// A name typed in the Data Set box and entered renames the current data set in one undo step; + /// the list still chooses another data set afterward. + #[test] + fn the_data_set_box_renames_the_current_data_set() { + let mut app = app_with_data(); + app.session.execute("dataset.capture", &json!({})).unwrap(); + app.session.execute("dataset.select", &json!({"name": "Data Set 1"})).unwrap(); + let before = undo_steps(&app); + let mut d = Driver::new(); + d.type_name(&mut app, "Spring"); + assert_eq!(set_names(&mut app), ["Spring", "Data Set 2"]); + assert_eq!(app.session.active().unwrap().doc.variables.active_dataset.as_deref(), Some("Spring")); + assert_eq!(undo_steps(&app), before + 1); + assert_eq!(app.session.active().unwrap().history.undo.last().map(|e| e.label.as_str()), Some("Rename Data Set")); + // The new name is what the box shows, and what the list offers with the other row. + let text = crate::tests_labels::painted_text(&mut app, show); + assert!(text.contains("Spring"), "{text}"); + app.run("dataset.select", json!({"name": "Data Set 2"})).unwrap(); + assert_eq!(app.session.active().unwrap().doc.variables.active_dataset.as_deref(), Some("Data Set 2")); + } + + /// The same name adds no undo step; an empty name or another data set's name is refused with a + /// status message, and the names stay as they were. + #[test] + fn the_data_set_box_refuses_an_empty_or_taken_name() { + let mut app = app_with_data(); + app.session.execute("dataset.capture", &json!({})).unwrap(); + app.session.execute("dataset.select", &json!({"name": "Data Set 1"})).unwrap(); + let before = undo_steps(&app); + let mut d = Driver::new(); + d.type_name(&mut app, "Data Set 1"); + assert_eq!(undo_steps(&app), before, "the same name runs nothing"); + assert_eq!(app.ui.status, ""); + for name in ["Data Set 2", " "] { + app.ui.status.clear(); + d.type_name(&mut app, name); + assert_eq!(set_names(&mut app), ["Data Set 1", "Data Set 2"], "{name:?}"); + assert_eq!(undo_steps(&app), before, "{name:?}"); + assert!(!app.ui.status.is_empty(), "{name:?} gives no status message"); + } + assert!(app.ui.status.contains("newName"), "{}", app.ui.status); + // Through the helper too: an unchanged or padded name runs nothing. + rename_active_dataset(&mut app, "Data Set 1", " Data Set 1 "); + assert_eq!(undo_steps(&app), before); + } + + /// With no data set the box is disabled, so typing in it renames nothing. + #[test] + fn the_data_set_box_is_disabled_without_a_data_set() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 300, "height": 200})).unwrap(); + let before = undo_steps(&app); + let mut d = Driver::new(); + d.type_name(&mut app, "Spring"); + assert!(set_names(&mut app).is_empty()); + assert_eq!(undo_steps(&app), before); + assert_eq!(app.ui.status, ""); + } + /// A click on a column header sorts the list by that column, and a second click on it /// reverses the order; the rows are drawn in the order `variable.list` reports. #[test] @@ -624,6 +779,8 @@ mod tests { "Update Data Set", "Rename Data Set…", "Delete Data Set", + "Import…", + "Import Data Sets…", "Load Variable Library…", "Save Variable Library…", "Select Bound Object", diff --git a/crates/ui-egui/src/place.rs b/crates/ui-egui/src/place.rs index 5e4f5930f7..3141cfb3c6 100644 --- a/crates/ui-egui/src/place.rs +++ b/crates/ui-egui/src/place.rs @@ -61,7 +61,7 @@ pub fn is_document(name: &str) -> bool { #[derive(Default)] pub struct PlaceState { /// Web: the bytes of the files picked for the Place dialog, by name. - picked: Vec<(String, Vec)>, + pub(crate) picked: Vec<(String, Vec)>, /// The loaded cursor's thumbnails by file name. thumbs: Vec<(String, Thumb)>, /// The Control bar's `image.info`, for (document uid, revision, image id). @@ -74,8 +74,11 @@ pub struct PlaceState { queue_asks: bool, /// The loaded cursor's files by name, with the size a click places them at. queue_sizes: Vec<(String, f64, f64)>, + /// The names of the loaded cursor's encrypted PDF files, which ask for their password. + queue_locked: Vec, /// The engine's count of cursor loads ([`vectorcraft_engine::Session::place_queue_loads`]) when - /// `queue_asks` and `queue_sizes` were set: a later load (`tool.setOption`, a script) clears them. + /// `queue_asks`, `queue_sizes` and `queue_locked` were set: a later load (`tool.setOption`, a + /// script) clears them. queue_load: u64, /// The import options dialog a click of the cursor opened (the token in its params' /// [`ASKED`]), with the automation roots the cursor was loaded in: its OK, pressed outside any @@ -88,6 +91,11 @@ pub struct PlaceState { /// file is placed. const ASKED: &str = "__placeCursorAsk"; +/// The `file.place` param that keeps where a file dropped on a canvas goes (`{doc, reverts}`, as +/// [`DropAt`]) through the import options dialog the drop opened, so its OK places the file in that +/// document; hidden from the dialog's fields and removed before the file is placed. +const DROPPED: &str = "__dropTarget"; + /// A place cursor thumbnail: decoded when the cursor is loaded, uploaded when first drawn (and /// again in a new graphics context). struct Thumb { @@ -125,10 +133,11 @@ fn engine(app: &mut VectorcraftApp, id: &str, p: &Value) -> Result Result { place_file(app, p, Read::AtOnce) } @@ -148,7 +157,23 @@ enum Read { ForUser { dropped: bool }, } -fn place_file(app: &mut VectorcraftApp, p: &Value, read: Read) -> Result { +fn place_file(app: &mut VectorcraftApp, p: &Value, mut read: Read) -> Result { + // A file dropped on a canvas, and the OK of the import options its drop asked for, go to the + // document it was dropped on, which becomes active again; not when that document has closed or + // been reverted since. + if let Some(target) = p.get(DROPPED) { + let field = |k: &str| target.get(k).and_then(Value::as_u64); + let Some(i) = app.session.documents().iter().position(|st| Some(st.uid) == field("doc")) else { + return Err("the document it was dropped on was closed".into()); + }; + if app.session.documents().get(i).is_some_and(|st| Some(st.reverts) != field("reverts")) { + return Err("the document it was dropped on was reverted".into()); + } + app.session.set_active(i); + if let Read::ForUser { .. } = read { + read = Read::ForUser { dropped: true }; + } + } // The OK of import options a click of the place cursor asked for places within the roots the // cursor was loaded in. A caller with roots of its own places within those. let Some(token) = p.get(ASKED) else { return place_file_in(app, p, read) }; @@ -181,6 +206,7 @@ fn place_file_in(app: &mut VectorcraftApp, p: &Value, read: Read) -> Result Result Result Result { @@ -409,9 +442,15 @@ pub fn confirm(app: &mut VectorcraftApp, d: &crate::state::Dialog) -> Result = many.iter().filter(|s| s.get("path").is_none()).collect(); let mut q = json!({ "paths": paths, "files": files, "link": link, "template": template }); if !ask { - // Each text file and DXF drawing in the cursor takes the options confirmed last. + // Each text file, DXF drawing and embedded PSD file in the cursor takes the options + // confirmed last. q["text"] = crate::dialogs::text_import::last_options(app); q["dxf"] = crate::dialogs::dxf_import::remembered(app); + if !link || paths.is_empty() { + // Files from bytes have no file to link to; they may carry the dialog's Link. + q["link"] = json!(false); + crate::dialogs::psd_import::queue_options(app, &mut q); + } } queue_files(app, &q, Read::ForUser { dropped: false }, ask) } @@ -449,15 +488,21 @@ fn queue_files(app: &mut VectorcraftApp, p: &Value, read: Read, asks: bool) -> R /// The file a click or drag of the place cursor places (`file.place` with `p`, its `rect` set): /// read off the UI thread where the files the user places are ([`crate::placing::start`]), else at /// once. When the Place dialog loaded the cursor with Show Import Options on, a file that has -/// import options asks for them first (Cancel leaves it unplaced). An error shows in the status bar. +/// import options asks for them first (Cancel leaves it unplaced); otherwise only an encrypted PDF +/// asks, for its password. An error shows in the status bar. pub(crate) fn place_from_cursor(app: &mut VectorcraftApp, p: &Value) { // Read within the automation roots of whoever loaded the cursor, even on a click of the person // at the keyboard: an agent's queue reaches no file it wasn't given. let roots = app.session.place_queue_roots(); forget_older_queue(app); vectorcraft_engine::file_access::confine(roots.as_ref(), || { - if app.place.queue_asks { + let locked = is_locked(app, p); + if app.place.queue_asks || locked { let mut p = clicked_at_full_size(app, p); + if !app.place.queue_asks { + // Only its password is asked for, as File › Place with Show Import Options off. + p["showImportOptions"] = json!(false); + } // The import options it may ask for keep the token, and their OK places within the // same roots ([`place_file`]). app.place.asked = roots.clone().map(|r| { @@ -484,10 +529,17 @@ fn forget_older_queue(app: &mut VectorcraftApp) { if app.place.queue_load != app.session.place_queue_loads() { app.place.queue_asks = false; app.place.queue_sizes.clear(); + app.place.queue_locked.clear(); app.place.asked = None; } } +/// Does `p` (a cursor click's `file.place` params) name a file the cursor holds as an encrypted PDF? +fn is_locked(app: &VectorcraftApp, p: &Value) -> bool { + let name = p.get("path").or_else(|| p.get("name")).and_then(Value::as_str).map(fileio::file_name); + name.is_some_and(|n| app.place.queue_locked.contains(&n)) +} + /// The params of a cursor click (`rect` at the file's queued size) on a PDF or DXF file, whose /// import options may change its size (another page, another scale): placed as its options place /// it at the click (`at`, the center of the box the click gave), as File › Place of that one file @@ -524,6 +576,13 @@ pub(crate) fn show_thumbnails(app: &mut VectorcraftApp, r: &Value, asks: bool) { .flatten() .filter_map(|f| Some((f["name"].as_str()?.to_string(), f["width"].as_f64()?, f["height"].as_f64()?))) .collect(); + app.place.queue_locked = r["files"] + .as_array() + .into_iter() + .flatten() + .filter(|f| f["needsPassword"] == true) + .filter_map(|f| Some(f["name"].as_str()?.to_string())) + .collect(); app.place.thumbs = r["files"] .as_array() .into_iter() @@ -605,29 +664,20 @@ pub type DropFile = (String, Option, Vec); /// Files dropped on the window, each placed on a canvas or opened (and added to Open Recent /// Files) as its target says: the placed ones first, so the last document opened is the one /// shown. A file for a canvas goes to the document it was dropped on, which becomes active again; -/// it isn't placed when that document has closed or been reverted since. +/// it isn't placed when that document has closed or been reverted since, and neither is it by the +/// OK of an import options dialog the drop opened ([`DROPPED`]). pub fn drop_files(app: &mut VectorcraftApp, mut files: Vec<(DropTarget, DropFile)>) { files.sort_by_key(|(target, _)| *target == DropTarget::Open); for (target, (name, path, bytes)) in files { - if let DropTarget::Place(d) = target { - let Some(i) = app.session.documents().iter().position(|st| st.uid == d.doc) else { - app.status(format!("Couldn't place {name}: the document it was dropped on was closed")); - continue; - }; - if app.session.documents().get(i).is_some_and(|st| st.reverts != d.reverts) { - app.status(format!("Couldn't place {name}: the document it was dropped on was reverted")); - continue; - } - app.session.set_active(i); - } let r = match target { - DropTarget::Place(DropAt { at, embed, .. }) => { + DropTarget::Place(DropAt { doc, reverts, at, embed }) => { let mut p = match &path { Some(path) => json!({ "path": path }), None => json!({ "name": name, "dataBase64": vectorcraft_format::base64_encode(&bytes) }), }; p["at"] = json!([at.x, at.y]); p["link"] = json!(!embed); + p[DROPPED] = json!({ "doc": doc, "reverts": reverts }); place_file(app, &p, Read::ForUser { dropped: true }).map(|_| ()) } DropTarget::Open => match path.as_deref() { diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index a4af5b70f5..2fbe54d633 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -227,6 +227,7 @@ pub const ICON_PANELS: &[(&str, &str, &str)] = &[ (crate::panels::learn::ID, "Learn", "graduation-cap"), (crate::addons::cleanup::ID, "Artwork Cleanup", "sparkles"), (crate::addons::color::ID, "Color Effects", "sun"), + (crate::addons::packaging::ID, "Fold Lines", "scissors"), (crate::addons::pathtools::ID, "Anchor Inspector", "dc-anchor-smooth"), (crate::addons::pathtools::shape::ID, "Parametric Shape", "hexagon"), (crate::addons::pen::ID, "Smart Pen", "spline-pointer"), @@ -550,6 +551,10 @@ pub struct UiState { #[serde(default)] pub toolbar_right: bool, pub status_bar: bool, + /// What the status bar's info field shows (its Show menu, `view.statusBarShow`): Current Tool by + /// default and in state saved without it ([`crate::chrome::deserialize_status_bar_show`]). + #[serde(default, deserialize_with = "crate::chrome::deserialize_status_bar_show")] + pub status_bar_show: crate::chrome::StatusBarShow, pub help_bar: bool, pub dock: bool, /// The bars that Tab (`window.dock`) hid, which the next Tab shows again; none when Tab has not @@ -827,6 +832,9 @@ pub struct UiState { /// never used). #[serde(default)] pub dxf_import: Value, + /// The PSD Import Options chosen last (layers, hiddenLayers, importSlices; null: never used). + #[serde(default)] + pub psd_import: Value, /// The Home screen is shown over the open documents (`app.home`): the active document's uid /// and the document count when it opened. Choosing a tab, or a document opening, closing or /// becoming active, leaves it. @@ -1177,6 +1185,7 @@ impl Default for UiState { tools_beside_canvas: false, toolbar_right: false, status_bar: true, + status_bar_show: crate::chrome::StatusBarShow::CurrentTool, help_bar: true, dock: true, tab_hid: None, @@ -1255,6 +1264,7 @@ impl Default for UiState { transform_each: Value::Null, rearrange_artboards_spacing: Value::Null, dxf_import: Value::Null, + psd_import: Value::Null, home: None, trace_hold_source: None, layers_panel: Default::default(), diff --git a/crates/ui-egui/src/tests/place.rs b/crates/ui-egui/src/tests/place.rs index f470ef49bc..0141f69403 100644 --- a/crates/ui-egui/src/tests/place.rs +++ b/crates/ui-egui/src/tests/place.rs @@ -1071,6 +1071,61 @@ fn the_place_cursors_files_ask_for_their_import_options_when_show_import_options assert_eq!(dialog_kind(&app), None); } +/// An encrypted PDF in the place cursor asks for its password when clicked, with Show Import +/// Options on or off, and the password's OK places it where the click put it. +#[test] +fn an_encrypted_pdf_in_the_place_cursor_asks_for_its_password_when_clicked() { + let mut app = app(); + let dir = Folder::new("ui-place-cursor-encrypted-pdf"); + let a = dir.file("a.png", &png(10, 10, 72.0)); + let pages = [PdfPage::new(100.0, 100.0, "0 g 0 0 10 10 re f"), PdfPage::new(300.0, 100.0, "1 0 0 rg 0 0 30 30 re f")]; + let locked = dir.file("locked.pdf", &pdf(&pages, Some("pw"))); + // The click gives the box of the size the cursor holds it at, a letter page. + let click = json!({"path": locked, "link": false, "rect": [10, 10, 612, 792]}); + let center = vectorcraft_geom::Point::new(316.0, 406.0); + let placed = |app: &VectorcraftApp| { + let st = app.session.active().unwrap(); + let b = st.doc.node(st.selection.objects[0]).unwrap().geometric_bounds().unwrap(); + (b.width().round(), b.center()) + }; + for show in [false, true] { + app.run("file.place", json!({"paths": [a, locked]})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("showImportOptions".into(), json!(show)); + d.fields.insert("link".into(), json!(false)); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(app.session.tool_options()["count"], 2, "kept in the cursor"); + crate::place::place_from_cursor(&mut app, &click); + let d = app.ui.dialog.as_mut().expect("the password dialog"); + assert!(d.bool("__locked")); + assert_eq!(d.fields["__place"], json!({"link": false, "at": [316.0, 406.0]})); + d.fields.insert("password".into(), json!("pw")); + crate::dialogs::confirm(&mut app).unwrap(); + if show { + // Unlocked, it asks for the page. + assert_eq!(dialog_kind(&app), Some("importPdf")); + crate::dialogs::confirm(&mut app).unwrap(); + } + assert_eq!((dialog_kind(&app), placed(&app)), (None, (100.0, center)), "Show Import Options {show}"); + } + // A cursor loaded by file.place.queue asks too, also with a `page`, which it then places. + app.run("file.place.queue", json!({"paths": [a, locked], "link": false, "page": 2})).unwrap(); + crate::place::place_from_cursor(&mut app, &json!({"path": locked, "link": false, "page": 2, "rect": [10, 10, 612, 792]})); + let d = app.ui.dialog.as_mut().expect("the password dialog"); + assert!(d.bool("__locked")); + d.fields.insert("password".into(), json!("pw")); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!((dialog_kind(&app), placed(&app).0), (None, 300.0), "page 2"); + // File › Place of it with a `page` and Show Import Options on asks for the password too. + crate::place::run_for_user(&mut app, &json!({"path": locked, "link": false, "page": 1})).unwrap(); + assert!(app.ui.dialog.as_ref().is_some_and(|d| d.bool("__locked"))); + app.ui.dialog = None; + // An encrypted PDF whose name has no PDF extension is still left out of the cursor. + let misnamed = dir.file("locked.dat", &pdf(&pages, Some("pw"))); + let r = app.run("file.place.queue", json!({"paths": [a, misnamed]})).unwrap(); + assert_eq!((&r["count"], &r["skipped"][0]["name"]), (&json!(1), &json!("locked.dat")), "{r}"); +} + /// A cursor loaded again after the Place dialog loaded it with Show Import Options on (a queue set /// on the Place tool) places its files at once. #[test] diff --git a/crates/ui-egui/src/tests/taskbar.rs b/crates/ui-egui/src/tests/taskbar.rs index 1e3d946100..b6d04ff12b 100644 --- a/crates/ui-egui/src/tests/taskbar.rs +++ b/crates/ui-egui/src/tests/taskbar.rs @@ -2,7 +2,8 @@ //! Path, compound paths and clipping masks their Release, images selected with vector art Make //! Clipping Mask, type converts between point and area type, type on a path opens its options, and //! a basic shape shows its properties in place of Lock. The basic shape tools show Edit Path, Fill, -//! Stroke and Shape Properties for the shape they draw. Type, and the Type tools while they edit it, +//! Stroke and Shape Properties for the shape they draw, and the Smooth tool its Fidelity and Tool +//! Options… for a path it can smooth. Type, and the Type tools while they edit it, //! show the font family, font style and Font Size controls. use egui::{Event, PointerButton, Pos2, Rect, vec2}; @@ -315,7 +316,7 @@ fn point_type_offers_dynamic_text() { /// The path's anchors (its first subpath). fn anchors(app: &VectorcraftApp, id: u64) -> Vec { match kind(app, id) { - NodeKind::Path { path, .. } => path.subpaths[0].anchors.clone(), + NodeKind::Path { path, .. } => path.subpaths[0].anchors.to_vec(), k => panic!("not a path: {k:?}"), } } @@ -721,6 +722,86 @@ fn shape_tool_bar_retargets_after_another_shape_and_undo() { assert_eq!(app.session.tool_id(), "directSelection"); } +/// Where the text the bar draws just right of `label`, on the same row, centers: the field after +/// the label. +fn field_after(texts: &[(String, Rect)], label: &str) -> Pos2 { + let l = texts.iter().find(|(t, _)| t == label).unwrap_or_else(|| panic!("no `{label}` in {texts:?}")).1; + texts + .iter() + .filter(|(_, r)| r.left() > l.right() && (r.center().y - l.center().y).abs() < 8.0) + .min_by(|a, b| a.1.left().total_cmp(&b.1.left())) + .unwrap_or_else(|| panic!("no field after `{label}` in {texts:?}")) + .1 + .center() +} + +/// The Smooth tool, with a path it can smooth selected, shows its Fidelity field and Tool Options…, +/// and none of the selection tools' actions or chips. A value typed in the field sets the tool's +/// Fidelity, and Tool Options… opens the tool's options with that value. +#[test] +fn the_smooth_tool_shows_fidelity_and_tool_options_for_a_path() { + let mut app = app(); + let path = id(app.run("shape.ellipse", json!({"x": 60, "y": 60, "width": 120, "height": 80})).unwrap()); + select(&mut app, &[path]); + app.run("tool.select", json!({"tool": "smooth"})).unwrap(); + let (_, named) = buttons(&mut app); + let names = names(&named); + for name in ["Tool Options…", "More Options"] { + assert!(names.contains(&name), "{name} in {names:?}"); + } + for name in ["Fill", "Stroke", "Recolor Artwork", "Lock (⌘2)", "Duplicate", "Edit Path", "Offset Path", "Simplify", "Smooth"] { + assert!(!names.contains(&name), "{name} is left out of {names:?}"); + } + let (ctx, texts) = bar(&mut app); + let p = field_after(&texts, "Fidelity:"); + let press = |pressed| Event::PointerButton { pos: p, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(&mut app, &ctx, vec![Event::PointerMoved(p), press(true), press(false)]); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![Event::Text("7".into())]); + let enter = Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + frame(&mut app, &ctx, vec![enter]); + frame(&mut app, &ctx, vec![]); + assert_eq!(app.session.tool_options()["fidelity"].as_f64(), Some(7.0)); + assert_eq!(app.session.tool_id(), "smooth"); + assert_eq!(app.session.active().unwrap().selection.objects, [NodeId(path)], "the selection is kept"); + click_button(&mut app, "Tool Options…"); + let d = app.ui.dialog.as_ref().expect("the Smooth tool's options"); + assert_eq!((d.kind.as_str(), d.str("tool").as_str()), (crate::dialogs::freehand::KIND, "smooth")); + assert_eq!(d.f64("fidelity", 0.0), 7.0); +} + +/// The Smooth tool shows no bar without a selected path it can smooth: with nothing selected, a +/// straight line or type. With a selection tool the bar has the selection's actions again, without +/// Fidelity. +#[test] +fn the_smooth_tool_shows_no_bar_without_a_path_to_smooth() { + let mut app = app(); + let path = id(app.run("shape.ellipse", json!({"x": 60, "y": 60, "width": 120, "height": 80})).unwrap()); + let line = id(app.run("shape.line", json!({"x1": 150, "y1": 200, "x2": 300, "y2": 240})).unwrap()); + let text = id(app.run("text.create", json!({"x": 220, "y": 60, "text": "Type"})).unwrap()); + app.run("tool.select", json!({"tool": "smooth"})).unwrap(); + for (what, ids) in [("nothing", vec![]), ("a straight line", vec![line]), ("type", vec![text])] { + select(&mut app, &ids); + let (ctx, _) = bar(&mut app); + assert!(canvas::task_bar_rect(&ctx).is_none(), "{what}: no bar"); + } + select(&mut app, &[path, line]); + let (ctx, texts) = bar(&mut app); + assert!(canvas::task_bar_rect(&ctx).is_some() && has(&texts, "Fidelity:"), "a path with a line: the bar, {texts:?}"); + // On one canvas the bar follows each change of the selection. + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + for (ids, shown) in [(vec![path], true), (vec![line], false), (vec![], false), (vec![path], true)] { + select(&mut app, &ids); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + assert_eq!(canvas::task_bar_rect(&ctx).is_some(), shown, "{ids:?}"); + } + app.run("tool.select", json!({"tool": "selection"})).unwrap(); + let (_, texts) = bar(&mut app); + assert!(has(&texts, "Duplicate") && !has(&texts, "Fidelity:"), "{texts:?}"); +} + /// A compound path under the Direct Selection tool isn't offered Edit Path, which would only switch /// to the tool already in use; the Selection tool still offers it. #[test] diff --git a/crates/ui-egui/src/tests/trace_runs.rs b/crates/ui-egui/src/tests/trace_runs.rs index d2de2f00f5..8dd72efe91 100644 --- a/crates/ui-egui/src/tests/trace_runs.rs +++ b/crates/ui-egui/src/tests/trace_runs.rs @@ -162,6 +162,23 @@ fn a_trace_needs_its_image_as_it_was() { assert!(app.ui.status.contains("changed meanwhile: trace it again"), "{}", app.ui.status); } +/// A trace started before File › Revert doesn't apply after it, even when the document was +/// reverted to the same image: nothing changes, and the status bar says why. +#[test] +fn a_trace_started_before_a_revert_does_not_apply() { + let mut app = app(); + let i = app.session.active_index().unwrap(); + let copy = (*app.session.doc().unwrap().doc).clone(); + let [img] = app.session.doc().unwrap().selection.objects[..] else { panic!("the image is selected") }; + crate::menus::invoke(&mut app, "imageTrace.make", json!({"preset": "Default"})); + assert!(app.session.replace_document(i, copy)); + wait(&mut app); + assert_eq!(undos(&app), 0, "nothing changes"); + let st = app.session.doc().unwrap(); + assert!(matches!(st.doc.node(img).unwrap().kind, vectorcraft_doc::NodeKind::Image(_)), "the image is not traced"); + assert_eq!(app.ui.status, "Image Trace finished, but its document was reverted: trace it again"); +} + /// The progress window opens after its delay with Cancel and Continue in Background; Continue in /// Background closes it and the trace goes on. #[test] diff --git a/crates/ui-egui/src/trace_runs.rs b/crates/ui-egui/src/trace_runs.rs index 3d80c1190a..d9800e6668 100644 --- a/crates/ui-egui/src/trace_runs.rs +++ b/crates/ui-egui/src/trace_runs.rs @@ -8,7 +8,8 @@ //! //! When it is done, what it traced is handed to its command with the same parameters //! ([`Traced::hand_in`]), so the edit is one undo step like any trace, unless the image or the -//! settings changed meanwhile: then nothing changes and the status bar says to trace it again. The +//! settings changed meanwhile or File › Revert replaced the document's content: then nothing +//! changes and the status bar says to trace it again. The //! control channel, MCP and scripts run the commands at once, and so does every trace on the web, //! in unit tests that don't set `off_the_ui_thread`, and with `VECTORCRAFT_SYNC_OPEN` set //! ([`available`]). @@ -158,8 +159,8 @@ pub fn poll(app: &mut VectorcraftApp) { } /// Applies trace `r`'s result in its document, which becomes the active one again, as its command -/// would while the object, its image and the settings are as they were; else why it has none, in -/// the status bar. +/// would while the object, its image and the settings are as they were and the document was not +/// reverted; else why it has none, in the status bar. fn finish(app: &mut VectorcraftApp, r: Running, done: Option) { // Cancel changes nothing, even when the trace ended just before it. if r.token.is_cancelled() { @@ -184,6 +185,10 @@ fn finish(app: &mut VectorcraftApp, r: Running, done: Option) { return; }; app.session.set_active(i); + if run.reverted(&app.session) { + app.status("Image Trace finished, but its document was reverted: trace it again"); + return; + } if !run.current(&app.session) { app.status("Image Trace finished, but the image or its settings changed meanwhile: trace it again"); return; diff --git a/docs/control-protocol.md b/docs/control-protocol.md index d52720f29e..76ad9628d1 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -1,6 +1,6 @@ # Control protocol -> **Last updated:** 2026-11-07 · **Change:** text style commands take a feature with a value (`"features": ["salt=2"]`), the font's alternate number, and shape runs that differ only in features as one piece of text; previously: Confining file access refuses a `:` in a name after the drive on Windows, an NTFS alternate data stream such as `x.svg:evil` (#3604); previously: Object → Expand… dimmed while the selection has an appearance Expand Appearance expands (`object.expand.info`'s `appearance`, #3089); previously: brush library panels (`window.brushLibrary`, `window.brushLibrary.other`, `ui.saveBrushLibrary`); previously: Transform Each opens on the values it was last confirmed with; its Copy button confirms with `copy: true` (#1732); previously: panel docking on craft-ui's layout: `ui.docking`, the parameters of `window.panel.float` and `window.panel.dock`; previously: `ui.screenshot`'s 64 MiB inline-PNG cap and its path-plus-data downgrade; symbol library panels (`window.symbolLibrary`, `window.symbolLibrary.other`, `ui.saveSymbolLibrary`); synthetic input budgets (#1709); bounded transport waits (#1726). +> **Last updated:** 2026-11-15 · **Change:** completed the `ui.resize` and `ui.focus` entries and removed a duplicate `ui.render` row; previously: text style commands take a feature with a value (`"features": ["salt=2"]`), the font's alternate number, and shape runs that differ only in features as one piece of text; previously: Confining file access refuses a `:` in a name after the drive on Windows, an NTFS alternate data stream such as `x.svg:evil` (#3604); previously: Object → Expand… dimmed while the selection has an appearance Expand Appearance expands (`object.expand.info`'s `appearance`, #3089); previously: brush library panels (`window.brushLibrary`, `window.brushLibrary.other`, `ui.saveBrushLibrary`); previously: Transform Each opens on the values it was last confirmed with; its Copy button confirms with `copy: true` (#1732); previously: panel docking on craft-ui's layout: `ui.docking`, the parameters of `window.panel.float` and `window.panel.dock`; previously: `ui.screenshot`'s 64 MiB inline-PNG cap and its path-plus-data downgrade; symbol library panels (`window.symbolLibrary`, `window.symbolLibrary.other`, `ui.saveSymbolLibrary`); synthetic input budgets (#1709); bounded transport waits (#1726). `vectorcraft --control ` listens on `127.0.0.1:` (loopback only). The port must be a number from 1 to 65535 (`--control=` works too), given once; otherwise the app prints an error and exits @@ -105,8 +105,8 @@ the two can still win that race. | `ui.dialog.set` / `.confirm` / `.cancel` | `{field, value, action?}` or `{fields: [{field, value}…], action?}` | fill and submit the open dialog. `ui.dialog.set` takes the fields the dialog has (`ui.inspect`) other than its `__` fields, the `__` fields that are controls of the dialog (such as `__section` and `__allArtboards` in Save PDF, `__constrain` in Transform Each and the shape dialogs, and `__search` and `__category` in Preferences; Save PDF's and Print's `__savePresetAs`, the preset name, only while Save Preset… asks for it, since OK then saves a preset), `discard` on a dialog with a discard button, `preview` on one with a live preview, the fields that the dialog reads but adds only when a control changes (such as `searchFolder`, or `copy` in the Transform dialogs), and the fields it passes to the command it runs: every parameter of the `command` dialog's command (`ui.paramDialog`), and the `textureImage` that Load Texture… sets in the Glass, Texturizer and Rough Pastels effects; any other field is an error that lists the dialog's fields, and the dialog stays as it was. Any other `__` field, held or not, holds what the dialog's OK acts on (such as the `__command` and `__params` of a `confirm` or `command` dialog) or the dialog's own state: setting it is the error "the `` dialog cannot set protected field ``", and the dialog stays as it was. `fields` sets the list (at most 256 items) in order (a missing `value` is `null`) and checks every item first: when one is refused, the call is an error and no field changes. `action: "confirm"` or `"cancel"` on `ui.dialog.set` then confirms or cancels the same dialog in the same request, as `ui.dialog.confirm` and `ui.dialog.cancel` do, and the reply is `{dialog, result}`: the dialog after the fields were set and the reply to confirm (`null` for cancel); any other `action` is an error and no field changes | | `ui.screenshot` | `{path?, data?}` | capture the window (PNG), written to `path`; `data: true` sends it back as `pngBase64` too. The inline PNG is capped at 64 MiB: with a `path` the file is still written and `pngBase64` is omitted when the image is larger, while a path-less `data: true` request fails if either the raw RGBA image or the encoded PNG exceeds the cap. Needs a presented frame: with the screen locked or the window minimized/covered it fails after ~8 s with an explanatory error | | `ui.render` | `{path?, scale?, artboard?, data?, traceViews?}` | render an artboard headlessly (PNG with the pixels of `app.export {format: "png", background: "white"}` at the same scale; `artboard`: its 0-based index, default the first; `traceViews: true`: Image Trace objects draw in their View, as on the canvas, instead of their tracing result): written to `path`, else (or with `data: true` as well) sent back as `pngBase64` | -| `ui.render` | `{path?, scale?, artboard?, data?}` | render an artboard headlessly (PNG with the pixels of `app.export {format: "png", background: "white"}` at the same scale; `artboard`: its 0-based index, default the first): written to `path`, else (or with `data: true` as well) sent back as `pngBase64` | -| `ui.resize` / `ui.focus` | | | +| `ui.resize` | `{width?, height?}` | request the window's inner size; omitted or null `width` and `height` default to 1440 and 900. Returns `null` | +| `ui.focus` | `{}` | request keyboard focus for the window. Returns `null` | | `app.open` / `app.save` / `app.export` / `app.quit` | `{path, importer?, params?}` / `{path?}` / `{path?, format?, artboard?, range?, scale?, …}` | `app.open` reads every format `document.open` reads (see `document.formats`) and returns its result (`{index, title, format, warnings, …}`; `warnings` say what didn't come in as it was, such as an EPS shown as its preview image and why its PostScript couldn't be read), or null when a dialog asks first or a library loads. The status bar (`ui.inspect` → `ui.status`), after a line about the document's linked files when there is one (Missing linked files below), counts the `warnings` and names the first that says reading the file left something out (the notes that make Save ask before writing over it), else the first; with several, hovering it lists them in that order, as many as fit in the window (at most 30), then how many more. After `app.save`, and `app.export` with a `path`, the status bar counts the reply's `warnings` and names the first, and with several, hovering it lists them in the reply's order (a save's notes start with what the format loses). With `importer` (an importer plug-in's format id, `plugin.`) it runs `file.openWith`: the file opens with that importer, also when a built-in format reads its extension, with the importer's parameters `params` (their defaults when omitted; no dialog asks for them). Without `importer`, `params` go to the importer that opens the file, and a built-in format does not read them. `app.export` encodes through the engine's `document.export` (same options; the document keeps its path) and writes `path` through the host; without `path` it returns `{dataBase64, format, bytes}`, as headless mode does. It refuses a key that no format takes, and an unknown key inside a PDF or EPS option object, before it writes anything (`docs/mcp.md`, Parameter keys). It accepts a key that only another format takes and does not use it: the reply's `warnings` and the status bar name the key ("`quality` was not used: PDF files don't read it"). `app.save` refuses a key that no save format takes, beside the path or in `options`, the same way. `app.quit`, `file.close` and `file.closeAll` first open a `saveChanges` dialog for each modified document (they return `{"pending": "saveChanges"}`): `ui.dialog.confirm` saves, `ui.dialog.set {field: "discard", value: true}` then confirm discards, `ui.dialog.cancel` cancels the whole close or quit | | `app.export` with `useArtboards` | `{path, useArtboards: true, range? \| artboards?, …}` | Export As: PNG, JPEG and WebP write one file per chosen artboard (default all; SVG does so for a `range`), `-.`, and return `{path, files: [path…]}`; a PDF keeps them as pages of `path`. `useArtboards: false` covers the bounds of the visible art. The menu's Export As… is `file.exportAs`: the `exportAs` dialog (`format`, `useArtboards`, `all`, `range`), then a save dialog and the format's options: `pngOptions` / `jpgOptions` / `webpOptions`, `svgOptions`, or `savePdf` for a PDF | | `ui.dialog.*` on `gradientStop` | `{field: "color" \| "opacity" \| "location", value}` | double-clicking a stop on the Gradient tool's annotator opens its popover (fields `index`, `x`, `y`, `tab`); set `color` (hex), `opacity` or `location` (percentages) and `ui.dialog.confirm` to apply them to the selected stop. `gradient.selectStop {index}` picks the stop the annotator, the panels and Delete/←/→ (`ui.key`) act on | @@ -1061,6 +1061,7 @@ Commands (`panel` and every panel parameter take a panel id in any case or its d | `window.panel.activate`, `.close`, `.closeGroup`, `.closeOthers` | `{panel}` | shows and selects, or hides | | `window.panel.minimize` | `{panel, minimized?}` | minimizes a dock group to its tabs, or a floating window to its title bar; omitted toggles | | `window.panel.collapse` | `{panel, collapsed?}` | `window.panel.minimize`; returns `{panel, collapsed, layout}` | +| `window.panel.cycleOptions` | `{panel}` | shows the panel at its next display size (its Show/Hide Options states, largest first), as the double triangle on its tab strip does; a panel without sizes is an error; returns `{panel, size, sizes}` | | `window.panel.iconic` | `{panel, iconic?}` | collapses the panel's dock column to icons, or expands it | | `window.panel.layout`, `ui.dock` | `{action}` | one craft-ui `Action`, externally tagged, e.g. `{"MoveFloating":{"panel":"swatches","rect":[44,66,360,450]}}` or `{"ResizeSplit":{"path":[],"size":{"Ratio":0.35}}}`; `ui.dock` also takes craft-ui's `{operation, …}` | @@ -1137,6 +1138,7 @@ hidden tab (whose frames the browser pauses) answers when it is shown again. | Date | Change | Summary | |---|---|---| +| 2026-11-15 | minor | Completed the `ui.resize` defaults and `ui.focus` contract; kept one `ui.render` entry, including `traceViews`. Documentation only. | | 2026-11-07 | minor | Documented OpenType feature values in text commands (`"salt=2"`, the font's alternate number) and that runs differing only in features shape as one piece of text. | | 2026-10-31 | minor | Confining file access: on Windows a `:` in a name after the drive (an NTFS alternate data stream) is refused with the device names (#3604). | | 2026-10-25 | minor | Panel docking on craft-ui's layout: `ui.docking`, the floating and dock parameters, native floating windows. | diff --git a/docs/development.md b/docs/development.md index 7c22d6ae98..64b66678b5 100644 --- a/docs/development.md +++ b/docs/development.md @@ -83,6 +83,7 @@ The canvas is rasterized on the CPU (`vectorcraft-render`, vello_cpu); the GPU ( - `WGPU_VALIDATION_INDIRECT_CALL=1`: turns wgpu's check of indirect draw arguments back on. VectorCraft draws nothing indirectly and turns it off, since the compute shader it needs fails to compile on some drivers (#651). - On Linux with Mesa, `MESA_VK_DEVICE_SELECT=10de:2f04!` (vendor:device as `vulkaninfo --summary` or `lspci -nn` show it) leaves only that GPU to Vulkan, and `DRI_PRIME=1` picks the other GPU. - Help › About and the control channel's `ui.inspect` (`graphicsAdapter`) show the adapter in use, and the app logs it at startup. +- **How frames reach the display.** By default the window presents with `autovsync` and lets the display queue one frame. With `autovsync`, wgpu uses relaxed vsync (FifoRelaxed, which tears a frame that arrives late) where the driver offers it, else vsync (Fifo). For a launch, `--present-mode` (or `VECTORCRAFT_PRESENT_MODE`) sets the present mode to `fifo` (vsync), `autovsync` or `novsync` (wgpu uses Immediate, else Mailbox, else Fifo, whichever the driver offers), and `--frame-latency` (or `VECTORCRAFT_FRAME_LATENCY`) sets the frames the display may queue, `1` to `3`. A flag overrides its variable, and a value that is not one of these stops the app with a message. On Windows and Linux, a launch with either one set opens its files in a new window, as with `--new-instance`, instead of handing them to a running VectorCraft. At startup the log records what the app asks the window surface for, for example `requested window surface: autovsync, frame latency 2 (override)`. The driver chooses the mode that `autovsync` and `novsync` resolve to and may clamp the latency, and on macOS egui uses at least 2 frames while the window is being resized. The code is `apps/vectorcraft/src/presentation.rs`. ## Logs @@ -98,6 +99,8 @@ When the interface thread stays in one part of a frame for 3 s (VectorCraft's ow |---|---| | `VECTORCRAFT_CONTROL_PORT` | Same as `--control `, which overrides it; a value that isn't a port from 1 to 65535 stops the app | | `VECTORCRAFT_IN_WINDOW_MENUS` | Any value but empty or `0`: same as `--in-window-menus` (see [macOS: the menu bar](#macos-the-menu-bar)) | +| `VECTORCRAFT_PRESENT_MODE` | Same as `--present-mode`, which overrides it: `fifo`, `autovsync` or `novsync`; any other value stops the app (see [Desktop graphics processor](#desktop-graphics-processor)) | +| `VECTORCRAFT_FRAME_LATENCY` | Same as `--frame-latency`, which overrides it: `1` to `3` frames; any other value stops the app (see [Desktop graphics processor](#desktop-graphics-processor)) | | `VECTORCRAFT_NO_PREFS` | No preferences read or written, no default Data Recovery folder and no log file, and no saved PDF presets or loaded ICC profiles kept (agents' test runs; also for `vectorcraft-cli`) | | `VECTORCRAFT_CONFIG_DIR` | The folder for the preferences and the folders next to them (`PDF Presets`, `Color Profiles`, …), for the app and `vectorcraft-cli` (see `docs/control-protocol.md`) | | `WGPU_POWER_PREF` | Graphics adapter: `low`, `high` or `none` (see [Desktop graphics processor](#desktop-graphics-processor)) | @@ -294,7 +297,10 @@ other `sv-*` locale resolve to it), Georgian (`ka`, complete; `ka-GE` and `ka_GE control channel, MCP and tests read them) and are translated only where the status bar draws them (`i18n::msg`). `@msg` catalog rows hold a whole message or a template such as `Couldn't open {name}: {e}`; `{_1}`, `{_2}` … stand for the format string's `{}`, and the values in the - placeholders are translated in turn (the reason after `: {e}` is often a message too). A literal brace in a + placeholders are translated in turn (the reason after `: {e}` is often a message too). A value that starts with + `{` is translated only when it has an exact row, so a JSON object stays as it is; a value that starts with `[` is + also matched against a template that starts with `[` and an index of digits, such as an effect's refusal + ``[{j}] `{_1}`: {why}``, so its reason is translated while a JSON array stays as it is. 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, Hindi, Hungarian, Italian, Japanese, Korean, Polish, Brazilian Portuguese, Russian, Simplified Chinese, Traditional Chinese, Swedish, Ukrainian, Vietnamese, Finnish, Turkish, Catalan, Dutch and Danish diff --git a/docs/effects-parity.md b/docs/effects-parity.md index 14f93dcfa5..74d2ac8f63 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 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 | +| 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, skewed or unevenly scaled object in an imported SVG is kept and runs in that object's user space, and SVG export writes it back under the same transform. A blur or drop shadow that blurs more in one direction than another in the document (two different standard deviations, or one in a skewed or unevenly scaled user space) is kept as this effect rather than opened as an even Gaussian Blur or Drop Shadow | | 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 @@ -181,9 +181,9 @@ VectorCraft choices; an original approximation, never compared with another appl | Revolve | initial: live, editable profile, rotation and light gizmos, default-on Cap with continuous curved rims, smooth vector shading and round seam joins, overlapping faces drawn in the order of their depths where they overlap, SVG/PDF output, Expand Appearance ([revolve.md](revolve.md), #846) | | Extrude & Bevel, Inflate, Rotate | initial: live, round seam joins, depth, twist, taper, solid or hollow caps, five original bevel shapes, Inflate volume, both sides, twist, taper and cap, Rotate of every fill and stroke, groups and layers turned about one shared axis (#4506), contours that cross, touch or overlap merged first ([three-d.md](three-d.md)), Position presets, rotation and light gizmos, SVG/PDF output, Expand Appearance ([three-d.md](three-d.md)) | | Materials panel, lighting, ray-traced render | Window › 3D and Materials panel with the object types (Plane, Extrude, Revolve, Inflate) and the Object, Rotation and Lighting settings of the applied effect, Render Settings › Wireframe, which draws the live effect as the edges of its faces, and Quick Actions › Expand as Wireframes ([three-d.md](three-d.md#3d-and-materials-panel)); one to ten directional lights with per-light Color (opaque RGB, white by default), Intensity, Rotation, Height, Softness and neutral Ambient Light, Revolve and colored Inflate use smooth vector shading; Extrude & Bevel and Rotate retain planar shading; original Standard, Diffuse, Top Left and Right lighting rigs; hard-edged shadows behind or below the object from the first light ([three-d.md](three-d.md#shadows)); the Materials tab's Graphics, document symbols mapped onto Extrude & Bevel's caps and onto a plane, moved with an artboard handle, and wrapped around Revolve's side ([three-d.md](three-d.md#graphics)); no base materials, graphics on Inflate or on Extrude & Bevel's walls and bevels, soft shadows or ray tracing | -| 3D (Classic): Extrude & Bevel, Revolve, Rotate | Extrude & Bevel (Classic) initial: live, round seam joins, Extrude Depth, Cap, five original bevel shapes with Height and Bevel Extent In or Out, Position presets and rotation gizmo, Perspective, Wireframe, No Shading, Diffuse and Plastic surfaces with one to ten lights, Light Intensity, Ambient Light, Highlight Intensity and Size, Blend Steps, Black, Custom or no Shading Color, Draw Hidden Faces ([create 3D objects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/create-3d-objects.html)); Revolve (Classic) initial: live, round seam joins, Angle, Cap, Offset from the left or right edge, Position presets and rotation gizmo, Perspective, the same four surfaces, lights, highlight, Blend Steps and Shading Color, groups and layers revolved about one shared axis (same page); Rotate (Classic) initial: live, round seam joins, every fill and stroke turned as one plane, Position presets and rotation gizmo, Perspective, No Shading and Diffuse surfaces with lights, Ambient Light, Blend Steps and Shading Color ([rotate objects in 3D](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/rotate-objects-in-3d.html)); Preserve Spot Colors in all three, unavailable with a Custom Shading Color ([Preserve Spot Color](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=260)); Map Art: none | +| 3D (Classic): Extrude & Bevel, Revolve, Rotate | Extrude & Bevel (Classic) initial: live, round seam joins, Extrude Depth, Cap, five original bevel shapes with Height and Bevel Extent In or Out, Position presets and rotation gizmo, Perspective, Wireframe, No Shading, Diffuse and Plastic surfaces with one to ten lights, Light Intensity, Ambient Light, Highlight Intensity and Size, Blend Steps, Black, Custom or no Shading Color, Draw Hidden Faces ([create 3D objects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/create-3d-objects.html)); Revolve (Classic) initial: live, round seam joins, Angle, Cap, Offset from the left or right edge, Position presets and rotation gizmo, Perspective, the same four surfaces, lights, highlight, Blend Steps and Shading Color, groups and layers revolved about one shared axis (same page); Rotate (Classic) initial: live, round seam joins, every fill and stroke turned as one plane, Position presets and rotation gizmo, Perspective, No Shading and Diffuse surfaces with lights, Ambient Light, Blend Steps and Shading Color ([rotate objects in 3D](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/rotate-objects-in-3d.html)); Preserve Spot Colors in all three, unavailable with a Custom Shading Color ([Preserve Spot Color](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=260)); all three: a lighting sphere on the Lighting tab whose lights drag, move to the back or front, and are added at the front center or deleted down to one ([lighting options](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=272)); all three: the track cube (face, edge, Shift and ring drags, keyboard steps; [three-d.md](three-d.md#track-cube)); Map Art: none | | Turntable (30.0 beta) | none | -| Export 3D objects (OBJ, USDA, glTF) | initial: Asset Export's Export 3D Object collects an object with Extrude & Bevel, Revolve, Inflate or Rotate as a 3D asset, and Export writes its solids as a USDA (the default), USDZ, glTF or OBJ mesh with a material in each solid's paint color (`assets.add3D`, `assets.set3DFormat`, `assets.export3D`); no textures, map art or shading ([3D export help](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/export-3d-vector-artwork.html)) | +| Export 3D objects (OBJ, USDA, glTF) | initial: Asset Export's Export 3D Object, and the 3D and Materials panel's Export 3D Object button (which then shows Asset Export with the new assets selected, [three-d.md](three-d.md#3d-and-materials-panel)), collect an object with Extrude & Bevel, Revolve, Inflate or Rotate as a 3D asset, and Export writes its solids as a USDA (the default), USDZ, glTF or OBJ mesh with a material in each solid's paint color (`assets.add3D`, `assets.set3DFormat`, `assets.export3D`); no textures, map art or shading ([3D export help](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/export-3d-vector-artwork.html)) | The `three-d` crate (depends on `geom` and `pathops`, with no UI or GPU dependencies) builds, rotates, projects, shades and depth-sorts the surfaces; the effects crate turns them into art. What's left (materials and shadows, ray-traced rendering, diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 207cf5bc1b..7a73bdc4c1 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -294,7 +294,7 @@ Names in the editing data that aren't UTF-8 (layers, objects, artboards, colors, | 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 | | EMF / WMF | open, export | yes | yes | an oversized embedded PNG or JPEG is refused from its header, before any pixels are decoded (#1776) | -| PSD | open, place, export | yes (open: layers as layers, or the merged image with `layers: false`; place: merged image; the merged image comes in clipped by the file's clipping path; every mode and depth; `.psd` and `.pdd`) | yes (layered, max editability) | placing as layers and a PSD import options dialog missing; the embedded ICC profile's tags are 4-byte aligned (#1584) | +| PSD | open, place, export | yes (open: layers as layers, or the merged image with `layers: false`; place: merged image, or the layers embedded as a group of objects with `layers: true`; the merged image comes in clipped by the file's clipping path; every mode and depth; `.psd` and `.pdd`) | yes (layered, max editability) | PSD Import Options on File › Open and on File › Place without Link (Convert Layers to Objects, Flatten Layers to a Single Image, Import Hidden Layers, Import Slices; `tests_psdlayers.rs`, `dialogs/psd_import.rs`); slices (image resource 1050, version 6 and the version 7 and 8 descriptor) open and embed as user slices with `importSlices` (`tests_psdslices.rs`); layer comps aren't read; the embedded ICC profile's tags are 4-byte aligned (#1584) | | PSB | open | yes (layers as layers, or the merged image; the merged image comes in clipped by the file's clipping path) | no | | | PNG / JPEG / GIF / BMP / TIFF / Targa | open, place, export | yes (PNG: `.png` and `.pns`; BMP: `.bmp`, `.dib` and `.rle`; Targa: `.tga`, `.vda`, `.icb` and `.vst`, raw or run-length encoded, with a 16-bit file's one-bit alpha) | yes; TIFF is also selectable in Export for Screens and Asset Export with its existing options | Targa: `tests_tiffbmp.rs`, `tests/links.rs`; TIFF: grayscale with an alpha channel or other extra channels reads (#1466 in part), and so do files that store each channel as its own plane (PlanarConfiguration 2), CMYK ones with their ink amounts, and 1-bit files compressed with CCITT Group 3 (Compression 2 and 3, one- and two-dimensional rows); the ICC profiles embedded in JPEG and TIFF have 4-byte aligned tags (#1584); PNG export marks its colours as sRGB (`embedIcc`, an `sRGB` chunk; no ICC profile is embedded, #2221) | | WebP | export (Export for Screens) | yes | yes (lossless only; lossy written lossless with a warning) | | diff --git a/docs/gaps.md b/docs/gaps.md index ef9bf6e150..6be95c171b 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,10 +1,10 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-15 · **Change:** minor (G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; 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 , 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 (G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; 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 , 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 -**Feature evidence last updated:** 2026-11-14. +**Feature evidence last updated:** 2026-11-15. Raster rendering fits and preflattens curved stroke outlines more tightly only below four times the raster tolerance, retaining thin-band coverage without changing stroke weight or vector export geometry. Current cached character/object outlines, cropped long strokes, gradient clips and effect rasters share the helper; cropped-region reuse and guarded flattening remain. The unchanged `fractional_curved_strokes_retain_coverage_between_notches` regression covers fractional weights, rotation, phase, opacity and f32-rounded endpoints. This is a quality/cost tradeoff, not a speed claim. Scores and estimates unchanged. @@ -34,9 +34,11 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-15 | minor | G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…, `ui.checkSpelling`, #4936) with Not in Dictionary sentence context, suggestions, Ignore, Ignore All, Change, Change All, Add to Dictionary, Done/Cancel, keyboard navigation, and one-step Undo/Redo; spell check complete; scores and estimates unchanged. | | 2026-11-15 | minor | G5: Neon & Glow joins Shadows and Glows, Outlines and Rules, Hand-Drawn, Textures, Painted and Sketched, Gradient Finishes, Shape Effects, Blends and Transparency, Game HUD and Status Effects as an eleventh built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor; original procedural styles generated in code); estimate unchanged (3–13 h). | | 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-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 on the merged branch (all 13 gates), including the test-helper correction for the upstream compile error tracked in #7727; native Windows full CI has two unchanged engine-test failures. Scores and estimates unchanged. | | 2026-11-14 | minor | G5: Tech Circuit adds three original procedural brushes (Circuit Trace, Bus Lines, Terminal Nodes); ten built-in brush libraries. G5 remaining estimate 3–13 h (estimated); parity scores and headline totals unchanged. | | 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 ``, 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. | @@ -457,10 +459,10 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Done:** COLR and SVG glyphs go with type that geometry effects reshape, into Expand Appearance and EMF/WMF export, where the type's outlines used to leave them out; bitmap glyphs (emoji) too, as images that hold their own pixels until a document takes them in; estimate unchanged. +- **Done:** spell check (#4936): engine (`text.spelling.check` and `text.spelling.suggest` on craft-proof); custom dictionary and Ignore All (`text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary`, `ignoreAll`); Auto Spell Check (`edit.autoSpellCheck`) with red wavy underlines and canvas context menu suggestions, Ignore All and Add to Dictionary; Edit › Edit Custom Dictionary…; and modal Check Spelling dialog (Edit › Spelling › Check Spelling…, `ui.checkSpelling`) with sentence context, suggestions list, "Change to" edit, Ignore, Ignore All, Change, Change All, Add to Dictionary, Done, Cancel, and keyboard navigation. Estimate unchanged. - **Missing:** CJK vertical composition (custom mojikumi sets and the Mojikumi Settings dialog, kinsoku settings #633, manual tate-chu-yoko), Middle Eastern - features beyond bidi, digit types, Character Direction and Kashidas (Middle Eastern composers, a split caret), spell check (its engine is done, #4936: `text.spelling.check` and - `text.spelling.suggest` on craft-proof; the custom dictionary and Ignore All commands; Auto Spell Check, `edit.autoSpellCheck`, with a right-click on an underlined word offering its suggestions, Ignore All and Add to Dictionary, and Spelling › Auto Spell Check in the context menu of type; the Edit Custom Dictionary dialog; the Check Spelling dialog remains), + features beyond bidi, digit types, Character Direction and Kashidas (a split caret; the Middle Eastern & South Asian composers are done, #4935), Touch Type, Retype, Snap to Glyph; optional preservation of font sizes during group scaling (#1034 enhancement). Itemized in [type-parity.md](type-parity.md). - **Impact:** professional typography and Japanese/Chinese publishing. @@ -468,6 +470,8 @@ 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 on the merged branch (all 13 gates), including the test-helper correction for the upstream 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. @@ -890,8 +894,10 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | Date | Change | Summary | |---|---|---| +| 2026-11-14 | minor | Type: Middle Eastern & South Asian and Standard composers per paragraph (#4935): Paragraph panel menu, paragraph styles, `text.setFormat {composer}` and the native file; the Standard composers set Indic, Arabic and Hebrew type glyph by glyph. `.ai`, EPS and PDF files carry no composer. Scores and estimates unchanged. | | 2026-11-14 | minor | Tech Circuit adds three original procedural brushes (Circuit Trace, Bus Lines, Terminal Nodes); ten built-in brush libraries. G5 remaining estimate 3–13 h (estimated); parity scores and headline totals 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-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 on the merged branch (all 13 gates), including the test-helper correction for the upstream compile error tracked in #7727; native Windows full CI has two unchanged engine-test failures. 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. | | 2026-11-09 | minor | G4 review (#6084): positional variants no supported feature draws can be applied as glyph choices in both Glyphs views; unlisted glyphs still respect name ownership. OpenType style options keep only a valid last on-value when enabling a set. Existing contextual/ligature lookup and unsupported-feature gaps remain; estimate unchanged. | | 2026-11-07 | minor | G4: the Glyphs panel's Alternates for Current Selection applies the OpenType feature that draws a variant to that letter alone (`salt=2`; the style commands take `tag=N`; runs that differ only in their features shape as one piece of text), so an Arabic word stays joined, and Show › Entire Font lists the unencoded glyphs (#5514). Estimate unchanged. | @@ -1139,3 +1145,5 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv 2026-10-28 behavior correction: Flare ray rotation follows vertical travel at one degree per document point, independent of pointer event count. Shift freezes the current orientation; Space also freezes rotation on the first update. This is the chosen application interaction rate. Scores and estimates unchanged. ## EPS Save evidence (2026-10-26) Ordinary Save and Save As keep EPS as EPS, with the chosen page frame, transparent margins and the complete editable VectorCraft document. Existing import-loss confirmation and transparency warnings remain; the Save TIFF preview is capped at 1024 pixels, while Export retains 2048. See [file-format-parity.md](file-format-parity.md#eps-save-and-source-protection) for limits and regression evidence. This narrows G9 save-back workflow coverage; native Illustrator editing-data fidelity, parity scores and hour estimates are unchanged. Since 2026-11-12 the EPS Options of Save As show Use Artboards, unchecked by default: unchecked, the bounding box fits the visible art; checked, Save keeps the chosen page frame and margins described here. + +> **Swatches status (2026-11-15):** Item context menus are implemented and covered by headless tests; full CI passed on the latest-main integration (all 13 gates), including the updated panel-view harness; parity scores and estimates are unchanged. diff --git a/docs/image-trace-adjustments.md b/docs/image-trace-adjustments.md index 22557771e2..2bd58e4df4 100644 --- a/docs/image-trace-adjustments.md +++ b/docs/image-trace-adjustments.md @@ -20,9 +20,9 @@ its current location. Opening the controls does not add a document undo step. 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 +Logo, Line Art and Outline, and 50 in the other eight. Noise is 1 px in Technical Drawing, 5 in High Fidelity Photo and Black and White Logo, 8 in 6 Colors +and 16 Colors, 10 in Low Fidelity Photo, 15 in 3 Colors and Shades of Gray, 20 in Sketched Art, Line +Art and Outline, 25 in Default, 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 diff --git a/docs/image-trace-quality.md b/docs/image-trace-quality.md index dacf436036..b111a25fb7 100644 --- a/docs/image-trace-quality.md +++ b/docs/image-trace-quality.md @@ -237,10 +237,10 @@ Every built-in preset other than Auto Color and Flat Logo traces at Paths 50. Co | 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 | +| 6 Colors | 50 | 50 | 8 | 65, 60, 16 | +| 16 Colors | 50 | 50 | 8 | 70, 55, 10 | | Shades of Gray | 50 | 50 | 15 | 60, 50, 10 | -| Black and White Logo | 50 | 75 | 25 | 95, 80, 8 | +| Black and White Logo | 50 | 75 | 5 | 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 | @@ -248,7 +248,9 @@ Every built-in preset other than Auto Color and Flat Logo traces at Paths 50. Co | 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. +versions of these presets use the same Paths, Corners and Noise. 6 Colors and 16 Colors were at Noise 15 +and Black and White Logo at 25 until [Noise joins the nearest color](#noise-joins-the-nearest-color); +the measurements below were made at those values. 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 @@ -309,6 +311,47 @@ identical settings on unchanged current source and the candidate, including sepa crops and white-composited PNG comparisons. These local fixtures are not repository assets. The parity score is unchanged. +## Noise joins the nearest color + +A region below Noise used to join the color it shares the longest border with. Along a thin dark +line on a light ground, a dark speck of the line touches the ground on more sides than the line, so +it joined the ground and the line broke into dashes. Now, when the color of the longest border is +10 or more apart from the region's own color (Oklab × 100), the region joins the neighboring color +nearest the average of its pixels, among the colors that share at least a tenth of the longest +border. The average is taken in the image as prepared for tracing (deblocked, and smoothed for a +photo) and leaves out the semi-transparent pixels along a cut-out image's edge that are the color +beside them blended with the transparent background. A single pixel whose longest border is tied +between colors keeps the previous rule. The rule changes only which +color a region joins, and higher Noise still continues the same merge sequence. It applies in Color +and Grayscale: in Black and White a region has only one neighboring color. The values are +VectorCraft's own. 6 Colors and 16 Colors move from Noise 15 to 8, and Black and White Logo from 25 to 5. +The new Noise values were chosen with the rule in place, and the measurements below include both +changes. + +Measured on 17 local images (synthetic shapes and photos at several sizes, a geometric drawing and +eight illustrations; not repository assets), against `main` at `ea3f81d9c3`, with the mean absolute +difference per channel (0 to 255) against the image on white: + +| preset | three illustrations with fine dark lines | four other illustrations | synthetic shapes and photos | +|:--|:--|:--|:--| +| 16 Colors | 8.15 / 10.80 / 8.69 → 5.82 / 6.25 / 6.01; anchors +72% to +99% | −1.8% to −11.9%; anchors +20% to +39% | within 0.08 of a level; anchors 0% to +37% | +| 6 Colors | 7.24 / 9.14 / 9.21 → 5.87 / 6.66 / 7.87; anchors +55% to +73% | −0.6% to −3.5%; anchors +13% to +20% | within 0.03; anchors 0% to +22% | +| High Fidelity Photo | 8.42 / 10.11 / 7.46 → 6.85 / 7.54 / 6.00; anchors +31% to +51% | −1.4% to −5.8%; anchors −9% to +4% | within 0.08; anchors −6% to +5% | + +With Black and White Logo, where only the Noise value changes, the pixels that differ from the image +thresholded at 128 fall from 2.00 / 2.42 / 1.96% to 1.49 / 1.58 / 1.23% on the three illustrations, +with 37% to 64% more anchors, and from 1.19 to 2.37% to 1.14 to 1.94% on the other four, with 5% to +41% more anchors; the synthetic inputs change by 0.01% or less. On a simple flat illustration the +difference changes by 1.0% or less in every preset, with up to 21% more anchors, and the geometric +drawing keeps its anchor count and difference in every preset. Tests: +`a_dark_speck_beside_a_dark_line_joins_the_line`, `a_speck_close_to_its_longest_border_color_joins_it`, +`a_color_with_a_short_border_is_not_chosen`, `a_lone_pixel_tied_between_colors_merges_by_border`, +`a_speck_of_settled_cut_edge_pixels_merges_by_border`, `noise_still_removes_every_region_below_it` and +`a_source_that_does_not_cover_the_labels_is_not_read` in `crates/trace/src/quantize/denoise.rs`. +`the_borders_of_a_gradients_bands_follow_its_contours` now traces at Noise 15: at 16 Colors' new +Noise 8 the borders of its noisy gradient stray 0.92 px from the contours, above the test's 0.9 px +limit. + ## Pieces returning to a junction An outline piece can return to its starting junction while being fitted as an open chain. At loose Corners/Paths settings, a nonzero positioned boundary could collapse to one cubic and lose a small diff --git a/docs/mcp.md b/docs/mcp.md index 31536f4d6c..245171f408 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1,6 +1,6 @@ # VectorCraft MCP server -> **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. +> **Last updated:** 2026-11-14 · **Change:** `text.setFormat {composer}` and paragraph styles also take `standardSingleLine` and `standardEveryLine` (#4935); existing values and responses unchanged. Previously: 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. > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). @@ -255,9 +255,12 @@ the suite) keep the agent to the folders you give it: paths kept of them and each data set's image, in every symbol, pattern, graph design and brush, used or not, colorized or not, and a stored brush entry that does not read as a brush is refused too, since its links cannot be checked. Otherwise the images of the art the file writes, - in opacity masks and in the symbols, patterns and brushes that art uses, are checked: hidden layers and - objects only with `hiddenLayers` (a save keeps them unless it is `false`), and template layers and the - layer of opacity-mask or symbol editing mode never. `selectedOnly` and `document.exportSelection` check the + in opacity masks, in the art drawn for placed documents and in the symbols, patterns and brushes that art + uses, are checked: hidden layers and objects only with `hiddenLayers` (a save keeps them unless it is + `false`), also inside symbols, patterns and graph designs, and template layers and the layer of + opacity-mask or symbol editing mode never. With `profile: "tiny12"` the file leaves out opacity masks, and + their images are not checked. An object whose effect SVG has no filter for is checked as the image the file + draws of it. `selectedOnly` and `document.exportSelection` check the selected objects only, and `clipboard.exportSvg` checks the copied objects, following a relative path from the document they came from while it is open; in a frame a request drives, Copy then puts no SVG on the system clipboard. An image whose pixels the document holds exports embedded, and a URL is not checked. @@ -628,7 +631,9 @@ For `draw_shape` and `draw_path`, omitted paint fields inherit the current [new- For a filled shape or path without an outline, pass an explicit `fill` and `stroke: "none"`. Lines start with no fill and a visible stroke. The Fill/Stroke proxy commands run through `run_command`: `paint.invert` and `paint.complement` recolor the active -proxy, including a grayscale image's colorized fill, while keeping each color's model. `paint.lastColor` / +proxy, including a grayscale image's colorized fill, while keeping each color's model. Given a group without an +Appearance item, they recolor the active proxy's fills or strokes of the objects inside it and of the group itself; +`target: "contents"` leaves the group's own fills or strokes as they are. `paint.lastColor` / `paint.lastGradient` re-apply the last solid color or gradient, and `paint.recent` returns the recent colors that every paint command (and the eyedropper) feeds: up to 30, newest first and each once, kept across documents for the session. `paint.proxies` returns what the proxies show: the fill and stroke, which one is active, and whether the selected @@ -849,15 +854,17 @@ inside a series group other than a path directly in it, a legend swatch's includ reached through `target: "contents"`. These commands leave that art out, edit the other objects they are given, and are an error when all their objects are design art: the `appearance.*` commands listed above, `effect.apply`, `appearance.addEffect` and the other `effect.*` commands that edit, move or remove an effect, -`effect.expandAppearance` (which also leaves the art inside a selected graph or series group as it was, unless an -effect of that group turns the whole group into other art, and is disabled when only design art is selected or -given), `threeD.mapGraphic`, +`effect.expandAppearance` (which also leaves the art inside a selected graph or series group as it was, except that +an effect of that group which reshapes or replaces the whole group bakes into that art too, and is disabled when only +design art is selected or given), `threeD.mapGraphic`, `graphicStyle.apply`, `graphicStyle.addFromLibrary` with `apply`, `graphicStyle.breakLink`, `transparency.set`, the `paint.freeform.*` commands that edit points and lines, and `appearance.copyFrom` as the target. `appearance.transfer` with design art as its `target`, or as its `source` without `copy`, is an error. -`paint.setFill`, `paint.setStroke`, `paint.swap`, `paint.default`, `paint.invert` and `paint.complement` with an -`item`, `stroke.set`, `stroke.weightUp`, `stroke.weightDown`, `stroke.setAdvanced`, `paint.editGradient`, -`paint.setGradientGeom` and `object.setOverprint` leave the art out without an error. When the first selected object is design art, the commands +`paint.setFill`, `paint.setStroke`, `paint.swap`, `paint.default`, `paint.invert`, `paint.complement`, +`stroke.set`, `stroke.weightUp`, `stroke.weightDown`, `stroke.setAdvanced`, `paint.editGradient`, +`paint.setGradientGeom` and `object.setOverprint` leave the art out without an error. When all their objects are design art, +`paint.editGradient`, `paint.swap`, `paint.default`, `paint.invert`, `paint.complement` and `stroke.set` also leave +the paint and stroke weight for new art and the remembered colors as they are. When the first selected object is design art, the commands do not use the Appearance panel's active row. When the first object given is design art, rows and effects given with `aligned: true` are rows of its stack in `appearance.setItem`, `appearance.removeItem`, `appearance.duplicateItem`, `transparency.set` with an `item`, `effect.apply`, `appearance.addEffect` and the other `effect.*` commands that edit, @@ -921,7 +928,8 @@ its own, can move or scale the plot at the next redraw. When all of a graph's ar 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`. +measured on `placed`. `placed` includes the labels, so in such a graph moving an outermost label on its own can move or +scale the plot at the next redraw. 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 @@ -964,7 +972,8 @@ them in the Swatches panel does); give colour group names instead to reorder the in the app runs `paint.setFill` (or `paint.setStroke`, the active proxy) with `ids: [the object under the pointer]`. The Swatches panel menu's commands: `swatch.addUsedColors {selection?, global?}`, `swatch.unused` (a query: the names Select All Unused selects; a spot swatch counts as used while an image placed from a DCS file has a plate of -its ink), `swatch.merge {names}` (the first is kept), `swatch.ungroup {name}` and +its ink), `swatch.merge {names}` (the first is kept; gradient stops linked to the others drop their process +plates), `swatch.ungroup {name}` and `swatch.sortByKind`. `brush.move {name | names, to?, type?}` reorders brushes among the brushes of their type, as dragging one onto another of its type in the Brushes panel does. `to` is an index among the brushes of that type in `brush.list` @@ -1312,7 +1321,7 @@ unknown label is refused. The `warnings` of the result name the first three such Opening a PDF (or `.ai`) imports every page as an artboard and layer; `document.open` takes `pages` ("2-3, 5", 1-based), `cropTo` (`bounding` (the art's bounds), `art`, `crop` (default), `trim`, `bleed`, `media`: the box each artboard gets; -with `trim` the bleed box round it becomes the document's bleed, and a PDF-compatible `.ai` or a PDF saved with its editing data opens on its trim boxes for +with `trim` the bleed box round it becomes the document's bleed and the artboards are 36 pt apart plus that bleed on both sides, and a PDF-compatible `.ai` or a PDF saved with its editing data opens on its trim boxes for `crop`, its crop box taking the bleed in) and `password` for an encrypted file. `document.pdfInfo` reads a file without opening it: the page count, each page's size and boxes, `needsPassword`, and with `thumbnail: n` a PNG of page n. It reads a PostScript file (an EPS, a `.ps` file, a `.ai` in PostScript form) as one page the size of its bounding box (a US Letter page without one), with an @@ -1419,9 +1428,11 @@ Drive a tool like a mouse: Edit a gradient with the Gradient tool's annotator (the bar runs along the vector; stop chips sit 10 px under it, midpoint diamonds 7 px above): a click on the bar adds a stop, dragging a chip moves it (drag it off the bar to -delete it, hold Alt to copy it), dragging the end handle changes the vector. Both ends of a vector drawn on the art, -the start of one a click applies, and the dragged start and end handles snap as drawn points do; with Shift, the end -or the handle keeps to 45° steps and snaps along them. The selected stop +delete it, hold Alt to copy it), dragging the end handle changes the length (the end stays on the bar's line, at +least 10 px from the start), and Alt-dragging it changes the length and angle together. Both ends of a vector drawn +on the art, the start of one a click applies, and the dragged start and end handles snap as drawn points do (the end +handle without Alt only onto points on the bar's line); with Shift, the end of a drawn vector, the Alt-dragged end +handle or the start handle keeps to 45° steps and snaps along them. The selected stop (`gradient.selectStop`) takes Delete and ←/→: ```json @@ -2860,7 +2871,10 @@ group selected on its own, or, for `symbolInstance`, an object that is not a sym leaves the selection empty. A selected object that is hidden or locked, inside a hidden or locked group or layer, on a template layer, on a locked artboard while nothing is isolated, or outside the isolated group is passed over. New art, such as a symbol instance just placed, is not passed over for being on a locked artboard while it stays selected. When -the selection holds no other object, they return the error "nothing selected". +the selection holds no other object, they return the error "nothing selected". `appearanceAttribute {item?}` takes +the fill or stroke at appearance item `item`, or the Appearance panel's active item when the call gives none or null; a +value that is not a whole number of 0 or more fails with "`item` must be a whole number" and leaves the selection as it +was. `select.similar {by?}` is the Control bar's Select Similar Objects button and the Select Similar Options menu beside it ([help](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=165)). It selects the @@ -3200,7 +3214,9 @@ number. `guide.add {vertical, pos, artboard?}` makes one (the x of a vertical guide, the y of a horizontal one, in points) → `{index}`. With `artboard` (an artboard's index) it is an artboard guide: it runs across that artboard only, moves with it (`artboard.move`, a pure move in `artboard.setProps`, `artboard.rearrange`), scales with it (`artboard.setProps {scaleArt}`), is copied with it (`artboard.duplicate`, `artboard.move {copy}`) and is -deleted with it (`artboard.delete`); without, a canvas guide runs across the whole canvas. `guide.list` → +deleted with it (`artboard.delete`); without, or with null, a canvas guide runs across the whole canvas. An `artboard` +that is not a whole number of 0 or more fails with "`artboard` must be a whole number", and an index past the last +artboard with `no such artboard`; neither adds a guide. `guide.list` → `[{index, id, vertical, pos, selected, artboard?, layer?, hidden, locked, shown, editable}…]` (`artboard` only for artboard guides; `id` is the guide's node and `layer` the layer it is on; `hidden` and `locked` are its own state, `shown` and `editable` also take its layer into account). `layer.setProps {ids: [id…], visible?, locked?}` hides or @@ -3368,6 +3384,14 @@ already walks Image Trace. Short agent entry points: `largeList`. Without `view` the command answers the current one. Each panel keeps its own view for the session, and the document does not change. An unknown panel or view is an error, and then nothing changes. It answers `{panel, view}`. +- Panel display sizes: `window.panel.cycleOptions {panel}` shows the panel at its next display size, as the double + triangle at the right end of its tab strip does, docked or floating. The sizes are the states its panel menu's Show + Options and Hide Options items set, largest first, and the smallest is followed by the largest. Align, Attributes, + Character, Color, Flattener Preview, Gradient, Info, Paragraph, Stroke and Transform have two sizes (options shown, + options hidden). Transparency has three: thumbnails and options, thumbnails alone, and neither. A panel whose + states match none of its sizes goes to its largest. An unknown panel or a panel without display sizes is an error, + and then nothing changes. It answers `{panel, size, sizes}`, where `size` 0 is the largest. The order of the sizes + and the panels that have them are VectorCraft's own. - The Brushes panel menu's Select All Unused: `brush.unused` (a query) lists the brushes no stroke paints with, in library order, and the panel selects them. Strokes in the art (opacity masks included), symbols, graph designs, pattern tiles (with the tiles that pattern editing's Cancel puts back) and graphic styles count, and so do the @@ -3541,6 +3565,11 @@ already walks Image Trace. Short agent entry points: 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}`. +- Import a data source: `variable.import {path}` (the Variables panel menu's Import…) reads a data source file by its + extension, in any case: a `.csv`, `.tsv` or `.txt` file as `dataset.import {path}` reads it, and an `.xml` file as + `variable.loadLibrary {path}` reads it, with that command's refusals, undo step and reply, plus `format` (`csv` or + `xml`). A path with any other extension, or none, is refused before the file is read. The panel menu's Import Data + Sets… and Load Variable Library… stay. - 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 @@ -3845,6 +3874,15 @@ already walks Image Trace. Short agent entry points: deleting the group removes them. The reply's `paths` and `anchors` count the traced paths only. With `keepColors` in `params`, the reply's `warnings` name each listed color that no traced color matches, and say when nothing was traced. + `noise` (Color, Grayscale and Black and White, not Flat Logo) merges areas smaller than that many pixels into a + neighboring color. Each one joins the color it shares the longest border with, unless that color is 10 or more apart from its own (Oklab + × 100). Then it joins the neighboring color nearest the average of its pixels, among the colors that share at + least a tenth of the longest border. The average is taken in the image as prepared for tracing (deblocked, and + smoothed for a photo) and leaves out the semi-transparent pixels along a cut-out image's edge that are the color + beside them blended with the transparent background. A single pixel whose + longest border is tied between two or more colors always joins by border. In Black and White an area has only one + neighboring color. These distances and fractions are VectorCraft's own values. The built-in presets 6 Colors and 16 + Colors use Noise 8, and Black and White Logo uses Noise 5. `imageTrace.presets.save {name?, newName?, preset?, enhanced?, params?}` saves tracing settings as a preset kept with the preferences: `params` over `preset`'s (default: the saved preset `name`, else Default), checked as `imageTrace.make` checks them; without `name` it is a new "Tracing Preset N", and `newName` renames a saved preset (the reply's @@ -3955,8 +3993,9 @@ already walks Image Trace. Short agent entry points: 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 + arrives and is its own undo step when it changes a paint. `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 (including a click whose drag or release crossed 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. A face that the Bucket fills has all its fills replaced by one fill with the paint, shown, fully opaque and blending normally, in the @@ -3970,8 +4009,10 @@ already walks Image Trace. Short agent entry points: `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 + defaults to the face's fill or the stroke paint the edge draws with. `livePaint.strokeEdge {scope: "connected", through}` + takes `through`, at most 4096 edge ids that the join counts as drawing with `match` whatever they draw with now; the tool + passes the edge the double-click's first click painted when that edge drew with `match` before the click. `through` with another scope, or one that is not an array of ids, is an error. `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 @@ -4580,6 +4621,18 @@ of the rows that are not excluded, in row order, and Save Prominent Colors saves {"name":"run_command","arguments":{"command":"recolor.weigh","params":{"map":[{"from":["rgb 255 0 0","rgb 128 0 204"],"to":"#00ff00"},{"from":["rgb 0 0 255"],"to":"#ffff00"}],"weights":[1,1]}}} ``` +The Assign tab's Find button (the dialog field `findColors`) finds the colors of the selected rows in the art +([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)). +While it is on and rows are selected, the art of those rows shows as the preview shows it (its current colors with +Preview off), and the rest of the selected art shows dimmed; a second click shows the art as before +([archived help, Recolor Artwork](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=149)). +As VectorCraft's own rules, a dimmed color is a 25% tint of its current color, or the nearest lighter tint (in steps +of 1%) when that tint is a color a selected row lists (`recolor.apply` gives each current color of the other rows +and the preserved colors that tint, then recolors the selected rows), a color that a selected row also lists is not +dimmed, so art that mixes colors dims only its other colors, and nothing is dimmed on the Edit tab or with no row +selected. Find changes only what the canvas shows: it records no undo step, Cancel leaves the art as it was, and OK +applies every row to the art as it does with Find off. + The `recolor.*` commands refuse parameters of the wrong form. A `limitTo` or `method` that is not a string gets the error for an unknown library or method. Other wrong-form parameters get an error that names them. `includeImages`, `includePatterns`, a row's `exclude`, `order`, `saturationBrightness` and the `white`, `black` and @@ -5569,17 +5622,30 @@ SVG Filter (New, Edit, Delete, Import…), and from the Appearance panel it edit The canvas, raster export, printing and PDF draw the filter with the object as its source graphic, its user space starting at `origin` (`[x, y]` in points, `[0, 0]` by default) with its units `scale` points (1 by default), its -object bounding box the drawn object's, and at the Document Raster Effects resolution when the view is finer. The +axes along `axes` (`[a, b, c, d]`: one unit along the filter's x axis points `[a, b]` in the document and one along +its y axis `[c, d]`, before `scale`; absent or `[1, 0, 0, 1]`, the document's axes, and `effect.setParams` sets them +back with `[1, 0, 0, 1]`, since the commands refuse `null`; each number -1000 to 1000 and `a·d - b·c` at least +0.001 from 0, or the command refuses it), its object bounding box the drawn object's, and at the Document Raster Effects resolution when the view is finer. The filter runs on coarser pixels when a morphology radius or kernel unit would span more than 32 of them, or a standard -deviation more than 512. An effect whose XML these rules refuse (from a file or a script) is not drawn or exported. The +deviation more than 512. With `axes`, the filter runs on pixels lined up with its own axes, so offsets, blurs and the +region run along them, and the result is drawn onto the object's pixels through `axes`; those pixels are about as fine +along each axis as the object's and coarser when there would be more than 4 times as many, or when a radius, kernel +unit or standard deviation would span more than 32 or 512 of them. The object's box is then +its box in that user space: a region measured against it, and a region or primitive lengths in `objectBoundingBox` +units, are measured against that box. Moving, turning, scaling or skewing the object moves `origin` with it and +leaves `axes` as they are, and `scale` too unless Scale Strokes & Effects scales it. An effect whose XML or `axes` these rules refuse (from a file or a script) is not drawn or exported. The filter is drawn and written rebuilt from its filter elements and their filter attributes alone, without comments, text, descriptions or other attributes. An image in a filter is drawn only when its bytes are a PNG, JPEG, GIF or WebP within the pixel limit. A filter region in user space given in percentages is measured against the object's box (x and y from its top-left corner), and one in em or ex or left out takes the default region of that box (10% beyond each side); these are VectorCraft's own rules. Scale Strokes & Effects scales -`scale`. SVG export writes the filter as a `` element when it is the object's last effect, its only pixel -effect and `scale` is 1 (with a region measured against the object's box, its only raster effect), with the object in a -group that places the filter's user space and such a region written in user units. The filter is written in SVG 1.1 +`scale`. SVG export writes the filter as a `` element when it is the object's last effect and its only pixel +effect (with a region measured against the object's box, its only raster effect) and SVG import can store its user +space again (`scale` and `axes` together within the import limits below), with the object in a +group that places the filter's user space and such a region written in user units. When `scale` isn't 1 or the effect +has `axes`, that group's transform is the filter's user space and the object is written in document coordinates in a +group inside the filter whose transform is the inverse, so its strokes keep their widths; SVG import reads that back +as the same `scale`, `origin` and `axes`. The filter is written in SVG 1.1 terms: `feImage`'s reference as `xlink:href`; each `feDropShadow` as the blur, offset, flood, composite and merge that [Filter Effects](https://www.w3.org/TR/filter-effects-1/#feDropShadowElement) gives as its equivalent; colors as `#rrggbb` with a flood color's alpha in `flood-opacity`; `image-rendering` as `optimizeSpeed` or `optimizeQuality`; @@ -5591,9 +5657,12 @@ whose `flood-color` is `currentColor` or with `primitiveUnits="objectBoundingBox its shadows are expanded, has no SVG 1.1 form. Neither does a filter whose written form, with its region and id, is one SVG import would not read, such as one longer than 64 KB. In that case, otherwise, and with the SVG Tiny 1.2 profile, the object becomes an image. SVG import keeps a filter that the live effects (Drop Shadow, the -glows, Gaussian Blur, Feather) can't express as an `svg.filter` effect holding the filter's XML, with `scale` and -`origin` from the object's user space, unless that user space is turned, skewed or scaled past 0.001 to 1000 points -to a unit, or the filter is styled by the document's style sheets: such a filter is left out with a warning. The native format keeps the document's filters and the effects. +glows, Gaussian Blur, Feather) can't express as an `svg.filter` effect holding the filter's XML, with `scale`, +`origin` and, when the object's user space is turned, skewed or scaled unevenly (a `rotate`, `skewX`, `skewY`, uneven +`scale` or `matrix` transform), `axes` from that user space, so the filter runs in the element's user space as +[SVG 1.1](https://www.w3.org/TR/SVG11/filters.html#FilterEffectsRegion) defines it. A filter is left out with a +warning when that user space is scaled past 0.001 to 1000 points to a unit (the square root of its area scale), its +`axes` would pass the limits above, or the filter is styled by the document's style sheets. The native format keeps the document's filters and the effects. ```json {"name":"run_command","arguments":{"command":"svgFilter.define","params":{"xml":""}}} @@ -5712,7 +5781,9 @@ the drag takes what the pen read there (the points' pressure, tilt and rotation, drag without that reading, such as a mouse drag, erases at the value itself. One Random value per drag, which way Tilt, Bearing and Rotation run, and the value itself without a reading are VectorCraft's own rules. The command refuses another mode, and a variation below 0 or past its range, and erases nothing. In the desktop app -the Eraser's tip outline at the pointer takes the angle, roundness and size the pen gives while it erases. +the Eraser's tip outline at the pointer takes the angle, roundness and size the pen gives while it erases, and the +outline of the area a drag covers takes, at each step, the tip the pen's readings give halfway along it. A Random +value shows as the value itself there, since the release draws it. `tool.setOption {tool: "eraser"}` takes the same keys. These commands refuse a string or another value that is not a number with `` `dy` must be a number, not "10" ``, @@ -5819,7 +5890,7 @@ 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 +way round, no more than an eighth of its length), measured along the path however many segments it is cut into, 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. @@ -5892,14 +5963,22 @@ are converted to, an RGB image that carries an ICC profile is converted from tha and then to the destination, instead of having its numbers read as sRGB (a profile the color engine can't read leaves them read as sRGB, with a warning); a gray image keeps its profile, as gray is not converted. An RGB destination other than sRGB that is the document's own RGB profile leaves RGB colors and RGB images as they are, so a tagged RGB image keeps its profile -there. +there. Any other image whose colors are converted (a CMYK image, or an RGB image going to a CMYK destination or to an +RGB one other than sRGB) but whose pixels are more than VectorCraft decodes or can't be written that way is left out with +the warning "an image couldn't be converted to the Output destination and is missing from the picture", rather than +written in its own colors. One whose pixel data can't be read is left out with the warning "an image couldn't be decoded +and is missing from the picture", as without a conversion. `preserveNumbers` still reads an image's numbers as sRGB. The destination is any profile `edit.colorSettings` lists (default: the document's 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). 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 +images are always untagged CMYK. Left unset (the default; `"default"` unsets it over a preset, while `null` keeps the +preset's value), `profiles` writes device colours and gray and RGB images keep the profiles they carry (not in +PDF/X-1a). Set to `none`, it also writes every image without the profile it carries, and a JPEG kept as it is without +its `ICC_PROFILE` segments, its other segments and compressed samples unchanged; PDF/A, PDF/X-3 and PDF/X-4 files keep +the profiles they tag images with. The Save PDF dialog lists the unset value as Default. `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: @@ -6122,8 +6201,12 @@ below 3 or above 1000 counts as 3 or 1000, and a fractional or negative `sides` Without `artboard`, or with an index the document doesn't have, it aligns them to the artboard under the center of the selection, or to the first artboard when no artboard is under the center. With `to: "selection"` or `"key"`, `object.align` does not use `artboard`. `select.allOnArtboard {artboard?}` (Select › All on Active Artboard) selects -the objects on artboard `artboard`, or on the first artboard when the call gives none; an index the document doesn't -have is an error. +the objects on artboard `artboard`, or on the first artboard when the call gives none or null. A value that is not a +whole number of 0 or more fails with "`artboard` must be a whole number", and an index the document doesn't have with +`no such artboard`; either leaves the selection as it was. `select.font {family, style?, scope?}` (Select Text +by Font) takes `scope: {artboards: [index…]}` the same way: an entry that is not a whole number fails with +"`scope.artboards` must contain whole numbers" before any entry is looked up, and an index the document doesn't have +fails with `no such artboard`. `object.distribute {to: "artboard", artboard?}` and `object.distributeSpacing {to: "artboard", artboard?}` (the Distribute Objects and Distribute Spacing buttons with Align to Artboard) use the same artboard as `object.align`. @@ -6601,6 +6684,22 @@ Reset Rotate View is the command `view.rotateReset`: the angle the selected objects share (`selectionRotation` in `document.inspect`, 0 when their angles differ), so their bounding box is square to the window. It returns `{angle}`, and with nothing selected it returns "nothing selected". +`view.statusBarShow` (desktop app, the Show menu that a click on the status bar's info field opens) chooses what that +field shows, with `show` set to one of these values: + +- `artboardName`: the name of the artboard the status bar's navigator shows. +- `currentTool`: the name of the tool in use. This is the default. +- `dateTime`: the date and time, as `2026-11-15 14:03`. The desktop app shows local time, and the web build shows UTC + with ` UTC` after it. +- `undos`: the active document's undo and redo step counts, as `Undos: 3 Redos: 1`. +- `colorProfile`: the profile the active document's colors use. That is the profile assigned for its color mode + (Edit › Assign Profile), or that mode's working space (Edit › Color Settings) when none is assigned or the + assigned one is not available. + +It returns the value set. The choice is kept with the UI state. A missing or other `show` fails with +``` `show` must be one of artboardName, currentTool, dateTime, undos, colorProfile ``` and leaves the choice as it was. +Without a document, the readouts that need one show a dash. + The Smart Guides preferences (Preferences › Smart Guides) apply to `pointer_gesture` with Smart Guides on (the default view) and to the mouse; they change what the tools show and how far a target pulls, and only Construction Guides change where a snapped point lands: @@ -7145,16 +7244,22 @@ that draws the image does not decode the file again. `file.place.info` describes a file without placing it and `image.info` reports a placed image's link, colour mode and effective ppi. `file.place.queue` loads the place cursor (the `place` tool) with several files: headless, drive it with `pointer_gesture` (a click places at 100% with the top-left corner there, a drag at the dragged size) and -`press_key` (Left/Right/Up/Down cycle, Escape discards the current file). `file.place`, `file.place.queue` and +`press_key` (Left/Right/Up/Down cycle, Escape discards the current file). The cursor keeps an encrypted PDF, `.ai` +or `.ait` file that it cannot read without the password, at 612 × 792 pt (VectorCraft's own size) with +`needsPassword: true` and no thumbnail; in the app a click or drag on it asks for the password, and headless it places +nothing. `file.place`, `file.place.queue` and `file.place.info` refuse, of the keys each one takes, a `link`, `replace` or `template` that is not true or false and a `thumbnail` that is not a number, naming the key, and place nothing; null is the same as leaving the key out. In the app, `file.place` asks for a file's import options before placing it: a text file without `text` (Text Import -Options), a DXF drawing without `dxf` (DXF Import Options), and a PDF, `.ai` or `.ait` file with several pages or a -password and no `page` (Place PDF). `showImportOptions: false` places such a file without asking, with the options -last confirmed in its dialog: the text options, and the DXF fit, lineweight, centering and layer choices with the -drawing at 1:1 in its own unit. A PDF is placed on page 1 (or `page`) and its crop box, and an encrypted PDF given no -`password` still asks for the password. A `showImportOptions` that is not true or false is refused, and nothing is placed. The +Options), a DXF drawing without `dxf` (DXF Import Options), a PDF, `.ai` or `.ait` file with several pages or a +password and no `page` (Place PDF), and a PSD or PSB file embedded without `layers` that has two layers or more or +slices (Place PSD). `showImportOptions: false` places such a file without asking, with the options last confirmed in +its dialog: the text options, the DXF fit, lineweight, centering and layer choices with the drawing at 1:1 in its own +unit, and the PSD conversion, hidden-layer and Import Slices choices. A PDF is placed on page 1 (or `page`) and its +crop box, and an encrypted PDF given no +`password` still asks for the password. An encrypted PDF given a `page` and no `password` asks for the password with +Show Import Options on too, and places that page. A `showImportOptions` that is not true or false is refused, and nothing is placed. The Place dialog (File › Place, or `file.place {paths}`) has a Show Import Options checkbox after Link, Template and Replace ([Place multiple files in a document](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/place-multiple-files-in-a-document.html)). It is on by default and saved with the preferences. On, each file that has import options asks for them before it is @@ -7188,12 +7293,16 @@ to}]}`. `edit.pasteWithoutFormatting` sets the labels of a pasted graph in a new graph's label character style and paragraph attributes, keeping each label's alignment and where it starts. The pasted graph no longer keeps its labels' character and paragraph formats, so a later `graph.setData` or `graph.setType` sets the labels the same way. The rest of the -graph's art is pasted as it was copied. +graph's art is pasted as it was copied. A pie's legend labels in its wedges are white on a dark wedge and black on a +light one, by the wedge colors as pasted: a wedge linked to a swatch merged with the document's takes that swatch's +color first. A global or spot swatch whose name the document gives another colour is a conflict: `clipboard.conflicts` lists them, and `swatchConflict` answers: `"merge"` (the default: the objects take the document's swatch), `"add"` (the -pasted swatch comes in renamed) or one answer per name. Pasting back into the document the objects came from uses -its resources as they are now and raises no conflict. +pasted swatch comes in renamed) or one answer per name. When a merged swatch turns a pie's wedge from light to dark +or back, the legend labels in that pie's wedges take the contrast a redraw gives them (white on a dark wedge, black on +a light one), unless the legend labels have a fill of their own. Pasting back into the document the objects came from +uses its resources as they are now and raises no conflict. Placement: `edit.paste {center}` centres the objects on a point (the app passes the view centre), else offsets them by `dx`/`dy` (the Paste Offset preference). With nothing selected, `edit.pasteInFront` / `edit.pasteInBack` put them @@ -8508,7 +8617,9 @@ becomes an asset (or one asset with `multiple: false`). ### 3D assets -Asset Export's menu item Export 3D Object (`assets.add3D {ids?, format?}`) collects each selected object (or `ids`) +Asset Export's menu item Export 3D Object and the 3D and Materials panel's Export 3D Object button +(`assets.add3D {ids?, format?}`; the button passes the ids of the selected objects that have a 3D effect and then shows +the Asset Export panel, [three-d.md](three-d.md#3d-and-materials-panel)) collect each selected object (or `ids`) that carries Extrude & Bevel, Revolve, Inflate or Rotate as a 3D asset, named after the object; an object already collected as a 3D asset keeps it, and an object without such an effect is refused. A 3D asset's Format is `usda` (the default), `usdz`, `gltf` or `obj`; the panel shows a Format row for the 3D assets it would export, and @@ -8582,6 +8693,66 @@ flattened picture every PSD file carries: Bitmap, Grayscale, Duotone, Indexed, R A document with transparency keeps it. `file.place {path}` links the file like any image (`links.update` reads it again when it changes); Multichannel files are refused. +`file.place` with `layers: true` embeds a PSD or PSB file's layers as objects instead, and `hiddenLayers: true` +brings the hidden layers in, hidden. The +[PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) +offer the conversion and the hidden layers only for a file that is opened or embedded, and a linked file shows its +flat image. The rest are VectorCraft's own rules: + +- The layers are read as `document.open` reads them (below) and placed as one group named after the file. A layer + becomes an image and a layer group becomes a group, each with the layer's name, visibility, opacity, blend mode + and opacity mask. A Pass Through group is not isolated; a group in any other mode is. +- The group takes the place the merged image would take: `at` centers the file's canvas and `rect` fits it. When + layers reach past the canvas, hidden layers included, the group is a clip group whose clipping path is the canvas. +- The layers are never linked. With `layers: true`, `link` is false unless it is given, and `link: true` is an + error. +- `hiddenLayers: true` without `layers: true` is an error. +- A file without layers is embedded as its merged image, and so is a file whose layers are all left out, with the + import's warnings. A file whose layers can't be read is embedded as its merged image with a warning. +- `file.place.queue` and `file.place.info` take `layers` and `hiddenLayers` too. + +`document.psdInfo` reads a PSD or PSB file without opening it: its `format` (`psd` or `psb`), the canvas `width` +and `height` in pixels, and the counts `layers` (group markers left out), `hiddenLayers`, `groups` and `slices` +(the slices `importSlices` brings in). A file without layer records, or whose layer records can't be read, has +`layers: 0`; a file without slices, or whose slices can't be read, has `slices: 0`. A file that is not a PSD or PSB +file is an error. + +`importSlices` brings a PSD or PSB file's slices in as user slices (Object › Slice), which Save for Web exports. +The [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) +keep the slices a file holds, and offer it only for a file that is opened or embedded. The slices are read from +image resource 1050 as the +[Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/) describes it, +in version 6 and in the descriptor of versions 7 and 8. The rest are VectorCraft's own rules: + +- `document.open` takes `importSlices`, default true, with the layers as objects and with `layers: false` alike. + The slices lie over the canvas, each clipped to it. +- `file.place` takes `importSlices`, default true when the file is embedded and false when it is linked; + `importSlices: true` with a linked file is an error. The slices move and scale with the placed art, in the same + undo step, and the reply lists their ids in `slices`. `file.place.info` counts them in `slices`, and + `file.place.queue` takes `importSlices` too. +- Each slice keeps its name, its type (Image or No Image), its link, target, message, alternative text and + background color, and a No Image slice keeps its cell text (plain text escaped as HTML). Text alignment isn't + read. A slice that follows a layer comes in as a user slice over the rectangle the file stores for it. +- Slices the file generated automatically are left out: the document lays out its own auto slices around the + others. A slice wholly outside the canvas, or without a size, is left out with a warning, and so are slices that + can't be read; the file's art comes in either way. A file without slices brings no warning. + +In the app, File › Open of a PSD or PSB file with two or more layers, or with slices, shows PSD Import Options: +Convert Layers to Objects (with Import Hidden Layers) or Flatten Layers to a Single Image, and Import Slices, which +is offered only for a file with slices and applies to either choice. File › Place shows the same dialog for such a +file placed without Link, and so does a file dropped on the canvas with Shift held. The dialog starts from the +choices made last, at first Convert Layers to Objects without hidden layers, with Import Slices. A file with fewer +than two layers and no slices, a file placed with Link, and `document.open` and `file.place` run as commands don't +show it. Several files placed together without Link load the place cursor without asking. With Show Import Options +on, each PSD or PSB file among them that would show the dialog shows it when it is clicked or dragged; with it off, +each one comes in with the choices made last. + +```json +{"name":"run_command","arguments":{"command":"file.place","params":{"path":"/tmp/poster.psd","layers":true,"hiddenLayers":true}}} +{"name":"run_command","arguments":{"command":"document.psdInfo","params":{"path":"/tmp/poster.psd"}}} +{"name":"run_command","arguments":{"command":"document.open","params":{"path":"/tmp/poster.psd","importSlices":false}}} +``` + A PSD or PSB file that names a clipping path (the saved path its clipping path resource names, in the [published PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/)) places, and opens as its merged image (`layers: false`, a file with no layers, or a file whose layers can't be read), inside a clip group whose clipping @@ -8641,8 +8812,7 @@ Each layer's pixels must fit the memory allowed for one image, and the pixels of canvases the merges make, must together fit eight times that; a file past either limit opens as its merged image, with a warning. The canvases one step of a merge holds at once must also fit the memory allowed for one image; when they don't, the layer that needed the merge comes in alone, with a warning: in the Normal mode, or as a layer of its -own instead of clipped. File › Open in the app has no PSD import options dialog: it converts the layers and leaves -hidden layers out. +own instead of clipped. ```json {"name":"run_command","arguments":{"command":"document.open","params":{"path":"/tmp/poster.psd","hiddenLayers":true}}} @@ -9068,7 +9238,11 @@ indent and bullet or number again. ``` `type.createOutlines` (Type › Create Outlines) makes a group with a path per glyph, ruby glyph and underline or -strikethrough bar, each painted as its characters are. The type object's own fills and strokes (the items around the +strikethrough bar, each painted as its characters are. When the type is scaled unevenly, sheared or flattened, each of +these paths takes only its characters' fill, and a path filled with the stroke's paint follows it: the area the +characters' stroke paints around the glyphs before the type's transform (dashes, caps, joins and alignment), transformed +with them as the canvas draws it. Under a move, rotation, reflection or uniform scale the paths keep a live stroke, its +weight and dashes scaled with the type. The type object's own fills and strokes (the items around the Appearance panel's Characters row, not the characters' formatting) go on paths of the type's whole outline: the items below the Characters row on one path under the glyph paths, the others on one path over them, in their order and with their opacity, blend mode, effects and stroke settings. Their gradients that are not placed are fixed to the type's @@ -9346,7 +9520,7 @@ a pair. The setting works only with a Kinsoku Set: with Kinsoku Set None the par and the menu item is unavailable. Off by default, for new type and for paragraphs saved before the option. It is saved with the paragraph (`bunri_kinshi` in `para`) only when on, paragraph styles carry it (Paragraph Style Options › East Asian Composition Settings), and Reset Panel turns it off. A value that is not true or false is refused. One undo -step. `.ai` editing data does not hold it, and a save reports a paragraph with it on and a pair in it as left out. The help page: +step. An `.ai` save writes it with each paragraph, under Kinsoku Set None too, and it reopens as set. The help page: https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html ```json @@ -9480,9 +9654,15 @@ around them ([the help page](https://helpx.adobe.com/illustrator/using/formattin the default and how the space is measured are VectorCraft's own rules: the value is from 0 to 100, 0 by default and saved only when not 0, and it is the share of the blank space on each side of a character's ink, inside the character's own width, that is taken away. 50 halves that space, and 100 sets the ink against the characters before and -after it; the glyph keeps its shape. 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. Tsume applies to horizontal type; vertical type keeps its spacing. Character styles carry it +after it; the glyph keeps its shape. The ink of a color glyph is the color art or bitmap drawn for it, not its outline. +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 takes +it too ([the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/format-east-asian-characters-in-vertical-text.html)): +a character that stands upright loses the share of the space above and below its ink, inside its cell down the column +(its vertical advance from the font's vertical metrics, else at least one em, with the Proportional Metrics change to +it), and moves up with it; a character lying on its side is measured along its own width, as in horizontal type; the +characters of a tate-chu-yoko block move closer across the column, and the block keeps its one em down the column. A +mark in an upright character's cluster moves with it, and Tsume measures the character's own ink only. Character styles carry it (`charStyle.new`, `charStyle.setAttrs` and `charStyle.edit` refuse a value outside the range). A value that is not a number is refused with `` `tsume` must be a number ``, and one outside the range with `` `tsume` must be from 0 to 100 ``. One undo step, and a call that gives the value the characters already have records none. With Show East Asian @@ -9961,6 +10141,30 @@ A digit the font lacks comes from a fallback font. Default and saved only when s {"name":"run_command","arguments":{"command":"text.setFormat","params":{"digits":"hindi"}}} ``` +## Adjust Diacritic Position + +`text.setFormat {diacriticHorizontal?, diacriticVertical?}` (the selected type, or `ids`) and +`text.setRangeStyle {id, start, end, diacriticHorizontal?, diacriticVertical?}` (a range) move the characters' diacritical +marks relative to their letters, as the Character panel's Adjust Horizontal and Adjust Vertical Diacritic Position do +([the reference, page 549](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=549)). +The units, range and direction are VectorCraft's own rules: each value is in thousandths of an em of the characters' size, +from -1000 to 1000; a positive horizontal value moves the marks right and a positive vertical value moves them up. Only +glyphs the font classes as marks (GDEF class 3) move; the letters keep their places and advances, and a font without +mark classes moves nothing. An Arabic harakat or a Hebrew point styled apart from its letter takes its own values; +other marks take the values of their letter. Setting one value leaves the other as it is. Both are 0 by default and +saved only when not 0, and character styles carry them (`charStyle.new`, `charStyle.setAttrs` and `charStyle.edit` +refuse a value outside the range). A value that is not a number is refused with `` `diacriticHorizontal` must be a +number ``, and one outside the range with `` `diacriticHorizontal` must be from -1000 to 1000 ``, naming the key. One +undo step, and a `text.setFormat` call that gives the values the characters already have records none. With Show Indic Options +on, the Character panel shows both fields, blank where the selected characters differ, with -200, -100, -50, +0, 50, 100 and 200 in their menus, and a value typed past either end sets that end; Reset Panel sets both to 0. +Character Style Options shows both fields in Advanced Character Formats. The canvas, PDF export and outlines draw the +moved marks; SVG export writes type with a moved mark as outlines. + +```json +{"name":"run_command","arguments":{"command":"text.setRangeStyle","params":{"id":12,"start":2,"end":4,"diacriticVertical":150}}} +``` + ## Font height reference `text.setFormat {fontHeightReference: "emBox"|"capHeight"|"xHeight"|"icfBox"}` (the selected type, or `ids`) and @@ -10282,7 +10486,7 @@ attribute map in one undo step. `to` is trimmed and must be unique. The command while preserving local overrides; Undo/Redo restores the definition and its users. The `charStyleOptions` dialog exposes `name`, `font_family`, `font_style`, `size`, `leading`, `kerning`, `tracking`, `case`, `position`, `underline`, `strikethrough`, `charAlign`, `h_scale`, `v_scale`, `baseline_shift`, `tcyUpDown`, -`tcyLeftRight`, `rotation`, `akiLeft`, `akiRight`, `tsume`, `language`, `fill`, `fill_tint`, `stroke`, `stroke_tint`, `stroke_width`, `overprint_fill`, `overprint_stroke`, +`tcyLeftRight`, `rotation`, `akiLeft`, `akiRight`, `tsume`, `diacriticHorizontal`, `diacriticVertical`, `language`, `fill`, `fill_tint`, `stroke`, `stroke_tint`, `stroke_width`, `overprint_fill`, `overprint_stroke`, `ot_figure`, `ot_position`, `ot_liga`, `ot_calt`, `ot_dlig`, `ot_swsh`, `ot_salt`, `ot_titl`, `ot_ordn`, `ot_frac`, `ot_sets`, `section` (`general`, `basic`, `advanced`, `color` or `opentype`), and `preview`. An empty field leaves its attribute unset. `leading` and `kerning` also accept `Auto` to store an explicit automatic value. @@ -10291,7 +10495,9 @@ Advanced Character Formats holds `h_scale` and `v_scale` (percent, 1 to 10000), -1296 to 1296, as `text.setRangeStyle` takes them; an explicit 0 stays distinct from unset), `rotation` (degrees, stored from -180 to 180), Insert Aki Left and Right `akiLeft` and `akiRight` (thousandths of an em, with the Character panel's 0, 250, 500 and 1000 in their menus; a value typed below 0 or past 1000 sets 0 or 1000), Tsume `tsume` (percent, with the Character panel's 0, 25, 50, 75 and 100 in its menu; a value typed below 0 or -past 100 sets 0 or 100; an explicit 0 stays distinct from unset) and `language` (a name or tag from Document +past 100 sets 0 or 100; an explicit 0 stays distinct from unset), Adjust Horizontal and Vertical Diacritic Position +`diacriticHorizontal` and `diacriticVertical` (thousandths of an em, with the Character panel's -200, -100, -50, 0, 50, +100 and 200 in their menus; a value typed below -1000 or past 1000 sets -1000 or 1000) and `language` (a name or tag from Document Setup's languages; English: USA stores the explicit default `null`, and a tag not in the list that the style already has is kept). Language sets the language the characters are shaped in; it does not change hyphenation or spelling. @@ -10344,7 +10550,7 @@ The `paraStyleOptions` dialog exposes `name`, `section` (`general`, `basic`, `ta 100000 pt); it is disabled at 256 stops or when a stop is already at that position. Delete Tab removes the selected stop, and Clear All Tabs leaves the style with no stops, which it then sets. OK sorts the stops by position; of two stops at one position it keeps the one edited last. -- Composition: `composer` (`singleLine` or `everyLine`) and the `roman_hanging` checkbox. +- Composition: `composer` (`singleLine`, `everyLine`, `standardSingleLine` or `standardEveryLine`) and the `roman_hanging` checkbox. - Hyphenation: the `hyphenate` checkbox, `words_longer_than`, `after_first`, `before_last`, `hyphen_limit`, `hyphenation_zone` and the `hyphenate_capitalized` checkbox. The options are inactive while Hyphenation is off, and Hyphenation Zone is inactive with the Every-line Composer. @@ -11327,9 +11533,17 @@ of the group in the Layers panel (`layer.move`). ## Paragraph composer -`text.setFormat {ids?, composer: "singleLine"|"everyLine"}` sets how a text object's lines are broken (the Paragraph -panel menu's Single-line and Every-line Composer; stored in the paragraph attributes as `para.composer`, saved only -when it is Single-line). Every-line, the default, picks the breaks of the whole paragraph together in area type: +`text.setFormat {ids?, composer: "singleLine"|"everyLine"|"standardSingleLine"|"standardEveryLine"}` sets how a text +object's lines are broken and whether complex scripts are shaped (the Paragraph panel menu's four composers: Middle +Eastern & South Asian Single-line and Every-line, and Standard Single-line and Every-line; stored in the paragraph +attributes as `para.composer`, saved only when it is not Every-line, which is the default and what all type used before the +Standard composers existed). `singleLine` and `everyLine` shape Indic, Arabic and Hebrew type with the font's layout +tables, as all type is set; `standardSingleLine` and `standardEveryLine` break lines the same way but set such type +glyph by glyph as the font maps its characters (no conjuncts, reordering, mark placement or joining forms), for legacy +fonts that keep a script on Latin character codes. The scripts a Standard composer leaves unshaped are Indic, Arabic and the +other joining scripts (Syriac, N'Ko, Mongolian, Adlam…) and Hebrew; Latin, Greek, Cyrillic, CJK, Thai and the rest keep their +kerning and ligatures under every composer. Letters left unshaped do not join, so Insert Kashidas adds no tatweel between them. An older VectorCraft cannot open a file that uses a Standard composer. `.ai`, EPS and PDF files carry no composer. +Every-line, the default, picks the breaks of the whole paragraph together in area type: justified text gets even word spacing, ragged text (left, centre or right aligned) an even rag, so it may move a word that fits to the next line to avoid a lone short word on the last line or a full line next to a short one. Single-line fills each line as far as it goes. Point type and type on a path have no line width, so both composers @@ -11349,8 +11563,10 @@ new height and broken again in the room there. When that leaves the taller chara 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. +shift: true}}` or `invoke_menu`) sets the Single-line form when every paragraph of the selected type (or every paragraph the +Type tool's selection touches) uses an Every-line one, else the Every-line form. Paragraphs that all use a Standard composer +keep it (`standardSingleLine` or `standardEveryLine`); any other mix takes the Middle Eastern & South Asian one (`singleLine` +or `everyLine`). It returns the composer it set. ```json {"name":"run_command","arguments":{"command":"text.setFormat","params":{"ids":[7],"composer":"singleLine"}}} @@ -11459,7 +11675,11 @@ that starts with `/version`) without changing anything. Give exactly one of `pat the set's name (`set`, else the file's name, else empty), its `version`, and its `actions`, each with its `name` and `steps`. A step lists its `name` (the file's `/internalName`), its `label` (the `/localizedName` it is shown with, or null when it has none or it is blank), `on` (false when the file sets `/isOn 0`), `params` (how many recorded values it -has) and its `line`. `unread` lists the tokens the reader skipped, with their lines. The reader stops at 8 MiB, 16 open +has), `values` and its `line`. `values` lists the step's recorded values in order, each as `{key, type, value, bytes?}`: +the block's `/key` and `/type` (null when it has none), and its `/value` when that is a whole number, or text in +parentheses or hexadecimal text that is UTF-8, with `bytes` giving the text's length in bytes; any other value, and text +that is not UTF-8, is null. Only the first 100,000 recorded values in the set are listed, so a step's `values` can be +shorter than its `params`. `unread` lists the tokens the reader skipped, with their lines. The reader stops at 8 MiB, 16 open blocks, 1,000 actions, 10,000 steps in an action and 100,000 steps in the set, and cuts names at 1,024 bytes. It sets `truncated` when it reaches one of these limits, when the text ends inside a block or a value or after a field's name, when `/actionCount`, `/eventCount` or a step's `/parameterCount` differs from the actions, steps or recorded values read @@ -11474,8 +11694,12 @@ label, in English or in the interface language, in any case and without a final that label and that command is directly in a top menu, can be recorded in actions, is what its menu bar item runs with no values and opens no dialog (Group, Ungroup). A submenu's items, file and document commands, Paste, Undo, Redo and add-on commands are never matched. The step runs with no params, and a step that is off in the file is excluded from -playback. Other steps are left out, including every step with no label and every step recorded with values (recorded -menu items too). The reply lists the first 1,000 in `skipped` (`{action, step}`, the step by its label, else its name), +playback. A Set Selection step, found by its `/internalName` whatever its label, comes in as a Select Object step +(`select.byNote` with `{note, caseSensitive, wholeWord}`) when it has exactly three recorded values: the note (key +`text`, 1952807028, of type `ustring`, UTF-8), Whole Word (key `word`, 2003792484) and Case Sensitive (key `case`, +1667330917), each of type `boolean` and 0 or 1. The note loses its leading and trailing spaces and must then be 1 to +1,024 bytes long. A Set Selection step with any other values is left out; no option is filled in. Other steps are left +out, including every other step with no label and every other step recorded with values (recorded menu items too). The reply lists the first 1,000 in `skipped` (`{action, step}`, the step by its label, else its name), `leftOut` counts them, and the status bar says how many were left out. An action with no name is called `Action N`, by its place in the file. Function keys and colors are not read. A file marked `truncated` is refused, and no set is added. Text that starts `/version` and is not an action set gives "not an action set file". Tokens in `unread` do not stop a @@ -12157,8 +12381,10 @@ overlapping the artboard or the centre on it), `inside` (the bounds wholly withi straddling two touching artboards is inside neither) or `outside` (on none of them). It looks at the objects Select All takes, or the isolated container's in isolation mode, so hidden and locked objects, objects on hidden, locked or template layers and art held by a locked artboard are left out. Bounds are geometric, a symbol instance's measured by its art. It -returns the `count` selected. An empty list, an index with no artboard, a value that isn't an index, or another -relation is an error, and the selection is left as it was. +returns the `count` selected. An empty list, an index with no artboard (`no such artboard`), a value that isn't a list +("`artboards` must be a list of artboard indices"), an entry that isn't a whole number of 0 or more ("`artboards` must +contain whole numbers", checked before any entry is looked up), or another relation is an error, and the selection is +left as it was. ```json {"name":"run_command","arguments":{"command":"addon.select.byArtboards","params":{"artboards":[2,6,11],"relation":"inside"}}} @@ -12390,6 +12616,58 @@ there is no step. → `{symbols: [name…], ids: [instance id…], skipped: [{la {"name":"run_command","arguments":{"command":"addon.document.symbolsFromLayers","params":{"replace":true}}} ``` +## Packaging Tools add-on + +Packaging Tools is a built-in add-on for the dielines of boxes and other folded packaging. Its commands are +`addon.packaging.setRole`, `addon.packaging.roles` and `addon.packaging.setRoleSwatch`. In the desktop app, Object › +Plug-ins › Packaging Tools › Fold Lines opens the Fold Lines panel, and Make Cut Line, Make Crease Line, Make Partial Cut +Line and Make Perforation Line run `addon.packaging.setRole` on the selection. + +### Fold line roles + +A fold line has one of four roles: Cut (`cut`), Crease (`crease`), Partial Cut (`partialCut`) and Perforation +(`perforation`). A path, compound path or live shape has a role when its top stroke is painted with the role's swatch, at +any tint. Each document has a role table that names the swatch of each role, stored in the document under +`packagingRoles` as `{"cut": "Cut", "crease": "Crease", "partialCut": "Partial Cut", "perforation": "Perforation"}`. A +role the table leaves out, or names with something other than a string, uses the swatch named after the role. When +`swatch.edit` renames a role's swatch, the table names the swatch by its new name and the role stays with it; another +role whose swatch did not exist yet and had that name moves to a new name ("Crease 2"). When `swatch.edit` turns Global +off for a role's swatch, which unlinks its strokes, the role moves to a new name, and the next `addon.packaging.setRole` +makes that swatch. When `swatch.merge` merges a role's swatch into a global swatch that carries no role, the kept swatch +takes the role. Native files keep the table and the strokes. PDF prints a role line on the separation of its swatch when +the swatch is a spot color, as the default role swatches are; a role carried by a global process color is written as an +ordinary color with no separation of its own. SVG, DXF and HP-GL keep the stroke's color, so the default role swatches +come out as four colors, and as four pens in HP-GL without a pen table. + +`addon.packaging.setRole` (`{role: cut|crease|partialCut|perforation|none, ids?, overprint?: true}`) gives the role to +each path, compound path and live shape among the objects (the selection by default), through groups and clip groups. +Objects that are locked or hidden, in a locked or hidden group or layer, or on a locked artboard are left out and +counted as skipped, also when `ids` names them. The top stroke is painted with the role's swatch at 100% and shown if +it was hidden, a path without a stroke gets a 1 pt stroke, and the stroke overprints unless `overprint` is false. When +the document lacks the role's swatch, the command makes it as a global spot swatch in the document's color mode: Cut 100% +magenta, Crease 100% cyan, Partial Cut 100% yellow and Perforation 50% magenta and 50% cyan (VectorCraft's own defaults). +When a color group, or a swatch that can't carry a role such as a process color that is not global, has the swatch's +name, the swatch is named "Cut 2" (and so on) and the role table names it. `none` takes the role away: the stroke keeps +the color it shows, no longer linked to the swatch, and stops overprinting. Text, images, symbol instances and other +objects are skipped and counted. The command fails with an unknown role and when the objects hold no path it can change. One undo +step, none when nothing changes. Result: `{ids, changed, skipped}`. + +`addon.packaging.roles` (`{ids?}`) returns `{roles: [{role, name, swatch, exists, count}], scope, selected}`: each role's +swatch, whether the document has it, and how many of the objects have the role. It counts the selection, or every object +of the document while nothing is selected and `ids` is left out (`scope` says which). Locked and hidden objects are +counted in every scope, and an object is counted once when both it and its group are given. The Fold Lines panel shows +these counts; clicking a role gives the selected paths that role. With nothing selected the panel says so. + +`addon.packaging.setRoleSwatch` (`{role, swatch}`) makes another global or spot color swatch carry the role. Objects +stroked with the old swatch keep their color and no longer have the role. It fails with a missing swatch, a gradient or +pattern swatch, a process color that is not global, a tint swatch, `[None]`, `[Registration]` and a swatch another role +has. One undo step, none when the role already has that swatch. Result: `{role, swatch, changed}`. The Fold Lines +panel's menu opens it as Role Swatches…. + +```json +{"name":"run_command","arguments":{"command":"addon.packaging.setRole","params":{"role":"crease"}}} +``` + ## Image Tools add-on Image Tools is a built-in add-on for placed images: its commands are `addon.image.removeBackground`, diff --git a/docs/roadmap.md b/docs/roadmap.md index 742fef93ed..da1645efb2 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 (PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; 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 (M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; 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). > @@ -59,6 +59,7 @@ M7 type: Touch Type moves a right-to-left character along its line and up from i | 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. | +| 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 on the merged branch (all 13 gates), including the test-helper correction for the upstream compile error tracked in #7727; native Windows full CI has two unchanged engine-test failures. 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; `the_list_fills_a_tall_panel_above_its_footer` in `crates/ui-egui/src/panels/swatches/tests.rs`). Scores and estimates unchanged. | | 2026-11-13 | minor | M4: PDF import (#5235, #6906): Indic type keeps its marks on their line, and a line whose type would not draw as the file does keeps the file's glyphs as outlines (opaque, alike-stroked ones share a path except under a soft mask, where each glyph keeps its own path and mask; translucent ones keep their own). Scores and estimates unchanged. Evidence: `crates/pdf/src/tests/reshaped.rs`. | | 2026-11-10 | minor | M13 / G6: MCP catalogue (#6460): headless lists UI commands, eight prompts, 33 tools, effect vs command ids; scores and estimates unchanged. | @@ -162,14 +163,14 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; estimates unchanged); 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 | +| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, the custom dictionary and Ignore All commands, Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, Spelling › Auto Spell Check in the context menu of type, the Edit Custom Dictionary dialog, and the modal Check Spelling dialog (Edit › Spelling › Check Spelling…, `Cmd+I`, `ui.checkSpelling`, #4936); 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, vertical type pending | 45–60 | | M8 | Transform & distort (Puppet Warp, Liquify tools, Envelopes, Blends, Perspective Grid) | ✅ done (M8.1–M8.20 on 2026-10-06, fidelity pass): Liquify Tool Options with one shared brush, pen pressure, hold-to-apply, a safe scope and incremental strokes; tool options that last; Puppet Warp rotation, multi-select, Control bar and a rest-shape session that follows Undo; Width tool on compound paths; Envelope dialogs with preview, Reset with Warp/Mesh, full Envelope Options, type/images/symbols/appearance/gradients/patterns distorted on canvas and in every export, warps that keep their frame, Edit Contents, mesh handles and Control bar; Blend Options, anchor-targeted Blend tool, editable spine, keys picked on the canvas, faithful interpolation and knockout; Anchor Point spine conversion/handle editing and selection priority (#2544), with #2425 Shift reshape preserved; Perspective Grid with Define Grid, presets, lock/snap/rulers, widgets, the 1–4 plane switch, movable planes, Perspective Selection scale/copy/perpendicular/Transform Again, and type and symbols truly projected with Edit Text. Left: Anti-Alias and Preserve Shape output, warp-envelope point editing, brush interpolation in blends, Free Transform/Scale/Reflect along a rotated box | 2–4 | | M9 | Live effects (+ 3D & Materials) | 🟡 2D effects done incl. Effect → Pathfinder, Color Adjustments and Document Raster Effects Settings; PDF export warns when the pixel cap lowers raster-effect resolution; Artistic › Colored Pencil, Cutout, Dry Brush, Film Grain, Fresco, Neon Glow, Paint Daubs, Palette Knife, Poster Edges, Rough Pastels, Smudge Stick, Sponge, Underpainting and Watercolor and Sketch › Halftone Pattern, Bas Relief, Charcoal, Conté Crayon, Photocopy, Stamp, Torn Edges and Water Paper done (57/57 Photoshop filters); Revolve with automatic smooth vector shading, default-on circular caps and continuous rims, Extrude & Bevel, Inflate and Rotate with one to ten colored directional lights and four original lighting presets; SVG Filters, remaining raster effects and 3D materials and shadows pending | 81–130 | | M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, ten generated libraries including Tech Circuit, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; 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 | 15–25 | | M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color, Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) | 6–10 | | M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; the script document model and batch work remain | 18–27 | -| M14 | 1.0 polish (preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset , UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307) | 18–28 | +| M14 | 1.0 polish (preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset , UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12) | 18–28 | | — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 | | — | Hardening at scale (big-file corpus, fuzzing, cross-platform + browser QA) | 🟡 PngSuite integrity and bounded fetching verified (#1729); real-world corpus/manual QA remain | 50–80 | | M14 follow-up | Color Picker layout (#2008) | ✅ Compact controls, centered header, stacked actions, aligned fields and screen sampling; narrow windows scroll vertically | Included above | @@ -211,6 +212,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | 2026-11-15 | minor | M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimates unchanged | | 2026-11-14 | minor | Tech Circuit adds three original procedural brushes (Circuit Trace, Bus Lines, Terminal Nodes); ten built-in brush libraries. G5 remaining estimate 3–13 h (estimated); parity scores and headline totals 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-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 on the merged branch (all 13 gates), including the test-helper correction for the upstream compile error tracked in #7727; native Windows full CI has two unchanged engine-test failures. 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 | | 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. | | 2026-11-12 | minor | M7: Glyphs panel applies feature-valued alternates and unencoded glyphs while keeping Arabic joining (#5514). Scores and estimates unchanged. | @@ -350,6 +352,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | 2026-10-13 | minor | G1: create width points through Width Point Edit with optional adjoining adjustment; command/pointer/history regressions and full CI passed; dialog layout reviewed; scores and hours unchanged | | 2026-10-13 | minor | Corner Radius: a link toggle behind the field in the Properties and Transform panels; off, a live rectangle shows a radius field for each corner (Top Left, Top Right, Bottom Right, Bottom Left), each setting its own corner (`singleCornerRadius` preference); split from #1594; score unchanged (estimated) | | 2026-10-13 | minor | Control transport deadlines (#1726): idle and partial clients and blocked replies release connection slots; parity scores and estimates unchanged. | +| 2026-11-15 | minor | M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…, `ui.checkSpelling`, #4936); spell check complete; scores and estimates unchanged. | | 2026-10-13 | minor | M12 row: Image Trace has 15 presets and the Ignore Color, Shapes, Auto Grouping and Gradients options (#1574, #1609, #1618, #1627); its speed figure, measured before these, is dropped for the measurements in `image-trace-quality.md` | | 2026-10-13 | minor | The interface is available in Polish (`pl`): menus, panels, dialogs and messages, with one/few/many plurals; AI-drafted, native review pending (#1498); Native documents with a lot of path data (traced or generated art, in layers, symbols or patterns) are saved as compact JSON, about a fifth of the size; small documents stay pretty-printed (#1492); 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); 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); 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); Make Compound Path on a group (such as outlined type) keeps the paint of its backmost path instead of drawing nothing, and compound paths joined into one keep their holes (#1537); a round corner next to a curved side curves smoothly instead of sticking out of the shape and the Smooth tool smooths only the stretch of path under the drag (#1547, fixes #1512); Join merges the selected anchor points that lie on one another, as after Average, into one anchor (#1582, fixes #1533); 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); Edit › Keyboard Shortcuts lists Edit › Duplicate and the other commands that are in no menu but run without parameters (panel-menu commands such as Break Link to Symbol), so they can be given shortcuts (#1549, #1580, fixes #1539); Raster effects (blur, shadow, glow, grain) drawn after a pattern, radial or freeform gradient fill export at their place and size (#1541, fixes #1536); the font scan on Linux also reads the folders fontconfig's configuration lists, such as TeX fonts under `/usr/share/texmf/fonts` (#1548, fixes #1529; not verified on Linux); estimates unchanged | | 2026-10-13 | minor | Direct Selection takes the selected object's anchor where anchors of overlapping objects coincide (#1508); commands and MCP `add_text` report area type that does not fit its frame (#1471), a tab stop in the Tabs panel drags from where the press landed (#1458); M9: 3D and Materials on outlined type and other shapes of many small curves (#1481), Twist 0° to 360° (#1524), twisted walls keep their faces (#1525); print-size images draw, export and crop (#1517), `vectorcraft-cli perf` reports load and memory on Windows (#1502); sliders in dialogs show their rail (#1483), a template layer stays in Preview in Outline view (#1486), French catalog complete again (#1511), a Hungarian message in the informal address (#1474); `graph.setData`'s CSV keeps each value exactly (#1485); estimates unchanged | @@ -409,3 +412,5 @@ separate. Scores and hours unchanged. [Behavior and command details](development 2026-10-28 behavior correction: Flare ray rotation follows vertical travel at one degree per document point, independent of pointer event count. Shift freezes the current orientation; Space also freezes rotation on the first update. This is the chosen application interaction rate. Scores and estimates unchanged. ## EPS Save evidence (2026-10-26) Ordinary Save and Save As keep EPS as EPS, with the chosen page frame, transparent margins and the complete editable VectorCraft document. Existing import-loss confirmation and transparency warnings remain; the Save TIFF preview is capped at 1024 pixels, while Export retains 2048. See [file-format-parity.md](file-format-parity.md#eps-save-and-source-protection) for limits and regression evidence. This narrows G9 save-back workflow coverage; native Illustrator editing-data fidelity, parity scores and hour estimates are unchanged. Since 2026-11-12 the EPS Options of Save As show Use Artboards, unchecked by default: unchecked, the bounding box fits the visible art; checked, Save keeps the chosen page frame and margins described here. + +> **Swatches status (2026-11-15):** Item context menus are implemented and covered by headless tests; full CI passed on the latest-main integration (all 13 gates), including the updated panel-view harness; parity scores and estimates are unchanged. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b52bcc7b5c..a61d0b5001 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 (PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; 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) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-15 · **Change:** minor (Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; 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) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -65,6 +65,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | 2026-11-15 | minor | G5: Neon & Glow joins Shadows and Glows, Outlines and Rules, Hand-Drawn, Textures, Painted and Sketched, Gradient Finishes, Shape Effects, Blends and Transparency, Game HUD and Status Effects as an eleventh built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor; original procedural styles generated in code); area score and estimate 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 | G5: Tech Circuit adds three original procedural brushes (Circuit Trace, Bus Lines, Terminal Nodes); ten built-in brush libraries. G5 remaining estimate 3–13 h (estimated); parity scores and headline totals 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 on the merged branch (all 13 gates), including the test-helper correction for the upstream compile error tracked in #7727; native Windows full CI has two unchanged engine-test failures. Scores and estimates 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. | @@ -247,16 +248,16 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (ten generated libraries including Tech Circuit, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media, User Defined, Other Library…, Save Brushes); Art brush Overlap and Pattern brush auto corners are done; remaining: pen pressure on macOS, Stylus Wheel, more built-in brush libraries, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | | Appearance, transparency, graphic styles, masks | 5 | 97% | raster effect reach in preview bounds | 1–2 | estimated; Transform typing, sliders, preview, and undo are covered in `crates/ui-egui/src/panels/tests_appearance.rs` | | 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, painter visibility); materials, light presets, shadows, ray tracing, the rest of 3D Classic (Map Art), Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); every 3D seam has round joins (2026-11-12, [three-d.md](three-d.md#seams)), score, gaps and hours unchanged | -| Type core | 9 | 80% | Auto-leading style resets are implemented; Hyphenation… and Justification… options are done (#2310, #2755), and a paragraph's Auto Leading also sets the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; remaining: Optical Margin Alignment, Middle Eastern features beyond bidi layout, optional group font-size preservation; transformed character controls fixed (#1034), see [type-parity.md](type-parity.md) | 14–19 | estimated; eleven-language pattern hyphenation in both composers, with grapheme and shaping-cluster protection (#4947, `hyphen::tests` and `layout::wrapping_tests`); Sanskrit patterns pending an allowlisted source; recent-font groups in font pickers (#3515); full-name font matches regression-tested (#1258); mixed paragraph alignment indication implemented; headless regressions, full integration CI and visual review pass; localized legacy family-name fallback with loaded/catalog regressions (#2208); Fractional Widths per type object regression-tested; color emoji fonts with bitmap glyphs (`sbix`, `CBDT`) draw and export; threading ports: every selected area type and type on a path shows its in and out ports (empty, arrow, red "+"), and the Selection tool threads from either, the in port into a frame before it, and a double-click on a threaded port breaks the thread there (`threads::tests::break_splits_the_thread_and_the_story_flows_into_the_first_part`, `select::tests::a_double_click_on_a_threaded_port_breaks_the_thread`, `canvas::tests::a_double_click_on_a_threaded_out_port_breaks_the_thread`) (#2572; `select::tests::a_click_on_the_in_port_threads_into_a_frame_before_it`, `text::tests::selected_type_shows_its_ports_in_each_state`, `threads::tests::add_before_threads_the_story_from_the_new_frame_into_the_clicked_one`, live screenshot); the Glyphs panel highlights and scrolls to the character selected with the Type tool (#4908, `panels::glyphs` tests); the OpenType panel lists only `ss01`–`ss20` sets present in the selected font and uses its custom names when supplied; Type-range desktop Copy publishes styled art and keeps font family, size and color on canvas Paste after editing (#5636); paint-only Arabic harakat keep joining with conditional GDEF-mark ownership and Insert Kashidas base-letter paint (`tests::harakat`) | -| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), variable font axes, tab leaders, spell check (engine, custom dictionary and Auto Spell Check with its right-click suggestions and Spelling › Auto Spell Check, and the Edit Custom Dictionary dialog done, #4936; the Check Spelling dialog remains), Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | +| Type core | 9 | 80% | Auto-leading style resets are implemented; Hyphenation… and Justification… options are done (#2310, #2755), and a paragraph's Auto Leading also sets the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; remaining: Optical Margin Alignment, Middle Eastern features beyond bidi layout (the Middle Eastern & South Asian and Standard composers are done per paragraph, #4935; `.ai`/EPS/PDF files carry no composer), optional group font-size preservation; transformed character controls fixed (#1034), see [type-parity.md](type-parity.md) | 14–19 | estimated; eleven-language pattern hyphenation in both composers, with grapheme and shaping-cluster protection (#4947, `hyphen::tests` and `layout::wrapping_tests`); Sanskrit patterns pending an allowlisted source; recent-font groups in font pickers (#3515); full-name font matches regression-tested (#1258); mixed paragraph alignment indication implemented; headless regressions, full integration CI and visual review pass; localized legacy family-name fallback with loaded/catalog regressions (#2208); Fractional Widths per type object regression-tested; color emoji fonts with bitmap glyphs (`sbix`, `CBDT`) draw and export; threading ports: every selected area type and type on a path shows its in and out ports (empty, arrow, red "+"), and the Selection tool threads from either, the in port into a frame before it, and a double-click on a threaded port breaks the thread there (`threads::tests::break_splits_the_thread_and_the_story_flows_into_the_first_part`, `select::tests::a_double_click_on_a_threaded_port_breaks_the_thread`, `canvas::tests::a_double_click_on_a_threaded_out_port_breaks_the_thread`) (#2572; `select::tests::a_click_on_the_in_port_threads_into_a_frame_before_it`, `text::tests::selected_type_shows_its_ports_in_each_state`, `threads::tests::add_before_threads_the_story_from_the_new_frame_into_the_clicked_one`, live screenshot); the Glyphs panel highlights and scrolls to the character selected with the Type tool (#4908, `panels::glyphs` tests); the OpenType panel lists only `ss01`–`ss20` sets present in the selected font and uses its custom names when supplied; Type-range desktop Copy publishes styled art and keeps font family, size and color on canvas Paste after editing (#5636); paint-only Arabic harakat keep joining with conditional GDEF-mark ownership and Insert Kashidas base-letter paint (`tests::harakat`) | +| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), variable font axes, tab leaders, Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | | Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons and Weather Icons are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested | -| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), tab leaders, spell check (engine, custom dictionary and Auto Spell Check with its right-click suggestions and Spelling › Auto Spell Check, and the Edit Custom Dictionary dialog done, #4936; the Check Spelling dialog remains), Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | +| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), tab leaders, Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | | Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons and Weather Icons are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested | | Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; simpler contour walk, identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments, so Paths is monotone on the code-drawn sweep) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them; Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views (scores/hours unchanged) | | Live vector effects | 5 | 85% | Outline Object, SVG Filters | 4–8 | measured count 49/50 (Pathfinder 13/13 with Trap), depth estimated; Warp Options controls verified by focused checks and original-image review | | 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, original lighting presets, painter visibility), Revolve (Classic) with Angle, Cap, Offset and the Plastic, Diffuse, No Shading and Wireframe surfaces, the Quick Actions › Expand as Wireframes command (#6354), the Render Settings › Wireframe mode on Extrude & Bevel, Revolve, Inflate and Rotate; materials, shadows, ray tracing, the rest of 3D Classic (Map Art), Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); Revolve (Classic) is covered by the `revolve::classic` tests and `dialogs::revolve::tests::classic_revolve_shows_its_options_and_applies_as_one_step`; Expand as Wireframes is covered by `crates/effects/src/solids/wireframe/tests.rs` and `crates/engine/src/cmd/wireframe/tests.rs`, and Render Settings › Wireframe by `crates/effects/src/solids/wireframe/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` (score, gaps and hours unchanged); every 3D seam has round joins (2026-11-12, [three-d.md](three-d.md#seams)), score, gaps and hours unchanged | -| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (mojikumi), variable font axes, tab leaders, spell check (engine, custom dictionary and Auto Spell Check with its right-click suggestions and Spelling › Auto Spell Check, and the Edit Custom Dictionary dialog done, #4936; the Check Spelling dialog remains), Touch Type, Retype | 20–28 | estimated; No Break keeps marked characters on one line; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | -| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (mojikumi), tab leaders, spell check (engine, custom dictionary and Auto Spell Check with its right-click suggestions and Spelling › Auto Spell Check, and the Edit Custom Dictionary dialog done, #4936; the Check Spelling dialog remains), Touch Type, Retype | 20–28 | estimated; No Break keeps marked characters on one line; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | +| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (mojikumi), variable font axes, tab leaders, Touch Type, Retype | 20–28 | estimated; No Break keeps marked characters on one line; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | +| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (mojikumi), tab leaders, Touch Type, Retype | 20–28 | estimated; No Break keeps marked characters on one line; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | | Raster effects (Effect Gallery) | 4 | 55% | — | — | estimated (raised from 52%: the Effect Gallery's filter thumbnails and in-dialog preview, an original landscape drawing passed through each filter, [Filter Gallery overview](https://helpx.adobe.com/photoshop/desktop/effects-filters/get-started-with-filters/filter-gallery.html), `dialogs::effect_gallery::tests::gallery_shows_thumbnails_and_an_in_dialog_preview`; the gallery itself shipped in #2883, six categories, per-filter settings, ordered stack, live canvas preview, one undo step, `stack_ok_is_one_undo_step`, `stack_preview_is_one_interaction`); measured count 57/57 (Artistic complete with Colored Pencil, Fresco, Paint Daubs, Palette Knife, Rough Pastels and Underpainting; Sketch complete with Torn Edges and Conté Crayon, `pixel::tests_sketch::conte_crayon_*`); texture redraw distances optimized (#1257), pixels verified; the score stays under 100% because the filters are original approximations; depth estimated | | Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons and Weather Icons are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) and on-canvas 9-slice guides (#5280) are done | 4–7 | estimated | | Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; large images trace with a warning; Auto Color keeps rare distinct colours) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them | @@ -271,7 +272,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Export for Screens, Asset Export, slices, Save for Web | 3 | 85% | anti-aliasing ghost borders (#983); TIFF choices and settings are implemented | 2–4 | estimated | | Print, colour management, separations, flattener | 3 | 80% | print preview fidelity | 2–4 | estimated | | Automation (Actions, Variables, scripting, batch) | 3 | 60% | a scripting surface (Illustrator: JavaScript/ExtendScript), Batch, image and graph variables, dataset import/export | 8–14 | estimated; MCP `add_text` exposes existing vertical type; score and hours unchanged | -| UI chrome (panels, Properties, workspaces, preferences) | 6 | 80% | Properties per context, 2 Preferences options stored but unused (#394, audited 2026-10-30: Scratch Disks, legacy vector clipboard), context menus in the panels that have none, accessibility | 13–20 | estimated; floating panels in OS windows of their own on the desktop (#4135), score and hours unchanged; macOS save Format menu implemented (#866), score and hours unchanged; Eyedropper cursor and precise setting checked (#1269), OS visual QA unverified; numeric-field focus and normal text drags regression-tested (#1326); a focus click released more than 1 pt from its press keeps the caret and a tap within 1 pt selects all (#6659); artboard navigation synchronizes the tool selection before destructive actions; status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates (sample widths cached by language/unit/DPI; regression and contributor original-file evidence below; scores/hours unchanged); effect dialogs' colour fields show a swatch that opens the Color Picker (#5365), score and hours unchanged; icon-strip flyouts retain user sizes (#5713); floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), scores and hours unchanged ; interim macOS cursor delivery (#2292), headless coverage only; native validation pending, score and hours unchanged | +| UI chrome (panels, Properties, workspaces, preferences) | 6 | 80% | Properties per context, 2 Preferences options stored but unused (#394, audited 2026-10-30: Scratch Disks, legacy vector clipboard), context menus in the panels that have none, accessibility | 13–20 | estimated; floating panels in OS windows of their own on the desktop (#4135), score and hours unchanged; macOS save Format menu implemented (#866), score and hours unchanged; Eyedropper cursor and precise setting checked (#1269), OS visual QA unverified; numeric-field focus and normal text drags regression-tested (#1326); a focus click released more than 1 pt from its press keeps the caret and a tap within 1 pt selects all (#6659); artboard navigation synchronizes the tool selection before destructive actions; status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates (sample widths cached by language/unit/DPI; regression and contributor original-file evidence below; scores/hours unchanged); effect dialogs' colour fields show a swatch that opens the Color Picker (#5365), score and hours unchanged; icon-strip flyouts retain user sizes (#5713); floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), scores and hours unchanged ; interim macOS cursor delivery (#2292), headless coverage only; native validation pending, score and hours unchanged; Swatches item context menus have focused regressions and rendered-layout evidence below; scores and estimates unchanged | | Libraries, Links, Package | 2 | 82% | shared libraries, linked graphics, gradients and patterns as library items (no cloud by design) | 2–3 | estimated | | Generative AI (Text to Vector, Generative Recolor, Shape Fill, Concept to Vector, Prompt to Edit, Rewrite Text) | 2 | 0% | a pluggable provider and the panels; needs an owner decision on models | 30–60 | measured (absent) | | **Feature depth** | **105** | **~75%** | | **~250–420** | | @@ -517,11 +518,11 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) | Appearance, transparency, graphic styles, masks | 5 | 98% | Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); raster effect reach in preview bounds (flattener presets apply in PDF, EPS and print) | 1–2 | | Live vector effects | 5 | 85% | Outline Object, Pathfinder Hard/Soft Mix and Trap (since done: #3061, #3063, #3785), SVG Filters, Transform Patterns and Scale Strokes & Effects on a fill's or stroke's own Transform effect | 6–10 | | 3D and Materials | 4 | ~25% | Initial Revolve, Extrude & Bevel, Inflate and Rotate, with simple lighting; materials, light presets, shadows, ray tracing, Rotate (Classic), Map Art and more complete visibility remain | 25–45 | -| Type advanced | 4 | 50% | CJK composition for vertical type (ruby, mojikumi beyond Line-end Punctuation Half Width — the other sets (and their paragraph-start bracket and indent rules), custom kinsoku sets (beyond Hard, Soft and None) and the Mojikumi Settings dialog —, manual tate-chu-yoko), tab leaders, spell check (its engine, custom dictionary commands, the Edit Custom Dictionary dialog and Auto Spell Check are done, #4936: the Check Spelling dialog remains; a right-click on an underlined word offers its suggestions, Ignore All and Add to Dictionary, and a right-click on type has Spelling › Auto Spell Check), Touch Type, Retype; vertical point/area/path type and Type Orientation have initial support (beyond parity, not scored: inline symbols in text) | 20–28 | +| Type advanced | 4 | 50% | CJK composition for vertical type (ruby, mojikumi beyond Line-end Punctuation Half Width — the other sets (and their paragraph-start bracket and indent rules), custom kinsoku sets (beyond Hard, Soft and None) and the Mojikumi Settings dialog —, manual tate-chu-yoko), tab leaders, Touch Type, Retype; vertical point/area/path type and Type Orientation have initial support (beyond parity, not scored: inline symbols in text) | 20–28 | | Raster effects (Effect Gallery, Document Raster Effects Settings) | 4 | 35% | ~36 Photoshop-style filters (Artistic, Brush Strokes, Sketch, Stylize) and Texturizer's Load Texture (since done, see the area table above, as is the Effect Gallery, #2883); Document Raster Effects Settings, raster effects in PDF, the pixel-filter pipeline, Radial Blur, Smart Blur (Normal, Edge Only and Overlay Edge), Unsharp Mask, Glowing Edges, Distort (Diffuse Glow, Glass, Ocean Ripple), Pixelate (Color Halftone, Crystallize, Mezzotint, Pointillize), Texture (Craquelure, Grain, Mosaic Tiles, Patchwork, Stained Glass, Texturizer) and Video (De-Interlace, NTSC Colors) are done | 8–14 | | 3D and Materials | 4 | ~25% | Initial Revolve, Extrude & Bevel, Inflate and Rotate, with simple lighting and four original lighting presets; materials, shadows, ray tracing, Rotate (Classic), Map Art and more complete visibility remain | 25–45 | -| Type advanced | 4 | 50% | CJK composition for vertical type (mojikumi beyond Line-end Punctuation Half Width — the other sets (and their paragraph-start bracket and indent rules), custom kinsoku sets (beyond Hard, Soft and None) and the Mojikumi Settings dialog —, manual tate-chu-yoko is done, its up/down settings remain; No Break is done), tab leaders, spell check (its engine, custom dictionary commands, the Edit Custom Dictionary dialog and Auto Spell Check are done, #4936: the Check Spelling dialog remains; a right-click on an underlined word offers its suggestions, Ignore All and Add to Dictionary, and a right-click on type has Spelling › Auto Spell Check), Touch Type, Retype; vertical point/area/path type and Type Orientation have initial support (beyond parity, not scored: inline symbols in text) | 20–28 | -| Type core | 9 | 80% | Middle Eastern features beyond bidi layout, Paragraph Direction, digit types and Kashidas (the Middle Eastern composers, editable bidirectional SVG text, a split caret where directions meet); paint-only harakat keep joining with conditional GDEF-mark colour ownership, but fonts without GDEF mark classes and some AAT/`morx` ligatures can still leave marks painted as their letters; Every-line Composer fidelity for justified and ragged text (available per object; mixed type sizes in a paragraph still break single-line in non-rectangular area type and with text wrap), Optical Margin Alignment, paragraph spacing limit for vertically justified area type, hidden characters, paragraph attributes in the Type tool's copy and paste (the characters keep their styles, the paragraphs take the destination's), mixed-value display in the Paragraph panel for a selection across differing paragraphs, partial selection of type-area anchors by marquee, optional font-size preservation during group scaling (scaled character controls fixed in #1034). Hyphenation and Justification options, Fractional Widths, System Layout, styled Type-range canvas Paste (#5636), and pattern hyphenation for eleven Indian languages with grapheme/cluster protection (#4947) are done; Sanskrit automatic patterns remain pending an allowlisted source | 14–19 | +| Type advanced | 4 | 50% | CJK composition for vertical type (mojikumi beyond Line-end Punctuation Half Width — the other sets (and their paragraph-start bracket and indent rules), custom kinsoku sets (beyond Hard, Soft and None) and the Mojikumi Settings dialog —, manual tate-chu-yoko is done, its up/down settings remain; No Break is done), tab leaders, Touch Type, Retype; vertical point/area/path type and Type Orientation have initial support (beyond parity, not scored: inline symbols in text) | 20–28 | +| Type core | 9 | 80% | Middle Eastern features beyond bidi layout, Paragraph Direction, digit types and Kashidas (editable bidirectional SVG text, a split caret where directions meet; the Middle Eastern & South Asian composers are done, #4935, but `.ai`/EPS/PDF files carry no composer); paint-only harakat keep joining with conditional GDEF-mark colour ownership, but fonts without GDEF mark classes and some AAT/`morx` ligatures can still leave marks painted as their letters; Every-line Composer fidelity for justified and ragged text (available per object; mixed type sizes in a paragraph still break single-line in non-rectangular area type and with text wrap), Optical Margin Alignment, paragraph spacing limit for vertically justified area type, hidden characters, paragraph attributes in the Type tool's copy and paste (the characters keep their styles, the paragraphs take the destination's), mixed-value display in the Paragraph panel for a selection across differing paragraphs, partial selection of type-area anchors by marquee, optional font-size preservation during group scaling (scaled character controls fixed in #1034). Hyphenation and Justification options, Fractional Widths, System Layout, styled Type-range canvas Paste (#5636), and pattern hyphenation for eleven Indian languages with grapheme/cluster protection (#4947) are done; Sanskrit automatic patterns remain pending an allowlisted source | 14–19 | | Symbols, blends, envelopes, Repeat, perspective | 5 | 90% | further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons and Weather Icons are done), dynamic symbols' `.ai` round trip, envelope Anti-Alias/Preserve Shape output and warp point editing, brush interpolation in blends (M8 fidelity pass done); Symbol Options › Registration and Export Type and on-canvas dynamic part paint (gradient/pattern, opacity, blend) are done; symbol editing shows draggable 9-slice guides (#5280), while guides outside the artwork remain unsupported | 4–7 | | Image Trace, graphs, image tools | 3 | 72% | graph Column designs (Graph Design, Marker designs and series colours set with Group Selection are done), Create Object Mosaic, per-feature stroke/fill choice and varying widths in Image Trace's Create Strokes (Vector Halftone and the Image Trace View modes, Palette and Create Strokes are done) | 6–10 | | Layers, artboards, document setup | 5 | 82% | Layers panel: a confirmation before deleting layers that hold art, row menu commands beyond Collect for Export (now on every layer, sublayer, group and object row), menus on guide and blend spine rows, the Layer Options dialog for several rows with mixed values, Paste Remembers Layers for sublayers; artboard preset polish (artboard escape routing and document setup modal handoff done; Move Artwork for artboard X/Y edits, Rearrange All Artboards, Document Setup, New Document and the rest of the Layers panel are done) | 4–7 | @@ -592,9 +593,12 @@ since 2026-10-01. - 3D lighting widget: the Lighting tab of the 3D and Materials panel shows every light on a sphere at its Rotation and Height; a drag moves a light in one undo step, a press selects it, Move Light to Back and Move Light to Front change its side, and the arrow keys move the focused light ([three-d.md](three-d.md#lighting-widget)). `crates/ui-egui/src/panels/tests_three_d.rs` covers the drag, selection, side and keyboard. - 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. +- 3D shadows: a command that applies or edits Extrude & Bevel, Inflate or Rotate with Shadows on checks the shadow from the faces kept by the builds that check the solids, as drawing casts it, so it builds each solid once instead of building it again for the shadow. A stroke whose solid is left out of the art past its own limits casts no shadow. Evidence: `solids::tests::the_check_builds_each_drawn_solid_once`, `solids::tests_shadow::a_stroke_left_out_of_the_art_casts_no_shadow`, `solids::tests_shadow::the_check_accepts_the_shadowed_objects_that_draw`. Scores unchanged. +- 3D shadows: in Revolve, Extrude & Bevel, Inflate and Rotate, a fill, stroke or member whose opacity is NaN or infinite casts no part of the shadow, as one at 0 % does, whether the shadow is cast from the solids drawn or from solids built for it alone; the art beside it still casts. This is VectorCraft's own rule. Evidence: `solids::tests_shadow::art_whose_opacity_is_not_a_finite_number_casts_no_shadow`, `revolve::tests::a_surface_whose_opacity_is_not_a_finite_number_casts_no_shadow`. 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 and Materials › Render Settings › Wireframe: `render: {mode: "wireframe"}` on Extrude & Bevel, Revolve, Inflate and Rotate draws the live effect as the edges of its faces, 0.5 pt black strokes with no shadow, in every output and in Expand Appearance ([three-d.md](three-d.md#3d-and-materials-panel)); `crates/effects/src/solids/wireframe/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. Scores and hours unchanged. +- 3D and Materials › Export 3D Object: the panel's button adds the selected objects that have a 3D effect to Asset Export as 3D assets (`assets.add3D`), one undo step and none when each is an asset already, selects their assets and shows the Asset Export panel ([three-d.md](three-d.md#3d-and-materials-panel)); `panels::three_d::tests::{export_3d_object_adds_the_selected_3d_objects_to_asset_export, export_3d_object_leaves_out_a_3d_object_inside_another}` 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. - 3D effects, images a clip hides: an image in a clipping group is left out of the solid when its transformed frame lies wholly outside the area every clipping path around it fills together, holes included, instead of when only the boxes miss; an image the clips show part of is still refused ([the help page](https://helpx.adobe.com/illustrator/using/clipping-masks.html) on clipping paths hiding everything outside their shape; the omission rule is VectorCraft's own). `solids::tests_sources::an_image_inside_a_clips_box_but_outside_its_shape_is_left_out` covers it. Scores and estimates unchanged. @@ -625,10 +629,11 @@ since 2026-10-01. - **`.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. - **Graphs saved to `.ai` keep their data and settings:** a grouped column, stacked column, line or area graph is written to a `.ai` file, in either form, with the records the `.ai` reader reads (`crates/eps/src/import/ai/read/graph.rs`, #7311): `%_Gs`, its plot, type, settings, axes and table, its series' groups each tagged `Go`, and `%_GS` ([the specification](https://13thmonkey.org/documentation/fonts/AI7FileFormat.pdf), §17 and appendix A). The file opens again with the same live graph. A graph with settings the reader doesn't keep, graph designs, label formatting, more than 10,000 categories or 256 series, or art the reader doesn't attach a graph to is written as its art, with a warning. `crates/eps/src/legacy_ai/tests.rs` and `crates/eps/src/ai_editing/tests.rs` write and read back each kind of graph; `a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns` checks every graph type the graph tools draw. Scores unchanged. +- **Graph section in the Properties panel:** with one graph selected, or series of one graph picked with Group Selection, the Properties panel shows a Graph section. Its Graph Type… button opens the dialog of Object › Graph › Type… ([Format pie graphs](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/format-pie-graphs.html)). Its Graph Data… button opens the dialog of Object › Graph › Data…; this button is VectorCraft's own. Column… shows when every series it would change draws columns or bars, and Marker… when every one draws lines, scatter points or radar lines; this is VectorCraft's own rule. Regression tests in `crates/ui-egui/src/panels/properties/tests.rs`. 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; 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:** 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. The light direction of Underpainting, Rough Pastels, Conté Crayon, Bas Relief, Plaster and Texturizer and the stroke direction of Sprayed Strokes and Graphic Pen now turn and reflect with such a Transform effect, each set to the nearest of its menu's choices (at a tie, the one clockwise of it; VectorCraft's own rule), and Color Halftone's four screen angles turn and reflect with the art ([Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html); effects `tests::rasterfollow::bas_relief_light_follows_rotation_and_reflection` and the tests after it). Not yet: filters whose strokes or patterns run along fixed page axes without a direction setting (Angled Strokes, Crosshatch, Mezzotint's lines, Halftone Pattern's lines, Grain's horizontal and vertical types, De-Interlace) keep those axes, and an uneven scale or a shear sets a direction from the one vector it maps, not a skewed pattern. 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. - **Rasterize before a Transform effect:** effects apply in the order they are listed, each one taking the result of the one before ([the help page](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/appearance-attributes-in-illustrator.html)). On a path or compound path, a Transform effect listed after the object's own Rasterize effect now moves the image that Rasterize makes: the image is made of the art before the Transform effect, at the Rasterize effect's resolution and with its room around the art, and the Transform effect scales, turns, reflects and moves the image with its pixel grid. Before, the Transform effect moved the art and Rasterize made a new image of the moved art on a grid square to the page. Keeping the image's pixel grid under the Transform effect is VectorCraft's own rule. A hidden Transform effect, or one with Transform Objects off, leaves the image where it is, and one that scales it to nothing leaves nothing drawn. The canvas, the object's bounds, Expand Appearance and PDF export draw the same image (effects `tests::rasterfollow::rasterize_following_ignores_hidden_and_objects_off`, `tests::rasterfollow::the_image_moves_by_each_transform_about_the_art_it_takes`; render `rasterize::rasterize_then_scale_uses_the_pretransform_pixels`, `rasterize::rasterize_then_rotate_and_reflect_moves_the_pixel_grid`, `rasterize::rasterize_then_nonuniform_scale_and_zero_scale_are_bounded`; engine `rastersettings::expand_rasterize_then_transform_matches_canvas`). Not yet: a Transform effect that makes copies or moves at random, a Transform effect followed by another kind of effect, a fill's or stroke's own Rasterize effect, and Rasterize on type, images, symbol instances and groups keep the earlier behavior. 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. @@ -703,6 +708,7 @@ since 2026-10-01. - **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, ); a type object's appearance is separate from its characters' (the help page, ); 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 type object's own effects and transparency:** Type › Create Outlines gives the group of outlines the type object's own effects, once, in their order, with their settings and hidden effects still hidden, so they stay live and editable and the outlines draw what the type drew (a Warp or Free Distort effect moves a gradient on the characters across the whole outline, as on the type); the effects of the object's own fills and strokes stay on their paths of the whole outline. The group also takes the object's opacity, blend mode, Isolate Blending, Opacity & Mask Define Knockout Shape and opacity mask. Outlined characters keep their stroke and fill (the help page, ); putting the object's effects on the group is VectorCraft's own rule. Measured by `tests::pathops::create_outlines_keeps_the_objects_own_effects_on_the_group`, `tests::pathops::create_outlines_keeps_the_objects_transparency_and_opacity_mask`, `tests::objexpand::create_outlines_draws_the_type_objects_own_effects` and `tests::objexpand::create_outlines_keeps_a_warped_character_gradient_across_the_type`. 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, ); 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). +- **Create Outlines keeps the characters' stroke on unevenly scaled type:** on type scaled unevenly, sheared or flattened, Type › Create Outlines, Object › Expand and geometry effects on the type turn each character stroke into a filled path of the area the canvas strokes: laid out around the glyphs before the type's transform (dashes, caps, joins and inside or outside alignment), then transformed with them, so a stroke scaled 300% across is three times as thick across upright stems as across level bars. Moved, rotated, reflected and uniformly scaled type keeps a live stroke with its weight and dashes scaled. `object.expand.info` reports a gradient on such a filled stroke. Outlined characters keep their stroke and fill (the help page, ); turning the stroke into a filled path only under such transforms is VectorCraft's own rule. Measured by `tests::charstroke::create_outlines_keeps_the_character_strokes_thickness_under_an_uneven_scale`, `tests::charstroke::create_outlines_keeps_a_live_character_stroke_under_a_uniform_scale_and_rotation`, `tests::objexpand::type_reports_a_stroke_gradient_its_uneven_scale_turns_into_a_fill` and `tests::typestroke` (`crates/effects`). 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). - **Composite fonts' custom character sets:** Type › Composite Fonts… › Custom adds named character sets to a composite font, each setting the characters it lists in its own font, style, size, baseline and scales ahead of their class; the later of two sets that list a character sets it ([the help page](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=348)). Characters are added by Direct Entry or by Unicode code and deleted one at a time; the sets are saved with the document and in `.vccomposite` files (`custom` in `type.compositeFonts.set`). Evidence: `tests::composite::custom_character_sets_take_their_characters_first` (`crates/text`), `compositefonts::tests::custom_character_sets_set_their_characters` (`crates/engine`), `dialogs::composite_fonts::tests::custom_character_sets_are_edited_in_the_dialog` (`crates/ui-egui`). Scores unchanged (estimated). @@ -799,6 +805,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Variables: when no object is bound to a variable that the data set has a value for, for example after Import Data Sets… defines new variables without binding them, choosing the data set in the Variables panel or stepping to it with the panel's arrows shows a status message, and `dataset.select`, `dataset.next` and `dataset.prev` add the message to the reply as `warning`. - 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. - Variables: the Variables panel lists its variables in three columns with headers (type, Variables, Objects), and a click on a header sorts the list by variable type, variable name or bound object name, with a second click reversing the order (`variable.sort`; `variable.list` follows the order), as the [Variable panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/variable-panel-overview.html) describes. + - Variables: the Data Set box at the top of the Variables panel takes typed text, and a new name entered there renames the current data set with `dataset.rename` in one undo step; the same name adds no undo step, an empty or taken name is refused with a status message, and the list button beside the box still chooses a data set. - 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}`. @@ -806,6 +813,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - 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`). - Actions panel menu: Load Actions… also reads action sets saved as `.aia` files ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html); `actionSet.read`, `ui.actionSet.load`). VectorCraft's own rules: the set comes in with all its actions. A step with a label and no recorded values comes in as the one menu command with the step's label, when that command is directly in a top menu, is what its menu bar item runs with no values and opens no dialog. A step that is off in the file stays excluded from playback. The other steps, recorded menu items included, are left out, and the status bar says how many. + - Actions panel menu: Load Actions… reads an `.aia` file's Set Selection step, which selects objects by the note typed in its dialog ([the help page](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/insert-non-recordable-tasks-into-actions.html)), as a Select Object step with its note, Case Sensitive and Whole Word (`ui.actionSet.load`; `actionSet.read` now lists each step's recorded values with their keys and types). VectorCraft's own rules: the step is found by its internal name whatever its label, and comes in only when it has exactly the note (UTF-8, 1 to 1,024 bytes once trimmed) and the two options (each 0 or 1); any other Set Selection step is left out and counted, with no option filled in. Tests `panels::actions::tests::{load_actions_reads_set_selection_steps_as_select_object, set_selection_steps_with_bad_values_are_left_out}`, `tests::actionset::{recorded_values_come_back_with_their_keys_and_types, recorded_values_past_the_cap_are_counted_but_not_kept}`. - Actions panel: the panel menu's Action Options… renames the selected action and keeps its steps ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html): the menu item opens a dialog that renames the action or gives it a function key and color; `ui.action.options`). It also sets the action's function key and color. - Actions panel: Create New Action (bottom bar) and the panel menu's New Action… ask for the new action's name, set, function key and color, and Record adds the action and starts recording into it ([Create new actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/record-actions.html): the New Action dialog takes the action's name and the set it goes in; `ui.action.new`, `ui.action.play`). The function key (F1 to F15, with Ctrl or Command and Shift) plays the action. An action's function key plays the action even when a command has the same shortcut, and the command keeps it. VectorCraft's own rules, which the page does not cover: when several actions have the same key the first in panel order plays; a copied action has no key; New Action does not open while an action is recording. The color is the color of the action's button in Button Mode. - Actions panel: the panel menu's Button Mode shows the actions as buttons with their names in their Action Options colors, without sets or individual commands; a click on a button plays its action without its excluded steps, and choosing Button Mode again returns to the list ([the help page](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=467) and [the next page](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=468); [the help page](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/exclude-commands-from-actions.html) says commands cannot be excluded in Button Mode; `ui.action.buttonMode`, `ui.action.playAt`). VectorCraft's own rules, which the pages do not cover: the menu item shows a check mark while Button Mode is on; every set's actions show, in set order and then action order; an action without a color is an ordinary button; function keys still play their actions; the bottom bar shows only Stop Playing/Recording while an action plays or records, and Play Current Selection while one waits at a stop; Button Mode cannot be turned on while an action records; and the mode is kept with the UI preferences. @@ -838,10 +846,12 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - 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. + - Graphs: in the Graph Data window, the pointer becomes a column-resize arrow over a column's right edge, and dragging the edge sets that column's width in whole digits, from 0 to 20 as Cell Style's Column Width allows. The columns after it move along. Cell Style's Column Width still sets every column, the dragged ones included ([Adjust decimal digits and column width](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/adjust-column-width.html)). - 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 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. - Variables: Variable Options… in the Variables panel menu, or a double click on a variable, shows the variable's name and kind, and OK changes either or both in one undo step (`variable.rename {name, newName?, kind?}`), as the [Work with variables](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/work-with-variables.html) page describes. VectorCraft's own rule for a kind change: objects that can't hold the new kind are unbound, and the variable's values in every data set are dropped. + - Variables: Import… in the Variables panel menu (`variable.import`) opens one file dialog for a data source and reads it by its extension: a CSV, TSV or TXT file as Import Data Sets… reads it, and an XML file as Load Variable Library… reads it. Other extensions are refused. - 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). @@ -870,7 +880,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Link replies under `--automation-read-root`: `links.list`, `links.check`, `links.info` and `document.open`'s link rows leave out the path, found path and folder of a linked file outside the read roots, and the stored size and date of it in `links.info`; each row keeps its id, file name and status, and the document's links are not changed. `crates/engine/src/tests/linkspanel.rs` (`link_paths_outside_the_read_roots_are_left_out`), `crates/engine/src/tests/placed_document.rs` (`link_info_leaves_out_a_placed_documents_path_outside_the_read_roots`). - Document replies under `--automation-read-root`: `document.inspect` gives `path` as null for a document file outside the read roots, and `document.json` names a linked image or placed file outside them by its file name alone, without its relative path, size or date, brush art included, leaves out a relative path that leads outside them and a stored brush entry that does not read as a brush, names a data set's image value outside them by its file name, and leaves an Export for Screens folder outside them out of `export_settings`; the document is not changed. `crates/engine/src/tests/placed_document.rs` (`document_replies_leave_out_paths_outside_the_read_roots`, `document_json_checks_brush_art_and_relative_paths_against_the_read_roots`). - SVG output under `--automation-read-root`: `document.serialize`, `document.export`, `document.exportSelection`, `document.exportForScreens`, `assets.export`, the SVG and SVGZ saves, `file.exportAs` and the SVG Options dialog's Show Code refuse an SVG or SVGZ of a document that links a JavaScript file outside the read roots, before any file or folder is written, with an error that names no file or folder; a URL, a file inside the roots and a relative path that leads inside them are written as stored, and the person at the keyboard exports every link as stored. `crates/engine/src/tests/interactivity.rs` (`confined_svg_output_refuses_a_linked_javascript_file_outside_the_read_roots`, `svg_output_keeps_linked_javascript_files_a_caller_may_read`), `crates/ui-egui/src/tests/automation.rs` (`control_svg_export_refuses_a_linked_javascript_file_outside_the_read_root`), `crates/ui-egui/src/dialogs/svg_options.rs` (`show_code_leaves_out_a_linked_javascript_file_outside_the_read_roots`). - - Linked images in SVG output under `--automation-read-root`: the same outputs, and `clipboard.exportSvg`, refuse an SVG or SVGZ that would name a linked image's file outside the read roots (`images: link`, an image whose pixels the document doesn't hold, or `preserveEditing`), before any file or folder is written, with an error that names no file or folder; Copy in a frame a request drives then puts no SVG on the system clipboard. Embedded pixels, a file inside the roots, a relative path that leads inside them and a URL are written as before, and the person at the keyboard exports every link as stored. `crates/engine/src/tests/links.rs` (`confined_svg_output_refuses_a_linked_image_file_outside_the_read_roots`, `svg_output_names_linked_image_files_a_caller_may_read`, `confined_clipboard_svg_refuses_a_linked_image_file_outside_the_read_roots`, `confined_preserve_editing_svg_refuses_a_brush_library_entry_it_cannot_read`, `confined_svg_output_checks_only_the_linked_images_it_writes`, `confined_svg_output_writes_a_colorized_gray_image_without_its_file`), `crates/ui-egui/src/tests/automation.rs` (`control_svg_export_refuses_a_linked_image_file_outside_the_read_root`), `crates/ui-egui/src/dialogs/svg_options.rs` (`show_code_leaves_out_a_linked_image_file_outside_the_read_roots`). + - Linked images in SVG output under `--automation-read-root`: the same outputs, and `clipboard.exportSvg`, refuse an SVG or SVGZ that would name a linked image's file outside the read roots (`images: link`, an image whose pixels the document doesn't hold, or `preserveEditing`), before any file or folder is written, with an error that names no file or folder; Copy in a frame a request drives then puts no SVG on the system clipboard. Embedded pixels, a file inside the roots, a relative path that leads inside them and a URL are written as before, and the person at the keyboard exports every link as stored. The check covers the art drawn for placed documents and leaves out what the file leaves out: hidden art in symbols, patterns and graph designs, opacity masks in SVG Tiny 1.2, and objects drawn as images for effects SVG has no filter for. `crates/engine/src/tests/links.rs` (`confined_svg_output_refuses_a_linked_image_file_outside_the_read_roots`, `svg_output_names_linked_image_files_a_caller_may_read`, `confined_clipboard_svg_refuses_a_linked_image_file_outside_the_read_roots`, `confined_preserve_editing_svg_refuses_a_brush_library_entry_it_cannot_read`, `confined_svg_output_checks_only_the_linked_images_it_writes`, `confined_svg_output_writes_a_colorized_gray_image_without_its_file`, `confined_svg_output_checks_the_images_of_placed_documents`, `confined_svg_output_leaves_hidden_symbol_art_unchecked`, `confined_svg_tiny_output_leaves_opacity_mask_images_unchecked`, `confined_svg_output_checks_the_images_drawn_for_pixel_effects`), `crates/ui-egui/src/tests/automation.rs` (`control_svg_export_refuses_a_linked_image_file_outside_the_read_root`), `crates/ui-egui/src/dialogs/svg_options.rs` (`show_code_leaves_out_a_linked_image_file_outside_the_read_roots`). - Linked-file and font-file searches under `--automation-read-root`: `links.findFiles` and `text.findFontFiles` replies, also later polls and stops of a search another client started, leave out the files found, a link's saved path and the folder searched outside the caller's read roots, and a failed search gives its reason without the path; `image.info` gives `link: null` for a linked file outside them; `text.addFontFiles` gives `folder: null` and the copies' file names when the Fonts folder is outside them. `crates/engine/src/tests/linkfiles.rs`, `crates/engine/src/tests/fontfiles.rs`, `crates/engine/tests/font_folder.rs`. - Swatch, brush, symbol and graphic style library lists under `--automation-read-root`: every library stays listed, the paths of library files and the user library folder outside the read roots are `null`, a library loaded from outside them is listed and found as `loaded/` and keeps that id for the session unless a library loaded later without a file shows that id itself, which moves it to the next free `loaded/ (N)`, and the app's own list is not changed. `crates/engine/src/tests/library_roots.rs`. - Preferences commands under `--automation-read-root`: `prefs.get`, `prefs.list`, `prefs.set` and `prefs.reset` show folder preferences outside the read roots as `null` and leave out an export preset's folder outside them, and the preferences are not changed. `crates/engine/src/tests/prefs_roots.rs`. @@ -901,7 +911,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - With automation read roots in force, `svgInteractivity.info`, `addFile` and `removeFile`, the JavaScript Files dialog in a frame a request drives and `ui_inspect`'s selected file name a linked JavaScript file outside the roots by its file name alone, as `document.json` does; `removeFile` unlinks it by that name and refuses a name that fits more than one linked file (`tests/interactivity.rs`). - Numeric fields keep the pointer's pressed character as the text-drag start when movement exceeds the click threshold (#1326); a completed focus click selects the unit too. Pixel/point, plain and optional fields are regression-tested in both directions, before/after focus, with replacement text; keyboard focus, double-click, arrows and wheel keep their prior behavior. Native egui input confirms partial replacement gives 17 px instead of 700 px, one Undo/Redo, window captures and an exact saved-document read in a separate CLI process. A focus click released more than 1 pt from its press keeps the caret, and a tap within 1 pt still selects all (#6659; short-drag and jitter-tap regressions in `tests/numfields.rs`). - Unit fields and length strings take `%` in arithmetic: `3cm*50%` reads as 1.5 cm, and `50pt+25%` reads as 62.5 pt. - - The contextual task bar's handle drags it anywhere on the canvas (kept whole on it as the window resizes); unpinned it keeps that offset as it follows the selection, and its More Options menu hides it, pins its position across selection changes (`window.taskBar.pin`), resets it under the selection (`window.taskBar.reset`) and shows the Properties panel. As in Illustrator the position isn't kept across launches. Not done: the bar's variants for other tools (only the selection tools, the Type tools, the basic shape tools and the Artboard tool show it). + - The contextual task bar's handle drags it anywhere on the canvas (kept whole on it as the window resizes); unpinned it keeps that offset as it follows the selection, and its More Options menu hides it, pins its position across selection changes (`window.taskBar.pin`), resets it under the selection (`window.taskBar.reset`) and shows the Properties panel. As in Illustrator the position isn't kept across launches. Not done: the bar's variants for other tools (only the selection tools, the Type tools, the basic shape tools, the Smooth tool and the Artboard tool show it). - A click on another object moves the contextual task bar under it without hiding it for the press; it gives way only to a drag (#4681). - With one image selected, the contextual task bar offers Image Trace, which traces the image at once with the Default preset (the Image Trace panel is left as it was), and Crop Image; with an Image Trace object it offers Expand, which keeps only the traced paths. This follows Illustrator's bar: for a selected image it includes Image Trace, Retype and Crop Image, and traced artwork can be expanded from it ([Contextual Task Bar announcement](https://community.adobe.com/announcements-651/contextual-task-bar-in-illustrator-2025-quick-actions-when-you-need-them-1546580)). Offset Path and Simplify, which don't apply to an image, aren't offered for one. Not done: Retype, which the app doesn't have. - With the Artboard tool, the contextual task bar sits under the selected artboards and offers Resize (Artboard Options for the active artboard), Duplicate (each selected artboard, in one undo step, the copies then selected), Rearrange All (with two or more artboards) and Export (Export for Screens with the selected artboards checked). This follows Illustrator's bar: while the Artboard tool is in use, it has options for resizing, duplicating and exporting artboards (the [Contextual Task Bar announcement](https://community.adobe.com/questions-652/contextual-task-bar-in-illustrator-2025-quick-actions-when-you-need-them-1546580); Rearrange and Export on the bar: [Managing Artboards in Illustrator](https://creativepro.com/managing-artboards-in-illustrator/)). @@ -911,6 +921,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The help page describes the contextual task bar as one horizontal row () and gives no rule for a canvas narrower than that row. VectorCraft's own rule: the bar stays whole on the canvas. When its actions don't fit in one row, they wrap, in order, onto rows under the row with the handle, the chips and More Options; an action wider than any row, or one that would need a row past the canvas's height, is listed in More Options instead; when the chips don't fit beside the handle and More Options, they take rows after the actions; with no row to spare for the font controls, the bar leaves them out; a canvas too small for the handle and More Options shows no bar. Evidence: `a_task_bars_actions_wrap_on_a_narrow_canvas` and `a_task_bar_action_wider_than_the_canvas_goes_in_more_options` in `crates/ui-egui/src/tests/taskbar.rs`. - With a live rectangle, rounded rectangle, ellipse or polygon selected with the Selection tool, the contextual task bar shows a Shape Properties button in place of Lock. It opens a popup with the shape's rows from the Transform panel (corner radius, pie angles, or sides, angle, corner and radius), which edit it through `object.setLiveShape`. The overview describes this: when a shape drawn with a shape tool (Rectangle, Star) is selected, the bar offers to change its properties where Lock Object would be ([Contextual Task Bar overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/contextual-task-bar-overview.html)). Object › Lock and ⌘2 still lock the shape. Not done: stars, which the app draws as plain paths. Evidence: `a_basic_shape_shows_its_properties_in_place_of_lock`, `the_shape_properties_popup_edits_the_shape` and `other_selections_keep_lock` in `crates/ui-egui/src/tests/taskbar.rs`. - While the Rectangle, Rounded Rectangle, Ellipse, Polygon or Star tool is in use, the contextual task bar offers Edit Path (the Direct Selection tool), the Fill and Stroke chips, and Shape Properties for the shape it draws, as the help page lists for those five tools (). VectorCraft's own rules: the bar shows while one of those tools has one closed path selected whole, as right after it draws one, and not with nothing selected, several objects, a group, an open path, type or picked-out anchors; it shows nothing during the drag that draws the shape; it leaves out the selection tools' Duplicate, Offset Path, Simplify, Recolor Artwork and Lock; the Line Segment tool shows no bar. Not done: Shape Properties for a star, which the app draws as a plain path, and Gen Shape Fill and Generate Vectors, which the app doesn't have. Evidence: `shape_tools_show_edit_path_paint_and_properties_after_drawing`, `shape_tools_have_no_shape_bar_without_a_single_shape` and `shape_tool_bar_retargets_after_another_shape_and_undo` in `crates/ui-egui/src/tests/taskbar.rs`. + - While the Smooth tool is in use with a path it can smooth selected (a path with three or more anchors, or two joined by a curve, on its own or inside a selected group), the contextual task bar shows the tool's Fidelity field and Tool Options…, which opens the Smooth tool's options. The overview says the Smooth tool's bar has its tool options (), and the tool's help page names Fidelity as its option (). A value typed or stepped in the field sets the tool's Fidelity through `tool.setOption`, with the same range, unit (screen pixels) and steps as the field in its options. VectorCraft's own rules: with nothing selected, or only straight lines or type selected, the tool shows no bar; the bar leaves out the selection tools' actions, the Fill and Stroke chips, Recolor Artwork and Lock; on a canvas too narrow for the field, More Options lists Fidelity, which opens the tool's options. Evidence: `the_smooth_tool_shows_fidelity_and_tool_options_for_a_path` and `the_smooth_tool_shows_no_bar_without_a_path_to_smooth` in `crates/ui-egui/src/tests/taskbar.rs`. - The contextual task bar has a Stroke chip beside the Fill chip, drawn with the paint the Stroke proxy shows (a "?" when the selected objects' strokes differ, as on the Fill chip); a click brings the Stroke proxy forward and shows the Swatches panel wherever it is docked, floating or closed, as a click on the Fill chip does for the Fill proxy. The reference app's bar has Fill and Stroke controls for changing an object's colors ([Contextual Task Bar overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/contextual-task-bar-overview.html)). Evidence: `the_task_bar_shows_a_stroke_chip_beside_fill` and `the_task_bar_chips_follow_the_proxies_and_show_swatches_anywhere` in `crates/ui-egui/src/canvas/tests.rs`. - With anchor points selected with Direct Selection, the contextual task bar offers Remove Anchor Points, Connect (`path.join`), Cut Path, and Convert Selected Anchor Points to Corner and to Smooth (`path.convertAnchors` with `to` set to `corner` or `smooth`), the commands of the Control bar's anchor buttons; the two convert buttons show their icons alone, named by their tool tips as on the Control bar (VectorCraft's own choice). The overview lists items that delete the selected anchors, join selected end points, split the path at the selected anchors, and make the selected anchors corner or smooth points ([Contextual Task Bar overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/contextual-task-bar-overview.html)). With a path selected whole with Direct Selection, the bar also offers Simplify and Smooth, which open the Simplify and Smooth sliders as Object › Path › Simplify… and Smooth… do; the same overview names Smooth as adjusting the path's curvature (#6784). VectorCraft's own rule: while anchors are picked out, the bar offers the anchor items without Simplify and Smooth. Evidence: `direct_selection_smooth_opens_the_smooth_slider` in `crates/ui-egui/src/tests/taskbar.rs`. - Tool flyouts tear off: dragging or clicking the tear-off bar on a flyout's right side (or releasing the long press over it) floats its group as a strip of tool buttons, moved by the same bar and put back in the toolbar by the × at its top (`window.floatTools`). While a group floats, the presses that would open its flyout raise the strip instead. Floating strips are kept with the preferences and in user workspaces. Not done: turning a strip vertical, docking it. @@ -931,6 +942,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - A toolbar made with New Toolbar has a + button (Add Tool…) above its ••• button. A click on it, or Enter while it has the keyboard focus, opens a menu of every tool under the All Tools drawer's headings, without the drawer: a tool picked there goes at the end of that toolbar, and the tools already in it are dimmed. Under Remove Tool, the menu lists the toolbar's tools, and a click takes one out. This menu is VectorCraft's own way to fill a toolbar without a drag (`toolbar.addTool` and `toolbar.removeTool` with `toolbar`; `the_add_tool_menu_fills_a_new_toolbar_without_a_drag`). - Window › Toolbars › Manage Toolbars… and Manage Toolbars… in the All Tools drawer's menu open a dialog that lists the toolbars made with New Toolbar: a new name typed for the selected toolbar renames it, + copies it with its tools (with none selected, + makes a blank toolbar), and the trash can deletes it. Each change shows under Window › Toolbars and stays in the workspace (; `window.toolbar.manage`, `window.toolbar.rename`, `window.toolbar.duplicate`, `window.toolbar.delete`; `manage_toolbars_renames_duplicates_and_deletes`). - A toolbar made with New Toolbar docks in a lane along the window's left or right edge when its title bar is dropped on that edge, or with Dock to Left and Dock to Right in the title bar's context menu. Toolbars docked at one edge stack from the top, each with its share of the lane's height, and the lane is as wide as its widest toolbar; a lane too short for its stack wraps it into more columns, up to half the window's width, and past that the toolbars show only their title bars, which the mouse wheel scrolls through when even they do not fit. Dragging the title bar out of the lane, or Float Toolbar, floats it again, and Escape during the drag puts it back. Hiding and renaming keep its place, and the workspace keeps it. New toolbars still start floating. The lanes and the stacking are VectorCraft's own rules (#1759; `window.toolbar.dock`, `window.toolbar.float`; `toolbars_dock_and_float_by_their_commands`, `docked_toolbars_stack_in_lanes_along_the_window_edges`, `a_title_bar_dropped_on_an_edge_docks_the_toolbar`). + - The status bar shows the errors of the toolbars made with New Toolbar (a missing, empty, too long or taken name, the 64-toolbar limit, a `side` or `order` that `window.toolbar.dock` does not take, and New Toolbar's dialog and Manage Toolbars) in every language that translates every message, with the toolbar's name, the parameter key and the value given kept as they are; the error the command returns stays English (`custom_toolbar_command_errors_are_translated`). - Window › Toolbars › Keep Tools Beside the Canvas, a VectorCraft layout option that is off by default, docks the Tools panel between left-side panels and the canvas instead of at the window's left edge; the canvas's left edge then also docks a floating Tools panel, and workspaces keep the setting. Scores are unchanged (`window.toolsBesideCanvas`; `docked_tools_keep_the_window_edge_unless_kept_beside_the_canvas`, `tools_redock_at_the_targets_of_the_chosen_placement`). - 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. @@ -949,6 +961,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - 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 status bar translates `script.run`'s refusals of `answers` in every language that translates every message: a value that is not a list, more than 10,000 answers, more than 1 MiB, an answer at an index that is not an object, does not have exactly `kind` and `value`, has a `value` its kind of dialog does not take, holds a prompt's text longer than 16 KiB or has an unknown `kind`, and `answers` given to a run in the app. The index, the counts and the code names are shown as they are, and the command's error stays in English. The untranslated-strings report also lists the refusals of `script.run`'s parameters (`script_answers_errors_are_translated`, `message_scan_reads_script_run_param_refusals`). - 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`). @@ -981,7 +994,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - After a rotation the Scale and Reflect tools, the Scale and Reflect dialogs, `object.scale`, `object.reflect` with a named axis and the Transform and Properties panels' flips act along the selection's turned bounding box until Reset Bounding Box: the horizontal and vertical scale stretch along its own width and height, and the vertical and horizontal reflection axes are its own. The Reflect tool's default axis and its Shift steps start from the box's axes, and an axis drawn with the tool is the line drawn on the page. `basis: "page"` keeps the page's axes (VectorCraft's own rules; `bboxrotate::scale_and_reflect_follow_the_turned_box`, tools `xform::transform::tests::scale_and_reflect_drags_follow_a_turned_bounding_box`). - 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). + - Native macOS menu bar, vector tool cursors, a command palette (Help › Search Commands…), 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 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. 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`. @@ -992,6 +1005,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - 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`). - File Info's (`file.info`) error for a value with control characters shows in the status bar in the interface language for every field: "description has control characters" for Description and Copyright Notice, which take line breaks and tabs, and "title has control characters or line breaks" for the other text fields and each keyword in a list. Each is its own message with a row in every catalog that translates all status and error messages, and the field's key stays as written (`file_info_control_character_refusals_translate_in_every_complete_catalog`, `control_characters_are_refused_with_the_field_rule`). - 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`). + - An effect a plug-in's output or an importer plug-in's objects carry that VectorCraft refuses (``[0] `id`: reason``) shows in the status bar with its reason in the interface language inside `plug-in output: …` and `can't open …`, in every catalog that translates all status and error messages; the index and the effect id stay as they are, and a JSON array in a message stays as it is (`nested_effect_refusals_translate_with_their_reason`, `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. @@ -1167,8 +1181,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Alt-drag with the Knife cuts in a straight line, and Shift+Alt-drag cuts at 45° or 90°, as [Cut objects using the Knife and Scissors tools](https://web.archive.org/web/20260926095638/https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/cut-objects.html) and [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) describe. Alt counts only when held at the press; the dashed line runs from the press point to the pointer, stays straight after Alt is let go, and release sends `path.knife` with those two points. Alt pressed after the press leaves the cut freehand. Shift+Alt keeps the endpoint at 45° steps from the horizontal and vertical, whatever the Constrain Angle. With Smart Guides on, a straight Knife cut snaps to anchor points and paths: [Cut objects using the Knife and Scissors tools](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/cut-objects.html) describes the Knife snapping to anchor points and paths while Smart Guides are on. Its ends snap as the ends of the Pencil's straight line do, to anchor points and path segments of art that is shown: the press, and the release of an Alt-drag. Shift+Alt steps 45° from the snapped press, and its release stays on that step. With Smart Guides off, or with Snap to Pixel or Snap to Grid on, the cut is not snapped. The dashed line and `path.knife` use the snapped points. Eraser Tool Options has Angle and Roundness besides Size, as [Erase paths using the Eraser tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/erase-paths-using-eraser-tool.html) describes: the Eraser's tip is an ellipse Size across, its long axis at Angle and its short axis Roundness percent of the long one, and a drag with a tip that is not round shows the outline of the area it erases (`path.eraseRegion` `angle` and `roundness`). - Eraser Tool Options gives Angle, Roundness and Size each a menu of Fixed, Random, Pressure, Tilt, Bearing and Rotation with a Variation field, as the same page describes: the tip varies by up to the Variation either way, Random once per drag and the others with what the pen reads at each point of the drag, and the tip outline at the pointer follows the pen while it erases. The outline of the area a drag shows keeps the set Angle and Roundness, and a mouse drag erases at the set values (`path.eraseRegion` `angleMode`, `roundnessMode`, `sizeMode` and their variations). - The outline a Blob Brush or Eraser drag shows is built a bounded amount per frame, so a long stroke does not slow the canvas: each frame takes at most 256 new points of the drag and outlines again only the pieces of up to 32 segments they change, and the parts of a piece's outline inside the rest of the area are removed a limited amount at a time. While work is left, the canvas draws again with the pointer still, the points not outlined yet show as a thin line, and the tip shows at the pointer. With Size set to Pressure the outline also shows only the edge of the whole area. The release sends the whole stroke as before (`path.blob`, `path.eraseRegion`). + Eraser Tool Options gives Angle, Roundness and Size each a menu of Fixed, Random, Pressure, Tilt, Bearing and Rotation with a Variation field, as the same page describes: the tip varies by up to the Variation either way, Random once per drag and the others with what the pen reads at each point of the drag, and the tip outline at the pointer follows the pen while it erases. The outline of the area a drag shows takes, at each step, the tip the pen's readings give halfway along it, with a Random value shown as the value itself, and a mouse drag erases at the set values (`path.eraseRegion` `angleMode`, `roundnessMode`, `sizeMode` and their variations). + The outline a Blob Brush or Eraser drag shows is built a bounded amount per frame, so a long stroke does not slow the canvas: each frame takes at most 256 new points of the drag and outlines again only the pieces of up to 32 segments they change, and the parts of a piece's outline inside the rest of the area are removed a limited amount at a time. While work is left, the canvas draws again with the pointer still, the points not outlined yet show as a thin line, and the tip shows at the pointer. When the tip varies with the pen (Size set to Pressure, or an Eraser mode that follows the pen), each step is its own piece and the outline also shows only the edge of the whole area. The release sends the whole stroke as before (`path.blob`, `path.eraseRegion`). The settled part of that outline is kept in paths of up to 64 pieces each. A path is shared from one frame to the next until a piece in it changes, and the canvas keeps the triangles it drew the path with while the view stays the same, so a frame does not copy, flatten or tessellate a settled path again; a pan, zoom or rotation draws each one once more. This is VectorCraft's own rule. The outline of a drag with a round Eraser tip is drawn whole each frame. - **Transform:** Rotate, Reflect, Scale, Shear (click or Alt-click snaps the reference point to anchors and centres; Alt-click opens the tool's dialog, and a drag with Alt down at the release, from the press or pressed mid-drag, transforms a copy), Reshape, Free Transform (free and perspective distort and shear, switched by the keys held during a handle drag). A Reshape drag stretches part of a path from the dragged point without losing the path's general form, as [Adjust path segments](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/adjust-path-segments.html) has it. On an open path the stretch reaches both ends: the end anchors stay in place, each anchor between moves less the nearer it lies to an end, and the handles of a smooth anchor stay in line (`path.reshape`; the reach and the shares are VectorCraft's own rule, in `docs/mcp.md`). A click sets a focal point and a click on a segment adds a highlighted anchor there; Shift-click adds more, and a drag from any of them moves them all. The anchors that are not direct-selected stay in place and a closed path selected whole moves whole (VectorCraft's own rule, in `docs/mcp.md`). @@ -1186,6 +1200,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur `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`). + `guide.add` and `select.allOnArtboard` (`artboard`), `select.font` (`scope.artboards`) and `addon.select.byArtboards` (`artboards`) refuse an artboard that is not a whole number of 0 or more, such as `"1"`, `-1`, `1.5` or `true`, naming the key, instead of reporting it as a missing artboard or reading it as artboard 0, and leave the document and selection unchanged; a whole number past the last artboard is still `no such artboard`, and a null or left-out `artboard` keeps its default (`tests::menucmds::guide_add_refuses_an_artboard_that_is_not_a_whole_number`). `select.same.appearanceAttribute` refuses such an `item` the same way instead of using the Appearance panel's active item (`tests::styles::select_same_appearance_attribute_refuses_an_item_that_is_not_a_whole_number`). `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`). @@ -1439,7 +1454,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 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`). + 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`). When such a later box covers an earlier box to the right and above, the grouping compares the earlier box with still later boxes only below the later box's bottom: 512 boxes, each 1 pt right of and above the one before, or left of and below it, compare 511 pairs where they compared 130,816, with and without transparency, and the groups stay the same (`cmd::flatten::analysis::tests::boxes_staggered_up_meet_only_the_box_before`, `boxes_stepping_up_and_down_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`). @@ -1455,7 +1470,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Type on a path with right-to-left text that does not fit shows the longest start of its text whose glyphs fit, also where tracking gives a letter a negative advance and a shorter start does not fit; the rest overflows or flows to the next threaded object (VectorCraft's own rule). Without hanging punctuation, and on a straight path or with no spacing, every start is measured without arranging it on the path again. With hanging punctuation, or spacing on a curve, when a letter has a negative advance, at most 32 of the starts that could fit are arranged one by one from the longest; when none of them fits, a binary search over the rest shows a start that fits, which is not always the longest (`overflowing_rtl_type_on_a_path_shows_the_longest_start_that_fits`, `the_longest_rtl_start_on_a_path_is_found_without_arranging_each_start`, `the_longest_rtl_start_on_a_path_is_the_one_each_start_gives` and `rtl_type_on_a_curve_whose_letters_take_the_line_back_is_arranged_a_bounded_number_of_times` in `crates/text/src/tests/bidi.rs`). Right-aligned and centered type on a curve with Spacing is placed by what its glyphs take where the line ends up, so text that fits is not cut off at the end bracket (`on_path_aligned_spaced_text_that_fits_shows_whole` in `crates/text/src/tests.rs`). The Paragraph panel menu's Kinsoku Shori Type (`text.setFormat {kinsokuType}`, with the East Asian options) picks Push In First, Push Out First or Push Out Only for each paragraph: a character the Kinsoku Set keeps off a line's start or end is set on the line, with the line's gaps next to CJK characters closed by at most a tenth of an em each to fit, or moved to the next line with the character before it. Push Out First pushes in only when pushing out would leave the line more than an em short. Push Out Only is the default, the setting is saved only when it is not, and paragraph styles carry it. The Paragraph panel menu's Bunri-Kinshi (`text.setFormat {bunriKinshi}`, with the East Asian options, and the East Asian Composition Settings section of Paragraph Style Options) keeps inseparable pairs on one line in each paragraph that has it: two em dashes, two ellipses, two two-dot leaders and the two halves of a vertical kana repeat mark (the pairs of W3C JLREQ's class cl-08, VectorCraft's set). Both composers and vertical type follow it, and justification adds no space inside a pair. It works with a Kinsoku Set only, is off by default and is saved only when on; editing the set of pairs is not available. - `.ai` import reads each paragraph's Kinsoku Set (None, Hard or Soft), Kinsoku Shori Type, Burasagari and Bunri-Kinshi from the file's editable text: the paragraph's own setting, else its paragraph style's or a style that one is based on, else the document's default. A paragraph with a custom Kinsoku set takes its paragraph style's set, and the importer warns about it. A value it cannot read takes its paragraph style's value too. `.ai` export does not write these settings. + `.ai` import reads each paragraph's Kinsoku Set (None, Hard or Soft), Kinsoku Shori Type, Burasagari and Bunri-Kinshi from the file's editable text: the paragraph's own setting, else its paragraph style's or a style that one is based on, else the document's default. A paragraph with a custom Kinsoku set takes its paragraph style's set, and the importer warns about it. A value it cannot read takes its paragraph style's value too. An `.ai` save writes all four settings for every paragraph, the normal paragraph style and the document's defaults, and lists the Hard and Soft sets, in the form that reader reads, so they reopen as set and are not reported as left out; Burasagari and Bunri-Kinshi keep their values under Kinsoku None. The Paragraph panel menu's Korean Line Break Anywhere (`text.setFormat {koreanLineBreakAnywhere}`, with the East Asian options, and the East Asian Composition Settings section of Paragraph Style Options) sets for each paragraph whether a line may break between any two Hangul syllables. When it is off, a word that contains Hangul breaks only at its spaces and after punctuation, or where the word is wider than the line, and takes no hyphen. New type has it off; paragraphs saved before the option read as on, so their lines do not move. The Paragraph panel menu's Reset Panel (`text.setStyle`, `text.setFormat` and `text.tabs.clear`) gives the selected type's paragraphs, or the paragraphs the Type tool's selection touches, Auto alignment, no indents or paragraph spacing, Hyphenate off with the default Hyphenation and Justification options, Auto direction, Bottom-to-Bottom Leading, the Line-end Punctuation Half Width Mojikumi Set, Regular burasagari, the Hard kinsoku set, Push Out Only, the Every-line Composer, Bunri-Kinshi, Roman Hanging Punctuation and Korean Line Break Anywhere off, no kashidas and no tab stops, as one undo step. The Paragraph panel menu's Hyphenation… (`ui.hyphenation`, `text.setFormat {wordsLongerThan, afterFirst, beforeLast, hyphenLimit, hyphenationZone, hyphenateCapitalized}`) sets each paragraph's hyphenation limits: the shortest word that breaks, the fewest letters on each side of the hyphen, the most hyphenated lines in a row, a zone at the right edge where the Single-line Composer breaks before a word instead of hyphenating it, and whether capitalized words break. The defaults are words longer than 5 letters, 3 letters on each side, no limit or zone, and capitalized words hyphenated; paragraph styles and the native file keep the options. @@ -1463,6 +1478,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Paragraph panel's Insert Kashidas (with the Indic options; `text.setFormat {kashida}`) lengthens each Arabic word of a justified horizontal area type line with a kashida, a tatweel between its last pair of joined letters, before the word spaces widen: Short, Medium and Long kashidas are at most a quarter, half and a whole em long, Stylistic ones are whole tatweels up to an em, and None (the default) leaves the line as before; paragraph styles and the native file keep the setting. The Character panel menu's Kashidas switch (with the Indic options; `text.setFormat` / `text.setRangeStyle {kashidas}`) allows Kashidas on selected characters, on by default for new and old text. A pair of joined letters receives one only when both characters allow it; turning one off leaves other eligible pairs in the word available. Character styles and the native file keep the switch. [Public help](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/justify-text-using-kashida-and-hyphenation.html) documents the menu control and the separate paragraph length choices; the default and pair rule are VectorCraft choices. Paint-only Arabic harakat (marks whose character styles differ only in fill, stroke and related paint) stay inside one shaping cluster so letters keep their joining forms; when a second character-level shaping pass matches the monotone glyphs, a glyph may take a later in-cluster character's run only when GDEF classifies it as a mark (class 3) and that character is a harakat; otherwise it keeps the shaping cluster's first character. Insert Kashidas tatweels take the base letter's paint rather than a trailing mark's. Fonts without GDEF and some AAT/`morx` ligatures can leave a mark painted as its letter (`crates/text/src/tests/harakat.rs`). + Character panel › Adjust Horizontal and Adjust Vertical Diacritic Position (with the Middle Eastern options; `text.setFormat` or `text.setRangeStyle {diacriticHorizontal, diacriticVertical}`, VectorCraft's own thousandths of an em from -1000 to 1000, 0 by default) move the selected characters' mark glyphs (GDEF class 3) right or left and up or down while the letters stay in place ([the reference, page 549](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=549)); an Arabic harakat or Hebrew point styled apart takes its own values, character styles carry both (Character Style Options › Advanced Character Formats edits them), the canvas and PDF draw the moved marks and SVG writes such type as outlines (`tests::harakat::diacritic_positions_move_marks_and_keep_letters`). The Paragraph panel's Bullets button, Type › Bullets and Numbering › Apply Bullets and the context menu's Apply Bullets (`text.setFormat {list, bullet}`, `type.applyBullets`) make paragraphs a bulleted list with the documented presets (none, filled dot, dash, hollow circle, filled square; [Create bulleted or numbered lists](https://web.archive.org/web/20260417034638/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/create-bulleted-or-numbered-lists.html)): the bullet starts each paragraph's first line in its first character's font, size and color, the first line's text starts at the next tab stop after the bullet (the left indent counts as a stop), the lines it wraps to start at the left indent, a paragraph with no indents gets 18 pt and -18 pt, and Return continues the list; Reset Panel turns it off, and paragraph styles and the native file keep it. The Paragraph panel's Bullets button, Type › Bullets and Numbering › Apply Bullets and the context menu's Apply Bullets (`text.setFormat {list, bullet}`, `type.applyBullets`) make paragraphs a bulleted list with the documented presets (none, filled dot, dash, hollow circle, filled square; [Create bulleted or numbered lists](https://web.archive.org/web/20260417034638/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/create-bulleted-or-numbered-lists.html)): the bullet starts each paragraph's first line in its first character's font, size and color, the first line's text starts at the next tab stop after the bullet (the left indent counts as a stop), the lines it wraps to start at the left indent, a paragraph with no indents gets 18 pt and -18 pt, and Return continues the list; Reset Panel turns it off, and paragraph styles and the native file keep it. The Bullets and Numbering dialog, levels and Convert to Text are not built yet. The Paragraph panel's Numbered List button, Type › Bullets and Numbering › Apply Numbers and the context menu's Apply Numbers (`text.setFormat {list, number}`, `type.applyNumbers`) make paragraphs a numbered list with the documented presets (1, A, a, I, i, 01, 001, and None, which turns the list off; [Bullets and numbering](https://web.archive.org/web/20250807202418/https://helpx.adobe.com/illustrator/using/bullets-numbering.html), [Create bulleted or numbered lists](https://web.archive.org/web/20260417034638/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/create-bulleted-or-numbered-lists.html)): each paragraph starts with its number and a period, counted through the list paragraphs of the story and its threaded frames, with the text and indents as in a bulleted list; letters go on from Z to AA, and roman numerals go on from III to IV, an empty paragraph is not numbered, and a paragraph in no list starts the count again at 1. @@ -1484,6 +1500,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **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). The Russian catalog (`crates/ui-egui/src/i18n/ru.tsv`) has 1,811 more `@msg` rows, for status and error messages of commands, scripts and file import and export, 3,444 `@msg` rows in all counted on 2026-11-13 (`russian_translates_command_script_and_file_messages` in `crates/ui-egui/src/i18n/tests.rs`). Scores and estimates are unchanged. 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. + Burasagari ([the help page](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)) leaves a right-to-left paragraph's comma or full stop inside its line, which then ends at a break where it fits with the mark, and in a left-to-right line with right-to-left text and a tab it hangs a mark only when the mark is drawn at the line's right end and the rest of the line fits as drawn; otherwise the line ends at the latest break that fits as drawn. Both are VectorCraft's own rules (`crates/text/src/layout/wrapping_tests.rs`, `crates/text/src/tests/hang.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. @@ -1492,7 +1509,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur 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. + 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 is taken away without changing the glyph's shape, with tracking, kerning and Insert Aki added after it; a color glyph's ink is its color art or bitmap. Vertical type takes it too ([the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/format-east-asian-characters-in-vertical-text.html)): by VectorCraft's own rule an upright character is measured above and below its ink inside its cell down the column, a character lying on its side along its own width, and a tate-chu-yoko block's characters across the column, the block keeping its one em. 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 `` 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). Isolation mode and opacity mask editing exclude each other ([transparency and blending modes](https://web.archive.org/web/20230102045151/https://helpx.adobe.com/illustrator/using/transparency-blending-modes.html)): in isolation mode a click or Alt-click on the mask thumbnail does not edit the mask, and Make Mask is off for one object; while a mask is edited, Enter Isolation Mode and Object › Perspective › Edit Text are off, the Contextual Task Bar leaves out Isolate, and Quick Actions leave out Isolate Group. @@ -1521,6 +1538,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 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, a trace started before File › Revert does not apply after it:** the reverted document keeps its tab, but a trace prepared before the revert no longer applies, even when the restored image, object and settings are the same. A background trace that finishes after the revert changes nothing and the status bar says the document was reverted; a result handed to `imageTrace.make` or `imageTrace.makeAndExpand` is dropped and the restored image is traced again, as one undo step. Reverting another document, or a revert that fails, does not affect the trace (VectorCraft's own rule). Tests: `a_trace_run_prepared_before_a_revert_does_not_apply_after_it` in `crates/engine`, `a_trace_started_before_a_revert_does_not_apply` in `crates/ui-egui`. 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. @@ -1536,6 +1554,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **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, Noise joins the nearest color:** in Color and Grayscale, a region below Noise whose longest-border color is 10 or more apart from its own (Oklab × 100) joins the neighboring color nearest the average of its pixels (leaving out cut-edge pixels that are the color beside them blended with the transparent background), among those sharing at least a tenth of that border, so thin dark lines no longer break into dashes; a single pixel tied between colors joins by border (VectorCraft's own rule and values). 6 Colors and 16 Colors use Noise 8 and Black and White Logo Noise 5. On three illustrations with fine dark lines the mean difference falls 29% to 42% (16 Colors) with 72% to 99% more anchors (see [quality notes](image-trace-quality.md#noise-joins-the-nearest-color)). Tests in `crates/trace/src/quantize/denoise.rs`. Scores and hours unchanged. - **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. @@ -1566,7 +1585,7 @@ 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 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 that has the face's fill, or paints every edge that draws with the edge's stroke paint, each with the bucket's paint (`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 when it changes a paint, and the paint compared is the one the face or edge had before the first of its clicks that painted it, including a click whose drag or release crossed 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_a_release_across_an_edge_matches_the_fill_before, live_paint_bucket_triple_click_released_from_another_face_matches_the_fill_before, live_paint_bucket_triple_click_after_making_the_group_across_an_edge_matches_the_made_fill, live_paint_bucket_triple_click_after_making_the_group_under_an_unfilled_path_matches_the_made_fill, live_paint_bucket_triple_click_after_merging_across_an_edge_matches_the_face_fill, live_paint_bucket_triple_click_after_merging_two_groups_matches_the_merged_fill, live_paint_bucket_triple_click_after_a_merge_splits_a_face_matches_the_part_fill, live_paint_bucket_triple_click_after_merging_matches_the_fixed_gradient, 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_bucket_double_click_across_a_junction_paints_the_joined_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_triple_click_with_a_view_tool_press_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}`. Object › Live Paint › Make turns the selected paths into a Live Paint group of faces and edges ([the help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/create-live-paint-groups.html)). As VectorCraft's own rule, each face takes every fill row that draws (shown, with paint and an opacity above 0) of its front-most covering source that has one and an opacity above 0, and each edge every stroke row that draws (also with a weight above 0) of its source, in order with their opacity, blending mode, effects and stroke settings, with gradients kept at their fit on the source and with the source's opacity and blending mode. Where a path is cut into several edges, each edge's dashes go on from where it starts along the path with the lengths set (dashes aligned to corners and path ends are not fitted to the cut edges), the arrowheads stay at the path's own ends, and a width profile or brush stays only on an edge that runs the whole path; each edge runs the way its path does, a gradient applied along a stroke starts again on each cut edge, and an inside or outside stroke is drawn centered on an open piece of a closed path. A painted lower row under an unpainted or hidden top row is kept, a hidden top row does not become visible, and a source in front whose fill does not draw does not hide the fill behind it. Rows that do not draw stay with the stored sources, which Release returns unchanged; the source's object effects are not carried. Evidence: `tests::build::{live_paint_make_keeps_lower_drawn_stroke_rows, live_paint_make_fits_dashes_and_arrowheads_to_each_edge, live_paint_make_starts_a_closed_edge_where_its_path_starts, live_paint_make_keeps_the_direction_of_gradient_strokes, live_paint_make_keeps_all_drawn_fill_rows_and_attributes, live_paint_make_uses_frontmost_source_with_drawn_fill}`. 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. @@ -1595,6 +1614,8 @@ 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 on the merged branch (all 13 gates), including the test-helper correction for the upstream 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. 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`. @@ -1621,6 +1642,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Document Color Mode for effects and graphs:** File › Document Color Mode and `document.open {colorMode}` convert the colors of effects (Drop Shadow, Inner Glow, Outer Glow and the other effects with a color, on objects, their fills and strokes and in graphic styles) and the series paints and label styles that a graph keeps, so a graph drawn again from new data keeps the converted colors; File › Document Color Mode also converts the fill and stroke that new art takes. Undo restores the original new-art fill and stroke and Redo applies the conversion again. - **Recolor Artwork layout (#3416):** the Edit chip list uses the modal scroll helper and its actual remaining height; the tab's minimum-height space scrolls with the chips. `tests_recolor` covers 5/20/200/400 colors, window resizing, 100/125/150/200% UI scaling, scrolling to and editing the final chip, Preview, Cancel, Confirm and Undo, alongside the existing #1733 drag regressions. Scores and estimates unchanged. - **Recolor Artwork Edit displays:** buttons beside the Edit tab's wheel show the colors on a smooth color wheel, a segmented color wheel or as color bars ([Edit colors using Recolor Artwork](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/edit-colors-using-edit-colors-dialog.html)). The segmented wheel draws 24 hues by 5 saturations as solid patches, and its markers move freely as on the smooth wheel. The bars show one solid bar per recolored color in row order: a click selects a bar for the color sliders, and a drag moves its row without changing a color ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)). The dialog opens on the smooth wheel; `display` (`smooth`, `segmented`, `bars`) is the dialog field. `tests_recolor` covers switching, the dialog height, segmented dragging and Brightness, and bar selection, editing, reordering, scrolling, Preview, Cancel and OK. Scores and estimates unchanged. + - **Recolor Artwork Find:** the Assign tab's Find button finds the colors of the selected rows in the art ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)): while it is on, their art shows as the preview shows it and the rest of the selected art shows dimmed, until a second click ([archived help, Recolor Artwork](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=149)). VectorCraft's own rules: a dimmed color is a 25% tint of its current color (or the nearest lighter tint when that one is a color a selected row lists), a color a selected row also lists is not dimmed, and Find records no undo step. `findColors` is the dialog field. Tests: `find_dims_the_colors_of_the_rows_not_selected` and `find_shows_the_selected_rows_art_and_dims_the_rest` in `crates/ui-egui/src/dialogs/recolor.rs`. Scores and estimates unchanged. - **Recolor Artwork New Row:** the Assign tab's New Row button adds a row with no current colors, so current colors can be moved into it and take its new color ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html), [Assign new colors to selected artworks](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/assign-new-colors-to-selected-artwork.html)). VectorCraft's own rules: the row goes above the first selected row (at the top when none is selected) with that row's new color and becomes the selection, and Merge with it as the first selected row moves the other rows' colors into it. The button needs selected art. An empty row recolors nothing, does not count toward Colors, adds no library swatch and gives a rewritten color group no color. Tests: `a_new_row_goes_above_the_selection_and_takes_merged_colors`, `an_empty_row_gives_the_group_no_color` and `colors_merged_into_a_new_row_take_its_new_color` in `crates/ui-egui/src/dialogs/recolor.rs`, `an_empty_row_recolors_nothing` and `an_empty_row_adds_no_swatch_and_no_group_color` in `crates/engine/src/tests/recolor.rs`. - **Edit Colors parameters:** `edit.colors.saturate` needs a number `intensity`, the value from -100% to 100% that Saturate takes ([Adjusting colors](https://web.archive.org/web/20230128232631/https://helpx.adobe.com/illustrator/using/adjusting-colors.html)), and answers "missing number `intensity`" without one; a number outside the range counts as its nearest end. A value that is not a number, such as `"40"`, is refused with `` `intensity` must be a number, not "40" ``, as in every command that needs a number (`tests::params::a_malformed_required_number_is_not_reported_as_missing`). `edit.colors.adjustBalance` refuses a channel and `color.harmony` refuses `steps` or `amount` that is not a number; both read `null` as a value left out. `tests::editcolors` and `tests::colorguide` cover them. - **Convert to Indexed Color:** Edit › Edit Colors › Convert to Indexed Color… (`edit.colors.toIndexed`) stores the embedded images in the selection as indexed-color PNGs of at most 256 colors. The palette is chosen as for a PNG-8 export, as evenly spaced levels of red, green and blue, or from the document's swatches, with diffusion, pattern or noise dithering; pixels under half opacity become transparent. The dialog previews live, and OK is one undo step. This is VectorCraft's own command and counts toward no score. `tests::editcolors` and `encode::tests_palette` cover it. Scores and estimates unchanged. @@ -1636,6 +1658,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **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`. + Merge Swatches (`swatch.merge`) also drops the process plates of the gradient stops linked to a swatch it merges, whether the kept swatch is spot, global process or process that isn't global, in the art, gradient swatches, graphic styles, the art of brushes and the fill and stroke for new art; a stop linked to another swatch keeps its plates, and Undo puts the links and plates back. This is VectorCraft's own rule. Evidence: `tests::linked_stops::merging_swatches_takes_the_process_plates_of_the_stops_it_relinks` 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. @@ -1683,6 +1706,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur 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 describes effects on one fill or stroke, and the help page 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`). + When an export bakes a symbol instance with geometry effects inside the art of another such instance, it counts the art the inner instance bakes to, the copies its symbol's effects make included, against the 262,144 objects of symbol art one export bakes that way; it counted only the symbol's art before its effects. An instance whose baked art would pass that count stays an instance with its effects, and the art baked for it still counts against the instances after it. These are VectorCraft's own limits (effects `bake::nested_reshape_counts_baked_art`, `nested_reshape_refusal_keeps_its_work_counted`, `nested_reshape_refused_siblings_bake_once`, `nested_reshape_counts_successful_descendants_once`). 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). @@ -1695,6 +1719,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur 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. PDF export writes a knockout group as one PDF knockout group (`/K true`, with `/I true` when the group isolates; ISO 32000-1, 11.4.6.3), so a knockout group of any size opens again in VectorCraft as a knockout group, and the form nesting of the file does not grow with the number of elements. When an element's opacity or mask defines its knockout shape, or it paints translucently, each element is drawn through one soft mask of the overlapping elements above it instead; past 65,536 objects in a group's masks (or 2,048 elements) the group is a PDF knockout group, with a warning that its translucent elements knock out fully. SVG export draws each element of a knockout group through one mask of the overlapping elements above it, and the masks refer to one copy of each element's shape, so the elements stay siblings and the file nests no deeper with more elements; past 65,536 shapes in a group's masks (or 2,048 elements) the group is written as a plain group, with a warning. Evidence: `pdf/src/tests/blend.rs`, `svg/tests/it/blend_export.rs`, `pdf/tests/gradient_forms.rs` (a gradient in a knockout group reads back in place). + A knockout group in Normal mode at full opacity that does not isolate, with nothing blending inside, is written without an isolated group around its elements, clipped or not, so the art below the group is its initial backdrop in the PDF as on the canvas (ISO 32000-1, 11.4.5): neither its `/K` group nor a form around a clipped group carries `/I true`, and an overprinting element in it overprints the art below the group. Evidence: `pdf/src/tests/blend.rs` (`a_knockout_group_without_blending_inside_is_isolated_only_when_it_isolates`, `an_overprinting_element_of_a_knockout_group_that_does_not_isolate_overprints_the_art_below`). + PDF import keeps a group's isolation when something inside it overprints as well as when something blends, so an isolated group or knockout group whose objects only overprint opens as an isolated group and is written with `/I true` again, and its overprinting objects still cover the inks of the art below the group. Evidence: `pdf/src/tests/blend.rs` (`an_isolated_group_with_an_overprinting_object_reads_back_isolated`, `an_overprinting_element_of_a_knockout_group_that_does_not_isolate_overprints_the_art_below`). - **Graphic styles:** styles keep opacity and blend mode, capture groups and type, apply on top with Alt, and link to the objects using them; Redefine, Break Link, Graphic Style Options, Select All Unused, Sort by Name, and Select > Same Graphic Style / Appearance Attribute. The panel has list and thumbnail views with rendered previews, merge, reorder and drag and drop, plus a Control bar Style picker; eleven generated style libraries (including Game HUD, Status Effects, Neon & Glow, Painted and Sketched, whose seven styles each repaint a solid fill with one watercolor, dry brush, pastel, charcoal or ink effect, and Textures) save and load as `.vcstyles`. The built-in Textures graphic style library (`graphicStyle.addFromLibrary {library: "textures"}`) has eight styles that paint their fills and strokes with the texture effects: Fine Grain (Grain), Canvas Weave and Burlap Sack (Texturizer), Cracked Glaze (Craquelure), Mosaic Floor (Mosaic Tiles), Quilted Squares (Patchwork), Leaded Glass (Stained Glass) and Damp Paper (Water Paper). The help page names new graphic styles for textures ([What's new](https://helpx.adobe.com/illustrator/desktop/new-features/whats-new.html)) without naming them, so the styles, their names and their settings are VectorCraft's own (`tests::stylelib::textures_styles_apply_their_texture_effects_and_keep_their_params_through_save_and_open`). In the Graphic Styles panel, Shift-click selects a range of styles and Ctrl/Cmd-click adds or removes one. @@ -1773,7 +1799,8 @@ 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 `